Support path resolution in binding templates.
[shibboleth/cpp-opensaml.git] / saml / saml1 / binding / impl / SAML1POSTEncoder.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  * SAML1POSTEncoder.cpp
19  * 
20  * SAML 1.x POST binding/profile 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 <fstream>
30 #include <sstream>
31 #include <xercesc/util/Base64.hpp>
32 #include <xmltooling/logging.h>
33 #include <xmltooling/util/NDC.h>
34 #include <xmltooling/util/PathResolver.h>
35 #include <xmltooling/util/TemplateEngine.h>
36
37 using namespace opensaml::saml1p;
38 using namespace opensaml::saml2md;
39 using namespace opensaml;
40 using namespace xmlsignature;
41 using namespace xmltooling::logging;
42 using namespace xmltooling;
43 using namespace std;
44
45 namespace opensaml {
46     namespace saml1p {              
47         class SAML_DLLLOCAL SAML1POSTEncoder : public MessageEncoder
48         {
49         public:
50             SAML1POSTEncoder(const DOMElement* e, const XMLCh* ns);
51             virtual ~SAML1POSTEncoder() {}
52             
53             long encode(
54                 GenericResponse& genericResponse,
55                 XMLObject* xmlObject,
56                 const char* destination,
57                 const EntityDescriptor* recipient=NULL,
58                 const char* relayState=NULL,
59                 const ArtifactGenerator* artifactGenerator=NULL,
60                 const Credential* credential=NULL,
61                 const XMLCh* signatureAlg=NULL,
62                 const XMLCh* digestAlg=NULL
63                 ) const;
64
65         protected:
66             /** Pathname of HTML template for transmission of message via POST. */
67             string m_template;
68         };
69
70         MessageEncoder* SAML_DLLLOCAL SAML1POSTEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
71         {
72             return new SAML1POSTEncoder(p.first, p.second);
73         }
74     };
75 };
76
77 static const XMLCh _template[] = UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
78
79 SAML1POSTEncoder::SAML1POSTEncoder(const DOMElement* e, const XMLCh* ns)
80 {
81     if (e) {
82         auto_ptr_char t(e->getAttributeNS(ns, _template));
83         if (t.get() && *t.get())
84             m_template = t.get();
85     }
86     if (m_template.empty())
87         throw XMLToolingException("SAML1POSTEncoder requires template XML attribute.");
88     XMLToolingConfig::getConfig().getPathResolver()->resolve(m_template, PathResolver::XMLTOOLING_CFG_FILE);
89 }
90
91 long SAML1POSTEncoder::encode(
92     GenericResponse& genericResponse,
93     XMLObject* xmlObject,
94     const char* destination,
95     const EntityDescriptor* recipient,
96     const char* relayState,
97     const ArtifactGenerator* artifactGenerator,
98     const Credential* credential,
99     const XMLCh* signatureAlg,
100     const XMLCh* digestAlg
101     ) const
102 {
103 #ifdef _DEBUG
104     xmltooling::NDC ndc("encode");
105 #endif
106     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML1POST");
107
108     TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
109     if (!engine)
110         throw BindingException("Encoding response using POST requires a TemplateEngine instance.");
111     
112     log.debug("validating input");
113     if (xmlObject->getParent())
114         throw BindingException("Cannot encode XML content with parent.");
115     Response* response = dynamic_cast<Response*>(xmlObject);
116     if (!response)
117         throw BindingException("XML content for SAML 1.x POST Encoder must be a SAML 1.x <Response>.");
118     if (!relayState)
119         throw BindingException("SAML 1.x POST Encoder requires relay state (TARGET) value.");
120     
121     DOMElement* rootElement = NULL;
122     if (credential) {
123         // Signature based on native XML signing.
124         if (response->getSignature()) {
125             log.debug("response already signed, skipping signature operation");
126         }
127         else {
128             log.debug("signing and marshalling the response");
129
130             // Build a Signature.
131             Signature* sig = SignatureBuilder::buildSignature();
132             response->setSignature(sig);
133             if (signatureAlg)
134                 sig->setSignatureAlgorithm(signatureAlg);
135             if (digestAlg) {
136                 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
137                 if (cr)
138                     cr->setDigestAlgorithm(digestAlg);
139             }
140     
141             // Sign response while marshalling.
142             vector<Signature*> sigs(1,sig);
143             rootElement = response->marshall((DOMDocument*)NULL,&sigs,credential);
144         }
145     }
146     else {
147         log.debug("marshalling the response");
148         rootElement = response->marshall();
149     }
150
151     // Push message into template.
152     TemplateEngine::TemplateParameters pmap;
153     string& xmlbuf = pmap.m_map["SAMLResponse"];
154     XMLHelper::serialize(rootElement, xmlbuf);
155     log.debug("marshalled response:\n%s", xmlbuf.c_str());
156     
157     // Replace with base-64 encoded version.
158     unsigned int len=0;
159     XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(xmlbuf.data()),xmlbuf.size(),&len);
160     if (out) {
161         xmlbuf.erase();
162         xmlbuf.append(reinterpret_cast<char*>(out),len);
163         XMLString::release(&out);
164     }
165     else {
166         throw BindingException("Base64 encoding of XML failed.");
167     }
168
169     // Fill in the rest of the data and send to the client.
170     log.debug("message encoded, sending HTML form template to client");
171     ifstream infile(m_template.c_str());
172     if (!infile)
173         throw BindingException("Failed to open HTML template for POST response ($1).", params(1,m_template.c_str()));
174     pmap.m_map["action"] = destination;
175     pmap.m_map["TARGET"] = relayState;
176     stringstream s;
177     engine->run(infile, s, pmap);
178     genericResponse.setContentType("text/html");
179     long ret = genericResponse.sendResponse(s);
180
181     // Cleanup by destroying XML.
182     delete xmlObject;
183     return ret;
184 }