2 * Licensed to the University Corporation for Advanced Internet
3 * Development, Inc. (UCAID) under one or more contributor license
4 * agreements. See the NOTICE file distributed with this work for
5 * additional information regarding copyright ownership.
7 * UCAID licenses this file to you under the Apache License,
8 * Version 2.0 (the "License"); you may not use this file except
9 * in compliance with the License. You may obtain a copy of the
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17 * either express or implied. See the License for the specific
18 * language governing permissions and limitations under the License.
22 * TransformSessionInitiator.cpp
24 * Support for mapping input into an entityID using a transform.
28 #include "Application.h"
29 #include "exceptions.h"
30 #include "ServiceProvider.h"
31 #include "SPRequest.h"
32 #include "handler/AbstractHandler.h"
33 #include "handler/RemotedHandler.h"
34 #include "handler/SessionInitiator.h"
35 #include "util/SPConstants.h"
38 # include "metadata/MetadataProviderCriteria.h"
39 # include <saml/saml2/metadata/Metadata.h>
41 #include <boost/tuple/tuple.hpp>
42 #include <xmltooling/XMLToolingConfig.h>
43 #include <xmltooling/util/URLEncoder.h>
44 #include <xercesc/util/XMLUniDefs.hpp>
45 #include <xercesc/util/regx/RegularExpression.hpp>
47 using namespace shibsp;
48 using namespace opensaml::saml2md;
49 using namespace opensaml;
50 using namespace xmltooling;
51 using namespace boost;
56 #if defined (_MSC_VER)
57 #pragma warning( push )
58 #pragma warning( disable : 4250 )
61 class SHIBSP_DLLLOCAL TransformSINodeFilter : public DOMNodeFilter
64 #ifdef SHIBSP_XERCESC_SHORT_ACCEPTNODE
69 acceptNode(const DOMNode* node) const {
74 static SHIBSP_DLLLOCAL TransformSINodeFilter g_TSINFilter;
77 static const XMLCh force[] = UNICODE_LITERAL_5(f,o,r,c,e);
78 static const XMLCh match[] = UNICODE_LITERAL_5(m,a,t,c,h);
79 static const XMLCh Regex[] = UNICODE_LITERAL_5(R,e,g,e,x);
80 static const XMLCh Subst[] = UNICODE_LITERAL_5(S,u,b,s,t);
83 class SHIBSP_DLLLOCAL TransformSessionInitiator : public SessionInitiator, public AbstractHandler, public RemotedHandler
86 TransformSessionInitiator(const DOMElement* e, const char* appId)
87 : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".SessionInitiator.Transform"), &g_TSINFilter), m_appId(appId) {
88 // If Location isn't set, defer address registration until the setParent call.
89 pair<bool,const char*> loc = getString("Location");
91 string address = m_appId + loc.second + "::run::TransformSI";
92 setAddress(address.c_str());
94 m_supportedOptions.insert("isPassive");
97 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess)) {
98 m_alwaysRun = getBool("alwaysRun").second;
99 e = XMLHelper::getFirstChildElement(e);
101 if (e->hasChildNodes()) {
102 bool flag = XMLHelper::getAttrBool(e, false, force);
103 if (XMLString::equals(e->getLocalName(), Subst)) {
104 auto_ptr_char temp(e->getTextContent());
105 if (temp.get() && *temp.get())
106 m_subst.push_back(pair<bool,string>(flag, temp.get()));
108 else if (XMLString::equals(e->getLocalName(), Regex) && e->hasAttributeNS(nullptr, match)) {
109 auto_ptr_char m(e->getAttributeNS(nullptr, match));
110 auto_ptr_char repl(e->getTextContent());
111 if (m.get() && *m.get() && repl.get() && *repl.get())
112 m_regex.push_back(tuple<bool,string,string>(flag, m.get(), repl.get()));
115 m_log.warn("Unknown element found in Transform SessionInitiator configuration, check for errors.");
118 e = XMLHelper::getNextSiblingElement(e);
124 virtual ~TransformSessionInitiator() {}
126 void setParent(const PropertySet* parent);
127 void receive(DDF& in, ostream& out);
128 pair<bool,long> run(SPRequest& request, string& entityID, bool isHandler=true) const;
131 void doRequest(const Application& application, string& entityID) const;
135 vector< pair<bool, string> > m_subst;
136 vector< tuple<bool,string,string> > m_regex;
140 #if defined (_MSC_VER)
141 #pragma warning( pop )
144 SessionInitiator* SHIBSP_DLLLOCAL TransformSessionInitiatorFactory(const pair<const DOMElement*,const char*>& p)
146 return new TransformSessionInitiator(p.first, p.second);
151 void TransformSessionInitiator::setParent(const PropertySet* parent)
153 DOMPropertySet::setParent(parent);
154 pair<bool,const char*> loc = getString("Location");
156 string address = m_appId + loc.second + "::run::TransformSI";
157 setAddress(address.c_str());
160 m_log.warn("no Location property in Transform SessionInitiator (or parent), can't register as remoted handler");
164 pair<bool,long> TransformSessionInitiator::run(SPRequest& request, string& entityID, bool isHandler) const
166 // We have to have a candidate name to function.
167 if (entityID.empty() || !checkCompatibility(request, isHandler))
168 return make_pair(false, 0L);
170 const Application& app = request.getApplication();
172 m_log.debug("attempting to transform input (%s) into a valid entityID", entityID.c_str());
174 if (SPConfig::getConfig().isEnabled(SPConfig::OutOfProcess))
175 doRequest(app, entityID);
178 DDF out,in = DDF(m_address.c_str()).structure();
179 DDFJanitor jin(in), jout(out);
180 in.addmember("application_id").string(app.getId());
181 in.addmember("entity_id").string(entityID.c_str());
183 // Remote the processing.
184 out = request.getServiceProvider().getListenerService()->send(in);
186 entityID = out.string();
189 return make_pair(false, 0L);
192 void TransformSessionInitiator::receive(DDF& in, ostream& out)
195 const char* aid = in["application_id"].string();
196 const Application* app = aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : nullptr;
198 // Something's horribly wrong.
199 m_log.error("couldn't find application (%s) to generate AuthnRequest", aid ? aid : "(missing)");
200 throw ConfigurationException("Unable to locate application for new session, deleted?");
203 const char* entityID = in["entity_id"].string();
205 throw ConfigurationException("No entityID parameter supplied to remoted SessionInitiator.");
207 string copy(entityID);
208 doRequest(*app, copy);
209 DDF ret = DDF(nullptr).string(copy.c_str());
210 DDFJanitor jout(ret);
214 void TransformSessionInitiator::doRequest(const Application& application, string& entityID) const
217 MetadataProvider* m = application.getMetadataProvider();
220 MetadataProviderCriteria mc(application, entityID.c_str(), &IDPSSODescriptor::ELEMENT_QNAME);
221 pair<const EntityDescriptor*,const RoleDescriptor*> entity;
223 // First check the original value, it might be valid already.
224 entity = m->getEntityDescriptor(mc);
229 m_log.debug("attempting transform of (%s)", entityID.c_str());
231 // Guess not, try each subst.
233 for (vector< pair<bool,string> >::const_iterator t = m_subst.begin(); t != m_subst.end(); ++t) {
234 string::size_type pos = t->second.find("$entityID");
235 if (pos == string::npos)
237 transform = t->second;
238 transform.replace(pos, 9, entityID);
240 m_log.info("forcibly transformed entityID from (%s) to (%s)", entityID.c_str(), transform.c_str());
241 entityID = transform;
244 m_log.debug("attempting lookup with entityID (%s)", transform.c_str());
246 mc.entityID_ascii = transform.c_str();
247 entity = m->getEntityDescriptor(mc);
249 m_log.info("transformed entityID from (%s) to (%s)", entityID.c_str(), transform.c_str());
251 entityID = transform;
257 for (vector< tuple<bool,string,string> >::const_iterator r = m_regex.begin(); r != m_regex.end(); ++r) {
259 RegularExpression exp(r->get<1>().c_str());
260 XMLCh* temp = exp.replace(entityID.c_str(), r->get<2>().c_str());
262 auto_ptr_char narrow(temp);
263 XMLString::release(&temp);
265 // For some reason it returns the match string if it doesn't match the expression.
266 if (entityID == narrow.get())
270 m_log.info("forcibly transformed entityID from (%s) to (%s)", entityID.c_str(), narrow.get());
271 entityID = narrow.get();
274 m_log.debug("attempting lookup with entityID (%s)", narrow.get());
276 mc.entityID_ascii = narrow.get();
277 entity = m->getEntityDescriptor(mc);
279 m_log.info("transformed entityID from (%s) to (%s)", entityID.c_str(), narrow.get());
281 entityID = narrow.get();
286 catch (XMLException& ex) {
287 auto_ptr_char msg(ex.getMessage());
288 m_log.error("caught error applying regular expression: %s", msg.get());
292 m_log.warn("unable to find a valid entityID based on the supplied input");