Search in sources :

Example 6 with OAuthPluginException

use of ddf.catalog.plugin.OAuthPluginException in project ddf by codice.

the class RESTEndpoint method getDocument.

/**
 * REST Get. Retrieves the metadata entry specified by the id from the federated source specified
 * by sourceid. Transformer argument is optional, but is used to specify what format the data
 * should be returned.
 *
 * @param encodedSourceId
 * @param encodedId
 * @param transformerParam
 * @param uriInfo
 * @return
 */
@Override
@GET
@Path("/sources/{sourceid}/{id}")
public Response getDocument(@Encoded @PathParam("sourceid") String encodedSourceId, @Encoded @PathParam("id") String encodedId, @QueryParam("transform") String transformerParam, @Context UriInfo uriInfo, @Context HttpServletRequest httpRequest) {
    try {
        Response.ResponseBuilder responseBuilder;
        String id = URLDecoder.decode(encodedId, CharEncoding.UTF_8);
        final BinaryContent content = catalogService.getDocument(encodedSourceId, encodedId, transformerParam, uriInfo.getAbsolutePath(), uriInfo.getQueryParameters(), httpRequest);
        if (content == null) {
            return Response.status(Status.NOT_FOUND).entity(String.format(PRE_FORMAT, UNABLE_TO_RETRIEVE_REQUESTED_METACARD)).type(MediaType.TEXT_HTML).build();
        }
        LOGGER.debug("Read and transform complete, preparing response.");
        responseBuilder = Response.ok(content.getInputStream(), content.getMimeTypeValue());
        // Add the Accept-ranges header to let the client know that we accept ranges in bytes
        responseBuilder.header(HEADER_ACCEPT_RANGES, BYTES);
        setFileNameOnResponseBuilder(id, content, responseBuilder);
        long size = content.getSize();
        if (size > 0) {
            responseBuilder.header(HEADER_CONTENT_LENGTH, size);
        }
        return responseBuilder.build();
    } catch (CatalogServiceException e) {
        return createBadRequestResponse(e.getMessage());
    } catch (DataUsageLimitExceededException e) {
        return Response.status(Status.REQUEST_ENTITY_TOO_LARGE).entity(String.format(PRE_FORMAT, e.getMessage())).type(MediaType.TEXT_HTML).build();
    } catch (OAuthPluginException e) {
        return Response.status(Status.SEE_OTHER).header(HttpHeaders.LOCATION, e.getUrl()).build();
    } catch (UnsupportedEncodingException e) {
        String exceptionMessage = "Unknown error occurred while processing request: ";
        LOGGER.info(exceptionMessage, e);
        throw new InternalServerErrorException(exceptionMessage);
    } catch (InternalServerErrorException e) {
        LOGGER.info(e.getMessage());
        return createErrorResponse(e.getMessage());
    }
}
Also used : Response(javax.ws.rs.core.Response) CatalogServiceException(org.codice.ddf.rest.api.CatalogServiceException) OAuthPluginException(ddf.catalog.plugin.OAuthPluginException) DataUsageLimitExceededException(ddf.catalog.resource.DataUsageLimitExceededException) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) BinaryContent(ddf.catalog.data.BinaryContent) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 7 with OAuthPluginException

use of ddf.catalog.plugin.OAuthPluginException in project ddf by codice.

the class QueryOperations method query.

// 
// Helper methods
// 
QueryResponse query(QueryRequest queryRequest, FederationStrategy strategy, boolean overrideFanoutRename, boolean fanoutEnabled) throws UnsupportedQueryException, FederationException {
    FederationStrategy fedStrategy = strategy;
    QueryResponse queryResponse;
    queryRequest = setFlagsOnRequest(queryRequest);
    try {
        queryRequest = validateQueryRequest(queryRequest);
        queryRequest = getFanoutQuery(queryRequest, fanoutEnabled);
        queryRequest = preProcessPreAuthorizationPlugins(queryRequest);
        queryRequest = populateQueryRequestPolicyMap(queryRequest);
        queryRequest = processPreQueryAccessPlugins(queryRequest);
        queryRequest = processPreQueryPlugins(queryRequest);
        queryRequest = validateQueryRequest(queryRequest);
        if (fedStrategy == null) {
            if (frameworkProperties.getFederationStrategy() == null) {
                throw new FederationException("No Federation Strategies exist.  Cannot execute federated query.");
            } else {
                LOGGER.debug("FederationStrategy was not specified, using default strategy: {}", frameworkProperties.getFederationStrategy().getClass());
                fedStrategy = frameworkProperties.getFederationStrategy();
            }
        }
        queryResponse = doQuery(queryRequest, fedStrategy);
        // Allow callers to determine the total results returned from the query; this value
        // may differ from the number of filtered results after processing plugins have been run.
        queryResponse.getProperties().put("actualResultSize", queryResponse.getResults().size());
        LOGGER.trace("BeforePostQueryFilter result size: {}", queryResponse.getResults().size());
        queryResponse = injectAttributes(queryResponse);
        queryResponse = validateFixQueryResponse(queryResponse, overrideFanoutRename, fanoutEnabled);
        queryResponse = postProcessPreAuthorizationPlugins(queryResponse);
        queryResponse = populateQueryResponsePolicyMap(queryResponse);
        queryResponse = processPostQueryAccessPlugins(queryResponse);
        queryResponse = processPostQueryPlugins(queryResponse);
        log(queryResponse);
    } catch (OAuthPluginException e) {
        throw e;
    } catch (RuntimeException re) {
        LOGGER.debug("Unhandled runtime exception during query", re);
        throw new UnsupportedQueryException("Exception during runtime while performing query", re);
    }
    return queryResponse;
}
Also used : OAuthPluginException(ddf.catalog.plugin.OAuthPluginException) FederationStrategy(ddf.catalog.federation.FederationStrategy) QueryResponse(ddf.catalog.operation.QueryResponse) UnsupportedQueryException(ddf.catalog.source.UnsupportedQueryException) FederationException(ddf.catalog.federation.FederationException)

Example 8 with OAuthPluginException

use of ddf.catalog.plugin.OAuthPluginException in project ddf by codice.

the class OAuthPluginTest method testInvalidRefreshedAccessToken.

@Test(expected = OAuthPluginException.class)
public void testInvalidRefreshedAccessToken() throws Exception {
    OAuthFederatedSource source = oauthPlugin.oauthSource;
    Subject subject = getSubject();
    QueryRequest input = mock(QueryRequest.class);
    when(input.getProperties()).thenReturn(ImmutableMap.of(SECURITY_SUBJECT, subject));
    String accessToken = getAccessTokenBuilder().withExpiresAt(new Date(Instant.now().minus(1, ChronoUnit.MINUTES).toEpochMilli())).sign(validAlgorithm);
    String refreshToken = getRefreshTokenBuilder().sign(validAlgorithm);
    Map<String, Map<String, Object>> stateMap = mock(Map.class);
    TokenInformation.TokenEntry tokenEntry = new TokenInformationImpl.TokenEntryImpl(accessToken, refreshToken, METADATA_ENDPOINT);
    when(tokenStorage.read(SESSION, CSW_SOURCE)).thenReturn(tokenEntry);
    when(tokenStorage.getStateMap()).thenReturn(stateMap);
    String invalidAccessToken = getAccessTokenBuilder().sign(invalidAlgorithm);
    Response response = mock(Response.class);
    when(response.getStatus()).thenReturn(200);
    when(response.getEntity()).thenReturn(getResponse(invalidAccessToken));
    when(oauthPlugin.webClient.form(any(Form.class))).thenReturn(response);
    try {
        oauthPlugin.process(source, input);
    } catch (OAuthPluginException e) {
        ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
        verify(stateMap, times(1)).put(anyString(), captor.capture());
        verify(tokenStorage, times(0)).create(anyString(), anyString(), anyString(), anyString(), anyString());
        verify(tokenStorage, times(1)).getStateMap();
        assertUrl(e, captor.getValue());
        throw e;
    }
}
Also used : OAuthFederatedSource(ddf.catalog.source.OAuthFederatedSource) ArgumentCaptor(org.mockito.ArgumentCaptor) QueryRequest(ddf.catalog.operation.QueryRequest) Form(javax.ws.rs.core.Form) TokenInformation(org.codice.ddf.security.token.storage.api.TokenInformation) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Subject(ddf.security.Subject) Date(java.util.Date) Response(javax.ws.rs.core.Response) OAuthPluginException(ddf.catalog.plugin.OAuthPluginException) JSONObject(net.minidev.json.JSONObject) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) Test(org.junit.Test)

Example 9 with OAuthPluginException

use of ddf.catalog.plugin.OAuthPluginException in project ddf by codice.

the class OAuthPluginTest method testInvalidRefreshError.

@Test(expected = OAuthPluginException.class)
public void testInvalidRefreshError() throws Exception {
    OAuthFederatedSource source = oauthPlugin.oauthSource;
    Subject subject = getSubject();
    QueryRequest input = mock(QueryRequest.class);
    when(input.getProperties()).thenReturn(ImmutableMap.of(SECURITY_SUBJECT, subject));
    String accessToken = getAccessTokenBuilder().withExpiresAt(new Date(Instant.now().minus(1, ChronoUnit.MINUTES).toEpochMilli())).sign(validAlgorithm);
    String refreshToken = getRefreshTokenBuilder().sign(validAlgorithm);
    Map<String, Map<String, Object>> stateMap = mock(Map.class);
    TokenInformation.TokenEntry tokenEntry = new TokenInformationImpl.TokenEntryImpl(accessToken, refreshToken, METADATA_ENDPOINT);
    when(tokenStorage.read(SESSION, CSW_SOURCE)).thenReturn(tokenEntry);
    when(tokenStorage.getStateMap()).thenReturn(stateMap);
    Response response = mock(Response.class);
    when(response.getStatus()).thenReturn(400);
    when(response.getEntity()).thenReturn(new ByteArrayInputStream("".getBytes()));
    when(oauthPlugin.webClient.form(any(Form.class))).thenReturn(response);
    try {
        oauthPlugin.process(source, input);
    } catch (OAuthPluginException e) {
        ArgumentCaptor<Map<String, Object>> captor = ArgumentCaptor.forClass(Map.class);
        verify(stateMap, times(1)).put(anyString(), captor.capture());
        verify(tokenStorage, times(1)).getStateMap();
        assertUrl(e, captor.getValue());
        throw e;
    }
}
Also used : OAuthFederatedSource(ddf.catalog.source.OAuthFederatedSource) ArgumentCaptor(org.mockito.ArgumentCaptor) QueryRequest(ddf.catalog.operation.QueryRequest) Form(javax.ws.rs.core.Form) TokenInformation(org.codice.ddf.security.token.storage.api.TokenInformation) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Subject(ddf.security.Subject) Date(java.util.Date) Response(javax.ws.rs.core.Response) OAuthPluginException(ddf.catalog.plugin.OAuthPluginException) ByteArrayInputStream(java.io.ByteArrayInputStream) JSONObject(net.minidev.json.JSONObject) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) Test(org.junit.Test)

Aggregations

OAuthPluginException (ddf.catalog.plugin.OAuthPluginException)9 Map (java.util.Map)7 QueryRequest (ddf.catalog.operation.QueryRequest)6 OAuthFederatedSource (ddf.catalog.source.OAuthFederatedSource)6 Subject (ddf.security.Subject)6 TokenInformation (org.codice.ddf.security.token.storage.api.TokenInformation)6 ImmutableMap (com.google.common.collect.ImmutableMap)5 Test (org.junit.Test)5 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)5 Date (java.util.Date)4 JSONObject (net.minidev.json.JSONObject)4 ArgumentCaptor (org.mockito.ArgumentCaptor)4 Response (javax.ws.rs.core.Response)3 BinaryContent (ddf.catalog.data.BinaryContent)2 FederationException (ddf.catalog.federation.FederationException)2 QueryResponse (ddf.catalog.operation.QueryResponse)2 DataUsageLimitExceededException (ddf.catalog.resource.DataUsageLimitExceededException)2 UnsupportedQueryException (ddf.catalog.source.UnsupportedQueryException)2 HashMap (java.util.HashMap)2 Form (javax.ws.rs.core.Form)2