Populate relay state in outgoing messages
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml1 / 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.saml1;
18
19 import java.util.ArrayList;
20
21 import javax.servlet.ServletRequest;
22 import javax.servlet.ServletResponse;
23
24 import org.apache.log4j.Logger;
25 import org.opensaml.common.binding.BindingException;
26 import org.opensaml.common.binding.decoding.MessageDecoder;
27 import org.opensaml.common.binding.encoding.MessageEncoder;
28 import org.opensaml.common.binding.security.SAMLSecurityPolicy;
29 import org.opensaml.saml1.binding.decoding.HTTPSOAP11Decoder;
30 import org.opensaml.saml1.binding.encoding.HTTPSOAP11Encoder;
31 import org.opensaml.saml1.core.AttributeQuery;
32 import org.opensaml.saml1.core.Request;
33 import org.opensaml.saml1.core.Response;
34 import org.opensaml.saml1.core.Statement;
35 import org.opensaml.saml1.core.StatusCode;
36 import org.opensaml.saml2.metadata.RoleDescriptor;
37 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
38 import org.opensaml.ws.security.SecurityPolicyException;
39
40 import edu.internet2.middleware.shibboleth.common.ShibbolethConstants;
41 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
42 import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
43 import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
44 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
45 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.AttributeQueryConfiguration;
46
47 /**
48  * SAML 1 Attribute Query profile handler.
49  */
50 public class AttributeQueryProfileHandler extends AbstractSAML1ProfileHandler {
51
52     /** Class logger. */
53     private final Logger log = Logger.getLogger(AttributeQueryProfileHandler.class);
54
55     /** {@inheritDoc} */
56     public String getProfileId() {
57         return "urn:mace:shibboleth:2.0:idp:profiles:saml1:query:attribute";
58     }
59
60     /** {@inheritDoc} */
61     public void processRequest(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response)
62             throws ProfileException {
63
64         AttributeQueryContext requestContext = new AttributeQueryContext(request, response);
65
66         Response samlResponse;
67         try {
68             decodeRequest(requestContext);
69
70             if (requestContext.getRelyingPartyConfiguration() == null) {
71                 log.error("SAML 1 Attribute Query profile is not configured for relying party "
72                         + requestContext.getRelyingPartyId());
73                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
74                         "SAML 1 Attribute Query profile is not configured for relying party "
75                                 + requestContext.getRelyingPartyId()));
76                 samlResponse = buildErrorResponse(requestContext);
77             }
78
79             resolvePrincipal(requestContext);
80
81             ArrayList<Statement> statements = new ArrayList<Statement>();
82             statements.add(buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches"));
83
84             samlResponse = buildResponse(requestContext, statements);
85         } catch (ProfileException e) {
86             samlResponse = buildErrorResponse(requestContext);
87         }
88
89         requestContext.setSamlResponse(samlResponse);
90         encodeResponse(requestContext);
91     }
92
93     /**
94      * Decodes the message in the request and adds it to the request context.
95      * 
96      * @param requestContext request context contianing the request to decode
97      * 
98      * @throws ProfileException throw if there is a problem decoding the request
99      */
100     protected void decodeRequest(AttributeQueryContext requestContext) throws ProfileException {
101         if (log.isDebugEnabled()) {
102             log.debug("Decoding incomming request");
103         }
104         MessageDecoder<ServletRequest> decoder = getMessageDecoderFactory().getMessageDecoder(
105                 HTTPSOAP11Decoder.BINDING_URI);
106         if (decoder == null) {
107             throw new ProfileException("No request decoder was registered for binding type: "
108                     + HTTPSOAP11Decoder.BINDING_URI);
109         }
110         super.populateMessageDecoder(decoder);
111
112         ProfileRequest<ServletRequest> profileRequest = requestContext.getProfileRequest();
113         decoder.setRequest(profileRequest.getRawRequest());
114         requestContext.setMessageDecoder(decoder);
115
116         try {
117             decoder.decode();
118             if (log.isDebugEnabled()) {
119                 log.debug("Decoded request");
120             }
121         } catch (BindingException e) {
122             log.error("Error decoding attribute query message", e);
123             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error decoding message"));
124             throw new ProfileException("Error decoding attribute query message");
125         } catch (SecurityPolicyException e) {
126             log.error("Message did not meet security policy requirements", e);
127             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
128                     "Message did not meet security policy requirements"));
129             throw new ProfileException("Message did not meet security policy requirements", e);
130         } finally {
131             // Set as much information as can be retrieved from the decoded message
132             SAMLSecurityPolicy securityPolicy = requestContext.getMessageDecoder().getSecurityPolicy();
133             requestContext.setRelyingPartyId(securityPolicy.getIssuer());
134
135             Request request = (Request) requestContext.getMessageDecoder().getSAMLMessage();
136             requestContext.setSamlRequest(request);
137             requestContext.setAttributeQuery(request.getAttributeQuery());
138
139             populateRelyingPartyData(requestContext);
140
141             populateAssertingPartyData(requestContext);
142         }
143     }
144
145     /**
146      * Populates the relying party entity and role metadata and relying party configuration data.
147      * 
148      * @param requestContext current request context with relying party ID populated
149      * 
150      * @throws ProfileException thrown if metadata can not be located for the relying party
151      */
152     protected void populateRelyingPartyData(AttributeQueryContext requestContext) throws ProfileException {
153         try {
154             requestContext.setRelyingPartyMetadata(getMetadataProvider().getEntityDescriptor(
155                     requestContext.getRelyingPartyId()));
156
157             RoleDescriptor relyingPartyRole = requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
158                     ShibbolethConstants.SAML11P_NS);
159
160             if (relyingPartyRole == null) {
161                 relyingPartyRole = requestContext.getRelyingPartyMetadata()
162                         .getSPSSODescriptor(ShibbolethConstants.SAML10P_NS);
163                 if (relyingPartyRole == null) {
164                     throw new MetadataProviderException("Unable to locate SPSSO role descriptor for entity "
165                             + requestContext.getRelyingPartyId());
166                 }
167             }
168             requestContext.setRelyingPartyRoleMetadata(relyingPartyRole);
169
170             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(requestContext.getRelyingPartyId());
171             requestContext.setRelyingPartyConfiguration(rpConfig);
172
173             requestContext.setProfileConfiguration((AttributeQueryConfiguration) rpConfig
174                     .getProfileConfiguration(AttributeQueryConfiguration.PROFILE_ID));
175
176         } catch (MetadataProviderException e) {
177             log.error("Unable to locate metadata for relying party " + requestContext.getRelyingPartyId());
178             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
179                     "Unable to locate metadata for relying party " + requestContext.getRelyingPartyId()));
180             throw new ProfileException("Unable to locate metadata for relying party "
181                     + requestContext.getRelyingPartyId());
182         }
183     }
184
185     /**
186      * Populates the asserting party entity and role metadata.
187      * 
188      * @param requestContext current request context with relying party configuration populated
189      * 
190      * @throws ProfileException thrown if metadata can not be located for the asserting party
191      */
192     protected void populateAssertingPartyData(AttributeQueryContext requestContext) throws ProfileException {
193         String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
194
195         try {
196             requestContext.setAssertingPartyId(assertingPartyId);
197
198             requestContext.setAssertingPartyMetadata(getMetadataProvider().getEntityDescriptor(assertingPartyId));
199
200             RoleDescriptor assertingPartyRole = requestContext.getAssertingPartyMetadata()
201                     .getAttributeAuthorityDescriptor(ShibbolethConstants.SAML11P_NS);
202
203             if (assertingPartyRole == null) {
204                 assertingPartyRole = requestContext.getAssertingPartyMetadata().getAttributeAuthorityDescriptor(
205                         ShibbolethConstants.SAML10P_NS);
206                 if (assertingPartyRole == null) {
207                     throw new MetadataProviderException("Unable to locate IDPSSO role descriptor for entity "
208                             + assertingPartyId);
209                 }
210             }
211             requestContext.setAssertingPartyRoleMetadata(assertingPartyRole);
212         } catch (MetadataProviderException e) {
213             log.error("Unable to locate metadata for asserting party " + assertingPartyId);
214             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
215                     "Unable to locate metadata for relying party " + assertingPartyId));
216             throw new ProfileException("Unable to locate metadata for relying party " + assertingPartyId);
217         }
218     }
219
220     /**
221      * Encodes the request's SAML response and writes it to the servlet response.
222      * 
223      * @param requestContext current request context
224      * 
225      * @throws ProfileException thrown if no message encoder is registered for this profiles binding
226      */
227     protected void encodeResponse(AttributeQueryContext requestContext) throws ProfileException {
228         if (log.isDebugEnabled()) {
229             log.debug("Encoding response to SAML request from relying party " + requestContext.getRelyingPartyId());
230         }
231         MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(
232                 HTTPSOAP11Encoder.BINDING_URI);
233         if (encoder == null) {
234             throw new ProfileException("No response encoder was registered for binding type: "
235                     + HTTPSOAP11Encoder.BINDING_URI);
236         }
237
238         super.populateMessageEncoder(encoder);
239         encoder.setRelayState(requestContext.getMessageDecoder().getRelayState());
240         ProfileResponse<ServletResponse> profileResponse = requestContext.getProfileResponse();
241         encoder.setResponse(profileResponse.getRawResponse());
242         encoder.setSamlMessage(requestContext.getSamlResponse());
243         requestContext.setMessageEncoder(encoder);
244
245         try {
246             encoder.encode();
247         } catch (BindingException e) {
248             throw new ProfileException("Unable to encode response to relying party: "
249                     + requestContext.getRelyingPartyId(), e);
250         }
251     }
252
253     /** Basic data structure used to accumulate information as a request is being processed. */
254     protected class AttributeQueryContext extends
255             SAML1ProfileRequestContext<Request, Response, AttributeQueryConfiguration> {
256         
257         private AttributeQuery attributeQuery;
258
259         /**
260          * Constructor.
261          * 
262          * @param request current profile request
263          * @param response current profile response
264          */
265         public AttributeQueryContext(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) {
266             super(request, response);
267         }
268         
269         public AttributeQuery getAttributeQuery(){
270             return attributeQuery;
271         }
272         
273         public void setAttributeQuery(AttributeQuery query){
274             attributeQuery = query;
275         }
276     }
277 }