Lots of code cleanup
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml1 / AttributeQueryProfileHandler.java
index c21eab8..177de75 100644 (file)
@@ -18,31 +18,35 @@ package edu.internet2.middleware.shibboleth.idp.profile.saml1;
 
 import java.util.ArrayList;
 
-import javax.servlet.ServletRequest;
-import javax.servlet.ServletResponse;
-
-import org.apache.log4j.Logger;
-import org.opensaml.common.binding.BindingException;
-import org.opensaml.common.binding.decoding.MessageDecoder;
-import org.opensaml.common.binding.encoding.MessageEncoder;
-import org.opensaml.common.binding.security.SAMLSecurityPolicy;
-import org.opensaml.saml1.binding.decoding.HTTPSOAP11Decoder;
-import org.opensaml.saml1.binding.encoding.HTTPSOAP11Encoder;
+import org.opensaml.common.SAMLObjectBuilder;
+import org.opensaml.common.binding.BasicEndpointSelector;
+import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
+import org.opensaml.common.xml.SAMLConstants;
 import org.opensaml.saml1.core.AttributeQuery;
+import org.opensaml.saml1.core.AttributeStatement;
 import org.opensaml.saml1.core.Request;
 import org.opensaml.saml1.core.Response;
 import org.opensaml.saml1.core.Statement;
 import org.opensaml.saml1.core.StatusCode;
-import org.opensaml.saml2.metadata.RoleDescriptor;
-import org.opensaml.saml2.metadata.provider.MetadataProviderException;
-import org.opensaml.ws.security.SecurityPolicyException;
+import org.opensaml.saml1.core.Subject;
+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.ws.message.decoder.MessageDecodingException;
+import org.opensaml.ws.transport.http.HTTPInTransport;
+import org.opensaml.ws.transport.http.HTTPOutTransport;
+import org.opensaml.xml.security.SecurityException;
+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.ProfileRequest;
-import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
-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.saml1.AttributeQueryConfiguration;
+import edu.internet2.middleware.shibboleth.idp.session.AuthenticationMethodInformation;
+import edu.internet2.middleware.shibboleth.idp.session.Session;
 
 /**
  * SAML 1 Attribute Query profile handler.
@@ -50,227 +54,218 @@ import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.At
 public class AttributeQueryProfileHandler extends AbstractSAML1ProfileHandler {
 
     /** Class logger. */
-    private final Logger log = Logger.getLogger(AttributeQueryProfileHandler.class);
+    private final Logger log = LoggerFactory.getLogger(AttributeQueryProfileHandler.class);
+
+    /** Builder of assertion consumer service endpoints. */
+    private SAMLObjectBuilder<AssertionConsumerService> acsEndpointBuilder;
+
+    /** Constructor. */
+    public AttributeQueryProfileHandler() {
+        super();
+
+        acsEndpointBuilder = (SAMLObjectBuilder<AssertionConsumerService>) getBuilderFactory().getBuilder(
+                AssertionConsumerService.DEFAULT_ELEMENT_NAME);
+    }
 
     /** {@inheritDoc} */
     public String getProfileId() {
-        return "urn:mace:shibboleth:2.0:idp:profiles:saml1:query:attribute";
+        return AttributeQueryConfiguration.PROFILE_ID;
     }
 
     /** {@inheritDoc} */
-    public void processRequest(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response)
-            throws ProfileException {
-
-        AttributeQueryContext requestContext = new AttributeQueryContext(request, response);
+    public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
+        AttributeQueryContext requestContext = decodeRequest(inTransport, outTransport);
 
         Response samlResponse;
         try {
-            decodeRequest(requestContext);
-
-            if (requestContext.getRelyingPartyConfiguration() == null) {
+            if (requestContext.getProfileConfiguration() == null) {
                 log.error("SAML 1 Attribute Query profile is not configured for relying party "
-                        + requestContext.getRelyingPartyId());
+                        + requestContext.getInboundMessageIssuer());
                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
                         "SAML 1 Attribute Query profile is not configured for relying party "
-                                + requestContext.getRelyingPartyId()));
+                                + requestContext.getInboundMessageIssuer()));
                 samlResponse = buildErrorResponse(requestContext);
-            }
+            } else {
+                resolvePrincipal(requestContext);
+
+                Session idpSession = getSessionManager().getSession(requestContext.getPrincipalName());
+                if (idpSession != null) {
+                    AuthenticationMethodInformation authnInfo = idpSession.getAuthenticationMethods().get(
+                            requestContext.getInboundMessageIssuer());
+                    if (authnInfo != null) {
+                        requestContext.setPrincipalAuthenticationMethod(authnInfo.getAuthenticationMethod());
+                    }
+                }
 
-            resolvePrincipal(requestContext);
+                resolveAttributes(requestContext);
+                requestContext.setReleasedAttributes(requestContext.getAttributes().keySet());
 
-            ArrayList<Statement> statements = new ArrayList<Statement>();
-            statements.add(buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches"));
+                ArrayList<Statement> statements = new ArrayList<Statement>();
+                AttributeStatement attributeStatement = buildAttributeStatement(requestContext,
+                        "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches");
+                if (attributeStatement != null) {
+                    statements.add(attributeStatement);
+                }
 
-            samlResponse = buildResponse(requestContext, statements);
+                samlResponse = buildResponse(requestContext, statements);
+            }
         } catch (ProfileException e) {
             samlResponse = buildErrorResponse(requestContext);
         }
 
-        requestContext.setSamlResponse(samlResponse);
+        requestContext.setOutboundSAMLMessage(samlResponse);
+        requestContext.setOutboundSAMLMessageId(samlResponse.getID());
+        requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
         encodeResponse(requestContext);
+        writeAuditLogEntry(requestContext);
     }
 
     /**
-     * Decodes the message in the request and adds it to the request context.
+     * Decodes an incoming request and populates a created request context with the resultant information.
      * 
-     * @param requestContext request context contianing the request to decode
+     * @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 void decodeRequest(AttributeQueryContext requestContext) throws ProfileException {
-        if (log.isDebugEnabled()) {
-            log.debug("Decoding incomming request");
-        }
-        MessageDecoder<ServletRequest> decoder = getMessageDecoderFactory().getMessageDecoder(
-                HTTPSOAP11Decoder.BINDING_URI);
-        if (decoder == null) {
-            throw new ProfileException("No request decoder was registered for binding type: "
-                    + HTTPSOAP11Decoder.BINDING_URI);
-        }
-        super.populateMessageDecoder(decoder);
+    protected AttributeQueryContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
+            throws ProfileException {
+        log.debug("Decoding message with decoder binding {}", getInboundBinding());
+
+        AttributeQueryContext requestContext = new AttributeQueryContext();
+
+        MetadataProvider metadataProvider = getMetadataProvider();
+        requestContext.setMetadataProvider(metadataProvider);
+
+        requestContext.setInboundMessageTransport(inTransport);
+        requestContext.setInboundSAMLProtocol(SAMLConstants.SAML11P_NS);
+        requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
+        requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
 
-        ProfileRequest<ServletRequest> profileRequest = requestContext.getProfileRequest();
-        decoder.setRequest(profileRequest.getRawRequest());
-        requestContext.setMessageDecoder(decoder);
+        requestContext.setOutboundMessageTransport(outTransport);
+        requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
 
         try {
-            decoder.decode();
-            if (log.isDebugEnabled()) {
-                log.debug("Decoded request");
+            SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
+            if (decoder == null) {
+                throw new ProfileException("No message decoder configured for inbound binding " + getInboundBinding());
             }
-        } catch (BindingException e) {
+            requestContext.setMessageDecoder(decoder);
+            decoder.decode(requestContext);
+            log.debug("Decoded request");
+
+            Request request = requestContext.getInboundSAMLMessage();
+            if (request == null || !(request instanceof Request) || request.getAttributeQuery() == null) {
+                log.error("Incoming message was not an Attribute request");
+                requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER, null,
+                        "Invalid SAML Attribute Request message."));
+                throw new ProfileException("Invalid SAML Attribute Request message.");
+            }
+
+            return requestContext;
+        } catch (MessageDecodingException e) {
             log.error("Error decoding attribute query message", e);
             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error decoding message"));
             throw new ProfileException("Error decoding attribute query 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, StatusCode.REQUEST_DENIED,
-                    "Message did not meet security policy requirements"));
+                    "Message did not meet security 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
-            SAMLSecurityPolicy securityPolicy = requestContext.getMessageDecoder().getSecurityPolicy();
-            requestContext.setRelyingPartyId(securityPolicy.getIssuer());
-
-            Request request = (Request) requestContext.getMessageDecoder().getSAMLMessage();
-            requestContext.setSamlRequest(request);
-            requestContext.setAttributeQuery(request.getAttributeQuery());
-
-            populateRelyingPartyData(requestContext);
-
-            populateAssertingPartyData(requestContext);
+            populateRequestContext(requestContext);
+            populateSAMLMessageInformation(requestContext);
+            populateProfileInformation(requestContext);
         }
     }
 
-    /**
-     * Populates the relying party entity and role metadata and relying party configuration data.
-     * 
-     * @param requestContext current request context with relying party ID populated
-     * 
-     * @throws ProfileException thrown if metadata can not be located for the relying party
-     */
-    protected void populateRelyingPartyData(AttributeQueryContext requestContext) throws ProfileException {
-        try {
-            requestContext.setRelyingPartyMetadata(getMetadataProvider().getEntityDescriptor(
-                    requestContext.getRelyingPartyId()));
-
-            RoleDescriptor relyingPartyRole = requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
-                    ShibbolethConstants.SAML11P_NS);
-
-            if (relyingPartyRole == null) {
-                relyingPartyRole = requestContext.getRelyingPartyMetadata()
-                        .getSPSSODescriptor(ShibbolethConstants.SAML10P_NS);
-                if (relyingPartyRole == null) {
-                    throw new MetadataProviderException("Unable to locate SPSSO role descriptor for entity "
-                            + requestContext.getRelyingPartyId());
-                }
-            }
-            requestContext.setRelyingPartyRoleMetadata(relyingPartyRole);
+    /** {@inheritDoc} */
+    protected void populateRelyingPartyInformation(BaseSAMLProfileRequestContext requestContext)
+            throws ProfileException {
+        super.populateRelyingPartyInformation(requestContext);
 
-            RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(requestContext.getRelyingPartyId());
-            requestContext.setRelyingPartyConfiguration(rpConfig);
+        EntityDescriptor relyingPartyMetadata = requestContext.getPeerEntityMetadata();
+        if (relyingPartyMetadata != null) {
+            requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
+            requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML11P_NS));
+        }
+    }
 
-            requestContext.setProfileConfiguration((AttributeQueryConfiguration) rpConfig
-                    .getProfileConfiguration(AttributeQueryConfiguration.PROFILE_ID));
+    /** {@inheritDoc} */
+    protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
+            throws ProfileException {
+        super.populateAssertingPartyInformation(requestContext);
 
-        } catch (MetadataProviderException e) {
-            log.error("Unable to locate metadata for relying party " + requestContext.getRelyingPartyId());
-            requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
-                    "Unable to locate metadata for relying party " + requestContext.getRelyingPartyId()));
-            throw new ProfileException("Unable to locate metadata for relying party "
-                    + requestContext.getRelyingPartyId());
+        EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
+        if (localEntityDescriptor != null) {
+            requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
+            requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
+                    .getAttributeAuthorityDescriptor(SAMLConstants.SAML11P_NS));
         }
     }
 
     /**
-     * Populates the asserting party entity and role metadata.
+     * 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
      * 
-     * @param requestContext current request context with relying party configuration populated
+     * This methods populates the following request context properties: subject name identifier
      * 
-     * @throws ProfileException thrown if metadata can not be located for the asserting party
+     * @param requestContext current request context
+     * 
+     * @throws ProfileException thrown if the inbound SAML message or subject identifier is null
      */
-    protected void populateAssertingPartyData(AttributeQueryContext requestContext) throws ProfileException {
-        String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
-
-        try {
-            requestContext.setAssertingPartyId(assertingPartyId);
-
-            requestContext.setAssertingPartyMetadata(getMetadataProvider().getEntityDescriptor(assertingPartyId));
-
-            RoleDescriptor assertingPartyRole = requestContext.getAssertingPartyMetadata()
-                    .getAttributeAuthorityDescriptor(ShibbolethConstants.SAML11P_NS);
+    protected void populateSAMLMessageInformation(BaseSAMLProfileRequestContext requestContext) throws ProfileException {
+        Request request = (Request) requestContext.getInboundSAMLMessage();
+        if (request == null) {
+            log.error("Decoder did not contain an attribute query, an error occured decoding the message");
+            throw new ProfileException("Unable to decode message.");
+        }
 
-            if (assertingPartyRole == null) {
-                assertingPartyRole = requestContext.getAssertingPartyMetadata().getAttributeAuthorityDescriptor(
-                        ShibbolethConstants.SAML10P_NS);
-                if (assertingPartyRole == null) {
-                    throw new MetadataProviderException("Unable to locate IDPSSO role descriptor for entity "
-                            + assertingPartyId);
-                }
+        AttributeQuery query = request.getAttributeQuery();
+        if (query != null) {
+            Subject subject = query.getSubject();
+            if (subject == null) {
+                log.error("Attribute query did not contain a proper subject");
+                ((AttributeQueryContext) requestContext).setFailureStatus(buildStatus(StatusCode.REQUESTER, null,
+                        "Attribute query did not contain a proper subject"));
+                throw new ProfileException("Attribute query did not contain a proper subject");
             }
-            requestContext.setAssertingPartyRoleMetadata(assertingPartyRole);
-        } catch (MetadataProviderException e) {
-            log.error("Unable to locate metadata for asserting party " + assertingPartyId);
-            requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
-                    "Unable to locate metadata for relying party " + assertingPartyId));
-            throw new ProfileException("Unable to locate metadata for relying party " + assertingPartyId);
+            requestContext.setSubjectNameIdentifier(subject.getNameIdentifier());
         }
     }
 
     /**
-     * Encodes the request's SAML response and writes it to the servlet response.
+     * Selects the appropriate endpoint for the relying party and stores it in the request context.
      * 
      * @param requestContext current request context
      * 
-     * @throws ProfileException thrown if no message encoder is registered for this profiles binding
+     * @return Endpoint selected from the information provided in the request context
      */
-    protected void encodeResponse(AttributeQueryContext requestContext) throws ProfileException {
-        if (log.isDebugEnabled()) {
-            log.debug("Encoding response to SAML request from relying party " + requestContext.getRelyingPartyId());
-        }
-        MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(
-                HTTPSOAP11Encoder.BINDING_URI);
-        if (encoder == null) {
-            throw new ProfileException("No response encoder was registered for binding type: "
-                    + HTTPSOAP11Encoder.BINDING_URI);
+    protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
+        Endpoint endpoint;
+
+        if (getInboundBinding().equals(SAMLConstants.SAML1_SOAP11_BINDING_URI)) {
+            endpoint = acsEndpointBuilder.buildObject();
+            endpoint.setBinding(SAMLConstants.SAML1_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();
         }
 
-        super.populateMessageEncoder(encoder);
-        ProfileResponse<ServletResponse> profileResponse = requestContext.getProfileResponse();
-        encoder.setResponse(profileResponse.getRawResponse());
-        encoder.setSamlMessage(requestContext.getSamlResponse());
-        requestContext.setMessageEncoder(encoder);
-
-        try {
-            encoder.encode();
-        } catch (BindingException e) {
-            throw new ProfileException("Unable to encode response to relying party: "
-                    + requestContext.getRelyingPartyId(), e);
-        }
+        return endpoint;
     }
 
     /** Basic data structure used to accumulate information as a request is being processed. */
     protected class AttributeQueryContext extends
-            SAML1ProfileRequestContext<Request, Response, AttributeQueryConfiguration> {
-        
-        private AttributeQuery attributeQuery;
-
-        /**
-         * Constructor.
-         * 
-         * @param request current profile request
-         * @param response current profile response
-         */
-        public AttributeQueryContext(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) {
-            super(request, response);
-        }
-        
-        public AttributeQuery getAttributeQuery(){
-            return attributeQuery;
-        }
-        
-        public void setAttributeQuery(AttributeQuery query){
-            attributeQuery = query;
-        }
-    }
+            BaseSAML1ProfileRequestContext<Request, Response, AttributeQueryConfiguration> {}
 }
\ No newline at end of file