Search in sources :

Example 1 with AuthenticationException

use of org.apache.archiva.redback.authentication.AuthenticationException in project archiva by apache.

the class RepositoryServletSecurityTest method testPutWithInvalidUserAndGuestHasWriteAccess.

// test deploy with invalid user, but guest has write access to repo
@Test
public void testPutWithInvalidUserAndGuestHasWriteAccess() throws Exception {
    servlet.setDavSessionProvider(davSessionProvider);
    ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
    archivaDavResourceFactory.setHttpAuth(httpAuth);
    archivaDavResourceFactory.setServletAuth(servletAuth);
    servlet.setResourceFactory(archivaDavResourceFactory);
    AuthenticationResult result = new AuthenticationResult();
    EasyMock.expect(httpAuth.getAuthenticationResult(anyObject(HttpServletRequest.class), anyObject(HttpServletResponse.class))).andReturn(result);
    EasyMock.expect(servletAuth.isAuthenticated(anyObject(HttpServletRequest.class), anyObject(AuthenticationResult.class))).andThrow(new AuthenticationException("Authentication error"));
    EasyMock.expect(servletAuth.isAuthorized("guest", "internal", ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD)).andReturn(true);
    // ArchivaDavResourceFactory#isAuthorized()
    SecuritySession session = new DefaultSecuritySession();
    EasyMock.expect(httpAuth.getAuthenticationResult(anyObject(HttpServletRequest.class), anyObject(HttpServletResponse.class))).andReturn(result);
    EasyMock.expect(httpAuth.getSecuritySession(anyObject(HttpSession.class))).andReturn(session);
    EasyMock.expect(servletAuth.isAuthenticated(anyObject(HttpServletRequest.class), eq(result))).andThrow(new AuthenticationException("Authentication error"));
    EasyMock.expect(httpAuth.getSessionUser(anyObject(HttpSession.class))).andReturn(null);
    // check if guest has write access
    EasyMock.expect(servletAuth.isAuthorized("guest", "internal", ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD)).andReturn(true);
    httpAuthControl.replay();
    servletAuthControl.replay();
    InputStream is = getClass().getResourceAsStream("/artifact.jar");
    assertNotNull("artifact.jar inputstream", is);
    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
    mockHttpServletRequest.addHeader("User-Agent", "foo");
    mockHttpServletRequest.setMethod("PUT");
    mockHttpServletRequest.setRequestURI("/repository/internal/path/to/artifact.jar");
    mockHttpServletRequest.setContent(IOUtils.toByteArray(is));
    mockHttpServletRequest.setContentType("application/octet-stream");
    MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
    servlet.service(mockHttpServletRequest, mockHttpServletResponse);
    httpAuthControl.verify();
    servletAuthControl.verify();
    assertEquals(HttpServletResponse.SC_CREATED, mockHttpServletResponse.getStatus());
}
Also used : MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationException(org.apache.archiva.redback.authentication.AuthenticationException) SecuritySession(org.apache.archiva.redback.system.SecuritySession) DefaultSecuritySession(org.apache.archiva.redback.system.DefaultSecuritySession) HttpSession(javax.servlet.http.HttpSession) InputStream(java.io.InputStream) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) DefaultSecuritySession(org.apache.archiva.redback.system.DefaultSecuritySession) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) AuthenticationResult(org.apache.archiva.redback.authentication.AuthenticationResult) Test(org.junit.Test)

Example 2 with AuthenticationException

use of org.apache.archiva.redback.authentication.AuthenticationException in project archiva by apache.

the class RepositoryServletSecurityTest method testGetWithInvalidUserAndGuestHasReadAccess.

// test get with invalid user, and guest has read access to repo
@Test
public void testGetWithInvalidUserAndGuestHasReadAccess() throws Exception {
    String commonsLangJar = "commons-lang/commons-lang/2.1/commons-lang-2.1.jar";
    String expectedArtifactContents = "dummy-commons-lang-artifact";
    Path artifactFile = repoRootInternal.getRoot().resolve(commonsLangJar);
    Files.createDirectories(artifactFile.getParent());
    org.apache.archiva.common.utils.FileUtils.writeStringToFile(artifactFile, Charset.defaultCharset(), expectedArtifactContents);
    servlet.setDavSessionProvider(davSessionProvider);
    ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
    archivaDavResourceFactory.setHttpAuth(httpAuth);
    archivaDavResourceFactory.setServletAuth(servletAuth);
    servlet.setResourceFactory(archivaDavResourceFactory);
    AuthenticationResult result = new AuthenticationResult();
    EasyMock.expect(httpAuth.getAuthenticationResult(anyObject(HttpServletRequest.class), anyObject(HttpServletResponse.class))).andReturn(result);
    EasyMock.expect(servletAuth.isAuthenticated(anyObject(HttpServletRequest.class), anyObject(AuthenticationResult.class))).andThrow(new AuthenticationException("Authentication error"));
    EasyMock.expect(servletAuth.isAuthorized("guest", "internal", ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS)).andReturn(true);
    // ArchivaDavResourceFactory#isAuthorized()
    SecuritySession session = new DefaultSecuritySession();
    EasyMock.expect(httpAuth.getAuthenticationResult(anyObject(HttpServletRequest.class), anyObject(HttpServletResponse.class))).andReturn(result);
    EasyMock.expect(httpAuth.getSecuritySession(anyObject(HttpSession.class))).andReturn(session);
    EasyMock.expect(httpAuth.getSessionUser(anyObject(HttpSession.class))).andReturn(null);
    EasyMock.expect(servletAuth.isAuthenticated(anyObject(HttpServletRequest.class), eq(result))).andReturn(true);
    EasyMock.expect(servletAuth.isAuthorized(anyObject(HttpServletRequest.class), eq(session), eq("internal"), eq(ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS))).andReturn(true);
    httpAuthControl.replay();
    servletAuthControl.replay();
    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
    mockHttpServletRequest.addHeader("User-Agent", "foo");
    mockHttpServletRequest.setMethod("GET");
    mockHttpServletRequest.setRequestURI("/repository/internal/" + commonsLangJar);
    MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
    servlet.service(mockHttpServletRequest, mockHttpServletResponse);
    httpAuthControl.verify();
    servletAuthControl.verify();
    assertEquals(HttpServletResponse.SC_OK, mockHttpServletResponse.getStatus());
    assertEquals("Expected file contents", expectedArtifactContents, mockHttpServletResponse.getContentAsString());
}
Also used : Path(java.nio.file.Path) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationException(org.apache.archiva.redback.authentication.AuthenticationException) SecuritySession(org.apache.archiva.redback.system.SecuritySession) DefaultSecuritySession(org.apache.archiva.redback.system.DefaultSecuritySession) HttpSession(javax.servlet.http.HttpSession) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) DefaultSecuritySession(org.apache.archiva.redback.system.DefaultSecuritySession) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) AuthenticationResult(org.apache.archiva.redback.authentication.AuthenticationResult) Test(org.junit.Test)

Example 3 with AuthenticationException

use of org.apache.archiva.redback.authentication.AuthenticationException in project archiva by apache.

the class ArchivaDavResourceFactory method isAuthorized.

protected boolean isAuthorized(DavServletRequest request, String repositoryId) throws DavException {
    try {
        AuthenticationResult result = httpAuth.getAuthenticationResult(request, null);
        SecuritySession securitySession = httpAuth.getSecuritySession(request.getSession(true));
        return // 
        servletAuth.isAuthenticated(request, result) && // 
        servletAuth.isAuthorized(// 
        request, // 
        securitySession, // 
        repositoryId, WebdavMethodUtil.getMethodPermission(request.getMethod()));
    } 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()))) {
                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.");
    } catch (AuthorizationException e) {
        throw new DavException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Fatal Authorization Subsystem Error.");
    } catch (UnauthorizedException e) {
        throw new UnauthorizedDavException(repositoryId, e.getMessage());
    }
}
Also used : MustChangePasswordException(org.apache.archiva.redback.policy.MustChangePasswordException) AccountLockedException(org.apache.archiva.redback.policy.AccountLockedException) AuthenticationException(org.apache.archiva.redback.authentication.AuthenticationException) AuthorizationException(org.apache.archiva.redback.authorization.AuthorizationException) DavException(org.apache.jackrabbit.webdav.DavException) SecuritySession(org.apache.archiva.redback.system.SecuritySession) UnauthorizedException(org.apache.archiva.redback.authorization.UnauthorizedException) AuthenticationResult(org.apache.archiva.redback.authentication.AuthenticationResult)

Example 4 with AuthenticationException

use of org.apache.archiva.redback.authentication.AuthenticationException 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 5 with AuthenticationException

use of org.apache.archiva.redback.authentication.AuthenticationException in project archiva by apache.

the class ArchivaUserManagerAuthenticator method authenticate.

@Override
public AuthenticationResult authenticate(AuthenticationDataSource ds) throws AuthenticationException, AccountLockedException, MustChangePasswordException {
    boolean authenticationSuccess = false;
    String username = null;
    Exception resultException = null;
    PasswordBasedAuthenticationDataSource source = (PasswordBasedAuthenticationDataSource) ds;
    List<AuthenticationFailureCause> authnResultErrors = new ArrayList<>();
    for (UserManager userManager : userManagers) {
        try {
            log.debug("Authenticate: {} with userManager: {}", source, userManager.getId());
            User user = userManager.findUser(source.getUsername());
            username = user.getUsername();
            if (user.isLocked()) {
                // throw new AccountLockedException( "Account " + source.getUsername() + " is locked.", user );
                AccountLockedException e = new AccountLockedException("Account " + source.getUsername() + " is locked.", user);
                log.warn("{}", e.getMessage());
                resultException = e;
                authnResultErrors.add(new AuthenticationFailureCause(AuthenticationConstants.AUTHN_LOCKED_USER_EXCEPTION, e.getMessage()));
            }
            if (user.isPasswordChangeRequired() && source.isEnforcePasswordChange()) {
                // throw new MustChangePasswordException( "Password expired.", user );
                MustChangePasswordException e = new MustChangePasswordException("Password expired.", user);
                log.warn("{}", e.getMessage());
                resultException = e;
                authnResultErrors.add(new AuthenticationFailureCause(AuthenticationConstants.AUTHN_MUST_CHANGE_PASSWORD_EXCEPTION, e.getMessage()));
            }
            PasswordEncoder encoder = securityPolicy.getPasswordEncoder();
            log.debug("PasswordEncoder: {}", encoder.getClass().getName());
            boolean isPasswordValid = encoder.isPasswordValid(user.getEncodedPassword(), source.getPassword());
            if (isPasswordValid) {
                log.debug("User {} provided a valid password", source.getUsername());
                try {
                    securityPolicy.extensionPasswordExpiration(user);
                    authenticationSuccess = true;
                    // REDBACK-151 do not make unnessesary updates to the user object
                    if (user.getCountFailedLoginAttempts() > 0) {
                        user.setCountFailedLoginAttempts(0);
                        if (!userManager.isReadOnly()) {
                            userManager.updateUser(user);
                        }
                    }
                    return new AuthenticationResult(true, source.getUsername(), null);
                } catch (MustChangePasswordException e) {
                    user.setPasswordChangeRequired(true);
                    // throw e;
                    resultException = e;
                    authnResultErrors.add(new AuthenticationFailureCause(AuthenticationConstants.AUTHN_MUST_CHANGE_PASSWORD_EXCEPTION, e.getMessage()).user(user));
                }
            } else {
                log.warn("Password is Invalid for user {} and userManager '{}'.", source.getUsername(), userManager.getId());
                authnResultErrors.add(new AuthenticationFailureCause(AuthenticationConstants.AUTHN_NO_SUCH_USER, "Password is Invalid for user " + source.getUsername() + ".").user(user));
                try {
                    securityPolicy.extensionExcessiveLoginAttempts(user);
                } finally {
                    if (!userManager.isReadOnly()) {
                        userManager.updateUser(user);
                    }
                }
            // return new AuthenticationResult( false, source.getUsername(), null, authnResultExceptionsMap );
            }
        } catch (UserNotFoundException e) {
            log.warn("Login for user {} and userManager {} failed. user not found.", source.getUsername(), userManager.getId());
            resultException = e;
            authnResultErrors.add(new AuthenticationFailureCause(AuthenticationConstants.AUTHN_NO_SUCH_USER, "Login for user " + source.getUsername() + " failed. user not found."));
        } catch (Exception e) {
            log.warn("Login for user {} and userManager {} failed, message: {}", source.getUsername(), userManager.getId(), e.getMessage());
            e.printStackTrace();
            resultException = e;
            authnResultErrors.add(new AuthenticationFailureCause(AuthenticationConstants.AUTHN_RUNTIME_EXCEPTION, "Login for user " + source.getUsername() + " failed, message: " + e.getMessage()));
        }
    }
    return new AuthenticationResult(authenticationSuccess, username, resultException, authnResultErrors);
}
Also used : UserNotFoundException(org.apache.archiva.redback.users.UserNotFoundException) AccountLockedException(org.apache.archiva.redback.policy.AccountLockedException) User(org.apache.archiva.redback.users.User) PasswordEncoder(org.apache.archiva.redback.policy.PasswordEncoder) ArrayList(java.util.ArrayList) RepositoryAdminException(org.apache.archiva.admin.model.RepositoryAdminException) AuthenticationException(org.apache.archiva.redback.authentication.AuthenticationException) UserNotFoundException(org.apache.archiva.redback.users.UserNotFoundException) AccountLockedException(org.apache.archiva.redback.policy.AccountLockedException) MustChangePasswordException(org.apache.archiva.redback.policy.MustChangePasswordException) AuthenticationResult(org.apache.archiva.redback.authentication.AuthenticationResult) MustChangePasswordException(org.apache.archiva.redback.policy.MustChangePasswordException) AuthenticationFailureCause(org.apache.archiva.redback.authentication.AuthenticationFailureCause) UserManager(org.apache.archiva.redback.users.UserManager) PasswordBasedAuthenticationDataSource(org.apache.archiva.redback.authentication.PasswordBasedAuthenticationDataSource)

Aggregations

AuthenticationException (org.apache.archiva.redback.authentication.AuthenticationException)9 AuthenticationResult (org.apache.archiva.redback.authentication.AuthenticationResult)8 Test (org.junit.Test)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)4 HttpServletResponse (javax.servlet.http.HttpServletResponse)4 UnauthorizedException (org.apache.archiva.redback.authorization.UnauthorizedException)4 AccountLockedException (org.apache.archiva.redback.policy.AccountLockedException)4 MustChangePasswordException (org.apache.archiva.redback.policy.MustChangePasswordException)4 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)4 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)4 SecuritySession (org.apache.archiva.redback.system.SecuritySession)3 InputStream (java.io.InputStream)2 Path (java.nio.file.Path)2 HttpSession (javax.servlet.http.HttpSession)2 DefaultSecuritySession (org.apache.archiva.redback.system.DefaultSecuritySession)2 UserNotFoundException (org.apache.archiva.redback.users.UserNotFoundException)2 SyndFeed (com.sun.syndication.feed.synd.SyndFeed)1 FeedException (com.sun.syndication.io.FeedException)1 SyndFeedOutput (com.sun.syndication.io.SyndFeedOutput)1 ArrayList (java.util.ArrayList)1