Enhance relay state handling.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / AbstractHandler.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  * AbstractHandler.cpp
19  * 
20  * Base class for handlers based on a DOMPropertySet. 
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "SPRequest.h"
28 #include "handler/AbstractHandler.h"
29 #include "remoting/ListenerService.h"
30
31 #include <log4cpp/Category.hh>
32 #include <saml/saml1/core/Protocols.h>
33 #include <saml/saml2/core/Protocols.h>
34 #include <saml/util/SAMLConstants.h>
35 #include <xmltooling/XMLToolingConfig.h>
36 #include <xmltooling/util/StorageService.h>
37 #include <xmltooling/util/URLEncoder.h>
38
39 using namespace shibsp;
40 using namespace samlconstants;
41 using namespace opensaml;
42 using namespace xmltooling;
43 using namespace log4cpp;
44 using namespace xercesc;
45 using namespace std;
46
47 namespace shibsp {
48     SHIBSP_DLLLOCAL PluginManager<Handler,pair<const DOMElement*,const char*>>::Factory SAML1ConsumerFactory;
49     SHIBSP_DLLLOCAL PluginManager<Handler,pair<const DOMElement*,const char*>>::Factory SAML2ConsumerFactory;
50 };
51
52 void SHIBSP_API shibsp::registerHandlers()
53 {
54     SPConfig& conf=SPConfig::getConfig();
55     
56     conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_ARTIFACT, SAML1ConsumerFactory);
57     conf.AssertionConsumerServiceManager.registerFactory(SAML1_PROFILE_BROWSER_POST, SAML1ConsumerFactory);
58     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_ARTIFACT, SAML2ConsumerFactory);
59     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST, SAML2ConsumerFactory);
60     conf.AssertionConsumerServiceManager.registerFactory(SAML20_BINDING_HTTP_POST_SIMPLESIGN, SAML2ConsumerFactory);
61 }
62
63 AbstractHandler::AbstractHandler(
64     const DOMElement* e, log4cpp::Category& log, DOMNodeFilter* filter, const map<string,string>* remapper
65     ) : m_log(log) {
66     load(e,log,filter,remapper);
67 }
68
69 void AbstractHandler::checkError(const XMLObject* response) const
70 {
71     const saml2p::StatusResponseType* r2 = dynamic_cast<const saml2p::StatusResponseType*>(response);
72     if (r2) {
73         const saml2p::Status* status = r2->getStatus();
74         if (status) {
75             const saml2p::StatusCode* sc = status->getStatusCode();
76             const XMLCh* code = sc ? sc->getValue() : NULL;
77             if (code && !XMLString::equals(code,saml2p::StatusCode::SUCCESS)) {
78                 FatalProfileException ex("SAML Response message contained an error.");
79                 auto_ptr_char c1(code);
80                 ex.addProperty("StatusCode", c1.get());
81                 if (sc->getStatusCode()) {
82                     code = sc->getStatusCode()->getValue();
83                     auto_ptr_char c2(code);
84                     ex.addProperty("StatusCode2", c2.get());
85                 }
86                 if (status->getStatusMessage()) {
87                     auto_ptr_char msg(status->getStatusMessage()->getMessage());
88                     ex.addProperty("StatusMessage", msg.get());
89                 }
90             }
91         }
92     }
93
94     const saml1p::Response* r1 = dynamic_cast<const saml1p::Response*>(response);
95     if (r1) {
96         const saml1p::Status* status = r1->getStatus();
97         if (status) {
98             const saml1p::StatusCode* sc = status->getStatusCode();
99             const QName* code = sc ? sc->getValue() : NULL;
100             if (code && *code != saml1p::StatusCode::SUCCESS) {
101                 FatalProfileException ex("SAML Response message contained an error.");
102                 ex.addProperty("StatusCode", code->toString().c_str());
103                 if (sc->getStatusCode()) {
104                     code = sc->getStatusCode()->getValue();
105                     if (code)
106                         ex.addProperty("StatusCode2", code->toString().c_str());
107                 }
108                 if (status->getStatusMessage()) {
109                     auto_ptr_char msg(status->getStatusMessage()->getMessage());
110                     ex.addProperty("StatusMessage", msg.get());
111                 }
112             }
113         }
114     }
115 }
116
117 void AbstractHandler::preserveRelayState(SPRequest& request, string& relayState) const
118 {
119     if (relayState.empty())
120         return;
121
122     // No setting means just pass it by value.
123     pair<bool,const char*> mech=getString("relayState");
124     if (!mech.first || !mech.second || !*mech.second)
125         return;
126
127     if (!strcmp(mech.second, "cookie")) {
128         // Here we store the state in a cookie and send a fixed
129         // value so we can recognize it on the way back.
130         if (relayState != "cookie") {
131             const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
132             pair<string,const char*> shib_cookie=request.getApplication().getCookieNameProps("_shibstate_");
133             string stateval = urlenc->encode(relayState.c_str()) + shib_cookie.second;
134             request.setCookie(shib_cookie.first.c_str(),stateval.c_str());
135             relayState = "cookie";
136         }
137     }
138     else if (strstr(mech.second,"ss:")==mech.second) {
139         if (relayState.find("ss:")!=0) {
140             mech.second+=3;
141             if (*mech.second) {
142                 DDF out,in = DDF("set::RelayState").structure();
143                 in.addmember("id").string(mech.second);
144                 in.addmember("value").string(relayState.c_str());
145                 DDFJanitor jin(in),jout(out);
146                 out = request.getServiceProvider().getListenerService()->send(in);
147                 if (!out.isstring())
148                     throw IOException("StorageService-backed RelayState mechanism did not return a state key.");
149                 relayState = string(mech.second-3) + ':' + out.string();
150             }
151         }
152     }
153     else
154         throw ConfigurationException("Unsupported relayState mechanism ($1).", params(1,mech.second));
155 }
156
157 void AbstractHandler::recoverRelayState(HTTPRequest& httpRequest, string& relayState, bool clear) const
158 {
159     SPConfig& conf = SPConfig::getConfig();
160
161     // Look for StorageService-backed state of the form "ss:SSID:key".
162     const char* state = relayState.c_str();
163     if (strstr(state,"ss:")==state) {
164         state += 3;
165         const char* key = strchr(state,':');
166         if (key) {
167             string ssid = relayState.substr(3, key - state);
168             key++;
169             if (!ssid.empty() && *key) {
170                 if (conf.isEnabled(SPConfig::OutOfProcess)) {
171                     StorageService* storage = conf.getServiceProvider()->getStorageService(ssid.c_str());
172                     if (storage) {
173                         if (storage->readString("RelayState",key,&relayState)>0) {
174                             if (clear)
175                                 storage->deleteString("RelayState",key);
176                             return;
177                         }
178                         else
179                             relayState.erase();
180                     }
181                     else {
182                         Category::getInstance(SHIBSP_LOGCAT".Handler").error(
183                             "Storage-backed RelayState with invalid StorageService ID (%s)", ssid.c_str()
184                             );
185                         relayState.erase();
186                     }
187                 }
188                 else if (conf.isEnabled(SPConfig::InProcess)) {
189                     // In process, we should be able to cast down to a full SPRequest.
190                     SPRequest& request = dynamic_cast<SPRequest&>(httpRequest);
191                     DDF out,in = DDF("get::RelayState").structure();
192                     in.addmember("id").string(ssid.c_str());
193                     in.addmember("key").string(key);
194                     in.addmember("clear").integer(clear ? 1 : 0);
195                     DDFJanitor jin(in),jout(out);
196                     out = request.getServiceProvider().getListenerService()->send(in);
197                     if (!out.isstring()) {
198                         Category::getInstance(SHIBSP_LOGCAT".Handler").error(
199                             "StorageService-backed RelayState mechanism did not return a state value."
200                             );
201                         relayState.erase();
202                     }
203                     else {
204                         relayState = out.string();
205                         return;
206                     }
207                 }
208             }
209         }
210     }
211     
212     if (conf.isEnabled(SPConfig::InProcess)) {
213         // In process, we should be able to cast down to a full SPRequest.
214         SPRequest& request = dynamic_cast<SPRequest&>(httpRequest);
215         if (relayState == "cookie") {
216             // Pull the value from the "relay state" cookie.
217             pair<string,const char*> relay_cookie = request.getApplication().getCookieNameProps("_shibstate_");
218             const char* state = request.getCookie(relay_cookie.first.c_str());
219             if (state && *state) {
220                 // URL-decode the value.
221                 char* rscopy=strdup(state);
222                 XMLToolingConfig::getConfig().getURLEncoder()->decode(rscopy);
223                 relayState = rscopy;
224                 free(rscopy);
225                 
226                 if (clear)
227                     request.setCookie(relay_cookie.first.c_str(),relay_cookie.second);
228                 return;
229             }
230
231             relayState.erase();
232         }
233
234         // Check for "default" value.
235         if (relayState.empty() || relayState == "default") {
236             pair<bool,const char*> homeURL=request.getApplication().getString("homeURL");
237             relayState=homeURL.first ? homeURL.second : "/";
238             return;
239         }
240     }
241
242     if (relayState == "default")
243         relayState.empty();
244 }