43a0e49b38579c7f4d0bc9307a9e0ef3edab64e5
[shibboleth/sp.git] / util / resolvertest.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  * resolvertest.cpp
19  * 
20  * Tool to exercise SP attribute subsystems.
21  */
22
23 #if defined (_MSC_VER) || defined(__BORLANDC__)
24 # include "config_win32.h"
25 #else
26 # include "config.h"
27 #endif
28
29 #ifdef WIN32
30 # define _CRT_NONSTDC_NO_DEPRECATE 1
31 # define _CRT_SECURE_NO_DEPRECATE 1
32 #endif
33
34 #include <shibsp/Application.h>
35 #include <shibsp/exceptions.h>
36 #include <shibsp/SPConfig.h>
37 #include <shibsp/ServiceProvider.h>
38 #include <shibsp/attribute/Attribute.h>
39 #include <shibsp/attribute/resolver/ResolutionContext.h>
40 #include <shibsp/handler/AssertionConsumerService.h>
41 #include <shibsp/metadata/MetadataProviderCriteria.h>
42 #include <shibsp/util/SPConstants.h>
43
44 #include <saml/saml1/core/Assertions.h>
45 #include <saml/saml2/core/Assertions.h>
46 #include <saml/saml2/metadata/Metadata.h>
47 #include <xercesc/util/XMLUniDefs.hpp>
48 #include <xmltooling/XMLToolingConfig.h>
49 #include <xmltooling/util/XMLHelper.h>
50
51 using namespace shibsp;
52 using namespace opensaml::saml2md;
53 using namespace opensaml;
54 using namespace xmltooling::logging;
55 using namespace xmltooling;
56 using namespace xercesc;
57 using namespace std;
58
59 #if defined (_MSC_VER)
60     #pragma warning( push )
61     #pragma warning( disable : 4250 )
62 #endif
63
64 class ResolverTest : public shibsp::AssertionConsumerService
65 {
66 public:
67     ResolverTest(const DOMElement* e, const char* appId)
68         : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".Utilities.ResolverTest")) {
69     }
70     virtual ~ResolverTest() {}
71     
72     ResolutionContext* resolveAttributes (
73         const Application& application,
74         const RoleDescriptor* issuer,
75         const XMLCh* protocol,
76         const saml1::NameIdentifier* v1nameid,
77         const saml2::NameID* nameid,
78         const XMLCh* authncontext_class,
79         const XMLCh* authncontext_decl,
80         const vector<const Assertion*>* tokens
81         ) const {
82         return shibsp::AssertionConsumerService::resolveAttributes(
83             application, issuer, protocol, v1nameid, nameid, authncontext_class, authncontext_decl, tokens
84             );
85     }
86
87 private:
88     void implementProtocol(
89         const Application& application,
90         const HTTPRequest& httpRequest,
91         HTTPResponse& httpResponse,
92         SecurityPolicy& policy,
93         const PropertySet* settings,
94         const XMLObject& xmlObject
95         ) const {
96             throw FatalProfileException("Should never be called.");
97     }
98 };
99
100 #if defined (_MSC_VER)
101     #pragma warning( pop )
102 #endif
103
104 void usage()
105 {
106     cerr << "usage: resolvertest -n <name> -i <IdP> -p <protocol> [-f <format URI> -a <application id>]" << endl;
107     cerr << "       resolvertest [-a <application id>] < assertion.xml" << endl;
108 }
109
110 int main(int argc,char* argv[])
111 {
112     char* a_param=NULL;
113     char* n_param=NULL;
114     char* f_param=NULL;
115     char* i_param=NULL;
116     char* prot = NULL;
117     const XMLCh* protocol = NULL;
118     char* path=NULL;
119     char* config=NULL;
120
121     for (int i=1; i<argc; i++) {
122         if (!strcmp(argv[i],"-n") && i+1<argc)
123             n_param=argv[++i];
124         else if (!strcmp(argv[i],"-f") && i+1<argc)
125             f_param=argv[++i];
126         else if (!strcmp(argv[i],"-i") && i+1<argc)
127             i_param=argv[++i];
128         else if (!strcmp(argv[i],"-p") && i+1<argc)
129             prot=argv[++i];
130         else if (!strcmp(argv[i],"-saml10"))
131             protocol=samlconstants::SAML10_PROTOCOL_ENUM;
132         else if (!strcmp(argv[i],"-saml11"))
133             protocol=samlconstants::SAML11_PROTOCOL_ENUM;
134         else if (!strcmp(argv[i],"-saml2"))
135             protocol=samlconstants::SAML20P_NS;
136         else if (!strcmp(argv[i],"-a") && i+1<argc)
137             a_param=argv[++i];
138     }
139
140     if (n_param && !i_param) {
141         usage();
142         exit(-10);
143     }
144
145     path=getenv("SHIBSP_SCHEMAS");
146     if (!path)
147         path=SHIBSP_SCHEMAS;
148     config=getenv("SHIBSP_CONFIG");
149     if (!config)
150         config=SHIBSP_CONFIG;
151     if (!a_param)
152         a_param="default";
153
154     XMLToolingConfig::getConfig().log_config(getenv("SHIBSP_LOGGING") ? getenv("SHIBSP_LOGGING") : SHIBSP_LOGGING);
155
156     SPConfig& conf=SPConfig::getConfig();
157     conf.setFeatures(
158         SPConfig::Metadata |
159         SPConfig::Trust |
160         SPConfig::AttributeResolution |
161         SPConfig::Credentials |
162         SPConfig::OutOfProcess
163         );
164     if (!conf.init(path))
165         return -1;
166
167     if (n_param) {
168         if (!protocol) {
169             if (prot)
170                 protocol = XMLString::transcode(prot);
171         }
172         if (!protocol) {
173             conf.term();
174             usage();
175             exit(-10);
176         }
177     }
178    
179     try {
180         static const XMLCh path[] = UNICODE_LITERAL_4(p,a,t,h);
181         static const XMLCh validate[] = UNICODE_LITERAL_8(v,a,l,i,d,a,t,e);
182         xercesc::DOMDocument* dummydoc=XMLToolingConfig::getConfig().getParser().newDocument();
183         XercesJanitor<xercesc::DOMDocument> docjanitor(dummydoc);
184         xercesc::DOMElement* dummy = dummydoc->createElementNS(NULL,path);
185         auto_ptr_XMLCh src(config);
186         dummy->setAttributeNS(NULL,path,src.get());
187         dummy->setAttributeNS(NULL,validate,xmlconstants::XML_ONE);
188
189         conf.setServiceProvider(conf.ServiceProviderManager.newPlugin(XML_SERVICE_PROVIDER,dummy));
190         conf.getServiceProvider()->init();
191     }
192     catch (exception&) {
193         conf.term();
194         return -2;
195     }
196
197     ServiceProvider* sp=conf.getServiceProvider();
198     sp->lock();
199
200     Category& log = Category::getInstance(SHIBSP_LOGCAT".Utility.ResolverTest");
201
202     const Application* app = sp->getApplication(a_param);
203     if (!app) {
204         log.error("unknown application ID (%s)", a_param);
205         sp->unlock();
206         conf.term();
207         return -3;
208     }
209
210     try {
211         ResolutionContext* ctx;
212
213         if (n_param) {
214             auto_ptr_XMLCh issuer(i_param);
215             auto_ptr_XMLCh name(n_param);
216             auto_ptr_XMLCh format(f_param);
217
218             MetadataProvider* m=app->getMetadataProvider();
219             xmltooling::Locker mlocker(m);
220             MetadataProviderCriteria mc(*app, i_param, &IDPSSODescriptor::ELEMENT_QNAME, protocol);
221             pair<const EntityDescriptor*,const RoleDescriptor*> site=m->getEntityDescriptor(mc);
222             if (!site.first)
223                 throw MetadataException("Unable to locate metadata for IdP ($1).", params(1,i_param));
224
225             // Build NameID(s).
226             auto_ptr<saml2::NameID> v2name(saml2::NameIDBuilder::buildNameID());
227             v2name->setName(name.get());
228             v2name->setFormat(format.get());
229             saml1::NameIdentifier* v1name = NULL;
230             if (!XMLString::equals(protocol, samlconstants::SAML20P_NS)) {
231                 v1name = saml1::NameIdentifierBuilder::buildNameIdentifier();
232                 v1name->setName(name.get());
233                 v1name->setFormat(format.get());
234                 v1name->setNameQualifier(issuer.get());
235             }
236
237             ResolverTest rt(NULL, a_param);
238             try {
239                 ctx = rt.resolveAttributes(*app, site.second, protocol, v1name, v2name.get(), NULL, NULL, NULL);
240             }
241             catch (...) {
242                 delete v1name;
243                 throw;
244             }
245         }
246         else {
247             // Try and load assertion from stdin.
248             DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(cin);
249             XercesJanitor<DOMDocument> docjan(doc);
250             auto_ptr<XMLObject> token(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
251             docjan.release();
252
253             // Get the issuer and protocol and NameIDs.
254             const XMLCh* issuer = NULL;
255             const saml1::NameIdentifier* v1name = NULL;
256             saml2::NameID* v2name = NULL;
257             saml2::Assertion* a2 = dynamic_cast<saml2::Assertion*>(token.get());
258             saml1::Assertion* a1 = dynamic_cast<saml1::Assertion*>(token.get());
259             if (a2) {
260                 const saml2::Issuer* iss = a2->getIssuer();
261                 issuer = iss ? iss->getName() : NULL;
262                 protocol = samlconstants::SAML20P_NS;
263                 v2name = a2->getSubject() ? a2->getSubject()->getNameID() : NULL;
264             }
265             else if (a1) {
266                 issuer = a1->getIssuer();
267                 if (a1->getMinorVersion().first && a1->getMinorVersion().second == 0)
268                     protocol = samlconstants::SAML10_PROTOCOL_ENUM;
269                 else
270                     protocol = samlconstants::SAML11_PROTOCOL_ENUM;
271                 v1name = a1->getAuthenticationStatements().size() ?
272                     a1->getAuthenticationStatements().front()->getSubject()->getNameIdentifier() : NULL;
273                 // Normalize the SAML 1.x NameIdentifier...
274                 v2name = saml2::NameIDBuilder::buildNameID();
275                 v2name->setName(v1name->getName());
276                 v2name->setFormat(v1name->getFormat());
277                 v2name->setNameQualifier(v1name->getNameQualifier());
278             }
279             else {
280                 throw FatalProfileException("Unknown assertion type.");
281             }
282
283             if (!issuer) {
284                 if (v1name)
285                     delete v2name;
286                 throw FatalProfileException("Unable to determine issuer.");
287             }
288
289             MetadataProvider* m=app->getMetadataProvider();
290             xmltooling::Locker mlocker(m);
291             MetadataProviderCriteria mc(*app, issuer, &IDPSSODescriptor::ELEMENT_QNAME, protocol);
292             pair<const EntityDescriptor*,const RoleDescriptor*> site=m->getEntityDescriptor(mc);
293             if (!site.first) {
294                 auto_ptr_char temp(issuer);
295                 throw MetadataException("Unable to locate metadata for IdP ($1).", params(1,temp.get()));
296             }
297             
298             vector<const Assertion*> tokens(1, dynamic_cast<Assertion*>(token.get()));
299             ResolverTest rt(NULL, a_param);
300             try {
301                 ctx = rt.resolveAttributes(*app, site.second, protocol, v1name, v2name, NULL, NULL, &tokens);
302             }
303             catch (...) {
304                 if (v1name)
305                     delete v2name;
306                 throw;
307             }
308         }
309
310         auto_ptr<ResolutionContext> wrapper(ctx);
311         for (vector<Attribute*>::const_iterator a = ctx->getResolvedAttributes().begin(); a != ctx->getResolvedAttributes().end(); ++a) {
312             cout << endl;
313             for (vector<string>::const_iterator s = (*a)->getAliases().begin(); s != (*a)->getAliases().end(); ++s)
314                 cout << "ID: " << *s << endl;
315             for (vector<string>::const_iterator s = (*a)->getSerializedValues().begin(); s != (*a)->getSerializedValues().end(); ++s)
316                 cout << "Value: " << *s << endl;
317         }
318         cout << endl;
319     }
320     catch(exception& ex) {
321         log.error(ex.what());
322         sp->unlock();
323         conf.term();
324         return -10;
325     }
326
327     sp->unlock();
328     conf.term();
329     return 0;
330 }