Lots of code cleanup
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml2 / SSOProfileHandler.java
index f198ba9..257a268 100644 (file)
@@ -22,13 +22,12 @@ import java.util.ArrayList;
 import javax.servlet.RequestDispatcher;
 import javax.servlet.ServletException;
 import javax.servlet.http.HttpServletRequest;
-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.saml2.binding.AuthnResponseEndpointSelector;
+import org.opensaml.saml2.core.AttributeStatement;
 import org.opensaml.saml2.core.AuthnContext;
 import org.opensaml.saml2.core.AuthnContextClassRef;
 import org.opensaml.saml2.core.AuthnContextDeclRef;
@@ -38,36 +37,41 @@ import org.opensaml.saml2.core.RequestedAuthnContext;
 import org.opensaml.saml2.core.Response;
 import org.opensaml.saml2.core.Statement;
 import org.opensaml.saml2.core.StatusCode;
+import org.opensaml.saml2.core.Subject;
 import org.opensaml.saml2.core.SubjectLocality;
 import org.opensaml.saml2.metadata.AssertionConsumerService;
 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.io.MarshallingException;
 import org.opensaml.xml.io.UnmarshallingException;
+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.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.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.PassiveAuthenticationException;
 import edu.internet2.middleware.shibboleth.idp.authn.Saml2LoginContext;
+import edu.internet2.middleware.shibboleth.idp.session.Session;
 
 /** SAML 2.0 SSO request profile handler. */
 public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
 
     /** Class logger. */
-    private final Logger log = Logger.getLogger(SSOProfileHandler.class);
+    private final Logger log = LoggerFactory.getLogger(SSOProfileHandler.class);
 
     /** Builder of AuthnStatement objects. */
     private SAMLObjectBuilder<AuthnStatement> authnStatementBuilder;
@@ -87,9 +91,6 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
     /** URL of the authentication manager servlet. */
     private String authenticationManagerPath;
 
-    /** URI of request decoder. */
-    private String decodingBinding;
-
     /**
      * Constructor.
      * 
@@ -115,17 +116,19 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
 
     /** {@inheritDoc} */
     public String getProfileId() {
-        return "urn:mace:shibboleth:2.0:idp:profiles:saml2:request:sso";
+        return SSOConfiguration.PROFILE_ID;
     }
 
     /** {@inheritDoc} */
     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
         HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
-        HttpSession httpSession = servletRequest.getSession(true);
 
-        if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
+        LoginContext loginContext = (LoginContext) servletRequest.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
+        if (loginContext == null) {
+            log.debug("Incoming request does not contain a login context, processing as first leg of request");
             performAuthentication(inTransport, outTransport);
         } else {
+            log.debug("Incoming request contains a login context, processing as second leg of request");
             completeAuthenticationRequest(inTransport, outTransport);
         }
     }
@@ -151,7 +154,8 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
             ProfileConfiguration ssoConfig = rpConfig.getProfileConfiguration(SSOConfiguration.PROFILE_ID);
             if (ssoConfig == null) {
-                log.error("SAML 2 SSO profile is not configured for relying party " + requestContext.getInboundMessageIssuer());
+                log.error("SAML 2 SSO profile is not configured for relying party "
+                        + requestContext.getInboundMessageIssuer());
                 throw new ProfileException("SAML 2 SSO profile is not configured for relying party "
                         + requestContext.getInboundMessageIssuer());
             }
@@ -165,8 +169,7 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
                 loginContext.getRequestedAuthenticationMethods().add(rpConfig.getDefaultAuthenticationMethod());
             }
 
-            HttpSession httpSession = servletRequest.getSession();
-            httpSession.setAttribute(Saml2LoginContext.LOGIN_CONTEXT_KEY, loginContext);
+            servletRequest.setAttribute(Saml2LoginContext.LOGIN_CONTEXT_KEY, loginContext);
             RequestDispatcher dispatcher = servletRequest.getRequestDispatcher(authenticationManagerPath);
             dispatcher.forward(servletRequest, ((HttpServletResponseAdapter) outTransport).getWrappedResponse());
         } catch (MarshallingException e) {
@@ -193,22 +196,43 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
     protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
             throws ProfileException {
         HttpServletRequest servletRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
-        HttpSession httpSession = servletRequest.getSession();
-
-        Saml2LoginContext loginContext = (Saml2LoginContext) httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
-        httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
 
+        Saml2LoginContext loginContext = (Saml2LoginContext) servletRequest
+                .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
         SSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
 
         checkSamlVersion(requestContext);
 
         Response samlResponse;
         try {
-            if (loginContext.getPrincipalName() == null) {
-                log.error("User's login context did not contain a principal, user considered unauthenticiated.");
-                requestContext
-                        .setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI, null));
-                throw new ProfileException("User failed authentication");
+            if (loginContext.getAuthenticationFailure() != null) {
+                log.error("User authentication failed with the following error: {}", loginContext
+                        .getAuthenticationFailure().toString());
+
+                if (loginContext.getAuthenticationFailure() instanceof PassiveAuthenticationException) {
+                    requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.NO_PASSIVE_URI,
+                            null));
+                } else {
+                    requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
+                            null));
+                }
+                throw new ProfileException("Authentication failure", loginContext.getAuthenticationFailure());
+            }
+
+            if (requestContext.getSubjectNameIdentifier() != null) {
+                log
+                        .debug("Authentication request contained a subject with a name identifier, resolving principal from NameID");
+                resolvePrincipal(requestContext);
+                String requestedPrincipalName = requestContext.getPrincipalName();
+                if (!DatatypeHelper.safeEquals(loginContext.getPrincipalName(), requestedPrincipalName)) {
+                    log
+                            .error(
+                                    "Authentication request identified principal {} but authentication mechanism identified principal {}",
+                                    requestedPrincipalName, loginContext.getPrincipalName());
+                    requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.AUTHN_FAILED_URI,
+                            null));
+                    throw new ProfileException("User failed authentication");
+                }
             }
 
             resolveAttributes(requestContext);
@@ -216,8 +240,11 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
             ArrayList<Statement> statements = new ArrayList<Statement>();
             statements.add(buildAuthnStatement(requestContext));
             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
-                requestContext.setRequestedAttributes(requestContext.getPrincipalAttributes().keySet());
-                statements.add(buildAttributeStatement(requestContext));
+                AttributeStatement attributeStatement = buildAttributeStatement(requestContext);
+                if (attributeStatement != null) {
+                    requestContext.setRequestedAttributes(requestContext.getAttributes().keySet());
+                    statements.add(attributeStatement);
+                }
             }
 
             samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:bearer", statements);
@@ -240,21 +267,20 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
      * 
      * @return request context with decoded information
      * 
-     * @throws ProfileException thrown if the incomming message failed decoding
+     * @throws ProfileException thrown if the incoming message failed decoding
      */
     protected SSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
             throws ProfileException {
-        if (log.isDebugEnabled()) {
-            log.debug("Decoding message with decoder binding " + decodingBinding);
-        }
-
+        log.debug("Decoding message with decoder binding {}", getInboundBinding());
         SSORequestContext requestContext = new SSORequestContext();
         requestContext.setMetadataProvider(getMetadataProvider());
-        
+        requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
+
+        requestContext.setCommunicationProfileId(SSOConfiguration.PROFILE_ID);
         requestContext.setInboundMessageTransport(inTransport);
         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
-        
+
         requestContext.setOutboundMessageTransport(outTransport);
         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
 
@@ -262,13 +288,23 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
             requestContext.setMessageDecoder(decoder);
             decoder.decode(requestContext);
+            log.debug("Decoded request");
+
+            if (!(requestContext.getInboundMessage() instanceof AuthnRequest)) {
+                log.error("Incomming message was not a AuthnRequest, it was a {}", requestContext.getInboundMessage()
+                        .getClass().getName());
+                requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER_URI, null,
+                        "Invalid SAML AuthnRequest message."));
+                throw new ProfileException("Invalid SAML AuthnRequest message.");
+            }
+
             return requestContext;
         } catch (MessageDecodingException e) {
             log.error("Error decoding authentication request message", e);
             throw new ProfileException("Error decoding authentication request message", e);
-        } catch (SecurityPolicyException e) {
-            log.error("Message did not meet security policy requirements", e);
-            throw new ProfileException("Message did not meet security policy requirements", e);
+        } catch (SecurityException e) {
+            log.error("Message did not meet security requirements", e);
+            throw new ProfileException("Message did not meet security requirements", e);
         }
     }
 
@@ -287,65 +323,85 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
             HTTPOutTransport out) throws ProfileException {
         SSORequestContext requestContext = new SSORequestContext();
 
-        try {
-            requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
-            
-            requestContext.setLoginContext(loginContext);
-            requestContext.setPrincipalName(loginContext.getPrincipalName());
-            requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
-            requestContext.setUserSession(getUserSession(in));
-            requestContext.setRelayState(loginContext.getRelayState());
+        requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
 
-            requestContext.setInboundMessageTransport(in);
-            requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
-            requestContext.setInboundMessage(loginContext.getAuthenticationRequest());
-            requestContext.setInboundSAMLMessage(loginContext.getAuthenticationRequest());
-            requestContext.setInboundSAMLMessageId(loginContext.getAuthenticationRequest().getID());
+        requestContext.setLoginContext(loginContext);
+
+        requestContext.setInboundMessageTransport(in);
+        requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
+
+        requestContext.setOutboundMessageTransport(out);
+        requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
+
+        requestContext.setMetadataProvider(getMetadataProvider());
+
+        String relyingPartyId = loginContext.getRelyingPartyId();
+        requestContext.setInboundMessageIssuer(relyingPartyId);
+
+        populateSAMLMessageInformation(requestContext);
+        populateRequestContext(requestContext);
+        populateProfileInformation(requestContext);
+
+        return requestContext;
+    }
 
-            MetadataProvider metadataProvider = getMetadataProvider();
-            requestContext.setMetadataProvider(metadataProvider);
+    /** {@inheritDoc} */
+    protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
+            throws ProfileException {
+        super.populateRelyingPartyInformation(requestContext);
 
-            String relyingPartyId = loginContext.getRelyingPartyId();
-            requestContext.setInboundMessageIssuer(relyingPartyId);
-            EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
-            requestContext.setPeerEntityMetadata(relyingPartyMetadata);
+        EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
+        if (relyingPartyMetadata != null) {
             requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
             requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML20P_NS));
-            RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
-            requestContext.setRelyingPartyConfiguration(rpConfig);
-            requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
+        }
+    }
+
+    /** {@inheritDoc} */
+    protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
+            throws ProfileException {
+        super.populateAssertingPartyInformation(requestContext);
 
-            String assertingPartyId = rpConfig.getProviderId();
-            requestContext.setLocalEntityId(assertingPartyId);
-            EntityDescriptor assertingPartyMetadata = metadataProvider.getEntityDescriptor(assertingPartyId);
-            requestContext.setLocalEntityMetadata(assertingPartyMetadata);
+        EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
+        if (localEntityDescriptor != null) {
             requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
-            requestContext.setLocalEntityRoleMetadata(assertingPartyMetadata
+            requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
                     .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
+        }
+    }
 
-            requestContext.setOutboundMessageTransport(out);
-            requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
-            SSOConfiguration profileConfig = (SSOConfiguration) rpConfig
-                    .getProfileConfiguration(SSOConfiguration.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());
-            }
+    /**
+     * Populates the request context with information from the inbound SAML message.
+     * 
+     * This method requires the the following request context properties to be populated: login context
+     * 
+     * This methods populates the following request context properties: inbound saml message, relay state, inbound saml
+     * message ID, 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 {
+        SSORequestContext ssoRequestContext = (SSORequestContext) requestContext;
+        try {
+            Saml2LoginContext loginContext = ssoRequestContext.getLoginContext();
+            requestContext.setRelayState(loginContext.getRelayState());
 
-            return requestContext;
+            AuthnRequest authnRequest = loginContext.getAuthenticationRequest();
+            requestContext.setInboundMessage(authnRequest);
+            requestContext.setInboundSAMLMessage(loginContext.getAuthenticationRequest());
+            requestContext.setInboundSAMLMessageId(loginContext.getAuthenticationRequest().getID());
+
+            Subject authnSubject = authnRequest.getSubject();
+            if (authnSubject != null) {
+                requestContext.setSubjectNameIdentifier(authnSubject.getNameID());
+            }
         } catch (UnmarshallingException e) {
             log.error("Unable to unmarshall authentication request context");
-            requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
+            ssoRequestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
                     "Error recovering request state"));
             throw new ProfileException("Error recovering request state", e);
-        } 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");
         }
     }
 
@@ -365,8 +421,10 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
         statement.setAuthnContext(authnContext);
         statement.setAuthnInstant(loginContext.getAuthenticationInstant());
 
-        // TODO
-        statement.setSessionIndex(null);
+        Session session = getUserSession(requestContext.getInboundMessageTransport());
+        if (session != null) {
+            statement.setSessionIndex(session.getSessionID());
+        }
 
         if (loginContext.getAuthenticationDuration() > 0) {
             statement.setSessionNotOnOrAfter(loginContext.getAuthenticationInstant().plus(
@@ -429,7 +487,6 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
         HTTPInTransport transport = (HTTPInTransport) requestContext.getInboundMessageTransport();
         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
         subjectLocality.setAddress(transport.getPeerAddress());
-        subjectLocality.setDNSName(transport.getPeerDomainName());
 
         return subjectLocality;
     }
@@ -441,7 +498,7 @@ public class SSOProfileHandler extends AbstractSAML2ProfileHandler {
      * 
      * @return Endpoint selected from the information provided in the request context
      */
-    protected Endpoint selectEndpoint(SSORequestContext requestContext) {
+    protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
         AuthnResponseEndpointSelector endpointSelector = new AuthnResponseEndpointSelector();
         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
         endpointSelector.setMetadataProvider(getMetadataProvider());