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