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