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