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