Search in sources :

Example 6 with UnauthorizedException

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);
    }
}
Also used : Path(java.nio.file.Path) TemporaryGroupIndex(org.apache.archiva.indexer.merger.TemporaryGroupIndex) MergedRemoteIndexesTaskRequest(org.apache.archiva.indexer.merger.MergedRemoteIndexesTaskRequest) MergedRemoteIndexesTask(org.apache.archiva.indexer.merger.MergedRemoteIndexesTask) DavException(org.apache.jackrabbit.webdav.DavException) HttpSession(javax.servlet.http.HttpSession) IndexMergerRequest(org.apache.archiva.indexer.merger.IndexMergerRequest) RepositorySearchException(org.apache.archiva.indexer.search.RepositorySearchException) IOException(java.io.IOException) Date(java.util.Date) UnauthorizedException(org.apache.archiva.redback.authorization.UnauthorizedException) IndexingContext(org.apache.maven.index.context.IndexingContext) IndexMergerException(org.apache.archiva.indexer.merger.IndexMergerException) Map(java.util.Map) HashMap(java.util.HashMap) HashSet(java.util.HashSet)

Example 7 with UnauthorizedException

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;
}
Also used : Path(java.nio.file.Path) ManagedRepository(org.apache.archiva.repository.ManagedRepository) DavException(org.apache.jackrabbit.webdav.DavException) ArrayList(java.util.ArrayList) IOException(java.io.IOException) IndexCreationFeature(org.apache.archiva.repository.features.IndexCreationFeature) ManagedRepositoryContent(org.apache.archiva.repository.ManagedRepositoryContent) UnauthorizedException(org.apache.archiva.redback.authorization.UnauthorizedException)

Example 8 with UnauthorizedException

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.");
    }
}
Also used : MustChangePasswordException(org.apache.archiva.redback.policy.MustChangePasswordException) AccountLockedException(org.apache.archiva.redback.policy.AccountLockedException) AuthenticationException(org.apache.archiva.redback.authentication.AuthenticationException) UnauthorizedException(org.apache.archiva.redback.authorization.UnauthorizedException) AuthenticationResult(org.apache.archiva.redback.authentication.AuthenticationResult)

Example 9 with UnauthorizedException

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.");
}
Also used : DecoderException(org.apache.commons.codec.DecoderException) Base64(org.apache.commons.codec.binary.Base64) AuthorizationException(org.apache.archiva.redback.authorization.AuthorizationException) SecuritySession(org.apache.archiva.redback.system.SecuritySession) ArrayList(java.util.ArrayList) UnauthorizedException(org.apache.archiva.redback.authorization.UnauthorizedException) Decoder(org.apache.commons.codec.Decoder) AuthenticationResult(org.apache.archiva.redback.authentication.AuthenticationResult)

Example 10 with UnauthorizedException

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);
    }
}
Also used : UserNotFoundException(org.apache.archiva.redback.users.UserNotFoundException) AccountLockedException(org.apache.archiva.redback.policy.AccountLockedException) HashMap(java.util.HashMap) AuthenticationException(org.apache.archiva.redback.authentication.AuthenticationException) FeedException(com.sun.syndication.io.FeedException) SyndFeedOutput(com.sun.syndication.io.SyndFeedOutput) RepositorySession(org.apache.archiva.metadata.repository.RepositorySession) MustChangePasswordException(org.apache.archiva.redback.policy.MustChangePasswordException) SyndFeed(com.sun.syndication.feed.synd.SyndFeed) RssFeedProcessor(org.apache.archiva.rss.processor.RssFeedProcessor) UnauthorizedException(org.apache.archiva.redback.authorization.UnauthorizedException)

Aggregations

UnauthorizedException (org.apache.archiva.redback.authorization.UnauthorizedException)12 AuthenticationResult (org.apache.archiva.redback.authentication.AuthenticationResult)9 SecuritySession (org.apache.archiva.redback.system.SecuritySession)7 DefaultSecuritySession (org.apache.archiva.redback.system.DefaultSecuritySession)5 Test (org.junit.Test)5 AuthenticationException (org.apache.archiva.redback.authentication.AuthenticationException)4 Path (java.nio.file.Path)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 AuthorizationException (org.apache.archiva.redback.authorization.AuthorizationException)3 AccountLockedException (org.apache.archiva.redback.policy.AccountLockedException)3 MustChangePasswordException (org.apache.archiva.redback.policy.MustChangePasswordException)3 User (org.apache.archiva.redback.users.User)3 DavException (org.apache.jackrabbit.webdav.DavException)3 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)3 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)3 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2