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