Search in sources :

Example 1 with Subject

use of ddf.security.Subject in project ddf by codice.

the class InMemoryProcessingFramework method storeMetacardUpdates.

private void storeMetacardUpdates(Map<String, Metacard> metacardsToUpdate, Map<String, Serializable> properties) {
    if (MapUtils.isNotEmpty(metacardsToUpdate)) {
        LOGGER.trace("Storing metacard updates");
        List<Map.Entry<Serializable, Metacard>> updateList = metacardsToUpdate.values().stream().map(metacard -> new AbstractMap.SimpleEntry<Serializable, Metacard>(metacard.getId(), metacard)).collect(Collectors.toList());
        UpdateRequest updateMetacardsRequest = new UpdateRequestImpl(updateList, UpdateRequest.UPDATE_BY_ID, properties);
        Subject subject = (Subject) updateMetacardsRequest.getProperties().get(SecurityConstants.SECURITY_SUBJECT);
        if (subject == null) {
            LOGGER.debug("No subject to send UpdateRequest. Updates will not be sent back to the catalog.");
        } else {
            subject.execute(() -> {
                try {
                    catalogFramework.update(updateMetacardsRequest);
                    LOGGER.debug("Successfully completed update metacards request");
                } catch (IngestException | SourceUnavailableException | RuntimeException e) {
                    LOGGER.info("Unable to complete update request", e);
                }
                return null;
            });
        }
    } else {
        LOGGER.debug("No metacards to update");
    }
}
Also used : ContentItemImpl(ddf.catalog.content.data.impl.ContentItemImpl) SourceUnavailableException(ddf.catalog.source.SourceUnavailableException) CatalogFramework(ddf.catalog.CatalogFramework) UpdateRequestImpl(ddf.catalog.operation.impl.UpdateRequestImpl) LoggerFactory(org.slf4j.LoggerFactory) UpdateStorageRequestImpl(ddf.catalog.content.operation.impl.UpdateStorageRequestImpl) HashMap(java.util.HashMap) ProcessDeleteItem(org.codice.ddf.catalog.async.data.api.internal.ProcessDeleteItem) PostProcessPlugin(org.codice.ddf.catalog.async.plugin.api.internal.PostProcessPlugin) ArrayList(java.util.ArrayList) ProcessingFramework(org.codice.ddf.catalog.async.processingframework.api.internal.ProcessingFramework) PluginExecutionException(ddf.catalog.plugin.PluginExecutionException) UpdateStorageRequest(ddf.catalog.content.operation.UpdateStorageRequest) ContentItem(ddf.catalog.content.data.ContentItem) Metacard(ddf.catalog.data.Metacard) Map(java.util.Map) SecurityConstants(ddf.security.SecurityConstants) UpdateRequest(ddf.catalog.operation.UpdateRequest) ProcessResourceItem(org.codice.ddf.catalog.async.data.api.internal.ProcessResourceItem) ByteSource(com.google.common.io.ByteSource) ExecutorService(java.util.concurrent.ExecutorService) ProcessResource(org.codice.ddf.catalog.async.data.api.internal.ProcessResource) Logger(org.slf4j.Logger) MapUtils(org.apache.commons.collections.MapUtils) IngestException(ddf.catalog.source.IngestException) IOException(java.io.IOException) Subject(ddf.security.Subject) ProcessCreateItem(org.codice.ddf.catalog.async.data.api.internal.ProcessCreateItem) Collectors(java.util.stream.Collectors) Serializable(java.io.Serializable) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) IOUtils(org.apache.commons.io.IOUtils) AbstractMap(java.util.AbstractMap) List(java.util.List) Validate.notNull(org.apache.commons.lang3.Validate.notNull) ProcessRequest(org.codice.ddf.catalog.async.data.api.internal.ProcessRequest) ProcessUpdateItem(org.codice.ddf.catalog.async.data.api.internal.ProcessUpdateItem) TemporaryFileBackedOutputStream(org.codice.ddf.platform.util.TemporaryFileBackedOutputStream) SourceUnavailableException(ddf.catalog.source.SourceUnavailableException) UpdateRequest(ddf.catalog.operation.UpdateRequest) IngestException(ddf.catalog.source.IngestException) UpdateRequestImpl(ddf.catalog.operation.impl.UpdateRequestImpl) Subject(ddf.security.Subject)

Example 2 with Subject

use of ddf.security.Subject in project ddf by codice.

the class InMemoryProcessingFramework method storeContentItemUpdates.

private void storeContentItemUpdates(Map<String, ContentItem> contentItemsToUpdate, Map<String, Serializable> properties) {
    if (MapUtils.isNotEmpty(contentItemsToUpdate)) {
        LOGGER.trace("Storing content item updates(s)");
        UpdateStorageRequest updateStorageRequest = new UpdateStorageRequestImpl(new ArrayList<>(contentItemsToUpdate.values()), properties);
        Subject subject = (Subject) updateStorageRequest.getProperties().get(SecurityConstants.SECURITY_SUBJECT);
        if (subject == null) {
            LOGGER.debug("No subject to send UpdateStorageRequest. Updates will not be sent back to the catalog");
        } else {
            subject.execute(() -> {
                try {
                    catalogFramework.update(updateStorageRequest);
                    LOGGER.debug("Successfully completed update storage request");
                } catch (IngestException | SourceUnavailableException | RuntimeException e) {
                    LOGGER.info("Unable to complete update storage request", e);
                }
                return null;
            });
        }
    } else {
        LOGGER.debug("No content items to update");
    }
}
Also used : SourceUnavailableException(ddf.catalog.source.SourceUnavailableException) UpdateStorageRequestImpl(ddf.catalog.content.operation.impl.UpdateStorageRequestImpl) UpdateStorageRequest(ddf.catalog.content.operation.UpdateStorageRequest) IngestException(ddf.catalog.source.IngestException) Subject(ddf.security.Subject)

Example 3 with Subject

use of ddf.security.Subject in project ddf by codice.

the class WorkspaceService method getWorkspaces.

@SuppressWarnings("unchecked")
@Listener("/service/workspaces")
public void getWorkspaces(final ServerSession remote, Message message) {
    ServerMessage.Mutable reply = new ServerMessageImpl();
    Map<String, Object> data = message.getDataAsMap();
    Subject subject = (Subject) bayeux.getContext().getRequestAttribute(SecurityConstants.SECURITY_SUBJECT);
    String username = SubjectUtils.getName(subject);
    // No workspaces persisted for a guest user (whose username="")
    if (StringUtils.isNotBlank(username)) {
        if (data == null || data.isEmpty() || data.get("workspaces") == null) {
            List<Map<String, Object>> workspacesList = new ArrayList<Map<String, Object>>();
            try {
                workspacesList = persistentStore.get(PersistentStore.WORKSPACE_TYPE, "user = '" + username + "'");
                if (workspacesList.size() == 1) {
                    // Convert workspace's JSON representation back to nested maps of Map<String, Object>
                    Map<String, Object> workspaces = (Map<String, Object>) workspacesList.get(0);
                    JSONContext.Client jsonContext = new Jackson1JSONContextClient();
                    String json = (String) workspaces.get("workspaces_json_txt");
                    LOGGER.debug("workspaces extracted JSON text:\n {}", json);
                    Map<String, Object> workspacesMap;
                    try {
                        workspacesMap = jsonContext.getParser().parse(new StringReader(json), Map.class);
                        reply.putAll(workspacesMap);
                    } catch (ParseException e) {
                        LOGGER.info("ParseException while trying to convert persisted workspaces's for user {} from JSON", username, e);
                    }
                }
            } catch (PersistenceException e) {
                LOGGER.info("PersistenceException while trying to retrieve persisted workspaces for user {}", username, e);
            }
            reply.put(Search.SUCCESSFUL, true);
            remote.deliver(serverSession, "/service/workspaces", reply);
        } else {
            LOGGER.debug("Persisting workspaces for username = {}", username);
            // Use JSON serializer so that only "data" component is serialized, not entire Message
            JSONContext.Server jsonContext = new Jackson1JSONContextServer();
            String json = jsonContext.getGenerator().generate(data);
            LOGGER.debug("workspaces JSON text:\n {}", json);
            PersistentItem item = new PersistentItem();
            item.addIdProperty(username);
            item.addProperty("user", username);
            item.addProperty("workspaces_json", json);
            try {
                persistentStore.add(PersistentStore.WORKSPACE_TYPE, item);
            } catch (PersistenceException e) {
                LOGGER.info("PersistenceException while trying to persist workspaces for user {}", username, e);
            }
            reply.put(Search.SUCCESSFUL, true);
            remote.deliver(serverSession, "/service/workspaces", reply);
        }
    }
}
Also used : PersistentItem(org.codice.ddf.persistence.PersistentItem) ServerMessage(org.cometd.bayeux.server.ServerMessage) ArrayList(java.util.ArrayList) Subject(ddf.security.Subject) JSONContext(org.cometd.common.JSONContext) ServerMessageImpl(org.cometd.server.ServerMessageImpl) StringReader(java.io.StringReader) PersistenceException(org.codice.ddf.persistence.PersistenceException) ParseException(java.text.ParseException) Jackson1JSONContextServer(org.cometd.server.Jackson1JSONContextServer) Jackson1JSONContextClient(org.cometd.common.Jackson1JSONContextClient) Map(java.util.Map) Listener(org.cometd.annotation.Listener)

Example 4 with Subject

use of ddf.security.Subject in project ddf by codice.

the class SearchService method processQuery.

/**
     * Service method called by Cometd when something arrives on the service channel
     *
     * @param remote
     *            - Client session
     * @param message
     *            - JSON message
     */
@Listener("/service/query")
public void processQuery(final ServerSession remote, Message message) {
    ServerMessage.Mutable reply = new ServerMessageImpl();
    Map<String, Object> queryMessage = message.getDataAsMap();
    if (queryMessage != null && queryMessage.containsKey(Search.ID)) {
        bayeux.createChannelIfAbsent("/" + queryMessage.get(Search.ID), new ConfigurableServerChannel.Initializer() {

            public void configureChannel(ConfigurableServerChannel channel) {
                channel.setPersistent(true);
            }
        });
        BayeuxContext context = bayeux.getContext();
        Subject subject = null;
        if (context != null) {
            subject = (Subject) context.getRequestAttribute(SecurityConstants.SECURITY_SUBJECT);
        }
        // kick off the query
        executeQuery(queryMessage, subject);
        reply.put(Search.SUCCESSFUL, true);
        remote.deliver(serverSession, reply);
    } else {
        reply.put(Search.SUCCESSFUL, false);
        reply.put("status", "ERROR: unable to return results, no id in query request");
        remote.deliver(serverSession, reply);
    }
}
Also used : ServerMessageImpl(org.cometd.server.ServerMessageImpl) ServerMessage(org.cometd.bayeux.server.ServerMessage) ConfigurableServerChannel(org.cometd.bayeux.server.ConfigurableServerChannel) BayeuxContext(org.cometd.bayeux.server.BayeuxContext) Subject(ddf.security.Subject) Listener(org.cometd.annotation.Listener)

Example 5 with Subject

use of ddf.security.Subject in project ddf by codice.

the class IdpEndpoint method handleLogin.

protected org.opensaml.saml.saml2.core.Response handleLogin(AuthnRequest authnRequest, String authMethod, HttpServletRequest request, AuthObj authObj, boolean passive, boolean hasCookie) throws SecurityServiceException, WSSecurityException, SimpleSign.SignatureException, ConstraintViolationException {
    LOGGER.debug("Performing login for user. passive: {}, cookie: {}", passive, hasCookie);
    BaseAuthenticationToken token = null;
    request.setAttribute(ContextPolicy.ACTIVE_REALM, BaseAuthenticationToken.ALL_REALM);
    if (PKI.equals(authMethod)) {
        LOGGER.debug("Logging user in via PKI.");
        PKIHandler pkiHandler = new PKIHandler();
        pkiHandler.setTokenFactory(tokenFactory);
        try {
            HandlerResult handlerResult = pkiHandler.getNormalizedToken(request, null, null, false);
            if (handlerResult.getStatus().equals(HandlerResult.Status.COMPLETED)) {
                token = handlerResult.getToken();
            }
        } catch (ServletException e) {
            LOGGER.info("Encountered an exception while checking for PKI auth info.", e);
        }
    } else if (USER_PASS.equals(authMethod)) {
        LOGGER.debug("Logging user in via BASIC auth.");
        if (authObj != null && authObj.username != null && authObj.password != null) {
            token = new UPAuthenticationToken(authObj.username, authObj.password, BaseAuthenticationToken.ALL_REALM);
        } else {
            BasicAuthenticationHandler basicAuthenticationHandler = new BasicAuthenticationHandler();
            HandlerResult handlerResult = basicAuthenticationHandler.getNormalizedToken(request, null, null, false);
            if (handlerResult.getStatus().equals(HandlerResult.Status.COMPLETED)) {
                token = handlerResult.getToken();
            }
        }
    } else if (SAML.equals(authMethod)) {
        LOGGER.debug("Logging user in via SAML assertion.");
        token = new SAMLAuthenticationToken(null, authObj.assertion, BaseAuthenticationToken.ALL_REALM);
    } else if (GUEST.equals(authMethod) && guestAccess) {
        LOGGER.debug("Logging user in as Guest.");
        token = new GuestAuthenticationToken(BaseAuthenticationToken.ALL_REALM, request.getRemoteAddr());
    } else {
        throw new IllegalArgumentException("Auth method is not supported.");
    }
    org.w3c.dom.Element samlToken = null;
    String statusCode;
    if (hasCookie) {
        samlToken = getSamlAssertion(request);
        statusCode = StatusCode.SUCCESS;
    } else {
        try {
            statusCode = StatusCode.AUTHN_FAILED;
            Subject subject = securityManager.getSubject(token);
            for (Object principal : subject.getPrincipals().asList()) {
                if (principal instanceof SecurityAssertion) {
                    SecurityToken securityToken = ((SecurityAssertion) principal).getSecurityToken();
                    samlToken = securityToken.getToken();
                }
            }
            if (samlToken != null) {
                statusCode = StatusCode.SUCCESS;
            }
        } catch (SecurityServiceException e) {
            if (!passive) {
                throw e;
            } else {
                statusCode = StatusCode.AUTHN_FAILED;
            }
        }
    }
    LOGGER.debug("User log in successful.");
    return SamlProtocol.createResponse(SamlProtocol.createIssuer(SystemBaseUrl.constructUrl("/idp/login", true)), SamlProtocol.createStatus(statusCode), authnRequest.getID(), samlToken);
}
Also used : SecurityServiceException(ddf.security.service.SecurityServiceException) GuestAuthenticationToken(org.codice.ddf.security.handler.api.GuestAuthenticationToken) PKIHandler(org.codice.ddf.security.handler.pki.PKIHandler) HandlerResult(org.codice.ddf.security.handler.api.HandlerResult) SecurityAssertion(ddf.security.assertion.SecurityAssertion) SAMLAuthenticationToken(org.codice.ddf.security.handler.api.SAMLAuthenticationToken) Subject(ddf.security.Subject) ServletException(javax.servlet.ServletException) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) Element(org.w3c.dom.Element) BaseAuthenticationToken(org.codice.ddf.security.handler.api.BaseAuthenticationToken) UPAuthenticationToken(org.codice.ddf.security.handler.api.UPAuthenticationToken) BasicAuthenticationHandler(org.codice.ddf.security.handler.basic.BasicAuthenticationHandler) SignableSAMLObject(org.opensaml.saml.common.SignableSAMLObject) SignableXMLObject(org.opensaml.xmlsec.signature.SignableXMLObject) XMLObject(org.opensaml.core.xml.XMLObject)

Aggregations

Subject (ddf.security.Subject)94 Test (org.junit.Test)47 SecurityAssertion (ddf.security.assertion.SecurityAssertion)23 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)23 HashMap (java.util.HashMap)20 Metacard (ddf.catalog.data.Metacard)18 SecurityManager (ddf.security.service.SecurityManager)14 IOException (java.io.IOException)14 Serializable (java.io.Serializable)14 CollectionPermission (ddf.security.permission.CollectionPermission)13 ArrayList (java.util.ArrayList)12 Map (java.util.Map)12 CreateRequest (ddf.catalog.operation.CreateRequest)11 CreateRequestImpl (ddf.catalog.operation.impl.CreateRequestImpl)11 UnsupportedQueryException (ddf.catalog.source.UnsupportedQueryException)10 SecurityServiceException (ddf.security.service.SecurityServiceException)10 HashSet (java.util.HashSet)10 PrincipalCollection (org.apache.shiro.subject.PrincipalCollection)9 Before (org.junit.Before)9 HttpServletRequest (javax.servlet.http.HttpServletRequest)8