Added some Javadoc and some debugging statements.
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / aa / arp / ArpEngine.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.aa.arp;
51
52 import java.net.URI;
53 import java.net.URISyntaxException;
54 import java.net.URL;
55 import java.security.Principal;
56 import java.util.Collections;
57 import java.util.HashMap;
58 import java.util.HashSet;
59 import java.util.Iterator;
60 import java.util.Map;
61 import java.util.Properties;
62 import java.util.Set;
63
64 import org.apache.log4j.Logger;
65
66 /**
67  *  Defines a processing engine for Attribute Release Policies.
68  *
69  * @author Walter Hoehn (wassa@columbia.edu)
70  */
71
72 public class ArpEngine {
73
74         private static Logger log = Logger.getLogger(ArpEngine.class.getName());
75         private ArpRepository repository;
76         private static Map matchFunctions = Collections.synchronizedMap(new HashMap());
77         static {
78                 //Initialize built-in match functions
79                 try {
80                         matchFunctions.put(
81                                 new URI("urn:mace:shibboleth:arp:matchFunction:exactShar"),
82                                 "edu.internet2.middleware.shibboleth.aa.arp.provider.ExactSharMatchFunction");
83                         matchFunctions.put(
84                                 new URI("urn:mace:shibboleth:arp:matchFunction:resourceTree"),
85                                 "edu.internet2.middleware.shibboleth.aa.arp.provider.ResourceTreeMatchFunction");
86                         matchFunctions.put(
87                                 new URI("urn:mace:shibboleth:arp:matchFunction:regexMatch"),
88                                 "edu.internet2.middleware.shibboleth.aa.arp.provider.RegexMatchFunction");
89                 } catch (URISyntaxException e) {
90                         log.error("Error mapping standard match functions: " + e);
91                 }
92         }
93
94         public ArpEngine(Properties properties) throws ArpException {
95                 try {
96                         repository = ArpRepositoryFactory.getInstance(properties);
97                 } catch (ArpRepositoryException e) {
98                         log.error("Could not start Arp Engine: " + e);
99                         throw new ArpException("Could not start Arp Engine.");
100                 }
101         }
102
103         public ArpEngine(ArpRepository repository, Properties properties) throws ArpException {
104                 this.repository = repository;
105         }
106
107         /**
108          * Lookup by identifier a function for matching ARP Target Components .
109          * @param functionIdentifier the identifier for the function
110          * @return the <code>Matchfunction</code> or null if not registered
111          */
112         
113         public static MatchFunction lookupMatchFunction(URI functionIdentifier) throws ArpException {
114                 String className = null;
115
116                 synchronized (matchFunctions) {
117                         className = (String) matchFunctions.get(functionIdentifier);
118                 }
119
120                 if (className == null) {
121                         return null;
122                 }
123                 try {
124                         Class matchFunction = Class.forName(className);
125                         Object functionObject = matchFunction.newInstance();
126                         if (functionObject instanceof MatchFunction) {
127                                 return (MatchFunction) functionObject;
128                         } else {
129                                 log.error(
130                                         "Improperly specified match function, (" + className + ") is not a match function.");
131                                 throw new ArpException(
132                                         "Improperly specified match function, (" + className + ") is not a match function.");
133                         }
134                 } catch (Exception e) {
135                         log.error("Could not load Match Function: (" + className + "): " + e);
136                         throw new ArpException("Could not load Match Function.");
137                 }
138         }
139
140         private Arp createEffectiveArp(Principal principal, String requester, URL resource)
141                 throws ArpProcessingException {
142                 try {
143                         Arp effectiveArp = new Arp(principal);
144                         effectiveArp.setDescription("Effective ARP.");
145
146                         Arp[] userPolicies = repository.getAllPolicies(principal);
147                         log.debug("Creating effective ARP from (" + userPolicies.length + ") polic(y|ies).");
148                         for (int i = 0; userPolicies.length > i; i++) {
149                                 Rule[] rules = userPolicies[i].getMatchingRules(requester, resource);
150
151                                 for (int j = 0; rules.length > j; j++) {
152                                         effectiveArp.addRule(rules[j]);
153                                 }
154                         }
155                         return effectiveArp;
156
157                 } catch (ArpRepositoryException e) {
158                         log.error("Error creating effective policy: " + e);
159                         throw new ArpProcessingException("Error creating effective policy.");
160                 }
161         }
162
163         /**
164          * Determines which attributes MIGHT be releasable for a given request.  This function 
165          * may be used to determine which attributes to resolve when a request for all
166          * attributes is made.  This is done for performance reasons only. ie: The resulting 
167          * attributes must still be filtered before release.
168          * @return an array of <code>URI</code> objects that name the possible attributes
169          */
170         public URI[] listPossibleReleaseAttributes(Principal principal, String requester, URL resource)
171                 throws ArpProcessingException {
172                 Set possibleReleaseSet = new HashSet();
173                 Set anyValueDenies = new HashSet();
174                 Rule[] rules = createEffectiveArp(principal, requester, resource).getAllRules();
175                 for (int i = 0; rules.length > i; i++) {
176                         Rule.Attribute[] attributes = rules[i].getAttributes();
177                         for (int j = 0; attributes.length > j; j++) {
178                                 if (attributes[j].releaseAnyValue()) {
179                                         possibleReleaseSet.add(attributes[j].getName());
180                                 } else if (attributes[j].denyAnyValue()) {
181                                         anyValueDenies.add(attributes[j].getName());
182                                 } else {
183                                         Rule.AttributeValue[] values = attributes[j].getValues();
184                                         for (int k = 0; values.length > k; k++) {
185                                                 if (values[k].getRelease().equals("permit")) {
186                                                         possibleReleaseSet.add(attributes[j].getName());
187                                                         break;
188                                                 }
189                                         }
190                                 }
191                         }
192                 }
193                 possibleReleaseSet.removeAll(anyValueDenies);
194                 if (log.isDebugEnabled()) {
195                         log.debug("Computed possible attribute release set.");
196                         Iterator iterator = possibleReleaseSet.iterator();
197                         while (iterator.hasNext()) {
198                                 log.debug("Possible attribute: " + iterator.next().toString());
199                         }
200                 }
201                 return (URI[]) possibleReleaseSet.toArray(new URI[0]);
202         }
203
204         /**
205          * Applies all applicable ARPs to a set of attributes.
206          * @return the attributes to be released
207          */
208         public ArpAttribute[] filterAttributes(
209                 ArpAttribute[] attributes,
210                 Principal principal,
211                 String requester,
212                 URL resource)
213                 throws ArpProcessingException {
214
215                 Set releaseSet = new HashSet();
216
217                 //Gather all applicable ARP attribute specifiers
218                 Set attributeNames = new HashSet();
219                 for (int i = 0; attributes.length > i; i++) {
220                         attributeNames.add(attributes[i].getName());
221                 }
222                 Rule[] rules = createEffectiveArp(principal, requester, resource).getAllRules();
223                 Set applicableRuleAttributes = new HashSet();
224                 for (int i = 0; rules.length > i; i++) {
225                         Rule.Attribute[] ruleAttributes = rules[i].getAttributes();
226                         for (int j = 0; ruleAttributes.length > j; j++) {
227                                 if (attributeNames.contains(ruleAttributes[j].getName().toString())) {
228                                         applicableRuleAttributes.add(ruleAttributes[j]);
229                                 }
230                         }
231                 }
232
233                 //Canonicalize specifiers
234                 Map arpAttributeSpecs =
235                         createCanonicalAttributeSpec(
236                                 (Rule.Attribute[]) applicableRuleAttributes.toArray(new Rule.Attribute[0]));
237
238                 //Filter
239                 for (int i = 0; attributes.length > i; i++) {
240                         Rule.Attribute attribute = (Rule.Attribute) arpAttributeSpecs.get(attributes[i].getName());
241
242                         //Handle no specifier
243                         if (attribute == null) {
244                                 continue;
245                         }
246
247                         //Handle Deny All
248                         if (attribute.denyAnyValue()) {
249                                 continue;
250                         }
251
252                         //Handle Permit All
253                         if (attribute.releaseAnyValue() && attribute.getValues().length == 0) {
254                                 releaseSet.add(attributes[i]);
255                                 continue;
256                         }
257
258                         //Handle Permit All-Except and Permit Specific
259                         Object[] resolvedValues = attributes[i].getValues();
260                         Set releaseValues = new HashSet();
261                         for (int j = 0; resolvedValues.length > j; j++) {
262                                 System.err.println(attribute.isValuePermitted(resolvedValues[j]));
263                                 if (attribute.isValuePermitted(resolvedValues[j])) {
264                                         releaseValues.add(resolvedValues[j]);
265                                 }
266                         }
267                         attributes[i].setValues((ArpAttribute[]) releaseValues.toArray(new ArpAttribute[0]));
268                         releaseSet.add(attributes[i]);
269                 }
270                 return (ArpAttribute[]) releaseSet.toArray(new ArpAttribute[0]);
271         }
272
273         private Map createCanonicalAttributeSpec(Rule.Attribute[] attributes) {
274                 Map canonicalSpec = new HashMap();
275                 for (int i = 0; attributes.length > i; i++) {
276                         if (!canonicalSpec.containsKey(attributes[i].getName().toString())) {
277                                 canonicalSpec.put(attributes[i].getName().toString(), attributes[i]);
278                         } else {
279                                 if (((Rule.Attribute) canonicalSpec.get(attributes[i].getName().toString())).denyAnyValue()) {
280                                         continue;
281                                 }
282                                 if (attributes[i].denyAnyValue()) {
283                                         ((Rule.Attribute) canonicalSpec.get(attributes[i].getName().toString())).setAnyValueDeny(true);
284                                         continue;
285                                 }
286                                 if (attributes[i].releaseAnyValue()) {
287                                         ((Rule.Attribute) canonicalSpec.get(attributes[i].getName().toString())).setAnyValuePermit(true);
288                                 }
289                                 Rule.AttributeValue[] values = attributes[i].getValues();
290                                 for (int j = 0; values.length > j; j++) {
291                                         ((Rule.Attribute) canonicalSpec.get(attributes[i].getName().toString())).addValue(values[j]);
292                                 }
293                         }
294                 }
295                 return canonicalSpec;
296         }
297
298 }