use of org.apache.archiva.redback.authorization.UnauthorizedException in project archiva by apache.
the class ArchivaDavResourceFactory method buildMergedIndexDirectory.
protected Path buildMergedIndexDirectory(List<String> repositories, String activePrincipal, DavServletRequest request, RepositoryGroupConfiguration repositoryGroupConfiguration) throws DavException {
try {
HttpSession session = request.getSession();
@SuppressWarnings("unchecked") Map<String, TemporaryGroupIndex> temporaryGroupIndexMap = (Map<String, TemporaryGroupIndex>) session.getAttribute(TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY);
if (temporaryGroupIndexMap == null) {
temporaryGroupIndexMap = new HashMap<>();
}
TemporaryGroupIndex tmp = temporaryGroupIndexMap.get(repositoryGroupConfiguration.getId());
if (tmp != null && tmp.getDirectory() != null && Files.exists(tmp.getDirectory())) {
if (System.currentTimeMillis() - tmp.getCreationTime() > (repositoryGroupConfiguration.getMergedIndexTtl() * 60 * 1000)) {
log.debug(MarkerFactory.getMarker("group.merged.index"), "tmp group index '{}' is too old so delete it", repositoryGroupConfiguration.getId());
indexMerger.cleanTemporaryGroupIndex(tmp);
} else {
log.debug(MarkerFactory.getMarker("group.merged.index"), "merged index for group '{}' found in cache", repositoryGroupConfiguration.getId());
return tmp.getDirectory();
}
}
Set<String> authzRepos = new HashSet<String>();
String permission = WebdavMethodUtil.getMethodPermission(request.getMethod());
for (String repository : repositories) {
try {
if (servletAuth.isAuthorized(activePrincipal, repository, permission)) {
authzRepos.add(repository);
authzRepos.addAll(this.repositorySearch.getRemoteIndexingContextIds(repository));
}
} catch (UnauthorizedException e) {
// TODO: review exception handling
log.debug("Skipping repository '{}' for user '{}': {}", repository, activePrincipal, e.getMessage());
}
}
log.info("generate temporary merged index for repository group '{}' for repositories '{}'", repositoryGroupConfiguration.getId(), authzRepos);
Path tempRepoFile = Files.createTempDirectory("temp");
tempRepoFile.toFile().deleteOnExit();
IndexMergerRequest indexMergerRequest = new IndexMergerRequest(authzRepos, true, repositoryGroupConfiguration.getId(), repositoryGroupConfiguration.getMergedIndexPath(), repositoryGroupConfiguration.getMergedIndexTtl()).mergedIndexDirectory(tempRepoFile).temporary(true);
MergedRemoteIndexesTaskRequest taskRequest = new MergedRemoteIndexesTaskRequest(indexMergerRequest, indexMerger);
MergedRemoteIndexesTask job = new MergedRemoteIndexesTask(taskRequest);
IndexingContext indexingContext = job.execute().getIndexingContext();
Path mergedRepoDir = indexingContext.getIndexDirectoryFile().toPath();
TemporaryGroupIndex temporaryGroupIndex = new TemporaryGroupIndex(mergedRepoDir, indexingContext.getId(), repositoryGroupConfiguration.getId(), //
repositoryGroupConfiguration.getMergedIndexTtl()).setCreationTime(new Date().getTime());
temporaryGroupIndexMap.put(repositoryGroupConfiguration.getId(), temporaryGroupIndex);
session.setAttribute(TemporaryGroupIndexSessionCleaner.TEMPORARY_INDEX_SESSION_KEY, temporaryGroupIndexMap);
return mergedRepoDir;
} catch (RepositorySearchException e) {
throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
} catch (IndexMergerException e) {
throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
} catch (IOException e) {
throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
}
}
use of org.apache.archiva.redback.authorization.UnauthorizedException in project archiva by apache.
the class ArchivaDavResourceFactory method getResourceFromGroup.
private DavResource getResourceFromGroup(DavServletRequest request, List<String> repositories, ArchivaDavResourceLocator locator, RepositoryGroupConfiguration repositoryGroupConfiguration) throws DavException {
if (repositoryGroupConfiguration.getRepositories() == null || repositoryGroupConfiguration.getRepositories().isEmpty()) {
Path file = Paths.get(System.getProperty("appserver.base"), "groups/" + repositoryGroupConfiguration.getId());
return new ArchivaDavResource(file.toString(), "groups/" + repositoryGroupConfiguration.getId(), null, request.getDavSession(), locator, this, mimeTypes, auditListeners, scheduler, fileLockManager);
}
List<Path> mergedRepositoryContents = new ArrayList<>();
// multiple repo types so we guess they are all the same type
// so use the first one
// FIXME add a method with group in the repository storage
String firstRepoId = repositoryGroupConfiguration.getRepositories().get(0);
String path = getLogicalResource(locator, repositoryRegistry.getManagedRepository(firstRepoId), false);
if (path.startsWith("/")) {
path = path.substring(1);
}
LogicalResource logicalResource = new LogicalResource(path);
// flow:
// if the current user logged in has permission to any of the repositories, allow user to
// browse the repo group but displaying only the repositories which the user has permission to access.
// otherwise, prompt for authentication.
String activePrincipal = getActivePrincipal(request);
boolean allow = isAllowedToContinue(request, repositories, activePrincipal);
// remove last /
String pathInfo = StringUtils.removeEnd(request.getPathInfo(), "/");
if (allow) {
if (StringUtils.endsWith(pathInfo, repositoryGroupConfiguration.getMergedIndexPath())) {
Path mergedRepoDir = buildMergedIndexDirectory(repositories, activePrincipal, request, repositoryGroupConfiguration);
mergedRepositoryContents.add(mergedRepoDir);
} else {
if (StringUtils.equalsIgnoreCase(pathInfo, "/" + repositoryGroupConfiguration.getId())) {
Path tmpDirectory = Paths.get(SystemUtils.getJavaIoTmpDir().toString(), repositoryGroupConfiguration.getId(), repositoryGroupConfiguration.getMergedIndexPath());
if (!Files.exists(tmpDirectory)) {
synchronized (tmpDirectory.toAbsolutePath().toString()) {
if (!Files.exists(tmpDirectory)) {
try {
Files.createDirectories(tmpDirectory);
} catch (IOException e) {
throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not create direcotory " + tmpDirectory);
}
}
}
}
mergedRepositoryContents.add(tmpDirectory.getParent());
}
for (String repository : repositories) {
ManagedRepositoryContent managedRepository = null;
ManagedRepository repo = repositoryRegistry.getManagedRepository(repository);
if (repo == null) {
throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid managed repository <" + repository + ">");
}
managedRepository = repo.getContent();
if (managedRepository == null) {
log.error("Inconsistency detected. Repository content not found for '{}'", repository);
throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid managed repository <" + repository + ">");
}
Path resourceFile = Paths.get(managedRepository.getRepoRoot(), logicalResource.getPath());
if (Files.exists(resourceFile)) {
// in case of group displaying index directory doesn't have sense !!
IndexCreationFeature idf = managedRepository.getRepository().getFeature(IndexCreationFeature.class).get();
String repoIndexDirectory = idf.getIndexPath().toString();
if (StringUtils.isNotEmpty(repoIndexDirectory)) {
if (!Paths.get(repoIndexDirectory).isAbsolute()) {
repoIndexDirectory = Paths.get(managedRepository.getRepository().getLocation()).resolve(StringUtils.isEmpty(repoIndexDirectory) ? ".indexer" : repoIndexDirectory).toAbsolutePath().toString();
}
}
if (StringUtils.isEmpty(repoIndexDirectory)) {
repoIndexDirectory = Paths.get(managedRepository.getRepository().getLocation()).resolve(".indexer").toAbsolutePath().toString();
}
if (!StringUtils.equals(FilenameUtils.normalize(repoIndexDirectory), FilenameUtils.normalize(resourceFile.toAbsolutePath().toString()))) {
// for prompted authentication
if (httpAuth.getSecuritySession(request.getSession(true)) != null) {
try {
if (isAuthorized(request, repository)) {
mergedRepositoryContents.add(resourceFile);
log.debug("Repository '{}' accessed by '{}'", repository, activePrincipal);
}
} catch (DavException e) {
// TODO: review exception handling
log.debug("Skipping repository '{}' for user '{}': {}", managedRepository, activePrincipal, e.getMessage());
}
} else {
// for the current user logged in
try {
if (servletAuth.isAuthorized(activePrincipal, repository, WebdavMethodUtil.getMethodPermission(request.getMethod()))) {
mergedRepositoryContents.add(resourceFile);
log.debug("Repository '{}' accessed by '{}'", repository, activePrincipal);
}
} catch (UnauthorizedException e) {
// TODO: review exception handling
log.debug("Skipping repository '{}' for user '{}': {}", managedRepository, activePrincipal, e.getMessage());
}
}
}
}
}
}
} else {
throw new UnauthorizedDavException(locator.getRepositoryId(), "User not authorized.");
}
ArchivaVirtualDavResource resource = new ArchivaVirtualDavResource(mergedRepositoryContents, logicalResource.getPath(), mimeTypes, locator, this);
// compatibility with MRM-440 to ensure browsing the repository group works ok
if (resource.isCollection() && !request.getRequestURI().endsWith("/")) {
throw new BrowserRedirectException(resource.getHref());
}
return resource;
}
use of org.apache.archiva.redback.authorization.UnauthorizedException in project archiva by apache.
the class ArchivaDavSessionProvider method attachSession.
@Override
public boolean attachSession(WebdavRequest request) throws DavException {
final String repositoryId = RepositoryPathUtil.getRepositoryName(removeContextPath(request));
try {
AuthenticationResult result = httpAuth.getAuthenticationResult(request, null);
// Create a dav session
request.setDavSession(new ArchivaDavSession());
return servletAuth.isAuthenticated(request, result);
} catch (AuthenticationException e) {
// safety check for MRM-911
String guest = UserManager.GUEST_USERNAME;
try {
if (servletAuth.isAuthorized(guest, ((ArchivaDavResourceLocator) request.getRequestLocator()).getRepositoryId(), WebdavMethodUtil.getMethodPermission(request.getMethod()))) {
request.setDavSession(new ArchivaDavSession());
return true;
}
} catch (UnauthorizedException ae) {
throw new UnauthorizedDavException(repositoryId, "You are not authenticated and authorized to access any repository.");
}
throw new UnauthorizedDavException(repositoryId, "You are not authenticated.");
} catch (MustChangePasswordException e) {
throw new UnauthorizedDavException(repositoryId, "You must change your password.");
} catch (AccountLockedException e) {
throw new UnauthorizedDavException(repositoryId, "User account is locked.");
}
}
use of org.apache.archiva.redback.authorization.UnauthorizedException in project archiva by apache.
the class RssFeedServlet method isAllowed.
/**
* Basic authentication.
*
* @param req
* @param repositoryId TODO
* @param groupId TODO
* @param artifactId TODO
* @return
*/
private boolean isAllowed(HttpServletRequest req, String repositoryId, String groupId, String artifactId) throws UserNotFoundException, AccountLockedException, AuthenticationException, MustChangePasswordException, UnauthorizedException {
String auth = req.getHeader("Authorization");
List<String> repoIds = new ArrayList<>();
if (repositoryId != null) {
repoIds.add(repositoryId);
} else if (artifactId != null && groupId != null) {
if (auth != null) {
if (!auth.toUpperCase().startsWith("BASIC ")) {
return false;
}
Decoder dec = new Base64();
String usernamePassword = "";
try {
usernamePassword = new String((byte[]) dec.decode(auth.substring(6).getBytes()));
} catch (DecoderException ie) {
log.warn("Error decoding username and password: {}", ie.getMessage());
}
if (usernamePassword == null || usernamePassword.trim().equals("")) {
repoIds = getObservableRepos(UserManager.GUEST_USERNAME);
} else {
String[] userCredentials = usernamePassword.split(":");
repoIds = getObservableRepos(userCredentials[0]);
}
} else {
repoIds = getObservableRepos(UserManager.GUEST_USERNAME);
}
} else {
return false;
}
for (String repoId : repoIds) {
try {
AuthenticationResult result = httpAuth.getAuthenticationResult(req, null);
SecuritySession securitySession = httpAuth.getSecuritySession(req.getSession(true));
if (//
servletAuth.isAuthenticated(req, result) && //
servletAuth.isAuthorized(//
req, //
securitySession, //
repoId, ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS)) {
return true;
}
} catch (AuthorizationException e) {
log.debug("AuthorizationException for repoId: {}", repoId);
} catch (UnauthorizedException e) {
log.debug("UnauthorizedException for repoId: {}", repoId);
}
}
throw new UnauthorizedException("Access denied.");
}
use of org.apache.archiva.redback.authorization.UnauthorizedException in project archiva by apache.
the class RssFeedServlet method doGet.
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String repoId = null;
String groupId = null;
String artifactId = null;
String url = StringUtils.removeEnd(req.getRequestURL().toString(), "/");
if (StringUtils.countMatches(StringUtils.substringAfter(url, "feeds/"), "/") > 0) {
artifactId = StringUtils.substringAfterLast(url, "/");
groupId = StringUtils.substringBeforeLast(StringUtils.substringAfter(url, "feeds/"), "/");
groupId = StringUtils.replaceChars(groupId, '/', '.');
} else if (StringUtils.countMatches(StringUtils.substringAfter(url, "feeds/"), "/") == 0) {
// we receive feeds?babla=ded which is not correct
if (StringUtils.countMatches(url, "feeds?") > 0) {
res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request url.");
return;
}
repoId = StringUtils.substringAfterLast(url, "/");
} else {
res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request url.");
return;
}
RssFeedProcessor processor = null;
try {
Map<String, String> map = new HashMap<>();
SyndFeed feed = null;
if (isAllowed(req, repoId, groupId, artifactId)) {
if (repoId != null) {
// new artifacts in repo feed request
processor = newArtifactsprocessor;
map.put(RssFeedProcessor.KEY_REPO_ID, repoId);
} else if ((groupId != null) && (artifactId != null)) {
// TODO: this only works for guest - we could pass in the list of repos
// new versions of artifact feed request
processor = newVersionsprocessor;
map.put(RssFeedProcessor.KEY_GROUP_ID, groupId);
map.put(RssFeedProcessor.KEY_ARTIFACT_ID, artifactId);
}
} else {
res.sendError(HttpServletResponse.SC_UNAUTHORIZED, USER_NOT_AUTHORIZED);
return;
}
RepositorySession repositorySession = repositorySessionFactory.createSession();
try {
feed = processor.process(map, repositorySession.getRepository());
} finally {
repositorySession.close();
}
if (feed == null) {
res.sendError(HttpServletResponse.SC_NO_CONTENT, "No information available.");
return;
}
res.setContentType(MIME_TYPE);
if (repoId != null) {
feed.setLink(req.getRequestURL().toString());
} else if ((groupId != null) && (artifactId != null)) {
feed.setLink(req.getRequestURL().toString());
}
SyndFeedOutput output = new SyndFeedOutput();
output.output(feed, res.getWriter());
} catch (UserNotFoundException unfe) {
log.debug(COULD_NOT_AUTHENTICATE_USER, unfe);
res.sendError(HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER);
} catch (AccountLockedException acce) {
res.sendError(HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER);
} catch (AuthenticationException authe) {
log.debug(COULD_NOT_AUTHENTICATE_USER, authe);
res.sendError(HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER);
} catch (FeedException ex) {
log.debug(COULD_NOT_GENERATE_FEED_ERROR, ex);
res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, COULD_NOT_GENERATE_FEED_ERROR);
} catch (MustChangePasswordException e) {
res.sendError(HttpServletResponse.SC_UNAUTHORIZED, COULD_NOT_AUTHENTICATE_USER);
} catch (UnauthorizedException e) {
log.debug(e.getMessage());
if (repoId != null) {
res.setHeader("WWW-Authenticate", "Basic realm=\"Repository Archiva Managed " + repoId + " Repository");
} else {
res.setHeader("WWW-Authenticate", "Basic realm=\"Artifact " + groupId + ":" + artifactId);
}
res.sendError(HttpServletResponse.SC_UNAUTHORIZED, USER_NOT_AUTHORIZED);
}
}
Aggregations