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