SAML v2 artifact resolver endpoint
authorlajoie <lajoie@ab3bd59b-922f-494d-bb5f-6f0a3c29deca>
Sat, 18 Aug 2007 14:11:20 +0000 (14:11 +0000)
committerlajoie <lajoie@ab3bd59b-922f-494d-bb5f-6f0a3c29deca>
Sat, 18 Aug 2007 14:11:20 +0000 (14:11 +0000)
minor SAML v2 SSO endpoint code cleanup

git-svn-id: https://subversion.switch.ch/svn/shibboleth/java-idp/trunk@2333 ab3bd59b-922f-494d-bb5f-6f0a3c29deca

src/edu/internet2/middleware/shibboleth/idp/profile/saml2/ArtifactResolution.java
src/edu/internet2/middleware/shibboleth/idp/profile/saml2/SSOProfileHandler.java

index 3832774..6584bce 100644 (file)
 
 package edu.internet2.middleware.shibboleth.idp.profile.saml2;
 
+import org.apache.log4j.Logger;
+import org.joda.time.DateTime;
+import org.opensaml.common.SAMLObject;
+import org.opensaml.common.SAMLObjectBuilder;
+import org.opensaml.common.binding.BasicEndpointSelector;
+import org.opensaml.common.binding.artifact.SAMLArtifactMap;
+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.core.ArtifactResolve;
+import org.opensaml.saml2.core.ArtifactResponse;
+import org.opensaml.saml2.core.Status;
+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.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 edu.internet2.middleware.shibboleth.common.profile.ProfileException;
+import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
+import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.ArtifactResolutionConfiguration;
 
 /**
  * SAML 2.0 Artifact resolution profile handler.
  */
 public class ArtifactResolution extends AbstractSAML2ProfileHandler {
 
-    /** {@inheritDoc} */
-    public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
-        // TODO Auto-generated method stub
+    /** Class logger. */
+    private final Logger log = Logger.getLogger(ArtifactResolution.class);
+
+    /** Map artifacts to SAML messages. */
+    private SAMLArtifactMap artifactMap;
 
+    /** Artifact response object builder. */
+    private SAMLObjectBuilder<ArtifactResponse> responseBuilder;
+
+    public ArtifactResolution() {
+        super();
+        responseBuilder = (SAMLObjectBuilder<ArtifactResponse>) getBuilderFactory().getBuilder(
+                ArtifactResponse.DEFAULT_ELEMENT_NAME);
     }
 
     /** {@inheritDoc} */
     public String getProfileId() {
-        // TODO Auto-generated method stub
-        return null;
+        return "urn:mace:shibboleth:2.0:idp:profiles:saml2:request:artifact";
+    }
+
+    /** {@inheritDoc} */
+    public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
+        ArtifactResponse samlResponse;
+
+        ArtifactResolutionRequestContext requestContext = decodeRequest(inTransport, outTransport);
+
+        try {
+            if (requestContext.getRelyingPartyConfiguration() == null) {
+                log.error("SAML 2 Artifact Resolve profile is not configured for relying party "
+                        + requestContext.getPeerEntityId());
+                requestContext.setFailureStatus(buildStatus(StatusCode.SUCCESS_URI, StatusCode.REQUEST_DENIED_URI,
+                        "SAML 2 Artifact Resolve profile is not configured for relying party "
+                                + requestContext.getPeerEntityId()));
+                throw new ProfileException("SAML 2 Artifact Resolve profile is not configured for relying party "
+                        + requestContext.getPeerEntityId());
+            }
+
+            checkSamlVersion(requestContext);
+
+            SAMLArtifactMapEntry artifactEntry = artifactMap.peek(requestContext.getArtifact().getBytes());
+            if (artifactEntry == null || artifactEntry.isExpired()) {
+                log.error("Unknown artifact.");
+                requestContext.setFailureStatus(buildStatus(StatusCode.SUCCESS_URI, StatusCode.REQUEST_DENIED_URI,
+                        "Unknown artifact."));
+                throw new ProfileException("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());
+                requestContext.setFailureStatus(buildStatus(StatusCode.SUCCESS_URI, StatusCode.REQUEST_DENIED_URI,
+                        "Artifact issuer mismatch."));
+                throw new ProfileException("Artifact issuer mismatch.");
+            }
+
+            if (!artifactEntry.getRelyingPartyId().equals(requestContext.getPeerEntityId())) {
+                log.error("Artifact requester mismatch.  Artifact was issued to " + artifactEntry.getRelyingPartyId()
+                        + " but was resolve request came from " + requestContext.getPeerEntityId());
+                requestContext.setFailureStatus(buildStatus(StatusCode.SUCCESS_URI, StatusCode.REQUEST_DENIED_URI,
+                        "Artifact requester mismatch."));
+                throw new ProfileException("Artifact requester mismatch.");
+            }
+
+            SAMLObject referencedMessage = artifactEntry.getSamlMessage();
+            requestContext.setReferencedMessage(referencedMessage);
+
+            // create the SAML response
+            samlResponse = buildArtifactResponse(requestContext);
+        } catch (ProfileException e) {
+            samlResponse = buildArtifactErrorResponse(requestContext);
+        }
+
+        requestContext.setOutboundSAMLMessage(samlResponse);
+        requestContext.setOutboundSAMLMessageId(samlResponse.getID());
+        requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
+
+        encodeResponse(requestContext);
+        writeAuditLogEntry(requestContext);
+    }
+
+    /**
+     * Decodes an incoming request and populates a created request context with the resultant information.
+     * 
+     * @param inTransport inbound message transport
+     * @param outTransport outbound message transport
+     * 
+     * @return the created request context
+     * 
+     * @throws ProfileException throw if there is a problem decoding the request
+     */
+    protected ArtifactResolutionRequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
+            throws ProfileException {
+        if (log.isDebugEnabled()) {
+            log.debug("Decoding incomming request");
+        }
+
+        MetadataProvider metadataProvider = getMetadataProvider();
+
+        ArtifactResolutionRequestContext requestContext = new ArtifactResolutionRequestContext();
+        requestContext.setInboundMessageTransport(inTransport);
+        requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
+        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");
+            }
+            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);
+            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);
+        } finally {
+            // Set as much information as can be retrieved from the decoded message
+            try {
+                ArtifactResolve artResolve = requestContext.getInboundSAMLMessage();
+                requestContext.setArtifact(artResolve.getArtifact().getArtifact());
+                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");
+            }
+        }
+    }
+
+    /**
+     * 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.setRelyingParty(requestContext.getPeerEntityMetadata());
+        endpointSelector.setRelyingPartyRole(requestContext.getPeerEntityRoleMetadata());
+        endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
+        endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
+        return endpointSelector.selectEndpoint();
+    }
+
+    /**
+     * Constructs a artifact resolution response with the derferenced SAML message inside.
+     * 
+     * @param requestContext current request context
+     * 
+     * @return constructed response
+     */
+    protected ArtifactResponse buildArtifactResponse(ArtifactResolutionRequestContext requestContext) {
+        DateTime issueInstant = new DateTime();
+
+        // create the SAML response and add the assertion
+        ArtifactResponse samlResponse = responseBuilder.buildObject();
+        samlResponse.setIssueInstant(issueInstant);
+        populateStatusResponse(requestContext, samlResponse);
+
+        Status status = buildStatus(StatusCode.SUCCESS_URI, null, null);
+        samlResponse.setStatus(status);
+
+        samlResponse.setMessage(requestContext.getReferencedMessage());
+
+        return samlResponse;
+    }
+
+    /**
+     * Constructs an artifact resolution response with an error status as content.
+     * 
+     * @param requestContext current request context
+     * 
+     * @return constructed response
+     */
+    protected ArtifactResponse buildArtifactErrorResponse(ArtifactResolutionRequestContext requestContext) {
+        ArtifactResponse samlResponse = responseBuilder.buildObject();
+        samlResponse.setIssueInstant(new DateTime());
+        populateStatusResponse(requestContext, samlResponse);
+
+        samlResponse.setStatus(requestContext.getFailureStatus());
+
+        return samlResponse;
+    }
+
+    /** Represents the internal state of a SAML 2.0 Artiface resolver request while it's being processed by the IdP. */
+    public class ArtifactResolutionRequestContext extends
+            BaseSAML2ProfileRequestContext<ArtifactResolve, ArtifactResponse, ArtifactResolutionConfiguration> {
+
+        /** Artifact to be resolved. */
+        private String artifact;
+
+        /** Message referenced by the SAML artifact. */
+        private SAMLObject referencedMessage;
+
+        /**
+         * Gets the artifact to be resolved.
+         * 
+         * @return artifact to be resolved
+         */
+        public String getArtifact() {
+            return artifact;
+        }
+
+        /**
+         * Sets the artifact to be resolved.
+         * 
+         * @param artifact artifact to be resolved
+         */
+        public void setArtifact(String artifact) {
+            this.artifact = artifact;
+        }
+
+        /**
+         * Gets the SAML message referenced by the artifact.
+         * 
+         * @return SAML message referenced by the artifact
+         */
+        public SAMLObject getReferencedMessage() {
+            return referencedMessage;
+        }
+
+        /**
+         * Sets the SAML message referenced by the artifact.
+         * 
+         * @param message SAML message referenced by the artifact
+         */
+        public void setReferencedMessage(SAMLObject message) {
+            referencedMessage = message;
+        }
     }
 }
\ No newline at end of file
index af2de05..f753517 100644 (file)
@@ -87,9 +87,6 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
     /** URL of the authentication manager servlet. */
     private String authenticationManagerPath;
 
-    /** URI of SAML 2 bindings supported for outgoing messaged encoding. */
-    private ArrayList<String> supportedOutgoingBindings;
-
     /** URI of request decoder. */
     private String decodingBinding;
 
@@ -109,11 +106,6 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
         }
         authenticationManagerPath = authnManagerPath;
 
-        if (outgoingBindings == null || outgoingBindings.isEmpty()) {
-            throw new IllegalArgumentException("List of supported outgoing bindings may not be empty");
-        }
-        supportedOutgoingBindings = new ArrayList<String>(outgoingBindings);
-
         decodingBinding = decoder;
 
         authnStatementBuilder = (SAMLObjectBuilder<AuthnStatement>) getBuilderFactory().getBuilder(
@@ -452,7 +444,7 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
         endpointSelector.setRelyingParty(requestContext.getPeerEntityMetadata());
         endpointSelector.setRelyingPartyRole(requestContext.getPeerEntityRoleMetadata());
         endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
-        endpointSelector.getSupportedIssuerBindings().addAll(supportedOutgoingBindings);
+        endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
         return endpointSelector.selectEndpoint();
     }