2 * ServiceProviderConfig.java
4 * A ServiceProviderConfig object holds an instance of the Shibboleth
5 * configuration data from the main configuration file and from all
6 * secondary files referenced by the main file.
8 * The configuration file is typically processed during Context
9 * initialization. In a Servlet environment, this is done from
10 * the ServletContextInitializer, while in JUnit testing it is
11 * done during test setup (unless you are testing configuration
12 * in which case it is part of the test itself). This occurs
13 * during init() processing and is inheritly synchronized.
15 * Initialization is a two step process. First create an
16 * instance of this class, then find a path to the configuration
17 * file and call loadConfigObjects().
19 * In addition to the option of loading external classes that
20 * implement one of the Plugin service interfaces by providing
21 * the name of the class in the type= attribute of the Plugin
22 * configuration XML, there is also a manual wiring interface.
23 * Create an implimenting object yourself, then add it to the
24 * configuration by passing an identifying URI and the object
25 * to a addOrReplaceXXXImplementation() method.
27 * These wiring calls are agressive, while the XML is passive.
28 * If the wiring call is made before loadConfigObject(), then
29 * XML referencing this same URI will find that it has already
30 * been loaded and use it. Alternately, if the call is made
31 * after loadConfigObject() then the XML will have processed
32 * the URI, loaded the file, and built an implimenting object.
33 * However, the wiring call will replace that object with the
34 * one provided in the call. Obviously making these calls
35 * first will be slightly more efficient, and is necessary if
36 * the XML configuration specifies URIs that will be provided
37 * by the wiring call and are not represented by any actual file.
39 * After initialization completes, this object and its arrays
40 * and collections should be structurally immutable. A map or
41 * array should not be changed by adding or removing members.
42 * Thus iteration over the collections can be unsynchronized.
43 * The reference to a value in the map can be swapped for a
44 * new object, because this doesn't effect iteration.
46 * Any method may obtain a copy of the current ServiceProviderConfig
47 * object by calling ServiceProviderContext.getServiceProviderConfig().
48 * This reference should only be held locally (for the duration
49 * of the request). Should the entire Shibboleth configuration file
50 * be reparsed (because of a dynamic update), then a new reference will
51 * be stored in the SPContext. Picking up a new reference for each
52 * request ensures that a program uses the latest configuration.
54 * When a secondary file (Metadata, Trust, AAP, etc.) is reloaded,
55 * a new object is constructed for that interface and the entry in
56 * the corresponding Map of providers of that interface is replaced.
57 * Therefore, non-local variables must only store the URI for such
58 * objects. A method can pass the URI to the Map lookup method and
59 * obtain a local variable reference to the current implementing
60 * object which can be used during the processing of the current
63 * Note: The URI for a secondary file cannot change just by
64 * reloading the file, but it can change if this main configuration
65 * file object is rebuilt. Therefore, if an external object stores
66 * a URI for a plugin object, it must be prepared for the Map lookup
67 * to return null. This would indicate that the main configuration
68 * file has been reloaded and the previously valid URI now no longer
69 * points to any implementing object.
71 * XML configuration data is parsed into two formats. First, it
72 * is processed by an ordinary JAXP XML parser into a W3C DOM format.
73 * The parser may validate the XML against an XSD schema, but the
74 * resulting DOM is "untyped". The XML becomes a tree of Element,
75 * Attribute, and Text nodes. The program must still convert an
76 * attribute or text string to a number, date, boolean, or any other
77 * data type even through the XSD declares that it must be of that
78 * type. The program must also search through the elements of the tree
79 * to find specific names for expected contents.
81 * This module then subjects the DOM to a secondary parse through
82 * some classes generated by compiling the XSD file with tools
83 * provided by the Apache XML Bean project. This turns the valid
84 * XML into strongly typed Java objects. A class is generated to
85 * represent every data type defined in the XSD schemas. Attribute
86 * values and child elements become properties of the objects of
87 * these classes. The XMLBean objects simplify the configuration
90 * If the configuration file directly reflected the program logic,
91 * the XML Bean classes would probably be enough. However, there
92 * are two important considerations:
94 * First, the Metadata is in transition. Currently we support an
95 * ad-hoc format defined by Shibboleth. However, it is expected
96 * that this will change in the next release to support a new
97 * standard accompanying SAML 2.0. The program logic anticipates
98 * this change, and is largely designed around concepts and
99 * structures of the new SAML standard. The actual configuration
100 * file and XML Beans support the old format, which must be mapped
101 * into this new structure.
103 * Second, secondary configuration elements (Credentials, Trust,
104 * Metadata, AAP, etc.) are "Pluggable" components. There is a
105 * built-in implementation of these services based on the XML
106 * configuration described in the Shibboleth documentation.
107 * However, the administrator can provide other classes that
108 * implement the required interfaces by simply coding the class
109 * name in the type= parameter of the XML element referencing the
110 * plugin. In this case we don't know the format of the opaque
111 * XML and simply pass it to the plugin.
114 * Dependencies: Requires XML Beans and the generated classes.
115 * Requires access to XSD schema files for configuration file formats.
116 * Logic depends on the order of enums in the XSD files.
118 * Error Strategy: A failure parsing the main configuration file
119 * prevents further processing. However, a problem parsing a plug-in
120 * configuration file should be noted while processing continues.
121 * This strategy reports all the errors in all the files to the log
122 * rather than stopping at the first error.
124 * --------------------
125 * Copyright 2002, 2004
126 * University Corporation for Advanced Internet Development, Inc.
127 * All rights reserved
128 * [Thats all we have to say to protect ourselves]
129 * Your permission to use this code is governed by "The Shibboleth License".
130 * A copy may be found at http://shibboleth.internet2.edu/license.html
131 * [Nothing in copyright law requires license text in every file.]
134 package edu.internet2.middleware.shibboleth.serviceprovider;
136 import java.net.MalformedURLException;
138 import java.util.ArrayList;
139 import java.util.Collection;
140 import java.util.Iterator;
141 import java.util.Map;
142 import java.util.TreeMap;
144 import org.apache.log4j.Logger;
145 import org.apache.xmlbeans.XmlException;
146 import org.apache.xmlbeans.XmlOptions;
147 import org.opensaml.SAMLAssertion;
148 import org.opensaml.SAMLAttribute;
149 import org.opensaml.SAMLAttributeStatement;
150 import org.opensaml.SAMLObject;
151 import org.w3c.dom.Document;
152 import org.w3c.dom.Element;
153 import org.w3c.dom.Node;
155 import x0.maceShibboleth1.AttributeAcceptancePolicyDocument;
156 import x0.maceShibbolethTargetConfig1.ApplicationDocument;
157 import x0.maceShibbolethTargetConfig1.PluggableType;
158 import x0.maceShibbolethTargetConfig1.RequestMapDocument;
159 import x0.maceShibbolethTargetConfig1.ShibbolethTargetConfigDocument;
160 import x0.maceShibbolethTargetConfig1.ApplicationDocument.Application;
161 import x0.maceShibbolethTargetConfig1.ApplicationsDocument.Applications;
162 import x0.maceShibbolethTargetConfig1.HostDocument.Host;
163 import x0.maceShibbolethTargetConfig1.PathDocument.Path;
164 import x0.maceShibbolethTargetConfig1.SHIREDocument.SHIRE;
165 import x0.maceShibbolethTargetConfig1.ShibbolethTargetConfigDocument.ShibbolethTargetConfig;
166 import edu.internet2.middleware.shibboleth.common.AAP;
167 import edu.internet2.middleware.shibboleth.common.AttributeRule;
168 import edu.internet2.middleware.shibboleth.common.Credentials;
169 import edu.internet2.middleware.shibboleth.common.ShibbolethConfigurationException;
170 import edu.internet2.middleware.shibboleth.common.XML;
171 import edu.internet2.middleware.shibboleth.metadata.EntityDescriptor;
172 import edu.internet2.middleware.shibboleth.metadata.EntityLocator;
173 import edu.internet2.middleware.shibboleth.metadata.Metadata;
174 import edu.internet2.middleware.shibboleth.metadata.Provider;
175 import edu.internet2.middleware.shibboleth.metadata.ProviderRole;
176 import edu.internet2.middleware.shibboleth.xml.Parser;
179 * Load the configuration files into objects, index them, and return them on request.
181 * <p>A new instance of the ServiceProviderConfig object can be created to
182 * parse a new version of the configuration file. It can then be swapped
183 * into the ServiceProviderContext reference and will be picked up by
184 * subsequent requests.</p>
186 * @author Howard Gilbert
188 public class ServiceProviderConfig {
191 private static final String INLINEURN = "urn:inlineBS:ID";
192 private static Logger log = Logger.getLogger(ServiceProviderConfig.class);
194 private ShibbolethTargetConfig // The XMLBean from the main config file
195 config = null; // (i.e. shibboleth.xml)
199 * The following Maps reference objects that implement a plugin
200 * interface indexed by their URI. There are builtin objects
201 * created from inline or external XML files, but external
202 * objects implementing the interfaces may be injected by
203 * calling the addOrReplaceXXX method. Public access to these
204 * Maps is indirect, through methods the ApplicationInfo object
205 * for a given configured or default application.
208 // Note EntityLocator extends and renames the old "Metadata" interface
209 private Map/*<String, EntityLocator>*/ entityLocators =
210 new TreeMap/*<String, EntityLocator>*/();
212 public void addOrReplaceMetadataImplementor(String uri, EntityLocator m) {
213 entityLocators.put(uri, m);
216 public EntityLocator getMetadataImplementor(String uri) {
217 return (EntityLocator) entityLocators.get(uri);
220 private Map/*<String, AAP>*/ attributePolicies =
221 new TreeMap/*<String, AAP>*/();
223 public void addOrReplaceAAPImplementor(String uri, AAP a) {
224 attributePolicies.put(uri,a);
227 public AAP getAAPImplementor(String uri) {
228 return (AAP) attributePolicies.get(uri);
231 private Map/*<String, ITrust>*/ certificateValidators =
232 new TreeMap/*<String, ITrust>*/();
234 public void addOrReplaceTrustImplementor(String uri, ITrust t) {
235 certificateValidators.put(uri,t);
238 public ITrust getTrustImplementor(String uri) {
239 return (ITrust) certificateValidators.get(uri);
244 * Objects created from the <Application(s)> elements.
245 * They manage collections of URI-Strings that index the
246 * previous maps to return Metadata, Trust, and AAP info
247 * applicable to this applicationId.
249 private Map/*<String, ApplicationInfo>*/ applications =
250 new TreeMap/*<String, ApplicationInfo>*/();
252 // Default application info from <Applications> element
253 private ApplicationInfo defaultApplicationInfo = null;
255 public ApplicationInfo getApplication(String applicationId) {
256 ApplicationInfo app=null;
257 app = (ApplicationInfo) applications.get(applicationId);
258 if (app==null) // If no specific match, return default
259 return defaultApplicationInfo;
264 // Objects created from single configuration file elements
265 private Credentials credentials = null;
266 private RequestMapDocument.RequestMap requestMap = null;
272 private final String SCHEMADIR = "/schemas/";
273 private final String MAINSCHEMA = SCHEMADIR + XML.MAIN_SHEMA_ID;
274 private final String METADATASCHEMA = SCHEMADIR + XML.SHIB_SCHEMA_ID;
275 private final String TRUSTSCHEMA = SCHEMADIR + XML.TRUST_SCHEMA_ID;
276 private final String AAPSCHEMA = SCHEMADIR + XML.SHIB_SCHEMA_ID;
278 private static final String XMLTRUSTPROVIDERTYPE =
279 "edu.internet2.middleware.shibboleth.common.provider.XMLTrust";
280 private static final String XMLAAPPROVIDERTYPE =
281 "edu.internet2.middleware.shibboleth.serviceprovider.XMLAAP";
282 private static final String XMLFEDERATIONPROVIDERTYPE =
283 "edu.internet2.middleware.shibboleth.common.provider.XMLMetadata";
284 private static final String XMLREVOCATIONPROVIDERTYPE =
285 "edu.internet2.middleware.shibboleth.common.provider.XMLRevocation";
286 private static final String XMLREQUESTMAPPROVIDERTYPE =
287 "edu.internet2.middleware.shibboleth.serviceprovider.XMLRequestMap";
288 private static final String XMLCREDENTIALSPROVIDERTYPE =
289 "edu.internet2.middleware.shibboleth.common.Credentials";
295 * The constructor prepares for, but does not parse the configuration.
297 * @throws ShibbolethConfigurationException
298 * if XML Parser cannot be initialized (Classpath problem)
300 public ServiceProviderConfig() {
304 * loadConfigObjects must be called once to parse the configuration.
306 * <p>To reload a modified configuration file, create and load a second
307 * object and swap the reference in the context object.</p>
309 * @param configFilePath URL or resource name of file
310 * @return the DOM Document
311 * @throws ShibbolethConfigurationException
312 * if there was an error loading the file
314 public synchronized void loadConfigObjects(String configFilePath)
315 throws ShibbolethConfigurationException {
318 log.error("ServiceProviderConfig.loadConfigObjects may not be called twice for the same object.");
319 throw new ShibbolethConfigurationException("Cannot reload configuration into same object.");
323 configDoc = Parser.loadDom(configFilePath, true);
324 if (configDoc==null) {
325 throw new ShibbolethConfigurationException("XML error in "+configFilePath);
327 loadConfigBean(configDoc);
333 * Given a URL, determine its ApplicationId from the RequestMap config.
335 * <p>Note: This is not a full implementation of all RequestMap
336 * configuration options. Other functions will be added as needed.</p>
338 public String mapRequest(String urlreq) {
339 String applicationId = "default";
343 url = new URL(urlreq);
344 } catch (MalformedURLException e) {
345 return applicationId;
348 String urlscheme = url.getProtocol();
349 String urlhostname = url.getHost();
350 String urlpath = url.getPath();
351 int urlport = url.getPort();
353 if (urlscheme.equals("http"))
355 else if (urlscheme.equals("https"))
359 // find Host entry for this virtual server
360 Host[] hostArray = requestMap.getHostArray();
361 for (int ihost=0;ihost<hostArray.length;ihost++) {
362 Host host = hostArray[ihost];
363 String hostScheme = host.getScheme().toString();
364 String hostName = host.getName();
365 String hostApplicationId = host.getApplicationId();
366 long hostport = host.getPort();
368 if (hostScheme.equals("http"))
370 else if (hostScheme.equals("https"))
374 if (!urlscheme.equals(hostScheme) ||
375 !urlhostname.equals(hostName)||
379 // find Path entry for this subdirectory
380 Path[] pathArray = host.getPathArray();
381 if (hostApplicationId!=null)
382 applicationId=hostApplicationId;
383 for (int i=0;i<pathArray.length;i++) {
384 String dirname = pathArray[i].getName();
385 if (urlpath.equals(dirname)||
386 urlpath.startsWith(dirname+"/")){
387 String pthid= pathArray[i].getApplicationId();
394 return applicationId;
398 * <p>Parse the main configuration file DOM into XML Bean</p>
400 * <p>Automatically load secondary configuration files designated
401 * by URLs in the main configuration file</p>
403 * @throws ShibbolethConfigurationException
405 private void loadConfigBean(Document configDoc)
406 throws ShibbolethConfigurationException {
407 boolean anyError=false;
408 ShibbolethTargetConfigDocument configBeanDoc;
410 // reprocess the already validated DOM to create a bean with typed fields
411 // dump the trash (comments, processing instructions, extra whitespace)
412 configBeanDoc = ShibbolethTargetConfigDocument.Factory.parse(configDoc,
413 new XmlOptions().setLoadStripComments().setLoadStripProcinsts().setLoadStripWhitespace());
414 config=configBeanDoc.getShibbolethTargetConfig();
415 } catch (XmlException e) {
416 // Since the DOM was already validated against the schema, errors will not typically occur here
417 log.error("Error while parsing shibboleth configuration");
418 throw new ShibbolethConfigurationException("Error while parsing shibboleth configuration");
421 // Extract the "root Element" object from the "Document" object
422 ShibbolethTargetConfig config = configBeanDoc.getShibbolethTargetConfig();
424 Applications apps = config.getApplications(); // <Applications>
429 * Create an <Application> id "default" from <Applications>
431 ApplicationDocument defaultAppDoc =
432 // Create a new XMLBeans "Document" level object
433 ApplicationDocument.Factory.newInstance();
434 ApplicationDocument.Application defaultApp =
435 // Add an XMLBeans "root Element" object to the Document
436 defaultAppDoc.addNewApplication();
437 // set or copy over fields from unrelated Applications object
438 defaultApp.setId("default");
439 defaultApp.setAAPProviderArray(apps.getAAPProviderArray());
440 defaultApp.setAttributeDesignatorArray(apps.getAttributeDesignatorArray());
441 defaultApp.setAudienceArray(apps.getAudienceArray());
442 defaultApp.setCredentialUse(apps.getCredentialUse());
443 defaultApp.setErrors(apps.getErrors());
444 defaultApp.setFederationProviderArray(apps.getFederationProviderArray());
445 defaultApp.setProviderId(apps.getProviderId());
446 defaultApp.setRevocationProviderArray(apps.getRevocationProviderArray());
447 defaultApp.setSessions(apps.getSessions());
448 defaultApp.setSignedAssertions(apps.getSignedAssertions());
449 defaultApp.setSignedResponse(apps.getSignedResponse());
450 defaultApp.setSignRequest(apps.getSignRequest());
451 defaultApp.setTrustProviderArray(apps.getTrustProviderArray());
454 * Now process secondary files configured in the applications
456 anyError |= processApplication(defaultApp);
458 Application[] apparray = apps.getApplicationArray();
459 for (int i=0;i<apparray.length;i++){
460 Application tempapp = apparray[i];
461 applications.put(tempapp.getId(),tempapp);
462 anyError |= processApplication(tempapp);
466 * Now process other secondary files
468 anyError |= processCredentials();
469 anyError |= processPluggableRequestMapProvider();
472 throw new ShibbolethConfigurationException("Errors processing configuration file, see log");
477 * Routine to handle CredentialProvider
479 * <p>Note: This only handles in-line XML.
480 * Also, Credentials was an existing Origin class, so it doesn't
481 * implement the new PluggableConfigurationComponent interface and
482 * can't be loaded by generic plugin support.
485 private boolean processCredentials() {
486 boolean anyError=false;
487 PluggableType[] pluggable = config.getCredentialsProviderArray();
488 for (int i=0;i<pluggable.length;i++) {
489 String pluggabletype = pluggable[i].getType();
490 if (!pluggabletype.equals(
491 "edu.internet2.middleware.shibboleth.common.Credentials")) {
492 log.error("Unsupported CredentialsProvider type "+pluggabletype);
496 PluggableType credentialsProvider = pluggable[i];
497 Node fragment = credentialsProvider.newDomNode();
498 // newDomNode returns the current node wrapped in a Fragment
500 Node credentialsProviderNode = fragment.getFirstChild();
501 Node credentialsNode=credentialsProviderNode.getFirstChild();
502 credentials = new Credentials((Element)credentialsNode);
503 } catch(Exception e) {
504 log.error("Cannot process Credentials element of Shibboleth configuration");
514 * Find and load secondary configuration files referenced in an Application(s)
516 * @param app Application object
517 * @throws ShibbolethConfigurationException
519 private boolean processApplication(Application app)
520 throws ShibbolethConfigurationException {
522 boolean anyError=false;
524 String applicationId = app.getId();
526 ApplicationInfo appinfo = new ApplicationInfo(app);
528 anyError |= processPluggableMetadata(appinfo);
529 anyError |= processPluggableAAPs(appinfo);
530 anyError |= processPluggableTrusts(appinfo);
532 applications.put(applicationId, appinfo);
538 * Generic code to create an object of a Pluggable type that implements
539 * a configuration interface.
541 * <p>The configuration schema defines "PluggableType" as a type of
542 * XML element that has opaque contents and attributes "type" and
543 * "uri". If the uri attribute is omitted, then the configuration
544 * data is inline XML content. The XSD files typically define the
545 * format of pluggable configuration elements, but without binding
546 * them to the PluggableType element that may contain them.</p>
548 * <p>The implimentation of pluggable objects is provided by
549 * external classes. There are "builtin" classes provided with
550 * Shibboleth (XMLMetadataImpl, XMLTrustImpl, XMLAAPImpl) that
551 * provide examples of how this is done. By design, others can
552 * provide their own classes just by putting the class name as
553 * the value of the type attribute.</p>
555 * <p>This routine handles the common setup. It creates objects
556 * of one of the builtin types, or it uses Class.forName() to
557 * access a user specified class. It then locates either the
558 * inline XML elements or the external XML file. It passes the
559 * XML to initialize the object. Finally, a reference to the
560 * object is stored in the appropriate Map.</p>
562 * <p>The objects created implement two interfaces. Mostly they
563 * implement a configuration interface (EntityDescriptor, ITrust,
564 * AAP, etc). However, for the purpose of this routine they also
565 * must be declared to implement PluggableConfigurationComponent
566 * and provide an initialize() method that parses a DOM Node
567 * containing their root XML configuration element.</p>
569 * @param pluggable XMLBean for element defined in XSD to be of "PluggableType"
570 * @param implclass java.lang.Class of Builtin implementation class
571 * @param interfaceClass java.lang.Class of Interface
572 * @param builtinName alias type to choose Builtin imlementation
573 * @param uriMap ApplicationInfo Map for this interface
579 PluggableType pluggable,
581 Class interfaceClass,
584 Map /*<String,PluggableConfigurationComponent>*/uriMap
587 String pluggabletype = pluggable.getType();
589 if (!pluggabletype.equals(builtinName)) {
590 // Not the builtin type, try to load user class by name
592 implclass = Class.forName(pluggabletype);
593 } catch (ClassNotFoundException e) {
594 log.error("Type value "+pluggabletype+" not found as supplied Java class");
597 if (!interfaceClass.isAssignableFrom(implclass)||
598 !PluggableConfigurationComponent.class.isAssignableFrom(implclass)) {
599 log.error(pluggabletype+" class does not support required interfaces.");
604 PluggableConfigurationComponent impl;
606 impl = (PluggableConfigurationComponent) implclass.newInstance();
607 } catch (Exception e) {
608 log.error("Unable to instantiate "+pluggabletype);
612 String uri = pluggable.getUri();
613 if (uri==null) { // inline
617 Node fragment = pluggable.newDomNode(); // XML-Fragment node
618 Node pluggableNode = fragment.getFirstChild(); // PluggableType
619 Node contentNode=pluggableNode.getFirstChild();// root element
620 impl.initialize(contentNode);
621 } catch (Exception e) {
622 log.error("XML error " + e);
626 } else { // external file
628 if (uriMap.get(uri)!=null) { // Already parsed this file
632 String tempname = impl.getSchemaPathname();
637 Document extdoc = Parser.loadDom(uri,true);
640 impl.initialize(extdoc);
641 } catch (Exception e) {
642 log.error("XML error " + e);
647 uriMap.put(uri,impl);
654 * Handle a FederationProvider
656 private boolean processPluggableMetadata(ApplicationInfo appinfo) {
657 boolean anyError = false;
658 PluggableType[] pluggable = appinfo.getApplicationConfig().getFederationProviderArray();
659 for (int i = 0;i<pluggable.length;i++) {
660 String uri = processPluggable(pluggable[i],
661 XMLMetadataImpl.class,
663 XMLFEDERATIONPROVIDERTYPE,
668 else if (uri.length()>0) {
669 appinfo.addGroupUri(uri);
676 * Reload XML Metadata configuration after file changed.
677 * @param uri Path to Metadata XML configuration
678 * @return true if file reloaded.
680 public boolean reloadFederation(String uri) {
681 if (getMetadataImplementor(uri)!=null||
682 uri.startsWith(INLINEURN))
685 Document sitedoc = Parser.loadDom(uri,true);
688 XMLMetadataImpl impl = new XMLMetadataImpl();
689 impl.initialize(sitedoc);
690 addOrReplaceMetadataImplementor(uri,impl);
691 } catch (Exception e) {
692 log.error("Error while parsing Metadata file "+uri);
693 log.error("XML error " + e);
700 * Handle an AAPProvider element with
701 * type="edu.internet2.middleware.shibboleth.common.provider.XMLAAP"
702 * @throws InternalConfigurationException
704 private boolean processPluggableAAPs(ApplicationInfo appinfo){
705 boolean anyError=false;
706 PluggableType[] pluggable = appinfo.getApplicationConfig().getAAPProviderArray();
707 for (int i = 0;i<pluggable.length;i++) {
708 String uri = processPluggable(pluggable[i],
716 else if (uri.length()>0) {
717 appinfo.addAapUri(uri);
724 * Reload XML AAP configuration after file changed.
725 * @param uri AAP to Trust XML configuration
726 * @return true if file reloaded.
728 public boolean reloadAAP(String uri) {
729 if (getAAPImplementor(uri)!=null||
730 uri.startsWith(INLINEURN))
733 Document aapdoc = Parser.loadDom(uri,true);
736 AttributeAcceptancePolicyDocument aap = AttributeAcceptancePolicyDocument.Factory.parse(aapdoc);
737 XMLAAPImpl impl = new XMLAAPImpl();
738 impl.initialize(aapdoc);
739 addOrReplaceAAPImplementor(uri,impl);
740 } catch (Exception e) {
741 log.error("Error while parsing AAP file "+uri);
742 log.error("XML error " + e);
750 * Handle a TrustProvider element with
751 * type="edu.internet2.middleware.shibboleth.common.provider.XMLTrust"
753 * Note: This code builds the semantic structure of trust. That is, it knows
754 * about certificates and keys. The actual logic of Trust (signature generation
755 * and validation) is implemented in a peer object defined in the external
756 * class XMLTrustImpl.
758 * @throws ShibbolethConfigurationException if X.509 certificate cannot be processed
759 * @throws InternalConfigurationException
761 private boolean processPluggableTrusts(ApplicationInfo appinfo){
762 boolean anyError=false;
763 PluggableType[] pluggable = appinfo.getApplicationConfig().getTrustProviderArray();
764 for (int i = 0;i<pluggable.length;i++) {
765 String uri = processPluggable(pluggable[i],
768 XMLTRUSTPROVIDERTYPE,
770 certificateValidators);
773 else if (uri.length()>0) {
774 appinfo.addTrustUri(uri);
781 * Reload XML Trust configuration after file changed.
782 * @param uri Path to Trust XML configuration
783 * @return true if file reloaded.
785 public boolean reloadTrust(String uri) {
786 if (getTrustImplementor(uri)!=null||
787 uri.startsWith(INLINEURN))
790 Document trustdoc = Parser.loadDom(uri,true);
793 XMLTrustImpl impl = new XMLTrustImpl();
794 impl.initialize(trustdoc);
795 addOrReplaceTrustImplementor(uri,impl);
796 } catch (Exception e) {
797 log.error("Error while parsing Trust file "+uri);
798 log.error("XML error " + e);
805 private boolean processPluggableRequestMapProvider(){
806 SHIRE shire = config.getSHIRE();
807 PluggableType mapProvider = shire.getRequestMapProvider();
809 String pluggabletype = mapProvider.getType();
810 if (!pluggabletype.equals(XMLREQUESTMAPPROVIDERTYPE)) {
811 log.error("Unsupported RequestMapProvider type "+pluggabletype);
815 RequestMapDocument requestMapDoc = null;
816 Document mapdoc = null;
817 Element maproot = null;
818 String uri = mapProvider.getUri();
820 if (uri==null) { // inline
824 Node fragment = mapProvider.newDomNode();
825 Node pluggableNode = fragment.getFirstChild();
826 Node contentNode=pluggableNode.getFirstChild();
828 requestMapDoc = RequestMapDocument.Factory.parse(contentNode);
829 } catch (Exception e) {
830 log.error("Error while parsing inline RequestMap");
831 log.error("XML error " + e);
835 } else { // external file
837 mapdoc = Parser.loadDom(uri,true);
840 requestMapDoc = RequestMapDocument.Factory.parse(mapdoc);
841 } catch (Exception e) {
842 log.error("Error while parsing RequestMap file "+uri);
843 log.error("XML error " + e);
848 requestMap = requestMapDoc.getRequestMap();
854 private int inlinenum = 1;
855 private String genDummyUri() {
856 return INLINEURN+Integer.toString(inlinenum++);
865 * ApplicationInfo represents the <Application(s)> object, its fields,
866 * and the pluggable configuration elements under it.
868 * <p>It can return arrays of Metadata, Trust, or AAP providers, but
869 * it also exposes convenience methods that shop the lookup(),
870 * validate(), and trust() calls to each object in the collection
871 * until success or failure is determined.</p>
873 * <p>For all other parameters, such as Session parameters, you
874 * can fetch the XMLBean by calling getApplicationConf() and
875 * query their value directly.
877 class ApplicationInfo
878 implements EntityLocator, ITrust {
880 private Application applicationConfig;
881 public Application getApplicationConfig() {
882 return applicationConfig;
886 * Construct this object from the XML Bean.
887 * @param application XMLBean for Application element
889 ApplicationInfo(Application application) {
890 this.applicationConfig=application;
895 * Following the general rule, this object may not keep
896 * direct references to the plugin interface implementors,
897 * but must look them up on every call through their URI keys.
898 * So we keep collections of URI strings instead.
900 ArrayList groupUris = new ArrayList();
901 ArrayList trustUris = new ArrayList();
902 ArrayList aapUris = new ArrayList();
904 void addGroupUri(String uri) {
907 void addTrustUri(String uri) {
910 void addAapUri(String uri) {
915 * Return the current array of objects that implement the
916 * ...metadata.Metadata interface
920 Metadata[] getMetadataProviders() {
921 Iterator iuris = groupUris.iterator();
922 int count = groupUris.size();
923 Metadata[] metadatas = new Metadata[count];
924 for (int i=0;i<count;i++) {
925 String uri =(String) iuris.next();
926 metadatas[i]=getMetadataImplementor(uri);
932 * A convenience function based on the Metadata interface.
934 * <p>Look for an entity ID through each implementor until the
935 * first one finds locates a describing object.</p>
937 * <p>Unfortunately, Metadata.lookup() was originally specified to
938 * return a "Provider". In current SAML 2.0 terms, the object
939 * returned should be an EntityDescriptor. So this is the new
940 * function in the new interface that will use the new term, but
941 * it does the same thing.</p>
943 * @param id ID of the OriginSite entity
944 * @return EntityDescriptor metadata object for that site.
946 public EntityDescriptor getEntityDescriptor(String id) {
947 Iterator iuris = groupUris.iterator();
948 while (iuris.hasNext()) {
949 String uri =(String) iuris.next();
950 EntityLocator locator=getMetadataImplementor(uri);
951 EntityDescriptor entity = locator.getEntityDescriptor(id);
959 * Convenience function to fulfill Metadata interface contract.
961 * @param id ID of OriginSite
962 * @return Provider object for that Site.
964 public Provider lookup(String id) {
965 return getEntityDescriptor(id);
969 * Return the current array of objects that implement the ITrust interface
973 public ITrust[] getTrustProviders() {
974 Iterator iuris = groupUris.iterator();
975 int count = groupUris.size();
976 ITrust[] trusts = new ITrust[count];
977 for (int i=0;i<count;i++) {
978 String uri =(String) iuris.next();
979 trusts[i]=getTrustImplementor(uri);
985 * Return the current array of objects that implement the AAP interface
989 public AAP[] getAAPProviders() {
990 Iterator iuris = aapUris.iterator();
991 int count = aapUris.size();
992 AAP[] aaps = new AAP[count];
993 for (int i=0;i<count;i++) {
994 String uri =(String) iuris.next();
995 aaps[i]=getAAPImplementor(uri);
1001 * Convenience function to apply AAP by calling the apply()
1002 * method of each AAP implementor.
1004 * <p>Any AAP implementor can delete an assertion or value.
1005 * Empty SAML elements get removed from the assertion.
1006 * This can yield an AttributeAssertion with no attributes.
1008 * @param entity Origin site that sent the assertion
1009 * @param assertion SAML Attribute Assertion
1011 void applyAAP(EntityDescriptor entity, SAMLAssertion assertion) {
1013 // Foreach AAP in the collection
1014 AAP[] providers = getAAPProviders();
1015 for (int i=0;i<providers.length;i++) {
1016 AAP aap = providers[i];
1017 if (aap.isAnyAttribute())
1020 // Foreach Statement in the Assertion
1021 Iterator statements = assertion.getStatements();
1023 while (statements.hasNext()) {
1024 Object statement = statements.next();
1025 if (statement instanceof SAMLAttributeStatement) {
1026 SAMLAttributeStatement attributeStatement =
1027 (SAMLAttributeStatement) statement;
1029 // Foreach Attribute in the AttributeStatement
1030 Iterator attributes = attributeStatement.getAttributes();
1032 while (attributes.hasNext()) {
1033 SAMLAttribute attribute =
1034 (SAMLAttribute) attributes.next();
1035 String name = attribute.getName();
1036 String namespace = attribute.getNamespace();
1037 AttributeRule rule = aap.lookup(name,namespace);
1039 // TODO Not sure, but code appears to keep unknown attributes
1040 log.warn("No rule found for attribute "+name);
1044 rule.apply(entity,attribute);
1045 if (!attribute.getValues().hasNext())
1046 attributeStatement.removeAttribute(iattribute);
1051 if (!attributeStatement.getAttributes().hasNext())
1052 assertion.removeStatement(istatement);
1064 * Returns a collection of attribute names to request from the AA.
1066 * @return Collection of attribute Name values
1068 public Collection getAttributeDesignators() {
1069 // TODO Not sure where this should come from
1070 return new ArrayList();
1075 * Convenience method implementing ITrust.validate() across
1076 * the collection of implementing objects. Returns true if
1077 * any Trust implementor approves the signatures in the object.
1079 * <p>In the interface, validate() is passed several arguments
1080 * that come from this object. In this function, those
1081 * arguments are ignored "this" is used.
1085 Iterator revocations, // Currently unused
1088 EntityLocator dummy // "this" is an EntityLocator
1091 // TODO If revocations are supported, "this" will provide them
1093 ITrust[] trustProviders = getTrustProviders();
1094 for (int i=0;i<trustProviders.length;i++) {
1095 ITrust trust = trustProviders[i];
1096 if (trust.validate(null,role,token,this))
1103 * Simpler version of validate that avoids dummy arguments
1105 * @param role Entity that sent Token (from Metadata)
1106 * @param token Signed SAMLObject
1109 public boolean validate(ProviderRole role, SAMLObject token) {
1110 return validate(null,role,token,null);
1114 * A method of ITrust that we must declare to claim that
1115 * ApplicationInfo implements ITrust. However, no code in the
1116 * ServiceProvider calls this (probably an Origin thing).
1118 * @param revocations
1120 * @return This dummy always returns false.
1122 public boolean attach(Iterator revocations, ProviderRole role) {
1131 private static class InternalConfigurationException extends Exception {
1132 InternalConfigurationException() {