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