Drive relying party endpoint selection off of metadata
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml1 / ShibbolethSSOProfileHandler.java
1 /*
2  * Copyright [2007] [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.io.IOException;
20 import java.io.UnsupportedEncodingException;
21 import java.net.URLDecoder;
22 import java.util.ArrayList;
23
24 import javax.servlet.RequestDispatcher;
25 import javax.servlet.ServletException;
26 import javax.servlet.ServletRequest;
27 import javax.servlet.ServletResponse;
28 import javax.servlet.http.HttpServletRequest;
29 import javax.servlet.http.HttpServletResponse;
30 import javax.servlet.http.HttpSession;
31
32 import org.apache.log4j.Logger;
33 import org.opensaml.common.SAMLObject;
34 import org.opensaml.common.SAMLObjectBuilder;
35 import org.opensaml.common.binding.BindingException;
36 import org.opensaml.common.binding.encoding.MessageEncoder;
37 import org.opensaml.common.xml.SAMLConstants;
38 import org.opensaml.saml1.core.AuthenticationStatement;
39 import org.opensaml.saml1.core.Response;
40 import org.opensaml.saml1.core.Statement;
41 import org.opensaml.saml1.core.StatusCode;
42 import org.opensaml.saml1.core.Subject;
43 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
44 import org.opensaml.xml.util.DatatypeHelper;
45
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.saml1.ShibbolethSSOConfiguration;
51 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
52 import edu.internet2.middleware.shibboleth.idp.authn.ShibbolethSSOLoginContext;
53
54 /** Shibboleth SSO request profile handler. */
55 public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
56
57     /** Class logger. */
58     private final Logger log = Logger.getLogger(ShibbolethSSOProfileHandler.class);
59
60     /** Builder of AuthenticationStatement objects. */
61     private SAMLObjectBuilder<AuthenticationStatement> authnStatementBuilder;
62
63     /** URL of the authentication manager servlet. */
64     private String authenticationManagerPath;
65
66     /** Message encoder binding URI. */
67     private String encodingBinding;
68
69     /**
70      * Constructor.
71      * 
72      * @param authnManagerPath path to the authentication manager servlet
73      * @param encoder URI of the encoding binding
74      * 
75      * @throws IllegalArgumentException thrown if either the authentication manager path or encoding binding URI are
76      *             null or empty
77      */
78     public ShibbolethSSOProfileHandler(String authnManagerPath, String encoder) {
79         if (DatatypeHelper.isEmpty(authnManagerPath) || DatatypeHelper.isEmpty(encoder)) {
80             throw new IllegalArgumentException("Authentication manager path and encoder binding URI may not be null");
81         }
82
83         authenticationManagerPath = authnManagerPath;
84         encodingBinding = encoder;
85
86         authnStatementBuilder = (SAMLObjectBuilder<AuthenticationStatement>) getBuilderFactory().getBuilder(
87                 AuthenticationStatement.DEFAULT_ELEMENT_NAME);
88     }
89
90     /**
91      * Convenience method for getting the SAML 1 AuthenticationStatement builder.
92      * 
93      * @return SAML 1 AuthenticationStatement builder
94      */
95     public SAMLObjectBuilder<AuthenticationStatement> getAuthenticationStatementBuilder() {
96         return authnStatementBuilder;
97     }
98
99     /** {@inheritDoc} */
100     public String getProfileId() {
101         return "urn:mace:shibboleth:2.0:idp:profiles:shibboleth:request:sso";
102     }
103
104     /** {@inheritDoc} */
105     public void processRequest(ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response)
106             throws ProfileException {
107
108         HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
109         if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
110             performAuthentication(request, response);
111         } else {
112             completeAuthenticationRequest(request, response);
113         }
114     }
115
116     /**
117      * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
118      * authenticating the user.
119      * 
120      * @param request current request
121      * @param response current response
122      * 
123      * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
124      *             authentication manager
125      */
126     protected void performAuthentication(ProfileRequest<ServletRequest> request,
127             ProfileResponse<ServletResponse> response) throws ProfileException {
128
129         HttpServletRequest httpRequest = (HttpServletRequest) request.getRawRequest();
130         HttpServletResponse httpResponse = (HttpServletResponse) response.getRawResponse();
131         HttpSession httpSession = httpRequest.getSession(true);
132
133         LoginContext loginContext = buildLoginContext(httpRequest);
134         httpSession.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
135
136         try {
137             RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
138             dispatcher.forward(httpRequest, httpResponse);
139         } catch (IOException ex) {
140             log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
141             throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
142         } catch (ServletException ex) {
143             log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
144             throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
145         }
146     }
147
148     /**
149      * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
150      * after they've been authenticated.
151      * 
152      * @param request current request
153      * @param response current response
154      * 
155      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
156      */
157     protected void completeAuthenticationRequest(ProfileRequest<ServletRequest> request,
158             ProfileResponse<ServletResponse> response) throws ProfileException {
159         HttpSession httpSession = ((HttpServletRequest) request.getRawRequest()).getSession(true);
160
161         ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpSession
162                 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
163         httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
164
165         ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, request, response);
166
167         Response samlResponse;
168         try {
169             if (!loginContext.isPrincipalAuthenticated()) {
170                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
171                 throw new ProfileException("User failed authentication");
172             }
173
174             ArrayList<Statement> statements = new ArrayList<Statement>();
175             statements.add(buildAuthenticationStatement(requestContext));
176             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
177                 statements
178                         .add(buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches"));
179             }
180
181             samlResponse = buildResponse(requestContext, statements);
182         } catch (ProfileException e) {
183             samlResponse = buildErrorResponse(requestContext);
184         }
185
186         requestContext.setSamlResponse(samlResponse);
187         encodeResponse(requestContext);
188         writeAuditLogEntry(requestContext);
189     }
190
191     /**
192      * Creates a login context from the incoming HTTP request.
193      * 
194      * @param request current HTTP request
195      * 
196      * @return the constructed login context
197      * 
198      * @throws ProfileException thrown if the incomming request did not contain a providerId, shire, and target
199      *             parameter
200      */
201     protected ShibbolethSSOLoginContext buildLoginContext(HttpServletRequest request) throws ProfileException {
202         ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
203
204         try {
205             String providerId = DatatypeHelper.safeTrimOrNullString(request.getParameter("providerId"));
206             if (providerId == null) {
207                 log.error("No providerId parameter in Shibboleth SSO request");
208                 throw new ProfileException("No providerId parameter in Shibboleth SSO request");
209             }
210             loginContext.setRelyingParty(URLDecoder.decode(providerId, "UTF-8"));
211
212             String acs = DatatypeHelper.safeTrimOrNullString(request.getParameter("shire"));
213             if (acs == null) {
214                 log.error("No shire parameter in Shibboleth SSO request");
215                 throw new ProfileException("No shire parameter in Shibboleth SSO request");
216             }
217             loginContext.setSpAssertionConsumerService(URLDecoder.decode(acs, "UTF-8"));
218
219             String target = DatatypeHelper.safeTrimOrNullString(request.getParameter("target"));
220             if (target == null) {
221                 log.error("No target parameter in Shibboleth SSO request");
222                 throw new ProfileException("No target parameter in Shibboleth SSO request");
223             }
224             loginContext.setSpTarget(URLDecoder.decode(target, "UTF-8"));
225         } catch (UnsupportedEncodingException e) {
226             // UTF-8 encoding required to be supported by all JVMs.
227         }
228
229         loginContext.setAuthenticationEngineURL(authenticationManagerPath);
230         loginContext.setProfileHandlerURL(request.getRequestURI());
231         return loginContext;
232     }
233
234     /**
235      * Creates an authentication request context from the current environmental information.
236      * 
237      * @param loginContext current login context
238      * @param request current request
239      * @param response current response
240      * 
241      * @return created authentication request context
242      * 
243      * @throws ProfileException thrown if asserting and relying party metadata can not be located
244      */
245     protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
246             ProfileRequest<ServletRequest> request, ProfileResponse<ServletResponse> response) throws ProfileException {
247         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext(request, response);
248
249         requestContext.setLoginContext(loginContext);
250
251         requestContext.setPrincipalName(loginContext.getPrincipalName());
252
253         requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
254
255         String relyingPartyId = loginContext.getRelyingPartyId();
256
257         requestContext.setRelyingPartyId(relyingPartyId);
258
259         try {
260
261             requestContext.setRelyingPartyMetadata(getMetadataProvider().getEntityDescriptor(
262                     requestContext.getRelyingPartyId()));
263
264             requestContext.setRelyingPartyRoleMetadata(requestContext.getRelyingPartyMetadata().getSPSSODescriptor(
265                     SAMLConstants.SAML1P_NS));
266
267             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
268             requestContext.setRelyingPartyConfiguration(rpConfig);
269
270             requestContext.setAssertingPartyId(requestContext.getRelyingPartyConfiguration().getProviderId());
271
272             requestContext.setAssertingPartyMetadata(getMetadataProvider().getEntityDescriptor(
273                     requestContext.getAssertingPartyId()));
274
275             requestContext.setAssertingPartyRoleMetadata(requestContext.getAssertingPartyMetadata()
276                     .getIDPSSODescriptor(SAMLConstants.SAML1P_NS));
277
278             requestContext.setProfileConfiguration((ShibbolethSSOConfiguration) rpConfig
279                     .getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID));
280
281             return requestContext;
282         } catch (MetadataProviderException e) {
283             log.error("Unable to locate metadata for asserting or relying party");
284             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error locating party metadata"));
285             throw new ProfileException("Error locating party metadata");
286         }
287     }
288
289     /**
290      * Builds the authentication statement for the authenticated principal.
291      * 
292      * @param requestContext current request context
293      * 
294      * @return the created statement
295      * 
296      * @throws ProfileException thrown if the authentication statement can not be created
297      */
298     protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
299             throws ProfileException {
300         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
301
302         AuthenticationStatement statement = getAuthenticationStatementBuilder().buildObject();
303         statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
304         statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
305
306         // TODO
307         statement.setSubjectLocality(null);
308
309         Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches");
310         statement.setSubject(statementSubject);
311
312         return statement;
313     }
314
315     /**
316      * Encodes the request's SAML response and writes it to the servlet response.
317      * 
318      * @param requestContext current request context
319      * 
320      * @throws ProfileException thrown if no message encoder is registered for this profiles binding
321      */
322     protected void encodeResponse(ShibbolethSSORequestContext requestContext) throws ProfileException {
323         if (log.isDebugEnabled()) {
324             log.debug("Encoding response to SAML request from relying party " + requestContext.getRelyingPartyId());
325         }
326         MessageEncoder<ServletResponse> encoder = getMessageEncoderFactory().getMessageEncoder(encodingBinding);
327         if (encoder == null) {
328             throw new ProfileException("No response encoder was registered for binding type: " + encodingBinding);
329         }
330
331         super.populateMessageEncoder(encoder);
332         encoder.setResponse(requestContext.getProfileResponse().getRawResponse());
333         encoder.setSamlMessage(requestContext.getSamlResponse());
334         requestContext.setMessageEncoder(encoder);
335
336         try {
337             encoder.encode();
338         } catch (BindingException e) {
339             throw new ProfileException("Unable to encode response to relying party: "
340                     + requestContext.getRelyingPartyId(), e);
341         }
342     }
343
344     /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
345     protected class ShibbolethSSORequestContext extends
346             SAML1ProfileRequestContext<SAMLObject, Response, ShibbolethSSOConfiguration> {
347
348         /** Current login context. */
349         private ShibbolethSSOLoginContext loginContext;
350
351         /**
352          * Constructor.
353          * 
354          * @param request current profile request
355          * @param response current profile response
356          */
357         public ShibbolethSSORequestContext(ProfileRequest<ServletRequest> request,
358                 ProfileResponse<ServletResponse> response) {
359             super(request, response);
360         }
361
362         /**
363          * Gets the current login context.
364          * 
365          * @return current login context
366          */
367         public ShibbolethSSOLoginContext getLoginContext() {
368             return loginContext;
369         }
370
371         /**
372          * Sets the current login context.
373          * 
374          * @param context current login context
375          */
376         public void setLoginContext(ShibbolethSSOLoginContext context) {
377             loginContext = context;
378         }
379     }
380 }