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