29935f787aa35866becd5796d15e7658f8a92ed8
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / aa / attrresolv / AttributeResolver.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.attrresolv;
51
52 import java.io.IOException;
53 import java.io.InputStream;
54 import java.security.Principal;
55 import java.util.ArrayList;
56 import java.util.Arrays;
57 import java.util.HashMap;
58 import java.util.HashSet;
59 import java.util.Iterator;
60 import java.util.List;
61 import java.util.Map;
62 import java.util.Properties;
63 import java.util.Set;
64
65 import javax.naming.directory.Attributes;
66
67 import org.apache.log4j.Logger;
68 import org.apache.xerces.parsers.DOMParser;
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 import org.xml.sax.EntityResolver;
74 import org.xml.sax.ErrorHandler;
75 import org.xml.sax.InputSource;
76 import org.xml.sax.SAXException;
77 import org.xml.sax.SAXParseException;
78
79 import edu.internet2.middleware.shibboleth.aa.attrresolv.ResolverAttributeSet.ResolverAttributeIterator;
80 import edu.internet2.middleware.shibboleth.aa.attrresolv.provider.ValueHandler;
81 import edu.internet2.middleware.shibboleth.common.ShibResource;
82 import edu.internet2.middleware.shibboleth.common.ShibResource.ResourceNotAvailableException;
83
84 /**
85  * An engine for obtaining attribute values for specified principals.  Attributes values are
86  * resolved using a directed graph of pluggable attribute definitions and data connectors.
87  *   
88  * @author Walter Hoehn (wassa@columbia.edu)
89  *
90  */
91
92 public class AttributeResolver {
93
94         private static Logger log = Logger.getLogger(AttributeResolver.class.getName());
95         private HashMap plugIns = new HashMap();
96         private ResolverCache resolverCache = new ResolverCache();
97         public static final String resolverNamespace = "urn:mace:shibboleth:resolver:1.0";
98
99         public AttributeResolver(Properties properties) throws AttributeResolverException {
100                 if (properties
101                         .getProperty("edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolver.ResolverConfig")
102                         == null) {
103                         log.error("No Attribute Resolver configuration file specified.");
104                         throw new AttributeResolverException("No Attribute Resolver configuration file specified.");
105                 }
106
107                 String configFile =
108                         properties.getProperty(
109                                 "edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolver.ResolverConfig");
110
111                 try {
112                         ShibResource config = new ShibResource(configFile, this.getClass());
113                         DOMParser parser = new DOMParser();
114                         parser.setFeature("http://xml.org/sax/features/validation", true);
115                         parser.setFeature("http://apache.org/xml/features/validation/schema", true);
116                         parser.setEntityResolver(new EntityResolver() {
117                                 public InputSource resolveEntity(String publicId, String systemId) throws SAXException {
118                                         if (systemId.endsWith("shibboleth-resolver-1.0.xsd")) {
119                                                 InputStream stream;
120                                                 try {
121                                                         return new InputSource(
122                                                                 new ShibResource("/schemas/shibboleth-resolver-1.0.xsd", this.getClass())
123                                                                         .getInputStream());
124                                                 } catch (IOException e) {
125                                                         throw new SAXException("Could not load entity: " + e);
126                                                 }
127                                         } else {
128                                                 return null;
129                                         }
130                                 }
131                         });
132
133                         parser.setErrorHandler(new ErrorHandler() {
134                                 public void error(SAXParseException arg0) throws SAXException {
135                                         throw new SAXException("Error parsing xml file: " + arg0);
136                                 }
137                                 public void fatalError(SAXParseException arg0) throws SAXException {
138                                         throw new SAXException("Error parsing xml file: " + arg0);
139                                 }
140                                 public void warning(SAXParseException arg0) throws SAXException {
141                                         throw new SAXException("Error parsing xml file: " + arg0);
142                                 }
143                         });
144                         parser.parse(new InputSource(config.getInputStream()));
145                         loadConfig(parser.getDocument());
146
147                 } catch (ResourceNotAvailableException e) {
148                         log.error("No Attribute Resolver configuration could be loaded from (" + configFile + "): " + e);
149                         throw new AttributeResolverException("No Attribute Resolver configuration found.");
150                 } catch (SAXException e) {
151                         log.error("Error parsing Attribute Resolver Configuration file: " + e);
152                         throw new AttributeResolverException("Error parsing Attribute Resolver Configuration file.");
153                 } catch (IOException e) {
154                         log.error("Error reading Attribute Resolver Configuration file: " + e);
155                         throw new AttributeResolverException("Error reading Attribute Resolver Configuration file.");
156                 }
157         }
158
159         private void loadConfig(Document document) throws AttributeResolverException {
160
161                 log.info("Configuring Attribute Resolver.");
162                 if (!document.getDocumentElement().getTagName().equals("AttributeResolver")) {
163                         log.error("Configuration must include <AttributeResolver> as the root node.");
164                         throw new AttributeResolverException("Cannot load Attribute Resolver.");
165                 }
166
167                 NodeList plugInNodes =
168                         document.getElementsByTagNameNS(resolverNamespace, "AttributeResolver").item(0).getChildNodes();
169                 if (plugInNodes.getLength() <= 0) {
170                         log.error("Configuration inclues no PlugIn definitions.");
171                         throw new AttributeResolverException("Cannot load Attribute Resolver.");
172                 }
173                 for (int i = 0; plugInNodes.getLength() > i; i++) {
174                         if (plugInNodes.item(i).getNodeType() == Node.ELEMENT_NODE) {
175                                 try {
176                                         log.info("Found a PlugIn. Loading...");
177                                         ResolutionPlugIn plugIn = ResolutionPlugInFactory.createPlugIn((Element) plugInNodes.item(i));
178                                         registerPlugIn(plugIn, plugIn.getId());
179                                 } catch (DuplicatePlugInException dpe) {
180                                         log.warn("Skipping PlugIn: " + dpe.getMessage());
181                                 } catch (ClassCastException cce) {
182                                         log.error("Problem realizing PlugIn configuration" + cce.getMessage());
183                                 } catch (AttributeResolverException are) {
184                                         log.warn("Skipping PlugIn: " + ((Element) plugInNodes.item(i)).getAttribute("id"));
185                                 }
186                         }
187                 }
188
189                 verifyPlugIns();
190                 log.info("Configuration complete.");
191         }
192
193         private void verifyPlugIns() throws AttributeResolverException {
194                 
195                 log.info("Verifying PlugIn graph consitency.");
196                 Set inconsistent = new HashSet();
197                 Iterator registered = plugIns.keySet().iterator();
198
199                 while (registered.hasNext()) {
200                         ResolutionPlugIn plugIn = lookupPlugIn((String) registered.next());
201                         log.debug("Checking PlugIn (" + plugIn.getId() + ") for consistency.");
202                         if (plugIn instanceof AttributeDefinitionPlugIn) {
203                                 verifyPlugIn((AttributeDefinitionPlugIn) plugIn, new HashSet(), inconsistent);
204                         }
205                 }
206                 
207                 if (!inconsistent.isEmpty()) {
208                         log.info("Unloading inconsistent PlugIns.");
209                         Iterator inconsistentIt = inconsistent.iterator();
210                         while (inconsistentIt.hasNext()) {
211                                 plugIns.remove(inconsistentIt.next());
212                         }
213                 }
214                 
215                 if (plugIns.size() < 1) {
216                         log.error("Failed to load any PlugIn definitions.");
217                         throw new AttributeResolverException("Cannot load Attribute Resolver.");
218                 }
219
220         }
221
222         private void verifyPlugIn(AttributeDefinitionPlugIn plugIn, Set verifyChain, Set inconsistent) {
223
224                 //Short-circuit if we have already found this PlugIn to be inconsistent
225                 if (inconsistent.contains(plugIn.getId())) {
226                         return;
227                 }
228
229                 //Make sure that we don't have a circular dependency
230                 if (verifyChain.contains(plugIn.getId())) {
231                         log.error(
232                                 "The PlugIn (" + plugIn.getId() + ") is inconsistent.  It is involved in a circular dependency chain.");
233                         inconsistent.add(plugIn.getId());
234                         return;
235                 }
236
237                 //Make sure all dependent Data Connectors are registered
238                 List depends = new ArrayList();
239                 depends.addAll(Arrays.asList(plugIn.getDataConnectorDependencyIds()));
240                 Iterator dependsIt = depends.iterator();
241                 while (dependsIt.hasNext()) {
242                         String key = (String) dependsIt.next();
243                         if (!plugIns.containsKey(key)) {
244                                 log.error(
245                                         "The PlugIn ("
246                                                 + plugIn.getId()
247                                                 + ") is inconsistent.  It depends on a PlugIn ("
248                                                 + key
249                                                 + ") that is not registered.");
250                                 inconsistent.add(plugIn.getId());
251                                 return;
252                         }
253                 }
254
255                 //Recursively go through all AttributeDefinition dependencies and make sure all are registered and consistent.
256                 depends.clear();
257                 depends.addAll(Arrays.asList(plugIn.getAttributeDefinitionDependencyIds()));
258                 dependsIt = depends.iterator();
259                 while (dependsIt.hasNext()) {
260                         String key = (String) dependsIt.next();
261
262                         if (!plugIns.containsKey(key)) {
263                                 log.error(
264                                         "The PlugIn ("
265                                                 + plugIn.getId()
266                                                 + ") is inconsistent.  It depends on a PlugIn ("
267                                                 + key
268                                                 + ") that is not registered.");
269                                 inconsistent.add(plugIn.getId());
270                                 return;
271                         }
272
273                         ResolutionPlugIn dependent = lookupPlugIn(key);
274                         if (!(dependent instanceof AttributeDefinitionPlugIn)) {
275                                 log.error(
276                                         "The PlugIn ("
277                                                 + plugIn.getId()
278                                                 + ") is inconsistent.  It depends on a PlugIn ("
279                                                 + key
280                                                 + ") that is mislabeled as an AttributeDefinitionPlugIn.");
281                                 inconsistent.add(plugIn.getId());
282                                 return;
283                         }
284                         
285                         verifyChain.add(plugIn.getId());
286                         verifyPlugIn((AttributeDefinitionPlugIn) dependent, verifyChain, inconsistent);
287
288                         if (inconsistent.contains(key)) {
289                                 log.error(
290                                         "The PlugIn ("
291                                                 + plugIn.getId()
292                                                 + ") is inconsistent.  It depends on a PlugIn ("
293                                                 + key
294                                                 + ") that is not inconsistent.");
295                                 inconsistent.add(plugIn.getId());
296                                 return;
297                         }
298                 }
299         }
300
301         private void registerPlugIn(ResolutionPlugIn connector, String id) throws DuplicatePlugInException {
302
303                 if (plugIns.containsKey(id)) {
304                         log.error("A PlugIn is already registered with the Id (" + id + ").");
305                         throw new DuplicatePlugInException("Found a duplicate PlugIn Id.");
306                 }
307                 plugIns.put(id, connector);
308                 log.info("Registered PlugIn: (" + id + ")");
309
310         }
311
312         private ResolutionPlugIn lookupPlugIn(String id) {
313                 return (ResolutionPlugIn) plugIns.get(id);
314         }
315
316         /**
317          * Resolve a set of attributes for a particular principal and requester.
318          * 
319          * @param principal the <code>Principal</code> for which the attributes should be resolved
320          * @param requester the name of the requesting entity
321          * @param attributes the set of attributes to be resolved
322          */
323         public void resolveAttributes(Principal principal, String requester, ResolverAttributeSet attributes) {
324
325                 HashMap requestCache = new HashMap();
326                 ResolverAttributeIterator iterator = attributes.resolverAttributeIterator();
327
328                 while (iterator.hasNext()) {
329                         ResolverAttribute attribute = iterator.nextResolverAttribute();
330                         try {
331                                 if (lookupPlugIn(attribute.getName()) == null) {
332                                         log.warn("No PlugIn registered for attribute: (" + attribute.getName() + ")");
333                                         iterator.remove();
334                                 } else {
335                                         log.info("Resolving attribute: (" + attribute.getName() + ")");
336                                         if (attribute.resolved()) {
337                                                 log.debug(
338                                                         "Attribute ("
339                                                                 + attribute.getName()
340                                                                 + ") already resolved for this request.  No need for further resolution.");
341
342                                         } else {
343                                                 resolveAttribute(attribute, principal, requester, requestCache, attributes);
344                                         }
345
346                                         if (!attribute.hasValues()) {
347                                                 iterator.remove();
348                                         }
349                                 }
350                         } catch (ResolutionPlugInException rpe) {
351                                 log.error("Problem encountered while resolving attribute: (" + attribute.getName() + "): " + rpe);
352                                 iterator.remove();
353                         }
354                 }
355         }
356
357         private void resolveAttribute(
358                 ResolverAttribute attribute,
359                 Principal principal,
360                 String requester,
361                 Map requestCache,
362                 ResolverAttributeSet requestedAttributes)
363                 throws ResolutionPlugInException {
364
365                 AttributeDefinitionPlugIn currentDefinition = (AttributeDefinitionPlugIn) lookupPlugIn(attribute.getName());
366
367                 //Check to see if we have already resolved the attribute during this request
368                 if (requestCache.containsKey(currentDefinition.getId())) {
369                         log.debug(
370                                 "Attribute ("
371                                         + currentDefinition.getId()
372                                         + ") already resolved for this request, using cached version");
373                         attribute.resolveFromCached((ResolverAttribute) requestCache.get(currentDefinition.getId()));
374                         return;
375                 }
376
377                 //Check to see if we have a cached resolution for this attribute
378                 if (currentDefinition.getTTL() > 0) {
379                         ResolverAttribute cachedAttribute =
380                                 resolverCache.getResolvedAttribute(principal, currentDefinition.getId());
381                         if (cachedAttribute != null) {
382                                 log.debug(
383                                         "Attribute ("
384                                                 + currentDefinition.getId()
385                                                 + ") resolution cached from a previous request, using cached version");
386                                 attribute.resolveFromCached(cachedAttribute);
387                                 return;
388                         }
389                 }
390
391                 //Resolve all attribute dependencies
392                 String[] attributeDependencies = currentDefinition.getAttributeDefinitionDependencyIds();
393                 Dependencies depends = new Dependencies();
394
395                 boolean dependancyOnly = false;
396                 for (int i = 0; attributeDependencies.length > i; i++) {
397                         log.debug(
398                                 "Attribute (" + attribute.getName() + ") depends on attribute (" + attributeDependencies[i] + ").");
399                         ResolverAttribute dependant = requestedAttributes.getByName(attributeDependencies[i]);
400                         if (dependant == null) {
401                                 dependancyOnly = true;
402                                 dependant = new DependentOnlyResolutionAttribute(attributeDependencies[i]);
403                         }
404                         resolveAttribute(dependant, principal, requester, requestCache, requestedAttributes);
405                         depends.addAttributeResolution(attributeDependencies[i], dependant);
406
407                 }
408
409                 //Resolve all connector dependencies
410                 String[] connectorDependencies = currentDefinition.getDataConnectorDependencyIds();
411                 for (int i = 0; connectorDependencies.length > i; i++) {
412                         log.debug(
413                                 "Attribute (" + attribute.getName() + ") depends on connector (" + connectorDependencies[i] + ").");
414                         //Check to see if we have already resolved the connector during this request
415                         if (requestCache.containsKey(connectorDependencies[i])) {
416                                 log.debug(
417                                         "Connector ("
418                                                 + connectorDependencies[i]
419                                                 + ") already resolved for this request, using cached version");
420                                 depends.addConnectorResolution(
421                                         connectorDependencies[i],
422                                         (Attributes) requestCache.get(connectorDependencies[i]));
423                         } else {
424                                 //Check to see if we have a cached resolution for this attribute
425                                 if (((DataConnectorPlugIn) lookupPlugIn(connectorDependencies[i])).getTTL() > 0) {
426                                         Attributes cachedAttributes =
427                                                 resolverCache.getResolvedConnector(principal, connectorDependencies[i]);
428                                         if (cachedAttributes != null) {
429                                                 log.debug(
430                                                         "Connector ("
431                                                                 + connectorDependencies[i]
432                                                                 + ") resolution cached from a previous request, using cached version");
433                                                 depends.addConnectorResolution(connectorDependencies[i], cachedAttributes);
434                                         }
435                                 }
436
437                                 Attributes resolvedConnector =
438                                         ((DataConnectorPlugIn) lookupPlugIn(connectorDependencies[i])).resolve(principal);
439                                 requestCache.put(connectorDependencies[i], resolvedConnector);
440                                 depends.addConnectorResolution(connectorDependencies[i], resolvedConnector);
441
442                                 //Add attribute resolution to cache
443                                 if (((DataConnectorPlugIn) lookupPlugIn(connectorDependencies[i])).getTTL() > 0) {
444                                         resolverCache.cacheConnectorResolution(
445                                                 principal,
446                                                 connectorDependencies[i],
447                                                 ((DataConnectorPlugIn) lookupPlugIn(connectorDependencies[i])).getTTL(),
448                                                 resolvedConnector);
449                                 }
450                         }
451                 }
452
453                 //Resolve the attribute
454                 currentDefinition.resolve(attribute, principal, requester, depends);
455
456                 //If necessary, cache for this request
457                 if (dependancyOnly || !attribute.hasValues()) {
458                         requestCache.put(currentDefinition.getId(), attribute);
459                 }
460
461                 //Add attribute resolution to cache
462                 if (currentDefinition.getTTL() > 0) {
463                         resolverCache.cacheAttributeResolution(
464                                 principal,
465                                 attribute.getName(),
466                                 currentDefinition.getTTL(),
467                                 attribute);
468                 }
469         }
470
471         private class DuplicatePlugInException extends Exception {
472                 public DuplicatePlugInException(String message) {
473                         super(message);
474                 }
475         }
476
477         class DependentOnlyResolutionAttribute implements ResolverAttribute {
478                 String name;
479                 ArrayList values = new ArrayList();
480                 boolean resolved = false;
481
482                 DependentOnlyResolutionAttribute(String name) {
483                         this.name = name;
484                 }
485
486                 public String getName() {
487                         return name;
488                 }
489
490                 public boolean resolved() {
491                         return resolved;
492                 }
493
494                 public void setResolved() {
495                         resolved = true;
496                 }
497
498                 public void resolveFromCached(ResolverAttribute attribute) {
499                 }
500
501                 public void setLifetime(long lifetime) {
502                 }
503
504                 public long getLifetime() {
505                         return 0;
506                 }
507
508                 public void addValue(Object value) {
509                         values.add(value);
510                 }
511
512                 public Iterator getValues() {
513                         return values.iterator();
514                 }
515
516                 public boolean hasValues() {
517                         if (values.isEmpty()) {
518                                 return false;
519                         }
520                         return true;
521                 }
522
523                 public void registerValueHandler(ValueHandler handler) {
524                 }
525
526                 public ValueHandler getRegisteredValueHandler() {
527                         return null;
528                 }
529         }
530
531 }