Update initialization logic to match rest of code.
[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/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
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         return -10;
141     }
142
143     if (!a_param)
144         a_param="default";
145
146     if (n_param) {
147         if (!protocol) {
148             if (prot)
149                 protocol = XMLString::transcode(prot);
150         }
151         if (!protocol) {
152             usage();
153             return -10;
154         }
155     }
156
157     SPConfig& conf=SPConfig::getConfig();
158     conf.setFeatures(
159         SPConfig::Metadata |
160         SPConfig::Trust |
161         SPConfig::AttributeResolution |
162         SPConfig::Credentials |
163         SPConfig::OutOfProcess
164         );
165     if (!conf.init())
166         return -1;
167     if (!conf.instantiate()) {
168         conf.term();
169         return -2;
170     }
171
172     ServiceProvider* sp=conf.getServiceProvider();
173     sp->lock();
174
175     Category& log = Category::getInstance(SHIBSP_LOGCAT".Utility.ResolverTest");
176
177     const Application* app = sp->getApplication(a_param);
178     if (!app) {
179         log.error("unknown application ID (%s)", a_param);
180         sp->unlock();
181         conf.term();
182         return -3;
183     }
184
185     try {
186         ResolutionContext* ctx;
187
188         if (n_param) {
189             auto_ptr_XMLCh issuer(i_param);
190             auto_ptr_XMLCh name(n_param);
191             auto_ptr_XMLCh format(f_param);
192
193             MetadataProvider* m=app->getMetadataProvider();
194             xmltooling::Locker mlocker(m);
195             MetadataProviderCriteria mc(*app, i_param, &IDPSSODescriptor::ELEMENT_QNAME, protocol);
196             pair<const EntityDescriptor*,const RoleDescriptor*> site=m->getEntityDescriptor(mc);
197             if (!site.first)
198                 throw MetadataException("Unable to locate metadata for IdP ($1).", params(1,i_param));
199
200             // Build NameID(s).
201             auto_ptr<saml2::NameID> v2name(saml2::NameIDBuilder::buildNameID());
202             v2name->setName(name.get());
203             v2name->setFormat(format.get());
204             saml1::NameIdentifier* v1name = NULL;
205             if (!XMLString::equals(protocol, samlconstants::SAML20P_NS)) {
206                 v1name = saml1::NameIdentifierBuilder::buildNameIdentifier();
207                 v1name->setName(name.get());
208                 v1name->setFormat(format.get());
209                 v1name->setNameQualifier(issuer.get());
210             }
211
212             ResolverTest rt(NULL, a_param);
213             try {
214                 ctx = rt.resolveAttributes(*app, site.second, protocol, v1name, v2name.get(), NULL, NULL, NULL);
215             }
216             catch (...) {
217                 delete v1name;
218                 throw;
219             }
220         }
221         else {
222             // Try and load assertion from stdin.
223             DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(cin);
224             XercesJanitor<DOMDocument> docjan(doc);
225             auto_ptr<XMLObject> token(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
226             docjan.release();
227
228             // Get the issuer and protocol and NameIDs.
229             const XMLCh* issuer = NULL;
230             const saml1::NameIdentifier* v1name = NULL;
231             saml2::NameID* v2name = NULL;
232             saml2::Assertion* a2 = dynamic_cast<saml2::Assertion*>(token.get());
233             saml1::Assertion* a1 = dynamic_cast<saml1::Assertion*>(token.get());
234             if (a2) {
235                 const saml2::Issuer* iss = a2->getIssuer();
236                 issuer = iss ? iss->getName() : NULL;
237                 protocol = samlconstants::SAML20P_NS;
238                 v2name = a2->getSubject() ? a2->getSubject()->getNameID() : NULL;
239             }
240             else if (a1) {
241                 issuer = a1->getIssuer();
242                 if (a1->getMinorVersion().first && a1->getMinorVersion().second == 0)
243                     protocol = samlconstants::SAML10_PROTOCOL_ENUM;
244                 else
245                     protocol = samlconstants::SAML11_PROTOCOL_ENUM;
246                 v1name = a1->getAuthenticationStatements().size() ?
247                     a1->getAuthenticationStatements().front()->getSubject()->getNameIdentifier() : NULL;
248                 // Normalize the SAML 1.x NameIdentifier...
249                 v2name = saml2::NameIDBuilder::buildNameID();
250                 v2name->setName(v1name->getName());
251                 v2name->setFormat(v1name->getFormat());
252                 v2name->setNameQualifier(v1name->getNameQualifier());
253             }
254             else {
255                 throw FatalProfileException("Unknown assertion type.");
256             }
257
258             if (!issuer) {
259                 if (v1name)
260                     delete v2name;
261                 throw FatalProfileException("Unable to determine issuer.");
262             }
263
264             MetadataProvider* m=app->getMetadataProvider();
265             xmltooling::Locker mlocker(m);
266             MetadataProviderCriteria mc(*app, issuer, &IDPSSODescriptor::ELEMENT_QNAME, protocol);
267             pair<const EntityDescriptor*,const RoleDescriptor*> site=m->getEntityDescriptor(mc);
268             if (!site.first) {
269                 auto_ptr_char temp(issuer);
270                 throw MetadataException("Unable to locate metadata for IdP ($1).", params(1,temp.get()));
271             }
272             
273             vector<const Assertion*> tokens(1, dynamic_cast<Assertion*>(token.get()));
274             ResolverTest rt(NULL, a_param);
275             try {
276                 ctx = rt.resolveAttributes(*app, site.second, protocol, v1name, v2name, NULL, NULL, &tokens);
277             }
278             catch (...) {
279                 if (v1name)
280                     delete v2name;
281                 throw;
282             }
283         }
284
285         auto_ptr<ResolutionContext> wrapper(ctx);
286         for (vector<Attribute*>::const_iterator a = ctx->getResolvedAttributes().begin(); a != ctx->getResolvedAttributes().end(); ++a) {
287             cout << endl;
288             for (vector<string>::const_iterator s = (*a)->getAliases().begin(); s != (*a)->getAliases().end(); ++s)
289                 cout << "ID: " << *s << endl;
290             for (vector<string>::const_iterator s = (*a)->getSerializedValues().begin(); s != (*a)->getSerializedValues().end(); ++s)
291                 cout << "Value: " << *s << endl;
292         }
293         cout << endl;
294     }
295     catch(exception& ex) {
296         log.error(ex.what());
297         sp->unlock();
298         conf.term();
299         return -10;
300     }
301
302     sp->unlock();
303     conf.term();
304     return 0;
305 }