Lots of code cleanup
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml1 / AbstractSAML1ProfileHandler.java
index 1974f1b..70c9cc8 100644 (file)
@@ -21,17 +21,14 @@ import java.util.Collection;
 import java.util.List;
 import java.util.Map;
 
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
+import javax.xml.namespace.QName;
 
-import org.apache.log4j.Logger;
 import org.joda.time.DateTime;
+import org.opensaml.Configuration;
 import org.opensaml.common.SAMLObject;
 import org.opensaml.common.SAMLObjectBuilder;
 import org.opensaml.common.SAMLVersion;
-import org.opensaml.common.impl.SAMLObjectContentReference;
-import org.opensaml.common.xml.SAMLConstants;
-import org.opensaml.log.Level;
+import org.opensaml.common.binding.encoding.SAMLMessageEncoder;
 import org.opensaml.saml1.core.Assertion;
 import org.opensaml.saml1.core.AttributeQuery;
 import org.opensaml.saml1.core.AttributeStatement;
@@ -56,26 +53,30 @@ 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.saml2.metadata.provider.MetadataProviderException;
+import org.opensaml.ws.message.encoder.MessageEncodingException;
 import org.opensaml.xml.XMLObjectBuilder;
+import org.opensaml.xml.io.Marshaller;
+import org.opensaml.xml.io.MarshallingException;
+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.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.SAML1NameIdentifierEncoder;
 import edu.internet2.middleware.shibboleth.common.attribute.provider.SAML1AttributeAuthority;
-import edu.internet2.middleware.shibboleth.common.attribute.provider.ShibbolethSAMLAttributeRequestContext;
-import edu.internet2.middleware.shibboleth.common.log.AuditLogEntry;
 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
-import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
-import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
+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.saml1.AbstractSAML1ProfileConfiguration;
 import edu.internet2.middleware.shibboleth.idp.profile.AbstractSAMLProfileHandler;
-import edu.internet2.middleware.shibboleth.idp.session.ServiceInformation;
 import edu.internet2.middleware.shibboleth.idp.session.Session;
 
 /** Common implementation details for profile handlers. */
@@ -85,7 +86,7 @@ public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHan
     public static final SAMLVersion SAML_VERSION = SAMLVersion.VERSION_11;
 
     /** Class logger. */
-    private static Logger log = Logger.getLogger(AbstractSAML1ProfileHandler.class);
+    private static Logger log = LoggerFactory.getLogger(AbstractSAML1ProfileHandler.class);
 
     /** Builder of Response objects. */
     private SAMLObjectBuilder<Response> responseBuilder;
@@ -102,9 +103,6 @@ public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHan
     /** Builder of AudienceRestrictionCondition objects. */
     private SAMLObjectBuilder<Audience> audienceBuilder;
 
-    /** Builder of NameIdentifier objects. */
-    private SAMLObjectBuilder<NameIdentifier> nameIdBuilder;
-
     /** Builder of SubjectConfirmation objects. */
     private SAMLObjectBuilder<SubjectConfirmation> subjectConfirmationBuilder;
 
@@ -140,8 +138,6 @@ public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHan
         audienceRestrictionConditionBuilder = (SAMLObjectBuilder<AudienceRestrictionCondition>) getBuilderFactory()
                 .getBuilder(AudienceRestrictionCondition.DEFAULT_ELEMENT_NAME);
         audienceBuilder = (SAMLObjectBuilder<Audience>) getBuilderFactory().getBuilder(Audience.DEFAULT_ELEMENT_NAME);
-        nameIdBuilder = (SAMLObjectBuilder<NameIdentifier>) getBuilderFactory().getBuilder(
-                NameIdentifier.DEFAULT_ELEMENT_NAME);
         subjectConfirmationBuilder = (SAMLObjectBuilder<SubjectConfirmation>) getBuilderFactory().getBuilder(
                 SubjectConfirmation.DEFAULT_ELEMENT_NAME);
         confirmationMethodBuilder = (SAMLObjectBuilder<ConfirmationMethod>) getBuilderFactory().getBuilder(
@@ -155,112 +151,69 @@ public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHan
         signatureBuilder = (XMLObjectBuilder<Signature>) getBuilderFactory().getBuilder(Signature.DEFAULT_ELEMENT_NAME);
     }
 
-    /**
-     * Convenience method for getting the SAML 1 Response builder.
-     * 
-     * @return SAML 1 Response builder
-     */
-    public SAMLObjectBuilder<Response> getResponseBuilder() {
-        return responseBuilder;
-    }
-
-    /**
-     * Convenience method for getting the SAML 1 Assertion builder.
-     * 
-     * @return SAML 1 Assertion builder
-     */
-    public SAMLObjectBuilder<Assertion> getAssertionBuilder() {
-        return assertionBuilder;
-    }
-
-    /**
-     * Convenience method for getting the SAML 1 Conditions builder.
-     * 
-     * @return SAML 1 Conditions builder
-     */
-    public SAMLObjectBuilder<Conditions> getConditionsBuilder() {
-        return conditionsBuilder;
-    }
-
-    /**
-     * Convenience method for getting the SAML 1 AudienceRestrictionCondition builder.
-     * 
-     * @return SAML 1 AudienceRestrictionCondition builder
-     */
-    public SAMLObjectBuilder<AudienceRestrictionCondition> getAudienceRestrictionConditionBuilder() {
-        return audienceRestrictionConditionBuilder;
-    }
-
-    /**
-     * Convenience method for getting the SAML 1 Audience builder.
-     * 
-     * @return SAML 1 Audience builder
-     */
-    public SAMLObjectBuilder<Audience> getAudienceBuilder() {
-        return audienceBuilder;
-    }
-
-    /**
-     * Convenience method for getting the SAML 1 NameIdentifier builder.
-     * 
-     * @return SAML 1 NameIdentifier builder
-     */
-    public SAMLObjectBuilder<NameIdentifier> getNameIdentifierBuilder() {
-        return nameIdBuilder;
+    /** {@inheritDoc} */
+    protected void populateRequestContext(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
+        BaseSAML1ProfileRequestContext saml1Request = (BaseSAML1ProfileRequestContext) requestContext;
+        try {
+            super.populateRequestContext(requestContext);
+        } catch (ProfileException e) {
+            if (saml1Request.getFailureStatus() == null) {
+                saml1Request.setFailureStatus(buildStatus(StatusCode.REQUESTER, null, e.getMessage()));
+            }
+            throw e;
+        }
     }
 
     /**
-     * Convenience method for getting the SAML 1 SubjectConfirmation builder.
+     * Populates the request context with the information about the user.
      * 
-     * @return SAML 1 SubjectConfirmation builder
-     */
-    public SAMLObjectBuilder<SubjectConfirmation> getSubjectConfirmationBuilder() {
-        return subjectConfirmationBuilder;
-    }
-
-    /**
-     * Convenience method for getting the SAML 1 ConfirmationMethod builder.
+     * This method requires the the following request context properties to be populated: inbound message transport,
+     * relying party ID
      * 
-     * @return SAML 1 ConfirmationMethod builder
-     */
-    public SAMLObjectBuilder<ConfirmationMethod> getConfirmationMethodBuilder() {
-        return confirmationMethodBuilder;
-    }
-
-    /**
-     * Convenience method for getting the SAML 1 Subject builder.
+     * This methods populates the following request context properties: user's session, user's principal name, and
+     * service authentication method
      * 
-     * @return SAML 1 Subject builder
+     * @param requestContext current request context
      */
-    public SAMLObjectBuilder<Subject> getSubjectBuilder() {
-        return subjectBuilder;
-    }
+    protected void populateUserInformation(BaseSAMLProfileRequestContext requestContext) {
+        Session userSession = getUserSession(requestContext.getInboundMessageTransport());
+        if (userSession == null) {
+            NameIdentifier subject = (NameIdentifier) requestContext.getSubjectNameIdentifier();
+            if (subject != null && subject.getNameIdentifier() != null) {
+                userSession = getUserSession(subject.getNameIdentifier());
+            }
+        }
 
-    /**
-     * Convenience method for getting the SAML 1 Status builder.
-     * 
-     * @return SAML 1 Status builder
-     */
-    public SAMLObjectBuilder<Status> getStatusBuilder() {
-        return statusBuilder;
+        if (userSession != null) {
+            requestContext.setUserSession(userSession);
+            requestContext.setPrincipalName(userSession.getPrincipalName());
+            requestContext.setPrincipalAuthenticationMethod(userSession.getServicesInformation().get(
+                    requestContext.getPeerEntityId()).getAuthenticationMethod().getAuthenticationMethod());
+        }
     }
 
     /**
-     * Convenience method for getting the SAML 1 StatusCode builder.
+     * Checks that the SAML major version for a request is 1.
      * 
-     * @return SAML 2 StatusCode builder
-     */
-    public SAMLObjectBuilder<StatusCode> getStatusCodeBuilder() {
-        return statusCodeBuilder;
-    }
-
-    /**
-     * Convenience method for getting the SAML 1 StatusMessage builder.
+     * @param requestContext current request context containing the SAML message
      * 
-     * @return SAML StatusMessage builder
+     * @throws ProfileException thrown if the major version of the SAML request is not 1
      */
-    public SAMLObjectBuilder<StatusMessage> getStatusMessageBuilder() {
-        return statusMessageBuilder;
+    protected void checkSamlVersion(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
+        SAMLObject samlObject = requestContext.getInboundSAMLMessage();
+
+        if (samlObject instanceof RequestAbstractType) {
+            RequestAbstractType request = (RequestAbstractType) samlObject;
+            if (request.getMajorVersion() < 1) {
+                requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER, StatusCode.REQUEST_VERSION_TOO_LOW,
+                        null));
+                throw new ProfileException("SAML request major version too low");
+            } else if (request.getMajorVersion() > 1) {
+                requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER, StatusCode.REQUEST_VERSION_TOO_HIGH,
+                        null));
+                throw new ProfileException("SAML request major version too low");
+            }
+        }
     }
 
     /**
@@ -273,19 +226,19 @@ public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHan
      * 
      * @throws ProfileException thrown if there is a problem creating the SAML response
      */
-    protected Response buildResponse(SAML1ProfileRequestContext requestContext, List<Statement> statements)
+    protected Response buildResponse(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext, List<Statement> statements)
             throws ProfileException {
 
         DateTime issueInstant = new DateTime();
 
         // create the assertion and add the attribute statement
         Assertion assertion = buildAssertion(requestContext, issueInstant);
-        if (statements != null) {
+        if (statements != null && !statements.isEmpty()) {
             assertion.getStatements().addAll(statements);
         }
 
         // create the SAML response and add the assertion
-        Response samlResponse = getResponseBuilder().buildObject();
+        Response samlResponse = responseBuilder.buildObject();
         samlResponse.setIssueInstant(issueInstant);
         populateStatusResponse(requestContext, samlResponse);
 
@@ -308,12 +261,12 @@ public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHan
      * 
      * @return the built assertion
      */
-    protected Assertion buildAssertion(SAML1ProfileRequestContext requestContext, DateTime issueInstant) {
-        Assertion assertion = getAssertionBuilder().buildObject();
+    protected Assertion buildAssertion(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
+        Assertion assertion = assertionBuilder.buildObject();
         assertion.setID(getIdGenerator().generateIdentifier());
         assertion.setIssueInstant(issueInstant);
         assertion.setVersion(SAMLVersion.VERSION_11);
-        assertion.setIssuer(requestContext.getAssertingPartyId());
+        assertion.setIssuer(requestContext.getLocalEntityId());
 
         Conditions conditions = buildConditions(requestContext, issueInstant);
         assertion.setConditions(conditions);
@@ -330,10 +283,10 @@ public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHan
      * 
      * @return constructed conditions
      */
-    protected Conditions buildConditions(SAML1ProfileRequestContext requestContext, DateTime issueInstant) {
+    protected Conditions buildConditions(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext, DateTime issueInstant) {
         AbstractSAML1ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
 
-        Conditions conditions = getConditionsBuilder().buildObject();
+        Conditions conditions = conditionsBuilder.buildObject();
         conditions.setNotBefore(issueInstant);
         conditions.setNotOnOrAfter(issueInstant.plus(profileConfig.getAssertionLifetime()));
 
@@ -342,9 +295,9 @@ public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHan
         // add audience restrictions
         audiences = profileConfig.getAssertionAudiences();
         if (audiences != null && audiences.size() > 0) {
-            AudienceRestrictionCondition audienceRestriction = getAudienceRestrictionConditionBuilder().buildObject();
+            AudienceRestrictionCondition audienceRestriction = audienceRestrictionConditionBuilder.buildObject();
             for (String audienceUri : audiences) {
-                Audience audience = getAudienceBuilder().buildObject();
+                Audience audience = audienceBuilder.buildObject();
                 audience.setUri(audienceUri);
                 audienceRestriction.getAudiences().add(audience);
             }
@@ -365,18 +318,18 @@ public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHan
      * @throws ProfileException thrown if a NameID can not be created either because there was a problem encoding the
      *             name ID attribute or because there are no supported name formats
      */
-    protected Subject buildSubject(SAML1ProfileRequestContext requestContext, String confirmationMethod)
+    protected Subject buildSubject(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext, String confirmationMethod)
             throws ProfileException {
         NameIdentifier nameID = buildNameId(requestContext);
-        requestContext.setSubjectNameID(nameID);
+        requestContext.setSubjectNameIdentifier(nameID);
 
-        ConfirmationMethod method = getConfirmationMethodBuilder().buildObject();
+        ConfirmationMethod method = confirmationMethodBuilder.buildObject();
         method.setConfirmationMethod(confirmationMethod);
 
-        SubjectConfirmation subjectConfirmation = getSubjectConfirmationBuilder().buildObject();
+        SubjectConfirmation subjectConfirmation = subjectConfirmationBuilder.buildObject();
         subjectConfirmation.getConfirmationMethods().add(method);
 
-        Subject subject = getSubjectBuilder().buildObject();
+        Subject subject = subjectBuilder.buildObject();
         subject.setNameIdentifier(nameID);
         subject.setSubjectConfirmation(subjectConfirmation);
 
@@ -387,7 +340,7 @@ public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHan
      * Builds a NameIdentifier appropriate for this request. NameIdentifier are built by inspecting the SAML request and
      * metadata, picking a name format that was requested by the relying party or is mutually supported by both the
      * relying party and asserting party as described in their metadata entries. Once a set of supported name formats is
-     * determined the principals attributes are inspected for an attribtue supported an attribute encoder whose category
+     * determined the principals attributes are inspected for an attribute supported an attribute encoder whose category
      * is one of the supported name formats.
      * 
      * @param requestContext current request context
@@ -397,43 +350,56 @@ public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHan
      * @throws ProfileException thrown if a NameIdentifier can not be created either because there was a problem
      *             encoding the name ID attribute or because there are no supported name formats
      */
-    protected NameIdentifier buildNameId(SAML1ProfileRequestContext requestContext) throws ProfileException {
-        if (log.isDebugEnabled()) {
-            log.debug("Building assertion NameIdentifier to relying party " + requestContext.getRelyingPartyId()
-                    + " for principal " + requestContext.getPrincipalName());
+    protected NameIdentifier buildNameId(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext)
+            throws ProfileException {
+        log.debug("Building assertion NameIdentifier to relying party {} for principal {}", requestContext
+                .getInboundMessageIssuer(), requestContext.getPrincipalName());
+        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, null,
+                    "Unable to construct NameIdentifier"));
+            throw new ProfileException("No principal attributes support NameIdentifier construction");
         }
-        Map<String, BaseAttribute> principalAttributes = requestContext.getPrincipalAttributes();
-        List<String> supportedNameFormats = getNameFormats(requestContext);
 
-        if (log.isDebugEnabled()) {
-            log.debug("Supported name formats: " + supportedNameFormats);
+        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, null,
+                    "Unable to construct NameIdentifier"));
+            throw new ProfileException("No principal attributes support NameIdentifier construction");
         }
 
-        if (principalAttributes != null && supportedNameFormats != null) {
-            try {
-                AttributeEncoder<NameIdentifier> nameIdEncoder = null;
-                for (BaseAttribute attribute : principalAttributes.values()) {
-                    for (String nameFormat : supportedNameFormats) {
-                        nameIdEncoder = attribute.getEncoderByCategory(nameFormat);
-                        if (nameIdEncoder != null) {
-                            if (log.isDebugEnabled()) {
-                                log.debug("Using attribute " + attribute.getId() + " suppoting name format "
-                                        + nameFormat + " to create the NameIdentifier for principal "
-                                        + requestContext.getPrincipalName());
-                            }
+        log.debug("Supported name formats: {}", supportedNameFormats);
+        try {
+            SAML1NameIdentifierEncoder nameIdEncoder;
+
+            for (BaseAttribute<?> attribute : principalAttributes.values()) {
+                for (AttributeEncoder encoder : attribute.getEncoders()) {
+                    if (encoder instanceof SAML1NameIdentifierEncoder) {
+                        nameIdEncoder = (SAML1NameIdentifierEncoder) encoder;
+                        if (supportedNameFormats.contains(nameIdEncoder.getNameFormat())) {
+                            log
+                                    .debug(
+                                            "Using attribute {} suppoting name format {} to create the NameIdentifier for principal",
+                                            attribute.getId(), nameIdEncoder.getNameFormat());
                             return nameIdEncoder.encode(attribute);
                         }
                     }
                 }
-            } catch (AttributeEncodingException e) {
-                requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
-                        "Unable to construct NameIdentifier"));
-                throw new ProfileException("Unable to encode NameIdentifier attribute", e);
             }
+            requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
+                    "Unable to construct NameIdentifier"));
+            log.error("No principal attribute supports an encoding into a supported name ID format.");
+            throw new ProfileException("No principal attribute supports an encoding into a supported name ID format.");
+        } catch (AttributeEncodingException e) {
+            log.error("Unable to construct NameIdentifier", e);
+            requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
+                    "Unable to construct NameIdentifier"));
+            throw new ProfileException("Unable to encode NameIdentifier attribute", e);
         }
 
-        requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Unable to construct NameID"));
-        throw new ProfileException("No principal attributes support NameIdentifier construction");
     }
 
     /**
@@ -443,34 +409,33 @@ public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHan
      * 
      * @return list of formats that may be used with the relying party
      * 
-     * @throws ProfileException thrown if there is a problem determing the NameIdentifier format to use
+     * @throws ProfileException thrown if there is a problem determining the NameIdentifier format to use
      */
-    protected List<String> getNameFormats(SAML1ProfileRequestContext requestContext) throws ProfileException {
+    protected List<String> getNameFormats(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext)
+            throws ProfileException {
         ArrayList<String> nameFormats = new ArrayList<String>();
 
-        try {
-            RoleDescriptor assertingPartyRole = getMetadataProvider().getRole(requestContext.getAssertingPartyId(),
-                    requestContext.getAssertingPartyRole(), SAMLConstants.SAML1P_NS);
-            List<String> assertingPartySupportedFormats = getEntitySupportedFormats(assertingPartyRole);
-
-            if (nameFormats.isEmpty()) {
-                RoleDescriptor relyingPartyRole = getMetadataProvider().getRole(requestContext.getRelyingPartyId(),
-                        requestContext.getRelyingPartyRole(), SAMLConstants.SAML1P_NS);
-                List<String> relyingPartySupportedFormats = getEntitySupportedFormats(relyingPartyRole);
-
-                assertingPartySupportedFormats.retainAll(relyingPartySupportedFormats);
-                nameFormats.addAll(assertingPartySupportedFormats);
-            }
-            if (nameFormats.isEmpty()) {
-                nameFormats.add("urn:oasis:names:tc:SAML:1.0:nameid-format:unspecified");
+        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);
+                    }
+                }
             }
+        }
 
-            return nameFormats;
-
-        } catch (MetadataProviderException e) {
-            requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Unable to lookup metadata"));
-            throw new ProfileException("Unable to determine lookup entity metadata", e);
+        if (nameFormats.isEmpty()) {
+            nameFormats.add("urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified");
         }
+
+        return nameFormats;
     }
 
     /**
@@ -510,8 +475,8 @@ public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHan
      * 
      * @return the constructed error response
      */
-    protected Response buildErrorResponse(SAML1ProfileRequestContext requestContext) {
-        Response samlResponse = getResponseBuilder().buildObject();
+    protected Response buildErrorResponse(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext) {
+        Response samlResponse = responseBuilder.buildObject();
         samlResponse.setIssueInstant(new DateTime());
         populateStatusResponse(requestContext, samlResponse);
 
@@ -526,10 +491,11 @@ public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHan
      * @param requestContext current request context
      * @param response the response to populate
      */
-    protected void populateStatusResponse(SAML1ProfileRequestContext requestContext, ResponseAbstractType response) {
+    protected void populateStatusResponse(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext,
+            ResponseAbstractType response) {
         response.setID(getIdGenerator().generateIdentifier());
 
-        SAMLObject samlMessage = requestContext.getSamlRequest();
+        SAMLObject samlMessage = requestContext.getInboundSAMLMessage();
         if (samlMessage != null && samlMessage instanceof RequestAbstractType) {
             response.setInResponseTo(((RequestAbstractType) samlMessage).getID());
         }
@@ -545,21 +511,21 @@ public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHan
      * 
      * @return a Status object.
      */
-    protected Status buildStatus(String topLevelCode, String secondLevelCode, String failureMessage) {
-        Status status = getStatusBuilder().buildObject();
+    protected Status buildStatus(QName topLevelCode, QName secondLevelCode, String failureMessage) {
+        Status status = statusBuilder.buildObject();
 
-        StatusCode statusCode = getStatusCodeBuilder().buildObject();
-        statusCode.setValue(DatatypeHelper.safeTrimOrNullString(topLevelCode));
+        StatusCode statusCode = statusCodeBuilder.buildObject();
+        statusCode.setValue(topLevelCode);
         status.setStatusCode(statusCode);
 
         if (secondLevelCode != null) {
-            StatusCode secondLevelStatusCode = getStatusCodeBuilder().buildObject();
-            secondLevelStatusCode.setValue(DatatypeHelper.safeTrimOrNullString(secondLevelCode));
+            StatusCode secondLevelStatusCode = statusCodeBuilder.buildObject();
+            secondLevelStatusCode.setValue(secondLevelCode);
             statusCode.setStatusCode(secondLevelStatusCode);
         }
 
         if (failureMessage != null) {
-            StatusMessage msg = getStatusMessageBuilder().buildObject();
+            StatusMessage msg = statusMessageBuilder.buildObject();
             msg.setMessage(failureMessage);
             status.setStatusMessage(msg);
         }
@@ -568,6 +534,32 @@ public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHan
     }
 
     /**
+     * Resolved the attributes for the principal.
+     * 
+     * @param requestContext current request context
+     * 
+     * @throws ProfileException thrown if attributes can not be resolved
+     */
+    protected void resolveAttributes(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
+        AbstractSAML1ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
+        SAML1AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
+
+        try {
+            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 from relying party "
+                    + requestContext.getInboundMessageIssuer(), e);
+            requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error resolving attributes"));
+            throw new ProfileException("Error resolving attributes for SAML request from relying party "
+                    + requestContext.getInboundMessageIssuer(), e);
+        }
+    }
+
+    /**
      * Executes a query for attributes and builds a SAML attribute statement from the results.
      * 
      * @param requestContext current request context
@@ -577,45 +569,34 @@ public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHan
      * 
      * @throws ProfileException thrown if there is a problem making the query
      */
-    protected AttributeStatement buildAttributeStatement(SAML1ProfileRequestContext requestContext, String subjectConfMethod)
-            throws ProfileException {
-
-        if (log.isDebugEnabled()) {
-            log.debug("Creating attribute statement in response to SAML request from relying party "
-                    + requestContext.getRelyingPartyId());
-        }
+    protected AttributeStatement buildAttributeStatement(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext,
+            String subjectConfMethod) throws ProfileException {
 
+        log.debug("Creating attribute statement in response to SAML request from relying party {}", requestContext
+                .getInboundMessageIssuer());
         AbstractSAML1ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
         SAML1AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
 
         try {
-            if (log.isDebugEnabled()) {
-                log.debug("Resolving attributes for principal " + requestContext.getPrincipalName()
-                        + " of SAML request from relying party " + requestContext.getRelyingPartyId());
-            }
-            Map<String, BaseAttribute> principalAttributes = attributeAuthority
-                    .getAttributes(buildAttributeRequestContext(requestContext));
-
-            requestContext.setPrincipalAttributes(principalAttributes);
-
             AttributeStatement statment;
-            if (requestContext.getSamlRequest() instanceof AttributeQuery) {
-                statment = attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext.getSamlRequest(),
-                        principalAttributes.values());
+            if (requestContext.getInboundSAMLMessage() instanceof AttributeQuery) {
+                statment = attributeAuthority.buildAttributeStatement((AttributeQuery) requestContext
+                        .getInboundSAMLMessage(), requestContext.getAttributes().values());
             } else {
-                statment = attributeAuthority.buildAttributeStatement(null, principalAttributes.values());
+                statment = attributeAuthority.buildAttributeStatement(null, requestContext.getAttributes().values());
             }
 
-            Subject statementSubject = buildSubject(requestContext, subjectConfMethod);
-            statment.setSubject(statementSubject);
+            if (statment != null) {
+                Subject statementSubject = buildSubject(requestContext, subjectConfMethod);
+                statment.setSubject(statementSubject);
+            }
 
             return statment;
         } catch (AttributeRequestException e) {
-            log.error("Error resolving attributes for SAML request from relying party "
-                    + requestContext.getRelyingPartyId(), e);
+            log.error("Error encoding attributes for principal " + requestContext.getPrincipalName(), e);
             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error resolving attributes"));
-            throw new ProfileException("Error resolving attributes for SAML request from relying party "
-                    + requestContext.getRelyingPartyId(), e);
+            throw new ProfileException("Error encoding attributes for principal " + requestContext.getPrincipalName(),
+                    e);
         }
     }
 
@@ -626,70 +607,27 @@ public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHan
      * 
      * @throws ProfileException thrown if the principal name can not be resolved
      */
-    protected void resolvePrincipal(SAML1ProfileRequestContext requestContext) throws ProfileException {
+    protected void resolvePrincipal(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext) throws ProfileException {
         AbstractSAML1ProfileConfiguration profileConfiguration = requestContext.getProfileConfiguration();
         SAML1AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
 
-        if (log.isDebugEnabled()) {
-            log.debug("Resolving principal name for subject of SAML request from relying party "
-                    + requestContext.getRelyingPartyId());
-        }
+        log.debug("Resolving principal name for subject of SAML request from relying party {}", requestContext
+                .getInboundMessageIssuer());
 
         try {
-            String principal = attributeAuthority.getPrincipal(buildAttributeRequestContext(requestContext));
+            String principal = attributeAuthority.getPrincipal(requestContext);
             requestContext.setPrincipalName(principal);
         } catch (AttributeRequestException e) {
             log.error("Error resolving attributes for SAML request from relying party "
-                    + requestContext.getRelyingPartyId(), e);
+                    + requestContext.getInboundMessageIssuer(), e);
             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
                     "Error resolving principal"));
             throw new ProfileException("Error resolving attributes for SAML request from relying party "
-                    + requestContext.getRelyingPartyId(), e);
+                    + requestContext.getInboundMessageIssuer(), e);
         }
     }
 
     /**
-     * Creates an attribute query context from the current profile request context.
-     * 
-     * @param requestContext current profile request
-     * 
-     * @return created query context
-     */
-    protected ShibbolethSAMLAttributeRequestContext<NameIdentifier, AttributeQuery> buildAttributeRequestContext(
-            SAML1ProfileRequestContext requestContext) {
-
-        ShibbolethSAMLAttributeRequestContext<NameIdentifier, AttributeQuery> queryContext;
-
-        if (requestContext.getSamlRequest() instanceof AttributeQuery) {
-            queryContext = new ShibbolethSAMLAttributeRequestContext<NameIdentifier, AttributeQuery>(
-                    getMetadataProvider(), requestContext.getRelyingPartyConfiguration(),
-                    (AttributeQuery) requestContext.getSamlRequest());
-        } else {
-            queryContext = new ShibbolethSAMLAttributeRequestContext<NameIdentifier, AttributeQuery>(
-                    getMetadataProvider(), requestContext.getRelyingPartyConfiguration());
-        }
-
-        queryContext.setAttributeRequester(requestContext.getAssertingPartyId());
-        queryContext.setPrincipalName(requestContext.getPrincipalName());
-        queryContext.setProfileConfiguration(requestContext.getProfileConfiguration());
-        queryContext.setRequest(requestContext.getProfileRequest());
-
-        Session userSession = getSessionManager().getSession(getUserSessionId(requestContext.getProfileRequest()));
-        if (userSession != null) {
-            queryContext.setUserSession(userSession);
-            ServiceInformation serviceInfo = userSession.getServiceInformation(requestContext.getRelyingPartyId());
-            if (serviceInfo != null) {
-                String principalAuthenticationMethod = serviceInfo.getAuthenticationMethod().getAuthenticationMethod();
-
-                requestContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
-                queryContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
-            }
-        }
-
-        return queryContext;
-    }
-
-    /**
      * Signs the given assertion if either the current profile configuration or the relying party configuration contains
      * signing credentials.
      * 
@@ -699,49 +637,45 @@ public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHan
      * @throws ProfileException thrown if the metadata can not be located for the relying party or, if signing is
      *             required, if a signing credential is not configured
      */
-    protected void signAssertion(SAML1ProfileRequestContext requestContext, Assertion assertion)
+    protected void signAssertion(BaseSAML1ProfileRequestContext<?, ?, ?> requestContext, Assertion assertion)
             throws ProfileException {
-        if (log.isDebugEnabled()) {
-            log.debug("Determining if SAML assertion to relying party " + requestContext.getRelyingPartyId()
-                    + " should be signed");
-        }
+        log.debug("Determining if SAML assertion to relying party {} should be signed", requestContext
+                .getInboundMessageIssuer());
 
         boolean signAssertion = false;
 
-        RoleDescriptor relyingPartyRole;
+        RoleDescriptor relyingPartyRole = requestContext.getPeerEntityRoleMetadata();
+        SAMLMessageEncoder encoder = getMessageEncoders().get(requestContext.getPeerEntityEndpoint().getBinding());
+        AbstractSAML1ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
+
         try {
-            relyingPartyRole = getMetadataProvider().getRole(requestContext.getRelyingPartyId(),
-                    requestContext.getRelyingPartyRole(), SAMLConstants.SAML20P_NS);
-        } catch (MetadataProviderException e) {
-            throw new ProfileException("Unable to lookup entity metadata for relying party "
-                    + requestContext.getRelyingPartyId());
+            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", encoder.getBindingURI());
+            throw new ProfileException("Unable to determine if outbound message should be signed");
         }
-        AbstractSAML1ProfileConfiguration profileConfig = requestContext.getProfileConfiguration();
 
-        if (relyingPartyRole instanceof SPSSODescriptor) {
+        if (!signAssertion && relyingPartyRole instanceof SPSSODescriptor) {
             SPSSODescriptor ssoDescriptor = (SPSSODescriptor) relyingPartyRole;
             if (ssoDescriptor.getWantAssertionsSigned() != null) {
                 signAssertion = ssoDescriptor.getWantAssertionsSigned().booleanValue();
-                if (log.isDebugEnabled()) {
-                    log.debug("Entity metadata for relying party " + requestContext.getRelyingPartyId()
-                            + " 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.getRelyingPartyId());
-        }
+        log.debug("Determining signing credntial for assertion to relying party {}", requestContext
+                .getInboundMessageIssuer());
         Credential signatureCredential = profileConfig.getSigningCredential();
         if (signatureCredential == null) {
             signatureCredential = requestContext.getRelyingPartyConfiguration().getDefaultSigningCredential();
@@ -753,160 +687,30 @@ public abstract class AbstractSAML1ProfileHandler extends AbstractSAMLProfileHan
                     + " or it's SAML2 attribute query profile configuration");
         }
 
-        if (log.isDebugEnabled()) {
-            log.debug("Signing assertion to relying party " + requestContext.getRelyingPartyId());
-        }
-        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);
-        assertion.setSignature(signature);
-
-        Signer.signObject(signature);
-    }
-
-    /**
-     * Writes an aduit log entry indicating the successful response to the attribute request.
-     * 
-     * @param context current request context
-     */
-    protected void writeAuditLogEntry(SAML1ProfileRequestContext context) {
-        AuditLogEntry auditLogEntry = new AuditLogEntry();
-        auditLogEntry.setMessageProfile(getProfileId());
-        auditLogEntry.setPrincipalAuthenticationMethod(context.getPrincipalAuthenticationMethod());
-        auditLogEntry.setPrincipalName(context.getPrincipalName());
-        auditLogEntry.setAssertingPartyId(context.getAssertingPartyId());
-        auditLogEntry.setRelyingPartyId(context.getRelyingPartyId());
-        auditLogEntry.setRequestBinding(context.getMessageDecoder().getBindingURI());
-        auditLogEntry.setRequestId(null);
-        auditLogEntry.setResponseBinding(context.getMessageEncoder().getBindingURI());
-        auditLogEntry.setResponseId(context.getSamlResponse().getID());
-        getAduitLog().log(Level.CRITICAL, auditLogEntry);
-    }
-
-    /**
-     * Contextual object used to accumlate information as profile requests are being processed.
-     * 
-     * @param <RequestType> type of SAML 1 request
-     * @param <ResponseType> type of SAML 1 response
-     * @param <ProfileConfigurationType> configuration type for this profile
-     */
-    protected class SAML1ProfileRequestContext<RequestType extends SAMLObject, ResponseType extends ResponseAbstractType, ProfileConfigurationType extends AbstractSAML1ProfileConfiguration>
-            extends SAMLProfileRequestContext {
-
-        /** SAML request message. */
-        private RequestType samlRequest;
-
-        /** SAML response message. */
-        private ResponseType samlResponse;
-
-        /** Request profile configuration. */
-        private ProfileConfigurationType profileConfiguration;
-
-        /** The NameIdentifier of the subject of this request. */
-        private NameIdentifier subjectNameIdentifier;
-
-        /** The request failure status. */
-        private Status failureStatus;
-
-        /**
-         * Constructor.
-         * 
-         * @param request current profile request
-         * @param response current profile response
-         */
-        public SAML1ProfileRequestContext(ProfileRequest<ServletRequest> request,
-                ProfileResponse<ServletResponse> response) {
-            super(request, response);
-        }
-
-        /**
-         * Gets the NameIdentifier of the subject of this request.
-         * 
-         * @return NameIdentifier of the subject of this request
-         */
-        public NameIdentifier getSubjectNameID() {
-            return subjectNameIdentifier;
-        }
-
-        /**
-         * Sets the NameIdentifier of the subject of this request.
-         * 
-         * @param id NameIdentifier of the subject of this request
-         */
-        public void setSubjectNameID(NameIdentifier id) {
-            subjectNameIdentifier = id;
-        }
 
-        /**
-         * Gets the profile configuration for this request.
-         * 
-         * @return profile configuration for this request
-         */
-        public ProfileConfigurationType getProfileConfiguration() {
-            return profileConfiguration;
-        }
-
-        /**
-         * Sets the profile configuration for this request.
-         * 
-         * @param configuration profile configuration for this request
-         */
-        public void setProfileConfiguration(ProfileConfigurationType configuration) {
-            profileConfiguration = configuration;
-        }
-
-        /**
-         * Gets the SAML request message.
-         * 
-         * @return SAML request message
-         */
-        public RequestType getSamlRequest() {
-            return samlRequest;
-        }
-
-        /**
-         * Sets the SAML request message.
-         * 
-         * @param request SAML request message
-         */
-        public void setSamlRequest(RequestType request) {
-            samlRequest = request;
-        }
-
-        /**
-         * Gets the SAML response message.
-         * 
-         * @return SAML response message
-         */
-        public ResponseType getSamlResponse() {
-            return samlResponse;
-        }
-
-        /**
-         * Sets the SAML response message.
-         * 
-         * @param response SAML response message
-         */
-        public void setSamlResponse(ResponseType response) {
-            samlResponse = response;
+        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);
         }
 
-        /**
-         * Gets the status reflecting a request failure.
-         * 
-         * @return status reflecting a request failure
-         */
-        public Status getFailureStatus() {
-            return failureStatus;
-        }
+        assertion.setSignature(signature);
 
-        /**
-         * Sets the status reflecting a request failure.
-         * 
-         * @param status status reflecting a request failure
-         */
-        public void setFailureStatus(Status status) {
-            failureStatus = status;
+        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);
         }
     }
 }
\ No newline at end of file