Lots of code cleanup
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml1 / ArtifactResolution.java
index 99d5f6f..b2d7ebb 100644 (file)
@@ -18,8 +18,8 @@ package edu.internet2.middleware.shibboleth.idp.profile.saml1;
 
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.List;
 
-import org.apache.log4j.Logger;
 import org.joda.time.DateTime;
 import org.opensaml.common.SAMLObjectBuilder;
 import org.opensaml.common.binding.BasicEndpointSelector;
@@ -28,8 +28,8 @@ import org.opensaml.common.binding.artifact.SAMLArtifactMap.SAMLArtifactMapEntry
 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
 import org.opensaml.common.xml.SAMLConstants;
 import org.opensaml.saml1.binding.SAML1ArtifactMessageContext;
-import org.opensaml.saml1.binding.artifact.AbstractSAML1Artifact;
 import org.opensaml.saml1.core.Assertion;
+import org.opensaml.saml1.core.AssertionArtifact;
 import org.opensaml.saml1.core.NameIdentifier;
 import org.opensaml.saml1.core.Request;
 import org.opensaml.saml1.core.Response;
@@ -38,16 +38,18 @@ import org.opensaml.saml1.core.StatusCode;
 import org.opensaml.saml2.metadata.AssertionConsumerService;
 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
 import org.opensaml.saml2.metadata.Endpoint;
+import org.opensaml.saml2.metadata.EntityDescriptor;
 import org.opensaml.saml2.metadata.SPSSODescriptor;
 import org.opensaml.saml2.metadata.provider.MetadataProvider;
-import org.opensaml.saml2.metadata.provider.MetadataProviderException;
 import org.opensaml.ws.message.decoder.MessageDecodingException;
-import org.opensaml.ws.security.SecurityPolicyException;
 import org.opensaml.ws.transport.http.HTTPInTransport;
 import org.opensaml.ws.transport.http.HTTPOutTransport;
+import org.opensaml.xml.security.SecurityException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
-import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
+import edu.internet2.middleware.shibboleth.common.profile.provider.BaseSAMLProfileRequestContext;
 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.ArtifactResolutionConfiguration;
 
 /**
@@ -56,11 +58,14 @@ import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.Ar
 public class ArtifactResolution extends AbstractSAML1ProfileHandler {
 
     /** Class logger. */
-    private final Logger log = Logger.getLogger(ArtifactResolution.class);
+    private final Logger log = LoggerFactory.getLogger(ArtifactResolution.class);
 
     /** Builder of Response objects. */
     private SAMLObjectBuilder<Response> responseBuilder;
 
+    /** Builder of assertion consumer service endpoints. */
+    private SAMLObjectBuilder<AssertionConsumerService> acsEndpointBuilder;
+
     /** Map artifacts to SAML messages. */
     private SAMLArtifactMap artifactMap;
 
@@ -75,11 +80,13 @@ public class ArtifactResolution extends AbstractSAML1ProfileHandler {
         artifactMap = map;
 
         responseBuilder = (SAMLObjectBuilder<Response>) getBuilderFactory().getBuilder(Response.DEFAULT_ELEMENT_NAME);
+        acsEndpointBuilder = (SAMLObjectBuilder<AssertionConsumerService>) getBuilderFactory().getBuilder(
+                AssertionConsumerService.DEFAULT_ELEMENT_NAME);
     }
 
     /** {@inheritDoc} */
     public String getProfileId() {
-        return "urn:mace:shibboleth:2.0:idp:profiles:saml1:request:artifact";
+        return ArtifactResolutionConfiguration.PROFILE_ID;
     }
 
     /** {@inheritDoc} */
@@ -89,7 +96,7 @@ public class ArtifactResolution extends AbstractSAML1ProfileHandler {
         ArtifactResolutionRequestContext requestContext = decodeRequest(inTransport, outTransport);
 
         try {
-            if (requestContext.getRelyingPartyConfiguration() == null) {
+            if (requestContext.getProfileConfiguration() == null) {
                 log.error("SAML 1 Artifact resolution profile is not configured for relying party "
                         + requestContext.getInboundMessageIssuer());
                 requestContext.setFailureStatus(buildStatus(StatusCode.SUCCESS, StatusCode.REQUEST_DENIED,
@@ -101,6 +108,8 @@ public class ArtifactResolution extends AbstractSAML1ProfileHandler {
 
             checkSamlVersion(requestContext);
 
+            derferenceArtifacts(requestContext);
+
             // create the SAML response
             samlResponse = buildArtifactResponse(requestContext);
         } catch (ProfileException e) {
@@ -127,17 +136,16 @@ public class ArtifactResolution extends AbstractSAML1ProfileHandler {
      */
     protected ArtifactResolutionRequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
             throws ProfileException {
-        if (log.isDebugEnabled()) {
-            log.debug("Decoding incomming request");
-        }
-
-        MetadataProvider metadataProvider = getMetadataProvider();
+        log.debug("Decoding message with decoder binding {}", getInboundBinding());
 
         ArtifactResolutionRequestContext requestContext = new ArtifactResolutionRequestContext();
+
+        MetadataProvider metadataProvider = getMetadataProvider();
         requestContext.setMetadataProvider(metadataProvider);
 
         requestContext.setInboundMessageTransport(inTransport);
         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML11P_NS);
+        requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
 
         requestContext.setOutboundMessageTransport(outTransport);
@@ -147,51 +155,54 @@ public class ArtifactResolution extends AbstractSAML1ProfileHandler {
             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
             requestContext.setMessageDecoder(decoder);
             decoder.decode(requestContext);
-            if (log.isDebugEnabled()) {
-                log.debug("Decoded request");
-            }
+            log.debug("Decoded request");
             return requestContext;
         } catch (MessageDecodingException e) {
             log.error("Error decoding artifact resolve message", e);
             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error decoding message"));
             throw new ProfileException("Error decoding artifact resolve message");
-        } catch (SecurityPolicyException e) {
-            log.error("Message did not meet security policy requirements", e);
+        } catch (SecurityException e) {
+            log.error("Message did not meet security requirements", e);
             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
-                    "Message did not meet security policy requirements"));
-            throw new ProfileException("Message did not meet security policy requirements", e);
+                    "Message did not meet security requirements"));
+            throw new ProfileException("Message did not meet security requirements", e);
         } finally {
             // Set as much information as can be retrieved from the decoded message
-            try {
-                String relyingPartyId = requestContext.getInboundMessageIssuer();
-                RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
-                requestContext.setRelyingPartyConfiguration(rpConfig);
-
-                String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
-                requestContext.setLocalEntityId(assertingPartyId);
-                requestContext.setLocalEntityMetadata(metadataProvider.getEntityDescriptor(assertingPartyId));
-                requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
-                requestContext.setLocalEntityRoleMetadata(requestContext.getLocalEntityMetadata()
-                        .getAttributeAuthorityDescriptor(SAMLConstants.SAML11P_NS));
-
-                ArtifactResolutionConfiguration profileConfig = (ArtifactResolutionConfiguration) rpConfig
-                        .getProfileConfiguration(ArtifactResolutionConfiguration.PROFILE_ID);
-                requestContext.setProfileConfiguration(profileConfig);
-                if (profileConfig.getSigningCredential() != null) {
-                    requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
-                } else if (rpConfig.getDefaultSigningCredential() != null) {
-                    requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
-                }
-
-            } catch (MetadataProviderException e) {
-                log.error("Unable to locate metadata for asserting or relying party");
-                requestContext
-                        .setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error locating party metadata"));
-                throw new ProfileException("Error locating party metadata");
-            }
+            populateRequestContext(requestContext);
+            populateProfileInformation(requestContext);
+        }
+    }
+
+    /** {@inheritDoc} */
+    protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
+            throws ProfileException {
+        super.populateRelyingPartyInformation(requestContext);
+
+        EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
+        if (relyingPartyMetadata != null) {
+            requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
+            requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML11P_NS));
+        }
+    }
+
+    /** {@inheritDoc} */
+    protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
+            throws ProfileException {
+        super.populateAssertingPartyInformation(requestContext);
+
+        EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
+        if (localEntityDescriptor != null) {
+            requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
+            requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
+                    .getAttributeAuthorityDescriptor(SAMLConstants.SAML11P_NS));
         }
     }
 
+    /** {@inheritDoc} */
+    protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
+        // nothing to do here
+    }
+
     /**
      * Selects the appropriate endpoint for the relying party and stores it in the request context.
      * 
@@ -199,49 +210,60 @@ public class ArtifactResolution extends AbstractSAML1ProfileHandler {
      * 
      * @return Endpoint selected from the information provided in the request context
      */
-    protected Endpoint selectEndpoint(ArtifactResolutionRequestContext requestContext) {
-        BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
-        endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
-        endpointSelector.setMetadataProvider(getMetadataProvider());
-        endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
-        endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
-        endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
-        endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
-        return endpointSelector.selectEndpoint();
+    protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
+        Endpoint endpoint;
+
+        if (getInboundBinding().equals(SAMLConstants.SAML1_SOAP11_BINDING_URI)) {
+            endpoint = acsEndpointBuilder.buildObject();
+            endpoint.setBinding(SAMLConstants.SAML1_SOAP11_BINDING_URI);
+        } else {
+            BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
+            endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
+            endpointSelector.setMetadataProvider(getMetadataProvider());
+            endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
+            endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
+            endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
+            endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
+            endpoint = endpointSelector.selectEndpoint();
+        }
+
+        return endpoint;
     }
 
     /**
-     * Derferences the provided artifacts and stores them in the request context.
+     * Derferences the artifacts within the incoming request and stores them in the request context.
      * 
      * @param requestContext current request context
+     * 
+     * @throws ProfileException thrown if the incoming request does not contain any {@link AssertionArtifact}s.
      */
-    protected void derferenceArtifacts(ArtifactResolutionRequestContext requestContext) {
-        Collection<AbstractSAML1Artifact> artifacts = requestContext.getArtifacts();
-        if (artifacts != null) {
-            ArrayList<Assertion> assertions = new ArrayList<Assertion>();
-            SAMLArtifactMapEntry artifactEntry;
-
-            for (AbstractSAML1Artifact artifact : artifacts) {
-                artifactEntry = artifactMap.get(artifact.getArtifactBytes());
-                if (artifactEntry == null || artifactEntry.isExpired()) {
-                    log.error("Unknown artifact.");
-                }
-
-                if (!artifactEntry.getIssuerId().equals(requestContext.getLocalEntityId())) {
-                    log.error("Artifact issuer mismatch.  Artifact issued by " + artifactEntry.getIssuerId()
-                            + " but IdP has entity ID of " + requestContext.getLocalEntityId());
-                }
-
-                if (!artifactEntry.getRelyingPartyId().equals(requestContext.getInboundMessageIssuer())) {
-                    log.error("Artifact requester mismatch.  Artifact was issued to "
-                            + artifactEntry.getRelyingPartyId() + " but was resolve request came from "
-                            + requestContext.getInboundMessageIssuer());
-                }
-                artifactMap.remove(artifact.getArtifactBytes());
-                assertions.add((Assertion) artifactEntry.getSamlMessage());
+    protected void derferenceArtifacts(ArtifactResolutionRequestContext requestContext) throws ProfileException {
+        Request request = requestContext.getInboundSAMLMessage();
+        List<AssertionArtifact> assertionArtifacts = request.getAssertionArtifacts();
+
+        if (assertionArtifacts == null || assertionArtifacts.size() == 0) {
+            log.error("No AssertionArtifacts available in request");
+            throw new ProfileException("No AssertionArtifacts available in request");
+        }
+
+        ArrayList<Assertion> assertions = new ArrayList<Assertion>();
+        SAMLArtifactMapEntry artifactEntry;
+        for (AssertionArtifact assertionArtifact : assertionArtifacts) {
+            artifactEntry = artifactMap.get(assertionArtifact.getAssertionArtifact());
+            if (artifactEntry == null || artifactEntry.isExpired()) {
+                log.error("Unknown artifact.");
             }
-            requestContext.setReferencedAssertions(assertions);
+
+            if (!artifactEntry.getIssuerId().equals(requestContext.getLocalEntityId())) {
+                log.error("Artifact issuer mismatch.  Artifact issued by " + artifactEntry.getIssuerId()
+                        + " but IdP has entity ID of " + requestContext.getLocalEntityId());
+            }
+
+            artifactMap.remove(assertionArtifact.getAssertionArtifact());
+            assertions.add((Assertion) artifactEntry.getSamlMessage());
         }
+
+        requestContext.setDereferencedAssertions(assertions);
     }
 
     /**
@@ -259,8 +281,8 @@ public class ArtifactResolution extends AbstractSAML1ProfileHandler {
         samlResponse.setIssueInstant(issueInstant);
         populateStatusResponse(requestContext, samlResponse);
 
-        if (requestContext.getReferencedAssertions() != null) {
-            samlResponse.getAssertions().addAll(requestContext.getReferencedAssertions());
+        if (requestContext.getDereferencedAssertions() != null) {
+            samlResponse.getAssertions().addAll(requestContext.getDereferencedAssertions());
         }
 
         Status status = buildStatus(StatusCode.SUCCESS, null, null);
@@ -269,33 +291,25 @@ public class ArtifactResolution extends AbstractSAML1ProfileHandler {
         return samlResponse;
     }
 
-    /** Represents the internal state of a SAML 1 Artiface resolver request while it's being processed by the IdP. */
+    /** Represents the internal state of a SAML 1 Artifact resolver request while it's being processed by the IdP. */
     public class ArtifactResolutionRequestContext extends
             BaseSAML1ProfileRequestContext<Request, Response, ArtifactResolutionConfiguration> implements
             SAML1ArtifactMessageContext<Request, Response, NameIdentifier> {
 
         /** Artifact to be resolved. */
-        private Collection<AbstractSAML1Artifact> artifacts;
+        private Collection<String> artifacts;
 
         /** Message referenced by the SAML artifact. */
         private Collection<Assertion> referencedAssertions;
 
-        /**
-         * Gets the artifacts to be resolved.
-         * 
-         * @return artifacts to be resolved
-         */
-        public Collection<AbstractSAML1Artifact> getArtifacts() {
+        /** {@inheritDoc} */
+        public Collection<String> getArtifacts() {
             return artifacts;
         }
 
-        /**
-         * Sets the artifacts to be resolved.
-         * 
-         * @param artifacts artifacts to be resolved
-         */
-        public void setArtifacts(Collection<AbstractSAML1Artifact> artifacts) {
-            this.artifacts = artifacts;
+        /** {@inheritDoc} */
+        public void setArtifacts(Collection<String> encodedArtifacts) {
+            this.artifacts = encodedArtifacts;
         }
 
         /**
@@ -303,7 +317,7 @@ public class ArtifactResolution extends AbstractSAML1ProfileHandler {
          * 
          * @return SAML assertions referenced by the artifact(s)
          */
-        public Collection<Assertion> getReferencedAssertions() {
+        public Collection<Assertion> getDereferencedAssertions() {
             return referencedAssertions;
         }
 
@@ -312,7 +326,7 @@ public class ArtifactResolution extends AbstractSAML1ProfileHandler {
          * 
          * @param assertions SAML assertions referenced by the artifact(s)
          */
-        public void setReferencedAssertions(Collection<Assertion> assertions) {
+        public void setDereferencedAssertions(Collection<Assertion> assertions) {
             referencedAssertions = assertions;
         }
     }