Search in sources :

Example 1 with User

use of org.apache.archiva.redback.users.User in project archiva by apache.

the class RepositoryServletSecurityTest method testPutWithValidUserWithWriteAccess.

// test deploy with a valid user with write access
@Test
public void testPutWithValidUserWithWriteAccess() throws Exception {
    assertTrue(Files.exists(repoRootInternal.getRoot()));
    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
    String putUrl = "http://machine.com/repository/internal/path/to/artifact.jar";
    InputStream is = getClass().getResourceAsStream("/artifact.jar");
    assertNotNull("artifact.jar inputstream", is);
    servlet.setDavSessionProvider(davSessionProvider);
    ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
    archivaDavResourceFactory.setHttpAuth(httpAuth);
    archivaDavResourceFactory.setServletAuth(servletAuth);
    TestAuditListener listener = new TestAuditListener();
    archivaDavResourceFactory.addAuditListener(listener);
    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))).andReturn(true);
    User user = new SimpleUser();
    user.setUsername("admin");
    // ArchivaDavResourceFactory#isAuthorized()
    SecuritySession session = new DefaultSecuritySession();
    EasyMock.expect(httpAuth.getAuthenticationResult(anyObject(HttpServletRequest.class), anyObject(HttpServletResponse.class))).andReturn(result);
    EasyMock.expect(httpAuth.getSecuritySession(mockHttpServletRequest.getSession())).andReturn(session);
    EasyMock.expect(httpAuth.getSessionUser(mockHttpServletRequest.getSession())).andReturn(user);
    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_UPLOAD))).andReturn(true);
    httpAuthControl.replay();
    servletAuthControl.replay();
    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());
    assertEquals("admin", listener.getEvents().get(0).getUserId());
}
Also used : TestAuditListener(org.apache.archiva.repository.audit.TestAuditListener) User(org.apache.archiva.redback.users.User) SimpleUser(org.apache.archiva.redback.users.memory.SimpleUser) SimpleUser(org.apache.archiva.redback.users.memory.SimpleUser) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) InputStream(java.io.InputStream) SecuritySession(org.apache.archiva.redback.system.SecuritySession) DefaultSecuritySession(org.apache.archiva.redback.system.DefaultSecuritySession) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthenticationResult(org.apache.archiva.redback.authentication.AuthenticationResult) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) DefaultSecuritySession(org.apache.archiva.redback.system.DefaultSecuritySession) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.Test)

Example 2 with User

use of org.apache.archiva.redback.users.User in project archiva by apache.

the class AbstractRepositoryAdmin method triggerAuditEvent.

protected void triggerAuditEvent(String repositoryId, String resource, String action, AuditInformation auditInformation) {
    User user = auditInformation == null ? null : auditInformation.getUser();
    AuditEvent event = new AuditEvent(repositoryId, user == null ? "null" : user.getUsername(), resource, action);
    event.setRemoteIP(auditInformation == null ? "null" : auditInformation.getRemoteAddr());
    for (AuditListener listener : getAuditListeners()) {
        listener.auditEvent(event);
    }
}
Also used : User(org.apache.archiva.redback.users.User) AuditEvent(org.apache.archiva.metadata.model.facets.AuditEvent) AuditListener(org.apache.archiva.repository.events.AuditListener)

Example 3 with User

use of org.apache.archiva.redback.users.User in project archiva by apache.

the class DefaultRepositoriesService method copyArtifact.

@Override
public Boolean copyArtifact(ArtifactTransferRequest artifactTransferRequest) throws ArchivaRestServiceException {
    // check parameters
    String userName = getAuditInformation().getUser().getUsername();
    if (StringUtils.isBlank(userName)) {
        throw new ArchivaRestServiceException("copyArtifact call: userName not found", null);
    }
    if (StringUtils.isBlank(artifactTransferRequest.getRepositoryId())) {
        throw new ArchivaRestServiceException("copyArtifact call: sourceRepositoryId cannot be null", null);
    }
    if (StringUtils.isBlank(artifactTransferRequest.getTargetRepositoryId())) {
        throw new ArchivaRestServiceException("copyArtifact call: targetRepositoryId cannot be null", null);
    }
    ManagedRepository source = null;
    try {
        source = managedRepositoryAdmin.getManagedRepository(artifactTransferRequest.getRepositoryId());
    } catch (RepositoryAdminException e) {
        throw new ArchivaRestServiceException(e.getMessage(), e);
    }
    if (source == null) {
        throw new ArchivaRestServiceException("cannot find repository with id " + artifactTransferRequest.getRepositoryId(), null);
    }
    ManagedRepository target = null;
    try {
        target = managedRepositoryAdmin.getManagedRepository(artifactTransferRequest.getTargetRepositoryId());
    } catch (RepositoryAdminException e) {
        throw new ArchivaRestServiceException(e.getMessage(), e);
    }
    if (target == null) {
        throw new ArchivaRestServiceException("cannot find repository with id " + artifactTransferRequest.getTargetRepositoryId(), null);
    }
    if (StringUtils.isBlank(artifactTransferRequest.getGroupId())) {
        throw new ArchivaRestServiceException("groupId is mandatory", null);
    }
    if (StringUtils.isBlank(artifactTransferRequest.getArtifactId())) {
        throw new ArchivaRestServiceException("artifactId is mandatory", null);
    }
    if (StringUtils.isBlank(artifactTransferRequest.getVersion())) {
        throw new ArchivaRestServiceException("version is mandatory", null);
    }
    if (VersionUtil.isSnapshot(artifactTransferRequest.getVersion())) {
        throw new ArchivaRestServiceException("copy of SNAPSHOT not supported", null);
    }
    // end check parameters
    User user = null;
    try {
        user = securitySystem.getUserManager().findUser(userName);
    } catch (UserNotFoundException e) {
        throw new ArchivaRestServiceException("user " + userName + " not found", e);
    } catch (UserManagerException e) {
        throw new ArchivaRestServiceException("ArchivaRestServiceException:" + e.getMessage(), e);
    }
    // check karma on source : read
    AuthenticationResult authn = new AuthenticationResult(true, userName, null);
    SecuritySession securitySession = new DefaultSecuritySession(authn, user);
    try {
        boolean authz = securitySystem.isAuthorized(securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS, artifactTransferRequest.getRepositoryId());
        if (!authz) {
            throw new ArchivaRestServiceException("not authorized to access repo:" + artifactTransferRequest.getRepositoryId(), null);
        }
    } catch (AuthorizationException e) {
        log.error("error reading permission: {}", e.getMessage(), e);
        throw new ArchivaRestServiceException(e.getMessage(), e);
    }
    // check karma on target: write
    try {
        boolean authz = securitySystem.isAuthorized(securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD, artifactTransferRequest.getTargetRepositoryId());
        if (!authz) {
            throw new ArchivaRestServiceException("not authorized to write to repo:" + artifactTransferRequest.getTargetRepositoryId(), null);
        }
    } catch (AuthorizationException e) {
        log.error("error reading permission: {}", e.getMessage(), e);
        throw new ArchivaRestServiceException(e.getMessage(), e);
    }
    // sounds good we can continue !
    ArtifactReference artifactReference = new ArtifactReference();
    artifactReference.setArtifactId(artifactTransferRequest.getArtifactId());
    artifactReference.setGroupId(artifactTransferRequest.getGroupId());
    artifactReference.setVersion(artifactTransferRequest.getVersion());
    artifactReference.setClassifier(artifactTransferRequest.getClassifier());
    String packaging = StringUtils.trim(artifactTransferRequest.getPackaging());
    artifactReference.setType(StringUtils.isEmpty(packaging) ? "jar" : packaging);
    try {
        ManagedRepositoryContent sourceRepository = getManagedRepositoryContent(artifactTransferRequest.getRepositoryId());
        String artifactSourcePath = sourceRepository.toPath(artifactReference);
        if (StringUtils.isEmpty(artifactSourcePath)) {
            log.error("cannot find artifact {}", artifactTransferRequest);
            throw new ArchivaRestServiceException("cannot find artifact " + artifactTransferRequest.toString(), null);
        }
        Path artifactFile = Paths.get(source.getLocation(), artifactSourcePath);
        if (!Files.exists(artifactFile)) {
            log.error("cannot find artifact {}", artifactTransferRequest);
            throw new ArchivaRestServiceException("cannot find artifact " + artifactTransferRequest.toString(), null);
        }
        ManagedRepositoryContent targetRepository = getManagedRepositoryContent(artifactTransferRequest.getTargetRepositoryId());
        String artifactPath = targetRepository.toPath(artifactReference);
        int lastIndex = artifactPath.lastIndexOf('/');
        String path = artifactPath.substring(0, lastIndex);
        Path targetPath = Paths.get(target.getLocation(), path);
        Date lastUpdatedTimestamp = Calendar.getInstance().getTime();
        int newBuildNumber = 1;
        String timestamp = null;
        Path versionMetadataFile = targetPath.resolve(MetadataTools.MAVEN_METADATA);
        /* unused */
        getMetadata(versionMetadataFile);
        if (!Files.exists(targetPath)) {
            Files.createDirectories(targetPath);
        }
        String filename = artifactPath.substring(lastIndex + 1);
        boolean fixChecksums = !(archivaAdministration.getKnownContentConsumers().contains("create-missing-checksums"));
        Path targetFile = targetPath.resolve(filename);
        if (Files.exists(targetFile) && target.isBlockRedeployments()) {
            throw new ArchivaRestServiceException("artifact already exists in target repo: " + artifactTransferRequest.getTargetRepositoryId() + " and redeployment blocked", null);
        } else {
            copyFile(artifactFile, targetPath, filename, fixChecksums);
            queueRepositoryTask(target.getId(), targetFile);
        }
        // copy source pom to target repo
        String pomFilename = filename;
        if (StringUtils.isNotBlank(artifactTransferRequest.getClassifier())) {
            pomFilename = StringUtils.remove(pomFilename, "-" + artifactTransferRequest.getClassifier());
        }
        pomFilename = FilenameUtils.removeExtension(pomFilename) + ".pom";
        Path pomFile = Paths.get(source.getLocation(), artifactSourcePath.substring(0, artifactPath.lastIndexOf('/')), pomFilename);
        if (pomFile != null && Files.size(pomFile) > 0) {
            copyFile(pomFile, targetPath, pomFilename, fixChecksums);
            queueRepositoryTask(target.getId(), targetPath.resolve(pomFilename));
        }
        // explicitly update only if metadata-updater consumer is not enabled!
        if (!archivaAdministration.getKnownContentConsumers().contains("metadata-updater")) {
            updateProjectMetadata(targetPath.toAbsolutePath().toString(), lastUpdatedTimestamp, timestamp, newBuildNumber, fixChecksums, artifactTransferRequest);
        }
        String msg = "Artifact \'" + artifactTransferRequest.getGroupId() + ":" + artifactTransferRequest.getArtifactId() + ":" + artifactTransferRequest.getVersion() + "\' was successfully deployed to repository \'" + artifactTransferRequest.getTargetRepositoryId() + "\'";
        log.debug("copyArtifact {}", msg);
    } catch (RepositoryException e) {
        log.error("RepositoryException: {}", e.getMessage(), e);
        throw new ArchivaRestServiceException(e.getMessage(), e);
    } catch (RepositoryAdminException e) {
        log.error("RepositoryAdminException: {}", e.getMessage(), e);
        throw new ArchivaRestServiceException(e.getMessage(), e);
    } catch (IOException e) {
        log.error("IOException: {}", e.getMessage(), e);
        throw new ArchivaRestServiceException(e.getMessage(), e);
    }
    return true;
}
Also used : UserNotFoundException(org.apache.archiva.redback.users.UserNotFoundException) Path(java.nio.file.Path) ManagedRepository(org.apache.archiva.admin.model.beans.ManagedRepository) User(org.apache.archiva.redback.users.User) AuthorizationException(org.apache.archiva.redback.authorization.AuthorizationException) SecuritySession(org.apache.archiva.redback.system.SecuritySession) DefaultSecuritySession(org.apache.archiva.redback.system.DefaultSecuritySession) RepositoryException(org.apache.archiva.repository.RepositoryException) MetadataRepositoryException(org.apache.archiva.metadata.repository.MetadataRepositoryException) IOException(java.io.IOException) RepositoryAdminException(org.apache.archiva.admin.model.RepositoryAdminException) Date(java.util.Date) AuthenticationResult(org.apache.archiva.redback.authentication.AuthenticationResult) UserManagerException(org.apache.archiva.redback.users.UserManagerException) ArchivaRestServiceException(org.apache.archiva.rest.api.services.ArchivaRestServiceException) ManagedRepositoryContent(org.apache.archiva.repository.ManagedRepositoryContent) DefaultSecuritySession(org.apache.archiva.redback.system.DefaultSecuritySession) ArtifactReference(org.apache.archiva.model.ArtifactReference)

Example 4 with User

use of org.apache.archiva.redback.users.User in project archiva by apache.

the class ArchivaServletAuthenticatorTest method testIsAuthorizedUserHasNoWriteAccess.

@Test
public void testIsAuthorizedUserHasNoWriteAccess() throws Exception {
    createUser(USER_ALPACA, "Al 'Archiva' Paca");
    assignRepositoryObserverRole(USER_ALPACA, "corporate");
    // httpServletRequestControl.expectAndReturn( request.getRemoteAddr(), "192.168.111.111" );
    EasyMock.expect(request.getRemoteAddr()).andReturn("192.168.111.111");
    UserManager userManager = securitySystem.getUserManager();
    User user = userManager.findUser(USER_ALPACA);
    AuthenticationResult result = new AuthenticationResult(true, USER_ALPACA, null);
    SecuritySession session = new DefaultSecuritySession(result, user);
    httpServletRequestControl.replay();
    try {
        servletAuth.isAuthorized(request, session, "corporate", ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD);
        fail("UnauthorizedException should have been thrown.");
    } catch (UnauthorizedException e) {
        assertEquals("Access denied for repository corporate", e.getMessage());
    }
    httpServletRequestControl.verify();
    restoreGuestInitialValues(USER_ALPACA);
}
Also used : User(org.apache.archiva.redback.users.User) UserManager(org.apache.archiva.redback.users.UserManager) SecuritySession(org.apache.archiva.redback.system.SecuritySession) DefaultSecuritySession(org.apache.archiva.redback.system.DefaultSecuritySession) UnauthorizedException(org.apache.archiva.redback.authorization.UnauthorizedException) DefaultSecuritySession(org.apache.archiva.redback.system.DefaultSecuritySession) AuthenticationResult(org.apache.archiva.redback.authentication.AuthenticationResult) Test(org.junit.Test)

Example 5 with User

use of org.apache.archiva.redback.users.User in project archiva by apache.

the class ArchivaServletAuthenticatorTest method testIsAuthorizedUserHasReadAccess.

@Test
public void testIsAuthorizedUserHasReadAccess() throws Exception {
    createUser(USER_ALPACA, "Al 'Archiva' Paca");
    assignRepositoryObserverRole(USER_ALPACA, "corporate");
    UserManager userManager = securitySystem.getUserManager();
    User user = userManager.findUser(USER_ALPACA);
    AuthenticationResult result = new AuthenticationResult(true, USER_ALPACA, null);
    SecuritySession session = new DefaultSecuritySession(result, user);
    boolean isAuthorized = servletAuth.isAuthorized(request, session, "corporate", ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS);
    assertTrue(isAuthorized);
    restoreGuestInitialValues(USER_ALPACA);
}
Also used : User(org.apache.archiva.redback.users.User) UserManager(org.apache.archiva.redback.users.UserManager) SecuritySession(org.apache.archiva.redback.system.SecuritySession) DefaultSecuritySession(org.apache.archiva.redback.system.DefaultSecuritySession) DefaultSecuritySession(org.apache.archiva.redback.system.DefaultSecuritySession) AuthenticationResult(org.apache.archiva.redback.authentication.AuthenticationResult) Test(org.junit.Test)

Aggregations

User (org.apache.archiva.redback.users.User)19 UserManager (org.apache.archiva.redback.users.UserManager)11 AuthenticationResult (org.apache.archiva.redback.authentication.AuthenticationResult)10 DefaultSecuritySession (org.apache.archiva.redback.system.DefaultSecuritySession)9 UserNotFoundException (org.apache.archiva.redback.users.UserNotFoundException)9 SecuritySession (org.apache.archiva.redback.system.SecuritySession)8 UserManagerException (org.apache.archiva.redback.users.UserManagerException)8 RepositoryAdminException (org.apache.archiva.admin.model.RepositoryAdminException)6 Test (org.junit.Test)5 AbstractUserManager (org.apache.archiva.redback.users.AbstractUserManager)4 UnauthorizedException (org.apache.archiva.redback.authorization.UnauthorizedException)3 Path (java.nio.file.Path)2 ArrayList (java.util.ArrayList)2 AuthorizationException (org.apache.archiva.redback.authorization.AuthorizationException)2 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 Date (java.util.Date)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 AuditInformation (org.apache.archiva.admin.model.AuditInformation)1