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