SAML 1 Attribute Query unit test and bug fixes
[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             throw new ProfileException("No principal attribute supported encoding into the a supported name ID format.");
345         } catch (AttributeEncodingException e) {
346             log.error("Unable to construct NameIdentifier", e);
347             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
348                     "Unable to construct NameIdentifier"));
349             throw new ProfileException("Unable to encode NameIdentifier attribute", e);
350         }
351
352     }
353
354     /**
355      * Gets the NameIdentifier format to use when creating NameIdentifiers for the relying party.
356      * 
357      * @param requestContext current request context
358      * 
359      * @return list of formats that may be used with the relying party
360      * 
361      * @throws ProfileException thrown if there is a problem determing the NameIdentifier format to use
362      */
363     protected List<String> getNameFormats(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext)
364             throws ProfileException {
365         ArrayList<String> nameFormats = new ArrayList<String>();
366
367         RoleDescriptor assertingPartyRole = requestContext.getLocalEntityRoleMetadata();
368         List<String> assertingPartySupportedFormats = getEntitySupportedFormats(assertingPartyRole);
369
370         if (nameFormats.isEmpty()) {
371             RoleDescriptor relyingPartyRole = requestContext.getPeerEntityRoleMetadata();
372             List<String> relyingPartySupportedFormats = getEntitySupportedFormats(relyingPartyRole);
373
374             assertingPartySupportedFormats.retainAll(relyingPartySupportedFormats);
375             nameFormats.addAll(assertingPartySupportedFormats);
376         }
377         if (nameFormats.isEmpty()) {
378             nameFormats.add("urn:oasis:names:tc:SAML:1.0:nameid-format:unspecified");
379         }
380
381         return nameFormats;
382     }
383
384     /**
385      * Gets the list of NameIdentifier formats supported for a given role.
386      * 
387      * @param role the role to get the list of supported NameIdentifier formats
388      * 
389      * @return list of supported NameIdentifier formats
390      */
391     protected List<String> getEntitySupportedFormats(RoleDescriptor role) {
392         List<NameIDFormat> nameIDFormats = null;
393
394         if (role instanceof SSODescriptor) {
395             nameIDFormats = ((SSODescriptor) role).getNameIDFormats();
396         } else if (role instanceof AuthnAuthorityDescriptor) {
397             nameIDFormats = ((AuthnAuthorityDescriptor) role).getNameIDFormats();
398         } else if (role instanceof PDPDescriptor) {
399             nameIDFormats = ((PDPDescriptor) role).getNameIDFormats();
400         } else if (role instanceof AttributeAuthorityDescriptor) {
401             nameIDFormats = ((AttributeAuthorityDescriptor) role).getNameIDFormats();
402         }
403
404         ArrayList<String> supportedFormats = new ArrayList<String>();
405         if (nameIDFormats != null) {
406             for (NameIDFormat format : nameIDFormats) {
407                 supportedFormats.add(format.getFormat());
408             }
409         }
410
411         return supportedFormats;
412     }
413
414     /**
415      * Constructs an SAML response message carrying a request error.
416      * 
417      * @param requestContext current request context containing the failure status
418      * 
419      * @return the constructed error response
420      */
421     protected Response buildErrorResponse(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext) {
422         Response samlResponse = responseBuilder.buildObject();
423         samlResponse.setIssueInstant(new DateTime());
424         populateStatusResponse(requestContext, samlResponse);
425
426         samlResponse.setStatus(requestContext.getFailureStatus());
427
428         return samlResponse;
429     }
430
431     /**
432      * Populates the response's id, in response to, issue instant, version, and issuer properties.
433      * 
434      * @param requestContext current request context
435      * @param response the response to populate
436      */
437     protected void populateStatusResponse(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext,
438             ResponseAbstractType response) {
439         response.setID(getIdGenerator().generateIdentifier());
440
441         SAMLObject samlMessage = requestContext.getInboundSAMLMessage();
442         if (samlMessage != null && samlMessage instanceof RequestAbstractType) {
443             response.setInResponseTo(((RequestAbstractType) samlMessage).getID());
444         }
445         response.setVersion(SAMLVersion.VERSION_11);
446     }
447
448     /**
449      * Build a status message, with an optional second-level failure message.
450      * 
451      * @param topLevelCode top-level status code
452      * @param secondLevelCode second-level status code
453      * @param failureMessage An optional second-level failure message
454      * 
455      * @return a Status object.
456      */
457     protected Status buildStatus(QName topLevelCode, QName secondLevelCode, String failureMessage) {
458         Status status = statusBuilder.buildObject();
459
460         StatusCode statusCode = statusCodeBuilder.buildObject();
461         statusCode.setValue(topLevelCode);
462         status.setStatusCode(statusCode);
463
464         if (secondLevelCode != null) {
465             StatusCode secondLevelStatusCode = statusCodeBuilder.buildObject();
466             secondLevelStatusCode.setValue(secondLevelCode);
467             statusCode.setStatusCode(secondLevelStatusCode);
468         }
469
470         if (failureMessage != null) {
471             StatusMessage msg = statusMessageBuilder.buildObject();
472             msg.setMessage(failureMessage);
473             status.setStatusMessage(msg);
474         }
475
476         return status;
477     }
478
479     /**
480      * Resolved the attributes for the principal.
481      * 
482      * @param requestContext current request context
483      * 
484      * @throws ProfileException thrown if attributes can not be resolved
485      */
486     protected void resolveAttributes(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
487         AbstractSAML1ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
488         SAML1AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
489
490         try {
491             if (log.isDebugEnabled()) {
492                 log.debug("Resolving attributes for principal " + requestContext.getPrincipalName()
493                         + " of SAML request from relying party " + requestContext.getInboundMessageIssuer());
494             }
495             Map<String, BaseAttribute> principalAttributes = attributeAuthority.getAttributes(requestContext);
496
497             requestContext.setAttributes(principalAttributes);
498         } catch (AttributeRequestException e) {
499             log.error("Error resolving attributes for SAML request from relying party "
500                     + requestContext.getInboundMessageIssuer(), e);
501             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error resolving attributes"));
502             throw new ProfileException("Error resolving attributes for SAML request from relying party "
503                     + requestContext.getInboundMessageIssuer(), e);
504         }
505     }
506
507     /**
508      * Executes a query for attributes and builds a SAML attribute statement from the results.
509      * 
510      * @param requestContext current request context
511      * @param subjectConfMethod subject confirmation method
512      * 
513      * @return attribute statement resulting from the query
514      * 
515      * @throws ProfileException thrown if there is a problem making the query
516      */
517     protected AttributeStatement buildAttributeStatement(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext,
518             String subjectConfMethod) throws ProfileException {
519
520         if (log.isDebugEnabled()) {
521             log.debug("Creating attribute statement in response to SAML request from relying party "
522                     + requestContext.getInboundMessageIssuer());
523         }
524
525         AbstractSAML1ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
526         SAML1AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
527
528         try {
529             AttributeStatement statment;
530             if (requestContext.getInboundSAMLMessage() instanceof AttributeQuery) {
531                 statment = attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext
532                         .getInboundSAMLMessage(), requestContext.getPrincipalAttributes().values());
533             } else {
534                 statment = attributeAuthority.buildAttributeStatement(null, requestContext.getPrincipalAttributes()
535                         .values());
536             }
537
538             Subject statementSubject = buildSubject(requestContext, subjectConfMethod);
539             statment.setSubject(statementSubject);
540
541             return statment;
542         } catch (AttributeRequestException e) {
543             log.error("Error encoding attributes for principal " + requestContext.getPrincipalName(), e);
544             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error resolving attributes"));
545             throw new ProfileException("Error encoding attributes for principal " + requestContext.getPrincipalName(),
546                     e);
547         }
548     }
549
550     /**
551      * Resolves the principal name of the subject of the request.
552      * 
553      * @param requestContext current request context
554      * 
555      * @throws ProfileException thrown if the principal name can not be resolved
556      */
557     protected void resolvePrincipal(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
558         AbstractSAML1ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
559         SAML1AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
560
561         if (log.isDebugEnabled()) {
562             log.debug("Resolving principal name for subject of SAML request from relying party "
563                     + requestContext.getInboundMessageIssuer());
564         }
565
566         try {
567             String principal = attributeAuthority.getPrincipal(requestContext);
568             requestContext.setPrincipalName(principal);
569         } catch (AttributeRequestException e) {
570             log.error("Error resolving attributes for SAML request from relying party "
571                     + requestContext.getInboundMessageIssuer(), e);
572             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
573                     "Error resolving principal"));
574             throw new ProfileException("Error resolving attributes for SAML request from relying party "
575                     + requestContext.getInboundMessageIssuer(), e);
576         }
577     }
578
579     /**
580      * Signs the given assertion if either the current profile configuration or the relying party configuration contains
581      * signing credentials.
582      * 
583      * @param requestContext current request context
584      * @param assertion assertion to sign
585      * 
586      * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
587      *             required, if a signing credential is not configured
588      */
589     protected void signAssertion(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext, Assertion assertion)
590             throws ProfileException {
591         if (log.isDebugEnabled()) {
592             log.debug("Determining if SAML assertion to relying party " + requestContext.getInboundMessageIssuer()
593                     + " should be signed");
594         }
595
596         boolean signAssertion = false;
597
598         RoleDescriptor relyingPartyRole = requestContext.getPeerEntityRoleMetadata();
599         AbstractSAML1ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
600
601         if (relyingPartyRole instanceof SPSSODescriptor) {
602             SPSSODescriptor ssoDescriptor = (SPSSODescriptor) relyingPartyRole;
603             if (ssoDescriptor.getWantAssertionsSigned() != null) {
604                 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
605                 if (log.isDebugEnabled()) {
606                     log.debug("Entity metadata for relying party " + requestContext.getInboundMessageIssuer()
607                             + " indicates to sign assertions: " + signAssertion);
608                 }
609             }
610         } else if (profileConfig.getSignAssertions()) {
611             signAssertion = true;
612             log.debug("IdP relying party configuration "
613                     + requestContext.getRelyingPartyConfiguration().getRelyingPartyId()
614                     + " indicates to sign assertions: " + signAssertion);
615         }
616
617         if (!signAssertion) {
618             return;
619         }
620
621         if (log.isDebugEnabled()) {
622             log.debug("Determining signing credntial for assertion to relying party "
623                     + requestContext.getInboundMessageIssuer());
624         }
625         Credential signatureCredential = profileConfig.getSigningCredential();
626         if (signatureCredential == null) {
627             signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
628         }
629
630         if (signatureCredential == null) {
631             throw new ProfileException("No signing credential is specified for relying party configuration "
632                     + requestContext.getRelyingPartyConfiguration().getProviderId()
633                     + " or it's SAML2 attribute query profile configuration");
634         }
635
636         if (log.isDebugEnabled()) {
637             log.debug("Signing assertion to relying party " + requestContext.getInboundMessageIssuer());
638         }
639         Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
640         
641         signature.setSigningCredential(signatureCredential);
642         try {
643             //TODO pull SecurityConfiguration from SAMLMessageContext?  needs to be added
644             //TODO how to pull what keyInfoGenName to use?
645             SecurityHelper.prepareSignatureParams(signature, signatureCredential, null, null);
646         } catch (SecurityException e) {
647             throw new ProfileException("Error preparing signature for signing", e);
648         }
649         
650         assertion.setSignature(signature);
651
652         Signer.signObject(signature);
653     }
654 }