Replace DOMParser with calls to pool or helper class.
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / utils / ResolverTest.java
1 /* 
2  * The Shibboleth License, Version 1. 
3  * Copyright (c) 2002 
4  * University Corporation for Advanced Internet Development, Inc. 
5  * All rights reserved
6  * 
7  * 
8  * Redistribution and use in source and binary forms, with or without 
9  * modification, are permitted provided that the following conditions are met:
10  * 
11  * Redistributions of source code must retain the above copyright notice, this 
12  * list of conditions and the following disclaimer.
13  * 
14  * Redistributions in binary form must reproduce the above copyright notice, 
15  * this list of conditions and the following disclaimer in the documentation 
16  * and/or other materials provided with the distribution, if any, must include 
17  * the following acknowledgment: "This product includes software developed by 
18  * the University Corporation for Advanced Internet Development 
19  * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement 
20  * may appear in the software itself, if and wherever such third-party 
21  * acknowledgments normally appear.
22  * 
23  * Neither the name of Shibboleth nor the names of its contributors, nor 
24  * Internet2, nor the University Corporation for Advanced Internet Development, 
25  * Inc., nor UCAID may be used to endorse or promote products derived from this 
26  * software without specific prior written permission. For written permission, 
27  * please contact shibboleth@shibboleth.org
28  * 
29  * Products derived from this software may not be called Shibboleth, Internet2, 
30  * UCAID, or the University Corporation for Advanced Internet Development, nor 
31  * may Shibboleth appear in their name, without prior written permission of the 
32  * University Corporation for Advanced Internet Development.
33  * 
34  * 
35  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
36  * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
37  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
38  * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK 
39  * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE. 
40  * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY 
41  * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT, 
42  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
43  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
44  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
46  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
47  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48  */
49
50 package edu.internet2.middleware.shibboleth.utils;
51
52 import jargs.gnu.CmdLineParser;
53
54 import java.io.ByteArrayOutputStream;
55 import java.io.PrintStream;
56 import java.io.PrintWriter;
57 import java.net.URL;
58 import java.net.MalformedURLException;
59 import java.security.Principal;
60
61 import org.apache.log4j.ConsoleAppender;
62 import org.apache.log4j.Level;
63 import org.apache.log4j.Logger;
64 import org.apache.log4j.PatternLayout;
65 import org.opensaml.SAMLException;
66 import org.w3c.dom.Document;
67 import org.w3c.dom.Element;
68 import org.w3c.dom.Node;
69 import org.w3c.dom.NodeList;
70
71 import edu.internet2.middleware.shibboleth.aa.AAAttribute;
72 import edu.internet2.middleware.shibboleth.aa.AAConfig;
73 import edu.internet2.middleware.shibboleth.aa.AAAttributeSet;
74 import edu.internet2.middleware.shibboleth.aa.AAAttributeSet.ShibAttributeIterator;
75 import edu.internet2.middleware.shibboleth.aa.arp.ArpEngine;
76 import edu.internet2.middleware.shibboleth.aa.arp.ArpException;
77 import edu.internet2.middleware.shibboleth.aa.arp.ArpProcessingException;
78 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolver;
79 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolverException;
80 import edu.internet2.middleware.shibboleth.common.AuthNPrincipal;
81 import edu.internet2.middleware.shibboleth.common.OriginConfig;
82 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
83 import edu.internet2.middleware.shibboleth.common.ShibbolethOriginConfig;
84 import edu.internet2.middleware.shibboleth.xml.Parser;
85
86 /**
87  * Utility for testing an Attribute Resolver configuration.
88  * 
89  * @author Walter Hoehn
90  * @author Noah Levitt
91  */
92 public class ResolverTest 
93 {
94         private static boolean debug = false;
95         private static String resolverxml = null;
96         private static String originxml = null;
97         private static String requester = null;
98         private static String user = null;
99         private static String resource = null;
100         private static URL resourceUrl = null;
101         private static AttributeResolver resolver = null;
102         private static ArpEngine arpEngine = null;
103
104         public static void main(String[] args) 
105         {
106                 parseCommandLine(args);
107                 initializeResolver();
108                 AAAttributeSet attributeSet = createAttributeSet();
109                 resolveAttributes(attributeSet);
110
111                 System.out.println("Received the following from the Attribute Resolver:");
112                 System.out.println();
113                 printAttributes(System.out, attributeSet);
114         }
115
116         private static void resolveAttributes(AAAttributeSet attributeSet)
117         {
118                 Principal principal = new AuthNPrincipal(user);
119
120                 resolver.resolveAttributes(principal, requester, attributeSet);
121
122                 try {
123                         if (arpEngine != null) {
124                                 arpEngine.filterAttributes(attributeSet, principal, requester, resourceUrl);
125                         }
126                 }
127                 catch (ArpProcessingException e) {
128                         System.err.println("Error applying Attribute Release Policy: " + e.getMessage());
129                         System.exit(1);
130                 }
131         }
132
133         private static void parseCommandLine(String[] args)
134         {
135                 CmdLineParser parser = new CmdLineParser();
136
137                 CmdLineParser.Option helpOption = parser.addBooleanOption('h', "help");
138                 CmdLineParser.Option debugOption = parser.addBooleanOption('d', "debug");
139                 CmdLineParser.Option originxmlOption = parser.addStringOption('\u0000', "originxml");
140                 CmdLineParser.Option userOption = parser.addStringOption('u', "user");
141                 CmdLineParser.Option requesterOption = parser.addStringOption('r', "requester");
142                 CmdLineParser.Option resolverxmlOption = parser.addStringOption('\u0000', "resolverxml");
143                 CmdLineParser.Option fileOption = parser.addStringOption('f', "file"); // deprecated
144                 CmdLineParser.Option resourceOption = parser.addStringOption('\u0000', "resource");
145
146                 try {
147                         parser.parse(args);
148                 } 
149                 catch (CmdLineParser.OptionException e) {
150                         System.out.println(e.getMessage());
151                         printUsage(System.out);
152                         System.exit(1);
153                 }
154
155                 Boolean helpEnabled = (Boolean) parser.getOptionValue(helpOption);
156                 if (helpEnabled != null && helpEnabled.booleanValue()) {
157                         printUsage(System.out);
158                         System.exit(0);
159                 }
160
161                 Boolean debugEnabled = ((Boolean) parser.getOptionValue(debugOption));
162                 if (debugEnabled != null) {
163                         debug = debugEnabled.booleanValue();
164                 }
165
166                 // if --resolverxml and --file both specified, silently use --resolverxml
167                 resolverxml = (String) parser.getOptionValue(resolverxmlOption); 
168                 if (resolverxml == null) {
169                         resolverxml = (String) parser.getOptionValue(fileOption);
170                 }
171
172                 originxml = (String) parser.getOptionValue(originxmlOption); 
173
174                 user = (String) parser.getOptionValue(userOption);
175                 requester = (String) parser.getOptionValue(requesterOption);
176                 resource = (String) parser.getOptionValue(resourceOption);
177
178                 configureLogging(debug);
179                 checkRequired();
180         }
181
182         /**
183          * Ensures that all required parameters were specified and successfully parsed.
184          */
185         private static void checkRequired() 
186         {
187                 if (user == null) {
188                         System.out.println("Missing required parameter --user.");
189                         System.out.println();
190                         printUsage(System.out);
191                         System.exit(1);
192                 }
193                 if ((resolverxml == null && originxml == null) || (resolverxml != null && originxml != null)) {
194                         System.out.println("Exactly one of --originxml and --resolverxml is required.");
195                         System.out.println();
196                         printUsage(System.out);
197                         System.exit(1);
198                 }
199         }
200
201         private static AAAttributeSet createAttributeSet()
202         {
203                 String[] attributes = resolver.listRegisteredAttributeDefinitionPlugIns();
204                 AAAttributeSet attributeSet = new AAAttributeSet();
205
206                 for (int i = 0; i < attributes.length; i++) {
207                         try { 
208                                 attributeSet.add(new AAAttribute(attributes[i]));
209                         }
210                         catch (SAMLException e) {
211                                 System.err.println("Error creating AAAttribute (" + attributes[i] + "): " + e.getMessage());
212                                 System.exit(1);
213                         }
214                 }
215
216                 return attributeSet;
217         }
218
219         private static void initializeResolver()
220         {
221                 if (originxml != null) {
222                         try {
223                                 Document originConfig = OriginConfig.getOriginConfig(originxml);
224                                 AAConfig configuration = new AAConfig(originConfig.getDocumentElement());
225
226                                 resolver = new AttributeResolver(configuration);
227
228                                 NodeList itemElements =
229                                         originConfig.getDocumentElement().getElementsByTagNameNS(
230                                                         ShibbolethOriginConfig.originConfigNamespace,
231                                                         "ReleasePolicyEngine");
232
233                                 if (itemElements.getLength() > 1) {
234                                         System.err.println("Warning: encountered multiple <ReleasePolicyEngine> configuration elements in (" + originxml + "). Using first...");
235                                 }
236
237                                 if (itemElements.getLength() < 1) {
238                                         arpEngine = new ArpEngine();
239                                 } else {
240                                         arpEngine = new ArpEngine((Element) itemElements.item(0));
241                                 }
242
243                                 if (resource != null) {
244                                         resourceUrl = new URL(resource);
245                                 }
246                         } 
247                         catch (ShibbolethConfigurationException e) {
248                                 System.err.println("Error loading origin configuration file (" + originxml + "): " + e.getMessage());
249                                 System.exit(1);
250                         }
251                         catch (AttributeResolverException e) {
252                                 System.err.println("Error initializing the Attribute Resolver: " + e.getMessage());
253                                 System.exit(1);
254                         }
255                         catch (ArpException e) {
256                                 System.err.println("Error initializing the ARP Engine: " + e.getMessage());
257                                 System.exit(1);
258                         }
259                         catch (MalformedURLException e) {
260                                 System.err.println("Specified resource URL is invalid: " + e.getMessage());
261                                 System.exit(1);
262                         }
263                 }
264                 else {
265                         try {
266                                 resolver = new AttributeResolver(resolverxml);
267                         } 
268                         catch (AttributeResolverException e) {
269                                 System.err.println("Error initializing the Attribute Resolver: " + e.getMessage());
270                                 System.exit(1);
271                         }
272                 }
273         }
274
275         private static void printAttributes(PrintStream out, AAAttributeSet attributeSet)
276         {
277                 try
278                 {
279                         for (ShibAttributeIterator iterator = attributeSet.shibAttributeIterator(); iterator.hasNext();) 
280                         {
281                                 AAAttribute attribute = iterator.nextShibAttribute();
282                                 Node node = attribute.toDOM();
283
284                                 ByteArrayOutputStream xml = new ByteArrayOutputStream();
285                                 if (!(node instanceof Element)) {
286                                         System.err.println("Received bad Element data from SAML library.");
287                                         System.exit(1);
288                                 }
289                                 out.println(Parser.serialize(node));
290                                 out.println();
291                         }
292                 }
293                 catch (SAMLException e) {
294                         System.err.println("Error creating SAML attribute: " + e.getMessage());
295                         System.exit(1);
296                 }
297         }
298
299         private static void configureLogging(boolean debugEnabled) 
300         {
301                 ConsoleAppender rootAppender = new ConsoleAppender();
302                 rootAppender.setWriter(new PrintWriter(System.out));
303                 rootAppender.setName("stdout");
304                 Logger.getRootLogger().addAppender(rootAppender);
305
306                 if (debugEnabled) {
307                         Logger.getRootLogger().setLevel(Level.DEBUG);
308                         rootAppender.setLayout(new PatternLayout("%-5p %-41X{serviceId} %d{ISO8601} (%c:%L) - %m%n")); 
309                 } else {
310                         Logger.getRootLogger().setLevel(Level.INFO);
311                         Logger.getLogger("edu.internet2.middleware.shibboleth.aa.attrresolv").setLevel(Level.WARN);
312                         rootAppender.setLayout(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)); 
313                 }
314                 Logger.getLogger("org.apache.xml.security").setLevel(Level.OFF);
315         }
316
317         private static void printUsage(PrintStream out) 
318         {
319                 // out.println("Tests an AA Attribute Resolver configuration.");
320                 out.println("Usage: resolvertest --user=USER {--originxml=URL|--resolverxml=URL} [OPTION...]");
321                 out.println();
322                 out.println("Options:");
323                 out.println("  -h, --help                Print usage information");
324                 out.println("  -d, --debug               Run in debug mode");
325                 out.println("  --originxml=FILEURL       URL of the origin configuration file. Attributes");
326                 out.println("                            will be filtered according to the Attribute Release");
327                 out.println("                            Policy (ARP) specified in the configuration file");
328                 out.println("  --resolverxml=FILEURL     URL of the resolver configuration file. No ARP");
329                 out.println("                            filtering will be done");
330                 out.println("  --user=USER               User for whom attributes should be resolved");
331                 out.println("  --requester=REQUESTER     Name of the requester (SHAR). Emulates");
332                 out.println("                            unauthenticated requester if not specified");
333                 out.println("  --resource=URL            URL of the resource. Only attributes available");
334                 out.println("                            to any resource will be returned if not specified");
335         }
336 }
337