Lots of code cleanup
[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.core.AttributeQuery;
31 import org.opensaml.saml2.core.AttributeStatement;
32 import org.opensaml.saml2.core.NameID;
33 import org.opensaml.saml2.core.Response;
34 import org.opensaml.saml2.core.Statement;
35 import org.opensaml.saml2.core.StatusCode;
36 import org.opensaml.saml2.core.Subject;
37 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
38 import org.opensaml.saml2.metadata.SPSSODescriptor;
39 import org.opensaml.ws.security.SecurityPolicyException;
40
41 import edu.internet2.middleware.shibboleth.common.attribute.AttributeRequestException;
42 import edu.internet2.middleware.shibboleth.common.attribute.BaseAttribute;
43 import edu.internet2.middleware.shibboleth.common.attribute.provider.SAML2AttributeAuthority;
44 import edu.internet2.middleware.shibboleth.common.attribute.provider.ShibbolethSAMLAttributeRequestContext;
45 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
46 import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
47 import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
48 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AttributeQueryConfiguration;
49 import edu.internet2.middleware.shibboleth.idp.session.ServiceInformation;
50 import edu.internet2.middleware.shibboleth.idp.session.Session;
51
52 /**
53  * SAML 2.0 Attribute Query profile handler.
54  */
55 public class AttributeQueryProfileHandler extends AbstractSAML2ProfileHandler {
56
57     /** Class logger. */
58     private static Logger log = Logger.getLogger(AttributeQueryProfileHandler.class);
59
60     /** SAML binding URI. */
61     private static final String BINDING = "urn:oasis:names:tc:SAML:2.0:bindings:SOAP";
62
63     /** {@inheritDoc} */
64     public String getProfileId() {
65         return "urn:mace:shibboleth:2.0:idp:profiles:saml2:query:attribute";
66     }
67
68     /** {@inheritDoc} */
69     public void processRequest(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response)
70             throws ProfileException {
71
72         AttributeQueryContext requestContext = new AttributeQueryContext(request, response);
73
74         Response samlResponse;
75         try {
76             decodeRequest(requestContext);
77
78             // populate request context with information from decoded message
79             SAMLSecurityPolicy securityPolicy = requestContext.getMessageDecoder().getSecurityPolicy();
80             requestContext.setRelyingPartyId(securityPolicy.getIssuer());
81             requestContext
82                     .setRelyingPartyConfiguration(getRelyingPartyConfiguration(requestContext.getRelyingPartyId()));
83             requestContext.setRelyingPartyRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
84             requestContext.setAssertingPartyId(requestContext.getRelyingPartyConfiguration().getProviderId());
85             requestContext.setAssertingPartyRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
86             requestContext.setProfileConfiguration((AttributeQueryConfiguration) getProfileConfiguration(requestContext
87                     .getRelyingPartyId(), AttributeQueryConfiguration.PROFILE_ID));
88             requestContext.setSamlRequest((AttributeQuery) requestContext.getMessageDecoder().getSAMLMessage());
89
90             // TODO principal
91
92             // create the SAML attribute statement
93             ArrayList<Statement> statements = new ArrayList<Statement>();
94             statements.add(buildAttributeStatement(requestContext));
95             
96             //TODO NameID
97             Subject assertionSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:sender-vouches");
98
99             // create the SAML response
100             samlResponse = buildResponse(requestContext, assertionSubject, statements);
101         } catch (SecurityPolicyException e) {
102             samlResponse = buildErrorResponse(requestContext, StatusCode.REQUESTER_URI, StatusCode.REQUEST_DENIED_URI,
103                     e.getMessage());
104         } catch (AttributeRequestException e) {
105             samlResponse = buildErrorResponse(requestContext, StatusCode.RESPONDER_URI,
106                     StatusCode.INVALID_ATTR_NAME_VALUE_URI, e.getMessage());
107         }
108
109         requestContext.setSamlResponse(samlResponse);
110
111         encodeResponse(requestContext);
112         writeAuditLogEntry(requestContext);
113     }
114
115     /**
116      * Decodes the message in the request and adds it to the request context.
117      * 
118      * @param requestContext request context contianing the request to decode
119      * 
120      * @throws ProfileException throw if there is a problem decoding the request
121      * @throws SecurityPolicyException thrown if the message was decoded properly but did not meet the necessary
122      *             security policy requirements
123      */
124     protected void decodeRequest(AttributeQueryContext requestContext) throws ProfileException, SecurityPolicyException {
125         MessageDecoder<ServletRequest> decoder = getMessageDecoderFactory().getMessageDecoder(BINDING);
126         if (decoder == null) {
127             throw new ProfileException("No request decoder was registered for binding type: " + BINDING);
128         }
129
130         super.populateMessageDecoder(decoder);
131         decoder.setRequest(requestContext.getProfileRequest().getRawRequest());
132         requestContext.setMessageDecoder(decoder);
133
134         try {
135             decoder.decode();
136             if (log.isDebugEnabled()) {
137                 log.debug("decoded http servlet request");
138             }
139         } catch (BindingException e) {
140             log.error("Error decoding attribute query message", e);
141             throw new ProfileException("Error decoding attribute query message");
142         }
143     }
144
145     /**
146      * Executes a query for attributes and builds a SAML attribute statement from the results.
147      * 
148      * @param requestContext current request context
149      * 
150      * @return attribute statement resulting from the query
151      * 
152      * @throws ProfileException thrown if there is a problem making the query
153      * @throws AttributeRequestException thrown if there is a problem resolving attributes
154      */
155     protected AttributeStatement buildAttributeStatement(AttributeQueryContext requestContext) throws ProfileException,
156             AttributeRequestException {
157
158         try {
159             AttributeQueryConfiguration profileConfiguration = requestContext.getProfileConfiguration();
160             if (profileConfiguration == null) {
161                 log.error("No SAML 2 attribute query profile configuration is defined for relying party: "
162                         + requestContext.getRelyingPartyId());
163                 throw new AttributeRequestException("SAML 2 attribute query is not configured for this relying party");
164             }
165
166             SAML2AttributeAuthority attributeAuthority = profileConfiguration.getAttributeAuthority();
167
168             Map<String, BaseAttribute> principalAttributes = attributeAuthority
169                     .getAttributes(buildAttributeRequestContext(requestContext));
170
171             requestContext.setPrincipalAttributes(principalAttributes);
172
173             return attributeAuthority.buildAttributeStatement(requestContext.getSamlRequest(), principalAttributes
174                     .values());
175         } catch (AttributeRequestException e) {
176             log.error("Error resolving attributes", e);
177             throw e;
178         }
179     }
180
181     /**
182      * Creates an attribute query context from the current profile request context.
183      * 
184      * @param requestContext current profile request
185      * 
186      * @return created query context
187      */
188     protected ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery> buildAttributeRequestContext(
189             AttributeQueryContext requestContext) {
190
191         ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery> queryContext = new ShibbolethSAMLAttributeRequestContext<NameID, AttributeQuery>(
192                 getMetadataProvider(), requestContext.getRelyingPartyConfiguration(), requestContext.getSamlRequest());
193
194         Session userSession = getSessionManager().getSession(getUserSessionId(requestContext.getProfileRequest()));
195         if (userSession != null) {
196             queryContext.setUserSession(userSession);
197             ServiceInformation serviceInfo = userSession.getServiceInformation(requestContext.getRelyingPartyId());
198             if (serviceInfo != null) {
199                 String principalAuthenticationMethod = serviceInfo.getAuthenticationMethod().getAuthenticationMethod();
200
201                 requestContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
202                 queryContext.setPrincipalAuthenticationMethod(principalAuthenticationMethod);
203             }
204         }
205
206         queryContext.setProfileConfiguration(requestContext.getProfileConfiguration());
207         queryContext.setRequest(requestContext.getProfileRequest());
208
209         return queryContext;
210     }
211
212     /**
213      * Encodes the request's SAML response and writes it to the servlet response.
214      * 
215      * @param requestContext current request context
216      * 
217      * @throws ProfileException thrown if no message encoder is registered for this profiles binding
218      */
219     protected void encodeResponse(AttributeQueryContext requestContext) throws ProfileException {
220         MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(BINDING);
221         if (encoder == null) {
222             throw new ProfileException("No response encoder was registered for binding type: " + BINDING);
223         }
224
225         super.populateMessageEncoder(encoder);
226         encoder.setResponse(requestContext.getProfileResponse().getRawResponse());
227         encoder.setSamlMessage(requestContext.getSamlResponse());
228         requestContext.setMessageEncoder(encoder);
229     }
230
231     /** Basic data structure used to accumulate information as a request is being processed. */
232     protected class AttributeQueryContext extends
233             SAML2ProfileRequestContext<AttributeQuery, Response, AttributeQueryConfiguration> {
234
235         /**
236          * Constructor.
237          * 
238          * @param request current profile request
239          * @param response current profile response
240          */
241         public AttributeQueryContext(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) {
242             super(request, response);
243         }
244     }
245 }