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