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