Options for per-content error handling.
[shibboleth/sp.git] / shibsp / ServiceProvider.cpp
index f971e4d..c4b70b8 100644 (file)
@@ -35,6 +35,7 @@
 #include <sstream>
 #include <xmltooling/XMLToolingConfig.h>
 #include <xmltooling/util/NDC.h>
+#include <xmltooling/util/URLEncoder.h>
 #include <xmltooling/util/XMLHelper.h>
 
 using namespace shibsp;
@@ -48,8 +49,7 @@ namespace shibsp {
     {
         if (mayRedirect) {
             // Check for redirection on errors instead of template.
-            const PropertySet* sessions=app ? app->getPropertySet("Sessions") : NULL;
-            pair<bool,const char*> redirectErrors = sessions ? sessions->getString("redirectErrors") : pair<bool,const char*>(false,NULL);
+            pair<bool,const char*> redirectErrors = app ? app->getString("redirectErrors") : pair<bool,const char*>(false,NULL);
             if (redirectErrors.first) {
                 string loc(redirectErrors.second);
                 loc = loc + '?' + tp.toQueryString();
@@ -61,23 +61,37 @@ namespace shibsp {
         request.setResponseHeader("Expires","01-Jan-1997 12:00:00 GMT");
         request.setResponseHeader("Cache-Control","private,no-store,no-cache");
     
+        // Error templates come from the request's settings or from the Errors property set.
+        pair<bool,const char*> pathname = pair<bool,const char*>(false,NULL);
+        try {
+            RequestMapper::Settings settings = request.getRequestSettings();
+            string pagename(page);
+            pagename += "Error";
+            pathname = settings.first->getString(pagename.c_str());
+        }
+        catch (exception& ex) {
+            request.log(SPRequest::SPError, ex.what());
+        }
+
+        // Nothing for request, so check app properties.
         const PropertySet* props=app ? app->getPropertySet("Errors") : NULL;
-        if (props) {
-            pair<bool,const char*> p=props->getString(page);
-            if (p.first) {
-                ifstream infile(p.second);
-                if (infile) {
-                    tp.setPropertySet(props);
-                    stringstream str;
-                    XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, tp, tp.getRichException());
-                    return request.sendResponse(str);
-                }
-            }
-            else if (!strcmp(page,"access")) {
-                istringstream msg("Access Denied");
-                return request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN);
+        if (!pathname.first && props)
+            pathname=props->getString(page);
+
+        if (pathname.first) {
+            ifstream infile(pathname.second);
+            if (infile) {
+                tp.setPropertySet(props);
+                stringstream str;
+                XMLToolingConfig::getConfig().getTemplateEngine()->run(infile, str, tp, tp.getRichException());
+                return request.sendResponse(str);
             }
         }
+        
+        if (!strcmp(page,"access")) {
+            istringstream msg("Access Denied");
+            return request.sendResponse(msg, HTTPResponse::XMLTOOLING_HTTP_STATUS_FORBIDDEN);
+        }
     
         string errstr = string("sendError could not process error template (") + page + ")";
         request.log(SPRequest::SPError, errstr);
@@ -86,27 +100,15 @@ namespace shibsp {
     }
     
     void SHIBSP_DLLLOCAL clearHeaders(SPRequest& request) {
-        // Clear invariant stuff.
-        request.clearHeader("Shib-Identity-Provider");
-        request.clearHeader("Shib-Authentication-Method");
-        request.clearHeader("Shib-AuthnContext-Class");
-        request.clearHeader("Shib-AuthnContext-Decl");
-        request.clearHeader("Shib-Attributes");
-        request.clearHeader("Shib-Application-ID");
-    
-        // TODO: Figure out a way to clear attribute headers...
-        /*
-        AttributeExtractor* extractor = request.getApplication().getAttributeExtractor();
-        if (extractor) {
-            Locker locker(extractor);
-            extractor->clearHeaders(request);
-        }
-        AttributeResolver* resolver = request.getApplication().getAttributeResolver();
-        if (resolver) {
-            Locker locker(resolver);
-            resolver->clearHeaders(request);
-        }
-        */
+        request.clearHeader("Shib-Session-ID", "HTTP_SHIB_SESSION_ID");
+        request.clearHeader("Shib-Identity-Provider", "HTTP_SHIB_IDENTITY_PROVIDER");
+        request.clearHeader("Shib-Authentication-Method", "HTTP_SHIB_AUTHENTICATION_METHOD");
+        request.clearHeader("Shib-AuthnContext-Class", "HTTP_SHIB_AUTHNCONTEXT_CLASS");
+        request.clearHeader("Shib-AuthnContext-Decl", "HTTP_SHIB_AUTHNCONTEXT_DECL");
+        request.clearHeader("Shib-Assertion-Count", "HTTP_SHIB_ASSERTION_COUNT");
+        request.clearHeader("REMOTE_USER", "HTTP_REMOTE_USER");
+        //request.clearHeader("Shib-Application-ID");   handle inside app method
+        request.getApplication().clearAttributeHeaders(request);
     }
 };
 
@@ -274,7 +276,7 @@ pair<bool,long> ServiceProvider::doAuthorization(SPRequest& request) const
         if (settings.second) {
             const Session* session = NULL;
             try {
-                session = request.getSession();
+                session = request.getSession(false);
             }
             catch (exception& e) {
                 request.log(SPRequest::SPWarn, string("unable to obtain session to pass to access control provider: ") + e.what());
@@ -328,7 +330,7 @@ pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSessio
 
         const Session* session = NULL;
         try {
-            session = request.getSession();
+            session = request.getSession(false);
         }
         catch (exception& e) {
             request.log(SPRequest::SPWarn, string("unable to obtain session to export to request: ") +  e.what());
@@ -346,6 +348,7 @@ pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSessio
         }
         
         request.setHeader("Shib-Application-ID", app->getId());
+        request.setHeader("Shib-Session-ID", session->getID());
 
         // Export the IdP name and Authn method/context info.
         const char* hval = session->getEntityID();
@@ -363,15 +366,36 @@ pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSessio
         // Maybe export the assertion keys.
         pair<bool,bool> exp=settings.first->getBool("exportAssertion");
         if (exp.first && exp.second) {
-            //setHeader("Shib-Attributes", reinterpret_cast<char*>(serialized));
-            // TODO: export lookup URLs to access assertions by ID
-            const vector<const char*>& tokens = session->getAssertionIDs();
+            const PropertySet* sessions=app->getPropertySet("Sessions");
+            pair<bool,const char*> exportLocation = sessions ? sessions->getString("exportLocation") : pair<bool,const char*>(false,NULL);
+            if (!exportLocation.first)
+                request.log(SPRequest::SPWarn, "can't export assertions without an exportLocation Sessions property");
+            else {
+                const URLEncoder* encoder = XMLToolingConfig::getConfig().getURLEncoder();
+                string exportName = "Shib-Assertion-00";
+                string baseURL;
+                if (!strncmp(exportLocation.second, "http", 4))
+                    baseURL = exportLocation.second;
+                else
+                    baseURL = string(request.getHandlerURL(targetURL.c_str())) + exportLocation.second;
+                baseURL = baseURL + "?key=" + session->getID() + "&ID=";
+                const vector<const char*>& tokens = session->getAssertionIDs();
+                vector<const char*>::size_type count = 0;
+                for (vector<const char*>::const_iterator tokenids = tokens.begin(); tokenids!=tokens.end(); ++tokenids) {
+                    count++;
+                    *(exportName.rbegin()) = '0' + (count%10);
+                    *(++exportName.rbegin()) = '0' + (count/10);
+                    string fullURL = baseURL + encoder->encode(*tokenids);
+                    request.setHeader(exportName.c_str(), fullURL.c_str());
+                }
+                request.setHeader("Shib-Assertion-Count", exportName.c_str() + 15);
+            }
         }
 
         // Export the attributes.
         bool remoteUserSet = false;
-        const multimap<string,Attribute*>& attributes = session->getAttributes();
-        for (multimap<string,Attribute*>::const_iterator a = attributes.begin(); a!=attributes.end(); ++a) {
+        const multimap<string,const Attribute*>& attributes = session->getIndexedAttributes();
+        for (multimap<string,const Attribute*>::const_iterator a = attributes.begin(); a!=attributes.end(); ++a) {
             const vector<string>& vals = a->second->getSerializedValues();
 
             // See if this needs to be set as the REMOTE_USER value.
@@ -406,7 +430,7 @@ pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSessio
     catch (exception& e) {
         TemplateParameters tp(&e);
         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
-        return make_pair(true,sendError(request, app, "rm", tp));
+        return make_pair(true,sendError(request, app, "session", tp));
     }
 #ifndef _DEBUG
     catch (...) {
@@ -414,7 +438,7 @@ pair<bool,long> ServiceProvider::doExport(SPRequest& request, bool requireSessio
         tp.m_map["errorType"] = "Unexpected Error";
         tp.m_map["errorText"] = "Caught an unknown exception.";
         tp.m_map["requestURL"] = targetURL.substr(0,targetURL.find('?'));
-        return make_pair(true,sendError(request, app, "rm", tp));
+        return make_pair(true,sendError(request, app, "session", tp));
     }
 #endif
 }