Add short name to encoders/decoders for endpoint generation.
[shibboleth/cpp-opensaml.git] / saml / saml2 / binding / impl / SAML2ECPEncoder.cpp
1 /*
2  *  Copyright 2001-2010 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  * SAML2ECPEncoder.cpp
19  * 
20  * SAML 2.0 ECP profile message encoder.
21  */
22
23 #include "internal.h"
24 #include "exceptions.h"
25 #include "binding/MessageEncoder.h"
26 #include "signature/ContentReference.h"
27 #include "saml1/core/Protocols.h"
28 #include "saml2/core/Protocols.h"
29
30 #include <sstream>
31 #include <xmltooling/logging.h>
32 #include <xmltooling/impl/AnyElement.h>
33 #include <xmltooling/io/HTTPResponse.h>
34 #include <xmltooling/util/NDC.h>
35 #include <xmltooling/signature/Signature.h>
36 #include <xmltooling/soap/SOAP.h>
37
38 using namespace samlconstants;
39 using namespace opensaml::saml2p;
40 using namespace opensaml::saml2md;
41 using namespace opensaml;
42 using namespace xmlconstants;
43 using namespace xmlsignature;
44 using namespace soap11;
45 using namespace xmltooling::logging;
46 using namespace xmltooling;
47 using namespace std;
48
49 namespace opensaml {
50     namespace saml2p {              
51         
52         static const XMLCh ProviderName[] = UNICODE_LITERAL_12(P,r,o,v,i,d,e,r,N,a,m,e);
53
54         class SAML_DLLLOCAL SAML2ECPEncoder : public MessageEncoder
55         {
56         public:
57             SAML2ECPEncoder(const DOMElement* e, const XMLCh* ns) : m_actor("http://schemas.xmlsoap.org/soap/actor/next"),
58                     m_providerName(e ? e->getAttributeNS(ns, ProviderName) : nullptr), m_idpList(nullptr) {
59                 DOMElement* child = e ? XMLHelper::getFirstChildElement(e, SAML20P_NS, IDPList::LOCAL_NAME) : nullptr;
60                 if (child)
61                     m_idpList = dynamic_cast<IDPList*>(XMLObjectBuilder::buildOneFromElement(child));
62             }
63             virtual ~SAML2ECPEncoder() {
64                 delete m_idpList;
65             }
66
67             const XMLCh* getProtocolFamily() const {
68                 return samlconstants::SAML20P_NS;
69             }
70
71             const char* getShortName() const {
72                 return "ECP";
73             }
74
75             long encode(
76                 GenericResponse& genericResponse,
77                 XMLObject* xmlObject,
78                 const char* destination,
79                 const EntityDescriptor* recipient=nullptr,
80                 const char* relayState=nullptr,
81                 const ArtifactGenerator* artifactGenerator=nullptr,
82                 const Credential* credential=nullptr,
83                 const XMLCh* signatureAlg=nullptr,
84                 const XMLCh* digestAlg=nullptr
85                 ) const;
86             
87         private:
88             auto_ptr_XMLCh m_actor;
89             const XMLCh* m_providerName;
90             IDPList* m_idpList;
91             AnyElementBuilder m_anyBuilder;
92         };
93
94         MessageEncoder* SAML_DLLLOCAL SAML2ECPEncoderFactory(const pair<const DOMElement*,const XMLCh*>& p)
95         {
96             return new SAML2ECPEncoder(p.first, p.second);
97         }
98     };
99 };
100
101 long SAML2ECPEncoder::encode(
102     GenericResponse& genericResponse,
103     XMLObject* xmlObject,
104     const char* destination,
105     const EntityDescriptor* recipient,
106     const char* relayState,
107     const ArtifactGenerator* artifactGenerator,
108     const Credential* credential,
109     const XMLCh* signatureAlg,
110     const XMLCh* digestAlg
111     ) const
112 {
113 #ifdef _DEBUG
114     xmltooling::NDC ndc("encode");
115 #endif
116     Category& log = Category::getInstance(SAML_LOGCAT".MessageEncoder.SAML2ECP");
117
118     log.debug("validating input");
119     if (xmlObject->getParent())
120         throw BindingException("Cannot encode XML content with parent.");
121
122     Response* response = nullptr;
123     AuthnRequest* request = dynamic_cast<AuthnRequest*>(xmlObject);
124     if (!request) {
125         response = dynamic_cast<Response*>(xmlObject);
126         if (!response)
127             throw BindingException("XML content for SAML 2.0 ECP Encoder must be a SAML 2.0 AuthnRequest or Response.");
128     }
129     
130     if (request && !request->getAssertionConsumerServiceURL())
131         throw BindingException("AuthnRequest must carry an AssertionConsumerServiceURL by value.");
132     else if (response && !response->getDestination())
133         throw BindingException("Response must carry a Destination attribute.");
134     
135     // PAOS request leg is a custom MIME type, SOAP response leg is just text/xml.
136     genericResponse.setContentType(request ? "application/vnd.paos+xml" : "text/xml");
137     HTTPResponse* httpResponse = dynamic_cast<HTTPResponse*>(&genericResponse);
138     if (httpResponse) {
139         httpResponse->setResponseHeader("Expires", "01-Jan-1997 12:00:00 GMT");
140         httpResponse->setResponseHeader("Cache-Control", "no-cache, no-store, must-revalidate, private");
141         httpResponse->setResponseHeader("Pragma", "no-cache");
142     }
143
144     // Wrap it in a SOAP envelope.
145     Envelope* env = EnvelopeBuilder::buildEnvelope();
146     Header* header = HeaderBuilder::buildHeader();
147     env->setHeader(header);
148     Body* body = BodyBuilder::buildBody();
149     env->setBody(body);
150     body->getUnknownXMLObjects().push_back(xmlObject);
151
152     ElementProxy* hdrblock;
153     xmltooling::QName qMU(SOAP11ENV_NS, Header::MUSTUNDERSTAND_ATTRIB_NAME, SOAP11ENV_PREFIX);
154     xmltooling::QName qActor(SOAP11ENV_NS, Header::ACTOR_ATTRIB_NAME, SOAP11ENV_PREFIX);
155     
156     if (request) {
157         // Create paos:Request header.
158         static const XMLCh service[] = UNICODE_LITERAL_7(s,e,r,v,i,c,e);
159         static const XMLCh responseConsumerURL[] = UNICODE_LITERAL_19(r,e,s,p,o,n,s,e,C,o,n,s,u,m,e,r,U,R,L);
160         hdrblock = dynamic_cast<ElementProxy*>(m_anyBuilder.buildObject(PAOS_NS, saml1p::Request::LOCAL_NAME, PAOS_PREFIX));
161         hdrblock->setAttribute(qMU, XML_ONE);
162         hdrblock->setAttribute(qActor, m_actor.get());
163         hdrblock->setAttribute(xmltooling::QName(nullptr, service), SAML20ECP_NS);
164         hdrblock->setAttribute(xmltooling::QName(nullptr, responseConsumerURL), request->getAssertionConsumerServiceURL());
165         header->getUnknownXMLObjects().push_back(hdrblock);
166
167         // Create ecp:Request header.
168         static const XMLCh IsPassive[] = UNICODE_LITERAL_9(I,s,P,a,s,s,i,v,e);
169         hdrblock = dynamic_cast<ElementProxy*>(m_anyBuilder.buildObject(SAML20ECP_NS, saml1p::Request::LOCAL_NAME, SAML20ECP_PREFIX));
170         hdrblock->setAttribute(qMU, XML_ONE);
171         hdrblock->setAttribute(qActor, m_actor.get());
172         if (!request->IsPassive())
173             hdrblock->setAttribute(xmltooling::QName(nullptr,IsPassive), XML_ZERO);
174         if (m_providerName)
175             hdrblock->setAttribute(xmltooling::QName(nullptr,ProviderName), m_providerName);
176         hdrblock->getUnknownXMLObjects().push_back(request->getIssuer()->clone());
177         if (request->getScoping() && request->getScoping()->getIDPList())
178             hdrblock->getUnknownXMLObjects().push_back(request->getScoping()->getIDPList()->clone());
179         else if (m_idpList)
180             hdrblock->getUnknownXMLObjects().push_back(m_idpList->clone());
181         header->getUnknownXMLObjects().push_back(hdrblock);
182     }
183     else {
184         // Create ecp:Response header.
185         hdrblock = dynamic_cast<ElementProxy*>(m_anyBuilder.buildObject(SAML20ECP_NS, Response::LOCAL_NAME, SAML20ECP_PREFIX));
186         hdrblock->setAttribute(qMU, XML_ONE);
187         hdrblock->setAttribute(qActor, m_actor.get());
188         hdrblock->setAttribute(xmltooling::QName(nullptr,AuthnRequest::ASSERTIONCONSUMERSERVICEURL_ATTRIB_NAME), response->getDestination());
189         header->getUnknownXMLObjects().push_back(hdrblock);
190     }
191     
192     if (relayState && *relayState) {
193         // Create ecp:RelayState header.
194         static const XMLCh RelayState[] = UNICODE_LITERAL_10(R,e,l,a,y,S,t,a,t,e);
195         hdrblock = dynamic_cast<ElementProxy*>(m_anyBuilder.buildObject(SAML20ECP_NS, RelayState, SAML20ECP_PREFIX));
196         hdrblock->setAttribute(qMU, XML_ONE);
197         hdrblock->setAttribute(qActor, m_actor.get());
198         auto_ptr_XMLCh rs(relayState);
199         hdrblock->setTextContent(rs.get());
200         header->getUnknownXMLObjects().push_back(hdrblock);
201     }
202     
203     try {
204         DOMElement* rootElement = nullptr;
205         if (credential) {
206             if (request->getSignature()) {
207                 log.debug("message already signed, skipping signature operation");
208                 rootElement = env->marshall();
209             }
210             else {
211                 log.debug("signing the message and marshalling the envelope");
212     
213                 // Build a Signature.
214                 Signature* sig = SignatureBuilder::buildSignature();
215                 request->setSignature(sig);    
216                 if (signatureAlg)
217                     sig->setSignatureAlgorithm(signatureAlg);
218                 if (digestAlg) {
219                     opensaml::ContentReference* cr = dynamic_cast<opensaml::ContentReference*>(sig->getContentReference());
220                     if (cr)
221                         cr->setDigestAlgorithm(digestAlg);
222                 }
223         
224                 // Sign message while marshalling.
225                 vector<Signature*> sigs(1,sig);
226                 rootElement = env->marshall((DOMDocument*)nullptr,&sigs,credential);
227             }
228         }
229         else {
230             log.debug("marshalling the envelope");
231             rootElement = env->marshall();
232         }
233
234         stringstream s;
235         s << *rootElement;
236         
237         if (log.isDebugEnabled()) {
238             string forlog(s.str());
239             log.debug("marshalled envelope:\n%s", forlog.c_str());
240         }
241
242         log.debug("sending serialized envelope");
243         long ret = genericResponse.sendResponse(s);
244     
245         // Cleanup by destroying XML.
246         delete env;
247         return ret;
248     }
249     catch (XMLToolingException&) {
250         // A bit weird...we have to "revert" things so that the message is isolated
251         // so the caller can free it.
252         xmlObject->getParent()->detach();
253         xmlObject->detach();
254         throw;
255     }
256 }