Set communication profile before decoding
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml1 / AttributeQueryProfileHandler.java
index bdefac4..498ba61 100644 (file)
@@ -23,17 +23,18 @@ 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.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.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;
@@ -42,8 +43,10 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
-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.
@@ -66,15 +69,16 @@ public class AttributeQueryProfileHandler extends AbstractSAML1ProfileHandler {
 
     /** {@inheritDoc} */
     public String getProfileId() {
-        return "urn:mace:shibboleth:2.0:idp:profiles:saml1:query:attribute";
+        return AttributeQueryConfiguration.PROFILE_ID;
     }
 
     /** {@inheritDoc} */
     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
-        AttributeQueryContext requestContext = decodeRequest(inTransport, outTransport);
-
+        AttributeQueryContext requestContext = null;
         Response samlResponse;
         try {
+            requestContext = decodeRequest(inTransport, outTransport);
+            
             if (requestContext.getProfileConfiguration() == null) {
                 log.error("SAML 1 Attribute Query profile is not configured for relying party "
                         + requestContext.getInboundMessageIssuer());
@@ -84,13 +88,24 @@ public class AttributeQueryProfileHandler extends AbstractSAML1ProfileHandler {
                 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());
+                    }
+                }
+
                 resolveAttributes(requestContext);
-                requestContext.setReleasedAttributes(requestContext.getPrincipalAttributes().keySet());
+                requestContext.setReleasedAttributes(requestContext.getAttributes().keySet());
 
                 ArrayList<Statement> statements = new ArrayList<Statement>();
-                if (!requestContext.getPrincipalAttributes().isEmpty()) {
-                    statements.add(buildAttributeStatement(requestContext,
-                            "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches"));
+                AttributeStatement attributeStatement = buildAttributeStatement(requestContext,
+                        "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches");
+                if (attributeStatement != null) {
+                    statements.add(attributeStatement);
                 }
 
                 samlResponse = buildResponse(requestContext, statements);
@@ -118,17 +133,17 @@ public class AttributeQueryProfileHandler extends AbstractSAML1ProfileHandler {
      */
     protected AttributeQueryContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
             throws ProfileException {
-        log.debug("Decoding incomming request");
-
-        MetadataProvider metadataProvider = getMetadataProvider();
+        log.debug("Decoding message with decoder binding {}", getInboundBinding());
 
         AttributeQueryContext requestContext = new AttributeQueryContext();
+        requestContext.setCommunicationProfileId(getProfileId());
+
+        MetadataProvider metadataProvider = getMetadataProvider();
         requestContext.setMetadataProvider(metadataProvider);
-        requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
 
-        requestContext.setCommunicationProfileId(AttributeQueryConfiguration.PROFILE_ID);
         requestContext.setInboundMessageTransport(inTransport);
         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML11P_NS);
+        requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
 
         requestContext.setOutboundMessageTransport(outTransport);
@@ -142,6 +157,15 @@ public class AttributeQueryProfileHandler extends AbstractSAML1ProfileHandler {
             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);
@@ -154,53 +178,63 @@ public class AttributeQueryProfileHandler extends AbstractSAML1ProfileHandler {
             throw new ProfileException("Message did not meet security policy requirements", e);
         } finally {
             // Set as much information as can be retrieved from the decoded message
+            populateRequestContext(requestContext);
+        }
+    }
 
-            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.");
-            }
-            AttributeQuery query = request.getAttributeQuery();
-            requestContext.setSubjectNameIdentifier(query.getSubject().getNameIdentifier());
-
-            String relyingPartyId = requestContext.getInboundMessageIssuer();
-            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);
-            }
-            requestContext.setRelyingPartyConfiguration(rpConfig);
-
-            AttributeQueryConfiguration profileConfig = (AttributeQueryConfiguration) rpConfig
-                    .getProfileConfiguration(AttributeQueryConfiguration.PROFILE_ID);
-            if (profileConfig != null) {
-                requestContext.setProfileConfiguration(profileConfig);
-                requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
-                if (profileConfig.getSigningCredential() != null) {
-                    requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
-                } else if (rpConfig.getDefaultSigningCredential() != null) {
-                    requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
-                }
-            }
-            requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
-
-            String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
-            requestContext.setLocalEntityId(assertingPartyId);
-            try {
-                EntityDescriptor localEntityDescriptor = metadataProvider.getEntityDescriptor(assertingPartyId);
-                if (localEntityDescriptor != null) {
-                    requestContext.setLocalEntityMetadata(localEntityDescriptor);
-                    requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
-                    requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
-                            .getAttributeAuthorityDescriptor(SAMLConstants.SAML11P_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");
+    /** {@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));
+        }
+    }
+
+    /** {@inheritDoc} */
+    protected void populateAssertingPartyInformation(BaseSAMLProfileRequestContext requestContext)
+            throws ProfileException {
+        super.populateAssertingPartyInformation(requestContext);
+
+        EntityDescriptor localEntityDescriptor = requestContext.getLocalEntityMetadata();
+        if (localEntityDescriptor != null) {
+            requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
+            requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
+                    .getAttributeAuthorityDescriptor(SAMLConstants.SAML11P_NS));
+        }
+    }
+
+    /**
+     * 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
+     * 
+     * This methods populates the following request context properties: 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 {
+        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.");
+        }
+
+        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.setSubjectNameIdentifier(subject.getNameIdentifier());
         }
     }
 
@@ -211,7 +245,7 @@ public class AttributeQueryProfileHandler extends AbstractSAML1ProfileHandler {
      * 
      * @return Endpoint selected from the information provided in the request context
      */
-    protected Endpoint selectEndpoint(AttributeQueryContext requestContext) {
+    protected Endpoint selectEndpoint(BaseSAMLProfileRequestContext requestContext) {
         Endpoint endpoint;
 
         if (getInboundBinding().equals(SAMLConstants.SAML1_SOAP11_BINDING_URI)) {