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