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