First set of logout base classes and non-building draft of SP-initiated logout.
[shibboleth/sp.git] / shibsp / impl / RemotedSessionCache.cpp
index f276ee8..180bbc3 100644 (file)
 #include "exceptions.h"\r
 #include "ServiceProvider.h"\r
 #include "SessionCache.h"\r
-#include "TransactionLog.h"\r
 #include "attribute/Attribute.h"\r
 #include "remoting/ListenerService.h"\r
 #include "util/SPConstants.h"\r
 \r
+#include <ctime>\r
 #include <sstream>\r
 #include <log4cpp/Category.hh>\r
 #include <xmltooling/XMLToolingConfig.h>\r
+#include <xmltooling/util/DateTime.h>\r
 #include <xmltooling/util/NDC.h>\r
 #include <xmltooling/util/XMLHelper.h>\r
 \r
 using namespace shibsp;\r
-using namespace opensaml::saml2md;\r
-using namespace opensaml;\r
 using namespace xmltooling;\r
 using namespace log4cpp;\r
 using namespace std;\r
@@ -50,19 +49,7 @@ namespace shibsp {
     {\r
     public:\r
         RemotedSession(RemotedCache* cache, DDF& obj) : m_version(obj["version"].integer()), m_obj(obj),\r
-                m_nameid(NULL), m_expires(0), m_lastAccess(time(NULL)), m_cache(cache), m_lock(NULL) {\r
-            const char* nameid = obj["nameid"].string();\r
-            if (!nameid)\r
-                throw FatalProfileException("NameID missing from remotely cached session.");\r
-            \r
-            // Parse and bind the NameID into an XMLObject.\r
-            istringstream instr(nameid);\r
-            DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr); \r
-            XercesJanitor<DOMDocument> janitor(doc);\r
-            auto_ptr<saml2::NameID> n(saml2::NameIDBuilder::buildNameID());\r
-            n->unmarshall(doc->getDocumentElement(), true);\r
-            janitor.release();\r
-            \r
+                m_expires(0), m_lastAccess(time(NULL)), m_cache(cache), m_lock(NULL) {\r
             auto_ptr_XMLCh exp(m_obj["expires"].string());\r
             if (exp.get()) {\r
                 DateTime iso(exp.get());\r
@@ -71,15 +58,12 @@ namespace shibsp {
             }\r
 \r
             m_lock = Mutex::create();\r
-            m_nameid = n.release();\r
         }\r
         \r
         ~RemotedSession() {\r
             delete m_lock;\r
             m_obj.destroy();\r
-            delete m_nameid;\r
-            for_each(m_attributes.begin(), m_attributes.end(), cleanup_const_pair<string,Attribute>());\r
-            for_each(m_tokens.begin(), m_tokens.end(), cleanup_pair<string,RootObject>());\r
+            for_each(m_attributes.begin(), m_attributes.end(), cleanup_pair<string,Attribute>());\r
         }\r
         \r
         Lockable* lock() {\r
@@ -90,6 +74,9 @@ namespace shibsp {
             m_lock->unlock();\r
         }\r
 \r
+        const char* getID() const {\r
+            return m_obj.name();\r
+        }\r
         const char* getApplicationID() const {\r
             return m_obj["application_id"].string();\r
         }\r
@@ -99,12 +86,12 @@ namespace shibsp {
         const char* getEntityID() const {\r
             return m_obj["entity_id"].string();\r
         }\r
+        const char* getProtocol() const {\r
+            return m_obj["protocol"].string();\r
+        }\r
         const char* getAuthnInstant() const {\r
             return m_obj["authn_instant"].string();\r
         }\r
-        const opensaml::saml2::NameID& getNameID() const {\r
-            return *m_nameid;\r
-        }\r
         const char* getSessionIndex() const {\r
             return m_obj["session_index"].string();\r
         }\r
@@ -114,44 +101,34 @@ namespace shibsp {
         const char* getAuthnContextDeclRef() const {\r
             return m_obj["authncontext_decl"].string();\r
         }\r
-        const map<string,const Attribute*>& getAttributes() const {\r
+        const multimap<string,Attribute*>& getAttributes() const {\r
             if (m_attributes.empty())\r
                 unmarshallAttributes();\r
             return m_attributes;\r
         }\r
         const vector<const char*>& getAssertionIDs() const {\r
             if (m_ids.empty()) {\r
-                DDF id = m_obj["assertions"].first();\r
+                DDF ids = m_obj["assertions"];\r
+                DDF id = ids.first();\r
                 while (id.isstring()) {\r
                     m_ids.push_back(id.string());\r
-                    id = id.next();\r
+                    id = ids.next();\r
                 }\r
             }\r
             return m_ids;\r
         }\r
         \r
-        const RootObject* getAssertion(const char* id) const;\r
-\r
-        void addAttributes(const vector<Attribute*>& attributes) {\r
-            throw ConfigurationException("addAttributes method not implemented by this session cache plugin.");\r
-        }\r
-        void addAssertion(RootObject* assertion) {\r
-            throw ConfigurationException("addAssertion method not implemented by this session cache plugin.");\r
-        }\r
-\r
         time_t expires() const { return m_expires; }\r
         time_t lastAccess() const { return m_lastAccess; }\r
-        void validate(const Application& application, const char* client_addr, time_t timeout, bool local=true);\r
+        void validate(const Application& application, const char* client_addr, time_t* timeout);\r
 \r
     private:\r
         void unmarshallAttributes() const;\r
 \r
         int m_version;\r
         mutable DDF m_obj;\r
-        saml2::NameID* m_nameid;\r
-        mutable map<string,const Attribute*> m_attributes;\r
+        mutable multimap<string,Attribute*> m_attributes;\r
         mutable vector<const char*> m_ids;\r
-        mutable map<string,RootObject*> m_tokens;\r
         time_t m_expires,m_lastAccess;\r
         RemotedCache* m_cache;\r
         Mutex* m_lock;\r
@@ -163,21 +140,8 @@ namespace shibsp {
         RemotedCache(const DOMElement* e);\r
         ~RemotedCache();\r
     \r
-        string insert(\r
-            time_t expires,\r
-            const Application& application,\r
-            const char* client_addr,\r
-            const saml2md::EntityDescriptor* issuer,\r
-            const saml2::NameID& nameid,\r
-            const char* authn_instant=NULL,\r
-            const char* session_index=NULL,\r
-            const char* authncontext_class=NULL,\r
-            const char* authncontext_decl=NULL,\r
-            const RootObject* ssoToken=NULL,\r
-            const vector<Attribute*>* attributes=NULL\r
-            );\r
-        Session* find(const char* key, const Application& application, const char* client_addr=NULL, time_t timeout=0);\r
-        void remove(const char* key, const Application& application, const char* client_addr);\r
+        Session* find(const char* key, const Application& application, const char* client_addr=NULL, time_t* timeout=NULL);\r
+        void remove(const char* key, const Application& application);\r
         \r
         void cleanup();\r
     \r
@@ -203,11 +167,12 @@ namespace shibsp {
 void RemotedSession::unmarshallAttributes() const\r
 {\r
     Attribute* attribute;\r
-    DDF attr = m_obj["attributes"].first();\r
+    DDF attrs = m_obj["attributes"];\r
+    DDF attr = attrs.first();\r
     while (!attr.isnull()) {\r
         try {\r
             attribute = Attribute::unmarshall(attr);\r
-            m_attributes[attribute->getId()] = attribute;\r
+            m_attributes.insert(make_pair(attribute->getId(),attribute));\r
             if (m_cache->m_log.isDebugEnabled())\r
                 m_cache->m_log.debug("unmarshalled attribute (ID: %s) with %d value%s",\r
                     attribute->getId(), attr.first().integer(), attr.first().integer()!=1 ? "s" : "");\r
@@ -216,55 +181,17 @@ void RemotedSession::unmarshallAttributes() const
             const char* id = attr.first().name();\r
             m_cache->m_log.error("error unmarshalling attribute (ID: %s): %s", id ? id : "none", ex.what());\r
         }\r
-        attr = attr.next();\r
+        attr = attrs.next();\r
     }\r
 }\r
 \r
-const RootObject* RemotedSession::getAssertion(const char* id) const\r
-{\r
-    map<string,RootObject*>::const_iterator i = m_tokens.find(id);\r
-    if (i!=m_tokens.end())\r
-        return i->second;\r
-\r
-    // Fetch from remoted cache.\r
-    DDF in("getAssertion::"REMOTED_SESSION_CACHE);\r
-    DDFJanitor jin(in);\r
-    in.structure();\r
-    in.addmember("key").string(m_obj.name());\r
-    in.addmember("id").string(id);\r
-\r
-    DDF out=SPConfig::getConfig().getServiceProvider()->getListenerService()->send(in);\r
-    DDFJanitor jout(out);\r
-    \r
-    // Parse and bind the document into an XMLObject.\r
-    istringstream instr(out.string());\r
-    DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(instr); \r
-    XercesJanitor<DOMDocument> janitor(doc);\r
-    auto_ptr<XMLObject> xmlObject(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));\r
-    janitor.release();\r
-    \r
-    RootObject* token = dynamic_cast<RootObject*>(xmlObject.get());\r
-    if (!token || !token->isAssertion())\r
-        throw FatalProfileException("Cached assertion was of an unknown object type.");\r
-\r
-    // Transfer ownership to us.\r
-    xmlObject.release();\r
-    m_tokens[id]=token;\r
-    return token;\r
-}\r
-\r
-void RemotedSession::validate(const Application& application, const char* client_addr, time_t timeout, bool local)\r
+void RemotedSession::validate(const Application& application, const char* client_addr, time_t* timeout)\r
 {\r
     // Basic expiration?\r
     time_t now = time(NULL);\r
     if (now > m_expires) {\r
-        m_cache->m_log.info("session expired (ID: %s)", m_obj.name());\r
-        RetryableProfileException ex("Your session has expired, and you must re-authenticate.");\r
-        if (!getEntityID())\r
-            throw ex;\r
-        MetadataProvider* m=application.getMetadataProvider();\r
-        Locker locker(m);\r
-        annotateException(&ex,m->getEntityDescriptor(getEntityID(),false)); // throws it\r
+        m_cache->m_log.info("session expired (ID: %s)", getID());\r
+        throw opensaml::RetryableProfileException("Your session has expired, and you must re-authenticate.");\r
     }\r
 \r
     // Address check?\r
@@ -273,33 +200,28 @@ void RemotedSession::validate(const Application& application, const char* client
             m_cache->m_log.debug("comparing client address %s against %s", client_addr, getClientAddress());\r
         if (strcmp(getClientAddress(),client_addr)) {\r
             m_cache->m_log.warn("client address mismatch");\r
-            RetryableProfileException ex(\r
+            throw opensaml::RetryableProfileException(\r
                 "Your IP address ($1) does not match the address recorded at the time the session was established.",\r
                 params(1,client_addr)\r
                 );\r
-            if (!getEntityID())\r
-                throw ex;\r
-            MetadataProvider* m=application.getMetadataProvider();\r
-            Locker locker(m);\r
-            annotateException(&ex,m->getEntityDescriptor(getEntityID(),false)); // throws it\r
         }\r
     }\r
 \r
-    if (local)\r
+    if (!timeout)\r
         return;\r
     \r
-    DDF in("touch::"REMOTED_SESSION_CACHE), out;\r
+    DDF in("touch::"REMOTED_SESSION_CACHE"::SessionCache"), out;\r
     DDFJanitor jin(in);\r
     in.structure();\r
-    in.addmember("key").string(m_obj.name());\r
+    in.addmember("key").string(getID());\r
     in.addmember("version").integer(m_obj["version"].integer());\r
-    if (timeout) {\r
+    if (*timeout) {\r
         // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.  \r
 #ifndef HAVE_GMTIME_R\r
-        struct tm* ptime=gmtime(&timeout);\r
+        struct tm* ptime=gmtime(timeout);\r
 #else\r
         struct tm res;\r
-        struct tm* ptime=gmtime_r(&timeout,&res);\r
+        struct tm* ptime=gmtime_r(timeout,&res);\r
 #endif\r
         char timebuf[32];\r
         strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);\r
@@ -349,117 +271,12 @@ RemotedCache::~RemotedCache()
     delete shutdown_wait;\r
 }\r
 \r
-string RemotedCache::insert(\r
-    time_t expires,\r
-    const Application& application,\r
-    const char* client_addr,\r
-    const saml2md::EntityDescriptor* issuer,\r
-    const saml2::NameID& nameid,\r
-    const char* authn_instant,\r
-    const char* session_index,\r
-    const char* authncontext_class,\r
-    const char* authncontext_decl,\r
-    const RootObject* ssoToken,\r
-    const vector<Attribute*>* attributes\r
-    )\r
-{\r
-    DDF in("insert::"REMOTED_SESSION_CACHE);\r
-    DDFJanitor jin(in);\r
-    in.structure();\r
-    if (expires) {\r
-#ifndef HAVE_GMTIME_R\r
-        struct tm* ptime=gmtime(&expires);\r
-#else\r
-        struct tm res;\r
-        struct tm* ptime=gmtime_r(&expires,&res);\r
-#endif\r
-        char timebuf[32];\r
-        strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);\r
-        in.addmember("expires").string(timebuf);\r
-    }\r
-    in.addmember("application_id").string(application.getId());\r
-    in.addmember("client_addr").string(client_addr);\r
-    if (issuer) {\r
-        auto_ptr_char provid(issuer->getEntityID());\r
-        in.addmember("entity_id").string(provid.get());\r
-    }\r
-    if (authn_instant)\r
-        in.addmember("authn_instant").string(authn_instant);\r
-    if (session_index)\r
-        in.addmember("session_index").string(session_index);\r
-    if (authncontext_class)\r
-        in.addmember("authncontext_class").string(authncontext_class);\r
-    if (authncontext_decl)\r
-        in.addmember("authncontext_decl").string(authncontext_decl);\r
-    \r
-    ostringstream namestr;\r
-    namestr << nameid;\r
-    in.addmember("nameid").string(namestr.str().c_str());\r
-\r
-    if (ssoToken) {\r
-        ostringstream tstr;\r
-        tstr << *ssoToken;\r
-        auto_ptr_char tokenid(ssoToken->getID());\r
-        DDF tokid = DDF(NULL).string(tokenid.get());\r
-        in.addmember("assertions").list().add(tokid);\r
-        in.addmember("token").string(tstr.str().c_str());\r
-    }\r
-    \r
-    if (attributes) {\r
-        DDF attr;\r
-        DDF attrs = in.addmember("attributes").list();\r
-        for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a) {\r
-            attr = (*a)->marshall();\r
-            attrs.add(attr);\r
-        }\r
-    }\r
-\r
-    DDF out=application.getServiceProvider().getListenerService()->send(in);\r
-    DDFJanitor jout(out);\r
-    if (out["key"].isstring()) {\r
-        // Transaction Logging\r
-        auto_ptr_char name(nameid.getName());\r
-        const char* pid = in["entity_id"].string();\r
-        TransactionLog* xlog = application.getServiceProvider().getTransactionLog();\r
-        Locker locker(xlog);\r
-        xlog->log.infoStream() <<\r
-            "New session (ID: " <<\r
-                out["key"].string() <<\r
-            ") with (applicationId: " <<\r
-                application.getId() <<\r
-            ") for principal from (IdP: " <<\r
-                (pid ? pid : "none") <<\r
-            ") at (ClientAddress: " <<\r
-                client_addr <<\r
-            ") with (NameIdentifier: " <<\r
-                name.get() <<\r
-            ")";\r
-\r
-        if (attributes) {\r
-            xlog->log.infoStream() <<\r
-                "Cached the following attributes with session (ID: " <<\r
-                    out["key"].string() <<\r
-                ") for (applicationId: " <<\r
-                    application.getId() <<\r
-                ") {";\r
-            for (vector<Attribute*>::const_iterator a=attributes->begin(); a!=attributes->end(); ++a)\r
-                xlog->log.infoStream() << "\t" << (*a)->getId() << " (" << (*a)->valueCount() << " values)";\r
-            xlog->log.info("}");\r
-            for_each(attributes->begin(), attributes->end(), xmltooling::cleanup<Attribute>());\r
-        }\r
-\r
-        return out["key"].string();\r
-    }\r
-    throw RetryableProfileException("A remoted cache insertion operation did not return a usable session key.");\r
-}\r
-\r
-Session* RemotedCache::find(const char* key, const Application& application, const char* client_addr, time_t timeout)\r
+Session* RemotedCache::find(const char* key, const Application& application, const char* client_addr, time_t* timeout)\r
 {\r
 #ifdef _DEBUG\r
     xmltooling::NDC ndc("find");\r
 #endif\r
 \r
-    bool localValidation = false;\r
     RemotedSession* session=NULL;\r
     m_log.debug("searching local cache for session (%s)", key);\r
     m_lock->rdlock();\r
@@ -468,17 +285,18 @@ Session* RemotedCache::find(const char* key, const Application& application, con
         m_lock->unlock();\r
         m_log.debug("session not found locally, searching remote cache");\r
 \r
-        DDF in("find::"REMOTED_SESSION_CACHE), out;\r
+        DDF in("find::"REMOTED_SESSION_CACHE"::SessionCache"), out;\r
         DDFJanitor jin(in);\r
         in.structure();\r
         in.addmember("key").string(key);\r
-        if (timeout) {\r
+        in.addmember("application_id").string(application.getId());\r
+        if (timeout && *timeout) {\r
             // On 64-bit Windows, time_t doesn't fit in a long, so I'm using ISO timestamps.  \r
 #ifndef HAVE_GMTIME_R\r
-            struct tm* ptime=gmtime(&timeout);\r
+            struct tm* ptime=gmtime(timeout);\r
 #else\r
             struct tm res;\r
-            struct tm* ptime=gmtime_r(&timeout,&res);\r
+            struct tm* ptime=gmtime_r(timeout,&res);\r
 #endif\r
             char timebuf[32];\r
             strftime(timebuf,32,"%Y-%m-%dT%H:%M:%SZ",ptime);\r
@@ -496,7 +314,7 @@ Session* RemotedCache::find(const char* key, const Application& application, con
             // Wrap the results in a local entry and save it.\r
             session = new RemotedSession(this, out);\r
             // The remote end has handled timeout issues, we handle address and expiration checks.\r
-            localValidation = true;\r
+            timeout = NULL;\r
         }\r
         catch (...) {\r
             out.destroy();\r
@@ -507,9 +325,8 @@ Session* RemotedCache::find(const char* key, const Application& application, con
         m_lock->wrlock();\r
         SharedLock shared(m_lock, false);\r
         if (m_hashtable.count(key)) {\r
+            // We're using an existing session entry.\r
             delete session;\r
-            // We're using an existing session entry, so we have to switch back to full validation.\r
-            localValidation = false;\r
             session = m_hashtable[key];\r
             session->lock();\r
         }\r
@@ -533,32 +350,30 @@ Session* RemotedCache::find(const char* key, const Application& application, con
         return NULL;\r
     }\r
 \r
-    // Verify currency and update the timestamp.\r
-    // If the local switch is false, we also update the access time.\r
+    // Verify currency and update the timestamp if indicated by caller.\r
     try {\r
-        session->validate(application, client_addr, timeout, localValidation);\r
+        session->validate(application, client_addr, timeout);\r
     }\r
     catch (...) {\r
         session->unlock();\r
-        remove(key, application, client_addr);\r
+        remove(key, application);\r
         throw;\r
     }\r
     \r
     return session;\r
 }\r
 \r
-void RemotedCache::remove(const char* key, const Application& application, const char* client_addr)\r
+void RemotedCache::remove(const char* key, const Application& application)\r
 {\r
     // Take care of local copy.\r
     dormant(key);\r
     \r
     // Now remote...\r
-    DDF in("remove::"REMOTED_SESSION_CACHE);\r
+    DDF in("remove::"REMOTED_SESSION_CACHE"::SessionCache");\r
     DDFJanitor jin(in);\r
     in.structure();\r
     in.addmember("key").string(key);\r
     in.addmember("application_id").string(application.getId());\r
-    in.addmember("client_addr").string(client_addr);\r
     \r
     DDF out = application.getServiceProvider().getListenerService()->send(in);\r
     out.destroy();\r
@@ -602,17 +417,16 @@ void RemotedCache::cleanup()
     xmltooling::NDC ndc("cleanup");\r
 #endif\r
 \r
-    int rerun_timer = 0;\r
     Mutex* mutex = Mutex::create();\r
   \r
     // Load our configuration details...\r
     static const XMLCh cleanupInterval[] = UNICODE_LITERAL_15(c,l,e,a,n,u,p,I,n,t,e,r,v,a,l);\r
-    const XMLCh* tag=m_root->getAttributeNS(NULL,cleanupInterval);\r
+    const XMLCh* tag=m_root ? m_root->getAttributeNS(NULL,cleanupInterval) : NULL;\r
+    int rerun_timer = 900;\r
     if (tag && *tag)\r
         rerun_timer = XMLString::parseInt(tag);\r
-\r
     if (rerun_timer <= 0)\r
-        rerun_timer = 900;        // rerun every 5 minutes\r
+        rerun_timer = 900;\r
 \r
     mutex->lock();\r
 \r
@@ -674,57 +488,3 @@ void* RemotedCache::cleanup_fn(void* cache_p)
     cache->cleanup();\r
     return NULL;\r
 }\r
-\r
-/* These are currently unimplemented.\r
-\r
-void RemotedSession::addAttributes(const vector<Attribute*>& attributes)\r
-{\r
-    DDF in("addAttributes::"REMOTED_SESSION_CACHE);\r
-    DDFJanitor jin(in);\r
-    in.structure();\r
-    in.addmember("key").string(m_key.c_str());\r
-    in.addmember("application_id").string(m_appId.c_str());\r
-\r
-    DDF attr;\r
-    DDF attrs = in.addmember("attributes").list();\r
-    for (vector<Attribute*>::const_iterator a=attributes.begin(); a!=attributes.end(); ++a) {\r
-        attr = (*a)->marshall();\r
-        attrs.add(attr);\r
-    }\r
-\r
-    attr=SPConfig::getConfig().getServiceProvider()->getListenerService()->send(in);\r
-    DDFJanitor jout(attr);\r
-    \r
-    // Transfer ownership to us.\r
-    m_attributes.insert(m_attributes.end(), attributes.begin(), attributes.end());\r
-}\r
-\r
-void RemotedSession::addAssertion(RootObject* assertion)\r
-{\r
-    if (!assertion || !assertion->isAssertion())\r
-        throw FatalProfileException("Unknown object type passed to session cache for storage.");\r
-\r
-    DDF in("addAssertion::"REMOTED_SESSION_CACHE);\r
-    DDFJanitor jin(in);\r
-    in.structure();\r
-    in.addmember("key").string(m_key.c_str());\r
-    in.addmember("application_id").string(m_appId.c_str());\r
-    \r
-    ostringstream os;\r
-    os << *assertion;\r
-    string token(os.str());\r
-    auto_ptr_char tokenid(assertion->getID());\r
-    in.addmember("assertion_id").string(tokenid.get());\r
-    in.addmember("assertion").string(token.c_str());\r
-\r
-    DDF out = SPConfig::getConfig().getServiceProvider()->getListenerService()->send(in);\r
-    out.destroy();\r
-    \r
-    // Add to local record and token map.\r
-    // Next attempt to find and lock session will refresh from remote store anyway.\r
-    m_obj["assertions"].addmember(tokenid.get()).string(token.c_str());\r
-    m_ids.clear();\r
-    m_tokens[tokenid.get()] = assertion;\r
-}\r
-\r
-*/
\ No newline at end of file