Minor logic bug in last commit
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml2 / AbstractSAML2ProfileHandler.java
index 24e8e9d..f9721c0 100644 (file)
@@ -21,11 +21,9 @@ 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.common.SAMLObjectBuilder;
 import org.opensaml.common.SAMLVersion;
-import org.opensaml.common.impl.SAMLObjectContentReference;
 import org.opensaml.saml2.core.Assertion;
 import org.opensaml.saml2.core.AttributeQuery;
 import org.opensaml.saml2.core.AttributeStatement;
@@ -55,10 +53,14 @@ import org.opensaml.saml2.metadata.SPSSODescriptor;
 import org.opensaml.saml2.metadata.SSODescriptor;
 import org.opensaml.ws.transport.http.HTTPInTransport;
 import org.opensaml.xml.XMLObjectBuilder;
+import org.opensaml.xml.security.SecurityException;
+import org.opensaml.xml.security.SecurityHelper;
 import org.opensaml.xml.security.credential.Credential;
 import org.opensaml.xml.signature.Signature;
 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;
@@ -77,7 +79,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;
@@ -323,21 +325,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,11 +351,9 @@ 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 {
@@ -386,32 +383,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,10 +420,8 @@ 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;
 
@@ -440,26 +431,21 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
             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);
+            log.debug("IdP relying party configuration {} indicates to sign assertions: {}", requestContext
+                    .getRelyingPartyConfiguration().getRelyingPartyId(), 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,12 +457,18 @@ 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);
@@ -574,16 +566,12 @@ 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());
-        }
+        log.debug("Building assertion NameID for principal/relying party:{}/{}", requestContext.getPrincipalName(),
+                requestContext.getInboundMessageIssuer());
         Map<String, BaseAttribute> principalAttributes = requestContext.getPrincipalAttributes();
         List<String> supportedNameFormats = getNameFormats(requestContext);
 
-        if (log.isDebugEnabled()) {
-            log.debug("Supported NameID formats: " + supportedNameFormats);
-        }
+        log.debug("Supported NameID formats: {}", supportedNameFormats);
 
         if (principalAttributes == null || supportedNameFormats == null) {
             log.error("No attributes for principal " + requestContext.getPrincipalName()
@@ -600,11 +588,10 @@ public abstract class AbstractSAML2ProfileHandler extends AbstractSAMLProfileHan
                     if (encoder instanceof SAML2NameIDAttributeEncoder) {
                         nameIdEncoder = (SAML2NameIDAttributeEncoder) 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 for principal.{}",
+                                            attribute.getId(), nameIdEncoder.getNameFormat());
                             return nameIdEncoder.encode(attribute);
                         }
                     }
@@ -633,35 +620,47 @@ 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);
-        }
-        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;
     }