https://issues.shibboleth.net/jira/browse/SSPCPP-187
[shibboleth/cpp-opensaml.git] / saml / saml1 / binding / impl / SAML1SOAPEncoder.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  * SAML1SOAPEncoder.cpp
19  * 
20  * SAML 1.x 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 "saml1/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::saml1p;
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 saml1p {              
46         class SAML_DLLLOCAL SAML1SOAPEncoder : public MessageEncoder
47         {
48         public:
49             SAML1SOAPEncoder() {}
50             virtual ~SAML1SOAPEncoder() {}
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 SAML1SOAPEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
70         {
71             return new SAML1SOAPEncoder();
72         }
73     };
74 };
75
76 long SAML1SOAPEncoder::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.SAML1SOAP");
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 Response.
109     Response* response = dynamic_cast<Response*>(xmlObject);
110     if (response) {
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(response);
117         xmlObject = env;
118     }
119
120     // Now check for a full Envelope (which might have just been created).
121     Envelope* env = dynamic_cast<Envelope*>(xmlObject);
122     if (env) {
123         if (!response) {
124             response = (env->getBody() && env->getBody()->hasChildren()) ?
125                 dynamic_cast<Response*>(env->getBody()->getUnknownXMLObjects().front()) : NULL;
126         }
127         try {
128             // Now check for signing requirements.
129             if (response && credential) {
130                 if (response->getSignature()) {
131                     log.debug("response already signed, skipping signature operation");
132                     rootElement = env->marshall();
133                 }
134                 else {
135                     log.debug("signing the response and marshalling the envelope");
136         
137                     // Build a Signature.
138                     Signature* sig = SignatureBuilder::buildSignature();
139                     response->setSignature(sig);    
140                     if (signatureAlg)
141                         sig->setSignatureAlgorithm(signatureAlg);
142                     if (digestAlg) {
143                         opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
144                         if (cr)
145                             cr->setDigestAlgorithm(digestAlg);
146                     }
147             
148                     // Sign message while marshalling.
149                     vector<Signature*> sigs(1,sig);
150                     rootElement = env->marshall((DOMDocument*)NULL,&sigs,credential);
151                 }
152             }
153             else {
154                 log.debug("marshalling the envelope");
155                 rootElement = env->marshall();
156             }
157
158             stringstream s;
159             s << *rootElement;
160             
161             if (log.isDebugEnabled())
162                 log.debug("marshalled envelope:\n%s", s.str().c_str());
163             
164             log.debug("sending serialized envelope");
165             bool error = (!response && env->getBody() && env->getBody()->hasChildren() &&
166                 dynamic_cast<Fault*>(env->getBody()->getUnknownXMLObjects().front()));
167             long ret = error ? genericResponse.sendError(s) : genericResponse.sendResponse(s);
168         
169             // Cleanup by destroying XML.
170             delete env;
171             return ret;
172         }
173         catch (XMLToolingException&) {
174             if (response && detachOnFailure) {
175                 // A bit weird...we have to "revert" things so that the response is isolated
176                 // so the caller can free it.
177                 if (response->getParent()) {
178                     response->getParent()->detach();
179                     response->detach();
180                 }
181             }
182             throw;
183         }
184     }
185
186     Fault* fault = dynamic_cast<Fault*>(xmlObject);
187     if (fault) {
188         try {
189             log.debug("building envelope and marshalling fault");
190             Envelope* env = EnvelopeBuilder::buildEnvelope();
191             Body* body = BodyBuilder::buildBody();
192             env->setBody(body);
193             body->getUnknownXMLObjects().push_back(fault);
194             rootElement = env->marshall();
195
196             stringstream s;
197             s << *rootElement;
198             
199             if (log.isDebugEnabled())
200                 log.debug("marshalled envelope:\n%s", s.str().c_str());
201             
202             log.debug("sending serialized envelope");
203             long ret = genericResponse.sendError(s);
204         
205             // Cleanup by destroying XML.
206             delete env;
207             return ret;
208         }
209         catch (XMLToolingException&) {
210             // A bit weird...we have to "revert" things so that the fault is isolated
211             // so the caller can free it.
212             if (fault->getParent()) {
213                 fault->getParent()->detach();
214                 fault->detach();
215             }
216             throw;
217         }
218     }
219     
220     throw BindingException("XML content for SAML 1.x SOAP Encoder must be a SAML 1.x <Response> or SOAP Fault/Envelope.");
221 }