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