d8ab60325dd954bfc8015ccae5aca0ed04332dbf
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / common / ServiceProviderMapper.java
1 /*
2  * The Shibboleth License, Version 1. Copyright (c) 2002 University Corporation for Advanced Internet Development, Inc.
3  * All rights reserved Redistribution and use in source and binary forms, with or without modification, are permitted
4  * provided that the following conditions are met: Redistributions of source code must retain the above copyright
5  * notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above
6  * copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials
7  * provided with the distribution, if any, must include the following acknowledgment: "This product includes software
8  * developed by the University Corporation for Advanced Internet Development <http://www.ucaid.edu> Internet2 Project.
9  * Alternately, this acknowledegement may appear in the software itself, if and wherever such third-party
10  * acknowledgments normally appear. Neither the name of Shibboleth nor the names of its contributors, nor Internet2, nor
11  * the University Corporation for Advanced Internet Development, Inc., nor UCAID may be used to endorse or promote
12  * products derived from this software without specific prior written permission. For written permission, please contact
13  * shibboleth@shibboleth.org Products derived from this software may not be called Shibboleth, Internet2, UCAID, or the
14  * University Corporation for Advanced Internet Development, nor may Shibboleth appear in their name, without prior
15  * written permission of the University Corporation for Advanced Internet Development. THIS SOFTWARE IS PROVIDED BY THE
16  * COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE
18  * DISCLAIMED AND THE ENTIRE RISK OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE. IN NO
19  * EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC.
20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
23  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 package edu.internet2.middleware.shibboleth.common;
27
28 import java.net.MalformedURLException;
29 import java.net.URI;
30 import java.net.URISyntaxException;
31 import java.net.URL;
32 import java.util.HashMap;
33 import java.util.Map;
34
35 import org.apache.log4j.Logger;
36 import org.w3c.dom.Element;
37 import org.w3c.dom.NodeList;
38
39 import edu.internet2.middleware.shibboleth.idp.IdPConfig;
40 import edu.internet2.middleware.shibboleth.metadata.EntitiesDescriptor;
41 import edu.internet2.middleware.shibboleth.metadata.Metadata;
42 import edu.internet2.middleware.shibboleth.metadata.EntityDescriptor;
43
44 /**
45  * Class for determining the effective relying party from the unique id of the service provider. Checks first for an
46  * exact match on the service provider, then for membership in a federation. Uses the default relying party if neither
47  * is found.
48  * 
49  * @author Walter Hoehn
50  */
51 public class ServiceProviderMapper {
52
53         private static Logger log = Logger.getLogger(ServiceProviderMapper.class.getName());
54         protected Map relyingParties = new HashMap();
55         private Metadata metaData;
56         private IdPConfig configuration;
57         private Credentials credentials;
58         private NameMapper nameMapper;
59
60         public ServiceProviderMapper(Element rawConfig, IdPConfig configuration, Credentials credentials,
61                         NameMapper nameMapper) throws ServiceProviderMapperException {
62
63                 this.configuration = configuration;
64                 this.credentials = credentials;
65                 this.nameMapper = nameMapper;
66
67                 NodeList itemElements = rawConfig.getElementsByTagNameNS(IdPConfig.configNameSpace, "RelyingParty");
68
69                 for (int i = 0; i < itemElements.getLength(); i++) {
70                         addRelyingParty((Element) itemElements.item(i));
71                 }
72
73                 verifyDefaultParty(configuration);
74
75         }
76
77         public void setMetadata(Metadata metadata) {
78
79                 this.metaData = metadata;
80         }
81
82         private IdPConfig getOriginConfig() {
83
84                 return configuration;
85         }
86
87         protected void verifyDefaultParty(IdPConfig configuration) throws ServiceProviderMapperException {
88
89                 // Verify we have a proper default party
90                 String defaultParty = configuration.getDefaultRelyingPartyName();
91                 if (defaultParty == null || defaultParty.equals("")) {
92                         if (relyingParties.size() != 1) {
93                                 log
94                                                 .error("Default Relying Party not specified.  Add a (defaultRelyingParty) attribute to <IdPConfig>.");
95                                 throw new ServiceProviderMapperException("Required configuration not specified.");
96                         } else {
97                                 log.debug("Only one Relying Party loaded.  Using this as the default.");
98                         }
99                 }
100                 log.debug("Default Relying Party set to: (" + defaultParty + ").");
101                 if (!relyingParties.containsKey(defaultParty)) {
102                         log.error("Default Relying Party refers to a Relying Party that has not been loaded.");
103                         throw new ServiceProviderMapperException("Invalid configuration (Default Relying Party).");
104                 }
105         }
106
107         protected RelyingParty getRelyingPartyImpl(String providerIdFromTarget) {
108
109                 // Null request, send the default
110                 if (providerIdFromTarget == null) {
111                         RelyingParty relyingParty = getDefaultRelyingParty();
112                         log.info("Using default Relying Party: (" + relyingParty.getName() + ").");
113                         return new UnknownProviderWrapper(relyingParty, providerIdFromTarget);
114                 }
115
116                 // Look for a configuration for the specific relying party
117                 if (relyingParties.containsKey(providerIdFromTarget)) {
118                         log.info("Found Relying Party for (" + providerIdFromTarget + ").");
119                         return (RelyingParty) relyingParties.get(providerIdFromTarget);
120                 }
121
122                 // Next, check to see if the relying party is in any groups
123                 RelyingParty groupParty = findRelyingPartyByGroup(providerIdFromTarget);
124                 if (groupParty != null) {
125                         log.info("Provider is a member of Relying Party (" + groupParty.getName() + ").");
126                         return new RelyingPartyGroupWrapper(groupParty, providerIdFromTarget);
127                 }
128
129                 // OK, we can't find it... just send the default
130                 RelyingParty relyingParty = getDefaultRelyingParty();
131                 log.info("Could not locate Relying Party configuration for (" + providerIdFromTarget
132                                 + ").  Using default Relying Party: (" + relyingParty.getName() + ").");
133                 return new UnknownProviderWrapper(relyingParty, providerIdFromTarget);
134         }
135
136         private RelyingParty findRelyingPartyByGroup(String providerIdFromTarget) {
137
138                 if (metaData == null) { return null; }
139
140                 EntityDescriptor provider = metaData.lookup(providerIdFromTarget);
141                 if (provider != null) {
142                         EntitiesDescriptor parent = provider.getEntitiesDescriptor();
143                         while (parent != null) {
144                                 if (relyingParties.containsKey(parent.getName())) {
145                                         log.info("Found matching Relying Party for group (" + parent.getName() + ").");
146                                         return (RelyingParty) relyingParties.get(parent.getName());
147                                 } else {
148                                         log.debug("Provider is a member of group (" + parent.getName()
149                                                         + "), but no matching Relying Party was found.");
150                                 }
151                                 parent = parent.getEntitiesDescriptor();
152                         }
153                 }
154                 return null;
155         }
156
157         public RelyingParty getDefaultRelyingParty() {
158
159                 // If there is no explicit default, pick the single configured Relying
160                 // Party
161                 String defaultParty = getOriginConfig().getDefaultRelyingPartyName();
162                 if (defaultParty == null || defaultParty.equals("")) { return (RelyingParty) relyingParties.values().iterator()
163                                 .next(); }
164
165                 // If we do have a default specified, use it...
166                 return (RelyingParty) relyingParties.get(defaultParty);
167         }
168
169         /**
170          * Returns the relying party for a legacy provider(the default)
171          */
172         public RelyingParty getLegacyRelyingParty() {
173
174                 RelyingParty relyingParty = getDefaultRelyingParty();
175                 log.info("Request is from legacy shib target.  Selecting default Relying Party: (" + relyingParty.getName()
176                                 + ").");
177                 return new LegacyWrapper((RelyingParty) relyingParty);
178
179         }
180
181         /**
182          * Returns the appropriate relying party for the supplied service provider id.
183          */
184         public RelyingParty getRelyingParty(String providerIdFromTarget) {
185
186                 if (providerIdFromTarget == null || providerIdFromTarget.equals("")) {
187                         RelyingParty relyingParty = getDefaultRelyingParty();
188                         log.info("Selecting default Relying Party: (" + relyingParty.getName() + ").");
189                         return new NoMetadataWrapper((RelyingParty) relyingParty);
190                 }
191
192                 return (RelyingParty) getRelyingPartyImpl(providerIdFromTarget);
193         }
194
195         private void addRelyingParty(Element e) throws ServiceProviderMapperException {
196
197                 log.debug("Found a Relying Party.");
198                 try {
199                         if (e.getLocalName().equals("RelyingParty")) {
200                                 RelyingParty party = new RelyingPartyImpl(e, configuration, credentials, nameMapper);
201                                 log.debug("Relying Party (" + party.getName() + ") loaded.");
202                                 relyingParties.put(party.getName(), party);
203                         }
204                 } catch (ServiceProviderMapperException exc) {
205                         log.error("Encountered an error while attempting to load Relying Party configuration.  Skipping...");
206                 }
207
208         }
209
210         /**
211          * Base relying party implementation.
212          * 
213          * @author Walter Hoehn
214          */
215         protected class RelyingPartyImpl implements RelyingParty {
216
217                 private RelyingPartyIdentityProvider identityProvider;
218                 private String name;
219                 private String overridenOriginProviderId;
220                 private URL overridenAAUrl;
221                 private URI overridenDefaultAuthMethod;
222                 private String hsNameFormatId;
223                 private IdPConfig configuration;
224                 private boolean overridenPassThruErrors = false;
225                 private boolean passThruIsOverriden = false;
226                 private boolean forceAttributePush = false;
227                 private boolean forceAttributeNoPush = false;
228                 private boolean defaultToPOST = true;
229
230                 public RelyingPartyImpl(Element partyConfig, IdPConfig globalConfig, Credentials credentials,
231                                 NameMapper nameMapper) throws ServiceProviderMapperException {
232
233                         configuration = globalConfig;
234
235                         // Get party name
236                         name = ((Element) partyConfig).getAttribute("name");
237                         if (name == null || name.equals("")) {
238                                 log.error("Relying Party name not set.  Add a (name) attribute to <RelyingParty>.");
239                                 throw new ServiceProviderMapperException("Required configuration not specified.");
240                         }
241                         log.debug("Loading Relying Party: (" + name + ").");
242
243                         // Process overrides for global configuration data
244                         String attribute = ((Element) partyConfig).getAttribute("providerId");
245                         if (attribute != null && !attribute.equals("")) {
246                                 log.debug("Overriding providerId for Relying Pary (" + name + ") with (" + attribute + ").");
247                                 overridenOriginProviderId = attribute;
248                         }
249
250                         attribute = ((Element) partyConfig).getAttribute("AAUrl");
251                         if (attribute != null && !attribute.equals("")) {
252                                 log.debug("Overriding AAUrl for Relying Pary (" + name + ") with (" + attribute + ").");
253                                 try {
254                                         overridenAAUrl = new URL(attribute);
255                                 } catch (MalformedURLException e) {
256                                         log.error("(AAUrl) attribute to is not a valid URL.");
257                                         throw new ServiceProviderMapperException("Configuration is invalid.");
258                                 }
259                         }
260
261                         attribute = ((Element) partyConfig).getAttribute("defaultAuthMethod");
262                         if (attribute != null && !attribute.equals("")) {
263                                 log.debug("Overriding defaultAuthMethod for Relying Pary (" + name + ") with (" + attribute + ").");
264                                 try {
265                                         overridenDefaultAuthMethod = new URI(attribute);
266                                 } catch (URISyntaxException e1) {
267                                         log.error("(defaultAuthMethod) attribute to is not a valid URI.");
268                                         throw new ServiceProviderMapperException("Configuration is invalid.");
269                                 }
270                         }
271
272                         attribute = ((Element) partyConfig).getAttribute("passThruErrors");
273                         if (attribute != null && !attribute.equals("")) {
274                                 log.debug("Overriding passThruErrors for Relying Pary (" + name + ") with (" + attribute + ").");
275                                 overridenPassThruErrors = Boolean.valueOf(attribute).booleanValue();
276                                 passThruIsOverriden = true;
277                         }
278
279                         // SSO profile defaulting
280                         attribute = ((Element) partyConfig).getAttribute("defaultToPOSTProfile");
281                         if (attribute != null && !attribute.equals("")) {
282                                 defaultToPOST = Boolean.valueOf(attribute).booleanValue();
283                         }
284                         if (defaultToPOST) {
285                                 log.debug("Relying party defaults to POST profile.");
286                         } else {
287                                 log.debug("Relying party defaults to Artifact profile.");
288                         }
289
290                         // Determine whether or not we are forcing attribute push on or off
291                         String forcePush = ((Element) partyConfig).getAttribute("forceAttributePush");
292                         String forceNoPush = ((Element) partyConfig).getAttribute("forceAttributeNoPush");
293
294                         if (forcePush != null && Boolean.valueOf(forcePush).booleanValue() && forceNoPush != null
295                                         && Boolean.valueOf(forceNoPush).booleanValue()) {
296                                 log.error("Invalid configuration:  Attribute push is forced to ON and OFF for this relying "
297                                                 + "party.  Turning off forcing in favor of profile defaults.");
298                         } else {
299                                 forceAttributePush = Boolean.valueOf(forcePush).booleanValue();
300                                 forceAttributeNoPush = Boolean.valueOf(forceNoPush).booleanValue();
301                                 log.debug("Attribute push forcing is set to (" + forceAttributePush + ").");
302                                 log.debug("No attribute push forcing is set to (" + forceAttributeNoPush + ").");
303                         }
304
305                         // Load and verify the name format that the HS should use in
306                         // assertions for this RelyingParty
307                         NodeList hsNameFormats = ((Element) partyConfig).getElementsByTagNameNS(IdPConfig.configNameSpace,
308                                         "HSNameFormat");
309                         // If no specification. Make sure we have a default mapping
310                         if (hsNameFormats.getLength() < 1) {
311                                 if (nameMapper.getNameIdentifierMappingById(null) == null) {
312                                         log.error("Relying Party HS Name Format not set.  Add a <HSNameFormat> element to <RelyingParty>.");
313                                         throw new ServiceProviderMapperException("Required configuration not specified.");
314                                 }
315
316                         } else {
317                                 // We do have a specification, so make sure it points to a
318                                 // valid Name Mapping
319                                 if (hsNameFormats.getLength() > 1) {
320                                         log.warn("Found multiple HSNameFormat specifications for Relying Party (" + name
321                                                         + ").  Ignoring all but the first.");
322                                 }
323
324                                 hsNameFormatId = ((Element) hsNameFormats.item(0)).getAttribute("nameMapping");
325                                 if (hsNameFormatId == null || hsNameFormatId.equals("")) {
326                                         log.error("HS Name Format mapping not set.  Add a (nameMapping) attribute to <HSNameFormat>.");
327                                         throw new ServiceProviderMapperException("Required configuration not specified.");
328                                 }
329
330                                 if (nameMapper.getNameIdentifierMappingById(hsNameFormatId) == null) {
331                                         log.error("Relying Party HS Name Format refers to a name mapping that is not loaded.");
332                                         throw new ServiceProviderMapperException("Required configuration not specified.");
333                                 }
334                         }
335
336                         // Load the credential for signing
337                         String credentialName = ((Element) partyConfig).getAttribute("signingCredential");
338                         Credential signingCredential = credentials.getCredential(credentialName);
339                         if (signingCredential == null) {
340                                 if (credentialName == null || credentialName.equals("")) {
341                                         log.error("Relying Party credential not set.  Add a (signingCredential) "
342                                                         + "attribute to <RelyingParty>.");
343                                         throw new ServiceProviderMapperException("Required configuration not specified.");
344                                 } else {
345                                         log.error("Relying Party credential invalid.  Fix the (signingCredential) attribute "
346                                                         + "on <RelyingParty>.");
347                                         throw new ServiceProviderMapperException("Required configuration is invalid.");
348                                 }
349
350                         }
351
352                         // Initialize and Identity Provider object for this use by this relying party
353                         identityProvider = new RelyingPartyIdentityProvider(overridenOriginProviderId != null
354                                         ? overridenOriginProviderId
355                                         : configuration.getProviderId(), signingCredential);
356
357                 }
358
359                 public String getProviderId() {
360
361                         return name;
362                 }
363
364                 public String getName() {
365
366                         return name;
367                 }
368
369                 public IdentityProvider getIdentityProvider() {
370
371                         return identityProvider;
372                 }
373
374                 public boolean isLegacyProvider() {
375
376                         return false;
377                 }
378
379                 public String getHSNameFormatId() {
380
381                         return hsNameFormatId;
382                 }
383
384                 public URI getDefaultAuthMethod() {
385
386                         if (overridenDefaultAuthMethod != null) {
387                                 return overridenDefaultAuthMethod;
388                         } else {
389                                 return configuration.getDefaultAuthMethod();
390                         }
391                 }
392
393                 public URL getAAUrl() {
394
395                         if (overridenAAUrl != null) {
396                                 return overridenAAUrl;
397                         } else {
398                                 return configuration.getAAUrl();
399                         }
400                 }
401
402                 public boolean passThruErrors() {
403
404                         if (passThruIsOverriden) {
405                                 return overridenPassThruErrors;
406                         } else {
407                                 return configuration.passThruErrors();
408                         }
409                 }
410
411                 public boolean forceAttributePush() {
412
413                         return forceAttributePush;
414                 }
415
416                 public boolean forceAttributeNoPush() {
417
418                         return forceAttributeNoPush;
419                 }
420
421                 public boolean defaultToPOSTProfile() {
422
423                         return defaultToPOST;
424                 }
425
426                 /**
427                  * Default identity provider implementation.
428                  * 
429                  * @author Walter Hoehn
430                  */
431                 protected class RelyingPartyIdentityProvider implements IdentityProvider {
432
433                         private String providerId;
434                         private Credential credential;
435
436                         public RelyingPartyIdentityProvider(String providerId, Credential credential) {
437
438                                 this.providerId = providerId;
439                                 this.credential = credential;
440                         }
441
442                         /*
443                          * @see edu.internet2.middleware.shibboleth.common.IdentityProvider#getProviderId()
444                          */
445                         public String getProviderId() {
446
447                                 return providerId;
448                         }
449
450                         /*
451                          * @see edu.internet2.middleware.shibboleth.common.IdentityProvider#getSigningCredential()
452                          */
453                         public Credential getSigningCredential() {
454
455                                 return credential;
456                         }
457                 }
458
459         }
460
461         /**
462          * Relying party implementation wrapper for relying parties that are federations.
463          * 
464          * @author Walter Hoehn
465          */
466         class RelyingPartyGroupWrapper implements RelyingParty {
467
468                 private RelyingParty wrapped;
469                 private String providerId;
470
471                 RelyingPartyGroupWrapper(RelyingParty wrapped, String providerId) {
472
473                         this.wrapped = wrapped;
474                         this.providerId = providerId;
475                 }
476
477                 public String getName() {
478
479                         return wrapped.getName();
480                 }
481
482                 public boolean isLegacyProvider() {
483
484                         return false;
485                 }
486
487                 public IdentityProvider getIdentityProvider() {
488
489                         return wrapped.getIdentityProvider();
490                 }
491
492                 public String getProviderId() {
493
494                         return providerId;
495                 }
496
497                 public String getHSNameFormatId() {
498
499                         return wrapped.getHSNameFormatId();
500                 }
501
502                 public URL getAAUrl() {
503
504                         return wrapped.getAAUrl();
505                 }
506
507                 public URI getDefaultAuthMethod() {
508
509                         return wrapped.getDefaultAuthMethod();
510                 }
511
512                 public boolean passThruErrors() {
513
514                         return wrapped.passThruErrors();
515                 }
516
517                 public boolean forceAttributePush() {
518
519                         return wrapped.forceAttributePush();
520                 }
521
522                 public boolean forceAttributeNoPush() {
523
524                         return wrapped.forceAttributeNoPush();
525                 }
526
527                 public boolean defaultToPOSTProfile() {
528
529                         return wrapped.defaultToPOSTProfile();
530                 }
531         }
532
533         /**
534          * Relying party implementation wrapper for anonymous service providers.
535          * 
536          * @author Walter Hoehn
537          */
538         protected class UnknownProviderWrapper implements RelyingParty {
539
540                 protected RelyingParty wrapped;
541                 protected String providerId;
542
543                 protected UnknownProviderWrapper(RelyingParty wrapped, String providerId) {
544
545                         this.wrapped = wrapped;
546                         this.providerId = providerId;
547                 }
548
549                 public String getName() {
550
551                         return wrapped.getName();
552                 }
553
554                 public IdentityProvider getIdentityProvider() {
555
556                         return wrapped.getIdentityProvider();
557                 }
558
559                 public String getProviderId() {
560
561                         return providerId;
562                 }
563
564                 public String getHSNameFormatId() {
565
566                         return wrapped.getHSNameFormatId();
567                 }
568
569                 public boolean isLegacyProvider() {
570
571                         return wrapped.isLegacyProvider();
572                 }
573
574                 public URL getAAUrl() {
575
576                         return wrapped.getAAUrl();
577                 }
578
579                 public URI getDefaultAuthMethod() {
580
581                         return wrapped.getDefaultAuthMethod();
582                 }
583
584                 public boolean passThruErrors() {
585
586                         return wrapped.passThruErrors();
587                 }
588
589                 public boolean forceAttributePush() {
590
591                         return false;
592                 }
593
594                 public boolean forceAttributeNoPush() {
595
596                         return false;
597                 }
598
599                 public boolean defaultToPOSTProfile() {
600
601                         return true;
602                 }
603         }
604
605         /**
606          * Relying party wrapper for Shibboleth &lt;=1.1 service providers.
607          * 
608          * @author Walter Hoehn
609          */
610         class LegacyWrapper extends UnknownProviderWrapper implements RelyingParty {
611
612                 LegacyWrapper(RelyingParty wrapped) {
613
614                         super(wrapped, null);
615                 }
616
617                 public boolean isLegacyProvider() {
618
619                         return true;
620                 }
621
622                 public String getHSNameFormatId() {
623
624                         return ((RelyingParty) wrapped).getHSNameFormatId();
625                 }
626
627                 public URL getAAUrl() {
628
629                         return ((RelyingParty) wrapped).getAAUrl();
630                 }
631
632                 public URI getDefaultAuthMethod() {
633
634                         return ((RelyingParty) wrapped).getDefaultAuthMethod();
635                 }
636         }
637
638         /**
639          * Relying party wrapper for providers for which we have no metadata
640          * 
641          * @author Walter Hoehn
642          */
643         class NoMetadataWrapper extends UnknownProviderWrapper implements RelyingParty {
644
645                 NoMetadataWrapper(RelyingParty wrapped) {
646
647                         super(wrapped, null);
648                 }
649
650                 public String getHSNameFormatId() {
651
652                         return ((RelyingParty) wrapped).getHSNameFormatId();
653                 }
654
655                 public URL getAAUrl() {
656
657                         return ((RelyingParty) wrapped).getAAUrl();
658                 }
659
660                 public URI getDefaultAuthMethod() {
661
662                         return ((RelyingParty) wrapped).getDefaultAuthMethod();
663                 }
664         }
665 }