Generate RequestInitiator metadata extension from parentless SessionInitiators.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / SAMLDSSessionInitiator.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  * SAMLDSSessionInitiator.cpp
19  *
20  * SAML Discovery Service support.
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "handler/AbstractHandler.h"
27 #include "handler/SessionInitiator.h"
28
29 #include <xmltooling/XMLToolingConfig.h>
30 #include <xmltooling/util/URLEncoder.h>
31
32 using namespace shibsp;
33 using namespace opensaml;
34 using namespace xmltooling;
35 using namespace std;
36
37 #ifndef SHIBSP_LITE
38 # include <saml/saml2/metadata/Metadata.h>
39 # include <saml/saml2/metadata/MetadataProvider.h>
40 using namespace opensaml::saml2md;
41 #endif
42
43 namespace shibsp {
44
45 #if defined (_MSC_VER)
46     #pragma warning( push )
47     #pragma warning( disable : 4250 )
48 #endif
49
50     class SHIBSP_DLLLOCAL SAMLDSSessionInitiator : public SessionInitiator, public AbstractHandler
51     {
52     public:
53         SAMLDSSessionInitiator(const DOMElement* e, const char* appId);
54         virtual ~SAMLDSSessionInitiator() {}
55
56         pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
57
58 #ifndef SHIBSP_LITE
59         void generateMetadata(SPSSODescriptor& role, const char* handlerURL) const {
60             // Initial guess at index to use.
61             pair<bool,unsigned int> ix = getUnsignedInt("index");
62             if (!ix.first)
63                 ix.second = 1;
64
65             // Find maximum index in use and go one higher.
66             if (role.getExtensions()) {
67                 const vector<XMLObject*>& exts = const_cast<const Extensions*>(role.getExtensions())->getUnknownXMLObjects();
68                 for (vector<XMLObject*>::const_reverse_iterator i = exts.rbegin(); i != exts.rend(); ++i) {
69                     const DiscoveryResponse* sub = dynamic_cast<DiscoveryResponse*>(*i);
70                     if (sub) {
71                         pair<bool,int> val = sub->getIndex();
72                         if (val.first) {
73                             if (ix.second <= val.second)
74                                 ix.second = val.second + 1;
75                             break;
76                         }
77                     }
78                 }
79             }
80
81             const char* loc = getString("Location").second;
82             string hurl(handlerURL);
83             if (*loc != '/')
84                 hurl += '/';
85             hurl += loc;
86             auto_ptr_XMLCh widen(hurl.c_str());
87
88             DiscoveryResponse* ep = DiscoveryResponseBuilder::buildDiscoveryResponse();
89             ep->setLocation(widen.get());
90             ep->setBinding(samlconstants::IDP_DISCOVERY_PROTOCOL_NS);
91             ep->setIndex(ix.second);
92             Extensions* ext = role.getExtensions();
93             if (!ext) {
94                 ext = ExtensionsBuilder::buildExtensions();
95                 role.setExtensions(ext);
96             }
97             ext->getUnknownXMLObjects().push_back(ep);
98         }
99 #endif
100
101     private:
102         const char* m_url;
103         const char* m_returnParam;
104         vector<string> m_preservedOptions;
105     };
106
107 #if defined (_MSC_VER)
108     #pragma warning( pop )
109 #endif
110
111     SessionInitiator* SHIBSP_DLLLOCAL SAMLDSSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
112     {
113         return new SAMLDSSessionInitiator(p.first, p.second);
114     }
115
116 };
117
118 SAMLDSSessionInitiator::SAMLDSSessionInitiator(const DOMElement* e, const char* appId)
119         : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.SAMLDS")), m_url(nullptr), m_returnParam(nullptr)
120 {
121     pair<bool,const char*> url = getString("URL");
122     if (!url.first)
123         throw ConfigurationException("SAMLDS SessionInitiator requires a URL property.");
124     m_url = url.second;
125     url = getString("entityIDParam");
126     if (url.first)
127         m_returnParam = url.second;
128
129     pair<bool,const char*> options = getString("preservedOptions");
130     if (options.first) {
131         int j = 0;
132         string opt = options.second;
133         for (unsigned int i = 0;  i < opt.length();  i++) {
134             if (opt.at(i) == ' ') {
135                 m_preservedOptions.push_back(opt.substr(j, i-j));
136                 j = i+1;
137             }
138         }
139         m_preservedOptions.push_back(opt.substr(j, opt.length()-j));
140     }
141     else {
142         m_preservedOptions.push_back("isPassive");
143         m_preservedOptions.push_back("forceAuthn");
144         m_preservedOptions.push_back("authnContextClassRef");
145         m_preservedOptions.push_back("authnContextComparison");
146         m_preservedOptions.push_back("NameIDFormat");
147         m_preservedOptions.push_back("SPNameQualifier");
148         m_preservedOptions.push_back("acsIndex");
149     }
150
151     m_supportedOptions.insert("isPassive");
152 }
153
154 pair<bool,long> SAMLDSSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
155 {
156     // The IdP CANNOT be specified for us to run. Otherwise, we'd be redirecting to a DS
157     // anytime the IdP's metadata was wrong.
158     if (!entityID.empty() || !checkCompatibility(request, isHandler))
159         return make_pair(false,0L);
160
161     string target;
162     pair<bool,const char*> prop;
163     bool isPassive=false;
164     const Application& app=request.getApplication();
165     pair<bool,const char*> discoveryURL = pair<bool,const char*>(true, m_url);
166
167     if (isHandler) {
168         prop.second = request.getParameter("SAMLDS");
169         if (prop.second && !strcmp(prop.second,"1")) {
170             saml2md::MetadataException ex("No identity provider was selected by user.");
171             ex.addProperty("statusCode", "urn:oasis:names:tc:SAML:2.0:status:Requester");
172             ex.addProperty("statusCode2", "urn:oasis:names:tc:SAML:2.0:status:NoAvailableIDP");
173             ex.raise();
174         }
175
176         prop = getString("target", request);
177         if (prop.first)
178             target = prop.second;
179
180         recoverRelayState(app, request, request, target, false);
181
182         pair<bool,bool> passopt = getBool("isPassive", request);
183         isPassive = passopt.first && passopt.second;
184
185         prop.second = request.getParameter("discoveryURL");
186         if (prop.second && *prop.second)
187             discoveryURL.second = prop.second;
188     }
189     else {
190         // Check for a hardwired target value in the map or handler.
191         prop = getString("target", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
192         if (prop.first)
193             target = prop.second;
194         else
195             target = request.getRequestURL();
196
197         pair<bool,bool> passopt = getBool("isPassive", request, HANDLER_PROPERTY_MAP|HANDLER_PROPERTY_FIXED);
198         isPassive = passopt.first && passopt.second;
199         discoveryURL = request.getRequestSettings().first->getString("discoveryURL");
200     }
201
202     if (!discoveryURL.first)
203         discoveryURL.second = m_url;
204     m_log.debug("sending request to SAMLDS (%s)", discoveryURL.second);
205
206     // Compute the return URL. We start with a self-referential link.
207     string returnURL = request.getHandlerURL(target.c_str());
208     prop = getString("Location");
209     if (prop.first)
210         returnURL += prop.second;
211     returnURL += "?SAMLDS=1"; // signals us not to loop if we get no answer back
212
213     if (isHandler) {
214         // We may already have RelayState set if we looped back here,
215         // but we've turned it back into a resource by this point, so if there's
216         // a target on the URL, reset to that value.
217         prop.second = request.getParameter("target");
218         if (prop.second && *prop.second)
219             target = prop.second;
220     }
221     preserveRelayState(app, request, target);
222     if (!isHandler)
223         preservePostData(app, request, request, target.c_str());
224
225     const URLEncoder* urlenc = XMLToolingConfig::getConfig().getURLEncoder();
226     if (isHandler) {
227         // Now the hard part. The base assumption is to append the entire query string, if any,
228         // to the self-link. But we want to replace target with the RelayState-preserved value
229         // to hide it from the DS.
230         const char* query = request.getQueryString();
231         if (query) {
232             // See if it starts with target.
233             if (!strncmp(query, "target=", 7)) {
234                 // We skip this altogether and advance the query past it to the first separator.
235                 query = strchr(query, '&');
236                 // If we still have more, just append it.
237                 if (query && *(++query))
238                     returnURL = returnURL + '&' + query;
239             }
240             else {
241                 // There's something in the query before target appears, so we have to find it.
242                 prop.second = strstr(query, "&target=");
243                 if (prop.second) {
244                     // We found it, so first append everything up to it.
245                     returnURL += '&';
246                     returnURL.append(query, prop.second - query);
247                     query = prop.second + 8; // move up just past the equals sign.
248                     prop.second = strchr(query, '&');
249                     if (prop.second)
250                         returnURL += prop.second;
251                 }
252                 else {
253                     // No target in the existing query, so just append it as is.
254                     returnURL = returnURL + '&' + query;
255                 }
256             }
257         }
258
259         // Now append the sanitized target as needed.
260         if (!target.empty())
261             returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());
262     }
263     else {
264         // For a virtual handler, we append target to the return link.
265          if (!target.empty())
266             returnURL = returnURL + "&target=" + urlenc->encode(target.c_str());
267          // Preserve designated request settings on the URL.
268          for (vector<string>::const_iterator opt = m_preservedOptions.begin(); opt != m_preservedOptions.end(); ++ opt) {
269              prop = request.getRequestSettings().first->getString(opt->c_str());
270              if (prop.first)
271                  returnURL = returnURL + '&' + (*opt) + '=' + urlenc->encode(prop.second);
272          }
273     }
274
275     string req=string(discoveryURL.second) + (strchr(discoveryURL.second,'?') ? '&' : '?') + "entityID=" + urlenc->encode(app.getString("entityID").second) +
276         "&return=" + urlenc->encode(returnURL.c_str());
277     if (m_returnParam)
278         req = req + "&returnIDParam=" + m_returnParam;
279     if (isPassive)
280         req += "&isPassive=true";
281
282     return make_pair(true, request.sendRedirect(req.c_str()));
283 }