Improve consistency of cache API methods.
[shibboleth/cpp-sp.git] / shibsp / handler / impl / AssertionLookup.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  * AssertionLookup.cpp
19  * 
20  * Handler for looking assertions in SessionCache
21  */
22
23 #include "internal.h"
24 #include "Application.h"
25 #include "exceptions.h"
26 #include "ServiceProvider.h"
27 #include "SessionCacheEx.h"
28 #include "handler/AbstractHandler.h"
29 #include "handler/RemotedHandler.h"
30 #include "util/SPConstants.h"
31
32 using namespace shibspconstants;
33 using namespace shibsp;
34 using namespace opensaml;
35 using namespace xmltooling;
36 using namespace std;
37
38 namespace shibsp {
39
40 #if defined (_MSC_VER)
41     #pragma warning( push )
42     #pragma warning( disable : 4250 )
43 #endif
44
45     class SHIBSP_DLLLOCAL Blocker : public DOMNodeFilter
46     {
47     public:
48         short acceptNode(const DOMNode* node) const {
49             return FILTER_REJECT;
50         }
51     };
52
53     static SHIBSP_DLLLOCAL Blocker g_Blocker;
54
55     class SHIBSP_API AssertionLookup : public AbstractHandler, public RemotedHandler
56     {
57     public:
58         AssertionLookup(const DOMElement* e, const char* appId);
59         virtual ~AssertionLookup() {}
60
61         pair<bool,long> run(SPRequest& request, bool isHandler=true) const;
62         void receive(DDF& in, ostream& out);
63
64         const char* getType() const {
65             return "AssertionLookup";
66         }
67
68     private:
69         pair<bool,long> processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const;
70
71         set<string> m_acl;
72     };
73
74 #if defined (_MSC_VER)
75     #pragma warning( pop )
76 #endif
77
78     Handler* SHIBSP_DLLLOCAL AssertionLookupFactory(const pair<const DOMElement*,const char*>& p)
79     {
80         return new AssertionLookup(p.first, p.second);
81     }
82
83 };
84
85 AssertionLookup::AssertionLookup(const DOMElement* e, const char* appId)
86     : AbstractHandler(e, Category::getInstance(SHIBSP_LOGCAT".AssertionLookup"), &g_Blocker)
87 {
88     setAddress("run::AssertionLookup");
89     if (SPConfig::getConfig().isEnabled(SPConfig::InProcess)) {
90         pair<bool,const char*> acl = getString("exportACL");
91         if (!acl.first) {
92             m_acl.insert("127.0.0.1");
93             return;
94         }
95         string aclbuf=acl.second;
96         int j = 0;
97         for (unsigned int i=0;  i < aclbuf.length();  i++) {
98             if (aclbuf.at(i)==' ') {
99                 m_acl.insert(aclbuf.substr(j, i-j));
100                 j = i+1;
101             }
102         }
103         m_acl.insert(aclbuf.substr(j, aclbuf.length()-j));
104     }
105 }
106
107 pair<bool,long> AssertionLookup::run(SPRequest& request, bool isHandler) const
108 {
109     string relayState;
110     SPConfig& conf = SPConfig::getConfig();
111     if (conf.isEnabled(SPConfig::InProcess)) {
112         if (m_acl.count(request.getRemoteAddr()) == 0) {
113             m_log.error("request for assertion lookup blocked from invalid address (%s)", request.getRemoteAddr().c_str());
114             istringstream msg("Assertion Lookup Blocked");
115             return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_UNAUTHORIZED));
116         }
117     }
118     
119     try {
120         if (conf.isEnabled(SPConfig::OutOfProcess)) {
121             // When out of process, we run natively and directly process the message.
122             return processMessage(request.getApplication(), request, request);
123         }
124         else {
125             // When not out of process, we remote all the message processing.
126             DDF out,in = wrap(request);
127             DDFJanitor jin(in), jout(out);
128             
129             out=request.getServiceProvider().getListenerService()->send(in);
130             return unwrap(request, out);
131         }
132     }
133     catch (exception& ex) {
134         m_log.error("error while processing request: %s", ex.what());
135         istringstream msg("Assertion Lookup Failed");
136         return make_pair(true,request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_ERROR));
137     }
138 }
139
140 void AssertionLookup::receive(DDF& in, ostream& out)
141 {
142     // Find application.
143     const char* aid=in["application_id"].string();
144     const Application* app=aid ? SPConfig::getConfig().getServiceProvider()->getApplication(aid) : NULL;
145     if (!app) {
146         // Something's horribly wrong.
147         m_log.error("couldn't find application (%s) for assertion lookup", aid ? aid : "(missing)");
148         throw ConfigurationException("Unable to locate application for assertion lookup, deleted?");
149     }
150     
151     // Unpack the request.
152     auto_ptr<HTTPRequest> req(getRequest(in));
153     //m_log.debug("found %d client certificates", req->getClientCertificates().size());
154
155     // Wrap a response shim.
156     DDF ret(NULL);
157     DDFJanitor jout(ret);
158     auto_ptr<HTTPResponse> resp(getResponse(ret));
159         
160     // Since we're remoted, the result should either be a throw, a false/0 return,
161     // which we just return as an empty structure, or a response/redirect,
162     // which we capture in the facade and send back.
163     processMessage(*app, *req.get(), *resp.get());
164     out << ret;
165 }
166
167 pair<bool,long> AssertionLookup::processMessage(const Application& application, HTTPRequest& httpRequest, HTTPResponse& httpResponse) const
168 {
169 #ifndef SHIBSP_LITE
170     const char* key = httpRequest.getParameter("key");
171     const char* ID = httpRequest.getParameter("ID");
172     if (!key || !*key || !ID || !*ID) {
173         m_log.error("assertion lookup request failed, missing required parameters");
174         throw FatalProfileException("Missing key or ID parameters.");
175     }
176
177     m_log.debug("processing assertion lookup request (session: %s, assertion: %s)", key, ID);
178
179     SessionCacheEx* cache = dynamic_cast<SessionCacheEx*>(application.getServiceProvider().getSessionCache());
180     if (!cache) {
181         m_log.error("session cache does not support extended API");
182         throw FatalProfileException("Session cache does not support assertion lookup.");
183     }
184
185     // The cache will either silently pass a session or NULL back, or throw an exception out.
186     Session* session = cache->find(application, ID);
187     if (!session) {
188         m_log.error("valid session (%s) not found for assertion lookup", key);
189         throw FatalProfileException("Session key not found.");
190     }
191
192     Locker locker(session, false);
193
194     const Assertion* assertion = session->getAssertion(ID);
195     if (!assertion) {
196         m_log.error("assertion (%s) not found in session (%s)", ID, key);
197         throw FatalProfileException("Assertion not found.");
198     }
199
200     stringstream s;
201     s << *assertion;
202     httpResponse.setContentType("application/samlassertion+xml");
203     return make_pair(true, httpResponse.sendResponse(s));
204 #else
205     return make_pair(false,0L);
206 #endif
207 }