More refactoring, moving more into the abstract SAML 2 profile handler
[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 import java.util.Map;
21
22 import javax.servlet.ServletRequest;
23 import javax.servlet.ServletResponse;
24
25 import org.apache.log4j.Logger;
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.saml2.binding.decoding.HTTPSOAP11Decoder;
31 import org.opensaml.saml2.core.AttributeQuery;
32 import org.opensaml.saml2.core.AttributeStatement;
33 import org.opensaml.saml2.core.NameID;
34 import org.opensaml.saml2.core.Response;
35 import org.opensaml.saml2.core.Statement;
36 import org.opensaml.saml2.core.StatusCode;
37 import org.opensaml.saml2.core.Subject;
38 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
39 import org.opensaml.saml2.metadata.SPSSODescriptor;
40 import org.opensaml.ws.security.SecurityPolicyException;
41
42 import edu.internet2.middleware.shibboleth.common.attribute.AttributeRequestException;
43 import edu.internet2.middleware.shibboleth.common.attribute.BaseAttribute;
44 import edu.internet2.middleware.shibboleth.common.attribute.provider.SAML2AttributeAuthority;
45 import edu.internet2.middleware.shibboleth.common.attribute.provider.ShibbolethSAMLAttributeRequestContext;
46 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
47 import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
48 import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
49 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
50 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AttributeQueryConfiguration;
51 import edu.internet2.middleware.shibboleth.idp.session.ServiceInformation;
52 import edu.internet2.middleware.shibboleth.idp.session.Session;
53
54 /**
55  * SAML 2.0 Attribute Query profile handler.
56  */
57 public class AttributeQueryProfileHandler extends AbstractSAML2ProfileHandler {
58
59     /** Class logger. */
60     private static Logger log = Logger.getLogger(AttributeQueryProfileHandler.class);
61
62     /** SAML binding URI. */
63     private static final String BINDING = "urn:oasis:names:tc:SAML:2.0:bindings:SOAP";
64
65     /** {@inheritDoc} */
66     public String getProfileId() {
67         return "urn:mace:shibboleth:2.0:idp:profiles:saml2:query:attribute";
68     }
69
70     /** {@inheritDoc} */
71     public void processRequest(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response)
72             throws ProfileException {
73
74         AttributeQueryContext requestContext = new AttributeQueryContext(request, response);
75
76         Response samlResponse;
77         try {
78             decodeRequest(requestContext);
79
80             // Lookup principal name and attributes, create attribute statement from information
81             ArrayList<Statement> statements = new ArrayList<Statement>();
82             statements.add(buildAttributeStatement(requestContext));
83
84             // create the assertion subject
85             Subject assertionSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:sender-vouches");
86
87             // create the SAML response
88             samlResponse = buildResponse(requestContext, assertionSubject, statements);
89         } catch (ProfileException e) {
90             samlResponse = buildErrorResponse(requestContext);
91         }
92
93         requestContext.setSamlResponse(samlResponse);
94
95         encodeResponse(requestContext);
96         writeAuditLogEntry(requestContext);
97     }
98
99     /**
100      * Decodes the message in the request and adds it to the request context.
101      * 
102      * @param requestContext request context contianing the request to decode
103      * 
104      * @throws ProfileException throw if there is a problem decoding the request
105      */
106     protected void decodeRequest(AttributeQueryContext requestContext) throws ProfileException {
107         if (log.isDebugEnabled()) {
108             log.debug("Decoding incomming request");
109         }
110         MessageDecoder<ServletRequest> decoder = getMessageDecoderFactory().getMessageDecoder(
111                 HTTPSOAP11Decoder.BINDING_URI);
112         if (decoder == null) {
113             throw new ProfileException("No request decoder was registered for binding type: "
114                     + HTTPSOAP11Decoder.BINDING_URI);
115         }
116         super.populateMessageDecoder(decoder);
117
118         decoder.setRequest(requestContext.getProfileRequest().getRawRequest());
119         requestContext.setMessageDecoder(decoder);
120
121         try {
122             decoder.decode();
123             if (log.isDebugEnabled()) {
124                 log.debug("Decoded request");
125             }
126         } catch (BindingException e) {
127             log.error("Error decoding attribute query message", e);
128             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error decoding message"));
129             throw new ProfileException("Error decoding attribute query message");
130         } catch (SecurityPolicyException e) {
131             log.error("Message did not meet security policy requirements", e);
132             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
133                     "Message did not meet security policy requirements"));
134             throw new ProfileException("Message did not meet security policy requirements", e);
135         } finally {
136             // Set as much information as can be retrieved from the decoded message
137             SAMLSecurityPolicy securityPolicy = requestContext.getMessageDecoder().getSecurityPolicy();
138             requestContext.setRelyingPartyId(securityPolicy.getIssuer());
139
140             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(requestContext.getRelyingPartyId());
141             requestContext.setRelyingPartyConfiguration(rpConfig);
142
143             requestContext.setRelyingPartyRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
144
145             requestContext.setAssertingPartyId(requestContext.getRelyingPartyConfiguration().getProviderId());
146
147             requestContext.setAssertingPartyRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
148
149             requestContext.setProfileConfiguration((AttributeQueryConfiguration) rpConfig
150                     .getProfileConfiguration(AttributeQueryConfiguration.PROFILE_ID));
151
152             requestContext.setSamlRequest((AttributeQuery) requestContext.getMessageDecoder().getSAMLMessage());
153         }
154     }
155
156     /**
157      * Encodes the request's SAML response and writes it to the servlet response.
158      * 
159      * @param requestContext current request context
160      * 
161      * @throws ProfileException thrown if no message encoder is registered for this profiles binding
162      */
163     protected void encodeResponse(AttributeQueryContext requestContext) throws ProfileException {
164         if (log.isDebugEnabled()) {
165             log.debug("Encoding response to SAML request " + requestContext.getSamlRequest().getID()
166                     + " from relying party " + requestContext.getRelyingPartyId());
167         }
168         MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(BINDING);
169         if (encoder == null) {
170             throw new ProfileException("No response encoder was registered for binding type: " + BINDING);
171         }
172
173         super.populateMessageEncoder(encoder);
174         encoder.setResponse(requestContext.getProfileResponse().getRawResponse());
175         encoder.setSamlMessage(requestContext.getSamlResponse());
176         requestContext.setMessageEncoder(encoder);
177
178         try {
179             encoder.encode();
180         } catch (BindingException e) {
181             throw new ProfileException("Unable to encode response to relying party: "
182                     + requestContext.getRelyingPartyId(), e);
183         }
184     }
185
186     /** Basic data structure used to accumulate information as a request is being processed. */
187     protected class AttributeQueryContext extends
188             SAML2ProfileRequestContext<AttributeQuery, Response, AttributeQueryConfiguration> {
189
190         /**
191          * Constructor.
192          * 
193          * @param request current profile request
194          * @param response current profile response
195          */
196         public AttributeQueryContext(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) {
197             super(request, response);
198         }
199     }
200 }