Lots of code cleanup
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml2 / AbstractSAML2ProfileHandler.java
index 24e8e9d..4dff4ff 100644 (file)
@@ -21,11 +21,12 @@ import java.util.Collection;
 import java.util.List;
 import java.util.Map;
 
-import org.apache.log4j.Logger;
 import org.joda.time.DateTime;
+import org.opensaml.Configuration;
 import org.opensaml.common.SAMLObjectBuilder;
 import org.opensaml.common.SAMLVersion;
-import org.opensaml.common.impl.SAMLObjectContentReference;
+import org.opensaml.common.binding.encoding.SAMLMessageEncoder;
+import org.opensaml.common.xml.SAMLConstants;
 import org.opensaml.saml2.core.Assertion;
 import org.opensaml.saml2.core.AttributeQuery;
 import org.opensaml.saml2.core.AttributeStatement;
@@ -45,6 +46,8 @@ import org.opensaml.saml2.core.StatusResponseType;
 import org.opensaml.saml2.core.Subject;
 import org.opensaml.saml2.core.SubjectConfirmation;
 import org.opensaml.saml2.core.SubjectConfirmationData;
+import org.opensaml.saml2.encryption.Encrypter;
+import org.opensaml.saml2.encryption.Encrypter.KeyPlacement;
 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
 import org.opensaml.saml2.metadata.AuthnAuthorityDescriptor;
 import org.opensaml.saml2.metadata.Endpoint;
@@ -53,22 +56,43 @@ import org.opensaml.saml2.metadata.PDPDescriptor;
 import org.opensaml.saml2.metadata.RoleDescriptor;
 import org.opensaml.saml2.metadata.SPSSODescriptor;
 import org.opensaml.saml2.metadata.SSODescriptor;
+import org.opensaml.security.MetadataCredentialResolver;
+import org.opensaml.security.MetadataCriteria;
+import org.opensaml.ws.message.encoder.MessageEncodingException;
 import org.opensaml.ws.transport.http.HTTPInTransport;
 import org.opensaml.xml.XMLObjectBuilder;
+import org.opensaml.xml.encryption.EncryptionException;
+import org.opensaml.xml.encryption.EncryptionParameters;
+import org.opensaml.xml.encryption.KeyEncryptionParameters;
+import org.opensaml.xml.io.Marshaller;
+import org.opensaml.xml.io.MarshallingException;
+import org.opensaml.xml.security.CriteriaSet;
+import org.opensaml.xml.security.SecurityConfiguration;
+import org.opensaml.xml.security.SecurityException;
+import org.opensaml.xml.security.SecurityHelper;
 import org.opensaml.xml.security.credential.Credential;
+import org.opensaml.xml.security.credential.UsageType;
+import org.opensaml.xml.security.criteria.EntityIDCriteria;
+import org.opensaml.xml.security.criteria.UsageCriteria;
 import org.opensaml.xml.signature.Signature;
+import org.opensaml.xml.signature.SignatureException;
 import org.opensaml.xml.signature.Signer;
 import org.opensaml.xml.util.DatatypeHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 import edu.internet2.middleware.shibboleth.common.attribute.AttributeRequestException;
 import edu.internet2.middleware.shibboleth.common.attribute.BaseAttribute;
 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncoder;
 import edu.internet2.middleware.shibboleth.common.attribute.encoding.AttributeEncodingException;
-import edu.internet2.middleware.shibboleth.common.attribute.encoding.SAML2NameIDAttributeEncoder;
+import edu.internet2.middleware.shibboleth.common.attribute.encoding.SAML2NameIDEncoder;
 import edu.internet2.middleware.shibboleth.common.attribute.provider.SAML2AttributeAuthority;
 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
+import edu.internet2.middleware.shibboleth.common.profile.provider.BaseSAMLProfileRequestContext;
+import edu.internet2.middleware.shibboleth.common.relyingparty.provider.CryptoOperationRequirementLevel;
 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AbstractSAML2ProfileConfiguration;
 import edu.internet2.middleware.shibboleth.idp.profile.AbstractSAMLProfileHandler;
+import edu.internet2.middleware.shibboleth.idp.session.Session;
 
 /** Common implementation details for profile handlers. */
 public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHandler {
@@ -77,7 +101,7 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
     public static final SAMLVersion SAML_VERSION = SAMLVersion.VERSION_20;
 
     /** Class logger. */
-    private Logger log = Logger.getLogger(AbstractSAML2ProfileHandler.class);
+    private Logger log = LoggerFactory.getLogger(AbstractSAML2ProfileHandler.class);
 
     /** For building response. */
     private SAMLObjectBuilder<Response> responseBuilder;
@@ -150,6 +174,47 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
         signatureBuilder = (XMLObjectBuilder<Signature>) getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME);
     }
 
+    /** {@inheritDoc} */
+    protected void populateRequestContext(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
+        BaseSAML2ProfileRequestContext saml2Request = (BaseSAML2ProfileRequestContext) requestContext;
+        try {
+            super.populateRequestContext(requestContext);
+        } catch (ProfileException e) {
+            if (saml2Request.getFailureStatus() == null) {
+                saml2Request.setFailureStatus(buildStatus(StatusCode.REQUESTER_URI, null, e.getMessage()));
+            }
+            throw e;
+        }
+    }
+
+    /**
+     * Populates the request context with the information about the user.
+     * 
+     * This method requires the the following request context properties to be populated: inbound message transport,
+     * relying party ID
+     * 
+     * This methods populates the following request context properties: user's session, user's principal name, and
+     * service authentication method
+     * 
+     * @param requestContext current request context
+     */
+    protected void populateUserInformation(BaseSAMLProfileRequestContext requestContext) {
+        Session userSession = getUserSession(requestContext.getInboundMessageTransport());
+        if (userSession == null) {
+            NameID subject = (NameID) requestContext.getSubjectNameIdentifier();
+            if (subject != null && subject.getValue() != null) {
+                userSession = getUserSession(subject.getValue());
+            }
+        }
+
+        if (userSession != null) {
+            requestContext.setUserSession(userSession);
+            requestContext.setPrincipalName(userSession.getPrincipalName());
+            requestContext.setPrincipalAuthenticationMethod(userSession.getServicesInformation().get(
+                    requestContext.getPeerEntityId()).getAuthenticationMethod().getAuthenticationMethod());
+        }
+    }
+
     /**
      * Checks that the SAML major version for a request is 2.
      * 
@@ -163,7 +228,7 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
             requestContext.setFailureStatus(buildStatus(StatusCode.VERSION_MISMATCH_URI,
                     StatusCode.REQUEST_VERSION_TOO_LOW_URI, null));
             throw new ProfileException("SAML request version too low");
-        } else if (version.getMajorVersion() > 2) {
+        } else if (version.getMajorVersion() > 2 || version.getMinorVersion() > 0) {
             requestContext.setFailureStatus(buildStatus(StatusCode.VERSION_MISMATCH_URI,
                     StatusCode.REQUEST_VERSION_TOO_HIGH_URI, null));
             throw new ProfileException("SAML request version too high");
@@ -191,7 +256,7 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
         // create the assertion and add the attribute statement
         Assertion assertion = buildAssertion(requestContext, issueInstant);
         assertion.setSubject(subject);
-        if (statements != null) {
+        if (statements != null && !statements.isEmpty()) {
             assertion.getStatements().addAll(statements);
         }
 
@@ -200,11 +265,39 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
         samlResponse.setIssueInstant(issueInstant);
         populateStatusResponse(requestContext, samlResponse);
 
-        samlResponse.getAssertions().add(assertion);
-
         // sign the assertion if it should be signed
         signAssertion(requestContext, assertion);
 
+        SAMLMessageEncoder encoder = getMessageEncoders().get(requestContext.getPeerEntityEndpoint().getBinding());
+        try {
+            if (requestContext.getProfileConfiguration().getEncryptAssertion() == CryptoOperationRequirementLevel.always
+                    || (requestContext.getProfileConfiguration().getEncryptAssertion() == CryptoOperationRequirementLevel.conditional && !encoder
+                            .providesMessageConfidentiality(requestContext))) {
+                log.debug("Attempting to encrypt assertion to relying party {}", requestContext
+                        .getInboundMessageIssuer());
+                try {
+                    Encrypter encrypter = getEncrypter(requestContext.getInboundMessageIssuer());
+                    samlResponse.getEncryptedAssertions().add(encrypter.encrypt(assertion));
+                } catch (SecurityException e) {
+                    log.error("Unable to construct encrypter", e);
+                    requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
+                            "Unable to encrypt assertion"));
+                    throw new ProfileException("Unable to construct encrypter", e);
+                } catch (EncryptionException e) {
+                    log.error("Unable to encrypt assertion", e);
+                    requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
+                            "Unable to encrypt assertion"));
+                    throw new ProfileException("Unable to encrypt assertion", e);
+                }
+            } else {
+                samlResponse.getAssertions().add(assertion);
+            }
+        } catch (MessageEncodingException e) {
+            log.error("Unable to determine if outbound encoding {} can provide confidentiality", encoder
+                    .getBindingURI());
+            throw new ProfileException("Unable to determine if assertions should be encrypted");
+        }
+
         Status status = buildStatus(StatusCode.SUCCESS_URI, null, null);
         samlResponse.setStatus(status);
 
@@ -266,22 +359,25 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
         Collection<String> audiences;
 
         // add audience restrictions
+        AudienceRestriction audienceRestriction = audienceRestrictionBuilder.buildObject();
+        // TODO we should only do this for certain outgoing bindings, not globally
+        Audience audience = audienceBuilder.buildObject();
+        audience.setAudienceURI(requestContext.getInboundMessageIssuer());
+        audienceRestriction.getAudiences().add(audience);
         audiences = profileConfig.getAssertionAudiences();
         if (audiences != null && audiences.size() > 0) {
-            AudienceRestriction audienceRestriction = audienceRestrictionBuilder.buildObject();
             for (String audienceUri : audiences) {
-                Audience audience = audienceBuilder.buildObject();
+                audience = audienceBuilder.buildObject();
                 audience.setAudienceURI(audienceUri);
                 audienceRestriction.getAudiences().add(audience);
             }
-            conditions.getAudienceRestrictions().add(audienceRestriction);
         }
+        conditions.getAudienceRestrictions().add(audienceRestriction);
 
         // add proxy restrictions
         audiences = profileConfig.getProxyAudiences();
         if (audiences != null && audiences.size() > 0) {
             ProxyRestriction proxyRestriction = proxyRestrictionBuilder.buildObject();
-            Audience audience;
             for (String audienceUri : audiences) {
                 audience = audienceBuilder.buildObject();
                 audience.setAudienceURI(audienceUri);
@@ -323,21 +419,18 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
         SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
 
         try {
-            if (log.isDebugEnabled()) {
-                log.debug("Resolving attributes for principal " + requestContext.getPrincipalName()
-                        + " of SAML request " + requestContext.getInboundSAMLMessageId() + " from relying party "
-                        + requestContext.getPeerEntityId());
-            }
+            log.debug("Resolving attributes for principal {} of SAML request from relying party {}", requestContext
+                    .getPrincipalName(), requestContext.getInboundMessageIssuer());
             Map<String, BaseAttribute> principalAttributes = attributeAuthority.getAttributes(requestContext);
 
             requestContext.setAttributes(principalAttributes);
         } catch (AttributeRequestException e) {
             log.error("Error resolving attributes for SAML request " + requestContext.getInboundSAMLMessageId()
-                    + " from relying party " + requestContext.getPeerEntityId(), e);
+                    + " from relying party " + requestContext.getInboundMessageIssuer(), e);
             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error resolving attributes"));
             throw new ProfileException("Error resolving attributes for SAML request "
                     + requestContext.getInboundSAMLMessageId() + " from relying party "
-                    + requestContext.getPeerEntityId(), e);
+                    + requestContext.getInboundMessageIssuer(), e);
         }
     }
 
@@ -352,20 +445,17 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
      */
     protected AttributeStatement buildAttributeStatement(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext)
             throws ProfileException {
-        if (log.isDebugEnabled()) {
-            log.debug("Creating attribute statement in response to SAML request "
-                    + requestContext.getInboundSAMLMessageId() + " from relying party "
-                    + requestContext.getPeerEntityId());
-        }
+        log.debug("Creating attribute statement in response to SAML request {} from relying party {}", requestContext
+                .getInboundSAMLMessageId(), requestContext.getInboundMessageIssuer());
+
         AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
         SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
         try {
             if (requestContext.getInboundSAMLMessage() instanceof AttributeQuery) {
                 return attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext
-                        .getInboundSAMLMessage(), requestContext.getPrincipalAttributes().values());
+                        .getInboundSAMLMessage(), requestContext.getAttributes().values());
             } else {
-                return attributeAuthority.buildAttributeStatement(null, requestContext.getPrincipalAttributes()
-                        .values());
+                return attributeAuthority.buildAttributeStatement(null, requestContext.getAttributes().values());
             }
         } catch (AttributeRequestException e) {
             log.error("Error encoding attributes for principal " + requestContext.getPrincipalName(), e);
@@ -386,32 +476,28 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
         AbstractSAML2ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
         if (profileConfiguration == null) {
             log.error("Unable to resolve principal, no SAML 2 profile configuration for relying party "
-                    + requestContext.getPeerEntityId());
+                    + requestContext.getInboundMessageIssuer());
             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
                     "Error resolving principal"));
             throw new ProfileException(
                     "Unable to resolve principal, no SAML 2 profile configuration for relying party "
-                            + requestContext.getPeerEntityId());
+                            + requestContext.getInboundMessageIssuer());
         }
         SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
-
-        if (log.isDebugEnabled()) {
-            log.debug("Resolving principal name for subject of SAML request "
-                    + requestContext.getInboundSAMLMessageId() + " from relying party "
-                    + requestContext.getPeerEntityId());
-        }
+        log.debug("Resolving principal name for subject of SAML request {} from relying party {}", requestContext
+                .getInboundSAMLMessageId(), requestContext.getInboundMessageIssuer());
 
         try {
             String principal = attributeAuthority.getPrincipal(requestContext);
             requestContext.setPrincipalName(principal);
         } catch (AttributeRequestException e) {
             log.error("Error resolving attributes for SAML request " + requestContext.getInboundSAMLMessageId()
-                    + " from relying party " + requestContext.getPeerEntityId(), e);
+                    + " from relying party " + requestContext.getInboundMessageIssuer(), e);
             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.UNKNOWN_PRINCIPAL_URI,
                     "Error resolving principal"));
             throw new ProfileException("Error resolving attributes for SAML request "
                     + requestContext.getInboundSAMLMessageId() + " from relying party "
-                    + requestContext.getPeerEntityId(), e);
+                    + requestContext.getInboundMessageIssuer(), e);
         }
     }
 
@@ -427,39 +513,42 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
      */
     protected void signAssertion(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext, Assertion assertion)
             throws ProfileException {
-        if (log.isDebugEnabled()) {
-            log.debug("Determining if SAML assertion to relying party " + requestContext.getPeerEntityId()
-                    + " should be signed");
-        }
+        log.debug("Determining if SAML assertion to relying party {} should be signed", requestContext
+                .getInboundMessageIssuer());
 
         boolean signAssertion = false;
 
+        SAMLMessageEncoder encoder = getMessageEncoders().get(requestContext.getPeerEntityEndpoint().getBinding());
         AbstractSAML2ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
+        try {
+            if (profileConfig.getSignAssertions() == CryptoOperationRequirementLevel.always
+                    || (profileConfig.getSignAssertions() == CryptoOperationRequirementLevel.conditional && !encoder
+                            .providesMessageIntegrity(requestContext))) {
+                signAssertion = true;
+                log.debug("IdP relying party configuration {} indicates to sign assertions: {}", requestContext
+                        .getRelyingPartyConfiguration().getRelyingPartyId(), signAssertion);
+            }
+        } catch (MessageEncodingException e) {
+            log.error("Unable to determine if outbound encoding {} can provide integrity protection", encoder
+                    .getBindingURI());
+            throw new ProfileException("Unable to determine if outbound message should be signed");
+        }
 
-        if (requestContext.getPeerEntityRoleMetadata() instanceof SPSSODescriptor) {
+        if (!signAssertion && requestContext.getPeerEntityRoleMetadata() instanceof SPSSODescriptor) {
             SPSSODescriptor ssoDescriptor = (SPSSODescriptor) requestContext.getPeerEntityRoleMetadata();
             if (ssoDescriptor.getWantAssertionsSigned() != null) {
                 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
-                if (log.isDebugEnabled()) {
-                    log.debug("Entity metadata for relying party " + requestContext.getPeerEntityId()
-                            + " indicates to sign assertions: " + signAssertion);
-                }
+                log.debug("Entity metadata for relying party {} indicates to sign assertions: {}", requestContext
+                        .getInboundMessageIssuer(), signAssertion);
             }
-        } else if (profileConfig.getSignAssertions()) {
-            signAssertion = true;
-            log.debug("IdP relying party configuration "
-                    + requestContext.getRelyingPartyConfiguration().getRelyingPartyId()
-                    + " indicates to sign assertions: " + signAssertion);
         }
 
         if (!signAssertion) {
             return;
         }
 
-        if (log.isDebugEnabled()) {
-            log.debug("Determining signing credntial for assertion to relying party "
-                    + requestContext.getPeerEntityId());
-        }
+        log.debug("Determining signing credntial for assertion to relying party {}", requestContext
+                .getInboundMessageIssuer());
         Credential signatureCredential = profileConfig.getSigningCredential();
         if (signatureCredential == null) {
             signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
@@ -471,15 +560,31 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
                     + " or it's SAML2 attribute query profile configuration");
         }
 
-        if (log.isDebugEnabled()) {
-            log.debug("Signing assertion to relying party " + requestContext.getPeerEntityId());
-        }
-        SAMLObjectContentReference contentRef = new SAMLObjectContentReference(assertion);
+        log.debug("Signing assertion to relying party {}", requestContext.getInboundMessageIssuer());
         Signature signature = signatureBuilder.buildObject(Signature.DEFAULT_ELEMENT_NAME);
-        signature.getContentReferences().add(contentRef);
+
+        signature.setSigningCredential(signatureCredential);
+        try {
+            // TODO pull SecurityConfiguration from SAMLMessageContext? needs to be added
+            // TODO how to pull what keyInfoGenName to use?
+            SecurityHelper.prepareSignatureParams(signature, signatureCredential, null, null);
+        } catch (SecurityException e) {
+            throw new ProfileException("Error preparing signature for signing", e);
+        }
+
         assertion.setSignature(signature);
 
-        Signer.signObject(signature);
+        Marshaller assertionMarshaller = Configuration.getMarshallerFactory().getMarshaller(assertion);
+        try {
+            assertionMarshaller.marshall(assertion);
+            Signer.signObject(signature);
+        } catch (MarshallingException e) {
+            log.error("Unable to marshall assertion for signing", e);
+            throw new ProfileException("Unable to marshall assertion for signing", e);
+        } catch (SignatureException e) {
+            log.error("Unable to sign assertion", e);
+            throw new ProfileException("Unable to sign assertion", e);
+        }
     }
 
     /**
@@ -530,7 +635,6 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
             DateTime issueInstant) throws ProfileException {
         NameID nameID = buildNameId(requestContext);
         requestContext.setSubjectNameIdentifier(nameID);
-        // TODO handle encryption
 
         SubjectConfirmationData confirmationData = subjectConfirmationDataBuilder.buildObject();
         HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
@@ -553,8 +657,35 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
         subjectConfirmation.setSubjectConfirmationData(confirmationData);
 
         Subject subject = subjectBuilder.buildObject();
-        subject.setNameID(nameID);
         subject.getSubjectConfirmations().add(subjectConfirmation);
+        SAMLMessageEncoder encoder = getMessageEncoders().get(requestContext.getPeerEntityEndpoint().getBinding());
+        try {
+            if (requestContext.getProfileConfiguration().getEncryptNameID() == CryptoOperationRequirementLevel.always
+                    || (requestContext.getProfileConfiguration().getEncryptNameID() == CryptoOperationRequirementLevel.conditional && !encoder
+                            .providesMessageConfidentiality(requestContext))) {
+                log.debug("Attempting to encrypt NameID to relying party {}", requestContext.getInboundMessageIssuer());
+                try {
+                    Encrypter encrypter = getEncrypter(requestContext.getInboundMessageIssuer());
+                    subject.setEncryptedID(encrypter.encrypt(nameID));
+                } catch (SecurityException e) {
+                    log.error("Unable to construct encrypter", e);
+                    requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
+                            "Unable to construct NameID"));
+                    throw new ProfileException("Unable to construct encrypter", e);
+                } catch (EncryptionException e) {
+                    log.error("Unable to encrypt NameID", e);
+                    requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
+                            "Unable to construct NameID"));
+                    throw new ProfileException("Unable to encrypt NameID", e);
+                }
+            } else {
+                subject.setNameID(nameID);
+            }
+        } catch (MessageEncodingException e) {
+            log.error("Unable to determine if outbound encoding {} can provide confidentiality", encoder
+                    .getBindingURI());
+            throw new ProfileException("Unable to determine if assertions should be encrypted");
+        }
 
         return subject;
     }
@@ -574,42 +705,42 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
      *             name ID attribute or because there are no supported name formats
      */
     protected NameID buildNameId(BaseSAML2ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
-        if (log.isDebugEnabled()) {
-            log.debug("Building assertion NameID for principal/relying party:" + requestContext.getPrincipalName()
-                    + "/" + requestContext.getPeerEntityId());
-        }
-        Map<String, BaseAttribute> principalAttributes = requestContext.getPrincipalAttributes();
-        List<String> supportedNameFormats = getNameFormats(requestContext);
+        log.debug("Building assertion NameID for principal/relying party:{}/{}", requestContext.getPrincipalName(),
+                requestContext.getInboundMessageIssuer());
 
-        if (log.isDebugEnabled()) {
-            log.debug("Supported NameID formats: " + supportedNameFormats);
+        Map<String, BaseAttribute> principalAttributes = requestContext.getAttributes();
+        if (principalAttributes == null || principalAttributes.isEmpty()) {
+            log.error("No attributes for principal {}, unable to construct of NameID", requestContext
+                    .getPrincipalName());
+            requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
+                    "Unable to construct NameID"));
+            throw new ProfileException("No principal attributes support NameID construction");
         }
 
-        if (principalAttributes == null || supportedNameFormats == null) {
-            log.error("No attributes for principal " + requestContext.getPrincipalName()
-                    + " support constructions of NameID");
+        List<String> supportedNameFormats = getNameFormats(requestContext);
+        if (supportedNameFormats == null || supportedNameFormats.isEmpty()) {
+            log.error("No common NameID formats supported by SP {} and IdP", requestContext.getInboundMessageIssuer());
             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.INVALID_NAMEID_POLICY_URI,
                     "Unable to construct NameID"));
             throw new ProfileException("No principal attributes support NameID construction");
         }
 
+        log.debug("Supported NameID formats: {}", supportedNameFormats);
         try {
-            SAML2NameIDAttributeEncoder nameIdEncoder;
+            SAML2NameIDEncoder nameIdEncoder;
             for (BaseAttribute<?> attribute : principalAttributes.values()) {
                 for (AttributeEncoder encoder : attribute.getEncoders()) {
-                    if (encoder instanceof SAML2NameIDAttributeEncoder) {
-                        nameIdEncoder = (SAML2NameIDAttributeEncoder) encoder;
+                    if (encoder instanceof SAML2NameIDEncoder) {
+                        nameIdEncoder = (SAML2NameIDEncoder) encoder;
                         if (supportedNameFormats.contains(nameIdEncoder.getNameFormat())) {
-                            if (log.isDebugEnabled()) {
-                                log.debug("Using attribute " + attribute.getId() + " suppoting NameID format "
-                                        + nameIdEncoder.getNameFormat() + " to create the NameID for principal "
-                                        + requestContext.getPrincipalName());
-                            }
+                            log.debug("Using attribute {} suppoting NameID format {} to create the NameID.", attribute
+                                    .getId(), nameIdEncoder.getNameFormat());
                             return nameIdEncoder.encode(attribute);
                         }
                     }
                 }
             }
+
             log.error("No principal attribute supported encoding into a supported name ID format.");
             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Unable to construct NameID"));
             throw new ProfileException("No principal attribute supported encoding into a supported name ID format.");
@@ -633,33 +764,45 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
             throws ProfileException {
         ArrayList<String> nameFormats = new ArrayList<String>();
 
-        List<String> assertingPartySupportedFormats = getEntitySupportedFormats(requestContext
-                .getLocalEntityRoleMetadata());
-
-        String nameFormat = null;
-        if (requestContext.getInboundSAMLMessage() instanceof AuthnRequest) {
-            AuthnRequest authnRequest = (AuthnRequest) requestContext.getInboundSAMLMessage();
-            if (authnRequest.getNameIDPolicy() != null && !DatatypeHelper.isEmpty(nameFormat)) {
-                nameFormat = authnRequest.getNameIDPolicy().getFormat();
-                if (assertingPartySupportedFormats.contains(nameFormat)) {
-                    nameFormats.add(nameFormat);
-                } else {
-                    requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI,
-                            StatusCode.INVALID_NAMEID_POLICY_URI, "Format not supported: " + nameFormat));
-                    throw new ProfileException("NameID format required by relying party is not supported");
+        // Determine name formats supported by both SP and IdP
+        RoleDescriptor relyingPartyRole = requestContext.getPeerEntityRoleMetadata();
+        if (relyingPartyRole != null) {
+            List<String> relyingPartySupportedFormats = getEntitySupportedFormats(relyingPartyRole);
+            if (relyingPartySupportedFormats != null && !relyingPartySupportedFormats.isEmpty()) {
+                nameFormats.addAll(relyingPartySupportedFormats);
+
+                RoleDescriptor assertingPartyRole = requestContext.getLocalEntityRoleMetadata();
+                if (assertingPartyRole != null) {
+                    List<String> assertingPartySupportedFormats = getEntitySupportedFormats(assertingPartyRole);
+                    if (assertingPartySupportedFormats != null && !assertingPartySupportedFormats.isEmpty()) {
+                        nameFormats.retainAll(assertingPartySupportedFormats);
+                    }
                 }
             }
         }
 
         if (nameFormats.isEmpty()) {
-            List<String> relyingPartySupportedFormats = getEntitySupportedFormats(requestContext
-                    .getPeerEntityRoleMetadata());
-
-            assertingPartySupportedFormats.retainAll(relyingPartySupportedFormats);
-            nameFormats.addAll(assertingPartySupportedFormats);
+            nameFormats.add("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified");
         }
-        if (nameFormats.isEmpty()) {
-            nameFormats.add("urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified");
+
+        // If authn request and name ID policy format specified, make sure it's in the list of supported formats
+        String nameFormat = null;
+        if (requestContext.getInboundSAMLMessage() instanceof AuthnRequest) {
+            AuthnRequest authnRequest = (AuthnRequest) requestContext.getInboundSAMLMessage();
+            if (authnRequest.getNameIDPolicy() != null) {
+                nameFormat = DatatypeHelper.safeTrimOrNullString(authnRequest.getNameIDPolicy().getFormat());
+                if (nameFormat != null) {
+                    if (nameFormats.contains(nameFormat)) {
+                        nameFormats.clear();
+                        nameFormats.add(nameFormat);
+                    } else {
+                        requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI,
+                                StatusCode.INVALID_NAMEID_POLICY_URI, "Format not supported: " + nameFormat));
+                        throw new ProfileException("NameID format required by relying party is not supported");
+                    }
+                }
+
+            }
         }
 
         return nameFormats;
@@ -711,4 +854,51 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
 
         return samlResponse;
     }
+
+    /**
+     * Gets an encrypter that may be used encrypt content to a given peer.
+     * 
+     * @param peerEntityId entity ID of the peer
+     * 
+     * @return encrypter that may be used encrypt content to a given peer
+     * 
+     * @throws SecurityException thrown if there is a problem constructing the encrypter. This normally occurs if the
+     *             key encryption credential for the peer can not be resolved or a required encryption algorithm is not
+     *             supported by the VM's JCE.
+     */
+    protected Encrypter getEncrypter(String peerEntityId) throws SecurityException {
+        SecurityConfiguration securityConfiguration = Configuration.getGlobalSecurityConfiguration();
+
+        EncryptionParameters dataEncParams = SecurityHelper
+                .buildDataEncryptionParams(null, securityConfiguration, null);
+
+        Credential keyEncryptionCredentials = getKeyEncryptionCredential(peerEntityId);
+        String wrappedJCAKeyAlgorithm = SecurityHelper.getKeyAlgorithmFromURI(dataEncParams.getAlgorithm());
+        KeyEncryptionParameters keyEncParams = SecurityHelper.buildKeyEncryptionParams(keyEncryptionCredentials,
+                wrappedJCAKeyAlgorithm, securityConfiguration, null, null);
+
+        Encrypter encrypter = new Encrypter(dataEncParams, keyEncParams);
+        encrypter.setKeyPlacement(KeyPlacement.INLINE);
+        return encrypter;
+    }
+
+    /**
+     * Gets the credential that can be used to encrypt encryption keys for a peer.
+     * 
+     * @param peerEntityId entity ID of the peer
+     * 
+     * @return credential that can be used to encrypt encryption keys for a peer
+     * 
+     * @throws SecurityException thrown if there is a problem resolving the credential from the peer's metadata
+     */
+    protected Credential getKeyEncryptionCredential(String peerEntityId) throws SecurityException {
+        MetadataCredentialResolver kekCredentialResolver = new MetadataCredentialResolver(getMetadataProvider());
+
+        CriteriaSet criteriaSet = new CriteriaSet();
+        criteriaSet.add(new EntityIDCriteria(peerEntityId));
+        criteriaSet.add(new MetadataCriteria(SPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS));
+        criteriaSet.add(new UsageCriteria(UsageType.ENCRYPTION));
+
+        return kekCredentialResolver.resolveSingle(criteriaSet);
+    }
 }
\ No newline at end of file