Revamped encoders to produce the actual HTTP responses.
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2ArtifactEncoder.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  * 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/URLEncoder.h"
27 #include "saml2/binding/SAML2Artifact.h"
28 #include "saml2/binding/SAML2ArtifactEncoder.h"
29 #include "saml2/core/Protocols.h"
30
31 #include <fstream>
32 #include <sstream>
33 #include <log4cpp/Category.hh>
34 #include <xmltooling/util/NDC.h>
35 #include <xmltooling/util/TemplateEngine.h>
36
37 using namespace opensaml::saml2p;
38 using namespace opensaml;
39 using namespace xmlsignature;
40 using namespace xmltooling;
41 using namespace log4cpp;
42 using namespace std;
43
44 namespace opensaml {
45     namespace saml2p {              
46         MessageEncoder* SAML_DLLLOCAL SAML2ArtifactEncoderFactory(const DOMElement* const & e)
47         {
48             return new SAML2ArtifactEncoder(e);
49         }
50     };
51 };
52
53 static const XMLCh templat[] = UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
54
55 SAML2ArtifactEncoder::SAML2ArtifactEncoder(const DOMElement* e)
56 {
57     if (e) {
58         auto_ptr_char t(e->getAttributeNS(NULL, templat));
59         if (t.get())
60             m_template = t.get();
61     }
62 }
63
64 SAML2ArtifactEncoder::~SAML2ArtifactEncoder() {}
65
66 long SAML2ArtifactEncoder::encode(
67     HTTPResponse& httpResponse,
68     xmltooling::XMLObject* xmlObject,
69     const char* destination,
70     const char* recipientID,
71     const char* relayState,
72     const CredentialResolver* credResolver,
73     const XMLCh* sigAlgorithm
74     ) const
75 {
76 #ifdef _DEBUG
77     xmltooling::NDC ndc("encode");
78 #endif
79     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2Artifact");
80     log.debug("validating input");
81     
82     if (relayState && strlen(relayState)>80)
83         throw BindingException("RelayState cannot exceed 80 bytes in length.");
84     
85     if (xmlObject->getParent())
86         throw BindingException("Cannot encode XML content with parent.");
87
88     StatusResponseType* response = NULL;
89     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
90     if (!request)
91         response = dynamic_cast<StatusResponseType*>(xmlObject);
92     if (!response)
93         throw BindingException("XML content for SAML 2.0 HTTP-Artifact Encoder must be a SAML 2.0 protocol message.");
94     
95     ArtifactMap* mapper = SAMLConfig::getConfig().getArtifactMap();
96     if (!mapper)
97         throw BindingException("SAML 2.0 HTTP-Artifact Encoder requires ArtifactMap be set in configuration.");
98
99     // Obtain a fresh artifact.
100     if (!m_artifactGenerator)
101         throw BindingException("SAML 2.0 HTTP-Artifact Encoder requires an ArtifactGenerator instance.");
102     log.debug("obtaining new artifact for relying party (%s)", recipientID ? recipientID : "unknown");
103     auto_ptr<SAMLArtifact> artifact(m_artifactGenerator->generateSAML2Artifact(recipientID));
104
105     if (credResolver) {
106         // Signature based on native XML signing.
107         if (request ? request->getSignature() : response->getSignature()) {
108             log.debug("message already signed, skipping signature operation");
109         }
110         else {
111             log.debug("signing the message");
112
113             // Build a Signature.
114             Signature* sig = buildSignature(credResolver, sigAlgorithm);
115             
116             // Append Signature.
117             request ? request->setSignature(sig) : response->setSignature(sig);    
118         
119             // Sign response while marshalling.
120             vector<Signature*> sigs(1,sig);
121             xmlObject->marshall((DOMDocument*)NULL,&sigs);
122         }
123     }
124     
125     // Store the message. Last step in storage will be to delete the XML.
126     log.debug("storing artifact and content in map");
127     mapper->storeContent(xmlObject, artifact.get(), recipientID);
128
129     if (m_template.empty()) {
130         // Generate redirect.
131         string loc = destination;
132         loc += (strchr(destination,'?') ? '&' : '?');
133         URLEncoder* escaper = SAMLConfig::getConfig().getURLEncoder();
134         loc = loc + "SAMLart=" + escaper->encode(artifact->encode().c_str());
135         if (relayState)
136             loc = loc + "&RelayState=" + escaper->encode(relayState);
137         log.debug("message encoded, sending redirect to client");
138         return httpResponse.sendRedirect(loc.c_str());
139     }
140     else {
141         // Push message into template and send result to client. 
142         log.debug("message encoded, sending HTML form template to client");
143         TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
144         if (!engine)
145             throw BindingException("Encoding artifact using POST requires a TemplateEngine instance.");
146         ifstream infile(m_template.c_str());
147         if (!infile)
148             throw BindingException("Failed to open HTML template for POST response ($1).", params(1,m_template.c_str()));
149         map<string,string> params;
150         params["action"] = destination;
151         params["SAMLart"] = artifact->encode();
152         if (relayState)
153             params["RelayState"] = relayState;
154         stringstream s;
155         engine->run(infile, s, params);
156         return httpResponse.sendResponse(s);
157     }
158 }