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