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