Rework cached data, add (stubbed) statemgr RPC.
[shibboleth/cpp-sp.git] / shib-target / shib-target.h
1 /*
2  * The Shibboleth License, Version 1.
3  * Copyright (c) 2002
4  * University Corporation for Advanced Internet Development, Inc.
5  * All rights reserved
6  *
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
11  * Redistributions of source code must retain the above copyright notice, this
12  * list of conditions and the following disclaimer.
13  *
14  * Redistributions in binary form must reproduce the above copyright notice,
15  * this list of conditions and the following disclaimer in the documentation
16  * and/or other materials provided with the distribution, if any, must include
17  * the following acknowledgment: "This product includes software developed by
18  * the University Corporation for Advanced Internet Development
19  * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement
20  * may appear in the software itself, if and wherever such third-party
21  * acknowledgments normally appear.
22  *
23  * Neither the name of Shibboleth nor the names of its contributors, nor
24  * Internet2, nor the University Corporation for Advanced Internet Development,
25  * Inc., nor UCAID may be used to endorse or promote products derived from this
26  * software without specific prior written permission. For written permission,
27  * please contact shibboleth@shibboleth.org
28  *
29  * Products derived from this software may not be called Shibboleth, Internet2,
30  * UCAID, or the University Corporation for Advanced Internet Development, nor
31  * may Shibboleth appear in their name, without prior written permission of the
32  * University Corporation for Advanced Internet Development.
33  *
34  *
35  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
36  * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
38  * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK
39  * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE.
40  * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY
41  * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT,
42  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
43  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
44  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
46  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
47  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48  */
49
50 /*
51  * shib-target.h -- top-level header file for the SHIB Common Target Library
52  *
53  * Created by:  Derek Atkins <derek@ihtfp.com>
54  *
55  * $Id$
56  */
57
58 #ifndef SHIB_TARGET_H
59 #define SHIB_TARGET_H
60
61 #include <saml/saml.h>
62 #include <shib/shib.h>
63 #include <shib/shib-threads.h>
64
65 #ifdef WIN32
66 # ifndef SHIBTARGET_EXPORTS
67 #  define SHIBTARGET_EXPORTS __declspec(dllimport)
68 # endif
69 # define SHIB_SCHEMAS "/opt/shibboleth/share/xml/shibboleth"
70 # define SHIB_CONFIG "/opt/shibboleth/etc/shibboleth/shibboleth.xml"
71 #else
72 # include <shib-target/shib-paths.h>
73 # define SHIBTARGET_EXPORTS
74 #endif
75
76 #include <shib-target/shibrpc.h>
77
78 namespace shibtarget {
79   
80   //******************************************************************************
81   // You probably don't care about much below this line
82   // unless you are using the lower-layer APIs provided by
83   // the shib target library.  Go to the end of the file to
84   // find the ShibTarget class -- you probably wnat to use that.
85   //
86
87   class SHIBTARGET_EXPORTS ShibTargetException : public std::exception
88   {
89   public:
90     explicit ShibTargetException() : m_code(SHIBRPC_OK) {}
91     explicit ShibTargetException(ShibRpcStatus code, const char* msg, const shibboleth::IEntityDescriptor* provider);
92     explicit ShibTargetException(ShibRpcStatus code, const char* msg, const shibboleth::IRoleDescriptor* role=NULL);
93     
94     virtual ~ShibTargetException() throw () {}
95     virtual ShibRpcStatus which() const throw () { return m_code; }
96     virtual const char* what() const throw () { return m_msg.c_str(); }
97     virtual const char* syswho() const throw() { return m_providerId.c_str(); }
98     virtual const char* where() const throw () { return m_errorURL.c_str(); }
99     virtual const char* who() const throw () { return m_contact.c_str(); }
100     virtual const char* how() const throw () { return m_email.c_str(); }
101
102   private:
103     ShibRpcStatus m_code;
104     std::string m_msg;
105     std::string m_providerId;
106     std::string m_errorURL;
107     std::string m_contact;
108     std::string m_email;
109   };
110
111   class RPCErrorPriv;
112   class SHIBTARGET_EXPORTS RPCError
113   {
114   public:
115     RPCError();
116     RPCError(ShibRpcError* e);
117     RPCError(int s, const char* st);
118     RPCError(ShibTargetException &exp);
119     ~RPCError();
120
121     bool isError();
122     bool isRetryable();
123
124     // Return a set of strings that correspond to the error properties
125     const char* getType();
126     const char* getText();
127     const char* getDesc();
128     const char* getProviderId();
129     const char* getErrorURL();
130     const char* getContactName();
131     const char* getContactEmail();
132     int getCode();
133
134   private:
135     RPCErrorPriv* m_priv;
136   };
137
138     // Abstract APIs for access to configuration information
139     
140     struct SHIBTARGET_EXPORTS IPropertySet
141     {
142         virtual std::pair<bool,bool> getBool(const char* name, const char* ns=NULL) const=0;
143         virtual std::pair<bool,const char*> getString(const char* name, const char* ns=NULL) const=0;
144         virtual std::pair<bool,const XMLCh*> getXMLString(const char* name, const char* ns=NULL) const=0;
145         virtual std::pair<bool,unsigned int> getUnsignedInt(const char* name, const char* ns=NULL) const=0;
146         virtual std::pair<bool,int> getInt(const char* name, const char* ns=NULL) const=0;
147         virtual const IPropertySet* getPropertySet(const char* name, const char* ns="urn:mace:shibboleth:target:config:1.0") const=0;
148         virtual const DOMElement* getElement() const=0;
149         virtual ~IPropertySet() {}
150     };
151
152     struct SHIBTARGET_EXPORTS IListener : public virtual saml::IPlugIn
153     {
154 #ifdef WIN32
155         typedef SOCKET ShibSocket;
156 #else
157         typedef int ShibSocket;
158 #endif
159         virtual bool create(ShibSocket& s) const=0;
160         virtual bool bind(ShibSocket& s, bool force=false) const=0;
161         virtual bool connect(ShibSocket& s) const=0;
162         virtual bool close(ShibSocket& s) const=0;
163         virtual bool accept(ShibSocket& listener, ShibSocket& s) const=0;
164         virtual CLIENT* getClientHandle(ShibSocket& s, u_long program, u_long version) const=0;
165         virtual ~IListener() {}
166     };
167
168     struct SHIBTARGET_EXPORTS IAccessControl : public virtual saml::ILockable, public virtual saml::IPlugIn
169     {
170         virtual bool authorized(
171             const saml::SAMLAuthenticationStatement& authn, const saml::Iterator<saml::SAMLAssertion*>& attrs
172             ) const=0;
173         virtual ~IAccessControl() {}
174     };
175
176     struct SHIBTARGET_EXPORTS IRequestMapper : public virtual saml::ILockable, public virtual saml::IPlugIn
177     {
178         typedef std::pair<const IPropertySet*,IAccessControl*> Settings;
179         virtual Settings getSettingsFromURL(const char* url) const=0;
180         virtual Settings getSettingsFromParsedURL(
181             const char* scheme, const char* hostname, unsigned int port, const char* path=NULL
182             ) const=0;
183         virtual ~IRequestMapper() {}
184     };
185     
186     struct SHIBTARGET_EXPORTS IApplication : public virtual IPropertySet
187     {
188         virtual const char* getId() const=0;
189         virtual saml::Iterator<saml::SAMLAttributeDesignator*> getAttributeDesignators() const=0;
190         virtual saml::Iterator<shibboleth::IAAP*> getAAPProviders() const=0;
191         virtual saml::Iterator<shibboleth::IMetadata*> getMetadataProviders() const=0;
192         virtual saml::Iterator<shibboleth::ITrust*> getTrustProviders() const=0;
193         virtual saml::Iterator<shibboleth::IRevocation*> getRevocationProviders() const=0;
194         virtual saml::Iterator<const XMLCh*> getAudiences() const=0;
195         virtual const IPropertySet* getCredentialUse(const shibboleth::IEntityDescriptor* provider) const=0;
196
197         // caller is borrowing object, must use within scope of config lock
198         virtual const saml::SAMLBrowserProfile* getBrowserProfile() const=0;
199         virtual const saml::SAMLBinding* getBinding(const XMLCh* binding) const=0;
200
201         // caller is given ownership of object, must use and delete within scope of config lock
202         virtual saml::SAMLBrowserProfile::ArtifactMapper* getArtifactMapper() const=0;
203
204         virtual ~IApplication() {}
205     };
206
207     struct SHIBTARGET_EXPORTS ISessionCacheEntry : public virtual saml::ILockable
208     {
209         virtual bool isValid(time_t lifetime, time_t timeout) const=0;
210         virtual const char* getClientAddress() const=0;
211         virtual ShibProfile getProfile() const=0;
212         virtual const char* getProviderId() const=0;
213         virtual const saml::SAMLAuthenticationStatement* getAuthnStatement() const=0;
214         virtual const saml::SAMLResponse* getResponse(bool filtered=true)=0;
215         virtual ~ISessionCacheEntry() {}
216     };
217
218     struct SHIBTARGET_EXPORTS ISessionCache : public virtual saml::IPlugIn
219     {
220         virtual void thread_init()=0;
221         virtual void thread_end()=0;
222         virtual std::string generateKey() const=0;
223         virtual void insert(
224             const char* key,
225             const IApplication* application,
226             const char* client_addr,
227             ShibProfile profile,
228             const char* providerId,
229             saml::SAMLAuthenticationStatement* s,
230             saml::SAMLResponse* r=NULL,
231             const shibboleth::IRoleDescriptor* source=NULL
232             )=0;
233         virtual ISessionCacheEntry* find(const char* key, const IApplication* application)=0;
234         virtual void remove(const char* key)=0;
235         virtual ~ISessionCache() {}
236     };
237
238     struct SHIBTARGET_EXPORTS IConfig : public virtual saml::ILockable, public virtual IPropertySet, public virtual saml::IPlugIn
239     {
240         virtual const IListener* getListener() const=0;
241         virtual ISessionCache* getSessionCache() const=0;
242         virtual saml::IReplayCache* getReplayCache() const=0;
243         virtual IRequestMapper* getRequestMapper() const=0;
244         virtual const IApplication* getApplication(const char* applicationId) const=0;
245         virtual saml::Iterator<shibboleth::ICredentials*> getCredentialsProviders() const=0;
246         virtual ~IConfig() {}
247     };
248
249     class SHIBTARGET_EXPORTS ShibTargetConfig
250     {
251     public:
252         ShibTargetConfig() : m_ini(NULL), m_features(0) {}
253         virtual ~ShibTargetConfig() {}
254
255         virtual bool init(const char* schemadir, const char* config) = 0;
256         virtual void shutdown() = 0;
257
258         enum components_t {
259             Listener = 1,
260             SessionCache = 2,
261             Metadata = 4,
262             Trust = 8,
263             Credentials = 16,
264             AAP = 32,
265             RequestMapper = 64,
266             GlobalExtensions = 128,
267             LocalExtensions = 256,
268             Logging = 512
269         };
270         void setFeatures(long enabled) {m_features = enabled;}
271         bool isEnabled(components_t feature) {return (m_features & feature)>0;}
272         virtual IConfig* getINI() const {return m_ini;}
273
274         static const XMLCh SHIBTARGET_NS[];
275         static ShibTargetConfig& getConfig();
276
277     protected:
278         IConfig* m_ini;
279         
280     private:
281         unsigned long m_features;
282     };
283
284     class ShibMLPPriv;
285     class SHIBTARGET_EXPORTS ShibMLP {
286     public:
287         ShibMLP();
288         ~ShibMLP();
289
290         void insert (const std::string& key, const std::string& value);
291         void insert (const std::string& key, const char* value) {
292           std::string v = value;
293           insert (key, v);
294         }
295         void insert (const char* key, const std::string& value) {
296           std::string k = key;
297           insert (k, value);
298         }
299         void insert (const char* key, const char* value) {
300           std::string k = key, v = value;
301           insert(k,v);
302         }
303         void insert (RPCError& e);
304
305         void clear () { m_map.clear(); }
306
307         const char* run (std::istream& s, const IPropertySet* props=NULL, std::string* output=NULL);
308         const char* run (const std::string& input, const IPropertySet* props=NULL, std::string* output=NULL);
309         const char* run (const char* input, const IPropertySet* props=NULL, std::string* output=NULL) {
310             std::string i = input;
311             return run(i,props,output);
312         }
313
314     private:
315         ShibMLPPriv *m_priv;
316         std::map<std::string,std::string> m_map;
317         std::string m_generated;
318     };
319
320   //******************************************************************************
321   //
322   // This is the interface you're looking for.
323   //
324
325   class HTAccessInfo {
326   public:
327     class RequireLine {
328     public:
329       bool use_line;
330       std::vector<std::string> tokens;
331     };
332
333     HTAccessInfo() {}
334     ~HTAccessInfo() {
335       for (int k = 0; k < elements.size(); k++)
336         delete elements[k];
337       elements.resize(0);
338     }
339
340     std::vector<RequireLine*> elements;
341     bool requireAll;
342   };
343
344   class HTGroupTable {
345   public:
346     virtual ~HTGroupTable() {}
347     virtual bool lookup(const char *entry) = 0;
348   protected:
349     HTGroupTable() {}
350   };
351
352   // This usurps the existing SHIRE and RM apis into a single class.
353   class ShibTargetPriv;
354   class SHIBTARGET_EXPORTS ShibTarget {
355   public:
356     ShibTarget(const IApplication *app);
357     virtual ~ShibTarget(void);
358
359     // These are defined here so the subclass does not need to specifically
360     // depend on log4cpp.  We could use log4cpp::Priority::PriorityLevel
361     // but this is just as easy, IMHO.  It's just a case statement in the
362     // implementation to handle the event level.
363     enum ShibLogLevel {
364       LogLevelDebug,
365       LogLevelInfo,
366       LogLevelWarn,
367       LogLevelError
368     };
369
370     //
371     // Note: subclasses MUST implement ALL of these virtual methods
372     //
373
374     // Send a message to the Webserver log
375     virtual void log(ShibLogLevel level, const std::string &msg)=0;
376
377     void log(ShibLogLevel level, const char *msg) {
378       std::string s = msg;
379       log(level, s);
380     }
381
382     // Get/Set a cookie for this connection
383     virtual std::string getCookies(void)=0;
384     virtual void setCookie(const std::string &name, const std::string &value)=0;
385
386     void setCookie(const char *name, const char *value) {
387       std::string ns = name;
388       std::string vs = value;
389       setCookie(ns, vs);
390     }
391     void setCookie(const char *name, const std::string &value) {
392       std::string ns = name;
393       setCookie(ns, value);
394     }
395
396
397     // Get the request's GET arguments or POST data from the server
398     virtual std::string getArgs(void)=0;
399     virtual std::string getPostData(void)=0;
400
401     // Clear a header, set a header
402     // These APIs are used for exporting the Assertions into the
403     // Headers.  It will clear some well-known headers first to make
404     // sure none remain.  Then it will process the set of assertions
405     // and export them via setHeader().
406     virtual void clearHeader(const std::string &name)=0;
407     virtual void setHeader(const std::string &name, const std::string &value)=0;
408     virtual std::string getHeader(const std::string &name)=0;
409     virtual void setRemoteUser(const std::string &user)=0;
410     virtual std::string getRemoteUser(void)=0;
411
412     void clearHeader(const char *n) {
413       std::string s = n;
414       clearHeader(s);
415     }
416     void setHeader(const char *n, const char *v) {
417       std::string ns = n;
418       std::string vs = v;
419       setHeader(ns, vs);
420     }
421     void setHeader(const std::string &n, const char *v) {
422       std::string vs = v;
423       setHeader(n, vs);
424     }
425     void setHeader(const char *n, const std::string &v) {
426       std::string ns = n;
427       setHeader(ns, v);
428     }
429     std::string getHeader(const char *n) {
430       std::string s = n;
431       return getHeader(s);
432     }
433     void setRemoteUser(const char *n) {
434       std::string s = n;
435       setRemoteUser(s);
436     }
437
438     // returns the "auth type"..  if this string is not "shibboleth" then
439     // the request will be denied.  Any kind of "override" should be handled
440     // by the subclass before returning this value.  Note that the default
441     // implementation always returns "shibboleth".
442     virtual std::string getAuthType(void);
443
444     // Note: we still need to define exactly what kind of data in contained
445     // in the HTAccessInfo -- perhaps we can stub it out so non-htaccess
446     // systems have something they can plug in?
447     virtual HTAccessInfo* getAccessInfo(void);
448     virtual HTGroupTable* getGroupTable(std::string &user);
449
450     // We're done.  Finish up.  Send either a result (error?) page or a redirect.
451     // If there are no headers supplied assume the content-type == text/html
452     typedef std::pair<std::string, std::string> header_t;
453     virtual void* sendPage(
454                            const std::string &msg,
455                            const std::string content_type = "text/html",
456                            const saml::Iterator<header_t>& headers = EMPTY(header_t),
457                            int code = 200
458                            )=0;
459     void* sendPage(const char *msg) {
460       std::string m = msg;
461       return sendPage(m);
462     }
463
464     virtual void* sendRedirect(const std::string url)=0;
465
466     // These next two APIs are used to obtain the module-specific "OK"
467     // and "Decline" results.  OK means "we believe that this request
468     // should be accepted".  Declined means "we believe that this is
469     // not a shibbolized request so we have no comment".
470
471     virtual void* returnDecline(void);
472     virtual void* returnOK(void);
473
474     //
475     // Note:  Subclasses need not implement anything below this line
476     //
477
478     // These functions implement the server-agnostic shibboleth engine
479     // The web server modules implement a subclass and then call into 
480     // these methods once they instantiate their request object.
481     // 
482     // Return value:
483     //   these APIs will always return the result of sendPage(), sendRedirect(),
484     //   returnDecline(), or returnOK() in the void* portion of the return code.
485     //   Exactly what those values are is module- (subclass-) implementation
486     //   specific.  The 'bool' part of the return value declares whether the
487     //   void* is valid or not.  If the bool is true then the void* is valid.
488     //   If the bool is false then the API did not call any callback, the void*
489     //   is not valid, and the caller should continue processing (the API Call
490     //   finished successfully).
491     //
492     //   The arguments are all overrides..  The requireSession and
493     //   exportAssertion values passed in here are only used if the
494     //   settings resource is negative.
495     //
496     //   The handleProfile argument declares whether doCheckAuthN() should
497     //   automatically call doHandlePOST() when it encounters a request for
498     //   the ShireURL;  if false it will call returnOK() instead.
499     //
500     std::pair<bool,void*> doCheckAuthN(bool requireSession = false, bool handleProfile = false);
501     std::pair<bool,void*> doHandleProfile();
502     std::pair<bool,void*> doCheckAuthZ();
503     std::pair<bool,void*> doExportAssertions(bool exportAssertion = false);
504
505     //**************************************************************************
506     // These APIs are for backwards-compatibility.  Hopefully they can
507     // eventually go away.
508
509     // SHIRE APIs
510
511     // Get the session cookie name and properties for the application
512     std::pair<const char*,const char*> getCookieNameProps() const;
513         
514     // Find the default assertion consumer service for the resource
515     const char* getShireURL(const char* resource) const;
516         
517     // Generate a Shib 1.x AuthnRequest redirect URL for the resource
518     const char* getAuthnRequest(const char* resource) const;
519         
520     // Process a lazy session setup request and turn it into an AuthnRequest
521     const char* getLazyAuthnRequest(const char* query_string) const;
522         
523   protected:
524     ShibTarget();
525
526     // Currently wraps remoted interface.
527     // TODO: Move this functionality behind ISessionCache
528     RPCError* stateMgr(
529         const char* packet,
530         const char* ip,
531         std::string& cookie
532         ) const;
533     
534     RPCError* sessionNew(
535         int supported_profiles,
536         const char* packet,
537         const char* statemgr_cookie,
538         const char* ip,
539         std::string& cookie,
540         std::string& target,
541         std::string& statemgr_packet
542         ) const;
543
544     RPCError* sessionGet(
545         const char* cookie,
546         const char* ip,
547         ShibProfile& profile,
548         std::string& provider_id,
549         saml::SAMLAuthenticationStatement** auth_statement=NULL,
550         saml::SAMLResponse** attr_response_pre=NULL,
551         saml::SAMLResponse** attr_response_post=NULL
552         ) const;
553
554     // Initialize the request from the parsed URL
555     // protocol == http, https, etc
556     // hostname == server name
557     // port == server port
558     // uri == resource path
559     // method == GET, POST, etc.
560     void init(ShibTargetConfig *config,
561               std::string protocol, std::string hostname, int port,
562               std::string uri, std::string content_type, std::string remote_host,
563               std::string method);
564
565   private:
566     mutable ShibTargetPriv *m_priv;
567   };
568 }
569
570 #endif /* SHIB_TARGET_H */