Update copyright.
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2ArtifactEncoder.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  * 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 long SAML2ArtifactEncoder::encode(
66     GenericResponse& genericResponse,
67     xmltooling::XMLObject* xmlObject,
68     const char* destination,
69     const char* recipientID,
70     const char* relayState,
71     const CredentialResolver* credResolver,
72     const XMLCh* sigAlgorithm
73     ) const
74 {
75 #ifdef _DEBUG
76     xmltooling::NDC ndc("encode");
77 #endif
78     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2Artifact");
79
80     log.debug("validating input");
81     HTTPResponse* httpResponse=dynamic_cast<HTTPResponse*>(&genericResponse);
82     if (!httpResponse)
83         throw BindingException("Unable to cast response interface to HTTPResponse type.");
84     if (relayState && strlen(relayState)>80)
85         throw BindingException("RelayState cannot exceed 80 bytes in length.");
86     
87     if (xmlObject->getParent())
88         throw BindingException("Cannot encode XML content with parent.");
89
90     StatusResponseType* response = NULL;
91     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
92     if (!request)
93         response = dynamic_cast<StatusResponseType*>(xmlObject);
94     if (!response)
95         throw BindingException("XML content for SAML 2.0 HTTP-Artifact Encoder must be a SAML 2.0 protocol message.");
96     
97     ArtifactMap* mapper = SAMLConfig::getConfig().getArtifactMap();
98     if (!mapper)
99         throw BindingException("SAML 2.0 HTTP-Artifact Encoder requires ArtifactMap be set in configuration.");
100
101     // Obtain a fresh artifact.
102     if (!m_artifactGenerator)
103         throw BindingException("SAML 2.0 HTTP-Artifact Encoder requires an ArtifactGenerator instance.");
104     log.debug("obtaining new artifact for relying party (%s)", recipientID ? recipientID : "unknown");
105     auto_ptr<SAMLArtifact> artifact(m_artifactGenerator->generateSAML2Artifact(recipientID));
106
107     if (credResolver) {
108         // Signature based on native XML signing.
109         if (request ? request->getSignature() : response->getSignature()) {
110             log.debug("message already signed, skipping signature operation");
111         }
112         else {
113             log.debug("signing the message");
114
115             // Build a Signature.
116             Signature* sig = buildSignature(credResolver, sigAlgorithm);
117             
118             // Append Signature.
119             request ? request->setSignature(sig) : response->setSignature(sig);    
120         
121             // Sign response while marshalling.
122             vector<Signature*> sigs(1,sig);
123             xmlObject->marshall((DOMDocument*)NULL,&sigs);
124         }
125     }
126     
127     // Store the message. Last step in storage will be to delete the XML.
128     log.debug("storing artifact and content in map");
129     mapper->storeContent(xmlObject, artifact.get(), recipientID);
130
131     if (m_template.empty()) {
132         // Generate redirect.
133         string loc = destination;
134         loc += (strchr(destination,'?') ? '&' : '?');
135         URLEncoder* escaper = SAMLConfig::getConfig().getURLEncoder();
136         loc = loc + "SAMLart=" + escaper->encode(artifact->encode().c_str());
137         if (relayState)
138             loc = loc + "&RelayState=" + escaper->encode(relayState);
139         log.debug("message encoded, sending redirect to client");
140         return httpResponse->sendRedirect(loc.c_str());
141     }
142     else {
143         // Push message into template and send result to client. 
144         log.debug("message encoded, sending HTML form template to client");
145         TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
146         if (!engine)
147             throw BindingException("Encoding artifact using POST requires a TemplateEngine instance.");
148         ifstream infile(m_template.c_str());
149         if (!infile)
150             throw BindingException("Failed to open HTML template for POST response ($1).", params(1,m_template.c_str()));
151         TemplateEngine::TemplateParameters params;
152         params.m_map["action"] = destination;
153         params.m_map["SAMLart"] = artifact->encode();
154         if (relayState)
155             params.m_map["RelayState"] = relayState;
156         stringstream s;
157         engine->run(infile, s, params);
158         httpResponse->setContentType("text/html");
159         return httpResponse->sendResponse(s);
160     }
161 }