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