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