check SAML versions on requests
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml2 / 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.saml2;
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.saml2.binding.decoding.HTTPSOAP11Decoder;
30 import org.opensaml.saml2.core.AttributeQuery;
31 import org.opensaml.saml2.core.Response;
32 import org.opensaml.saml2.core.Statement;
33 import org.opensaml.saml2.core.StatusCode;
34 import org.opensaml.saml2.core.Subject;
35 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
36 import org.opensaml.saml2.metadata.SPSSODescriptor;
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.saml2.AttributeQueryConfiguration;
44
45 /** SAML 2.0 Attribute Query profile handler. */
46 public class AttributeQueryProfileHandler extends AbstractSAML2ProfileHandler {
47
48     /** Class logger. */
49     private static Logger log = Logger.getLogger(AttributeQueryProfileHandler.class);
50
51     /** SAML binding URI. */
52     private static final String BINDING = "urn:oasis:names:tc:SAML:2.0:bindings:SOAP";
53
54     /** {@inheritDoc} */
55     public String getProfileId() {
56         return "urn:mace:shibboleth:2.0:idp:profiles:saml2: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             checkSamlVersion(requestContext);
70             
71             // Resolve attribute query name id to principal name and place in context
72             resolvePrincipal(requestContext);
73
74             // Lookup principal name and attributes, create attribute statement from information
75             ArrayList<Statement> statements = new ArrayList<Statement>();
76             statements.add(buildAttributeStatement(requestContext));
77
78             // create the assertion subject
79             Subject assertionSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:sender-vouches");
80
81             // create the SAML response
82             samlResponse = buildResponse(requestContext, assertionSubject, statements);
83         } catch (ProfileException e) {
84             samlResponse = buildErrorResponse(requestContext);
85         }
86
87         requestContext.setSamlResponse(samlResponse);
88
89         encodeResponse(requestContext);
90         writeAuditLogEntry(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         decoder.setRequest(requestContext.getProfileRequest().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_URI, 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_URI, StatusCode.REQUEST_DENIED_URI,
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             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(requestContext.getRelyingPartyId());
135             requestContext.setRelyingPartyConfiguration(rpConfig);
136
137             requestContext.setRelyingPartyRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
138
139             requestContext.setAssertingPartyId(requestContext.getRelyingPartyConfiguration().getProviderId());
140
141             requestContext.setAssertingPartyRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
142
143             requestContext.setProfileConfiguration((AttributeQueryConfiguration) rpConfig
144                     .getProfileConfiguration(AttributeQueryConfiguration.PROFILE_ID));
145
146             requestContext.setSamlRequest((AttributeQuery) requestContext.getMessageDecoder().getSAMLMessage());
147         }
148     }
149
150     /**
151      * Encodes the request's SAML response and writes it to the servlet response.
152      * 
153      * @param requestContext current request context
154      * 
155      * @throws ProfileException thrown if no message encoder is registered for this profiles binding
156      */
157     protected void encodeResponse(AttributeQueryContext requestContext) throws ProfileException {
158         if (log.isDebugEnabled()) {
159             log.debug("Encoding response to SAML request " + requestContext.getSamlRequest().getID()
160                     + " from relying party " + requestContext.getRelyingPartyId());
161         }
162         MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(BINDING);
163         if (encoder == null) {
164             throw new ProfileException("No response encoder was registered for binding type: " + BINDING);
165         }
166
167         super.populateMessageEncoder(encoder);
168         encoder.setResponse(requestContext.getProfileResponse().getRawResponse());
169         encoder.setSamlMessage(requestContext.getSamlResponse());
170         requestContext.setMessageEncoder(encoder);
171
172         try {
173             encoder.encode();
174         } catch (BindingException e) {
175             throw new ProfileException("Unable to encode response to relying party: "
176                     + requestContext.getRelyingPartyId(), e);
177         }
178     }
179
180     /** Basic data structure used to accumulate information as a request is being processed. */
181     protected class AttributeQueryContext extends
182             SAML2ProfileRequestContext<AttributeQuery, Response, AttributeQueryConfiguration> {
183
184         /**
185          * Constructor.
186          * 
187          * @param request current profile request
188          * @param response current profile response
189          */
190         public AttributeQueryContext(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) {
191             super(request, response);
192         }
193     }
194 }