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