Revamped binding classes with security policy layer.
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2POSTEncoder.cpp
1 /*
2  *  Copyright 2001-2006 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  * SAML2POSTEncoder.cpp
19  * 
20  * SAML 2.0 HTTP-POST binding message encoder
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "binding/HTTPResponse.h"
26 #include "saml2/binding/SAML2POSTEncoder.h"
27 #include "saml2/core/Protocols.h"
28
29 #include <fstream>
30 #include <sstream>
31 #include <log4cpp/Category.hh>
32 #include <xercesc/util/Base64.hpp>
33 #include <xmltooling/util/NDC.h>
34 #include <xmltooling/util/TemplateEngine.h>
35
36 using namespace opensaml::saml2p;
37 using namespace opensaml;
38 using namespace xmlsignature;
39 using namespace xmltooling;
40 using namespace log4cpp;
41 using namespace std;
42
43 namespace opensaml {
44     namespace saml2p {              
45         MessageEncoder* SAML_DLLLOCAL SAML2POSTEncoderFactory(const DOMElement* const & e)
46         {
47             return new SAML2POSTEncoder(e);
48         }
49     };
50 };
51
52 static const XMLCh templat[] = UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
53
54 SAML2POSTEncoder::SAML2POSTEncoder(const DOMElement* e)
55 {
56     if (e) {
57         auto_ptr_char t(e->getAttributeNS(NULL, templat));
58         if (t.get())
59             m_template = t.get();
60     }
61     if (m_template.empty())
62         throw XMLToolingException("SAML2POSTEncoder requires template attribute.");
63 }
64
65 SAML2POSTEncoder::~SAML2POSTEncoder() {}
66
67 long SAML2POSTEncoder::encode(
68     GenericResponse& genericResponse,
69     XMLObject* xmlObject,
70     const char* destination,
71     const char* recipientID,
72     const char* relayState,
73     const CredentialResolver* credResolver,
74     const XMLCh* sigAlgorithm
75     ) const
76 {
77 #ifdef _DEBUG
78     xmltooling::NDC ndc("encode");
79 #endif
80     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2POST");
81
82     log.debug("validating input");
83     HTTPResponse* httpResponse=dynamic_cast<HTTPResponse*>(&genericResponse);
84     if (!httpResponse)
85         throw BindingException("Unable to cast response interface to HTTPResponse type.");
86     if (xmlObject->getParent())
87         throw BindingException("Cannot encode XML content with parent.");
88     
89     StatusResponseType* response = NULL;
90     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
91     if (!request) {
92         response = dynamic_cast<StatusResponseType*>(xmlObject);
93         if (!response)
94             throw BindingException("XML content for SAML 2.0 HTTP-POST Encoder must be a SAML 2.0 protocol message.");
95     }
96     
97     DOMElement* rootElement = NULL;
98     if (credResolver) {
99         // Signature based on native XML signing.
100         if (request ? request->getSignature() : response->getSignature()) {
101             log.debug("message already signed, skipping signature operation");
102         }
103         else {
104             log.debug("signing and marshalling the message");
105
106             // Build a Signature.
107             Signature* sig = buildSignature(credResolver, sigAlgorithm);
108             
109             // Append Signature.
110             request ? request->setSignature(sig) : response->setSignature(sig);    
111         
112             // Sign response while marshalling.
113             vector<Signature*> sigs(1,sig);
114             rootElement = xmlObject->marshall((DOMDocument*)NULL,&sigs);
115         }
116     }
117     else {
118         log.debug("marshalling the message");
119         rootElement = xmlObject->marshall();
120     }
121     
122     string xmlbuf;
123     XMLHelper::serialize(rootElement, xmlbuf);
124     unsigned int len=0;
125     XMLByte* out=Base64::encode(reinterpret_cast<const XMLByte*>(xmlbuf.data()),xmlbuf.size(),&len);
126     if (out) {
127         xmlbuf.erase();
128         xmlbuf.append(reinterpret_cast<char*>(out),len);
129         XMLString::release(&out);
130     }
131     else {
132         throw BindingException("Base64 encoding of XML failed.");
133     }
134     
135     // Push message into template and send result to client.
136     log.debug("message encoded, sending HTML form template to client");
137     TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
138     if (!engine)
139         throw BindingException("Encoding message using POST requires a TemplateEngine instance.");
140     ifstream infile(m_template.c_str());
141     if (!infile)
142         throw BindingException("Failed to open HTML template for POST message ($1).", params(1,m_template.c_str()));
143     map<string,string> params;
144     params["action"] = destination;
145     params[request ? "SAMLRequest" : "SAMLResponse"] = xmlbuf;
146     if (relayState)
147         params["RelayState"] = relayState;
148     stringstream s;
149     engine->run(infile, s, params);
150     httpResponse->setContentType("text/html");
151     long ret = httpResponse->sendResponse(s, HTTPResponse::SAML_HTTP_STATUS_OK);
152
153     // Cleanup by destroying XML.
154     delete xmlObject;
155     return ret;
156 }