Set communication profile before decoding
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml1 / ShibbolethSSOProfileHandler.java
index acfc0bd..da1ab1f 100644 (file)
@@ -23,7 +23,6 @@ import javax.servlet.RequestDispatcher;
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
-import javax.servlet.http.HttpSession;
 
 import org.opensaml.common.SAMLObjectBuilder;
 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
@@ -41,8 +40,6 @@ import org.opensaml.saml2.metadata.Endpoint;
 import org.opensaml.saml2.metadata.EntityDescriptor;
 import org.opensaml.saml2.metadata.IDPSSODescriptor;
 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.transport.http.HTTPInTransport;
 import org.opensaml.ws.transport.http.HTTPOutTransport;
@@ -55,6 +52,7 @@ import org.slf4j.LoggerFactory;
 
 import edu.internet2.middleware.shibboleth.common.ShibbolethConstants;
 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
+import edu.internet2.middleware.shibboleth.common.profile.provider.BaseSAMLProfileRequestContext;
 import edu.internet2.middleware.shibboleth.common.relyingparty.ProfileConfiguration;
 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.ShibbolethSSOConfiguration;
@@ -74,6 +72,9 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
     /** Builder of SubjectLocality objects. */
     private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
 
+    /** Builder of Endpoint objects. */
+    private SAMLObjectBuilder<Endpoint> endpointBuilder;
+
     /** URL of the authentication manager servlet. */
     private String authenticationManagerPath;
 
@@ -96,11 +97,14 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
 
         subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
                 SubjectLocality.DEFAULT_ELEMENT_NAME);
+
+        endpointBuilder = (SAMLObjectBuilder<Endpoint>) getBuilderFactory().getBuilder(
+                AssertionConsumerService.DEFAULT_ELEMENT_NAME);
     }
 
     /** {@inheritDoc} */
     public String getProfileId() {
-        return "urn:mace:shibboleth:2.0:idp:profiles:shibboleth:request:sso";
+        return ShibbolethSSOConfiguration.PROFILE_ID;
     }
 
     /** {@inheritDoc} */
@@ -108,17 +112,13 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
         log.debug("Processing incoming request");
 
         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
-        HttpSession httpSession = httpRequest.getSession();
-        LoginContext loginContext = (LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
+        LoginContext loginContext = (LoginContext) httpRequest.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
 
         if (loginContext == null) {
-            log.debug("User session does not contain a login context, processing as first leg of request");
-            performAuthentication(inTransport, outTransport);
-        } else if (!loginContext.isPrincipalAuthenticated() && !loginContext.getAuthenticationAttempted()) {
-            log.debug("User session contained a login context but user was not authenticated, processing as first leg of request");
+            log.debug("Incoming request does not contain a login context, processing as first leg of request");
             performAuthentication(inTransport, outTransport);
         } else {
-            log.debug("User session contains a login context, processing as second leg of request");
+            log.debug("Incoming request contains a login context, processing as second leg of request");
             completeAuthenticationRequest(inTransport, outTransport);
         }
     }
@@ -138,7 +138,6 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
 
         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
         HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
-        HttpSession httpSession = httpRequest.getSession(true);
 
         ShibbolethSSORequestContext requestContext = decodeRequest(inTransport, outTransport);
         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
@@ -152,18 +151,16 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
         }
         loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
 
-        httpSession.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
+        httpRequest.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
 
         try {
             RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
             dispatcher.forward(httpRequest, httpResponse);
             return;
         } catch (IOException ex) {
-            httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
             log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
             throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
         } catch (ServletException ex) {
-            httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
             log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
             throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
         }
@@ -182,10 +179,12 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
     protected ShibbolethSSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
             throws ProfileException {
         log.debug("Decoding message with decoder binding {}", getInboundBinding());
-        
+
         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
 
         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
+        requestContext.setCommunicationProfileId(getProfileId());
+        
         requestContext.setMetadataProvider(getMetadataProvider());
         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
 
@@ -215,7 +214,6 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
         loginContext.setSpTarget(requestContext.getRelayState());
         loginContext.setAuthenticationEngineURL(authenticationManagerPath);
         loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
-
         requestContext.setLoginContext(loginContext);
 
         return requestContext;
@@ -233,19 +231,18 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
     protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
             throws ProfileException {
         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
-        HttpSession httpSession = httpRequest.getSession(true);
-
-        ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpSession
+        ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpRequest
                 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
-        httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
 
         ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
 
         Response samlResponse;
         try {
-            if (loginContext.getPrincipalName() == null) {
+            if (loginContext.getAuthenticationFailure() != null) {
+                log.error("User authentication failed with the following error: {}", loginContext
+                        .getAuthenticationFailure().toString());
                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
-                throw new ProfileException("User failed authentication");
+                throw new ProfileException("Authentication failure", loginContext.getAuthenticationFailure());
             }
 
             resolveAttributes(requestContext);
@@ -256,7 +253,7 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
                 AttributeStatement attributeStatement = buildAttributeStatement(requestContext,
                         "urn:oasis:names:tc:SAML:1.0:cm:bearer");
                 if (attributeStatement != null) {
-                    requestContext.setRequestedAttributes(requestContext.getPrincipalAttributes().keySet());
+                    requestContext.setRequestedAttributes(requestContext.getAttributes().keySet());
                     statements.add(attributeStatement);
                 }
             }
@@ -287,13 +284,11 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
     protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
             HTTPInTransport in, HTTPOutTransport out) throws ProfileException {
         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
+        requestContext.setCommunicationProfileId(getProfileId());
 
         requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
 
         requestContext.setLoginContext(loginContext);
-        requestContext.setPrincipalName(loginContext.getPrincipalName());
-        requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
-        requestContext.setUserSession(getUserSession(in));
         requestContext.setRelayState(loginContext.getSpTarget());
 
         requestContext.setInboundMessageTransport(in);
@@ -302,60 +297,45 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
         requestContext.setOutboundMessageTransport(out);
         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
 
-        MetadataProvider metadataProvider = getMetadataProvider();
-        requestContext.setMetadataProvider(metadataProvider);
+        requestContext.setMetadataProvider(getMetadataProvider());
 
         String relyingPartyId = loginContext.getRelyingPartyId();
+        requestContext.setPeerEntityId(relyingPartyId);
         requestContext.setInboundMessageIssuer(relyingPartyId);
 
-        try {
-            EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
-            if (relyingPartyMetadata != null) {
-                requestContext.setPeerEntityMetadata(relyingPartyMetadata);
-                requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
-                requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata
-                        .getSPSSODescriptor(SAMLConstants.SAML11P_NS));
-            }
-        } catch (MetadataProviderException e) {
-            log.error("Unable to locate metadata for relying party");
-            requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
-                    "Error locating relying party metadata"));
-            throw new ProfileException("Error locating relying party metadata");
-        }
+        populateRequestContext(requestContext);
+
+        return requestContext;
+    }
 
-        RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
-        if (rpConfig == null) {
-            log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
-            throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
-                    + relyingPartyId);
+    /** {@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));
         }
-        requestContext.setRelyingPartyConfiguration(rpConfig);
+    }
 
-        ShibbolethSSOConfiguration profileConfig = (ShibbolethSSOConfiguration) rpConfig
-                .getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
-        requestContext.setProfileConfiguration(profileConfig);
-        requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
-        requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
+    /** {@inheritDoc} */
+    protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
+            throws ProfileException {
+        super.populateAssertingPartyInformation(requestContext);
 
-        String assertingPartyId = rpConfig.getProviderId();
-        requestContext.setLocalEntityId(assertingPartyId);
-        requestContext.setOutboundMessageIssuer(assertingPartyId);
-        try {
-            EntityDescriptor localEntityDescriptor = metadataProvider.getEntityDescriptor(assertingPartyId);
-            if (localEntityDescriptor != null) {
-                requestContext.setLocalEntityMetadata(localEntityDescriptor);
-                requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
-                requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
-                        .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
-            }
-        } catch (MetadataProviderException e) {
-            log.error("Unable to locate metadata for asserting party");
-            requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
-                    "Error locating asserting party metadata"));
-            throw new ProfileException("Error locating asserting party metadata");
+        EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
+        if (localEntityDescriptor != null) {
+            requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
+            requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
+                    .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
         }
+    }
 
-        return requestContext;
+    /** {@inheritDoc} */
+    protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
+        // nothing to do here
     }
 
     /**
@@ -365,8 +345,8 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
      * 
      * @return Endpoint selected from the information provided in the request context
      */
-    protected Endpoint selectEndpoint(ShibbolethSSORequestContext requestContext) {
-        ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
+    protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
+        ShibbolethSSOLoginContext loginContext = ((ShibbolethSSORequestContext) requestContext).getLoginContext();
 
         ShibbolethSSOEndpointSelector endpointSelector = new ShibbolethSSOEndpointSelector();
         endpointSelector.setSpAssertionConsumerService(loginContext.getSpAssertionConsumerService());
@@ -377,7 +357,16 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
         endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
         endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
 
-        return endpointSelector.selectEndpoint();
+        Endpoint endpoint = endpointSelector.selectEndpoint();
+        if (endpoint == null && loginContext.getSpAssertionConsumerService() != null) {
+            endpoint = endpointBuilder.buildObject();
+            endpoint.setLocation(loginContext.getSpAssertionConsumerService());
+            endpoint.setBinding(getSupportedOutboundBindings().get(0));
+            log.warn("No endpoint available for relying party {}. Generating endpoint with ACS url {} and binding {}",
+                    new Object[] { requestContext.getPeerEntityId(), endpoint.getLocation(), endpoint.getBinding() });
+        }
+
+        return endpoint;
     }
 
     /**
@@ -417,7 +406,6 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
 
         HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
         subjectLocality.setIPAddress(inTransport.getPeerAddress());
-        subjectLocality.setDNSAddress(inTransport.getPeerDomainName());
 
         return subjectLocality;
     }