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