Clean up some settings and add VC project files for plugins project.
[shibboleth/cpp-sp.git] / util / resolvertest.cpp
1 /**
2  * Licensed to the University Corporation for Advanced Internet
3  * Development, Inc. (UCAID) under one or more contributor license
4  * agreements. See the NOTICE file distributed with this work for
5  * additional information regarding copyright ownership.
6  *
7  * UCAID licenses this file to you under the Apache License,
8  * Version 2.0 (the "License"); you may not use this file except
9  * in compliance with the License. You may obtain a copy of the
10  * License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
17  * either express or implied. See the License for the specific
18  * language governing permissions and limitations under the License.
19  */
20
21 /**
22  * resolvertest.cpp
23  * 
24  * Tool to exercise SP attribute subsystems.
25  */
26
27 #if defined (_MSC_VER) || defined(__BORLANDC__)
28 # include "config_win32.h"
29 #else
30 # include "config.h"
31 #endif
32
33 #ifdef WIN32
34 # define _CRT_NONSTDC_NO_DEPRECATE 1
35 # define _CRT_SECURE_NO_DEPRECATE 1
36 #endif
37
38 #include <shibsp/Application.h>
39 #include <shibsp/SPConfig.h>
40 #include <shibsp/ServiceProvider.h>
41 #include <shibsp/attribute/Attribute.h>
42 #include <shibsp/attribute/resolver/ResolutionContext.h>
43 #include <shibsp/handler/AssertionConsumerService.h>
44 #include <shibsp/metadata/MetadataProviderCriteria.h>
45 #include <shibsp/util/SPConstants.h>
46
47 #include <saml/exceptions.h>
48 #include <saml/saml1/core/Assertions.h>
49 #include <saml/saml2/core/Assertions.h>
50 #include <saml/saml2/metadata/Metadata.h>
51 #include <saml/saml2/metadata/MetadataProvider.h>
52 #include <xercesc/util/XMLUniDefs.hpp>
53 #include <xmltooling/XMLToolingConfig.h>
54 #include <xmltooling/util/ParserPool.h>
55 #include <xmltooling/util/XMLHelper.h>
56
57 using namespace shibsp;
58 using namespace opensaml::saml2md;
59 using namespace opensaml;
60 using namespace xmltooling::logging;
61 using namespace xmltooling;
62 using namespace xercesc;
63 using namespace std;
64
65 #if defined (_MSC_VER)
66     #pragma warning( push )
67     #pragma warning( disable : 4250 )
68 #endif
69
70 class ResolverTest : public shibsp::AssertionConsumerService
71 {
72 public:
73     ResolverTest(const DOMElement* e, const char* appId)
74         : shibsp::AssertionConsumerService(e, appId, Category::getInstance(SHIBSP_LOGCAT".Utilities.ResolverTest")) {
75     }
76     virtual ~ResolverTest() {}
77     
78     ResolutionContext* resolveAttributes (
79         const Application& application,
80         const RoleDescriptor* issuer,
81         const XMLCh* protocol,
82         const saml1::NameIdentifier* v1nameid,
83         const saml2::NameID* nameid,
84         const XMLCh* authncontext_class,
85         const XMLCh* authncontext_decl,
86         const vector<const Assertion*>* tokens
87         ) const {
88         return shibsp::AssertionConsumerService::resolveAttributes(
89             application, issuer, protocol, v1nameid, nameid, authncontext_class, authncontext_decl, tokens
90             );
91     }
92
93 private:
94     void implementProtocol(
95         const Application& application,
96         const HTTPRequest& httpRequest,
97         HTTPResponse& httpResponse,
98         SecurityPolicy& policy,
99         const PropertySet* settings,
100         const XMLObject& xmlObject
101         ) const {
102             throw FatalProfileException("Should never be called.");
103     }
104 };
105
106 #if defined (_MSC_VER)
107     #pragma warning( pop )
108 #endif
109
110 void usage()
111 {
112     cerr << "usage: resolvertest -n <name> -i <IdP> -p <protocol> [-f <format URI> -a <application id>]" << endl;
113     cerr << "       resolvertest [-a <application id>] < assertion.xml" << endl;
114 }
115
116 int main(int argc,char* argv[])
117 {
118     char* a_param=nullptr;
119     char* n_param=nullptr;
120     char* f_param=nullptr;
121     char* i_param=nullptr;
122     char* prot = nullptr;
123     const XMLCh* protocol = nullptr;
124
125     for (int i=1; i<argc; i++) {
126         if (!strcmp(argv[i],"-n") && i+1<argc)
127             n_param=argv[++i];
128         else if (!strcmp(argv[i],"-f") && i+1<argc)
129             f_param=argv[++i];
130         else if (!strcmp(argv[i],"-i") && i+1<argc)
131             i_param=argv[++i];
132         else if (!strcmp(argv[i],"-p") && i+1<argc)
133             prot=argv[++i];
134         else if (!strcmp(argv[i],"-saml10"))
135             protocol=samlconstants::SAML10_PROTOCOL_ENUM;
136         else if (!strcmp(argv[i],"-saml11"))
137             protocol=samlconstants::SAML11_PROTOCOL_ENUM;
138         else if (!strcmp(argv[i],"-saml2"))
139             protocol=samlconstants::SAML20P_NS;
140         else if (!strcmp(argv[i],"-a") && i+1<argc)
141             a_param=argv[++i];
142     }
143
144     if (n_param && !i_param) {
145         usage();
146         return -10;
147     }
148
149     if (!a_param)
150         a_param="default";
151
152     if (n_param) {
153         if (!protocol) {
154             if (prot)
155                 protocol = XMLString::transcode(prot);
156         }
157         if (!protocol) {
158             usage();
159             return -10;
160         }
161     }
162
163     SPConfig& conf=SPConfig::getConfig();
164     conf.setFeatures(
165         SPConfig::Metadata |
166         SPConfig::Trust |
167         SPConfig::AttributeResolution |
168         SPConfig::Credentials |
169         SPConfig::OutOfProcess |
170         SPConfig::Caching
171         );
172     if (!conf.init())
173         return -1;
174     if (!conf.instantiate()) {
175         conf.term();
176         return -2;
177     }
178
179     ServiceProvider* sp=conf.getServiceProvider();
180     sp->lock();
181
182     Category& log = Category::getInstance(SHIBSP_LOGCAT".Utility.ResolverTest");
183
184     const Application* app = sp->getApplication(a_param);
185     if (!app) {
186         log.error("unknown application ID (%s)", a_param);
187         sp->unlock();
188         conf.term();
189         return -3;
190     }
191
192     try {
193         ResolutionContext* ctx;
194
195         if (n_param) {
196             auto_ptr_XMLCh issuer(i_param);
197             auto_ptr_XMLCh name(n_param);
198             auto_ptr_XMLCh format(f_param);
199
200             MetadataProvider* m=app->getMetadataProvider();
201             xmltooling::Locker mlocker(m);
202             MetadataProviderCriteria mc(*app, i_param, &IDPSSODescriptor::ELEMENT_QNAME, protocol);
203             pair<const EntityDescriptor*,const RoleDescriptor*> site=m->getEntityDescriptor(mc);
204             if (!site.first)
205                 throw MetadataException("Unable to locate metadata for IdP ($1).", params(1,i_param));
206
207             // Build NameID(s).
208             auto_ptr<saml2::NameID> v2name(saml2::NameIDBuilder::buildNameID());
209             v2name->setName(name.get());
210             v2name->setFormat(format.get());
211             saml1::NameIdentifier* v1name = nullptr;
212             if (!XMLString::equals(protocol, samlconstants::SAML20P_NS)) {
213                 v1name = saml1::NameIdentifierBuilder::buildNameIdentifier();
214                 v1name->setName(name.get());
215                 v1name->setFormat(format.get());
216                 v1name->setNameQualifier(issuer.get());
217             }
218
219             ResolverTest rt(nullptr, a_param);
220             try {
221                 ctx = rt.resolveAttributes(*app, site.second, protocol, v1name, v2name.get(), nullptr, nullptr, nullptr);
222             }
223             catch (...) {
224                 delete v1name;
225                 throw;
226             }
227         }
228         else {
229             // Try and load assertion from stdin.
230             DOMDocument* doc = XMLToolingConfig::getConfig().getParser().parse(cin);
231             XercesJanitor<DOMDocument> docjan(doc);
232             auto_ptr<XMLObject> token(XMLObjectBuilder::buildOneFromElement(doc->getDocumentElement(), true));
233             docjan.release();
234
235             // Get the issuer and protocol and NameIDs.
236             const XMLCh* issuer = nullptr;
237             const saml1::NameIdentifier* v1name = nullptr;
238             saml2::NameID* v2name = nullptr;
239             saml2::Assertion* a2 = dynamic_cast<saml2::Assertion*>(token.get());
240             saml1::Assertion* a1 = dynamic_cast<saml1::Assertion*>(token.get());
241             if (a2) {
242                 const saml2::Issuer* iss = a2->getIssuer();
243                 issuer = iss ? iss->getName() : nullptr;
244                 protocol = samlconstants::SAML20P_NS;
245                 v2name = a2->getSubject() ? a2->getSubject()->getNameID() : nullptr;
246             }
247             else if (a1) {
248                 issuer = a1->getIssuer();
249                 if (a1->getMinorVersion().first && a1->getMinorVersion().second == 0)
250                     protocol = samlconstants::SAML10_PROTOCOL_ENUM;
251                 else
252                     protocol = samlconstants::SAML11_PROTOCOL_ENUM;
253                 v1name = a1->getAuthenticationStatements().size() ?
254                     a1->getAuthenticationStatements().front()->getSubject()->getNameIdentifier() : nullptr;
255                 if (!v1name)
256                     v1name = a1->getAttributeStatements().size() ?
257                     a1->getAttributeStatements().front()->getSubject()->getNameIdentifier() : nullptr;
258                 if (v1name) {
259                     // Normalize the SAML 1.x NameIdentifier...
260                     v2name = saml2::NameIDBuilder::buildNameID();
261                     v2name->setName(v1name->getName());
262                     v2name->setFormat(v1name->getFormat());
263                     v2name->setNameQualifier(v1name->getNameQualifier());
264                 }
265             }
266             else {
267                 throw FatalProfileException("Unknown assertion type.");
268             }
269
270             auto_ptr<saml2::NameID> nameidwrapper(v1name ? v2name : nullptr);
271
272             if (!issuer)
273                 throw FatalProfileException("Unable to determine issuer.");
274
275             MetadataProvider* m=app->getMetadataProvider();
276             xmltooling::Locker mlocker(m);
277             MetadataProviderCriteria mc(*app, issuer, &IDPSSODescriptor::ELEMENT_QNAME, protocol);
278             pair<const EntityDescriptor*,const RoleDescriptor*> site=m->getEntityDescriptor(mc);
279             if (!site.first) {
280                 auto_ptr_char temp(issuer);
281                 throw MetadataException("Unable to locate metadata for IdP ($1).", params(1,temp.get()));
282             }
283             
284             vector<const Assertion*> tokens(1, dynamic_cast<Assertion*>(token.get()));
285             ResolverTest rt(nullptr, a_param);
286             ctx = rt.resolveAttributes(*app, site.second, protocol, v1name, v2name, nullptr, nullptr, &tokens);
287         }
288
289         auto_ptr<ResolutionContext> wrapper(ctx);
290         for (vector<Attribute*>::const_iterator a = ctx->getResolvedAttributes().begin(); a != ctx->getResolvedAttributes().end(); ++a) {
291             for (vector<string>::const_iterator s = (*a)->getAliases().begin(); s != (*a)->getAliases().end(); ++s) {
292                 cout << *s << ": ";
293                 for (vector<string>::const_iterator v = (*a)->getSerializedValues().begin(); v != (*a)->getSerializedValues().end(); ++v) {
294                     if (v != (*a)->getSerializedValues().begin())
295                         cout << ';';
296                     cout << *v;
297                 }
298                 cout << endl;
299             }
300         }
301         cout << endl;
302     }
303     catch(exception& ex) {
304         log.error(ex.what());
305         sp->unlock();
306         conf.term();
307         return -10;
308     }
309
310     sp->unlock();
311     conf.term();
312     return 0;
313 }