Lots of code cleanup
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml1 / ShibbolethSSOProfileHandler.java
index bb0f5aa..a9c2e07 100644 (file)
@@ -23,12 +23,11 @@ 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.apache.log4j.Logger;
 import org.opensaml.common.SAMLObjectBuilder;
 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
 import org.opensaml.common.xml.SAMLConstants;
+import org.opensaml.saml1.core.AttributeStatement;
 import org.opensaml.saml1.core.AuthenticationStatement;
 import org.opensaml.saml1.core.Request;
 import org.opensaml.saml1.core.Response;
@@ -41,21 +40,22 @@ 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.security.SecurityPolicyException;
 import org.opensaml.ws.transport.http.HTTPInTransport;
 import org.opensaml.ws.transport.http.HTTPOutTransport;
 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
+import org.opensaml.xml.security.SecurityException;
 import org.opensaml.xml.util.DatatypeHelper;
+import org.slf4j.Logger;
+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;
-import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.SSOConfiguration;
 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
 import edu.internet2.middleware.shibboleth.idp.authn.ShibbolethSSOLoginContext;
@@ -64,7 +64,7 @@ import edu.internet2.middleware.shibboleth.idp.authn.ShibbolethSSOLoginContext;
 public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
 
     /** Class logger. */
-    private final Logger log = Logger.getLogger(ShibbolethSSOProfileHandler.class);
+    private final Logger log = LoggerFactory.getLogger(ShibbolethSSOProfileHandler.class);
 
     /** Builder of AuthenticationStatement objects. */
     private SAMLObjectBuilder<AuthenticationStatement> authnStatementBuilder;
@@ -98,27 +98,21 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
 
     /** {@inheritDoc} */
     public String getProfileId() {
-        return "urn:mace:shibboleth:2.0:idp:profiles:shibboleth:request:sso";
+        return ShibbolethSSOConfiguration.PROFILE_ID;
     }
 
     /** {@inheritDoc} */
     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
-        if (log.isDebugEnabled()) {
-            log.debug("Processing incomming request");
-        }
+        log.debug("Processing incoming request");
 
         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
-        HttpSession httpSession = httpRequest.getSession();
+        LoginContext loginContext = (LoginContext) httpRequest.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
 
-        if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
-            if (log.isDebugEnabled()) {
-                log.debug("User session does not contain a login context, processing as first leg of request");
-            }
+        if (loginContext == null) {
+            log.debug("Incoming request does not contain a login context, processing as first leg of request");
             performAuthentication(inTransport, outTransport);
         } else {
-            if (log.isDebugEnabled()) {
-                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,18 +132,20 @@ 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();
 
-        if (getRelyingPartyConfiguration(loginContext.getRelyingPartyId()) == null) {
+        RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(loginContext.getRelyingPartyId());
+        ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
+        if (ssoConfig == null) {
             log.error("Shibboleth SSO profile is not configured for relying party " + loginContext.getRelyingPartyId());
             throw new ProfileException("Shibboleth SSO profile is not configured for relying party "
                     + loginContext.getRelyingPartyId());
         }
+        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);
@@ -176,11 +172,21 @@ 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.setMetadataProvider(getMetadataProvider());
+        requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
+
+        requestContext.setCommunicationProfileId(ShibbolethSSOConfiguration.PROFILE_ID);
         requestContext.setInboundMessageTransport(inTransport);
+        requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
+        requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
+
         requestContext.setOutboundMessageTransport(outTransport);
+        requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
 
         SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
         requestContext.setMessageDecoder(decoder);
@@ -189,17 +195,18 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
         } catch (MessageDecodingException e) {
             log.error("Error decoding Shibboleth SSO request", e);
             throw new ProfileException("Error decoding Shibboleth SSO request", e);
-        } catch (SecurityPolicyException e) {
-            log.error("Shibboleth SSO request does not meet security policy requirements", e);
-            throw new ProfileException("Shibboleth SSO request does not meet security policy requirements", e);
+        } catch (SecurityException e) {
+            log.error("Shibboleth SSO request does not meet security requirements", e);
+            throw new ProfileException("Shibboleth SSO request does not meet security requirements", e);
         }
 
         ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
-        loginContext.setRelyingParty(requestContext.getPeerEntityId());
+        loginContext.setRelyingParty(requestContext.getInboundMessageIssuer());
         loginContext.setSpAssertionConsumerService(requestContext.getSpAssertionConsumerService());
         loginContext.setSpTarget(requestContext.getRelayState());
         loginContext.setAuthenticationEngineURL(authenticationManagerPath);
         loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
+
         requestContext.setLoginContext(loginContext);
 
         return requestContext;
@@ -217,19 +224,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);
@@ -237,8 +243,12 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
             ArrayList<Statement> statements = new ArrayList<Statement>();
             statements.add(buildAuthenticationStatement(requestContext));
             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
-                requestContext.setRequestedAttributes(requestContext.getPrincipalAttributes().keySet());
-                statements.add(buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer"));
+                AttributeStatement attributeStatement = buildAttributeStatement(requestContext,
+                        "urn:oasis:names:tc:SAML:1.0:cm:bearer");
+                if (attributeStatement != null) {
+                    requestContext.setRequestedAttributes(requestContext.getAttributes().keySet());
+                    statements.add(attributeStatement);
+                }
             }
 
             samlResponse = buildResponse(requestContext, statements);
@@ -268,57 +278,58 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
             HTTPInTransport in, HTTPOutTransport out) throws ProfileException {
         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
 
-        try {
-            requestContext.setLoginContext(loginContext);
-            requestContext.setPrincipalName(loginContext.getPrincipalName());
-            requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
-            requestContext.setUserSession(getUserSession(in));
-            requestContext.setRelayState(loginContext.getSpTarget());
-
-            requestContext.setInboundMessageTransport(in);
-            requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
-
-            MetadataProvider metadataProvider = getMetadataProvider();
-            requestContext.setMetadataProvider(metadataProvider);
-
-            String relyingPartyId = loginContext.getRelyingPartyId();
-            requestContext.setPeerEntityId(relyingPartyId);
-            EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
-            requestContext.setPeerEntityMetadata(relyingPartyMetadata);
+        requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
+
+        requestContext.setLoginContext(loginContext);
+        requestContext.setRelayState(loginContext.getSpTarget());
+
+        requestContext.setInboundMessageTransport(in);
+        requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
+
+        requestContext.setOutboundMessageTransport(out);
+        requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
+
+        requestContext.setMetadataProvider(getMetadataProvider());
+
+        String relyingPartyId = loginContext.getRelyingPartyId();
+        requestContext.setInboundMessageIssuer(relyingPartyId);
+
+        populateRequestContext(requestContext);
+
+        return 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));
-            RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
-            requestContext.setRelyingPartyConfiguration(rpConfig);
-            requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
-
-            String assertingPartyId = rpConfig.getProviderId();
-            requestContext.setLocalEntityId(assertingPartyId);
-            EntityDescriptor assertingPartyMetadata = metadataProvider.getEntityDescriptor(assertingPartyId);
-            requestContext.setLocalEntityMetadata(assertingPartyMetadata);
-            requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
-            requestContext.setLocalEntityRoleMetadata(assertingPartyMetadata
-                    .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
+        }
+    }
 
-            requestContext.setOutboundMessageTransport(out);
-            requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
-            ShibbolethSSOConfiguration profileConfig = (ShibbolethSSOConfiguration) rpConfig
-                    .getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
-            requestContext.setProfileConfiguration(profileConfig);
-            requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
-            if (profileConfig.getSigningCredential() != null) {
-                requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
-            } else if (rpConfig.getDefaultSigningCredential() != null) {
-                requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
-            }
+    /** {@inheritDoc} */
+    protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
+            throws ProfileException {
+        super.populateAssertingPartyInformation(requestContext);
 
-            return requestContext;
-        } 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");
+        EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
+        if (localEntityDescriptor != null) {
+            requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
+            requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
+                    .getIDPSSODescriptor(SAMLConstants.SAML20P_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.
      * 
@@ -326,8 +337,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());
@@ -378,7 +389,6 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
 
         HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
         subjectLocality.setIPAddress(inTransport.getPeerAddress());
-        subjectLocality.setDNSAddress(inTransport.getPeerDomainName());
 
         return subjectLocality;
     }
@@ -387,9 +397,6 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
     public class ShibbolethSSORequestContext extends
             BaseSAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
 
-        /** Time since the epoch. */
-        private long time;
-
         /** SP-provide assertion consumer service URL. */
         private String spAssertionConsumerService;
 
@@ -431,23 +438,5 @@ public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
         public void setSpAssertionConsumerService(String acs) {
             spAssertionConsumerService = acs;
         }
-
-        /**
-         * Sets the time since the epoch.
-         * 
-         * @return time since the epoch
-         */
-        public long getTime() {
-            return time;
-        }
-
-        /**
-         * Sets the time since the epoch.
-         * 
-         * @param time time since the epoch
-         */
-        public void setTime(long time) {
-            this.time = time;
-        }
     }
 }
\ No newline at end of file