Basic unit test and related fixes for Shibboleth SSO profile
[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.util.ArrayList;
21
22 import javax.servlet.RequestDispatcher;
23 import javax.servlet.ServletException;
24 import javax.servlet.http.HttpServletRequest;
25 import javax.servlet.http.HttpServletResponse;
26 import javax.servlet.http.HttpSession;
27
28 import org.apache.log4j.Logger;
29 import org.opensaml.common.SAMLObjectBuilder;
30 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
31 import org.opensaml.common.xml.SAMLConstants;
32 import org.opensaml.saml1.core.AuthenticationStatement;
33 import org.opensaml.saml1.core.Request;
34 import org.opensaml.saml1.core.Response;
35 import org.opensaml.saml1.core.Statement;
36 import org.opensaml.saml1.core.StatusCode;
37 import org.opensaml.saml1.core.Subject;
38 import org.opensaml.saml1.core.SubjectLocality;
39 import org.opensaml.saml2.metadata.AssertionConsumerService;
40 import org.opensaml.saml2.metadata.Endpoint;
41 import org.opensaml.saml2.metadata.EntityDescriptor;
42 import org.opensaml.saml2.metadata.IDPSSODescriptor;
43 import org.opensaml.saml2.metadata.SPSSODescriptor;
44 import org.opensaml.saml2.metadata.provider.MetadataProvider;
45 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
46 import org.opensaml.ws.message.decoder.MessageDecodingException;
47 import org.opensaml.ws.security.SecurityPolicyException;
48 import org.opensaml.ws.transport.http.HTTPInTransport;
49 import org.opensaml.ws.transport.http.HTTPOutTransport;
50 import org.opensaml.ws.transport.http.HttpServletRequestAdapter;
51 import org.opensaml.ws.transport.http.HttpServletResponseAdapter;
52 import org.opensaml.xml.util.DatatypeHelper;
53
54 import edu.internet2.middleware.shibboleth.common.ShibbolethConstants;
55 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
56 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
57 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.ShibbolethSSOConfiguration;
58 import edu.internet2.middleware.shibboleth.common.util.HttpHelper;
59 import edu.internet2.middleware.shibboleth.idp.authn.LoginContext;
60 import edu.internet2.middleware.shibboleth.idp.authn.ShibbolethSSOLoginContext;
61
62 /** Shibboleth SSO request profile handler. */
63 public class ShibbolethSSOProfileHandler extends AbstractSAML1ProfileHandler {
64
65     /** Class logger. */
66     private final Logger log = Logger.getLogger(ShibbolethSSOProfileHandler.class);
67
68     /** Builder of AuthenticationStatement objects. */
69     private SAMLObjectBuilder<AuthenticationStatement> authnStatementBuilder;
70
71     /** Builder of SubjectLocality objects. */
72     private SAMLObjectBuilder<SubjectLocality> subjectLocalityBuilder;
73
74     /** URL of the authentication manager servlet. */
75     private String authenticationManagerPath;
76
77     /**
78      * Constructor.
79      * 
80      * @param authnManagerPath path to the authentication manager servlet
81      * 
82      * @throws IllegalArgumentException thrown if either the authentication manager path or encoding binding URI are
83      *             null or empty
84      */
85     public ShibbolethSSOProfileHandler(String authnManagerPath) {
86         if (DatatypeHelper.isEmpty(authnManagerPath)) {
87             throw new IllegalArgumentException("Authentication manager path may not be null");
88         }
89         authenticationManagerPath = authnManagerPath;
90
91         authnStatementBuilder = (SAMLObjectBuilder<AuthenticationStatement>) getBuilderFactory().getBuilder(
92                 AuthenticationStatement.DEFAULT_ELEMENT_NAME);
93
94         subjectLocalityBuilder = (SAMLObjectBuilder<SubjectLocality>) getBuilderFactory().getBuilder(
95                 SubjectLocality.DEFAULT_ELEMENT_NAME);
96     }
97
98     /** {@inheritDoc} */
99     public String getProfileId() {
100         return "urn:mace:shibboleth:2.0:idp:profiles:shibboleth:request:sso";
101     }
102
103     /** {@inheritDoc} */
104     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
105         if (log.isDebugEnabled()) {
106             log.debug("Processing incomming request");
107         }
108
109         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
110         HttpSession httpSession = httpRequest.getSession();
111
112         if (httpSession.getAttribute(LoginContext.LOGIN_CONTEXT_KEY) == null) {
113             if (log.isDebugEnabled()) {
114                 log.debug("User session does not contain a login context, processing as first leg of request");
115             }
116             performAuthentication(inTransport, outTransport);
117         } else {
118             if (log.isDebugEnabled()) {
119                 log.debug("User session contains a login context, processing as second leg of request");
120             }
121             completeAuthenticationRequest(inTransport, outTransport);
122         }
123     }
124
125     /**
126      * Creates a {@link LoginContext} an sends the request off to the AuthenticationManager to begin the process of
127      * authenticating the user.
128      * 
129      * @param inTransport inbound message transport
130      * @param outTransport outbound message transport
131      * 
132      * @throws ProfileException thrown if there is a problem creating the login context and transferring control to the
133      *             authentication manager
134      */
135     protected void performAuthentication(HTTPInTransport inTransport, HTTPOutTransport outTransport)
136             throws ProfileException {
137
138         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
139         HttpServletResponse httpResponse = ((HttpServletResponseAdapter) outTransport).getWrappedResponse();
140         HttpSession httpSession = httpRequest.getSession(true);
141
142         ShibbolethSSORequestContext requestContext = decodeRequest(inTransport, outTransport);
143         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
144
145         RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(loginContext.getRelyingPartyId());
146         ShibbolethSSOConfiguration ssoConfig = (ShibbolethSSOConfiguration) rpConfig.getProfileConfigurations().get(ShibbolethSSOConfiguration.PROFILE_ID);
147         if (ssoConfig == null) {
148             log.error("Shibboleth SSO profile is not configured for relying party " + loginContext.getRelyingPartyId());
149             throw new ProfileException("Shibboleth SSO profile is not configured for relying party "
150                     + loginContext.getRelyingPartyId());
151         }
152
153         httpSession.setAttribute(LoginContext.LOGIN_CONTEXT_KEY, loginContext);
154
155         try {
156             RequestDispatcher dispatcher = httpRequest.getRequestDispatcher(authenticationManagerPath);
157             dispatcher.forward(httpRequest, httpResponse);
158             return;
159         } catch (IOException ex) {
160             log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
161             throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
162         } catch (ServletException ex) {
163             log.error("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
164             throw new ProfileException("Error forwarding Shibboleth SSO request to AuthenticationManager", ex);
165         }
166     }
167
168     /**
169      * Decodes an incoming request and populates a created request context with the resultant information.
170      * 
171      * @param inTransport inbound message transport
172      * @param outTransport outbound message transport
173      * 
174      * @return the created request context
175      * 
176      * @throws ProfileException throw if there is a problem decoding the request
177      */
178     protected ShibbolethSSORequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
179             throws ProfileException {
180         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
181
182         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
183         requestContext.setMetadataProvider(getMetadataProvider());
184         
185         requestContext.setInboundMessageTransport(inTransport);
186         requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);        
187         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
188         
189         requestContext.setOutboundMessageTransport(outTransport);
190         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
191
192         SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
193         requestContext.setMessageDecoder(decoder);
194         try {
195             decoder.decode(requestContext);
196         } catch (MessageDecodingException e) {
197             log.error("Error decoding Shibboleth SSO request", e);
198             throw new ProfileException("Error decoding Shibboleth SSO request", e);
199         } catch (SecurityPolicyException e) {
200             log.error("Shibboleth SSO request does not meet security policy requirements", e);
201             throw new ProfileException("Shibboleth SSO request does not meet security policy requirements", e);
202         }
203
204         ShibbolethSSOLoginContext loginContext = new ShibbolethSSOLoginContext();
205         loginContext.setRelyingParty(requestContext.getInboundMessageIssuer());
206         loginContext.setSpAssertionConsumerService(requestContext.getSpAssertionConsumerService());
207         loginContext.setSpTarget(requestContext.getRelayState());
208         loginContext.setAuthenticationEngineURL(authenticationManagerPath);
209         loginContext.setProfileHandlerURL(HttpHelper.getRequestUriWithoutContext(httpRequest));
210         requestContext.setLoginContext(loginContext);
211
212         return requestContext;
213     }
214
215     /**
216      * Creates a response to the Shibboleth SSO and sends the user, with response in tow, back to the relying party
217      * after they've been authenticated.
218      * 
219      * @param inTransport inbound message transport
220      * @param outTransport outbound message transport
221      * 
222      * @throws ProfileException thrown if the response can not be created and sent back to the relying party
223      */
224     protected void completeAuthenticationRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
225             throws ProfileException {
226         HttpServletRequest httpRequest = ((HttpServletRequestAdapter) inTransport).getWrappedRequest();
227         HttpSession httpSession = httpRequest.getSession(true);
228
229         ShibbolethSSOLoginContext loginContext = (ShibbolethSSOLoginContext) httpSession
230                 .getAttribute(LoginContext.LOGIN_CONTEXT_KEY);
231         httpSession.removeAttribute(LoginContext.LOGIN_CONTEXT_KEY);
232
233         ShibbolethSSORequestContext requestContext = buildRequestContext(loginContext, inTransport, outTransport);
234
235         Response samlResponse;
236         try {
237             if (loginContext.getPrincipalName() == null) {
238                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "User failed authentication"));
239                 throw new ProfileException("User failed authentication");
240             }
241
242             resolveAttributes(requestContext);
243
244             ArrayList<Statement> statements = new ArrayList<Statement>();
245             statements.add(buildAuthenticationStatement(requestContext));
246             if (requestContext.getProfileConfiguration().includeAttributeStatement()) {
247                 requestContext.setRequestedAttributes(requestContext.getPrincipalAttributes().keySet());
248                 statements.add(buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer"));
249             }
250
251             samlResponse = buildResponse(requestContext, statements);
252         } catch (ProfileException e) {
253             samlResponse = buildErrorResponse(requestContext);
254         }
255
256         requestContext.setOutboundSAMLMessage(samlResponse);
257         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
258         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
259         encodeResponse(requestContext);
260         writeAuditLogEntry(requestContext);
261     }
262
263     /**
264      * Creates an authentication request context from the current environmental information.
265      * 
266      * @param loginContext current login context
267      * @param in inbound transport
268      * @param out outbount transport
269      * 
270      * @return created authentication request context
271      * 
272      * @throws ProfileException thrown if there is a problem creating the context
273      */
274     protected ShibbolethSSORequestContext buildRequestContext(ShibbolethSSOLoginContext loginContext,
275             HTTPInTransport in, HTTPOutTransport out) throws ProfileException {
276         ShibbolethSSORequestContext requestContext = new ShibbolethSSORequestContext();
277
278         try {
279             requestContext.setMessageDecoder(getMessageDecoders().get(getInboundBinding()));
280             
281             requestContext.setLoginContext(loginContext);
282             requestContext.setPrincipalName(loginContext.getPrincipalName());
283             requestContext.setPrincipalAuthenticationMethod(loginContext.getAuthenticationMethod());
284             requestContext.setUserSession(getUserSession(in));
285             requestContext.setRelayState(loginContext.getSpTarget());
286
287             requestContext.setInboundMessageTransport(in);
288             requestContext.setInboundSAMLProtocol(ShibbolethConstants.SHIB_SSO_PROFILE_URI);
289
290             MetadataProvider metadataProvider = getMetadataProvider();
291             requestContext.setMetadataProvider(metadataProvider);
292
293             String relyingPartyId = loginContext.getRelyingPartyId();
294             requestContext.setInboundMessageIssuer(relyingPartyId);
295             EntityDescriptor relyingPartyMetadata = metadataProvider.getEntityDescriptor(relyingPartyId);
296             requestContext.setPeerEntityMetadata(relyingPartyMetadata);
297             requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
298             requestContext.setPeerEntityRoleMetadata(relyingPartyMetadata.getSPSSODescriptor(SAMLConstants.SAML11P_NS));
299             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
300             requestContext.setRelyingPartyConfiguration(rpConfig);
301             requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
302
303             String assertingPartyId = rpConfig.getProviderId();
304             requestContext.setLocalEntityId(assertingPartyId);
305             EntityDescriptor assertingPartyMetadata = metadataProvider.getEntityDescriptor(assertingPartyId);
306             requestContext.setLocalEntityMetadata(assertingPartyMetadata);
307             requestContext.setLocalEntityRole(IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
308             requestContext.setLocalEntityRoleMetadata(assertingPartyMetadata
309                     .getIDPSSODescriptor(SAMLConstants.SAML20P_NS));
310
311             requestContext.setOutboundMessageTransport(out);
312             requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
313             ShibbolethSSOConfiguration profileConfig = (ShibbolethSSOConfiguration) rpConfig
314                     .getProfileConfiguration(ShibbolethSSOConfiguration.PROFILE_ID);
315             requestContext.setProfileConfiguration(profileConfig);
316             requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
317             if (profileConfig.getSigningCredential() != null) {
318                 requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
319             } else if (rpConfig.getDefaultSigningCredential() != null) {
320                 requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
321             }
322
323             return requestContext;
324         } catch (MetadataProviderException e) {
325             log.error("Unable to locate metadata for asserting or relying party");
326             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error locating party metadata"));
327             throw new ProfileException("Error locating party metadata");
328         }
329     }
330
331     /**
332      * Selects the appropriate endpoint for the relying party and stores it in the request context.
333      * 
334      * @param requestContext current request context
335      * 
336      * @return Endpoint selected from the information provided in the request context
337      */
338     protected Endpoint selectEndpoint(ShibbolethSSORequestContext requestContext) {
339         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
340
341         ShibbolethSSOEndpointSelector endpointSelector = new ShibbolethSSOEndpointSelector();
342         endpointSelector.setSpAssertionConsumerService(loginContext.getSpAssertionConsumerService());
343         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
344         endpointSelector.setMetadataProvider(getMetadataProvider());
345         endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
346         endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
347         endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
348         endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
349
350         return endpointSelector.selectEndpoint();
351     }
352
353     /**
354      * Builds the authentication statement for the authenticated principal.
355      * 
356      * @param requestContext current request context
357      * 
358      * @return the created statement
359      * 
360      * @throws ProfileException thrown if the authentication statement can not be created
361      */
362     protected AuthenticationStatement buildAuthenticationStatement(ShibbolethSSORequestContext requestContext)
363             throws ProfileException {
364         ShibbolethSSOLoginContext loginContext = requestContext.getLoginContext();
365
366         AuthenticationStatement statement = authnStatementBuilder.buildObject();
367         statement.setAuthenticationInstant(loginContext.getAuthenticationInstant());
368         statement.setAuthenticationMethod(loginContext.getAuthenticationMethod());
369
370         statement.setSubjectLocality(buildSubjectLocality(requestContext));
371
372         Subject statementSubject = buildSubject(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:bearer");
373         statement.setSubject(statementSubject);
374
375         return statement;
376     }
377
378     /**
379      * Constructs the subject locality for the authentication statement.
380      * 
381      * @param requestContext curent request context
382      * 
383      * @return subject locality for the authentication statement
384      */
385     protected SubjectLocality buildSubjectLocality(ShibbolethSSORequestContext requestContext) {
386         SubjectLocality subjectLocality = subjectLocalityBuilder.buildObject();
387
388         HTTPInTransport inTransport = (HTTPInTransport) requestContext.getInboundMessageTransport();
389         subjectLocality.setIPAddress(inTransport.getPeerAddress());
390         subjectLocality.setDNSAddress(inTransport.getPeerDomainName());
391
392         return subjectLocality;
393     }
394
395     /** Represents the internal state of a Shibboleth SSO Request while it's being processed by the IdP. */
396     public class ShibbolethSSORequestContext extends
397             BaseSAML1ProfileRequestContext<Request, Response, ShibbolethSSOConfiguration> {
398
399         /** SP-provide assertion consumer service URL. */
400         private String spAssertionConsumerService;
401
402         /** Current login context. */
403         private ShibbolethSSOLoginContext loginContext;
404
405         /**
406          * Gets the current login context.
407          * 
408          * @return current login context
409          */
410         public ShibbolethSSOLoginContext getLoginContext() {
411             return loginContext;
412         }
413
414         /**
415          * Sets the current login context.
416          * 
417          * @param context current login context
418          */
419         public void setLoginContext(ShibbolethSSOLoginContext context) {
420             loginContext = context;
421         }
422
423         /**
424          * Gets the SP-provided assertion consumer service URL.
425          * 
426          * @return SP-provided assertion consumer service URL
427          */
428         public String getSpAssertionConsumerService() {
429             return spAssertionConsumerService;
430         }
431
432         /**
433          * Sets the SP-provided assertion consumer service URL.
434          * 
435          * @param acs SP-provided assertion consumer service URL
436          */
437         public void setSpAssertionConsumerService(String acs) {
438             spAssertionConsumerService = acs;
439         }
440     }
441 }