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