More refactoring, moving more into the abstract SAML 2 profile handler
[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 javax.servlet.ServletRequest;
25 import javax.servlet.ServletResponse;
26
27 import org.apache.log4j.Logger;
28 import org.joda.time.DateTime;
29 import org.opensaml.common.SAMLObjectBuilder;
30 import org.opensaml.common.SAMLVersion;
31 import org.opensaml.common.impl.SAMLObjectContentReference;
32 import org.opensaml.common.xml.SAMLConstants;
33 import org.opensaml.log.Level;
34 import org.opensaml.saml2.core.Advice;
35 import org.opensaml.saml2.core.Assertion;
36 import org.opensaml.saml2.core.AttributeQuery;
37 import org.opensaml.saml2.core.AttributeStatement;
38 import org.opensaml.saml2.core.Audience;
39 import org.opensaml.saml2.core.AudienceRestriction;
40 import org.opensaml.saml2.core.AuthnRequest;
41 import org.opensaml.saml2.core.Conditions;
42 import org.opensaml.saml2.core.Issuer;
43 import org.opensaml.saml2.core.NameID;
44 import org.opensaml.saml2.core.ProxyRestriction;
45 import org.opensaml.saml2.core.RequestAbstractType;
46 import org.opensaml.saml2.core.Response;
47 import org.opensaml.saml2.core.Statement;
48 import org.opensaml.saml2.core.Status;
49 import org.opensaml.saml2.core.StatusCode;
50 import org.opensaml.saml2.core.StatusMessage;
51 import org.opensaml.saml2.core.StatusResponseType;
52 import org.opensaml.saml2.core.Subject;
53 import org.opensaml.saml2.core.SubjectConfirmation;
54 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
55 import org.opensaml.saml2.metadata.AuthnAuthorityDescriptor;
56 import org.opensaml.saml2.metadata.NameIDFormat;
57 import org.opensaml.saml2.metadata.PDPDescriptor;
58 import org.opensaml.saml2.metadata.RoleDescriptor;
59 import org.opensaml.saml2.metadata.SPSSODescriptor;
60 import org.opensaml.saml2.metadata.SSODescriptor;
61 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
62 import org.opensaml.xml.XMLObjectBuilder;
63 import org.opensaml.xml.security.credential.Credential;
64 import org.opensaml.xml.signature.Signature;
65 import org.opensaml.xml.signature.Signer;
66 import org.opensaml.xml.util.DatatypeHelper;
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.provider.SAML2AttributeAuthority;
73 import edu.internet2.middleware.shibboleth.common.attribute.provider.ShibbolethSAMLAttributeRequestContext;
74 import edu.internet2.middleware.shibboleth.common.log.AuditLogEntry;
75 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
76 import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
77 import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
78 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AbstractSAML2ProfileConfiguration;
79 import edu.internet2.middleware.shibboleth.idp.profile.AbstractSAMLProfileHandler;
80 import edu.internet2.middleware.shibboleth.idp.session.ServiceInformation;
81 import edu.internet2.middleware.shibboleth.idp.session.Session;
82
83 /**
84  * Common implementation details for profile handlers.
85  */
86 public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHandler {
87
88     /** SAML Version for this profile handler. */
89     public static final SAMLVersion SAML_VERSION = SAMLVersion.VERSION_20;
90
91     /** Class logger. */
92     private Logger log = Logger.getLogger(AbstractSAML2ProfileHandler.class);
93
94     /** For building response. */
95     private SAMLObjectBuilder<Response> responseBuilder;
96
97     /** For building status. */
98     private SAMLObjectBuilder<Status> statusBuilder;
99
100     /** For building statuscode. */
101     private SAMLObjectBuilder<StatusCode> statusCodeBuilder;
102
103     /** For building StatusMessages. */
104     private SAMLObjectBuilder<StatusMessage> statusMessageBuilder;
105
106     /** For building assertion. */
107     private SAMLObjectBuilder<Assertion> assertionBuilder;
108
109     /** For building issuer. */
110     private SAMLObjectBuilder<Issuer> issuerBuilder;
111
112     /** For building subject. */
113     private SAMLObjectBuilder<Subject> subjectBuilder;
114
115     /** For builder subject confirmation. */
116     private SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder;
117
118     /** For building conditions. */
119     private SAMLObjectBuilder<Conditions> conditionsBuilder;
120
121     /** For building audience restriction. */
122     private SAMLObjectBuilder<AudienceRestriction> audienceRestrictionBuilder;
123
124     /** For building proxy retrictions. */
125     private SAMLObjectBuilder<ProxyRestriction> proxyRestrictionBuilder;
126
127     /** For building audience. */
128     private SAMLObjectBuilder<Audience> audienceBuilder;
129
130     /** For building advice. */
131     private SAMLObjectBuilder<Advice> adviceBuilder;
132
133     /** For building signature. */
134     private XMLObjectBuilder<Signature> signatureBuilder;
135
136     /** Constructor. */
137     @SuppressWarnings("unchecked")
138     protected AbstractSAML2ProfileHandler() {
139         super();
140
141         responseBuilder = (SAMLObjectBuilder<Response>) getBuilderFactory().getBuilder(Response.DEFAULT_ELEMENT_NAME);
142         statusBuilder = (SAMLObjectBuilder<Status>) getBuilderFactory().getBuilder(Status.DEFAULT_ELEMENT_NAME);
143         statusCodeBuilder = (SAMLObjectBuilder<StatusCode>) getBuilderFactory().getBuilder(
144                 StatusCode.DEFAULT_ELEMENT_NAME);
145         statusMessageBuilder = (SAMLObjectBuilder<StatusMessage>) getBuilderFactory().getBuilder(
146                 StatusMessage.DEFAULT_ELEMENT_NAME);
147         issuerBuilder = (SAMLObjectBuilder<Issuer>) getBuilderFactory().getBuilder(Issuer.DEFAULT_ELEMENT_NAME);
148         assertionBuilder = (SAMLObjectBuilder<Assertion>) getBuilderFactory()
149                 .getBuilder(Assertion.DEFAULT_ELEMENT_NAME);
150         subjectBuilder = (SAMLObjectBuilder<Subject>) getBuilderFactory().getBuilder(Subject.DEFAULT_ELEMENT_NAME);
151         subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) getBuilderFactory().getBuilder(
152                 SubjectConfirmation.DEFAULT_ELEMENT_NAME);
153         conditionsBuilder = (SAMLObjectBuilder<Conditions>) getBuilderFactory().getBuilder(
154                 Conditions.DEFAULT_ELEMENT_NAME);
155         audienceRestrictionBuilder = (SAMLObjectBuilder<AudienceRestriction>) getBuilderFactory().getBuilder(
156                 AudienceRestriction.DEFAULT_ELEMENT_NAME);
157         proxyRestrictionBuilder = (SAMLObjectBuilder<ProxyRestriction>) getBuilderFactory().getBuilder(
158                 ProxyRestriction.DEFAULT_ELEMENT_NAME);
159         audienceBuilder = (SAMLObjectBuilder<Audience>) getBuilderFactory().getBuilder(Audience.DEFAULT_ELEMENT_NAME);
160         adviceBuilder = (SAMLObjectBuilder<Advice>) getBuilderFactory().getBuilder(Advice.DEFAULT_ELEMENT_NAME);
161         signatureBuilder = (XMLObjectBuilder<Signature>) getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME);
162     }
163
164     /**
165      * Convenience method for getting the SAML 2 advice builder.
166      * 
167      * @return SAML 2 advice builder
168      */
169     public SAMLObjectBuilder<Advice> getAdviceBuilder() {
170         return adviceBuilder;
171     }
172
173     /**
174      * Convenience method for getting the SAML 2 assertion builder.
175      * 
176      * @return SAML 2 assertion builder
177      */
178     public SAMLObjectBuilder<Assertion> getAssertionBuilder() {
179         return assertionBuilder;
180     }
181
182     /**
183      * Convenience method for getting the SAML 2 audience builder.
184      * 
185      * @return SAML 2 audience builder
186      */
187     public SAMLObjectBuilder<Audience> getAudienceBuilder() {
188         return audienceBuilder;
189     }
190
191     /**
192      * Convenience method for getting the SAML 2 audience restriction builder.
193      * 
194      * @return SAML 2 audience restriction builder
195      */
196     public SAMLObjectBuilder<AudienceRestriction> getAudienceRestrictionBuilder() {
197         return audienceRestrictionBuilder;
198     }
199
200     /**
201      * Convenience method for getting the SAML 2 conditions builder.
202      * 
203      * @return SAML 2 conditions builder
204      */
205     public SAMLObjectBuilder<Conditions> getConditionsBuilder() {
206         return conditionsBuilder;
207     }
208
209     /**
210      * Convenience method for getting the SAML 2 Issuer builder.
211      * 
212      * @return SAML 2 Issuer builder
213      */
214     public SAMLObjectBuilder<Issuer> getIssuerBuilder() {
215         return issuerBuilder;
216     }
217
218     /**
219      * Convenience method for getting the SAML 2 proxy restriction builder.
220      * 
221      * @return SAML 2 proxy restriction builder
222      */
223     public SAMLObjectBuilder<ProxyRestriction> getProxyRestrictionBuilder() {
224         return proxyRestrictionBuilder;
225     }
226
227     /**
228      * Convenience method for getting the SAML 2 response builder.
229      * 
230      * @return SAML 2 response builder
231      */
232     public SAMLObjectBuilder<Response> getResponseBuilder() {
233         return responseBuilder;
234     }
235
236     /**
237      * Convenience method for getting the Signature builder.
238      * 
239      * @return signature builder
240      */
241     public XMLObjectBuilder<Signature> getSignatureBuilder() {
242         return signatureBuilder;
243     }
244
245     /**
246      * Convenience method for getting the SAML 2 status builder.
247      * 
248      * @return SAML 2 status builder
249      */
250     public SAMLObjectBuilder<Status> getStatusBuilder() {
251         return statusBuilder;
252     }
253
254     /**
255      * Convenience method for getting the SAML 2 status code builder.
256      * 
257      * @return SAML 2 status code builder
258      */
259     public SAMLObjectBuilder<StatusCode> getStatusCodeBuilder() {
260         return statusCodeBuilder;
261     }
262
263     /**
264      * Convenience method for getting the SAML 2 status message builder.
265      * 
266      * @return SAML 2 status message builder
267      */
268     public SAMLObjectBuilder<StatusMessage> getStatusMessageBuilder() {
269         return statusMessageBuilder;
270     }
271
272     /**
273      * Convenience method for getting the SAML 2 subject builder.
274      * 
275      * @return SAML 2 subject builder
276      */
277     public SAMLObjectBuilder<Subject> getSubjectBuilder() {
278         return subjectBuilder;
279     }
280
281     /**
282      * Convenience method for getting the SAML 2 subject confirmation builder.
283      * 
284      * @return SAML 2 subject confirmation builder
285      */
286     public SAMLObjectBuilder<SubjectConfirmation> getSubjectConfirmationBuilder() {
287         return subjectConfirmationBuilder;
288     }
289
290     /**
291      * Builds a response to the attribute query within the request context.
292      * 
293      * @param requestContext current request context
294      * @param assertionSubject subject of the assertion within the response
295      * @param statements the statements to include in the response
296      * 
297      * @return the built response
298      * 
299      * @throws ProfileException thrown if there is a problem creating the SAML response
300      */
301     protected Response buildResponse(SAML2ProfileRequestContext requestContext, Subject assertionSubject,
302             List<Statement> statements) throws ProfileException {
303
304         DateTime issueInstant = new DateTime();
305
306         // create the assertion and add the attribute statement
307         Assertion assertion = buildAssertion(requestContext, issueInstant);
308         assertion.setSubject(assertionSubject);
309         if (statements != null) {
310             assertion.getStatements().addAll(statements);
311         }
312
313         // create the SAML response and add the assertion
314         Response samlResponse = getResponseBuilder().buildObject();
315         samlResponse.setIssueInstant(issueInstant);
316         populateStatusResponse(requestContext, samlResponse);
317
318         samlResponse.getAssertions().add(assertion);
319
320         // sign the assertion if it should be signed
321         signAssertion(requestContext, assertion);
322
323         Status status = buildStatus(StatusCode.SUCCESS_URI, null, null);
324         samlResponse.setStatus(status);
325
326         return samlResponse;
327     }
328
329     /**
330      * Builds a basic assertion with its id, issue instant, SAML version, issuer, subject, and conditions populated.
331      * 
332      * @param requestContext current request context
333      * @param issueInstant time to use as assertion issue instant
334      * 
335      * @return the built assertion
336      */
337     protected Assertion buildAssertion(SAML2ProfileRequestContext requestContext, DateTime issueInstant) {
338         Assertion assertion = getAssertionBuilder().buildObject();
339         assertion.setID(getIdGenerator().generateIdentifier());
340         assertion.setIssueInstant(issueInstant);
341         assertion.setVersion(SAMLVersion.VERSION_20);
342         assertion.setIssuer(buildEntityIssuer(requestContext));
343
344         Conditions conditions = buildConditions(requestContext, issueInstant);
345         assertion.setConditions(conditions);
346
347         return assertion;
348     }
349
350     /**
351      * Creates an {@link Issuer} populated with information about the relying party.
352      * 
353      * @param requestContext current request context
354      * 
355      * @return the built issuer
356      */
357     protected Issuer buildEntityIssuer(SAML2ProfileRequestContext requestContext) {
358         Issuer issuer = getIssuerBuilder().buildObject();
359         issuer.setFormat(Issuer.ENTITY);
360         issuer.setValue(requestContext.getRelyingPartyId());
361
362         return issuer;
363     }
364
365     /**
366      * Builds a SAML assertion condition set. The following fields are set; not before, not on or after, audience
367      * restrictions, and proxy restrictions.
368      * 
369      * @param requestContext current request context
370      * @param issueInstant timestamp the assertion was created
371      * 
372      * @return constructed conditions
373      */
374     protected Conditions buildConditions(SAML2ProfileRequestContext requestContext, DateTime issueInstant) {
375         AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
376
377         Conditions conditions = getConditionsBuilder().buildObject();
378         conditions.setNotBefore(issueInstant);
379         conditions.setNotOnOrAfter(issueInstant.plus(profileConfig.getAssertionLifetime()));
380
381         Collection<String> audiences;
382
383         // add audience restrictions
384         audiences = profileConfig.getAssertionAudiences();
385         if (audiences != null && audiences.size() > 0) {
386             AudienceRestriction audienceRestriction = getAudienceRestrictionBuilder().buildObject();
387             for (String audienceUri : audiences) {
388                 Audience audience = getAudienceBuilder().buildObject();
389                 audience.setAudienceURI(audienceUri);
390                 audienceRestriction.getAudiences().add(audience);
391             }
392             conditions.getAudienceRestrictions().add(audienceRestriction);
393         }
394
395         // add proxy restrictions
396         audiences = profileConfig.getProxyAudiences();
397         if (audiences != null && audiences.size() > 0) {
398             ProxyRestriction proxyRestriction = getProxyRestrictionBuilder().buildObject();
399             Audience audience;
400             for (String audienceUri : audiences) {
401                 audience = getAudienceBuilder().buildObject();
402                 audience.setAudienceURI(audienceUri);
403                 proxyRestriction.getAudiences().add(audience);
404             }
405
406             proxyRestriction.setProxyCount(profileConfig.getProxyCount());
407             conditions.getConditions().add(proxyRestriction);
408         }
409
410         return conditions;
411     }
412
413     /**
414      * Populates the response's id, in response to, issue instant, version, and issuer properties.
415      * 
416      * @param requestContext current request context
417      * @param response the response to populate
418      */
419     protected void populateStatusResponse(SAML2ProfileRequestContext requestContext, StatusResponseType response) {
420         response.setID(getIdGenerator().generateIdentifier());
421         if (requestContext.getSamlRequest() != null) {
422             response.setInResponseTo(requestContext.getSamlRequest().getID());
423         }
424         response.setVersion(SAMLVersion.VERSION_20);
425         response.setIssuer(buildEntityIssuer(requestContext));
426     }
427
428     /**
429      * Executes a query for attributes and builds a SAML attribute statement from the results.
430      * 
431      * @param requestContext current request context
432      * 
433      * @return attribute statement resulting from the query
434      * 
435      * @throws ProfileException thrown if there is a problem making the query
436      */
437     protected AttributeStatement buildAttributeStatement(SAML2ProfileRequestContext requestContext)
438             throws ProfileException {
439
440         if (log.isDebugEnabled()) {
441             log.debug("Creating attribute statement in response to SAML request "
442                     + requestContext.getSamlRequest().getID() + " from relying party "
443                     + requestContext.getRelyingPartyId());
444         }
445
446         AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
447         SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
448
449         if (log.isDebugEnabled()) {
450             log.debug("Resolving principal name for subject of SAML request " + requestContext.getSamlRequest().getID()
451                     + " from relying party " + requestContext.getRelyingPartyId());
452         }
453
454         try {
455             if (log.isDebugEnabled()) {
456                 log.debug("Resolving attributes for principal " + requestContext.getPrincipalName()
457                         + " of SAML request " + requestContext.getSamlRequest().getID() + " from relying party "
458                         + requestContext.getRelyingPartyId());
459             }
460             Map<String, BaseAttribute> principalAttributes = attributeAuthority
461                     .getAttributes(buildAttributeRequestContext(requestContext));
462
463             requestContext.setPrincipalAttributes(principalAttributes);
464
465             if (requestContext.getSamlRequest() instanceof AttributeQuery) {
466                 return attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext.getSamlRequest(),
467                         principalAttributes.values());
468             } else {
469                 return attributeAuthority.buildAttributeStatement(null, principalAttributes.values());
470             }
471         } catch (AttributeRequestException e) {
472             log.error("Error resolving attributes for SAML request " + requestContext.getSamlRequest().getID()
473                     + " from relying party " + requestContext.getRelyingPartyId(), e);
474             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
475             throw new ProfileException("Error resolving attributes for SAML request "
476                     + requestContext.getSamlRequest().getID() + " from relying party "
477                     + requestContext.getRelyingPartyId(), e);
478         }
479     }
480
481     /**
482      * Resolves the principal name of the subject of the request.
483      * 
484      * @param requestContext current request context
485      * 
486      * @throws ProfileException thrown if the principal name can not be resolved
487      */
488     protected void resolvePrincipal(SAML2ProfileRequestContext requestContext) throws ProfileException {
489         AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
490         SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
491
492         if (log.isDebugEnabled()) {
493             log.debug("Resolving principal name for subject of SAML request " + requestContext.getSamlRequest().getID()
494                     + " from relying party " + requestContext.getRelyingPartyId());
495         }
496
497         try {
498             String principal = attributeAuthority.getPrincipal(buildAttributeRequestContext(requestContext));
499             requestContext.setPrincipalName(principal);
500         } catch (AttributeRequestException e) {
501             log.error("Error resolving attributes for SAML request " + requestContext.getSamlRequest().getID()
502                     + " from relying party " + requestContext.getRelyingPartyId(), e);
503             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.UNKNOWN_PRINCIPAL_URI,
504                     "Error resolving principal"));
505             throw new ProfileException("Error resolving attributes for SAML request "
506                     + requestContext.getSamlRequest().getID() + " from relying party "
507                     + requestContext.getRelyingPartyId(), e);
508         }
509     }
510
511     /**
512      * Creates an attribute query context from the current profile request context.
513      * 
514      * @param requestContext current profile request
515      * 
516      * @return created query context
517      */
518     protected ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery> buildAttributeRequestContext(
519             SAML2ProfileRequestContext requestContext) {
520
521         ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery> queryContext;
522         if (requestContext.getSamlRequest() instanceof AttributeQuery) {
523             queryContext = new ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery>(getMetadataProvider(),
524                     requestContext.getRelyingPartyConfiguration(), (AttributeQuery) requestContext.getSamlRequest());
525         } else {
526             queryContext = new ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery>(getMetadataProvider(),
527                     requestContext.getRelyingPartyConfiguration());
528         }
529
530         queryContext.setAttributeRequester(requestContext.getAssertingPartyId());
531         queryContext.setPrincipalName(requestContext.getPrincipalName());
532         queryContext.setProfileConfiguration(requestContext.getProfileConfiguration());
533         queryContext.setRequest(requestContext.getProfileRequest());
534
535         Session userSession = getSessionManager().getSession(getUserSessionId(requestContext.getProfileRequest()));
536         if (userSession != null) {
537             queryContext.setUserSession(userSession);
538             ServiceInformation serviceInfo = userSession.getServiceInformation(requestContext.getRelyingPartyId());
539             if (serviceInfo != null) {
540                 String principalAuthenticationMethod = serviceInfo.getAuthenticationMethod().getAuthenticationMethod();
541
542                 requestContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
543                 queryContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
544             }
545         }
546
547         return queryContext;
548     }
549
550     /**
551      * Signs the given assertion if either the current profile configuration or the relying party configuration contains
552      * signing credentials.
553      * 
554      * @param requestContext current request context
555      * @param assertion assertion to sign
556      * 
557      * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
558      *             required, if a signing credential is not configured
559      */
560     protected void signAssertion(SAML2ProfileRequestContext requestContext, Assertion assertion)
561             throws ProfileException {
562         if (log.isDebugEnabled()) {
563             log.debug("Determining if SAML assertion to relying party " + requestContext.getRelyingPartyId()
564                     + " should be signed");
565         }
566
567         boolean signAssertion = false;
568
569         RoleDescriptor relyingPartyRole;
570         try {
571             relyingPartyRole = getMetadataProvider().getRole(requestContext.getRelyingPartyId(),
572                     requestContext.getRelyingPartyRole(), SAMLConstants.SAML20P_NS);
573         } catch (MetadataProviderException e) {
574             throw new ProfileException("Unable to lookup entity metadata for relying party "
575                     + requestContext.getRelyingPartyId());
576         }
577         AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
578
579         if (relyingPartyRole instanceof SPSSODescriptor) {
580             SPSSODescriptor ssoDescriptor = (SPSSODescriptor) relyingPartyRole;
581             if (ssoDescriptor.getWantAssertionsSigned() != null) {
582                 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
583                 if (log.isDebugEnabled()) {
584                     log.debug("Entity metadata for relying party " + requestContext.getRelyingPartyId()
585                             + " indicates to sign assertions: " + signAssertion);
586                 }
587             }
588         } else if (profileConfig.getSignAssertions()) {
589             signAssertion = true;
590             log.debug("IdP relying party configuration "
591                     + requestContext.getRelyingPartyConfiguration().getRelyingPartyId()
592                     + " indicates to sign assertions: " + signAssertion);
593         }
594
595         if (!signAssertion) {
596             return;
597         }
598
599         if (log.isDebugEnabled()) {
600             log.debug("Determining signing credntial for assertion to relying party "
601                     + requestContext.getRelyingPartyId());
602         }
603         Credential signatureCredential = profileConfig.getSigningCredential();
604         if (signatureCredential == null) {
605             signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
606         }
607
608         if (signatureCredential == null) {
609             throw new ProfileException("No signing credential is specified for relying party configuration "
610                     + requestContext.getRelyingPartyConfiguration().getProviderId()
611                     + " or it's SAML2 attribute query profile configuration");
612         }
613
614         if (log.isDebugEnabled()) {
615             log.debug("Signing assertion to relying party " + requestContext.getRelyingPartyId());
616         }
617         SAMLObjectContentReference contentRef = new SAMLObjectContentReference(assertion);
618         Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
619         signature.getContentReferences().add(contentRef);
620         assertion.setSignature(signature);
621
622         Signer.signObject(signature);
623     }
624
625     /**
626      * Build a status message, with an optional second-level failure message.
627      * 
628      * @param topLevelCode The top-level status code. Should be from saml-core-2.0-os, sec. 3.2.2.2
629      * @param secondLevelCode An optional second-level failure code. Should be from saml-core-2.0-is, sec 3.2.2.2. If
630      *            null, no second-level Status element will be set.
631      * @param failureMessage An optional second-level failure message
632      * 
633      * @return a Status object.
634      */
635     protected Status buildStatus(String topLevelCode, String secondLevelCode, String failureMessage) {
636         Status status = getStatusBuilder().buildObject();
637
638         StatusCode statusCode = getStatusCodeBuilder().buildObject();
639         statusCode.setValue(DatatypeHelper.safeTrimOrNullString(topLevelCode));
640         status.setStatusCode(statusCode);
641
642         if (secondLevelCode != null) {
643             StatusCode secondLevelStatusCode = getStatusCodeBuilder().buildObject();
644             secondLevelStatusCode.setValue(DatatypeHelper.safeTrimOrNullString(secondLevelCode));
645             statusCode.setStatusCode(secondLevelStatusCode);
646         }
647
648         if (failureMessage != null) {
649             StatusMessage msg = getStatusMessageBuilder().buildObject();
650             msg.setMessage(failureMessage);
651             status.setStatusMessage(msg);
652         }
653
654         return status;
655     }
656
657     /**
658      * Builds the SAML subject for the user for the service provider.
659      * 
660      * @param requestContext current request context
661      * @param confirmationMethod subject confirmation method used for the subject
662      * 
663      * @return SAML subject for the user for the service provider
664      * 
665      * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
666      *             name ID attribute or because there are no supported name formats
667      */
668     protected Subject buildSubject(SAML2ProfileRequestContext requestContext, String confirmationMethod)
669             throws ProfileException {
670         NameID nameID = buildNameId(requestContext);
671         requestContext.setSubjectNameID(nameID);
672         // TODO handle encryption
673
674         SubjectConfirmation subjectConfirmation = getSubjectConfirmationBuilder().buildObject();
675         subjectConfirmation.setMethod(confirmationMethod);
676
677         Subject subject = getSubjectBuilder().buildObject();
678         subject.setNameID(nameID);
679         subject.getSubjectConfirmations().add(subjectConfirmation);
680
681         return subject;
682     }
683
684     /**
685      * Builds a NameID appropriate for this request. NameIDs are built by inspecting the SAML request and metadata,
686      * picking a name format that was requested by the relying party or is mutually supported by both the relying party
687      * and asserting party as described in their metadata entries. Once a set of supported name formats is determined
688      * the principals attributes are inspected for an attribtue supported an attribute encoder whose category is one of
689      * the supported name formats.
690      * 
691      * @param requestContext current request context
692      * 
693      * @return the NameID appropriate for this request
694      * 
695      * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
696      *             name ID attribute or because there are no supported name formats
697      */
698     protected NameID buildNameId(SAML2ProfileRequestContext requestContext) throws ProfileException {
699         if (log.isDebugEnabled()) {
700             log.debug("Building assertion NameID for principal/relying party:" + requestContext.getPrincipalName()
701                     + "/" + requestContext.getRelyingPartyId());
702         }
703         Map<String, BaseAttribute> principalAttributes = requestContext.getPrincipalAttributes();
704         List<String> supportedNameFormats = getNameFormats(requestContext);
705
706         if (log.isDebugEnabled()) {
707             log.debug("Supported NameID formats: " + supportedNameFormats);
708         }
709
710         if (principalAttributes != null && supportedNameFormats != null) {
711             try {
712                 AttributeEncoder<NameID> nameIdEncoder = null;
713                 for (BaseAttribute attribute : principalAttributes.values()) {
714                     for (String nameFormat : supportedNameFormats) {
715                         nameIdEncoder = attribute.getEncoderByCategory(nameFormat);
716                         if (nameIdEncoder != null) {
717                             if (log.isDebugEnabled()) {
718                                 log.debug("Using attribute " + attribute.getId() + " suppoting NameID format "
719                                         + nameFormat + " to create the NameID for principal "
720                                         + requestContext.getPrincipalName());
721                             }
722                             return nameIdEncoder.encode(attribute);
723                         }
724                     }
725                 }
726             } catch (AttributeEncodingException e) {
727                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
728                         "Unable to construct NameID"));
729                 throw new ProfileException("Unable to encode NameID attribute", e);
730             }
731         }
732
733         requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
734                 "Unable to construct NameID"));
735         throw new ProfileException("No principal attributes support NameID construction");
736     }
737
738     /**
739      * Gets the NameID format to use when creating NameIDs for the relying party.
740      * 
741      * @param requestContext current request context
742      * 
743      * @return list of nameID formats that may be used with the relying party
744      * 
745      * @throws ProfileException thrown if there is a problem determing the NameID format to use
746      */
747     protected List<String> getNameFormats(SAML2ProfileRequestContext requestContext) throws ProfileException {
748         ArrayList<String> nameFormats = new ArrayList<String>();
749
750         try {
751             RoleDescriptor assertingPartyRole = getMetadataProvider().getRole(requestContext.getAssertingPartyId(),
752                     requestContext.getAssertingPartyRole(), SAMLConstants.SAML20P_NS);
753             List<String> assertingPartySupportedFormats = getEntitySupportedFormats(assertingPartyRole);
754
755             String nameFormat = null;
756             if (requestContext.getSamlRequest() instanceof AuthnRequest) {
757                 AuthnRequest authnRequest = (AuthnRequest) requestContext.getSamlRequest();
758                 if (authnRequest.getNameIDPolicy() != null) {
759                     nameFormat = authnRequest.getNameIDPolicy().getFormat();
760                     if (assertingPartySupportedFormats.contains(nameFormat)) {
761                         nameFormats.add(nameFormat);
762                     } else {
763                         requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI,
764                                 StatusCode.INVALID_NAMEID_POLICY_URI, "Format not supported: " + nameFormat));
765                         throw new ProfileException("NameID format required by relying party is not supported");
766                     }
767                 }
768             }
769
770             if (nameFormats.isEmpty()) {
771                 RoleDescriptor relyingPartyRole = getMetadataProvider().getRole(requestContext.getRelyingPartyId(),
772                         requestContext.getRelyingPartyRole(), SAMLConstants.SAML20P_NS);
773                 List<String> relyingPartySupportedFormats = getEntitySupportedFormats(relyingPartyRole);
774
775                 assertingPartySupportedFormats.retainAll(relyingPartySupportedFormats);
776                 nameFormats.addAll(assertingPartySupportedFormats);
777             }
778             if (nameFormats.isEmpty()) {
779                 nameFormats.add("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
780             }
781
782             return nameFormats;
783
784         } catch (MetadataProviderException e) {
785             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
786                     "Unable to lookup entity metadata"));
787             throw new ProfileException("Unable to determine lookup entity metadata", e);
788         }
789     }
790
791     /**
792      * Gets the list of NameID formats supported for a given role.
793      * 
794      * @param role the role to get the list of supported NameID formats
795      * 
796      * @return list of supported NameID formats
797      */
798     protected List<String> getEntitySupportedFormats(RoleDescriptor role) {
799         List<NameIDFormat> nameIDFormats = null;
800
801         if (role instanceof SSODescriptor) {
802             nameIDFormats = ((SSODescriptor) role).getNameIDFormats();
803         } else if (role instanceof AuthnAuthorityDescriptor) {
804             nameIDFormats = ((AuthnAuthorityDescriptor) role).getNameIDFormats();
805         } else if (role instanceof PDPDescriptor) {
806             nameIDFormats = ((PDPDescriptor) role).getNameIDFormats();
807         } else if (role instanceof AttributeAuthorityDescriptor) {
808             nameIDFormats = ((AttributeAuthorityDescriptor) role).getNameIDFormats();
809         }
810
811         ArrayList<String> supportedFormats = new ArrayList<String>();
812         if (nameIDFormats != null) {
813             for (NameIDFormat format : nameIDFormats) {
814                 supportedFormats.add(format.getFormat());
815             }
816         }
817
818         return supportedFormats;
819     }
820
821     /**
822      * Constructs an SAML response message carrying a request error.
823      * 
824      * @param requestContext current request context
825      * 
826      * @return the constructed error response
827      */
828     protected Response buildErrorResponse(SAML2ProfileRequestContext requestContext) {
829         Response samlResponse = getResponseBuilder().buildObject();
830         samlResponse.setIssueInstant(new DateTime());
831         populateStatusResponse(requestContext, samlResponse);
832
833         samlResponse.setStatus(requestContext.getFailureStatus());
834
835         return samlResponse;
836     }
837
838     /**
839      * Writes an aduit log entry indicating the successful response to the attribute request.
840      * 
841      * @param context current request context
842      */
843     protected void writeAuditLogEntry(SAML2ProfileRequestContext context) {
844         AuditLogEntry auditLogEntry = new AuditLogEntry();
845         auditLogEntry.setMessageProfile(getProfileId());
846         auditLogEntry.setPrincipalAuthenticationMethod(context.getPrincipalAuthenticationMethod());
847         auditLogEntry.setPrincipalName(context.getPrincipalName());
848         auditLogEntry.setAssertingPartyId(context.getAssertingPartyId());
849         auditLogEntry.setRelyingPartyId(context.getRelyingPartyId());
850         auditLogEntry.setRequestBinding(context.getMessageDecoder().getBindingURI());
851         auditLogEntry.setRequestId(context.getSamlRequest().getID());
852         auditLogEntry.setResponseBinding(context.getMessageEncoder().getBindingURI());
853         auditLogEntry.setResponseId(context.getSamlResponse().getID());
854         getAduitLog().log(Level.CRITICAL, auditLogEntry);
855     }
856
857     /**
858      * Contextual object used to accumlate information as profile requests are being processed.
859      * 
860      * @param <RequestType> type of SAML 2 request
861      * @param <ResponseType> type of SAML 2 response
862      * @param <ProfileConfigurationType> configuration type for this profile
863      */
864     protected class SAML2ProfileRequestContext<RequestType extends RequestAbstractType, ResponseType extends StatusResponseType, ProfileConfigurationType extends AbstractSAML2ProfileConfiguration>
865             extends SAMLProfileRequestContext {
866
867         /** SAML request message. */
868         private RequestType samlRequest;
869
870         /** SAML response message. */
871         private ResponseType samlResponse;
872
873         /** Request profile configuration. */
874         private ProfileConfigurationType profileConfiguration;
875
876         /** The NameID of the subject of this request. */
877         private NameID subjectNameID;
878
879         /** The request failure status. */
880         private Status failureStatus;
881
882         /**
883          * Constructor.
884          * 
885          * @param request current profile request
886          * @param response current profile response
887          */
888         public SAML2ProfileRequestContext(ProfileRequest<ServletRequest> request,
889                 ProfileResponse<ServletResponse> response) {
890             super(request, response);
891         }
892
893         /**
894          * Gets the NameID of the subject of this request.
895          * 
896          * @return NameID of the subject of this request
897          */
898         public NameID getSubjectNameID() {
899             return subjectNameID;
900         }
901
902         /**
903          * Sets the NameID of the subject of this request.
904          * 
905          * @param nameID NameID of the subject of this request
906          */
907         public void setSubjectNameID(NameID nameID) {
908             subjectNameID = nameID;
909         }
910
911         /**
912          * Gets the profile configuration for this request.
913          * 
914          * @return profile configuration for this request
915          */
916         public ProfileConfigurationType getProfileConfiguration() {
917             return profileConfiguration;
918         }
919
920         /**
921          * Sets the profile configuration for this request.
922          * 
923          * @param configuration profile configuration for this request
924          */
925         public void setProfileConfiguration(ProfileConfigurationType configuration) {
926             profileConfiguration = configuration;
927         }
928
929         /**
930          * Gets the SAML request message.
931          * 
932          * @return SAML request message
933          */
934         public RequestType getSamlRequest() {
935             return samlRequest;
936         }
937
938         /**
939          * Sets the SAML request message.
940          * 
941          * @param request SAML request message
942          */
943         public void setSamlRequest(RequestType request) {
944             samlRequest = request;
945         }
946
947         /**
948          * Gets the SAML response message.
949          * 
950          * @return SAML response message
951          */
952         public ResponseType getSamlResponse() {
953             return samlResponse;
954         }
955
956         /**
957          * Sets the SAML response message.
958          * 
959          * @param response SAML response message
960          */
961         public void setSamlResponse(ResponseType response) {
962             samlResponse = response;
963         }
964
965         /**
966          * Gets the status reflecting a request failure.
967          * 
968          * @return status reflecting a request failure
969          */
970         public Status getFailureStatus() {
971             return failureStatus;
972         }
973
974         /**
975          * Sets the status reflecting a request failure.
976          * 
977          * @param status status reflecting a request failure
978          */
979         public void setFailureStatus(Status status) {
980             failureStatus = status;
981         }
982     }
983 }