Fix bug SIDP-58
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml2 / AttributeQueryProfileHandler.java
1 /*
2  * Copyright [2006] [University Corporation for Advanced Internet Development, Inc.]
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package edu.internet2.middleware.shibboleth.idp.profile.saml2;
18
19 import java.util.ArrayList;
20
21 import org.opensaml.common.SAMLObjectBuilder;
22 import org.opensaml.common.binding.BasicEndpointSelector;
23 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
24 import org.opensaml.common.xml.SAMLConstants;
25 import org.opensaml.saml2.core.AttributeQuery;
26 import org.opensaml.saml2.core.AttributeStatement;
27 import org.opensaml.saml2.core.Response;
28 import org.opensaml.saml2.core.Statement;
29 import org.opensaml.saml2.core.StatusCode;
30 import org.opensaml.saml2.metadata.AssertionConsumerService;
31 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
32 import org.opensaml.saml2.metadata.Endpoint;
33 import org.opensaml.saml2.metadata.EntityDescriptor;
34 import org.opensaml.saml2.metadata.SPSSODescriptor;
35 import org.opensaml.saml2.metadata.provider.MetadataProvider;
36 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
37 import org.opensaml.ws.message.decoder.MessageDecodingException;
38 import org.opensaml.ws.transport.http.HTTPInTransport;
39 import org.opensaml.ws.transport.http.HTTPOutTransport;
40 import org.opensaml.xml.security.SecurityException;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
45 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
46 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AttributeQueryConfiguration;
47
48 /** SAML 2.0 Attribute Query profile handler. */
49 public class AttributeQueryProfileHandler extends AbstractSAML2ProfileHandler {
50
51     /** Class logger. */
52     private static Logger log = LoggerFactory.getLogger(AttributeQueryProfileHandler.class);
53
54     /** Builder of assertion consumer service endpoints. */
55     private SAMLObjectBuilder<AssertionConsumerService> acsEndpointBuilder;
56
57     /** Constructor. */
58     public AttributeQueryProfileHandler() {
59         super();
60
61         acsEndpointBuilder = (SAMLObjectBuilder<AssertionConsumerService>) getBuilderFactory().getBuilder(
62                 AssertionConsumerService.DEFAULT_ELEMENT_NAME);
63     }
64
65     /** {@inheritDoc} */
66     public String getProfileId() {
67         return "urn:mace:shibboleth:2.0:idp:profiles:saml2:query:attribute";
68     }
69
70     /** {@inheritDoc} */
71     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
72         Response samlResponse;
73
74         AttributeQueryContext requestContext = decodeRequest(inTransport, outTransport);
75
76         try {
77             if (requestContext.getProfileConfiguration() == null) {
78                 log.error("SAML 2 Attribute Query profile is not configured for relying party "
79                         + requestContext.getInboundMessageIssuer());
80                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
81                         "SAML 2 Attribute Query profile is not configured for relying party "
82                                 + requestContext.getInboundMessageIssuer()));
83                 throw new ProfileException("SAML 2 Attribute Query profile is not configured for relying party "
84                         + requestContext.getInboundMessageIssuer());
85             }
86
87             checkSamlVersion(requestContext);
88
89             // Resolve attribute query name id to principal name and place in context
90             resolvePrincipal(requestContext);
91             resolveAttributes(requestContext);
92             requestContext.setReleasedAttributes(requestContext.getPrincipalAttributes().keySet());
93
94             // Lookup principal name and attributes, create attribute statement from information
95             ArrayList<Statement> statements = new ArrayList<Statement>();
96             AttributeStatement attributeStatement = buildAttributeStatement(requestContext);
97             if (attributeStatement != null) {
98                 statements.add(attributeStatement);
99             }
100
101             // create the SAML response
102             samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:sender-vouches", statements);
103         } catch (ProfileException e) {
104             samlResponse = buildErrorResponse(requestContext);
105         }
106
107         requestContext.setOutboundSAMLMessage(samlResponse);
108         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
109         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
110
111         encodeResponse(requestContext);
112         writeAuditLogEntry(requestContext);
113     }
114
115     /**
116      * Decodes an incoming request and populates a created request context with the resultant information.
117      * 
118      * @param inTransport inbound message transport
119      * @param outTransport outbound message transport
120      * 
121      * @return the created request context
122      * 
123      * @throws ProfileException throw if there is a problem decoding the request
124      */
125     protected AttributeQueryContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
126             throws ProfileException {
127         log.debug("Decoding incomming request");
128
129         MetadataProvider metadataProvider = getMetadataProvider();
130
131         AttributeQueryContext requestContext = new AttributeQueryContext();
132         requestContext.setMetadataProvider(metadataProvider);
133         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
134
135         requestContext.setCommunicationProfileId(AttributeQueryConfiguration.PROFILE_ID);
136         requestContext.setInboundMessageTransport(inTransport);
137         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
138         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
139
140         requestContext.setOutboundMessageTransport(outTransport);
141         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
142
143         try {
144             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
145             requestContext.setMessageDecoder(decoder);
146             decoder.decode(requestContext);
147             log.debug("Decoded request");
148             return requestContext;
149         } catch (MessageDecodingException e) {
150             log.error("Error decoding attribute query message", e);
151             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error decoding message"));
152             throw new ProfileException("Error decoding attribute query message");
153         } catch (SecurityException e) {
154             log.error("Message did not meet security requirements", e);
155             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
156                     "Message did not meet security requirements"));
157             throw new ProfileException("Message did not meet security requirements", e);
158         } finally {
159             // Set as much information as can be retrieved from the decoded message
160             AttributeQuery query = requestContext.getInboundSAMLMessage();
161             requestContext.setSubjectNameIdentifier(query.getSubject().getNameID());
162
163             String relyingPartyId = requestContext.getInboundMessageIssuer();
164             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
165             if (rpConfig == null) {
166                 log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
167                 throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
168                         + relyingPartyId);
169             }
170             requestContext.setRelyingPartyConfiguration(rpConfig);
171
172             AttributeQueryConfiguration profileConfig = (AttributeQueryConfiguration) rpConfig
173                     .getProfileConfiguration(AttributeQueryConfiguration.PROFILE_ID);
174             if (profileConfig != null) {
175                 requestContext.setProfileConfiguration(profileConfig);
176                 requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
177                 if (profileConfig.getSigningCredential() != null) {
178                     requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
179                 } else if (rpConfig.getDefaultSigningCredential() != null) {
180                     requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
181                 }
182             }
183
184             requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
185
186             String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
187             requestContext.setLocalEntityId(assertingPartyId);
188             try {
189                 EntityDescriptor localEntityDescriptor = metadataProvider.getEntityDescriptor(assertingPartyId);
190                 if (localEntityDescriptor != null) {
191                     requestContext.setLocalEntityMetadata(localEntityDescriptor);
192                     requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
193                     requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
194                             .getAttributeAuthorityDescriptor(SAMLConstants.SAML20P_NS));
195                 }
196             } catch (MetadataProviderException e) {
197                 log.error("Unable to locate metadata for asserting party");
198                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
199                         "Error locating asserting party metadata"));
200                 throw new ProfileException("Error locating asserting party metadata");
201             }
202         }
203     }
204
205     /**
206      * Selects the appropriate endpoint for the relying party and stores it in the request context.
207      * 
208      * @param requestContext current request context
209      * 
210      * @return Endpoint selected from the information provided in the request context
211      */
212     protected Endpoint selectEndpoint(AttributeQueryContext requestContext) {
213         Endpoint endpoint;
214
215         if (getInboundBinding().equals(SAMLConstants.SAML2_SOAP11_BINDING_URI)) {
216             endpoint = acsEndpointBuilder.buildObject();
217             endpoint.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI);
218         } else {
219             BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
220             endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
221             endpointSelector.setMetadataProvider(getMetadataProvider());
222             endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
223             endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
224             endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
225             endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
226             endpoint = endpointSelector.selectEndpoint();
227         }
228
229         return endpoint;
230     }
231
232     /** Basic data structure used to accumulate information as a request is being processed. */
233     protected class AttributeQueryContext extends
234             BaseSAML2ProfileRequestContext<AttributeQuery, Response, AttributeQueryConfiguration> {
235
236     }
237 }