Set communication profile before decoding
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml2 / ArtifactResolution.java
index 1b1c378..d4e4e95 100644 (file)
@@ -16,9 +16,7 @@
 
 package edu.internet2.middleware.shibboleth.idp.profile.saml2;
 
-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.binding.BasicEndpointSelector;
@@ -27,8 +25,6 @@ import org.opensaml.common.binding.artifact.SAMLArtifactMap.SAMLArtifactMapEntry
 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
 import org.opensaml.common.xml.SAMLConstants;
 import org.opensaml.saml2.binding.SAML2ArtifactMessageContext;
-import org.opensaml.saml2.binding.artifact.AbstractSAML2Artifact;
-import org.opensaml.saml2.binding.artifact.SAML2ArtifactBuilderFactory;
 import org.opensaml.saml2.core.ArtifactResolve;
 import org.opensaml.saml2.core.ArtifactResponse;
 import org.opensaml.saml2.core.NameID;
@@ -37,17 +33,18 @@ import org.opensaml.saml2.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.util.Base64;
+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.saml2.ArtifactResolutionConfiguration;
 
 /**
@@ -56,7 +53,7 @@ import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.Ar
 public class ArtifactResolution extends AbstractSAML2ProfileHandler {
 
     /** Class logger. */
-    private final Logger log = Logger.getLogger(ArtifactResolution.class);
+    private final Logger log = LoggerFactory.getLogger(ArtifactResolution.class);
 
     /** Map artifacts to SAML messages. */
     private SAMLArtifactMap artifactMap;
@@ -64,16 +61,28 @@ public class ArtifactResolution extends AbstractSAML2ProfileHandler {
     /** Artifact response object builder. */
     private SAMLObjectBuilder<ArtifactResponse> responseBuilder;
 
-    /** Constructor. */
-    public ArtifactResolution() {
+    /** Builder of assertion consumer service endpoints. */
+    private SAMLObjectBuilder<AssertionConsumerService> acsEndpointBuilder;
+
+    /**
+     * Constructor.
+     * 
+     * @param map ArtifactMap used to lookup artifacts to be resolved.
+     */
+    public ArtifactResolution(SAMLArtifactMap map) {
         super();
+
+        artifactMap = map;
+
         responseBuilder = (SAMLObjectBuilder<ArtifactResponse>) getBuilderFactory().getBuilder(
                 ArtifactResponse.DEFAULT_ELEMENT_NAME);
+        acsEndpointBuilder = (SAMLObjectBuilder<AssertionConsumerService>) getBuilderFactory().getBuilder(
+                AssertionConsumerService.DEFAULT_ELEMENT_NAME);
     }
 
     /** {@inheritDoc} */
     public String getProfileId() {
-        return "urn:mace:shibboleth:2.0:idp:profiles:saml2:request:artifact";
+        return ArtifactResolutionConfiguration.PROFILE_ID;
     }
 
     /** {@inheritDoc} */
@@ -83,19 +92,19 @@ public class ArtifactResolution extends AbstractSAML2ProfileHandler {
         ArtifactResolutionRequestContext requestContext = decodeRequest(inTransport, outTransport);
 
         try {
-            if (requestContext.getRelyingPartyConfiguration() == null) {
+            if (requestContext.getProfileConfiguration() == null) {
                 log.error("SAML 2 Artifact Resolve profile is not configured for relying party "
-                        + requestContext.getPeerEntityId());
+                        + requestContext.getInboundMessageIssuer());
                 requestContext.setFailureStatus(buildStatus(StatusCode.SUCCESS_URI, StatusCode.REQUEST_DENIED_URI,
                         "SAML 2 Artifact Resolve profile is not configured for relying party "
-                                + requestContext.getPeerEntityId()));
+                                + requestContext.getInboundMessageIssuer()));
                 throw new ProfileException("SAML 2 Artifact Resolve profile is not configured for relying party "
-                        + requestContext.getPeerEntityId());
+                        + requestContext.getInboundMessageIssuer());
             }
 
             checkSamlVersion(requestContext);
 
-            SAMLArtifactMapEntry artifactEntry = artifactMap.peek(requestContext.getArtifact().getArtifactBytes());
+            SAMLArtifactMapEntry artifactEntry = artifactMap.get(requestContext.getArtifact());
             if (artifactEntry == null || artifactEntry.isExpired()) {
                 log.error("Unknown artifact.");
                 requestContext.setFailureStatus(buildStatus(StatusCode.SUCCESS_URI, StatusCode.REQUEST_DENIED_URI,
@@ -109,17 +118,15 @@ public class ArtifactResolution extends AbstractSAML2ProfileHandler {
                         "Artifact issuer mismatch."));
             }
 
-            if (!artifactEntry.getRelyingPartyId().equals(requestContext.getPeerEntityId())) {
+            if (!artifactEntry.getRelyingPartyId().equals(requestContext.getInboundMessageIssuer())) {
                 log.error("Artifact requester mismatch.  Artifact was issued to " + artifactEntry.getRelyingPartyId()
-                        + " but was resolve request came from " + requestContext.getPeerEntityId());
+                        + " but was resolve request came from " + requestContext.getInboundMessageIssuer());
                 requestContext.setFailureStatus(buildStatus(StatusCode.SUCCESS_URI, StatusCode.REQUEST_DENIED_URI,
                         "Artifact requester mismatch."));
             }
-            artifactMap.get(requestContext.getArtifact().getArtifactBytes());
-            SAMLObject referencedMessage = artifactEntry.getSamlMessage();
-            requestContext.setReferencedMessage(referencedMessage);
 
             // create the SAML response
+            requestContext.setReferencedMessage(artifactEntry.getSamlMessage());
             samlResponse = buildArtifactResponse(requestContext);
         } catch (ProfileException e) {
             samlResponse = buildArtifactErrorResponse(requestContext);
@@ -145,92 +152,108 @@ public class ArtifactResolution extends AbstractSAML2ProfileHandler {
      */
     protected ArtifactResolutionRequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
             throws ProfileException {
-        if (log.isDebugEnabled()) {
-            log.debug("Decoding incomming request");
-        }
+        log.debug("Decoding message with decoder binding {}", getInboundBinding());
+
+        ArtifactResolutionRequestContext requestContext = new ArtifactResolutionRequestContext();
+        requestContext.setCommunicationProfileId(getProfileId());
 
         MetadataProvider metadataProvider = getMetadataProvider();
+        requestContext.setMetadataProvider(metadataProvider);
 
-        ArtifactResolutionRequestContext requestContext = new ArtifactResolutionRequestContext();
         requestContext.setInboundMessageTransport(inTransport);
         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
+        requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
+        requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
+
         requestContext.setOutboundMessageTransport(outTransport);
         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
-        requestContext.setMetadataProvider(metadataProvider);
 
         try {
             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_URI, 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_URI, StatusCode.REQUEST_DENIED_URI,
-                    "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 {
-                ArtifactResolve artResolve = requestContext.getInboundSAMLMessage();
-                requestContext.setInboundSAMLMessageId(artResolve.getID());
-                requestContext.setInboundSAMLMessageIssueInstant(artResolve.getIssueInstant());
-
-                String relyingPartyId = requestContext.getPeerEntityId();
-                requestContext.setPeerEntityMetadata(metadataProvider.getEntityDescriptor(relyingPartyId));
-                requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
-                requestContext.setPeerEntityRoleMetadata(requestContext.getPeerEntityMetadata().getSPSSODescriptor(
-                        SAMLConstants.SAML20P_NS));
-                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.SAML20P_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_URI, null,
-                        "Error locating party metadata"));
-                throw new ProfileException("Error locating party metadata");
-            }
+            populateRequestContext(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.SAML20P_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.SAML20P_NS));
         }
     }
 
     /**
+     * Populates the request context with information from the inbound SAML message.
+     * 
+     * This method requires the the following request context properties to be populated: inbound saml message
+     * 
+     * This methods populates the following request context properties: subject name identifier
+     * 
+     * @param requestContext current request context
+     * 
+     * @throws ProfileException thrown if the inbound SAML message or subject identifier is null
+     */
+    protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
+        ArtifactResolve samlMessage = (ArtifactResolve) requestContext.getInboundSAMLMessage();
+        ((ArtifactResolutionRequestContext) requestContext).setArtifact(samlMessage.getArtifact().getArtifact());
+    }
+
+    /**
      * Selects the appropriate endpoint for the relying party and stores it in the request context.
      * 
      * @param requestContext current request context
      * 
      * @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.SAML2_SOAP11_BINDING_URI)) {
+            endpoint = acsEndpointBuilder.buildObject();
+            endpoint.setBinding(SAMLConstants.SAML2_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;
     }
 
     /**
@@ -282,43 +305,27 @@ public class ArtifactResolution extends AbstractSAML2ProfileHandler {
             implements SAML2ArtifactMessageContext<ArtifactResolve, ArtifactResponse, NameID> {
 
         /** Artifact to be resolved. */
-        private AbstractSAML2Artifact artifact;
+        private String artifact;
 
         /** Message referenced by the SAML artifact. */
         private SAMLObject referencedMessage;
 
-        /**
-         * Gets the artifact to be resolved.
-         * 
-         * @return artifact to be resolved
-         */
-        public AbstractSAML2Artifact getArtifact() {
+        /** {@inheritDoc} */
+        public String getArtifact() {
             return artifact;
         }
 
-        /**
-         * Sets the artifact to be resolved.
-         * 
-         * @param artifact artifact to be resolved
-         */
-        public void setArtifact(AbstractSAML2Artifact artifact) {
-            this.artifact = artifact;
+        /** {@inheritDoc} */
+        public void setArtifact(String saml2Artifact) {
+            this.artifact = saml2Artifact;
         }
 
-        /**
-         * Gets the SAML message referenced by the artifact.
-         * 
-         * @return SAML message referenced by the artifact
-         */
+        /** {@inheritDoc} */
         public SAMLObject getReferencedMessage() {
             return referencedMessage;
         }
 
-        /**
-         * Sets the SAML message referenced by the artifact.
-         * 
-         * @param message SAML message referenced by the artifact
-         */
+        /** {@inheritDoc} */
         public void setReferencedMessage(SAMLObject message) {
             referencedMessage = message;
         }