https://issues.shibboleth.net/jira/browse/SSPCPP-187
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2SOAPEncoder.cpp
1 /*
2  *  Copyright 2001-2007 Internet2
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 /**
18  * SAML2SOAPEncoder.cpp
19  * 
20  * SAML 2.0 SOAP binding message encoder
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "binding/MessageEncoder.h"
26 #include "signature/ContentReference.h"
27 #include "saml2/core/Protocols.h"
28
29 #include <sstream>
30 #include <xmltooling/logging.h>
31 #include <xmltooling/io/HTTPResponse.h>
32 #include <xmltooling/util/NDC.h>
33 #include <xmltooling/soap/SOAP.h>
34
35 using namespace opensaml::saml2p;
36 using namespace opensaml::saml2md;
37 using namespace opensaml;
38 using namespace xmlsignature;
39 using namespace soap11;
40 using namespace xmltooling::logging;
41 using namespace xmltooling;
42 using namespace std;
43
44 namespace opensaml {
45     namespace saml2p {              
46         class SAML_DLLLOCAL SAML2SOAPEncoder : public MessageEncoder
47         {
48         public:
49             SAML2SOAPEncoder() {}
50             virtual ~SAML2SOAPEncoder() {}
51
52             bool isUserAgentPresent() const {
53                 return false;
54             }
55
56             long encode(
57                 GenericResponse& genericResponse,
58                 XMLObject* xmlObject,
59                 const char* destination,
60                 const EntityDescriptor* recipient=NULL,
61                 const char* relayState=NULL,
62                 const ArtifactGenerator* artifactGenerator=NULL,
63                 const Credential* credential=NULL,
64                 const XMLCh* signatureAlg=NULL,
65                 const XMLCh* digestAlg=NULL
66                 ) const;
67         };
68
69         MessageEncoder* SAML_DLLLOCAL SAML2SOAPEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
70         {
71             return new SAML2SOAPEncoder();
72         }
73     };
74 };
75
76 long SAML2SOAPEncoder::encode(
77     GenericResponse& genericResponse,
78     XMLObject* xmlObject,
79     const char* destination,
80     const EntityDescriptor* recipient,
81     const char* relayState,
82     const ArtifactGenerator* artifactGenerator,
83     const Credential* credential,
84     const XMLCh* signatureAlg,
85     const XMLCh* digestAlg
86     ) const
87 {
88 #ifdef _DEBUG
89     xmltooling::NDC ndc("encode");
90 #endif
91     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2SOAP");
92
93     log.debug("validating input");
94     if (xmlObject->getParent())
95         throw BindingException("Cannot encode XML content with parent.");
96
97     genericResponse.setContentType("text/xml");
98     HTTPResponse* httpResponse = dynamic_cast<HTTPResponse*>(&genericResponse);
99     if (httpResponse) {
100         httpResponse->setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
101         httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
102         httpResponse->setResponseHeader("Pragma", "no-cache");
103     }
104
105     bool detachOnFailure = false;
106     DOMElement* rootElement = NULL;
107
108     // Check for a naked message.
109     SignableObject* msg = dynamic_cast<SignableObject*>(xmlObject);
110     if (msg) {
111         // Wrap it in a SOAP envelope and point xmlObject at that.
112         detachOnFailure = true;
113         Envelope* env = EnvelopeBuilder::buildEnvelope();
114         Body* body = BodyBuilder::buildBody();
115         env->setBody(body);
116         body->getUnknownXMLObjects().push_back(msg);
117         xmlObject = env;
118     }
119
120     Envelope* env = dynamic_cast<Envelope*>(xmlObject);
121     if (env) {
122         if (!msg) {
123             msg = (env->getBody() && env->getBody()->hasChildren()) ?
124                 dynamic_cast<SignableObject*>(env->getBody()->getUnknownXMLObjects().front()) : NULL;
125         }
126         try {
127             if (msg && credential) {
128                 if (msg->getSignature()) {
129                     log.debug("message already signed, skipping signature operation");
130                     rootElement = env->marshall();
131                 }
132                 else {
133                     log.debug("signing the message and marshalling the envelope");
134         
135                     // Build a Signature.
136                     Signature* sig = SignatureBuilder::buildSignature();
137                     msg->setSignature(sig);    
138                     if (signatureAlg)
139                         sig->setSignatureAlgorithm(signatureAlg);
140                     if (digestAlg) {
141                         opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
142                         if (cr)
143                             cr->setDigestAlgorithm(digestAlg);
144                     }
145             
146                     // Sign message while marshalling.
147                     vector<Signature*> sigs(1,sig);
148                     rootElement = env->marshall((DOMDocument*)NULL,&sigs,credential);
149                 }
150             }
151             else {
152                 log.debug("marshalling the envelope");
153                 rootElement = env->marshall();
154             }
155
156             stringstream s;
157             s << *rootElement;
158             
159             if (log.isDebugEnabled())
160                 log.debug("marshalled envelope:\n%s", s.str().c_str());
161
162             log.debug("sending serialized envelope");
163             bool error = (!msg && env->getBody() && env->getBody()->hasChildren() &&
164                 dynamic_cast<Fault*>(env->getBody()->getUnknownXMLObjects().front()));
165             long ret = error ? genericResponse.sendError(s) : genericResponse.sendResponse(s);
166         
167             // Cleanup by destroying XML.
168             delete env;
169             return ret;
170         }
171         catch (XMLToolingException&) {
172             if (msg && detachOnFailure) {
173                 // A bit weird...we have to "revert" things so that the message is isolated
174                 // so the caller can free it.
175                 if (msg->getParent()) {
176                     msg->getParent()->detach();
177                     msg->detach();
178                 }
179             }
180             throw;
181         }
182     }
183
184     Fault* fault = dynamic_cast<Fault*>(xmlObject);
185     if (fault) {
186         try {
187             log.debug("building envelope and marshalling fault");
188             Envelope* env = EnvelopeBuilder::buildEnvelope();
189             Body* body = BodyBuilder::buildBody();
190             env->setBody(body);
191             body->getUnknownXMLObjects().push_back(fault);
192             rootElement = env->marshall();
193     
194             stringstream s;
195             s << *rootElement;
196             
197             if (log.isDebugEnabled())
198                 log.debug("marshalled envelope:\n%s", s.str().c_str());
199
200             log.debug("sending serialized envelope");
201             long ret = genericResponse.sendError(s);
202         
203             // Cleanup by destroying XML.
204             delete env;
205             return ret;
206         }
207         catch (XMLToolingException&) {
208             // A bit weird...we have to "revert" things so that the fault is isolated
209             // so the caller can free it.
210             if (fault->getParent()) {
211                 fault->getParent()->detach();
212                 fault->detach();
213             }
214             throw;
215         }
216     }
217
218     throw BindingException("XML content for SAML 2.0 SOAP Encoder must be a SAML 2.0 message or SOAP Fault/Envelope.");
219 }