0216db3127a1961a09337cdaca071fb0ea2581bc
[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.core.Subject;
31 import org.opensaml.saml2.metadata.AssertionConsumerService;
32 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
33 import org.opensaml.saml2.metadata.Endpoint;
34 import org.opensaml.saml2.metadata.EntityDescriptor;
35 import org.opensaml.saml2.metadata.SPSSODescriptor;
36 import org.opensaml.saml2.metadata.provider.MetadataProvider;
37 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
38 import org.opensaml.ws.message.decoder.MessageDecodingException;
39 import org.opensaml.ws.transport.http.HTTPInTransport;
40 import org.opensaml.ws.transport.http.HTTPOutTransport;
41 import org.opensaml.xml.security.SecurityException;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
46 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
47 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AttributeQueryConfiguration;
48 import edu.internet2.middleware.shibboleth.idp.session.AuthenticationMethodInformation;
49 import edu.internet2.middleware.shibboleth.idp.session.Session;
50
51 /** SAML 2.0 Attribute Query profile handler. */
52 public class AttributeQueryProfileHandler extends AbstractSAML2ProfileHandler {
53
54     /** Class logger. */
55     private static Logger log = LoggerFactory.getLogger(AttributeQueryProfileHandler.class);
56
57     /** Builder of assertion consumer service endpoints. */
58     private SAMLObjectBuilder<AssertionConsumerService> acsEndpointBuilder;
59
60     /** Constructor. */
61     public AttributeQueryProfileHandler() {
62         super();
63
64         acsEndpointBuilder = (SAMLObjectBuilder<AssertionConsumerService>) getBuilderFactory().getBuilder(
65                 AssertionConsumerService.DEFAULT_ELEMENT_NAME);
66     }
67
68     /** {@inheritDoc} */
69     public String getProfileId() {
70         return "urn:mace:shibboleth:2.0:idp:profiles:saml2:query:attribute";
71     }
72
73     /** {@inheritDoc} */
74     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
75         Response samlResponse;
76
77         AttributeQueryContext requestContext = decodeRequest(inTransport, outTransport);
78
79         try {
80             if (requestContext.getProfileConfiguration() == null) {
81                 log.error("SAML 2 Attribute Query profile is not configured for relying party "
82                         + requestContext.getInboundMessageIssuer());
83                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
84                         "SAML 2 Attribute Query profile is not configured for relying party "
85                                 + requestContext.getInboundMessageIssuer()));
86                 samlResponse = buildErrorResponse(requestContext);
87             } else {
88                 checkSamlVersion(requestContext);
89
90                 // Resolve attribute query name id to principal name and place in context
91                 resolvePrincipal(requestContext);
92
93                 Session idpSession = getSessionManager().getSession(requestContext.getPrincipalName());
94                 if (idpSession != null) {
95                     AuthenticationMethodInformation authnInfo = idpSession.getAuthenticationMethods().get(
96                             requestContext.getInboundMessageIssuer());
97                     if (authnInfo != null) {
98                         requestContext.setPrincipalAuthenticationMethod(authnInfo.getAuthenticationMethod());
99                     }
100                 }
101
102                 resolveAttributes(requestContext);
103                 requestContext.setReleasedAttributes(requestContext.getAttributes().keySet());
104
105                 // Lookup principal name and attributes, create attribute statement from information
106                 ArrayList<Statement> statements = new ArrayList<Statement>();
107                 AttributeStatement attributeStatement = buildAttributeStatement(requestContext);
108                 if (attributeStatement != null) {
109                     statements.add(attributeStatement);
110                 }
111
112                 // create the SAML response
113                 samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:sender-vouches",
114                         statements);
115             }
116         } catch (ProfileException e) {
117             samlResponse = buildErrorResponse(requestContext);
118         }
119
120         requestContext.setOutboundSAMLMessage(samlResponse);
121         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
122         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
123
124         encodeResponse(requestContext);
125         writeAuditLogEntry(requestContext);
126     }
127
128     /**
129      * Decodes an incoming request and populates a created request context with the resultant information.
130      * 
131      * @param inTransport inbound message transport
132      * @param outTransport outbound message transport
133      * 
134      * @return the created request context
135      * 
136      * @throws ProfileException throw if there is a problem decoding the request
137      */
138     protected AttributeQueryContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
139             throws ProfileException {
140         log.debug("Decoding message with decoder binding {}", getInboundBinding());
141
142         MetadataProvider metadataProvider = getMetadataProvider();
143
144         AttributeQueryContext requestContext = new AttributeQueryContext();
145         requestContext.setMetadataProvider(metadataProvider);
146         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
147
148         requestContext.setCommunicationProfileId(AttributeQueryConfiguration.PROFILE_ID);
149         requestContext.setInboundMessageTransport(inTransport);
150         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
151         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
152
153         requestContext.setOutboundMessageTransport(outTransport);
154         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
155
156         try {
157             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
158             requestContext.setMessageDecoder(decoder);
159             decoder.decode(requestContext);
160             log.debug("Decoded request");
161
162             if (!(requestContext.getInboundSAMLMessage() instanceof AttributeQuery)) {
163                 log.error("Incoming message was not a AttributeQuery, it was a {}", requestContext
164                         .getInboundSAMLMessage().getClass().getName());
165                 requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER_URI, null,
166                         "Invalid SAML AttributeQuery message."));
167                 throw new ProfileException("Invalid SAML AttributeQuery message.");
168             }
169
170             return requestContext;
171         } catch (MessageDecodingException e) {
172             log.error("Error decoding attribute query message", e);
173             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error decoding message"));
174             throw new ProfileException("Error decoding attribute query message");
175         } catch (SecurityException e) {
176             log.error("Message did not meet security requirements", e);
177             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
178                     "Message did not meet security requirements"));
179             throw new ProfileException("Message did not meet security requirements", e);
180         } finally {
181             // Set as much information as can be retrieved from the decoded message
182             AttributeQuery query = requestContext.getInboundSAMLMessage();
183             if (query != null) {
184                 Subject subject = query.getSubject();
185                 if (subject == null) {
186                     log.error("Attribute query did not contain a proper subject");
187                     requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER_URI, null,
188                             "Attribute query did not contain a proper subject"));
189                     throw new ProfileException("Attribute query did not contain a proper subject");
190                 }
191                 requestContext.setSubjectNameIdentifier(subject.getNameID());
192             }
193
194             String relyingPartyId = requestContext.getInboundMessageIssuer();
195             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
196             if (rpConfig == null) {
197                 log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
198                 throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
199                         + relyingPartyId);
200             }
201             requestContext.setRelyingPartyConfiguration(rpConfig);
202
203             AttributeQueryConfiguration profileConfig = (AttributeQueryConfiguration) rpConfig
204                     .getProfileConfiguration(AttributeQueryConfiguration.PROFILE_ID);
205             if (profileConfig != null) {
206                 requestContext.setProfileConfiguration(profileConfig);
207                 requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
208             }
209
210             requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
211
212             String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
213             requestContext.setLocalEntityId(assertingPartyId);
214             requestContext.setOutboundMessageIssuer(assertingPartyId);
215             try {
216                 EntityDescriptor localEntityDescriptor = metadataProvider.getEntityDescriptor(assertingPartyId);
217                 if (localEntityDescriptor != null) {
218                     requestContext.setLocalEntityMetadata(localEntityDescriptor);
219                     requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
220                     requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
221                             .getAttributeAuthorityDescriptor(SAMLConstants.SAML20P_NS));
222                 }
223             } catch (MetadataProviderException e) {
224                 log.error("Unable to locate metadata for asserting party");
225                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
226                         "Error locating asserting party metadata"));
227                 throw new ProfileException("Error locating asserting party metadata");
228             }
229         }
230     }
231
232     /**
233      * Selects the appropriate endpoint for the relying party and stores it in the request context.
234      * 
235      * @param requestContext current request context
236      * 
237      * @return Endpoint selected from the information provided in the request context
238      */
239     protected Endpoint selectEndpoint(AttributeQueryContext requestContext) {
240         Endpoint endpoint;
241
242         if (getInboundBinding().equals(SAMLConstants.SAML2_SOAP11_BINDING_URI)) {
243             endpoint = acsEndpointBuilder.buildObject();
244             endpoint.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI);
245         } else {
246             BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
247             endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
248             endpointSelector.setMetadataProvider(getMetadataProvider());
249             endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
250             endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
251             endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
252             endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
253             endpoint = endpointSelector.selectEndpoint();
254         }
255
256         return endpoint;
257     }
258
259     /** Basic data structure used to accumulate information as a request is being processed. */
260     protected class AttributeQueryContext extends
261             BaseSAML2ProfileRequestContext<AttributeQuery, Response, AttributeQueryConfiguration> {
262
263     }
264 }