Now with SAML 1 attribute query goodness (though not yet tested)
[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 import java.util.Map;
21
22 import javax.servlet.ServletRequest;
23 import javax.servlet.ServletResponse;
24
25 import org.apache.log4j.Logger;
26 import org.opensaml.common.binding.BindingException;
27 import org.opensaml.common.binding.decoding.MessageDecoder;
28 import org.opensaml.common.binding.encoding.MessageEncoder;
29 import org.opensaml.common.binding.security.SAMLSecurityPolicy;
30 import org.opensaml.saml2.binding.decoding.HTTPSOAP11Decoder;
31 import org.opensaml.saml2.core.AttributeQuery;
32 import org.opensaml.saml2.core.AttributeStatement;
33 import org.opensaml.saml2.core.NameID;
34 import org.opensaml.saml2.core.Response;
35 import org.opensaml.saml2.core.Statement;
36 import org.opensaml.saml2.core.StatusCode;
37 import org.opensaml.saml2.core.Subject;
38 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
39 import org.opensaml.saml2.metadata.SPSSODescriptor;
40 import org.opensaml.ws.security.SecurityPolicyException;
41
42 import edu.internet2.middleware.shibboleth.common.attribute.AttributeRequestException;
43 import edu.internet2.middleware.shibboleth.common.attribute.BaseAttribute;
44 import edu.internet2.middleware.shibboleth.common.attribute.provider.SAML2AttributeAuthority;
45 import edu.internet2.middleware.shibboleth.common.attribute.provider.ShibbolethSAMLAttributeRequestContext;
46 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
47 import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
48 import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
49 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
50 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AttributeQueryConfiguration;
51 import edu.internet2.middleware.shibboleth.idp.session.ServiceInformation;
52 import edu.internet2.middleware.shibboleth.idp.session.Session;
53
54 /**
55  * SAML 2.0 Attribute Query profile handler.
56  */
57 public class AttributeQueryProfileHandler extends AbstractSAML2ProfileHandler {
58
59     /** Class logger. */
60     private static Logger log = Logger.getLogger(AttributeQueryProfileHandler.class);
61
62     /** SAML binding URI. */
63     private static final String BINDING = "urn:oasis:names:tc:SAML:2.0:bindings:SOAP";
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(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response)
72             throws ProfileException {
73
74         AttributeQueryContext requestContext = new AttributeQueryContext(request, response);
75
76         Response samlResponse;
77         try {
78             decodeRequest(requestContext);
79
80             // Lookup principal name and attributes, create attribute statement from information
81             ArrayList<Statement> statements = new ArrayList<Statement>();
82             statements.add(buildAttributeStatement(requestContext));
83
84             // create the assertion subject
85             Subject assertionSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:sender-vouches");
86
87             // create the SAML response
88             samlResponse = buildResponse(requestContext, assertionSubject, statements);
89         } catch (SecurityPolicyException e) {
90             samlResponse = buildErrorResponse(requestContext, StatusCode.REQUESTER_URI, StatusCode.REQUEST_DENIED_URI,
91                     e.getMessage());
92         } catch (AttributeRequestException e) {
93             samlResponse = buildErrorResponse(requestContext, StatusCode.RESPONDER_URI,
94                     StatusCode.INVALID_ATTR_NAME_VALUE_URI, e.getMessage());
95         } catch (ProfileException e) {
96             samlResponse = buildErrorResponse(requestContext, StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
97                     e.getMessage());
98         }
99
100         requestContext.setSamlResponse(samlResponse);
101
102         encodeResponse(requestContext);
103         writeAuditLogEntry(requestContext);
104     }
105
106     /**
107      * Decodes the message in the request and adds it to the request context.
108      * 
109      * @param requestContext request context contianing the request to decode
110      * 
111      * @throws ProfileException throw if there is a problem decoding the request
112      * @throws SecurityPolicyException thrown if the message was decoded properly but did not meet the necessary
113      *             security policy requirements
114      */
115     protected void decodeRequest(AttributeQueryContext requestContext) throws ProfileException, SecurityPolicyException {
116         if (log.isDebugEnabled()) {
117             log.debug("Decoding incomming request");
118         }
119         MessageDecoder<ServletRequest> decoder = getMessageDecoderFactory().getMessageDecoder(
120                 HTTPSOAP11Decoder.BINDING_URI);
121         if (decoder == null) {
122             throw new ProfileException("No request decoder was registered for binding type: "
123                     + HTTPSOAP11Decoder.BINDING_URI);
124         }
125         super.populateMessageDecoder(decoder);
126
127         decoder.setRequest(requestContext.getProfileRequest().getRawRequest());
128         requestContext.setMessageDecoder(decoder);
129
130         try {
131             decoder.decode();
132             if (log.isDebugEnabled()) {
133                 log.debug("Decoded request");
134             }
135         } catch (BindingException e) {
136             log.error("Error decoding attribute query message", e);
137             throw new ProfileException("Error decoding attribute query message");
138         } finally {
139             // Set as much information as can be retrieved from the decoded message
140             SAMLSecurityPolicy securityPolicy = requestContext.getMessageDecoder().getSecurityPolicy();
141             requestContext.setRelyingPartyId(securityPolicy.getIssuer());
142
143             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(requestContext.getRelyingPartyId());
144             requestContext.setRelyingPartyConfiguration(rpConfig);
145
146             requestContext.setRelyingPartyRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
147
148             requestContext.setAssertingPartyId(requestContext.getRelyingPartyConfiguration().getProviderId());
149
150             requestContext.setAssertingPartyRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
151
152             requestContext.setProfileConfiguration((AttributeQueryConfiguration) rpConfig
153                     .getProfileConfiguration(AttributeQueryConfiguration.PROFILE_ID));
154
155             requestContext.setSamlRequest((AttributeQuery) requestContext.getMessageDecoder().getSAMLMessage());
156         }
157     }
158
159     /**
160      * Executes a query for attributes and builds a SAML attribute statement from the results.
161      * 
162      * @param requestContext current request context
163      * 
164      * @return attribute statement resulting from the query
165      * 
166      * @throws ProfileException thrown if there is a problem making the query
167      * @throws AttributeRequestException thrown if there is a problem resolving attributes
168      */
169     protected AttributeStatement buildAttributeStatement(AttributeQueryContext requestContext) throws ProfileException,
170             AttributeRequestException {
171
172         if (log.isDebugEnabled()) {
173             log.debug("Creating attribute statement in response to SAML request "
174                     + requestContext.getSamlRequest().getID() + " from relying party "
175                     + requestContext.getRelyingPartyId());
176         }
177
178         try {
179             AttributeQueryConfiguration profileConfiguration = requestContext.getProfileConfiguration();
180             if (profileConfiguration == null) {
181                 log.error("No SAML 2 attribute query profile configuration is defined for relying party: "
182                         + requestContext.getRelyingPartyId());
183                 throw new AttributeRequestException("SAML 2 attribute query is not configured for this relying party");
184             }
185
186             SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
187
188             ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery> attributeRequestContext = buildAttributeRequestContext(requestContext);
189
190             if (log.isDebugEnabled()) {
191                 log.debug("Resolving principal name for subject of SAML request "
192                         + requestContext.getSamlRequest().getID() + " from relying party "
193                         + requestContext.getRelyingPartyId());
194             }
195             String principal = attributeAuthority.getPrincipal(attributeRequestContext);
196             requestContext.setPrincipalName(principal);
197
198             if (log.isDebugEnabled()) {
199                 log.debug("Resolving attributes for principal " + principal + " of SAML request "
200                         + requestContext.getSamlRequest().getID() + " from relying party "
201                         + requestContext.getRelyingPartyId());
202             }
203             Map<String, BaseAttribute> principalAttributes = attributeAuthority
204                     .getAttributes(buildAttributeRequestContext(requestContext));
205
206             requestContext.setPrincipalAttributes(principalAttributes);
207
208             return attributeAuthority.buildAttributeStatement(requestContext.getSamlRequest(), principalAttributes
209                     .values());
210         } catch (AttributeRequestException e) {
211             log.error("Error resolving attributes for SAML request " + requestContext.getSamlRequest().getID()
212                     + " from relying party " + requestContext.getRelyingPartyId(), e);
213             throw e;
214         }
215     }
216
217     /**
218      * Creates an attribute query context from the current profile request context.
219      * 
220      * @param requestContext current profile request
221      * 
222      * @return created query context
223      */
224     protected ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery> buildAttributeRequestContext(
225             AttributeQueryContext requestContext) {
226
227         ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery> queryContext = new ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery>(
228                 getMetadataProvider(), requestContext.getRelyingPartyConfiguration(), requestContext.getSamlRequest());
229
230         queryContext.setAttributeRequester(requestContext.getAssertingPartyId());
231         queryContext.setPrincipalName(requestContext.getPrincipalName());
232         queryContext.setProfileConfiguration(requestContext.getProfileConfiguration());
233         queryContext.setRequest(requestContext.getProfileRequest());
234
235         Session userSession = getSessionManager().getSession(getUserSessionId(requestContext.getProfileRequest()));
236         if (userSession != null) {
237             queryContext.setUserSession(userSession);
238             ServiceInformation serviceInfo = userSession.getServiceInformation(requestContext.getRelyingPartyId());
239             if (serviceInfo != null) {
240                 String principalAuthenticationMethod = serviceInfo.getAuthenticationMethod().getAuthenticationMethod();
241
242                 requestContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
243                 queryContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
244             }
245         }
246
247         return queryContext;
248     }
249
250     /**
251      * Encodes the request's SAML response and writes it to the servlet response.
252      * 
253      * @param requestContext current request context
254      * 
255      * @throws ProfileException thrown if no message encoder is registered for this profiles binding
256      */
257     protected void encodeResponse(AttributeQueryContext requestContext) throws ProfileException {
258         if (log.isDebugEnabled()) {
259             log.debug("Encoding response to SAML request " + requestContext.getSamlRequest().getID()
260                     + " from relying party " + requestContext.getRelyingPartyId());
261         }
262         MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(BINDING);
263         if (encoder == null) {
264             throw new ProfileException("No response encoder was registered for binding type: " + BINDING);
265         }
266
267         super.populateMessageEncoder(encoder);
268         encoder.setResponse(requestContext.getProfileResponse().getRawResponse());
269         encoder.setSamlMessage(requestContext.getSamlResponse());
270         requestContext.setMessageEncoder(encoder);
271
272         try {
273             encoder.encode();
274         } catch (BindingException e) {
275             throw new ProfileException("Unable to encode response to relying party: "
276                     + requestContext.getRelyingPartyId(), e);
277         }
278     }
279
280     /** Basic data structure used to accumulate information as a request is being processed. */
281     protected class AttributeQueryContext extends
282             SAML2ProfileRequestContext<AttributeQuery, Response, AttributeQueryConfiguration> {
283
284         /**
285          * Constructor.
286          * 
287          * @param request current profile request
288          * @param response current profile response
289          */
290         public AttributeQueryContext(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) {
291             super(request, response);
292         }
293     }
294 }