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