Switch encoders to metadata-based recipient parameter.
[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/MessageEncoder.h"
27 #include "saml2/binding/SAML2Artifact.h"
28 #include "saml2/core/Protocols.h"
29 #include "saml2/metadata/Metadata.h"
30
31 #include <fstream>
32 #include <sstream>
33 #include <log4cpp/Category.hh>
34 #include <xmltooling/io/HTTPResponse.h>
35 #include <xmltooling/util/NDC.h>
36 #include <xmltooling/util/TemplateEngine.h>
37 #include <xmltooling/util/URLEncoder.h>
38
39 using namespace opensaml::saml2p;
40 using namespace opensaml::saml2md;
41 using namespace opensaml;
42 using namespace xmlsignature;
43 using namespace xmltooling;
44 using namespace log4cpp;
45 using namespace std;
46
47 namespace opensaml {
48     namespace saml2p {              
49         class SAML_DLLLOCAL SAML2ArtifactEncoder : public MessageEncoder
50         {
51         public:
52             SAML2ArtifactEncoder(const DOMElement* e);
53             virtual ~SAML2ArtifactEncoder() {}
54             
55             long encode(
56                 GenericResponse& genericResponse,
57                 XMLObject* xmlObject,
58                 const char* destination,
59                 const EntityDescriptor* recipient=NULL,
60                 const char* relayState=NULL,
61                 const Credential* credential=NULL,
62                 const XMLCh* signatureAlg=NULL,
63                 const XMLCh* digestAlg=NULL
64                 ) const;
65         
66         private:
67             bool m_post;
68             string m_template;
69         };
70
71         MessageEncoder* SAML_DLLLOCAL SAML2ArtifactEncoderFactory(const DOMElement* const & e)
72         {
73             return new SAML2ArtifactEncoder(e);
74         }
75     };
76
77     static const XMLCh _template[] =    UNICODE_LITERAL_8(t,e,m,p,l,a,t,e);
78     static const XMLCh postArtifact[] = UNICODE_LITERAL_12(p,o,s,t,A,r,t,i,f,a,c,t);
79 };
80
81 SAML2ArtifactEncoder::SAML2ArtifactEncoder(const DOMElement* e) : m_post(false)
82 {
83     if (e) {
84         const XMLCh* flag = e->getAttributeNS(NULL, postArtifact);
85         m_post = (flag && (*flag==chLatin_t || *flag==chDigit_1));
86         if (m_post) {
87             auto_ptr_char t(e->getAttributeNS(NULL, _template));
88             if (t.get())
89                 m_template = t.get();
90         }
91     }
92 }
93
94 long SAML2ArtifactEncoder::encode(
95     GenericResponse& genericResponse,
96     XMLObject* xmlObject,
97     const char* destination,
98     const EntityDescriptor* recipient,
99     const char* relayState,
100     const Credential* credential,
101     const XMLCh* signatureAlg,
102     const XMLCh* digestAlg
103     ) const
104 {
105 #ifdef _DEBUG
106     xmltooling::NDC ndc("encode");
107 #endif
108     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2Artifact");
109
110     log.debug("validating input");
111     HTTPResponse* httpResponse=dynamic_cast<HTTPResponse*>(&genericResponse);
112     if (!httpResponse)
113         throw BindingException("Unable to cast response interface to HTTPResponse type.");
114     if (relayState && strlen(relayState)>80)
115         throw BindingException("RelayState cannot exceed 80 bytes in length.");
116     
117     if (xmlObject->getParent())
118         throw BindingException("Cannot encode XML content with parent.");
119
120     StatusResponseType* response = NULL;
121     RequestAbstractType* request = dynamic_cast<RequestAbstractType*>(xmlObject);
122     if (!request)
123         response = dynamic_cast<StatusResponseType*>(xmlObject);
124     if (!response)
125         throw BindingException("XML content for SAML 2.0 HTTP-Artifact Encoder must be a SAML 2.0 protocol message.");
126     
127     ArtifactMap* mapper = SAMLConfig::getConfig().getArtifactMap();
128     if (!mapper)
129         throw BindingException("SAML 2.0 HTTP-Artifact Encoder requires ArtifactMap be set in configuration.");
130
131     // Obtain a fresh artifact.
132     if (!m_artifactGenerator)
133         throw BindingException("SAML 2.0 HTTP-Artifact Encoder requires an ArtifactGenerator instance.");
134     auto_ptr_char recipientID(recipient ? recipient->getEntityID() : NULL);
135     log.debug("obtaining new artifact for relying party (%s)", recipientID.get() ? recipientID.get() : "unknown");
136     auto_ptr<SAMLArtifact> artifact(m_artifactGenerator->generateSAML2Artifact(recipient));
137
138     if (credential) {
139         // Signature based on native XML signing.
140         if (request ? request->getSignature() : response->getSignature()) {
141             log.debug("message already signed, skipping signature operation");
142         }
143         else {
144             log.debug("signing the message");
145
146             // Build a Signature.
147             Signature* sig = SignatureBuilder::buildSignature();
148             request ? request->setSignature(sig) : response->setSignature(sig);    
149             if (signatureAlg)
150                 sig->setSignatureAlgorithm(signatureAlg);
151             if (digestAlg) {
152                 opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
153                 if (cr)
154                     cr->setDigestAlgorithm(digestAlg);
155             }
156             
157             // Sign response while marshalling.
158             vector<Signature*> sigs(1,sig);
159             xmlObject->marshall((DOMDocument*)NULL,&sigs,credential);
160         }
161     }
162     
163     // Store the message. Last step in storage will be to delete the XML.
164     log.debug("storing artifact and content in map");
165     mapper->storeContent(xmlObject, artifact.get(), recipientID.get());
166
167     if (m_template.empty()) {
168         // Generate redirect.
169         string loc = destination;
170         loc += (strchr(destination,'?') ? '&' : '?');
171         const URLEncoder* escaper = XMLToolingConfig::getConfig().getURLEncoder();
172         loc = loc + "SAMLart=" + escaper->encode(artifact->encode().c_str());
173         if (relayState && *relayState)
174             loc = loc + "&RelayState=" + escaper->encode(relayState);
175         log.debug("message encoded, sending redirect to client");
176         return httpResponse->sendRedirect(loc.c_str());
177     }
178     else {
179         // Push message into template and send result to client. 
180         log.debug("message encoded, sending HTML form template to client");
181         TemplateEngine* engine = XMLToolingConfig::getConfig().getTemplateEngine();
182         if (!engine)
183             throw BindingException("Encoding artifact using POST requires a TemplateEngine instance.");
184         ifstream infile(m_template.c_str());
185         if (!infile)
186             throw BindingException("Failed to open HTML template for POST response ($1).", params(1,m_template.c_str()));
187         TemplateEngine::TemplateParameters params;
188         params.m_map["action"] = destination;
189         params.m_map["SAMLart"] = artifact->encode();
190         if (relayState && *relayState)
191             params.m_map["RelayState"] = relayState;
192         stringstream s;
193         engine->run(infile, s, params);
194         httpResponse->setContentType("text/html");
195         return httpResponse->sendResponse(s);
196     }
197 }