5f85fdeb62a78cd0fec4a9bbd7ed82f6752565ca
[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.IOException;
56 import java.io.PrintStream;
57 import java.io.PrintWriter;
58 import java.net.URL;
59 import java.net.MalformedURLException;
60 import java.security.Principal;
61
62 import org.apache.log4j.ConsoleAppender;
63 import org.apache.log4j.Level;
64 import org.apache.log4j.Logger;
65 import org.apache.log4j.PatternLayout;
66 import org.apache.xml.serialize.OutputFormat;
67 import org.apache.xml.serialize.XMLSerializer;
68 import org.opensaml.SAMLException;
69 import org.w3c.dom.Document;
70 import org.w3c.dom.Element;
71 import org.w3c.dom.Node;
72 import org.w3c.dom.NodeList;
73
74 import edu.internet2.middleware.shibboleth.aa.AAAttribute;
75 import edu.internet2.middleware.shibboleth.aa.AAConfig;
76 import edu.internet2.middleware.shibboleth.aa.AAAttributeSet;
77 import edu.internet2.middleware.shibboleth.aa.AAAttributeSet.ShibAttributeIterator;
78 import edu.internet2.middleware.shibboleth.aa.arp.ArpEngine;
79 import edu.internet2.middleware.shibboleth.aa.arp.ArpException;
80 import edu.internet2.middleware.shibboleth.aa.arp.ArpProcessingException;
81 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolver;
82 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolverException;
83 import edu.internet2.middleware.shibboleth.common.AuthNPrincipal;
84 import edu.internet2.middleware.shibboleth.common.OriginConfig;
85 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
86 import edu.internet2.middleware.shibboleth.common.ShibbolethOriginConfig;
87
88 /**
89  * Utility for testing an Attribute Resolver configuration.
90  * 
91  * @author Walter Hoehn
92  * @author Noah Levitt
93  */
94 public class ResolverTest 
95 {
96         private static boolean debug = false;
97         private static String resolverxml = null;
98         private static String originxml = null;
99         private static String requester = null;
100         private static String user = null;
101         private static String resource = null;
102         private static URL resourceUrl = null;
103         private static AttributeResolver resolver = null;
104         private static ArpEngine arpEngine = null;
105
106         public static void main(String[] args) 
107         {
108                 parseCommandLine(args);
109                 initializeResolver();
110                 AAAttributeSet attributeSet = createAttributeSet();
111                 resolveAttributes(attributeSet);
112
113                 System.out.println("Received the following from the Attribute Resolver:");
114                 System.out.println();
115                 printAttributes(System.out, attributeSet);
116         }
117
118         private static void resolveAttributes(AAAttributeSet attributeSet)
119         {
120                 Principal principal = new AuthNPrincipal(user);
121
122                 resolver.resolveAttributes(principal, requester, attributeSet);
123
124                 try {
125                         if (arpEngine != null) {
126                                 arpEngine.filterAttributes(attributeSet, principal, requester, resourceUrl);
127                         }
128                 }
129                 catch (ArpProcessingException e) {
130                         System.err.println("Error applying Attribute Release Policy: " + e.getMessage());
131                         System.exit(1);
132                 }
133         }
134
135         private static void parseCommandLine(String[] args)
136         {
137                 CmdLineParser parser = new CmdLineParser();
138
139                 CmdLineParser.Option helpOption = parser.addBooleanOption('h', "help");
140                 CmdLineParser.Option debugOption = parser.addBooleanOption('d', "debug");
141                 CmdLineParser.Option originxmlOption = parser.addStringOption('\u0000', "originxml");
142                 CmdLineParser.Option userOption = parser.addStringOption('u', "user");
143                 CmdLineParser.Option requesterOption = parser.addStringOption('r', "requester");
144                 CmdLineParser.Option resolverxmlOption = parser.addStringOption('\u0000', "resolverxml");
145                 CmdLineParser.Option fileOption = parser.addStringOption('f', "file"); // deprecated
146                 CmdLineParser.Option resourceOption = parser.addStringOption('\u0000', "resource");
147
148                 try {
149                         parser.parse(args);
150                 } 
151                 catch (CmdLineParser.OptionException e) {
152                         System.out.println(e.getMessage());
153                         printUsage(System.out);
154                         System.exit(1);
155                 }
156
157                 Boolean helpEnabled = (Boolean) parser.getOptionValue(helpOption);
158                 if (helpEnabled != null && helpEnabled.booleanValue()) {
159                         printUsage(System.out);
160                         System.exit(0);
161                 }
162
163                 Boolean debugEnabled = ((Boolean) parser.getOptionValue(debugOption));
164                 if (debugEnabled != null) {
165                         debug = debugEnabled.booleanValue();
166                 }
167
168                 // if --resolverxml and --file both specified, silently use --resolverxml
169                 resolverxml = (String) parser.getOptionValue(resolverxmlOption); 
170                 if (resolverxml == null) {
171                         resolverxml = (String) parser.getOptionValue(fileOption);
172                 }
173
174                 originxml = (String) parser.getOptionValue(originxmlOption); 
175
176                 user = (String) parser.getOptionValue(userOption);
177                 requester = (String) parser.getOptionValue(requesterOption);
178                 resource = (String) parser.getOptionValue(resourceOption);
179
180                 configureLogging(debug);
181                 checkRequired();
182         }
183
184         /**
185          * Ensures that all required parameters were specified and successfully parsed.
186          */
187         private static void checkRequired() 
188         {
189                 if (user == null) {
190                         System.out.println("Missing required parameter --user.");
191                         System.out.println();
192                         printUsage(System.out);
193                         System.exit(1);
194                 }
195                 if ((resolverxml == null && originxml == null) || (resolverxml != null && originxml != null)) {
196                         System.out.println("Exactly one of --originxml and --resolverxml is required.");
197                         System.out.println();
198                         printUsage(System.out);
199                         System.exit(1);
200                 }
201         }
202
203         private static AAAttributeSet createAttributeSet()
204         {
205                 String[] attributes = resolver.listRegisteredAttributeDefinitionPlugIns();
206                 AAAttributeSet attributeSet = new AAAttributeSet();
207
208                 for (int i = 0; i < attributes.length; i++) {
209                         try { 
210                                 attributeSet.add(new AAAttribute(attributes[i]));
211                         }
212                         catch (SAMLException e) {
213                                 System.err.println("Error creating AAAttribute (" + attributes[i] + "): " + e.getMessage());
214                                 System.exit(1);
215                         }
216                 }
217
218                 return attributeSet;
219         }
220
221         private static void initializeResolver()
222         {
223                 if (originxml != null) {
224                         try {
225                                 Document originConfig = OriginConfig.getOriginConfig(originxml);
226                                 AAConfig configuration = new AAConfig(originConfig.getDocumentElement());
227
228                                 resolver = new AttributeResolver(configuration);
229
230                                 NodeList itemElements =
231                                         originConfig.getDocumentElement().getElementsByTagNameNS(
232                                                         ShibbolethOriginConfig.originConfigNamespace,
233                                                         "ReleasePolicyEngine");
234
235                                 if (itemElements.getLength() > 1) {
236                                         System.err.println("Warning: encountered multiple <ReleasePolicyEngine> configuration elements in (" + originxml + "). Using first...");
237                                 }
238
239                                 if (itemElements.getLength() < 1) {
240                                         arpEngine = new ArpEngine();
241                                 } else {
242                                         arpEngine = new ArpEngine((Element) itemElements.item(0));
243                                 }
244
245                                 if (resource != null) {
246                                         resourceUrl = new URL(resource);
247                                 }
248                         } 
249                         catch (ShibbolethConfigurationException e) {
250                                 System.err.println("Error loading origin configuration file (" + originxml + "): " + e.getMessage());
251                                 System.exit(1);
252                         }
253                         catch (AttributeResolverException e) {
254                                 System.err.println("Error initializing the Attribute Resolver: " + e.getMessage());
255                                 System.exit(1);
256                         }
257                         catch (ArpException e) {
258                                 System.err.println("Error initializing the ARP Engine: " + e.getMessage());
259                                 System.exit(1);
260                         }
261                         catch (MalformedURLException e) {
262                                 System.err.println("Specified resource URL is invalid: " + e.getMessage());
263                                 System.exit(1);
264                         }
265                 }
266                 else {
267                         try {
268                                 resolver = new AttributeResolver(resolverxml);
269                         } 
270                         catch (AttributeResolverException e) {
271                                 System.err.println("Error initializing the Attribute Resolver: " + e.getMessage());
272                                 System.exit(1);
273                         }
274                 }
275         }
276
277         private static void printAttributes(PrintStream out, AAAttributeSet attributeSet)
278         {
279                 try
280                 {
281                         for (ShibAttributeIterator iterator = attributeSet.shibAttributeIterator(); iterator.hasNext();) 
282                         {
283                                 AAAttribute attribute = iterator.nextShibAttribute();
284                                 Node node = attribute.toDOM();
285
286                                 ByteArrayOutputStream xml = new ByteArrayOutputStream();
287                                 if (!(node instanceof Element)) {
288                                         System.err.println("Received bad Element data from SAML library.");
289                                         System.exit(1);
290                                 }
291                                 OutputFormat format = new OutputFormat();
292                                 format.setIndenting(true);
293                                 format.setIndent(4);
294
295                                 new XMLSerializer(xml, format).serialize((Element) node);
296
297                                 out.println(xml.toString());
298                                 out.println();
299                         }
300                 }
301                 catch (SAMLException e) {
302                         System.err.println("Error creating SAML attribute: " + e.getMessage());
303                         System.exit(1);
304                 }
305                 catch (IOException e) {
306                         System.err.println("Error serializing output from Resolver: " + e.getMessage());
307                         System.exit(1);
308                 }
309         }
310
311         private static void configureLogging(boolean debugEnabled) 
312         {
313                 ConsoleAppender rootAppender = new ConsoleAppender();
314                 rootAppender.setWriter(new PrintWriter(System.out));
315                 rootAppender.setName("stdout");
316                 Logger.getRootLogger().addAppender(rootAppender);
317
318                 if (debugEnabled) {
319                         Logger.getRootLogger().setLevel(Level.DEBUG);
320                         rootAppender.setLayout(new PatternLayout("%-5p %-41X{serviceId} %d{ISO8601} (%c:%L) - %m%n")); 
321                 } else {
322                         Logger.getRootLogger().setLevel(Level.INFO);
323                         Logger.getLogger("edu.internet2.middleware.shibboleth.aa.attrresolv").setLevel(Level.WARN);
324                         rootAppender.setLayout(new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)); 
325                 }
326                 Logger.getLogger("org.apache.xml.security").setLevel(Level.OFF);
327         }
328
329         private static void printUsage(PrintStream out) 
330         {
331                 // out.println("Tests an AA Attribute Resolver configuration.");
332                 out.println("Usage: resolvertest --user=USER {--originxml=URL|--resolverxml=URL} [OPTION...]");
333                 out.println();
334                 out.println("Options:");
335                 out.println("  -h, --help                Print usage information");
336                 out.println("  -d, --debug               Run in debug mode");
337                 out.println("  --originxml=FILEURL       URL of the origin configuration file. Attributes");
338                 out.println("                            will be filtered according to the Attribute Release");
339                 out.println("                            Policy (ARP) specified in the configuration file");
340                 out.println("  --resolverxml=FILEURL     URL of the resolver configuration file. No ARP");
341                 out.println("                            filtering will be done");
342                 out.println("  --user=USER               User for whom attributes should be resolved");
343                 out.println("  --requester=REQUESTER     Name of the requester (SHAR). Emulates");
344                 out.println("                            unauthenticated requester if not specified");
345                 out.println("  --resource=URL            URL of the resource. Only attributes available");
346                 out.println("                            to any resource will be returned if not specified");
347         }
348 }
349