Minor checkstyle cleanups
[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             resolveAttributes(requestContext);
81
82             ArrayList<Statement> statements = new ArrayList<Statement>();
83             statements.add(buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches"));
84
85             samlResponse = buildResponse(requestContext, statements);
86         } catch (ProfileException e) {
87             samlResponse = buildErrorResponse(requestContext);
88         }
89
90         requestContext.setSamlResponse(samlResponse);
91         encodeResponse(requestContext);
92     }
93
94     /**
95      * Decodes the message in the request and adds it to the request context.
96      * 
97      * @param requestContext request context contianing the request to decode
98      * 
99      * @throws ProfileException throw if there is a problem decoding the request
100      */
101     protected void decodeRequest(AttributeQueryContext requestContext) throws ProfileException {
102         if (log.isDebugEnabled()) {
103             log.debug("Decoding incomming request");
104         }
105         MessageDecoder<ServletRequest> decoder = getMessageDecoderFactory().getMessageDecoder(
106                 HTTPSOAP11Decoder.BINDING_URI);
107         if (decoder == null) {
108             throw new ProfileException("No request decoder was registered for binding type: "
109                     + HTTPSOAP11Decoder.BINDING_URI);
110         }
111         super.populateMessageDecoder(decoder);
112
113         ProfileRequest<ServletRequest> profileRequest = requestContext.getProfileRequest();
114         decoder.setRequest(profileRequest.getRawRequest());
115         requestContext.setMessageDecoder(decoder);
116
117         try {
118             decoder.decode();
119             if (log.isDebugEnabled()) {
120                 log.debug("Decoded request");
121             }
122         } catch (BindingException e) {
123             log.error("Error decoding attribute query message", e);
124             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error decoding message"));
125             throw new ProfileException("Error decoding attribute query message");
126         } catch (SecurityPolicyException e) {
127             log.error("Message did not meet security policy requirements", e);
128             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
129                     "Message did not meet security policy requirements"));
130             throw new ProfileException("Message did not meet security policy requirements", e);
131         } finally {
132             // Set as much information as can be retrieved from the decoded message
133             SAMLSecurityPolicy securityPolicy = requestContext.getMessageDecoder().getSecurityPolicy();
134             requestContext.setRelyingPartyId(securityPolicy.getIssuer());
135
136             Request request = (Request) requestContext.getMessageDecoder().getSAMLMessage();
137             requestContext.setSamlRequest(request);
138             requestContext.setAttributeQuery(request.getAttributeQuery());
139
140             populateRelyingPartyData(requestContext);
141
142             populateAssertingPartyData(requestContext);
143         }
144     }
145
146     /**
147      * Populates the relying party entity and role metadata and relying party configuration data.
148      * 
149      * @param requestContext current request context with relying party ID populated
150      * 
151      * @throws ProfileException thrown if metadata can not be located for the relying party
152      */
153     protected void populateRelyingPartyData(AttributeQueryContext requestContext) throws ProfileException {
154         try {
155             requestContext.setRelyingPartyMetadata(getMetadataProvider().getEntityDescriptor(
156                     requestContext.getRelyingPartyId()));
157
158             RoleDescriptor relyingPartyRole = requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
159                     ShibbolethConstants.SAML11P_NS);
160
161             if (relyingPartyRole == null) {
162                 relyingPartyRole = requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
163                         ShibbolethConstants.SAML10P_NS);
164                 if (relyingPartyRole == null) {
165                     throw new MetadataProviderException("Unable to locate SPSSO role descriptor for entity "
166                             + requestContext.getRelyingPartyId());
167                 }
168             }
169             requestContext.setRelyingPartyRoleMetadata(relyingPartyRole);
170
171             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(requestContext.getRelyingPartyId());
172             requestContext.setRelyingPartyConfiguration(rpConfig);
173
174             requestContext.setProfileConfiguration((AttributeQueryConfiguration) rpConfig
175                     .getProfileConfiguration(AttributeQueryConfiguration.PROFILE_ID));
176
177         } catch (MetadataProviderException e) {
178             log.error("Unable to locate metadata for relying party " + requestContext.getRelyingPartyId());
179             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
180                     "Unable to locate metadata for relying party " + requestContext.getRelyingPartyId()));
181             throw new ProfileException("Unable to locate metadata for relying party "
182                     + requestContext.getRelyingPartyId());
183         }
184     }
185
186     /**
187      * Populates the asserting party entity and role metadata.
188      * 
189      * @param requestContext current request context with relying party configuration populated
190      * 
191      * @throws ProfileException thrown if metadata can not be located for the asserting party
192      */
193     protected void populateAssertingPartyData(AttributeQueryContext requestContext) throws ProfileException {
194         String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
195
196         try {
197             requestContext.setAssertingPartyId(assertingPartyId);
198
199             requestContext.setAssertingPartyMetadata(getMetadataProvider().getEntityDescriptor(assertingPartyId));
200
201             RoleDescriptor assertingPartyRole = requestContext.getAssertingPartyMetadata()
202                     .getAttributeAuthorityDescriptor(ShibbolethConstants.SAML11P_NS);
203
204             if (assertingPartyRole == null) {
205                 assertingPartyRole = requestContext.getAssertingPartyMetadata().getAttributeAuthorityDescriptor(
206                         ShibbolethConstants.SAML10P_NS);
207                 if (assertingPartyRole == null) {
208                     throw new MetadataProviderException("Unable to locate IDPSSO role descriptor for entity "
209                             + assertingPartyId);
210                 }
211             }
212             requestContext.setAssertingPartyRoleMetadata(assertingPartyRole);
213         } catch (MetadataProviderException e) {
214             log.error("Unable to locate metadata for asserting party " + assertingPartyId);
215             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
216                     "Unable to locate metadata for relying party " + assertingPartyId));
217             throw new ProfileException("Unable to locate metadata for relying party " + assertingPartyId);
218         }
219     }
220
221     /**
222      * Encodes the request's SAML response and writes it to the servlet response.
223      * 
224      * @param requestContext current request context
225      * 
226      * @throws ProfileException thrown if no message encoder is registered for this profiles binding
227      */
228     protected void encodeResponse(AttributeQueryContext requestContext) throws ProfileException {
229         if (log.isDebugEnabled()) {
230             log.debug("Encoding response to SAML request from relying party " + requestContext.getRelyingPartyId());
231         }
232         MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(
233                 HTTPSOAP11Encoder.BINDING_URI);
234         if (encoder == null) {
235             throw new ProfileException("No response encoder was registered for binding type: "
236                     + HTTPSOAP11Encoder.BINDING_URI);
237         }
238
239         super.populateMessageEncoder(encoder);
240         encoder.setRelayState(requestContext.getMessageDecoder().getRelayState());
241         ProfileResponse<ServletResponse> profileResponse = requestContext.getProfileResponse();
242         encoder.setResponse(profileResponse.getRawResponse());
243         encoder.setSamlMessage(requestContext.getSamlResponse());
244         requestContext.setMessageEncoder(encoder);
245
246         try {
247             encoder.encode();
248         } catch (BindingException e) {
249             throw new ProfileException("Unable to encode response to relying party: "
250                     + requestContext.getRelyingPartyId(), e);
251         }
252     }
253
254     /** Basic data structure used to accumulate information as a request is being processed. */
255     protected class AttributeQueryContext extends
256             SAML1ProfileRequestContext<Request, Response, AttributeQueryConfiguration> {
257
258         /** Current attribute query. */
259         private AttributeQuery attributeQuery;
260
261         /**
262          * Constructor.
263          * 
264          * @param request current profile request
265          * @param response current profile response
266          */
267         public AttributeQueryContext(ProfileRequest<ServletRequest> request, 
268                 ProfileResponse<ServletResponse> response) {
269             super(request, response);
270         }
271
272         /**
273          * Gets the attribute query of the request.
274          * 
275          * @return attribute query of the request
276          */
277         public AttributeQuery getAttributeQuery() {
278             return attributeQuery;
279         }
280
281         /**
282          * Sets the attribute query of the request.
283          * 
284          * @param query attribute query of the request
285          */
286         public void setAttributeQuery(AttributeQuery query) {
287             attributeQuery = query;
288         }
289     }
290 }