Reducing header overuse, non-inlining selected methods (CPPOST-35).
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2ArtifactEncoder.cpp
1 /*
2  *  Copyright 2001-2009 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  * SAML2ArtifactEncoder.cpp
19  * 
20  * SAML 2.0 HTTP-Artifact binding message encoder
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "binding/ArtifactMap.h"
26 #include "binding/MessageEncoder.h"
27 #include "saml2/binding/SAML2Artifact.h"
28 #include "saml2/core/Protocols.h"
29 #include "saml2/metadata/Metadata.h"
30
31 #include <fstream>
32 #include <sstream>
33 #include <xmltooling/logging.h>
34 #include <xmltooling/XMLToolingConfig.h>
35 #include <xmltooling/io/HTTPResponse.h>
36 #include <xmltooling/util/NDC.h>
37 #include <xmltooling/util/PathResolver.h>
38 #include <xmltooling/util/TemplateEngine.h>
39 #include <xmltooling/util/URLEncoder.h>
40
41 using namespace opensaml::saml2p;
42 using namespace opensaml::saml2md;
43 using namespace opensaml;
44 using namespace xmlsignature;
45 using namespace xmltooling::logging;
46 using namespace xmltooling;
47 using namespace std;
48
49 namespace opensaml {
50     namespace saml2p {              
51         class SAML_DLLLOCAL SAML2ArtifactEncoder : public MessageEncoder
52         {
53         public:
54             SAML2ArtifactEncoder(const DOMElement* e, const XMLCh* ns);
55             virtual ~SAML2ArtifactEncoder() {}
56             
57             long encode(
58                 GenericResponse& genericResponse,
59                 XMLObject* xmlObject,
60                 const char* destination,
61                 const EntityDescriptor* recipient=NULL,
62                 const char* relayState=NULL,
63                 const ArtifactGenerator* artifactGenerator=NULL,
64                 const Credential* credential=NULL,
65                 const XMLCh* signatureAlg=NULL,
66                 const XMLCh* digestAlg=NULL
67                 ) const;
68         
69         private:
70             bool m_post;
71             string m_template;
72         };
73
74         MessageEncoder* SAML_DLLLOCAL SAML2ArtifactEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
75         {
76             return new SAML2ArtifactEncoder(p.first, p.second);
77         }
78     };
79
80     static const XMLCh _template[] =    UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
81     static const XMLCh postArtifact[] = UNICODE_LITERAL_12(p,o,s,t,A,r,t,i,f,a,c,t);
82 };
83
84 SAML2ArtifactEncoder::SAML2ArtifactEncoder(const DOMElement* e, const XMLCh* ns) : m_post(false)
85 {
86     if (e) {
87         const XMLCh* flag = e->getAttributeNS(ns, postArtifact);
88         m_post = (flag && (*flag==chLatin_t || *flag==chDigit_1));
89         if (m_post) {
90             auto_ptr_char t(e->getAttributeNS(ns, _template));
91             if (t.get() && *t.get()) {
92                 m_template = t.get();
93                 XMLToolingConfig::getConfig().getPathResolver()->resolve(m_template, PathResolver::XMLTOOLING_CFG_FILE);
94             }
95         }
96     }
97 }
98
99 long SAML2ArtifactEncoder::encode(
100     GenericResponse& genericResponse,
101     XMLObject* xmlObject,
102     const char* destination,
103     const EntityDescriptor* recipient,
104     const char* relayState,
105     const ArtifactGenerator* artifactGenerator,
106     const Credential* credential,
107     const XMLCh* signatureAlg,
108     const XMLCh* digestAlg
109     ) const
110 {
111 #ifdef _DEBUG
112     xmltooling::NDC ndc("encode");
113 #endif
114     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2Artifact");
115
116     log.debug("validating input");
117     HTTPResponse* httpResponse=dynamic_cast<HTTPResponse*>(&genericResponse);
118     if (!httpResponse)
119         throw BindingException("Unable to cast response interface to HTTPResponse type.");
120     if (relayState && strlen(relayState)>80)
121         throw BindingException("RelayState cannot exceed 80 bytes in length.");
122     
123     if (xmlObject->getParent())
124         throw BindingException("Cannot encode XML content with parent.");
125
126     StatusResponseType* response = NULL;
127     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
128     if (!request) {
129         response = dynamic_cast<StatusResponseType*>(xmlObject);
130         if (!response)
131             throw BindingException("XML content for SAML 2.0 HTTP-Artifact Encoder must be a SAML 2.0 protocol message.");
132     }
133     
134     ArtifactMap* mapper = SAMLConfig::getConfig().getArtifactMap();
135     if (!mapper)
136         throw BindingException("SAML 2.0 HTTP-Artifact Encoder requires ArtifactMap be set in configuration.");
137
138     // Obtain a fresh artifact.
139     if (!artifactGenerator)
140         throw BindingException("SAML 2.0 HTTP-Artifact Encoder requires an ArtifactGenerator instance.");
141     auto_ptr_char recipientID(recipient ? recipient->getEntityID() : NULL);
142     log.debug("obtaining new artifact for relying party (%s)", recipientID.get() ? recipientID.get() : "unknown");
143     auto_ptr<SAMLArtifact> artifact(artifactGenerator->generateSAML2Artifact(recipient));
144
145     if (credential) {
146         // Signature based on native XML signing.
147         if (request ? request->getSignature() : response->getSignature()) {
148             log.debug("message already signed, skipping signature operation");
149         }
150         else {
151             log.debug("signing the message");
152
153             // Build a Signature.
154             Signature* sig = SignatureBuilder::buildSignature();
155             request ? request->setSignature(sig) : response->setSignature(sig);    
156             if (signatureAlg)
157                 sig->setSignatureAlgorithm(signatureAlg);
158             if (digestAlg) {
159                 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
160                 if (cr)
161                     cr->setDigestAlgorithm(digestAlg);
162             }
163             
164             // Sign response while marshalling.
165             vector<Signature*> sigs(1,sig);
166             xmlObject->marshall((DOMDocument*)NULL,&sigs,credential);
167         }
168     }
169
170     if (log.isDebugEnabled())
171         log.debugStream() << "marshalled message:" << logging::eol << *xmlObject << logging::eol;
172     
173     // Store the message. Last step in storage will be to delete the XML.
174     log.debug("storing artifact and content in map");
175     mapper->storeContent(xmlObject, artifact.get(), recipientID.get());
176
177     if (m_template.empty()) {
178         // Generate redirect.
179         string loc = destination;
180         loc += (strchr(destination,'?') ? '&' : '?');
181         const URLEncoder* escaper = XMLToolingConfig::getConfig().getURLEncoder();
182         loc = loc + "SAMLart=" + escaper->encode(artifact->encode().c_str());
183         if (relayState && *relayState)
184             loc = loc + "&RelayState=" + escaper->encode(relayState);
185         log.debug("message encoded, sending redirect to client");
186         return httpResponse->sendRedirect(loc.c_str());
187     }
188     else {
189         // Push message into template and send result to client. 
190         log.debug("message encoded, sending HTML form template to client");
191         TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
192         if (!engine)
193             throw BindingException("Encoding artifact using POST requires a TemplateEngine instance.");
194         ifstream infile(m_template.c_str());
195         if (!infile)
196             throw BindingException("Failed to open HTML template for POST response ($1).", params(1,m_template.c_str()));
197         TemplateEngine::TemplateParameters params;
198         params.m_map["action"] = destination;
199         params.m_map["SAMLart"] = artifact->encode();
200         if (relayState && *relayState)
201             params.m_map["RelayState"] = relayState;
202         stringstream s;
203         engine->run(infile, s, params);
204         httpResponse->setContentType("text/html");
205         httpResponse->setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
206         httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
207         httpResponse->setResponseHeader("Pragma", "no-cache");
208         return httpResponse->sendResponse(s);
209     }
210 }