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