fb22055944bb9b8628ea0e0e8a97ff0f1170d164
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml2 / AbstractSAML2ProfileHandler.java
1 /*
2  * Copyright [2007] [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.idp.profile.saml2;
18
19 import java.util.ArrayList;
20 import java.util.Collection;
21 import java.util.List;
22 import java.util.Map;
23
24 import org.joda.time.DateTime;
25 import org.opensaml.common.SAMLObjectBuilder;
26 import org.opensaml.common.SAMLVersion;
27 import org.opensaml.saml2.core.Assertion;
28 import org.opensaml.saml2.core.AttributeQuery;
29 import org.opensaml.saml2.core.AttributeStatement;
30 import org.opensaml.saml2.core.Audience;
31 import org.opensaml.saml2.core.AudienceRestriction;
32 import org.opensaml.saml2.core.AuthnRequest;
33 import org.opensaml.saml2.core.Conditions;
34 import org.opensaml.saml2.core.Issuer;
35 import org.opensaml.saml2.core.NameID;
36 import org.opensaml.saml2.core.ProxyRestriction;
37 import org.opensaml.saml2.core.Response;
38 import org.opensaml.saml2.core.Statement;
39 import org.opensaml.saml2.core.Status;
40 import org.opensaml.saml2.core.StatusCode;
41 import org.opensaml.saml2.core.StatusMessage;
42 import org.opensaml.saml2.core.StatusResponseType;
43 import org.opensaml.saml2.core.Subject;
44 import org.opensaml.saml2.core.SubjectConfirmation;
45 import org.opensaml.saml2.core.SubjectConfirmationData;
46 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
47 import org.opensaml.saml2.metadata.AuthnAuthorityDescriptor;
48 import org.opensaml.saml2.metadata.Endpoint;
49 import org.opensaml.saml2.metadata.NameIDFormat;
50 import org.opensaml.saml2.metadata.PDPDescriptor;
51 import org.opensaml.saml2.metadata.RoleDescriptor;
52 import org.opensaml.saml2.metadata.SPSSODescriptor;
53 import org.opensaml.saml2.metadata.SSODescriptor;
54 import org.opensaml.ws.transport.http.HTTPInTransport;
55 import org.opensaml.xml.XMLObjectBuilder;
56 import org.opensaml.xml.security.SecurityException;
57 import org.opensaml.xml.security.SecurityHelper;
58 import org.opensaml.xml.security.credential.Credential;
59 import org.opensaml.xml.signature.Signature;
60 import org.opensaml.xml.signature.Signer;
61 import org.opensaml.xml.util.DatatypeHelper;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64
65 import edu.internet2.middleware.shibboleth.common.attribute.AttributeRequestException;
66 import edu.internet2.middleware.shibboleth.common.attribute.BaseAttribute;
67 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncoder;
68 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncodingException;
69 import edu.internet2.middleware.shibboleth.common.attribute.encoding.SAML2NameIDAttributeEncoder;
70 import edu.internet2.middleware.shibboleth.common.attribute.provider.SAML2AttributeAuthority;
71 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
72 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AbstractSAML2ProfileConfiguration;
73 import edu.internet2.middleware.shibboleth.idp.profile.AbstractSAMLProfileHandler;
74
75 /** Common implementation details for profile handlers. */
76 public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHandler {
77
78     /** SAML Version for this profile handler. */
79     public static final SAMLVersion SAML_VERSION = SAMLVersion.VERSION_20;
80
81     /** Class logger. */
82     private Logger log = LoggerFactory.getLogger(AbstractSAML2ProfileHandler.class);
83
84     /** For building response. */
85     private SAMLObjectBuilder<Response> responseBuilder;
86
87     /** For building status. */
88     private SAMLObjectBuilder<Status> statusBuilder;
89
90     /** For building statuscode. */
91     private SAMLObjectBuilder<StatusCode> statusCodeBuilder;
92
93     /** For building StatusMessages. */
94     private SAMLObjectBuilder<StatusMessage> statusMessageBuilder;
95
96     /** For building assertion. */
97     private SAMLObjectBuilder<Assertion> assertionBuilder;
98
99     /** For building issuer. */
100     private SAMLObjectBuilder<Issuer> issuerBuilder;
101
102     /** For building subject. */
103     private SAMLObjectBuilder<Subject> subjectBuilder;
104
105     /** For building subject confirmation. */
106     private SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder;
107
108     /** For building subject confirmation data. */
109     private SAMLObjectBuilder<SubjectConfirmationData> subjectConfirmationDataBuilder;
110
111     /** For building conditions. */
112     private SAMLObjectBuilder<Conditions> conditionsBuilder;
113
114     /** For building audience restriction. */
115     private SAMLObjectBuilder<AudienceRestriction> audienceRestrictionBuilder;
116
117     /** For building proxy retrictions. */
118     private SAMLObjectBuilder<ProxyRestriction> proxyRestrictionBuilder;
119
120     /** For building audience. */
121     private SAMLObjectBuilder<Audience> audienceBuilder;
122
123     /** For building signature. */
124     private XMLObjectBuilder<Signature> signatureBuilder;
125
126     /** Constructor. */
127     @SuppressWarnings("unchecked")
128     protected AbstractSAML2ProfileHandler() {
129         super();
130
131         responseBuilder = (SAMLObjectBuilder<Response>) getBuilderFactory().getBuilder(Response.DEFAULT_ELEMENT_NAME);
132         statusBuilder = (SAMLObjectBuilder<Status>) getBuilderFactory().getBuilder(Status.DEFAULT_ELEMENT_NAME);
133         statusCodeBuilder = (SAMLObjectBuilder<StatusCode>) getBuilderFactory().getBuilder(
134                 StatusCode.DEFAULT_ELEMENT_NAME);
135         statusMessageBuilder = (SAMLObjectBuilder<StatusMessage>) getBuilderFactory().getBuilder(
136                 StatusMessage.DEFAULT_ELEMENT_NAME);
137         issuerBuilder = (SAMLObjectBuilder<Issuer>) getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
138         assertionBuilder = (SAMLObjectBuilder<Assertion>) getBuilderFactory()
139                 .getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
140         subjectBuilder = (SAMLObjectBuilder<Subject>) getBuilderFactory().getBuilder(Subject.DEFAULT_ELEMENT_NAME);
141         subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) getBuilderFactory().getBuilder(
142                 SubjectConfirmation.DEFAULT_ELEMENT_NAME);
143         subjectConfirmationDataBuilder = (SAMLObjectBuilder<SubjectConfirmationData>) getBuilderFactory().getBuilder(
144                 SubjectConfirmationData.DEFAULT_ELEMENT_NAME);
145         conditionsBuilder = (SAMLObjectBuilder<Conditions>) getBuilderFactory().getBuilder(
146                 Conditions.DEFAULT_ELEMENT_NAME);
147         audienceRestrictionBuilder = (SAMLObjectBuilder<AudienceRestriction>) getBuilderFactory().getBuilder(
148                 AudienceRestriction.DEFAULT_ELEMENT_NAME);
149         proxyRestrictionBuilder = (SAMLObjectBuilder<ProxyRestriction>) getBuilderFactory().getBuilder(
150                 ProxyRestriction.DEFAULT_ELEMENT_NAME);
151         audienceBuilder = (SAMLObjectBuilder<Audience>) getBuilderFactory().getBuilder(Audience.DEFAULT_ELEMENT_NAME);
152         signatureBuilder = (XMLObjectBuilder<Signature>) getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME);
153     }
154
155     /**
156      * Checks that the SAML major version for a request is 2.
157      * 
158      * @param requestContext current request context containing the SAML message
159      * 
160      * @throws ProfileException thrown if the major version of the SAML request is not 2
161      */
162     protected void checkSamlVersion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
163         SAMLVersion version = requestContext.getInboundSAMLMessage().getVersion();
164         if (version.getMajorVersion() < 2) {
165             requestContext.setFailureStatus(buildStatus(StatusCode.VERSION_MISMATCH_URI,
166                     StatusCode.REQUEST_VERSION_TOO_LOW_URI, null));
167             throw new ProfileException("SAML request version too low");
168         } else if (version.getMajorVersion() > 2) {
169             requestContext.setFailureStatus(buildStatus(StatusCode.VERSION_MISMATCH_URI,
170                     StatusCode.REQUEST_VERSION_TOO_HIGH_URI, null));
171             throw new ProfileException("SAML request version too high");
172         }
173     }
174
175     /**
176      * Builds a response to the attribute query within the request context.
177      * 
178      * @param requestContext current request context
179      * @param subjectConfirmationMethod confirmation method used for the subject
180      * @param statements the statements to include in the response
181      * 
182      * @return the built response
183      * 
184      * @throws ProfileException thrown if there is a problem creating the SAML response
185      */
186     protected Response buildResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext,
187             String subjectConfirmationMethod, List<Statement> statements) throws ProfileException {
188
189         DateTime issueInstant = new DateTime();
190
191         Subject subject = buildSubject(requestContext, subjectConfirmationMethod, issueInstant);
192
193         // create the assertion and add the attribute statement
194         Assertion assertion = buildAssertion(requestContext, issueInstant);
195         assertion.setSubject(subject);
196         if (statements != null) {
197             assertion.getStatements().addAll(statements);
198         }
199
200         // create the SAML response and add the assertion
201         Response samlResponse = responseBuilder.buildObject();
202         samlResponse.setIssueInstant(issueInstant);
203         populateStatusResponse(requestContext, samlResponse);
204
205         samlResponse.getAssertions().add(assertion);
206
207         // sign the assertion if it should be signed
208         signAssertion(requestContext, assertion);
209
210         Status status = buildStatus(StatusCode.SUCCESS_URI, null, null);
211         samlResponse.setStatus(status);
212
213         return samlResponse;
214     }
215
216     /**
217      * Builds a basic assertion with its id, issue instant, SAML version, issuer, subject, and conditions populated.
218      * 
219      * @param requestContext current request context
220      * @param issueInstant time to use as assertion issue instant
221      * 
222      * @return the built assertion
223      */
224     protected Assertion buildAssertion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
225         Assertion assertion = assertionBuilder.buildObject();
226         assertion.setID(getIdGenerator().generateIdentifier());
227         assertion.setIssueInstant(issueInstant);
228         assertion.setVersion(SAMLVersion.VERSION_20);
229         assertion.setIssuer(buildEntityIssuer(requestContext));
230
231         Conditions conditions = buildConditions(requestContext, issueInstant);
232         assertion.setConditions(conditions);
233
234         return assertion;
235     }
236
237     /**
238      * Creates an {@link Issuer} populated with information about the relying party.
239      * 
240      * @param requestContext current request context
241      * 
242      * @return the built issuer
243      */
244     protected Issuer buildEntityIssuer(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) {
245         Issuer issuer = issuerBuilder.buildObject();
246         issuer.setFormat(Issuer.ENTITY);
247         issuer.setValue(requestContext.getLocalEntityId());
248
249         return issuer;
250     }
251
252     /**
253      * Builds a SAML assertion condition set. The following fields are set; not before, not on or after, audience
254      * restrictions, and proxy restrictions.
255      * 
256      * @param requestContext current request context
257      * @param issueInstant timestamp the assertion was created
258      * 
259      * @return constructed conditions
260      */
261     protected Conditions buildConditions(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
262         AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
263
264         Conditions conditions = conditionsBuilder.buildObject();
265         conditions.setNotBefore(issueInstant);
266         conditions.setNotOnOrAfter(issueInstant.plus(profileConfig.getAssertionLifetime()));
267
268         Collection<String> audiences;
269
270         // add audience restrictions
271         audiences = profileConfig.getAssertionAudiences();
272         if (audiences != null && audiences.size() > 0) {
273             AudienceRestriction audienceRestriction = audienceRestrictionBuilder.buildObject();
274             for (String audienceUri : audiences) {
275                 Audience audience = audienceBuilder.buildObject();
276                 audience.setAudienceURI(audienceUri);
277                 audienceRestriction.getAudiences().add(audience);
278             }
279             conditions.getAudienceRestrictions().add(audienceRestriction);
280         }
281
282         // add proxy restrictions
283         audiences = profileConfig.getProxyAudiences();
284         if (audiences != null && audiences.size() > 0) {
285             ProxyRestriction proxyRestriction = proxyRestrictionBuilder.buildObject();
286             Audience audience;
287             for (String audienceUri : audiences) {
288                 audience = audienceBuilder.buildObject();
289                 audience.setAudienceURI(audienceUri);
290                 proxyRestriction.getAudiences().add(audience);
291             }
292
293             proxyRestriction.setProxyCount(profileConfig.getProxyCount());
294             conditions.getConditions().add(proxyRestriction);
295         }
296
297         return conditions;
298     }
299
300     /**
301      * Populates the response's id, in response to, issue instant, version, and issuer properties.
302      * 
303      * @param requestContext current request context
304      * @param response the response to populate
305      */
306     protected void populateStatusResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext,
307             StatusResponseType response) {
308         response.setID(getIdGenerator().generateIdentifier());
309         if (requestContext.getInboundSAMLMessage() != null) {
310             response.setInResponseTo(requestContext.getInboundSAMLMessageId());
311         }
312         response.setVersion(SAMLVersion.VERSION_20);
313         response.setIssuer(buildEntityIssuer(requestContext));
314     }
315
316     /**
317      * Resolves the attributes for the principal.
318      * 
319      * @param requestContext current request context
320      * 
321      * @throws ProfileException thrown if there is a problem resolved attributes
322      */
323     protected void resolveAttributes(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
324         AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
325         SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
326
327         try {
328             log.debug("Resolving attributes for principal {} of SAML request from relying party {}", requestContext
329                     .getPrincipalName(), requestContext.getInboundMessageIssuer());
330             Map<String, BaseAttribute> principalAttributes = attributeAuthority.getAttributes(requestContext);
331
332             requestContext.setAttributes(principalAttributes);
333         } catch (AttributeRequestException e) {
334             log.error("Error resolving attributes for SAML request " + requestContext.getInboundSAMLMessageId()
335                     + " from relying party " + requestContext.getInboundMessageIssuer(), e);
336             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
337             throw new ProfileException("Error resolving attributes for SAML request "
338                     + requestContext.getInboundSAMLMessageId() + " from relying party "
339                     + requestContext.getInboundMessageIssuer(), e);
340         }
341     }
342
343     /**
344      * Executes a query for attributes and builds a SAML attribute statement from the results.
345      * 
346      * @param requestContext current request context
347      * 
348      * @return attribute statement resulting from the query
349      * 
350      * @throws ProfileException thrown if there is a problem making the query
351      */
352     protected AttributeStatement buildAttributeStatement(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext)
353             throws ProfileException {
354         log.debug("Creating attribute statement in response to SAML request {} from relying party {}", requestContext
355                 .getInboundSAMLMessageId(), requestContext.getInboundMessageIssuer());
356
357         AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
358         SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
359         try {
360             if (requestContext.getInboundSAMLMessage() instanceof AttributeQuery) {
361                 return attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext
362                         .getInboundSAMLMessage(), requestContext.getPrincipalAttributes().values());
363             } else {
364                 return attributeAuthority.buildAttributeStatement(null, requestContext.getPrincipalAttributes()
365                         .values());
366             }
367         } catch (AttributeRequestException e) {
368             log.error("Error encoding attributes for principal " + requestContext.getPrincipalName(), e);
369             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
370             throw new ProfileException("Error encoding attributes for principal " + requestContext.getPrincipalName(),
371                     e);
372         }
373     }
374
375     /**
376      * Resolves the principal name of the subject of the request.
377      * 
378      * @param requestContext current request context
379      * 
380      * @throws ProfileException thrown if the principal name can not be resolved
381      */
382     protected void resolvePrincipal(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
383         AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
384         if (profileConfiguration == null) {
385             log.error("Unable to resolve principal, no SAML 2 profile configuration for relying party "
386                     + requestContext.getInboundMessageIssuer());
387             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
388                     "Error resolving principal"));
389             throw new ProfileException(
390                     "Unable to resolve principal, no SAML 2 profile configuration for relying party "
391                             + requestContext.getInboundMessageIssuer());
392         }
393         SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
394         log.debug("Resolving principal name for subject of SAML request {} from relying party {}", requestContext
395                 .getInboundSAMLMessageId(), requestContext.getInboundMessageIssuer());
396
397         try {
398             String principal = attributeAuthority.getPrincipal(requestContext);
399             requestContext.setPrincipalName(principal);
400         } catch (AttributeRequestException e) {
401             log.error("Error resolving attributes for SAML request " + requestContext.getInboundSAMLMessageId()
402                     + " from relying party " + requestContext.getInboundMessageIssuer(), e);
403             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.UNKNOWN_PRINCIPAL_URI,
404                     "Error resolving principal"));
405             throw new ProfileException("Error resolving attributes for SAML request "
406                     + requestContext.getInboundSAMLMessageId() + " from relying party "
407                     + requestContext.getInboundMessageIssuer(), e);
408         }
409     }
410
411     /**
412      * Signs the given assertion if either the current profile configuration or the relying party configuration contains
413      * signing credentials.
414      * 
415      * @param requestContext current request context
416      * @param assertion assertion to sign
417      * 
418      * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
419      *             required, if a signing credential is not configured
420      */
421     protected void signAssertion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, Assertion assertion)
422             throws ProfileException {
423         log.debug("Determining if SAML assertion to relying party {} should be signed", requestContext
424                 .getInboundMessageIssuer());
425
426         boolean signAssertion = false;
427
428         AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
429         if (profileConfig.getSignAssertions()) {
430             signAssertion = true;
431             log.debug("IdP relying party configuration {} indicates to sign assertions: {}", requestContext
432                     .getRelyingPartyConfiguration().getRelyingPartyId(), signAssertion);
433         }
434
435         if (!signAssertion && requestContext.getPeerEntityRoleMetadata() instanceof SPSSODescriptor) {
436             SPSSODescriptor ssoDescriptor = (SPSSODescriptor) requestContext.getPeerEntityRoleMetadata();
437             if (ssoDescriptor.getWantAssertionsSigned() != null) {
438                 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
439                 log.debug("Entity metadata for relying party {} indicates to sign assertions: {}", requestContext
440                         .getInboundMessageIssuer(), signAssertion);
441             }
442         }
443
444         if (!signAssertion) {
445             return;
446         }
447
448         log.debug("Determining signing credntial for assertion to relying party {}", requestContext
449                 .getInboundMessageIssuer());
450         Credential signatureCredential = profileConfig.getSigningCredential();
451         if (signatureCredential == null) {
452             signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
453         }
454
455         if (signatureCredential == null) {
456             throw new ProfileException("No signing credential is specified for relying party configuration "
457                     + requestContext.getRelyingPartyConfiguration().getProviderId()
458                     + " or it's SAML2 attribute query profile configuration");
459         }
460
461         log.debug("Signing assertion to relying party {}", requestContext.getInboundMessageIssuer());
462         Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
463
464         signature.setSigningCredential(signatureCredential);
465         try {
466             // TODO pull SecurityConfiguration from SAMLMessageContext? needs to be added
467             // TODO how to pull what keyInfoGenName to use?
468             SecurityHelper.prepareSignatureParams(signature, signatureCredential, null, null);
469         } catch (SecurityException e) {
470             throw new ProfileException("Error preparing signature for signing", e);
471         }
472
473         assertion.setSignature(signature);
474
475         Signer.signObject(signature);
476     }
477
478     /**
479      * Build a status message, with an optional second-level failure message.
480      * 
481      * @param topLevelCode The top-level status code. Should be from saml-core-2.0-os, sec. 3.2.2.2
482      * @param secondLevelCode An optional second-level failure code. Should be from saml-core-2.0-is, sec 3.2.2.2. If
483      *            null, no second-level Status element will be set.
484      * @param failureMessage An optional second-level failure message
485      * 
486      * @return a Status object.
487      */
488     protected Status buildStatus(String topLevelCode, String secondLevelCode, String failureMessage) {
489         Status status = statusBuilder.buildObject();
490
491         StatusCode statusCode = statusCodeBuilder.buildObject();
492         statusCode.setValue(DatatypeHelper.safeTrimOrNullString(topLevelCode));
493         status.setStatusCode(statusCode);
494
495         if (secondLevelCode != null) {
496             StatusCode secondLevelStatusCode = statusCodeBuilder.buildObject();
497             secondLevelStatusCode.setValue(DatatypeHelper.safeTrimOrNullString(secondLevelCode));
498             statusCode.setStatusCode(secondLevelStatusCode);
499         }
500
501         if (failureMessage != null) {
502             StatusMessage msg = statusMessageBuilder.buildObject();
503             msg.setMessage(failureMessage);
504             status.setStatusMessage(msg);
505         }
506
507         return status;
508     }
509
510     /**
511      * Builds the SAML subject for the user for the service provider.
512      * 
513      * @param requestContext current request context
514      * @param confirmationMethod subject confirmation method used for the subject
515      * @param issueInstant instant the subject confirmation data should reflect for issuance
516      * 
517      * @return SAML subject for the user for the service provider
518      * 
519      * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
520      *             name ID attribute or because there are no supported name formats
521      */
522     protected Subject buildSubject(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, String confirmationMethod,
523             DateTime issueInstant) throws ProfileException {
524         NameID nameID = buildNameId(requestContext);
525         requestContext.setSubjectNameIdentifier(nameID);
526         // TODO handle encryption
527
528         SubjectConfirmationData confirmationData = subjectConfirmationDataBuilder.buildObject();
529         HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
530         confirmationData.setAddress(inTransport.getPeerAddress());
531         confirmationData.setInResponseTo(requestContext.getInboundSAMLMessageId());
532         confirmationData.setNotOnOrAfter(issueInstant.plus(requestContext.getProfileConfiguration()
533                 .getAssertionLifetime()));
534
535         Endpoint relyingPartyEndpoint = requestContext.getPeerEntityEndpoint();
536         if (relyingPartyEndpoint != null) {
537             if (relyingPartyEndpoint.getResponseLocation() != null) {
538                 confirmationData.setRecipient(relyingPartyEndpoint.getResponseLocation());
539             } else {
540                 confirmationData.setRecipient(relyingPartyEndpoint.getLocation());
541             }
542         }
543
544         SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();
545         subjectConfirmation.setMethod(confirmationMethod);
546         subjectConfirmation.setSubjectConfirmationData(confirmationData);
547
548         Subject subject = subjectBuilder.buildObject();
549         subject.setNameID(nameID);
550         subject.getSubjectConfirmations().add(subjectConfirmation);
551
552         return subject;
553     }
554
555     /**
556      * Builds a NameID appropriate for this request. NameIDs are built by inspecting the SAML request and metadata,
557      * picking a name format that was requested by the relying party or is mutually supported by both the relying party
558      * and asserting party as described in their metadata entries. Once a set of supported name formats is determined
559      * the principals attributes are inspected for an attribute supported an attribute encoder whose category is one of
560      * the supported name formats.
561      * 
562      * @param requestContext current request context
563      * 
564      * @return the NameID appropriate for this request
565      * 
566      * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
567      *             name ID attribute or because there are no supported name formats
568      */
569     protected NameID buildNameId(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
570         log.debug("Building assertion NameID for principal/relying party:{}/{}", requestContext.getPrincipalName(),
571                 requestContext.getInboundMessageIssuer());
572         Map<String, BaseAttribute> principalAttributes = requestContext.getPrincipalAttributes();
573         List<String> supportedNameFormats = getNameFormats(requestContext);
574
575         log.debug("Supported NameID formats: {}", supportedNameFormats);
576
577         if (principalAttributes == null || supportedNameFormats == null) {
578             log.error("No attributes for principal " + requestContext.getPrincipalName()
579                     + " support constructions of NameID");
580             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
581                     "Unable to construct NameID"));
582             throw new ProfileException("No principal attributes support NameID construction");
583         }
584
585         try {
586             SAML2NameIDAttributeEncoder nameIdEncoder;
587             for (BaseAttribute<?> attribute : principalAttributes.values()) {
588                 for (AttributeEncoder encoder : attribute.getEncoders()) {
589                     if (encoder instanceof SAML2NameIDAttributeEncoder) {
590                         nameIdEncoder = (SAML2NameIDAttributeEncoder) encoder;
591                         if (supportedNameFormats.contains(nameIdEncoder.getNameFormat())) {
592                             log
593                                     .debug(
594                                             "Using attribute {} suppoting NameID format {} to create the NameID for principal.{}",
595                                             attribute.getId(), nameIdEncoder.getNameFormat());
596                             return nameIdEncoder.encode(attribute);
597                         }
598                     }
599                 }
600             }
601             log.error("No principal attribute supported encoding into a supported name ID format.");
602             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
603             throw new ProfileException("No principal attribute supported encoding into a supported name ID format.");
604         } catch (AttributeEncodingException e) {
605             log.error("Unable to encode NameID attribute", e);
606             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
607             throw new ProfileException("Unable to encode NameID attribute", e);
608         }
609     }
610
611     /**
612      * Gets the NameID format to use when creating NameIDs for the relying party.
613      * 
614      * @param requestContext current request context
615      * 
616      * @return list of nameID formats that may be used with the relying party
617      * 
618      * @throws ProfileException thrown if there is a problem determing the NameID format to use
619      */
620     protected List<String> getNameFormats(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext)
621             throws ProfileException {
622         ArrayList<String> nameFormats = new ArrayList<String>();
623
624         // Determine name formats supported by both SP and IdP
625         RoleDescriptor relyingPartyRole = requestContext.getPeerEntityRoleMetadata();
626         if (relyingPartyRole != null) {
627             List<String> relyingPartySupportedFormats = getEntitySupportedFormats(relyingPartyRole);
628             if (relyingPartySupportedFormats != null && !relyingPartySupportedFormats.isEmpty()) {
629                 nameFormats.addAll(relyingPartySupportedFormats);
630
631                 RoleDescriptor assertingPartyRole = requestContext.getLocalEntityRoleMetadata();
632                 if (assertingPartyRole != null) {
633                     List<String> assertingPartySupportedFormats = getEntitySupportedFormats(assertingPartyRole);
634                     if (assertingPartySupportedFormats != null && !assertingPartySupportedFormats.isEmpty()) {
635                         nameFormats.retainAll(assertingPartySupportedFormats);
636                     }
637                 }
638             }
639         }
640
641         if (nameFormats.isEmpty()) {
642             nameFormats.add("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
643         }
644
645         // If authn request and name ID policy format specified, make sure it's in the list of supported formats
646         String nameFormat = null;
647         if (requestContext.getInboundSAMLMessage() instanceof AuthnRequest) {
648             AuthnRequest authnRequest = (AuthnRequest) requestContext.getInboundSAMLMessage();
649             if (authnRequest.getNameIDPolicy() != null) {
650                 nameFormat = DatatypeHelper.safeTrimOrNullString(authnRequest.getNameIDPolicy().getFormat());
651                 if (nameFormat != null) {
652                     if (nameFormats.contains(nameFormat)) {
653                         nameFormats.clear();
654                         nameFormats.add(nameFormat);
655                     } else {
656                         requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI,
657                                 StatusCode.INVALID_NAMEID_POLICY_URI, "Format not supported: " + nameFormat));
658                         throw new ProfileException("NameID format required by relying party is not supported");
659                     }
660                 }
661
662             }
663         }
664
665         return nameFormats;
666     }
667
668     /**
669      * Gets the list of NameID formats supported for a given role.
670      * 
671      * @param role the role to get the list of supported NameID formats
672      * 
673      * @return list of supported NameID formats
674      */
675     protected List<String> getEntitySupportedFormats(RoleDescriptor role) {
676         List<NameIDFormat> nameIDFormats = null;
677
678         if (role instanceof SSODescriptor) {
679             nameIDFormats = ((SSODescriptor) role).getNameIDFormats();
680         } else if (role instanceof AuthnAuthorityDescriptor) {
681             nameIDFormats = ((AuthnAuthorityDescriptor) role).getNameIDFormats();
682         } else if (role instanceof PDPDescriptor) {
683             nameIDFormats = ((PDPDescriptor) role).getNameIDFormats();
684         } else if (role instanceof AttributeAuthorityDescriptor) {
685             nameIDFormats = ((AttributeAuthorityDescriptor) role).getNameIDFormats();
686         }
687
688         ArrayList<String> supportedFormats = new ArrayList<String>();
689         if (nameIDFormats != null) {
690             for (NameIDFormat format : nameIDFormats) {
691                 supportedFormats.add(format.getFormat());
692             }
693         }
694
695         return supportedFormats;
696     }
697
698     /**
699      * Constructs an SAML response message carrying a request error.
700      * 
701      * @param requestContext current request context
702      * 
703      * @return the constructed error response
704      */
705     protected Response buildErrorResponse(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) {
706         Response samlResponse = responseBuilder.buildObject();
707         samlResponse.setIssueInstant(new DateTime());
708         populateStatusResponse(requestContext, samlResponse);
709
710         samlResponse.setStatus(requestContext.getFailureStatus());
711
712         return samlResponse;
713     }
714 }