Deal with selecting relying party endpoint sooner and populating subject confirmation...
[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.common.xml.SAMLConstants;
30 import org.opensaml.saml2.binding.decoding.HTTPSOAP11Decoder;
31 import org.opensaml.saml2.core.AttributeQuery;
32 import org.opensaml.saml2.core.Response;
33 import org.opensaml.saml2.core.Statement;
34 import org.opensaml.saml2.core.StatusCode;
35 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
36 import org.opensaml.ws.security.SecurityPolicyException;
37
38 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
39 import edu.internet2.middleware.shibboleth.common.profile.ProfileRequest;
40 import edu.internet2.middleware.shibboleth.common.profile.ProfileResponse;
41 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
42 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AttributeQueryConfiguration;
43
44 /** SAML 2.0 Attribute Query profile handler. */
45 public class AttributeQueryProfileHandler extends AbstractSAML2ProfileHandler {
46
47     /** Class logger. */
48     private static Logger log = Logger.getLogger(AttributeQueryProfileHandler.class);
49
50     /** SAML binding URI. */
51     private static final String BINDING = "urn:oasis:names:tc:SAML:2.0:bindings:SOAP";
52
53     /** {@inheritDoc} */
54     public String getProfileId() {
55         return "urn:mace:shibboleth:2.0:idp:profiles:saml2: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 2 Attribute Query profile is not configured for relying party "
70                         + requestContext.getRelyingPartyId());
71                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
72                         "SAML 2 Attribute Query profile is not configured for relying party "
73                                 + requestContext.getRelyingPartyId()));
74                 samlResponse = buildErrorResponse(requestContext);
75             }
76
77             checkSamlVersion(requestContext);
78
79             // Resolve attribute query name id to principal name and place in context
80             resolvePrincipal(requestContext);
81
82             // Lookup principal name and attributes, create attribute statement from information
83             ArrayList<Statement> statements = new ArrayList<Statement>();
84             statements.add(buildAttributeStatement(requestContext));
85
86             // create the SAML response
87             samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:sender-vouches", statements);
88         } catch (ProfileException e) {
89             samlResponse = buildErrorResponse(requestContext);
90         }
91
92         requestContext.setSamlResponse(samlResponse);
93
94         encodeResponse(requestContext);
95         writeAuditLogEntry(requestContext);
96     }
97
98     /**
99      * Decodes the message in the request and adds it to the request context.
100      * 
101      * @param requestContext request context contianing the request to decode
102      * 
103      * @throws ProfileException throw if there is a problem decoding the request
104      */
105     protected void decodeRequest(AttributeQueryContext requestContext) throws ProfileException {
106         if (log.isDebugEnabled()) {
107             log.debug("Decoding incomming request");
108         }
109         MessageDecoder<ServletRequest> decoder = getMessageDecoderFactory().getMessageDecoder(
110                 HTTPSOAP11Decoder.BINDING_URI);
111         if (decoder == null) {
112             throw new ProfileException("No request decoder was registered for binding type: "
113                     + HTTPSOAP11Decoder.BINDING_URI);
114         }
115         super.populateMessageDecoder(decoder);
116
117         ProfileRequest<ServletRequest> profileRequest = requestContext.getProfileRequest(); 
118         decoder.setRequest(profileRequest.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             try {
141                 requestContext.setRelyingPartyMetadata(getMetadataProvider().getEntityDescriptor(
142                         requestContext.getRelyingPartyId()));
143
144                 requestContext.setRelyingPartyRoleMetadata(requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
145                         SAMLConstants.SAML20P_NS));
146
147                 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(requestContext.getRelyingPartyId());
148                 requestContext.setRelyingPartyConfiguration(rpConfig);
149
150                 requestContext.setAssertingPartyId(requestContext.getRelyingPartyConfiguration().getProviderId());
151
152                 requestContext.setAssertingPartyMetadata(getMetadataProvider().getEntityDescriptor(
153                         requestContext.getAssertingPartyId()));
154
155                 requestContext.setAssertingPartyRoleMetadata(requestContext.getAssertingPartyMetadata()
156                         .getAttributeAuthorityDescriptor(SAMLConstants.SAML20P_NS));
157
158                 requestContext.setProfileConfiguration((AttributeQueryConfiguration) rpConfig
159                         .getProfileConfiguration(AttributeQueryConfiguration.PROFILE_ID));
160
161                 requestContext.setSamlRequest((AttributeQuery) requestContext.getMessageDecoder().getSAMLMessage());
162             } catch (MetadataProviderException e) {
163                 log.error("Unable to locate metadata for asserting or relying party");
164                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
165                         "Error locating party metadata"));
166                 throw new ProfileException("Error locating party metadata");
167             }
168         }
169     }
170
171     /**
172      * Encodes the request's SAML response and writes it to the servlet response.
173      * 
174      * @param requestContext current request context
175      * 
176      * @throws ProfileException thrown if no message encoder is registered for this profiles binding
177      */
178     protected void encodeResponse(AttributeQueryContext requestContext) throws ProfileException {
179         if (log.isDebugEnabled()) {
180             log.debug("Encoding response to SAML request " + requestContext.getSamlRequest().getID()
181                     + " from relying party " + requestContext.getRelyingPartyId());
182         }
183         MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(BINDING);
184         if (encoder == null) {
185             throw new ProfileException("No response encoder was registered for binding type: " + BINDING);
186         }
187
188         super.populateMessageEncoder(encoder);
189         encoder.setRelayState(requestContext.getMessageDecoder().getRelayState());
190         ProfileResponse<ServletResponse> profileResponse = requestContext.getProfileResponse();
191         encoder.setResponse(profileResponse.getRawResponse());
192         encoder.setSamlMessage(requestContext.getSamlResponse());
193         requestContext.setMessageEncoder(encoder);
194
195         try {
196             encoder.encode();
197         } catch (BindingException e) {
198             throw new ProfileException("Unable to encode response to relying party: "
199                     + requestContext.getRelyingPartyId(), e);
200         }
201     }
202
203     /** Basic data structure used to accumulate information as a request is being processed. */
204     protected class AttributeQueryContext extends
205             SAML2ProfileRequestContext<AttributeQuery, Response, AttributeQueryConfiguration> {
206
207         /**
208          * Constructor.
209          * 
210          * @param request current profile request
211          * @param response current profile response
212          */
213         public AttributeQueryContext(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) {
214             super(request, response);
215         }
216     }
217 }