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