Search in sources :

Example 31 with Fault

use of org.apache.cxf.interceptor.Fault 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, StandardCharsets.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(IDP_SERVER_FAILURE_MSG));
                    }
                    List<IDPEntry> idpEntrys = idpList.getIDPEntrys();
                    if (idpEntrys == null || idpEntrys.size() == 0) {
                        throw new Fault(new AccessDeniedException(IDP_SERVER_FAILURE_MSG));
                    }
                    // 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(IDP_SERVER_FAILURE_MSG));
        }
        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, StandardCharsets.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());
        XMLObject 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);
            Map<String, List<String>> headers = new HashMap<>();
            message.put(Message.PROTOCOL_HEADERS, headers);
            httpResponse.headers.forEach((entry) -> headers.put(entry.getKey(), // CXF Expects pairs of <String, List<String>>
            entry.getValue() instanceof List ? ((List<Object>) entry.getValue()).stream().map(String::valueOf).collect(Collectors.toList()) : Lists.newArrayList(String.valueOf(entry.getValue()))));
        } 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) HashMap(java.util.HashMap) InputStream(java.io.InputStream) SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) Element(org.w3c.dom.Element) AuthnRequest(org.opensaml.saml.saml2.core.AuthnRequest) Request(org.opensaml.saml.saml2.ecp.Request) HttpRequest(com.google.api.client.http.HttpRequest) IDPList(org.opensaml.saml.saml2.core.IDPList) XMLObject(org.opensaml.core.xml.XMLObject) Fault(org.apache.cxf.interceptor.Fault) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) IOException(java.io.IOException) 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) XMLObject(org.opensaml.core.xml.XMLObject) IDPEntry(org.opensaml.saml.saml2.core.IDPEntry)

Example 32 with Fault

use of org.apache.cxf.interceptor.Fault in project ddf by codice.

the class BodyWriter method doWriteBody.

void doWriteBody(Message outMessage, Object body, Type bodyType) throws Fault {
    try {
        Type paramType = body.getClass();
        if (bodyType != null) {
            paramType = bodyType;
        }
        writeBody(body, outMessage, body.getClass(), paramType);
    } catch (Exception ex) {
        throw new Fault(ex);
    }
}
Also used : MediaType(javax.ws.rs.core.MediaType) Type(java.lang.reflect.Type) Fault(org.apache.cxf.interceptor.Fault)

Example 33 with Fault

use of org.apache.cxf.interceptor.Fault in project cxf by apache.

the class SoapHeaderInterceptor method handleMessage.

public void handleMessage(Message m) throws Fault {
    SoapMessage message = (SoapMessage) m;
    SoapVersion soapVersion = message.getVersion();
    Exchange exchange = message.getExchange();
    MessageContentsList parameters = MessageContentsList.getContentsList(message);
    if (null == parameters) {
        parameters = new MessageContentsList();
    }
    BindingOperationInfo bop = exchange.getBindingOperationInfo();
    if (null == bop) {
        return;
    }
    if (bop.isUnwrapped()) {
        bop = bop.getWrappedOperation();
    }
    boolean client = isRequestor(message);
    BindingMessageInfo bmi = client ? bop.getOutput() : bop.getInput();
    if (bmi == null) {
        // one way operation.
        return;
    }
    List<SoapHeaderInfo> headers = bmi.getExtensors(SoapHeaderInfo.class);
    if (headers == null || headers.isEmpty()) {
        return;
    }
    boolean supportsNode = this.supportsDataReader(message, Node.class);
    Service service = ServiceModelUtil.getService(message.getExchange());
    Schema schema = null;
    final boolean schemaValidationEnabled = ServiceUtils.isSchemaValidationEnabled(SchemaValidationType.IN, message);
    if (schemaValidationEnabled) {
        schema = EndpointReferenceUtils.getSchema(service.getServiceInfos().get(0), message.getExchange().getBus());
    }
    for (SoapHeaderInfo header : headers) {
        MessagePartInfo mpi = header.getPart();
        try {
            if (schemaValidationEnabled && schema != null) {
                validateHeader(message, mpi, schema);
            }
        } catch (Fault f) {
            if (!isRequestor(message)) {
                f.setFaultCode(Fault.FAULT_CODE_CLIENT);
            }
            throw f;
        }
        if (mpi.getTypeClass() != null) {
            Header param = findHeader(message, mpi);
            Object object = null;
            if (param != null) {
                message.getHeaders().remove(param);
                if (param.getDataBinding() == null) {
                    Node source = (Node) param.getObject();
                    if (source instanceof Element) {
                        // need to remove these attributes as they
                        // would cause validation failures
                        Element el = (Element) source;
                        el.removeAttributeNS(soapVersion.getNamespace(), soapVersion.getAttrNameMustUnderstand());
                        el.removeAttributeNS(soapVersion.getNamespace(), soapVersion.getAttrNameRole());
                    }
                    if (supportsNode) {
                        object = getNodeDataReader(message).read(mpi, source);
                    } else {
                        W3CDOMStreamReader reader = new W3CDOMStreamReader((Element) source);
                        try {
                            // advance into the first tag
                            reader.nextTag();
                        } catch (XMLStreamException e) {
                        // ignore
                        }
                        object = getDataReader(message, XMLStreamReader.class).read(mpi, reader);
                    }
                } else {
                    object = param.getObject();
                }
            }
            parameters.put(mpi, object);
        }
    }
    if (!parameters.isEmpty()) {
        message.setContent(List.class, parameters);
    }
}
Also used : BindingOperationInfo(org.apache.cxf.service.model.BindingOperationInfo) MessageContentsList(org.apache.cxf.message.MessageContentsList) SoapHeaderInfo(org.apache.cxf.binding.soap.model.SoapHeaderInfo) Schema(javax.xml.validation.Schema) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) Service(org.apache.cxf.service.Service) Fault(org.apache.cxf.interceptor.Fault) MessagePartInfo(org.apache.cxf.service.model.MessagePartInfo) SoapMessage(org.apache.cxf.binding.soap.SoapMessage) SoapVersion(org.apache.cxf.binding.soap.SoapVersion) Exchange(org.apache.cxf.message.Exchange) BindingMessageInfo(org.apache.cxf.service.model.BindingMessageInfo) Header(org.apache.cxf.headers.Header) XMLStreamException(javax.xml.stream.XMLStreamException) W3CDOMStreamReader(org.apache.cxf.staxutils.W3CDOMStreamReader)

Example 34 with Fault

use of org.apache.cxf.interceptor.Fault in project cxf by apache.

the class SoapFaultSerializerTest method testFaultToSoapFault.

@Test
public void testFaultToSoapFault() throws Exception {
    Exception ex = new Exception();
    Fault fault = new Fault(ex, Fault.FAULT_CODE_CLIENT);
    verifyFaultToSoapFault(fault, null, true, Soap11.getInstance());
    verifyFaultToSoapFault(fault, null, true, Soap12.getInstance());
    fault = new Fault(ex, Fault.FAULT_CODE_SERVER);
    verifyFaultToSoapFault(fault, null, false, Soap11.getInstance());
    verifyFaultToSoapFault(fault, null, false, Soap12.getInstance());
    fault.setMessage("fault-one");
    verifyFaultToSoapFault(fault, "fault-one", false, Soap11.getInstance());
    ex = new Exception("fault-two");
    fault = new Fault(ex, Fault.FAULT_CODE_CLIENT);
    verifyFaultToSoapFault(fault, "fault-two", true, Soap11.getInstance());
    fault = new Fault(ex, new QName("http://cxf.apache.org", "myFaultCode"));
    SoapFault f = verifyFaultToSoapFault(fault, "fault-two", false, Soap12.getInstance());
    assertEquals("myFaultCode", f.getSubCodes().get(0).getLocalPart());
}
Also used : SoapFault(org.apache.cxf.binding.soap.SoapFault) QName(javax.xml.namespace.QName) Fault(org.apache.cxf.interceptor.Fault) SOAPFault(javax.xml.soap.SOAPFault) SoapFault(org.apache.cxf.binding.soap.SoapFault) Test(org.junit.Test)

Example 35 with Fault

use of org.apache.cxf.interceptor.Fault in project cxf by apache.

the class SAAJInInterceptor method handleMessage.

@SuppressWarnings("unchecked")
public void handleMessage(SoapMessage message) throws Fault {
    if (isGET(message)) {
        return;
    }
    Boolean bodySet = (Boolean) message.get(BODY_FILLED_IN);
    if (Boolean.TRUE.equals(bodySet)) {
        return;
    }
    message.put(BODY_FILLED_IN, Boolean.TRUE);
    try {
        SOAPMessage soapMessage = message.getContent(SOAPMessage.class);
        if (soapMessage == null) {
            MessageFactory factory = preInterceptor.getFactory(message);
            soapMessage = factory.createMessage();
            message.setContent(SOAPMessage.class, soapMessage);
        }
        XMLStreamReader xmlReader = message.getContent(XMLStreamReader.class);
        if (xmlReader == null) {
            return;
        }
        final SOAPPart part = soapMessage.getSOAPPart();
        Document node = (Document) message.getContent(Node.class);
        if (node != part && node != null) {
            StaxUtils.copy(node, new SAAJStreamWriter(part));
        } else {
            SOAPEnvelope env = soapMessage.getSOAPPart().getEnvelope();
            if (node == null) {
                adjustPrefixes(env, (String) message.get(ReadHeadersInterceptor.ENVELOPE_PREFIX), (String) message.get(ReadHeadersInterceptor.BODY_PREFIX));
            }
            List<XMLEvent> events = (List<XMLEvent>) message.get(ReadHeadersInterceptor.ENVELOPE_EVENTS);
            applyEvents(events, env);
            SOAPBody body = soapMessage.getSOAPBody();
            events = (List<XMLEvent>) message.get(ReadHeadersInterceptor.BODY_EVENTS);
            applyEvents(events, body);
        }
        message.setContent(Node.class, soapMessage.getSOAPPart());
        Collection<Attachment> atts = message.getAttachments();
        if (atts != null) {
            for (Attachment a : atts) {
                if (a.getDataHandler().getDataSource() instanceof AttachmentDataSource) {
                    try {
                        ((AttachmentDataSource) a.getDataHandler().getDataSource()).cache(message);
                    } catch (IOException e) {
                        throw new Fault(e);
                    }
                }
                AttachmentPart ap = soapMessage.createAttachmentPart(a.getDataHandler());
                Iterator<String> i = a.getHeaderNames();
                while (i != null && i.hasNext()) {
                    String h = i.next();
                    String val = a.getHeader(h);
                    ap.addMimeHeader(h, val);
                }
                if (StringUtils.isEmpty(ap.getContentId())) {
                    ap.setContentId(a.getId());
                }
                soapMessage.addAttachmentPart(ap);
            }
        }
        // replace header element if necessary
        if (message.hasHeaders()) {
            replaceHeaders(soapMessage, message);
        }
        if (soapMessage.getSOAPPart().getEnvelope().getHeader() == null) {
            soapMessage.getSOAPPart().getEnvelope().addHeader();
        }
        // If we have an xmlReader that already is counting the attributes and such
        // then we don't want to rely on the system level defaults in StaxUtils.copy
        // CXF-6173
        boolean secureReader = StaxUtils.isSecureReader(xmlReader, message);
        StaxUtils.copy(xmlReader, new SAAJStreamWriter(soapMessage.getSOAPPart(), soapMessage.getSOAPPart().getEnvelope().getBody()), true, !secureReader);
        DOMSource bodySource = new DOMSource(soapMessage.getSOAPPart().getEnvelope().getBody());
        xmlReader = StaxUtils.createXMLStreamReader(bodySource);
        xmlReader.nextTag();
        // move past body tag
        xmlReader.nextTag();
        message.setContent(XMLStreamReader.class, xmlReader);
    } catch (SOAPException soape) {
        throw new SoapFault(new org.apache.cxf.common.i18n.Message("SOAPHANDLERINTERCEPTOR_EXCEPTION", BUNDLE), soape, message.getVersion().getSender());
    } catch (XMLStreamException e) {
        throw new SoapFault(new org.apache.cxf.common.i18n.Message("SOAPHANDLERINTERCEPTOR_EXCEPTION", BUNDLE), e, message.getVersion().getSender());
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) SoapFault(org.apache.cxf.binding.soap.SoapFault) XMLStreamReader(javax.xml.stream.XMLStreamReader) SoapMessage(org.apache.cxf.binding.soap.SoapMessage) Message(org.apache.cxf.message.Message) SOAPMessage(javax.xml.soap.SOAPMessage) Node(org.w3c.dom.Node) AttachmentDataSource(org.apache.cxf.attachment.AttachmentDataSource) Attachment(org.apache.cxf.message.Attachment) SoapFault(org.apache.cxf.binding.soap.SoapFault) Fault(org.apache.cxf.interceptor.Fault) SOAPEnvelope(javax.xml.soap.SOAPEnvelope) Document(org.w3c.dom.Document) SOAPMessage(javax.xml.soap.SOAPMessage) SOAPException(javax.xml.soap.SOAPException) SOAPPart(javax.xml.soap.SOAPPart) List(java.util.List) ArrayList(java.util.ArrayList) MessageFactory(javax.xml.soap.MessageFactory) AttachmentPart(javax.xml.soap.AttachmentPart) IOException(java.io.IOException) SOAPBody(javax.xml.soap.SOAPBody) XMLStreamException(javax.xml.stream.XMLStreamException) XMLEvent(javax.xml.stream.events.XMLEvent)

Aggregations

Fault (org.apache.cxf.interceptor.Fault)283 IOException (java.io.IOException)74 QName (javax.xml.namespace.QName)56 Message (org.apache.cxf.message.Message)52 XMLStreamException (javax.xml.stream.XMLStreamException)50 Element (org.w3c.dom.Element)42 Message (org.apache.cxf.common.i18n.Message)34 Exchange (org.apache.cxf.message.Exchange)30 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)30 SOAPException (javax.xml.soap.SOAPException)28 InputStream (java.io.InputStream)27 ArrayList (java.util.ArrayList)27 XMLStreamReader (javax.xml.stream.XMLStreamReader)26 XMLStreamWriter (javax.xml.stream.XMLStreamWriter)26 BindingOperationInfo (org.apache.cxf.service.model.BindingOperationInfo)25 Test (org.junit.Test)24 SecurityToken (org.apache.cxf.ws.security.tokenstore.SecurityToken)23 List (java.util.List)21 SOAPMessage (javax.xml.soap.SOAPMessage)21 MessagePartInfo (org.apache.cxf.service.model.MessagePartInfo)21