Search in sources :

Example 16 with HttpResponse

use of com.google.api.client.http.HttpResponse in project ddf by codice.

the class PaosInInterceptor method handleMessage.

@Override
public void handleMessage(Message message) throws Fault {
    List authHeader = (List) ((Map) message.getExchange().getOutMessage().get(Message.PROTOCOL_HEADERS)).get("Authorization");
    String authorization = null;
    if (authHeader != null && authHeader.size() > 0) {
        authorization = (String) authHeader.get(0);
    }
    InputStream content = message.getContent(InputStream.class);
    String contentType = (String) message.get(Message.CONTENT_TYPE);
    if (contentType == null || !contentType.contains(APPLICATION_VND_PAOS_XML)) {
        return;
    }
    try {
        SOAPPart soapMessage = SamlProtocol.parseSoapMessage(IOUtils.toString(content, Charset.forName("UTF-8")));
        Iterator iterator = soapMessage.getEnvelope().getHeader().examineAllHeaderElements();
        IDPEntry idpEntry = null;
        String relayState = "";
        String responseConsumerURL = "";
        String messageId = "";
        while (iterator.hasNext()) {
            Element soapHeaderElement = (SOAPHeaderElement) iterator.next();
            if (RELAY_STATE.equals(soapHeaderElement.getLocalName())) {
                relayState = DOM2Writer.nodeToString(soapHeaderElement);
            } else if (REQUEST.equals(soapHeaderElement.getLocalName()) && soapHeaderElement.getNamespaceURI().equals(URN_OASIS_NAMES_TC_SAML_2_0_PROFILES_SSO_ECP)) {
                try {
                    soapHeaderElement = SamlProtocol.convertDomImplementation(soapHeaderElement);
                    Request ecpRequest = (Request) OpenSAMLUtil.fromDom(soapHeaderElement);
                    IDPList idpList = ecpRequest.getIDPList();
                    if (idpList == null) {
                        throw new Fault(new AccessDeniedException("Unable to complete SAML ECP connection. Unable to determine IdP server."));
                    }
                    List<IDPEntry> idpEntrys = idpList.getIDPEntrys();
                    if (idpEntrys == null || idpEntrys.size() == 0) {
                        throw new Fault(new AccessDeniedException("Unable to complete SAML ECP connection. Unable to determine IdP server."));
                    }
                    //choose the right entry, probably need to do something better than select the first one
                    //but the spec doesn't specify how this is supposed to be done
                    idpEntry = idpEntrys.get(0);
                } catch (WSSecurityException e) {
                    //TODO figure out IdP alternatively
                    LOGGER.info("Unable to determine IdP appropriately. ECP connection will fail. SP may be incorrectly configured. Contact the administrator for the remote system.");
                }
            } else if (REQUEST.equals(soapHeaderElement.getLocalName()) && soapHeaderElement.getNamespaceURI().equals(URN_LIBERTY_PAOS_2003_08)) {
                responseConsumerURL = soapHeaderElement.getAttribute(RESPONSE_CONSUMER_URL);
                messageId = soapHeaderElement.getAttribute(MESSAGE_ID);
            }
        }
        if (idpEntry == null) {
            throw new Fault(new AccessDeniedException("Unable to complete SAML ECP connection. Unable to determine IdP server."));
        }
        String token = createToken(authorization);
        checkAuthnRequest(soapMessage);
        Element authnRequestElement = SamlProtocol.getDomElement(soapMessage.getEnvelope().getBody().getFirstChild());
        String loc = idpEntry.getLoc();
        String soapRequest = buildSoapMessage(token, relayState, authnRequestElement, null);
        HttpResponseWrapper httpResponse = getHttpResponse(loc, soapRequest, null);
        InputStream httpResponseContent = httpResponse.content;
        SOAPPart idpSoapResponse = SamlProtocol.parseSoapMessage(IOUtils.toString(httpResponseContent, Charset.forName("UTF-8")));
        Iterator responseHeaderElements = idpSoapResponse.getEnvelope().getHeader().examineAllHeaderElements();
        String newRelayState = "";
        while (responseHeaderElements.hasNext()) {
            SOAPHeaderElement soapHeaderElement = (SOAPHeaderElement) responseHeaderElements.next();
            if (RESPONSE.equals(soapHeaderElement.getLocalName())) {
                String assertionConsumerServiceURL = soapHeaderElement.getAttribute(ASSERTION_CONSUMER_SERVICE_URL);
                if (!responseConsumerURL.equals(assertionConsumerServiceURL)) {
                    String soapFault = buildSoapFault(ECP_RESPONSE, "The responseConsumerURL does not match the assertionConsumerServiceURL.");
                    httpResponse = getHttpResponse(responseConsumerURL, soapFault, null);
                    message.setContent(InputStream.class, httpResponse.content);
                    return;
                }
            } else if (RELAY_STATE.equals(soapHeaderElement.getLocalName())) {
                newRelayState = DOM2Writer.nodeToString(soapHeaderElement);
                if (StringUtils.isNotEmpty(relayState) && !relayState.equals(newRelayState)) {
                    LOGGER.debug("RelayState does not match between ECP request and response");
                }
                if (StringUtils.isNotEmpty(relayState)) {
                    newRelayState = relayState;
                }
            }
        }
        checkSamlpResponse(idpSoapResponse);
        Element samlpResponseElement = SamlProtocol.getDomElement(idpSoapResponse.getEnvelope().getBody().getFirstChild());
        Response paosResponse = null;
        if (StringUtils.isNotEmpty(messageId)) {
            paosResponse = getPaosResponse(messageId);
        }
        String soapResponse = buildSoapMessage(null, newRelayState, samlpResponseElement, paosResponse);
        httpResponse = getHttpResponse(responseConsumerURL, soapResponse, message.getExchange().getOutMessage());
        if (httpResponse.statusCode < 400) {
            httpResponseContent = httpResponse.content;
            message.setContent(InputStream.class, httpResponseContent);
        } else {
            throw new Fault(new AccessDeniedException("Unable to complete SAML ECP connection due to an error."));
        }
    } catch (IOException e) {
        LOGGER.debug("Error encountered while performing ECP handshake.", e);
    } catch (XMLStreamException | SOAPException e) {
        throw new Fault(new AccessDeniedException("Unable to complete SAML ECP connection. The server's response was not in the correct format."));
    } catch (WSSecurityException e) {
        throw new Fault(new AccessDeniedException("Unable to complete SAML ECP connection. Unable to send SOAP request messages."));
    }
}
Also used : SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) AccessDeniedException(org.apache.cxf.interceptor.security.AccessDeniedException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) Element(org.w3c.dom.Element) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) HttpRequest(com.google.api.client.http.HttpRequest) Request(org.opensaml.saml.saml2.ecp.Request) IDPList(org.opensaml.saml.saml2.core.IDPList) Fault(org.apache.cxf.interceptor.Fault) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) HttpResponse(com.google.api.client.http.HttpResponse) Response(ddf.security.liberty.paos.Response) XMLStreamException(javax.xml.stream.XMLStreamException) SOAPException(javax.xml.soap.SOAPException) SOAPPart(javax.xml.soap.SOAPPart) Iterator(java.util.Iterator) IDPList(org.opensaml.saml.saml2.core.IDPList) List(java.util.List) IDPEntry(org.opensaml.saml.saml2.core.IDPEntry)

Example 17 with HttpResponse

use of com.google.api.client.http.HttpResponse in project elasticsearch by elastic.

the class GceMetadataService method metadata.

public String metadata(String metadataPath) throws IOException, URISyntaxException {
    // Forcing Google Token API URL as set in GCE SDK to
    //      http://metadata/computeMetadata/v1/instance/service-accounts/default/token
    // See https://developers.google.com/compute/docs/metadata#metadataserver
    final URI urlMetadataNetwork = new URI(GCE_HOST.get(settings)).resolve("/computeMetadata/v1/instance/").resolve(metadataPath);
    logger.debug("get metadata from [{}]", urlMetadataNetwork);
    HttpHeaders headers;
    try {
        // hack around code messiness in GCE code
        // TODO: get this fixed
        headers = Access.doPrivileged(HttpHeaders::new);
        GenericUrl genericUrl = Access.doPrivileged(() -> new GenericUrl(urlMetadataNetwork));
        // This is needed to query meta data: https://cloud.google.com/compute/docs/metadata
        headers.put("Metadata-Flavor", "Google");
        HttpResponse response = Access.doPrivilegedIOException(() -> getGceHttpTransport().createRequestFactory().buildGetRequest(genericUrl).setHeaders(headers).execute());
        String metadata = response.parseAsString();
        logger.debug("metadata found [{}]", metadata);
        return metadata;
    } catch (Exception e) {
        throw new IOException("failed to fetch metadata from [" + urlMetadataNetwork + "]", e);
    }
}
Also used : HttpHeaders(com.google.api.client.http.HttpHeaders) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) IOException(java.io.IOException) URI(java.net.URI) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) GeneralSecurityException(java.security.GeneralSecurityException)

Example 18 with HttpResponse

use of com.google.api.client.http.HttpResponse in project elasticsearch by elastic.

the class RetryHttpInitializerWrapperTests method testSimpleRetry.

public void testSimpleRetry() throws Exception {
    FailThenSuccessBackoffTransport fakeTransport = new FailThenSuccessBackoffTransport(HttpStatusCodes.STATUS_CODE_SERVER_ERROR, 3);
    MockGoogleCredential credential = RetryHttpInitializerWrapper.newMockCredentialBuilder().build();
    MockSleeper mockSleeper = new MockSleeper();
    RetryHttpInitializerWrapper retryHttpInitializerWrapper = new RetryHttpInitializerWrapper(credential, mockSleeper, TimeValue.timeValueSeconds(5));
    Compute client = new Compute.Builder(fakeTransport, new JacksonFactory(), null).setHttpRequestInitializer(retryHttpInitializerWrapper).setApplicationName("test").build();
    HttpRequest request = client.getRequestFactory().buildRequest("Get", new GenericUrl("http://elasticsearch.com"), null);
    HttpResponse response = request.execute();
    assertThat(mockSleeper.getCount(), equalTo(3));
    assertThat(response.getStatusCode(), equalTo(200));
}
Also used : LowLevelHttpRequest(com.google.api.client.http.LowLevelHttpRequest) HttpRequest(com.google.api.client.http.HttpRequest) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) Compute(com.google.api.services.compute.Compute) MockGoogleCredential(com.google.api.client.googleapis.testing.auth.oauth2.MockGoogleCredential) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) HttpResponse(com.google.api.client.http.HttpResponse) LowLevelHttpResponse(com.google.api.client.http.LowLevelHttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) MockSleeper(com.google.api.client.testing.util.MockSleeper)

Example 19 with HttpResponse

use of com.google.api.client.http.HttpResponse in project elasticsearch by elastic.

the class RetryHttpInitializerWrapper method initialize.

@Override
public void initialize(HttpRequest httpRequest) {
    final HttpUnsuccessfulResponseHandler backoffHandler = new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff.Builder().setMaxElapsedTimeMillis(((int) maxWait.getMillis())).build()).setSleeper(sleeper);
    httpRequest.setInterceptor(wrappedCredential);
    httpRequest.setUnsuccessfulResponseHandler(new HttpUnsuccessfulResponseHandler() {

        int retry = 0;

        @Override
        public boolean handleResponse(HttpRequest request, HttpResponse response, boolean supportsRetry) throws IOException {
            if (wrappedCredential.handleResponse(request, response, supportsRetry)) {
                // and no backoff is desired.
                return true;
            } else if (backoffHandler.handleResponse(request, response, supportsRetry)) {
                // Otherwise, we defer to the judgement of
                // our internal backoff handler.
                logger.debug("Retrying [{}] times : [{}]", retry, request.getUrl());
                return true;
            } else {
                return false;
            }
        }
    });
    httpRequest.setIOExceptionHandler(new HttpBackOffIOExceptionHandler(new ExponentialBackOff.Builder().setMaxElapsedTimeMillis(((int) maxWait.getMillis())).build()).setSleeper(sleeper));
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpBackOffIOExceptionHandler(com.google.api.client.http.HttpBackOffIOExceptionHandler) HttpBackOffUnsuccessfulResponseHandler(com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler) HttpUnsuccessfulResponseHandler(com.google.api.client.http.HttpUnsuccessfulResponseHandler) HttpResponse(com.google.api.client.http.HttpResponse) IOException(java.io.IOException) ExponentialBackOff(com.google.api.client.util.ExponentialBackOff)

Example 20 with HttpResponse

use of com.google.api.client.http.HttpResponse in project OpenRefine by OpenRefine.

the class DeAuthorizeCommand method doGet.

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Type", "application/json");
        String sessionToken = TokenCookie.getToken(request);
        if (sessionToken != null) {
            // No method to do this in Google's client lib, so roll our own
            HttpRequestFactory factory = HTTP_TRANSPORT.createRequestFactory();
            GenericUrl url = new GenericUrl("https://accounts.google.com/o/oauth2/revoke?token=" + sessionToken);
            HttpRequest rqst = factory.buildGetRequest(url);
            HttpResponse resp = rqst.execute();
            if (resp.getStatusCode() != 200) {
                respond(response, String.valueOf(resp.getStatusCode()), resp.getStatusMessage());
            }
            TokenCookie.deleteToken(request, response);
        }
        respond(response, "200 OK", "");
    } catch (Exception e) {
        respondException(response, e);
    }
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) HttpRequestFactory(com.google.api.client.http.HttpRequestFactory) HttpResponse(com.google.api.client.http.HttpResponse) GenericUrl(com.google.api.client.http.GenericUrl) ServletException(javax.servlet.ServletException) IOException(java.io.IOException)

Aggregations

HttpResponse (com.google.api.client.http.HttpResponse)33 IOException (java.io.IOException)22 HttpRequest (com.google.api.client.http.HttpRequest)20 GenericUrl (com.google.api.client.http.GenericUrl)19 LowLevelHttpResponse (com.google.api.client.http.LowLevelHttpResponse)11 HttpTransport (com.google.api.client.http.HttpTransport)8 InputStream (java.io.InputStream)8 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)7 Test (org.junit.Test)7 NetHttpTransport (com.google.api.client.http.javanet.NetHttpTransport)6 HttpBackOffIOExceptionHandler (com.google.api.client.http.HttpBackOffIOExceptionHandler)4 HttpBackOffUnsuccessfulResponseHandler (com.google.api.client.http.HttpBackOffUnsuccessfulResponseHandler)4 HttpResponseException (com.google.api.client.http.HttpResponseException)4 HttpUnsuccessfulResponseHandler (com.google.api.client.http.HttpUnsuccessfulResponseHandler)4 LowLevelHttpRequest (com.google.api.client.http.LowLevelHttpRequest)4 JsonFactory (com.google.api.client.json.JsonFactory)4 JacksonFactory (com.google.api.client.json.jackson2.JacksonFactory)4 MockLowLevelHttpRequest (com.google.api.client.testing.http.MockLowLevelHttpRequest)4 MockLowLevelHttpResponse (com.google.api.client.testing.http.MockLowLevelHttpResponse)4 ExponentialBackOff (com.google.api.client.util.ExponentialBackOff)4