Search in sources :

Example 16 with SecurityServiceException

use of ddf.security.service.SecurityServiceException in project ddf by codice.

the class UserManagerImpl method authenticate.

/**
     * @param authentication The {@link Authentication} that proves the users identity. {@link org.apache.ftpserver.usermanager.AnonymousAuthentication} is not permitted
     * @return {@link User} upon successful authorization
     * @throws AuthenticationFailedException upon unsuccessful authorization
     */
public User authenticate(Authentication authentication) throws AuthenticationFailedException {
    UPAuthenticationToken upAuthenticationToken;
    String username;
    User user;
    if (authentication instanceof UsernamePasswordAuthentication) {
        username = ((UsernamePasswordAuthentication) authentication).getUsername();
        upAuthenticationToken = new UPAuthenticationToken(username, ((UsernamePasswordAuthentication) authentication).getPassword());
        try {
            Subject subject = securityManager.getSubject(upAuthenticationToken);
            if (subject != null) {
                if (!doesExist(username)) {
                    user = createUser(username, subject);
                } else {
                    user = getUserByName(username);
                    updateUserSubject(user, subject);
                }
                return user;
            }
        } catch (SecurityServiceException e) {
            LOGGER.info("Failure to retrieve subject.", e);
            throw new AuthenticationFailedException("Failure to retrieve subject.");
        }
    }
    throw new AuthenticationFailedException("Authentication failed");
}
Also used : SecurityServiceException(ddf.security.service.SecurityServiceException) FtpUser(ddf.catalog.ftp.user.FtpUser) User(org.apache.ftpserver.ftplet.User) AuthenticationFailedException(org.apache.ftpserver.ftplet.AuthenticationFailedException) UPAuthenticationToken(org.codice.ddf.security.handler.api.UPAuthenticationToken) UsernamePasswordAuthentication(org.apache.ftpserver.usermanager.UsernamePasswordAuthentication) Subject(ddf.security.Subject)

Example 17 with SecurityServiceException

use of ddf.security.service.SecurityServiceException in project ddf by codice.

the class FederationAdminServiceImpl method deleteRegistryEntriesByMetacardIds.

@Override
public void deleteRegistryEntriesByMetacardIds(List<String> metacardIds, Set<String> destinations) throws FederationAdminException {
    if (CollectionUtils.isEmpty(metacardIds)) {
        throw new FederationAdminException("An empty list of metacard ids to be deleted was received. Nothing to delete.");
    }
    List<Serializable> serializableIds = new ArrayList<>(metacardIds);
    Map<String, Serializable> properties = new HashMap<>();
    DeleteRequest deleteRequest = new DeleteRequestImpl(serializableIds, Metacard.ID, properties, destinations);
    try {
        DeleteResponse deleteResponse = security.runWithSubjectOrElevate(() -> catalogFramework.delete(deleteRequest));
        if (!deleteResponse.getProcessingErrors().isEmpty()) {
            throw new FederationAdminException("Processing error occurred while deleting registry entry. Details" + System.lineSeparator() + stringifyProcessingErrors(deleteResponse.getProcessingErrors()));
        }
    } catch (SecurityServiceException | InvocationTargetException e) {
        String message = "Error deleting registry entries by metacard ids.";
        LOGGER.debug("{} Metacard Ids provided: {}", message, metacardIds);
        throw new FederationAdminException(message, e);
    }
}
Also used : FederationAdminException(org.codice.ddf.registry.federationadmin.service.internal.FederationAdminException) Serializable(java.io.Serializable) SecurityServiceException(ddf.security.service.SecurityServiceException) HashMap(java.util.HashMap) DeleteRequestImpl(ddf.catalog.operation.impl.DeleteRequestImpl) ArrayList(java.util.ArrayList) InvocationTargetException(java.lang.reflect.InvocationTargetException) DeleteResponse(ddf.catalog.operation.DeleteResponse) DeleteRequest(ddf.catalog.operation.DeleteRequest)

Example 18 with SecurityServiceException

use of ddf.security.service.SecurityServiceException in project ddf by codice.

the class FederationAdminServiceImpl method deleteRegistryEntriesByRegistryIds.

@Override
public void deleteRegistryEntriesByRegistryIds(List<String> registryIds, Set<String> destinations) throws FederationAdminException {
    if (CollectionUtils.isEmpty(registryIds)) {
        throw new FederationAdminException("An empty list of registry ids to be deleted was received. Nothing to delete.");
    }
    List<Serializable> serializableIds = new ArrayList<>(registryIds);
    Map<String, Serializable> properties = new HashMap<>();
    String deleteField = RegistryObjectMetacardType.REGISTRY_ID;
    if (CollectionUtils.isNotEmpty(destinations)) {
        deleteField = Metacard.ID;
        try {
            List<Metacard> localMetacards = security.runWithSubjectOrElevate(() -> this.getRegistryMetacardsByRegistryIds(registryIds));
            List<Filter> idFilters = localMetacards.stream().map(e -> filterBuilder.attribute(RegistryObjectMetacardType.REMOTE_METACARD_ID).is().equalTo().text(e.getId())).collect(Collectors.toList());
            Filter baseFilter = filterBuilder.allOf(getBasicFilter(RegistryConstants.REGISTRY_TAG_INTERNAL));
            List<Metacard> toDelete = security.runWithSubjectOrElevate(() -> this.getRegistryMetacardsByFilter(filterBuilder.allOf(baseFilter, filterBuilder.anyOf(idFilters)), destinations));
            serializableIds = toDelete.stream().map(e -> e.getId()).collect(Collectors.toList());
        } catch (SecurityServiceException | InvocationTargetException e) {
            throw new FederationAdminException("Error looking up metacards to delete.", e);
        }
    }
    DeleteRequest deleteRequest = new DeleteRequestImpl(serializableIds, deleteField, properties, destinations);
    try {
        DeleteResponse deleteResponse = security.runWithSubjectOrElevate(() -> catalogFramework.delete(deleteRequest));
        if (!deleteResponse.getProcessingErrors().isEmpty()) {
            throw new FederationAdminException("Processing error occurred while deleting registry entry. Details:" + System.lineSeparator() + stringifyProcessingErrors(deleteResponse.getProcessingErrors()));
        }
    } catch (SecurityServiceException | InvocationTargetException e) {
        String message = "Error deleting registry entries by registry id.";
        LOGGER.debug("{} Registry Ids provided: {}", message, registryIds);
        throw new FederationAdminException(message, e);
    }
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) CreateRequest(ddf.catalog.operation.CreateRequest) UpdateRequestImpl(ddf.catalog.operation.impl.UpdateRequestImpl) FederationAdminService(org.codice.ddf.registry.federationadmin.service.internal.FederationAdminService) LoggerFactory(org.slf4j.LoggerFactory) FederationAdminException(org.codice.ddf.registry.federationadmin.service.internal.FederationAdminException) Map(java.util.Map) DeleteRequestImpl(ddf.catalog.operation.impl.DeleteRequestImpl) Bundle(org.osgi.framework.Bundle) InputTransformer(ddf.catalog.transform.InputTransformer) PrintWriter(java.io.PrintWriter) SortByImpl(org.geotools.filter.SortByImpl) RegistryUtility(org.codice.ddf.registry.common.metacard.RegistryUtility) Set(java.util.Set) ParserException(org.codice.ddf.parser.ParserException) Collectors(java.util.stream.Collectors) BundleContext(org.osgi.framework.BundleContext) Serializable(java.io.Serializable) InvocationTargetException(java.lang.reflect.InvocationTargetException) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) Objects(java.util.Objects) DeleteRequest(ddf.catalog.operation.DeleteRequest) IOUtils(org.apache.commons.io.IOUtils) QueryResponse(ddf.catalog.operation.QueryResponse) List(java.util.List) SlotTypeHelper(org.codice.ddf.registry.schemabindings.helper.SlotTypeHelper) Optional(java.util.Optional) RegistryObjectMetacardType(org.codice.ddf.registry.common.metacard.RegistryObjectMetacardType) UpdateResponse(ddf.catalog.operation.UpdateResponse) QueryRequestImpl(ddf.catalog.operation.impl.QueryRequestImpl) FilterBuilder(ddf.catalog.filter.FilterBuilder) PropertyNameImpl(ddf.catalog.filter.impl.PropertyNameImpl) CatalogFramework(ddf.catalog.CatalogFramework) HashMap(java.util.HashMap) DeleteResponse(ddf.catalog.operation.DeleteResponse) ArrayList(java.util.ArrayList) SecurityServiceException(ddf.security.service.SecurityServiceException) MetacardMarshaller(org.codice.ddf.registry.schemabindings.helper.MetacardMarshaller) SortBy(org.opengis.filter.sort.SortBy) CreateResponse(ddf.catalog.operation.CreateResponse) CollectionUtils(org.apache.commons.collections.CollectionUtils) Metacard(ddf.catalog.data.Metacard) QueryRequest(ddf.catalog.operation.QueryRequest) UpdateRequest(ddf.catalog.operation.UpdateRequest) RegistryConstants(org.codice.ddf.registry.common.RegistryConstants) InternationalStringTypeHelper(org.codice.ddf.registry.schemabindings.helper.InternationalStringTypeHelper) Result(ddf.catalog.data.Result) SortOrder(org.opengis.filter.sort.SortOrder) CreateRequestImpl(ddf.catalog.operation.impl.CreateRequestImpl) QueryImpl(ddf.catalog.operation.impl.QueryImpl) Logger(org.slf4j.Logger) RegistryPackageType(oasis.names.tc.ebxml_regrep.xsd.rim._3.RegistryPackageType) Security(org.codice.ddf.security.common.Security) StringWriter(java.io.StringWriter) IOException(java.io.IOException) AbstractMap(java.util.AbstractMap) PropertyName(org.opengis.filter.expression.PropertyName) ProcessingDetails(ddf.catalog.operation.ProcessingDetails) Filter(org.opengis.filter.Filter) Collections(java.util.Collections) FrameworkUtil(org.osgi.framework.FrameworkUtil) FederationAdminException(org.codice.ddf.registry.federationadmin.service.internal.FederationAdminException) Serializable(java.io.Serializable) SecurityServiceException(ddf.security.service.SecurityServiceException) HashMap(java.util.HashMap) DeleteRequestImpl(ddf.catalog.operation.impl.DeleteRequestImpl) ArrayList(java.util.ArrayList) InvocationTargetException(java.lang.reflect.InvocationTargetException) Metacard(ddf.catalog.data.Metacard) DeleteResponse(ddf.catalog.operation.DeleteResponse) Filter(org.opengis.filter.Filter) DeleteRequest(ddf.catalog.operation.DeleteRequest)

Example 19 with SecurityServiceException

use of ddf.security.service.SecurityServiceException in project ddf by codice.

the class Query method getMetacardForId.

/**
     * @param searchPhrase The search phrase used to query for the metacard.
     * @param proxyTicket  The CAS proxy ticket that will be used by the STS to get a SAML assertion.
     * @return
     */
private String getMetacardForId(String searchPhrase, String proxyTicket) {
    Filter filter = filterBuilder.attribute(Metacard.ANY_TEXT).is().like().text(searchPhrase);
    LOGGER.info("Query filter: {}", filter.toString());
    String queryError = "Unable to perform query " + filter.toString() + ".";
    QueryRequest request = new QueryRequestImpl(new QueryImpl(filter), true);
    StringBuilder responseString = new StringBuilder();
    try {
        Subject subject = securityManager.getSubject(new CasAuthenticationToken(proxyTicket));
        LOGGER.info("Adding {} property with value {} to request", SecurityConstants.SECURITY_SUBJECT, subject);
        request.getProperties().put(SecurityConstants.SECURITY_SUBJECT, subject);
    } catch (SecurityServiceException se) {
        LOGGER.error("Could not retrieve subject from securitymanager.", se);
        return queryError;
    }
    try {
        LOGGER.debug("About to query the catalog framework with query {}", filter.toString());
        QueryResponse queryResponse = catalogFramework.query(request, null);
        LOGGER.debug("Got query response from catalog framework for query {}", filter.toString());
        List<Result> results = queryResponse.getResults();
        if (results != null) {
            String message = "The query for " + filter.toString() + " returned " + results.size() + " results.";
            responseString.append(message);
            LOGGER.debug(message);
            for (Result curResult : results) {
                Metacard metacard = curResult.getMetacard();
                LOGGER.debug("Transforming the metacard with id [{}] to xml.", metacard.getId());
                BinaryContent content = catalogFramework.transform(metacard, "xml", null);
                StringWriter writer = new StringWriter();
                IOUtils.copy(content.getInputStream(), writer, "UTF8");
                LOGGER.debug("Formatting xml for metacard with id [{}].", metacard.getId());
                responseString.append(format(writer.toString()));
            }
        } else {
            String message = "The query for " + filter.toString() + " returned a null result.";
            responseString.append(message);
            LOGGER.warn(message);
        }
    } catch (SourceUnavailableException e) {
        LOGGER.error(queryError, e);
    } catch (UnsupportedQueryException e) {
        LOGGER.error(queryError, e);
    } catch (FederationException e) {
        LOGGER.error(queryError, e);
    } catch (CatalogTransformerException e) {
        LOGGER.error(queryError, e);
    } catch (IOException e) {
        LOGGER.error(queryError, e);
    }
    return responseString.toString();
}
Also used : SourceUnavailableException(ddf.catalog.source.SourceUnavailableException) SecurityServiceException(ddf.security.service.SecurityServiceException) QueryRequest(ddf.catalog.operation.QueryRequest) CasAuthenticationToken(ddf.security.service.impl.cas.CasAuthenticationToken) UnsupportedQueryException(ddf.catalog.source.UnsupportedQueryException) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) IOException(java.io.IOException) BinaryContent(ddf.catalog.data.BinaryContent) FederationException(ddf.catalog.federation.FederationException) Subject(ddf.security.Subject) Result(ddf.catalog.data.Result) QueryImpl(ddf.catalog.operation.impl.QueryImpl) Metacard(ddf.catalog.data.Metacard) StringWriter(java.io.StringWriter) Filter(org.opengis.filter.Filter) QueryRequestImpl(ddf.catalog.operation.impl.QueryRequestImpl) QueryResponse(ddf.catalog.operation.QueryResponse)

Example 20 with SecurityServiceException

use of ddf.security.service.SecurityServiceException in project ddf by codice.

the class ExportCommandTest method testExecuteWhenSecurityExceptionIsThrown.

@Test
public void testExecuteWhenSecurityExceptionIsThrown() throws Exception {
    // Setup
    when(security.runWithSubjectOrElevate(any(Callable.class))).thenThrow(new SecurityServiceException(INSUFFICIENT_PRIVILEGES_MESSAGE));
    ExportCommand exportCommand = new ExportCommandUnderTest(mockConfigurationMigrationService, mockDefaultExportDirectory);
    // Perform Test
    exportCommand.execute();
    // Verify
    assertErrorMessage(INSUFFICIENT_PRIVILEGES_MESSAGE);
}
Also used : SecurityServiceException(ddf.security.service.SecurityServiceException) Callable(java.util.concurrent.Callable) Test(org.junit.Test)

Aggregations

SecurityServiceException (ddf.security.service.SecurityServiceException)34 Subject (ddf.security.Subject)11 SecurityManager (ddf.security.service.SecurityManager)9 Test (org.junit.Test)9 IOException (java.io.IOException)8 InvocationTargetException (java.lang.reflect.InvocationTargetException)8 X509Certificate (java.security.cert.X509Certificate)6 Response (javax.ws.rs.core.Response)6 SecurityAssertion (ddf.security.assertion.SecurityAssertion)5 HashMap (java.util.HashMap)5 HttpServletRequest (javax.servlet.http.HttpServletRequest)5 Matchers.containsString (org.hamcrest.Matchers.containsString)5 Matchers.anyString (org.mockito.Matchers.anyString)5 CatalogTransformerException (ddf.catalog.transform.CatalogTransformerException)4 Serializable (java.io.Serializable)4 ServletException (javax.servlet.ServletException)4 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)4 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)4 Metacard (ddf.catalog.data.Metacard)3 Result (ddf.catalog.data.Result)3