Code cleanup: removed some Shibboleth 1.1 compatibility code.
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / common / ServiceProviderMapper.java
1 /*
2  * Copyright [2005] [University Corporation for Advanced Internet Development, Inc.]
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package edu.internet2.middleware.shibboleth.common;
18
19 import java.net.MalformedURLException;
20 import java.net.URI;
21 import java.net.URISyntaxException;
22 import java.net.URL;
23 import java.util.ArrayList;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27
28 import org.apache.log4j.Logger;
29 import org.w3c.dom.Element;
30 import org.w3c.dom.NodeList;
31
32 import edu.internet2.middleware.shibboleth.idp.IdPConfig;
33 import edu.internet2.middleware.shibboleth.metadata.EntitiesDescriptor;
34 import edu.internet2.middleware.shibboleth.metadata.EntityDescriptor;
35 import edu.internet2.middleware.shibboleth.metadata.Metadata;
36
37 /**
38  * Class for determining the effective relying party from the unique id of the service provider. Checks first for an
39  * exact match on the service provider, then for membership in a group of providers (perhaps a federation). Uses the
40  * default relying party if neither is found.
41  * 
42  * @author Walter Hoehn
43  */
44 public class ServiceProviderMapper {
45
46         private static Logger log = Logger.getLogger(ServiceProviderMapper.class.getName());
47         protected Map relyingParties = new HashMap();
48         private Metadata metaData;
49         private IdPConfig configuration;
50         private Credentials credentials;
51         private NameMapper nameMapper;
52
53         public ServiceProviderMapper(Element rawConfig, IdPConfig configuration, Credentials credentials,
54                         NameMapper nameMapper) throws ServiceProviderMapperException {
55
56                 this.configuration = configuration;
57                 this.credentials = credentials;
58                 this.nameMapper = nameMapper;
59
60                 NodeList itemElements = rawConfig.getElementsByTagNameNS(IdPConfig.configNameSpace, "RelyingParty");
61
62                 for (int i = 0; i < itemElements.getLength(); i++) {
63                         addRelyingParty((Element) itemElements.item(i));
64                 }
65
66                 verifyDefaultParty(configuration);
67
68         }
69
70         public void setMetadata(Metadata metadata) {
71
72                 this.metaData = metadata;
73         }
74
75         private IdPConfig getIdPConfig() {
76
77                 return configuration;
78         }
79
80         protected void verifyDefaultParty(IdPConfig configuration) throws ServiceProviderMapperException {
81
82                 // Verify we have a proper default party
83                 String defaultParty = configuration.getDefaultRelyingPartyName();
84                 if (defaultParty == null || defaultParty.equals("")) {
85                         if (relyingParties.size() != 1) {
86                                 log
87                                                 .error("Default Relying Party not specified.  Add a (defaultRelyingParty) attribute to <IdPConfig>.");
88                                 throw new ServiceProviderMapperException("Required configuration not specified.");
89                         } else {
90                                 log.debug("Only one Relying Party loaded.  Using this as the default.");
91                         }
92                 }
93                 log.debug("Default Relying Party set to: (" + defaultParty + ").");
94                 if (!relyingParties.containsKey(defaultParty)) {
95                         log.error("Default Relying Party refers to a Relying Party that has not been loaded.");
96                         throw new ServiceProviderMapperException("Invalid configuration (Default Relying Party).");
97                 }
98         }
99
100         protected RelyingParty getRelyingPartyImpl(String providerIdFromSP) {
101
102                 // Null request, send the default
103                 if (providerIdFromSP == null) {
104                         RelyingParty relyingParty = getDefaultRelyingParty();
105                         log.info("Using default Relying Party: (" + relyingParty.getName() + ").");
106                         return new UnknownProviderWrapper(relyingParty, providerIdFromSP);
107                 }
108
109                 // Look for a configuration for the specific relying party
110                 if (relyingParties.containsKey(providerIdFromSP)) {
111                         log.info("Found Relying Party for (" + providerIdFromSP + ").");
112                         return (RelyingParty) relyingParties.get(providerIdFromSP);
113                 }
114
115                 // Next, check to see if the relying party is in any groups
116                 RelyingParty groupParty = findRelyingPartyByGroup(providerIdFromSP);
117                 if (groupParty != null) {
118                         log.info("Provider is a member of Relying Party (" + groupParty.getName() + ").");
119                         return new RelyingPartyGroupWrapper(groupParty, providerIdFromSP);
120                 }
121
122                 // OK, we can't find it... just send the default
123                 RelyingParty relyingParty = getDefaultRelyingParty();
124                 log.info("Could not locate Relying Party configuration for (" + providerIdFromSP
125                                 + ").  Using default Relying Party: (" + relyingParty.getName() + ").");
126                 return new UnknownProviderWrapper(relyingParty, providerIdFromSP);
127         }
128
129         private RelyingParty findRelyingPartyByGroup(String providerIdFromSP) {
130
131                 if (metaData == null) { return null; }
132
133                 EntityDescriptor provider = metaData.lookup(providerIdFromSP);
134                 if (provider != null) {
135                         EntitiesDescriptor parent = provider.getEntitiesDescriptor();
136                         while (parent != null) {
137                                 if (parent.getName() != null) {
138                                         if (relyingParties.containsKey(parent.getName())) {
139                                                 log.info("Found matching Relying Party for group (" + parent.getName() + ").");
140                                                 return (RelyingParty) relyingParties.get(parent.getName());
141                                         } else {
142                                                 log.debug("Provider is a member of group (" + parent.getName()
143                                                                 + "), but no matching Relying Party was found.");
144                                         }
145                                 }
146                                 parent = parent.getEntitiesDescriptor();
147                         }
148                 }
149                 return null;
150         }
151
152         public RelyingParty getDefaultRelyingParty() {
153
154                 // If there is no explicit default, pick the single configured Relying
155                 // Party
156                 String defaultParty = getIdPConfig().getDefaultRelyingPartyName();
157                 if (defaultParty == null || defaultParty.equals("")) { return (RelyingParty) relyingParties.values().iterator()
158                                 .next(); }
159
160                 // If we do have a default specified, use it...
161                 return (RelyingParty) relyingParties.get(defaultParty);
162         }
163
164         /**
165          * Returns the appropriate relying party for the supplied service provider id.
166          */
167         public RelyingParty getRelyingParty(String providerIdFromSP) {
168
169                 if (providerIdFromSP == null || providerIdFromSP.equals("")) {
170                         RelyingParty relyingParty = getDefaultRelyingParty();
171                         log.info("Selecting default Relying Party: (" + relyingParty.getName() + ").");
172                         return new NoMetadataWrapper((RelyingParty) relyingParty);
173                 }
174
175                 return (RelyingParty) getRelyingPartyImpl(providerIdFromSP);
176         }
177
178         private void addRelyingParty(Element e) throws ServiceProviderMapperException {
179
180                 log.debug("Found a Relying Party.");
181                 try {
182                         if (e.getLocalName().equals("RelyingParty")) {
183                                 RelyingParty party = new RelyingPartyImpl(e, configuration, credentials, nameMapper);
184                                 log.debug("Relying Party (" + party.getName() + ") loaded.");
185                                 relyingParties.put(party.getName(), party);
186                         }
187                 } catch (ServiceProviderMapperException exc) {
188                         log.error("Encountered an error while attempting to load Relying Party configuration.  Skipping...");
189                 }
190
191         }
192
193         /**
194          * Base relying party implementation.
195          * 
196          * @author Walter Hoehn
197          */
198         protected class RelyingPartyImpl implements RelyingParty {
199
200                 private RelyingPartyIdentityProvider identityProvider;
201                 private String name;
202                 private String overridenIdPProviderId;
203                 private URL overridenAAUrl;
204                 private URI overridenDefaultAuthMethod;
205                 private List mappingIds = new ArrayList();
206                 private IdPConfig configuration;
207                 private boolean overridenPassThruErrors = false;
208                 private boolean passThruIsOverriden = false;
209                 private boolean forceAttributePush = false;
210                 private boolean forceAttributeNoPush = false;
211                 private boolean singleAssertion = false;
212                 private boolean defaultToPOST = true;
213                 private boolean wantsAssertionsSigned = false;
214                 private int preferredArtifactType = 1;
215                 private String defaultTarget;
216                 private boolean wantsSchemaHack = false;
217
218                 public RelyingPartyImpl(Element partyConfig, IdPConfig globalConfig, Credentials credentials,
219                                 NameMapper nameMapper) throws ServiceProviderMapperException {
220
221                         configuration = globalConfig;
222
223                         // Get party name
224                         name = ((Element) partyConfig).getAttribute("name");
225                         if (name == null || name.equals("")) {
226                                 log.error("Relying Party name not set.  Add a (name) attribute to <RelyingParty>.");
227                                 throw new ServiceProviderMapperException("Required configuration not specified.");
228                         }
229                         log.debug("Loading Relying Party: (" + name + ").");
230
231                         // Process overrides for global configuration data
232                         String attribute = ((Element) partyConfig).getAttribute("providerId");
233                         if (attribute != null && !attribute.equals("")) {
234                                 log.debug("Overriding providerId for Relying Pary (" + name + ") with (" + attribute + ").");
235                                 overridenIdPProviderId = attribute;
236                         }
237
238                         attribute = ((Element) partyConfig).getAttribute("AAUrl");
239                         if (attribute != null && !attribute.equals("")) {
240                                 log.debug("Overriding AAUrl for Relying Pary (" + name + ") with (" + attribute + ").");
241                                 try {
242                                         overridenAAUrl = new URL(attribute);
243                                 } catch (MalformedURLException e) {
244                                         log.error("(AAUrl) attribute to is not a valid URL.");
245                                         throw new ServiceProviderMapperException("Configuration is invalid.");
246                                 }
247                         }
248
249                         attribute = ((Element) partyConfig).getAttribute("defaultAuthMethod");
250                         if (attribute != null && !attribute.equals("")) {
251                                 log.debug("Overriding defaultAuthMethod for Relying Pary (" + name + ") with (" + attribute + ").");
252                                 try {
253                                         overridenDefaultAuthMethod = new URI(attribute);
254                                 } catch (URISyntaxException e1) {
255                                         log.error("(defaultAuthMethod) attribute to is not a valid URI.");
256                                         throw new ServiceProviderMapperException("Configuration is invalid.");
257                                 }
258                         }
259
260                         attribute = ((Element) partyConfig).getAttribute("passThruErrors");
261                         if (attribute != null && !attribute.equals("")) {
262                                 log.debug("Overriding passThruErrors for Relying Pary (" + name + ") with (" + attribute + ").");
263                                 overridenPassThruErrors = Boolean.valueOf(attribute).booleanValue();
264                                 passThruIsOverriden = true;
265                         }
266
267                         // SSO profile defaulting
268                         attribute = ((Element) partyConfig).getAttribute("defaultToPOSTProfile");
269                         if (attribute != null && !attribute.equals("")) {
270                                 defaultToPOST = Boolean.valueOf(attribute).booleanValue();
271                         }
272                         if (defaultToPOST) {
273                                 log.debug("Relying party defaults to POST profile.");
274                         } else {
275                                 log.debug("Relying party defaults to Artifact profile.");
276                         }
277
278                         attribute = ((Element) partyConfig).getAttribute("singleAssertion");
279                         if (attribute != null && !attribute.equals("")) {
280                                 singleAssertion = Boolean.valueOf(attribute).booleanValue();
281                         }
282                         if (singleAssertion) {
283                                 log.debug("Relying party defaults to a single assertion when pushing attributes.");
284                         } else {
285                                 log.debug("Relying party defaults to multiple assertions when pushing attributes.");
286                         }
287
288                         // Relying Party wants assertions signed?
289                         attribute = ((Element) partyConfig).getAttribute("signAssertions");
290                         if (attribute != null && !attribute.equals("")) {
291                                 wantsAssertionsSigned = Boolean.valueOf(attribute).booleanValue();
292                         }
293                         if (wantsAssertionsSigned) {
294                                 log.debug("Relying party wants SAML Assertions to be signed.");
295                         } else {
296                                 log.debug("Relying party does not want SAML Assertions to be signed.");
297                         }
298
299                         // Decide whether or not to use the schema hack for old xerces
300                         attribute = ((Element) partyConfig).getAttribute("schemaHack");
301                         if (attribute != null && !attribute.equals("")) {
302                                 wantsSchemaHack = Boolean.valueOf(attribute).booleanValue();
303                         }
304                         if (wantsSchemaHack) {
305                                 log.debug("XML schema hack enabled for this relying party.");
306                         }
307
308                         // Set a default target for use in artifact redirects
309                         defaultTarget = ((Element) partyConfig).getAttribute("defaultTarget");
310
311                         // Determine whether or not we are forcing attribute push on or off
312                         String forcePush = ((Element) partyConfig).getAttribute("forceAttributePush");
313                         String forceNoPush = ((Element) partyConfig).getAttribute("forceAttributeNoPush");
314
315                         if (forcePush != null && Boolean.valueOf(forcePush).booleanValue() && forceNoPush != null
316                                         && Boolean.valueOf(forceNoPush).booleanValue()) {
317                                 log.error("Invalid configuration:  Attribute push is forced to ON and OFF for this relying "
318                                                 + "party.  Turning off forcing in favor of profile defaults.");
319                         } else {
320                                 forceAttributePush = Boolean.valueOf(forcePush).booleanValue();
321                                 forceAttributeNoPush = Boolean.valueOf(forceNoPush).booleanValue();
322                                 log.debug("Attribute push forcing is set to (" + forceAttributePush + ").");
323                                 log.debug("No attribute push forcing is set to (" + forceAttributeNoPush + ").");
324                         }
325
326                         attribute = ((Element) partyConfig).getAttribute("preferredArtifactType");
327                         if (attribute != null && !attribute.equals("")) {
328                                 log.debug("Overriding AAUrl for Relying Pary (" + name + ") with (" + attribute + ").");
329                                 try {
330                                         preferredArtifactType = Integer.parseInt(attribute);
331                                 } catch (NumberFormatException e) {
332                                         log.error("(preferredArtifactType) attribute to is not a valid integer.");
333                                         throw new ServiceProviderMapperException("Configuration is invalid.");
334                                 }
335                                 log.debug("Preferred artifact type: (" + preferredArtifactType + ").");
336                         }
337
338                         // Load and verify the name mappings that should be used in
339                         // assertions for this RelyingParty
340
341                         NodeList nameIDs = ((Element) partyConfig).getElementsByTagNameNS(IdPConfig.configNameSpace, "NameID");
342                         // If no specification. Make sure we have a default mapping
343                         if (nameIDs.getLength() < 1) {
344                                 if (nameMapper.getNameIdentifierMappingById(null) == null) {
345                                         log.error("Relying Party NameId configuration not set.  Add a <NameID> element to <RelyingParty>.");
346                                         throw new ServiceProviderMapperException("Required configuration not specified.");
347                                 }
348
349                         } else {
350
351                                 // We do have a specification, so make sure it points to a
352                                 // valid Name Mapping
353
354                                 for (int i = 0; i < nameIDs.getLength(); i++) {
355
356                                         String mappingId = ((Element) nameIDs.item(i)).getAttribute("nameMapping");
357                                         if (mappingId == null || mappingId.equals("")) {
358                                                 log.error("Name mapping not set.  Add a (nameMapping) attribute to <NameID>.");
359                                                 throw new ServiceProviderMapperException("Required configuration not specified.");
360                                         }
361
362                                         if (nameMapper.getNameIdentifierMappingById(mappingId) == null) {
363                                                 log.error("Relying Party NameID refers to a name mapping that is not loaded.");
364                                                 throw new ServiceProviderMapperException("Required configuration not specified.");
365                                         }
366
367                                         mappingIds.add(mappingId);
368                                 }
369                         }
370
371                         // Load the credential for signing
372                         String credentialName = ((Element) partyConfig).getAttribute("signingCredential");
373                         Credential signingCredential = credentials.getCredential(credentialName);
374                         if (signingCredential == null) {
375                                 if (credentialName == null || credentialName.equals("")) {
376                                         log.error("Relying Party credential not set.  Add a (signingCredential) "
377                                                         + "attribute to <RelyingParty>.");
378                                         throw new ServiceProviderMapperException("Required configuration not specified.");
379                                 } else {
380                                         log.error("Relying Party credential invalid.  Fix the (signingCredential) attribute "
381                                                         + "on <RelyingParty>.");
382                                         throw new ServiceProviderMapperException("Required configuration is invalid.");
383                                 }
384
385                         }
386
387                         // Initialize and Identity Provider object for this use by this relying party
388                         identityProvider = new RelyingPartyIdentityProvider(overridenIdPProviderId != null
389                                         ? overridenIdPProviderId
390                                         : configuration.getProviderId(), signingCredential);
391
392                 }
393
394                 public String getProviderId() {
395
396                         return name;
397                 }
398
399                 public String getName() {
400
401                         return name;
402                 }
403
404                 public IdentityProvider getIdentityProvider() {
405
406                         return identityProvider;
407                 }
408
409                 public String[] getNameMapperIds() {
410
411                         return (String[]) mappingIds.toArray(new String[0]);
412                 }
413
414                 public URI getDefaultAuthMethod() {
415
416                         if (overridenDefaultAuthMethod != null) {
417                                 return overridenDefaultAuthMethod;
418                         } else {
419                                 return configuration.getDefaultAuthMethod();
420                         }
421                 }
422
423                 public URL getAAUrl() {
424
425                         if (overridenAAUrl != null) {
426                                 return overridenAAUrl;
427                         } else {
428                                 return configuration.getAAUrl();
429                         }
430                 }
431
432                 public boolean passThruErrors() {
433
434                         if (passThruIsOverriden) {
435                                 return overridenPassThruErrors;
436                         } else {
437                                 return configuration.passThruErrors();
438                         }
439                 }
440
441                 public boolean forceAttributePush() {
442
443                         return forceAttributePush;
444                 }
445
446                 public boolean forceAttributeNoPush() {
447
448                         return forceAttributeNoPush;
449                 }
450
451                 public boolean singleAssertion() {
452
453                         return singleAssertion;
454                 }
455
456                 public boolean defaultToPOSTProfile() {
457
458                         return defaultToPOST;
459                 }
460
461                 public boolean wantsAssertionsSigned() {
462
463                         return wantsAssertionsSigned;
464                 }
465
466                 public int getPreferredArtifactType() {
467
468                         return preferredArtifactType;
469                 }
470
471                 public String getDefaultTarget() {
472
473                         return defaultTarget;
474                 }
475
476                 public boolean wantsSchemaHack() {
477
478                         return wantsSchemaHack;
479                 }
480
481                 /**
482                  * Default identity provider implementation.
483                  * 
484                  * @author Walter Hoehn
485                  */
486                 protected class RelyingPartyIdentityProvider implements IdentityProvider {
487
488                         private String providerId;
489                         private Credential credential;
490
491                         public RelyingPartyIdentityProvider(String providerId, Credential credential) {
492
493                                 this.providerId = providerId;
494                                 this.credential = credential;
495                         }
496
497                         /*
498                          * @see edu.internet2.middleware.shibboleth.common.IdentityProvider#getProviderId()
499                          */
500                         public String getProviderId() {
501
502                                 return providerId;
503                         }
504
505                         /*
506                          * @see edu.internet2.middleware.shibboleth.common.IdentityProvider#getSigningCredential()
507                          */
508                         public Credential getSigningCredential() {
509
510                                 return credential;
511                         }
512                 }
513         }
514
515         /**
516          * Relying party implementation wrapper for relying parties that are groups.
517          * 
518          * @author Walter Hoehn
519          */
520         class RelyingPartyGroupWrapper implements RelyingParty {
521
522                 private RelyingParty wrapped;
523                 private String providerId;
524
525                 RelyingPartyGroupWrapper(RelyingParty wrapped, String providerId) {
526
527                         this.wrapped = wrapped;
528                         this.providerId = providerId;
529                 }
530
531                 public String getName() {
532
533                         return wrapped.getName();
534                 }
535
536                 public IdentityProvider getIdentityProvider() {
537
538                         return wrapped.getIdentityProvider();
539                 }
540
541                 public String getProviderId() {
542
543                         return providerId;
544                 }
545
546                 public String[] getNameMapperIds() {
547
548                         return wrapped.getNameMapperIds();
549                 }
550
551                 public URL getAAUrl() {
552
553                         return wrapped.getAAUrl();
554                 }
555
556                 public URI getDefaultAuthMethod() {
557
558                         return wrapped.getDefaultAuthMethod();
559                 }
560
561                 public boolean passThruErrors() {
562
563                         return wrapped.passThruErrors();
564                 }
565
566                 public boolean forceAttributePush() {
567
568                         return wrapped.forceAttributePush();
569                 }
570
571                 public boolean forceAttributeNoPush() {
572
573                         return wrapped.forceAttributeNoPush();
574                 }
575
576                 public boolean singleAssertion() {
577
578                         return wrapped.singleAssertion();
579                 }
580
581                 public boolean defaultToPOSTProfile() {
582
583                         return wrapped.defaultToPOSTProfile();
584                 }
585
586                 public boolean wantsAssertionsSigned() {
587
588                         return wrapped.wantsAssertionsSigned();
589                 }
590
591                 public int getPreferredArtifactType() {
592
593                         return wrapped.getPreferredArtifactType();
594                 }
595
596                 public String getDefaultTarget() {
597
598                         return wrapped.getDefaultTarget();
599                 }
600
601                 public boolean wantsSchemaHack() {
602
603                         return wrapped.wantsSchemaHack();
604                 }
605         }
606
607         /**
608          * Relying party implementation wrapper for anonymous service providers.
609          * 
610          * @author Walter Hoehn
611          */
612         protected class UnknownProviderWrapper implements RelyingParty {
613
614                 protected RelyingParty wrapped;
615                 protected String providerId;
616
617                 protected UnknownProviderWrapper(RelyingParty wrapped, String providerId) {
618
619                         this.wrapped = wrapped;
620                         this.providerId = providerId;
621                 }
622
623                 public String getName() {
624
625                         return wrapped.getName();
626                 }
627
628                 public IdentityProvider getIdentityProvider() {
629
630                         return wrapped.getIdentityProvider();
631                 }
632
633                 public String getProviderId() {
634
635                         return providerId;
636                 }
637
638                 public String[] getNameMapperIds() {
639
640                         return wrapped.getNameMapperIds();
641                 }
642
643                 public URL getAAUrl() {
644
645                         return wrapped.getAAUrl();
646                 }
647
648                 public URI getDefaultAuthMethod() {
649
650                         return wrapped.getDefaultAuthMethod();
651                 }
652
653                 public boolean passThruErrors() {
654
655                         return wrapped.passThruErrors();
656                 }
657
658                 public boolean forceAttributePush() {
659
660                         return false;
661                 }
662
663                 public boolean forceAttributeNoPush() {
664
665                         return false;
666                 }
667
668                 public boolean singleAssertion() {
669
670                         return false;
671                 }
672
673                 public boolean defaultToPOSTProfile() {
674
675                         return true;
676                 }
677
678                 public boolean wantsAssertionsSigned() {
679
680                         return wrapped.wantsAssertionsSigned();
681                 }
682
683                 public int getPreferredArtifactType() {
684
685                         return wrapped.getPreferredArtifactType();
686                 }
687
688                 public String getDefaultTarget() {
689
690                         return wrapped.getDefaultTarget();
691                 }
692
693                 public boolean wantsSchemaHack() {
694
695                         return wrapped.wantsSchemaHack();
696                 }
697         }
698
699         /**
700          * Relying party wrapper for providers for which we have no metadata
701          * 
702          * @author Walter Hoehn
703          */
704         class NoMetadataWrapper extends UnknownProviderWrapper implements RelyingParty {
705
706                 NoMetadataWrapper(RelyingParty wrapped) {
707
708                         super(wrapped, null);
709                 }
710
711                 public String[] getNameMapperIds() {
712
713                         return ((RelyingParty) wrapped).getNameMapperIds();
714                 }
715
716                 public URL getAAUrl() {
717
718                         return ((RelyingParty) wrapped).getAAUrl();
719                 }
720
721                 public URI getDefaultAuthMethod() {
722
723                         return ((RelyingParty) wrapped).getDefaultAuthMethod();
724                 }
725         }
726 }