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