Search in sources :

Example 6 with SessionCookieConfig

use of jakarta.servlet.SessionCookieConfig in project tomcat by apache.

the class TestLoadBalancerDrainingValve method runValve.

@Test
public void runValve() throws Exception {
    IMocksControl control = EasyMock.createControl();
    ServletContext servletContext = control.createMock(ServletContext.class);
    Context ctx = control.createMock(Context.class);
    Request request = control.createMock(Request.class);
    Response response = control.createMock(Response.class);
    String sessionCookieName = "JSESSIONID";
    String sessionId = "cafebabe";
    String requestURI = "/test/path";
    SessionCookieConfig cookieConfig = new CookieConfig();
    cookieConfig.setDomain("example.com");
    cookieConfig.setName(sessionCookieName);
    cookieConfig.setPath("/");
    cookieConfig.setSecure(secureSessionConfig);
    // Valve.init requires all of this stuff
    EasyMock.expect(ctx.getMBeanKeyProperties()).andStubReturn("");
    EasyMock.expect(ctx.getName()).andStubReturn("");
    EasyMock.expect(ctx.getPipeline()).andStubReturn(new StandardPipeline());
    EasyMock.expect(ctx.getDomain()).andStubReturn("foo");
    EasyMock.expect(ctx.getLogger()).andStubReturn(org.apache.juli.logging.LogFactory.getLog(LoadBalancerDrainingValve.class));
    EasyMock.expect(ctx.getServletContext()).andStubReturn(servletContext);
    // Set up the actual test
    EasyMock.expect(request.getAttribute(LoadBalancerDrainingValve.ATTRIBUTE_KEY_JK_LB_ACTIVATION)).andStubReturn(jkActivation);
    EasyMock.expect(Boolean.valueOf(request.isRequestedSessionIdValid())).andStubReturn(Boolean.valueOf(validSessionId));
    ArrayList<Cookie> cookies = new ArrayList<>();
    if (enableIgnore) {
        cookies.add(new Cookie("ignore", "true"));
    }
    if (!validSessionId && jkActivation.equals("DIS")) {
        MyCookie cookie = new MyCookie(cookieConfig.getName(), sessionId);
        cookie.setPath(cookieConfig.getPath());
        cookie.setValue(sessionId);
        cookies.add(cookie);
        EasyMock.expect(request.getRequestedSessionId()).andStubReturn(sessionId);
        EasyMock.expect(request.getRequestURI()).andStubReturn(requestURI);
        EasyMock.expect(request.getCookies()).andStubReturn(cookies.toArray(new Cookie[0]));
        EasyMock.expect(request.getContext()).andStubReturn(ctx);
        EasyMock.expect(ctx.getSessionCookieName()).andStubReturn(sessionCookieName);
        EasyMock.expect(servletContext.getSessionCookieConfig()).andStubReturn(cookieConfig);
        EasyMock.expect(request.getQueryString()).andStubReturn(queryString);
        EasyMock.expect(ctx.getSessionCookiePath()).andStubReturn("/");
        if (!enableIgnore) {
            EasyMock.expect(Boolean.valueOf(ctx.getSessionCookiePathUsesTrailingSlash())).andStubReturn(Boolean.TRUE);
            EasyMock.expect(request.getQueryString()).andStubReturn(queryString);
            // Response will have cookie deleted
            MyCookie expectedCookie = new MyCookie(cookieConfig.getName(), "");
            expectedCookie.setPath(cookieConfig.getPath());
            expectedCookie.setMaxAge(0);
            EasyMock.expect(Boolean.valueOf(request.isSecure())).andReturn(secureRequest);
            // These two lines just mean EasyMock.expect(response.addCookie) but for a void method
            response.addCookie(expectedCookie);
            // Indirect call
            EasyMock.expect(ctx.getSessionCookieName()).andReturn(sessionCookieName);
            String expectedRequestURI = requestURI;
            if (null != queryString) {
                expectedRequestURI = expectedRequestURI + '?' + queryString;
            }
            response.setHeader("Location", expectedRequestURI);
            response.setStatus(307);
        }
    }
    Valve next = control.createMock(Valve.class);
    if (expectInvokeNext) {
        // Expect the "next" Valve to fire
        // Next 2 lines are basically EasyMock.expect(next.invoke(req,res)) but for a void method
        next.invoke(request, response);
        EasyMock.expectLastCall();
    }
    // Get set to actually test
    control.replay();
    LoadBalancerDrainingValve valve = new LoadBalancerDrainingValve();
    valve.setContainer(ctx);
    valve.init();
    valve.setNext(next);
    valve.setIgnoreCookieName("ignore");
    valve.setIgnoreCookieValue("true");
    valve.invoke(request, response);
    control.verify();
}
Also used : Context(org.apache.catalina.Context) ServletContext(jakarta.servlet.ServletContext) Cookie(jakarta.servlet.http.Cookie) Request(org.apache.catalina.connector.Request) ArrayList(java.util.ArrayList) SessionCookieConfig(jakarta.servlet.SessionCookieConfig) StandardPipeline(org.apache.catalina.core.StandardPipeline) IMocksControl(org.easymock.IMocksControl) Response(org.apache.catalina.connector.Response) ServletContext(jakarta.servlet.ServletContext) Valve(org.apache.catalina.Valve) SessionCookieConfig(jakarta.servlet.SessionCookieConfig) Test(org.junit.Test)

Example 7 with SessionCookieConfig

use of jakarta.servlet.SessionCookieConfig in project spring-boot by spring-projects.

the class AbstractServletWebServerFactoryTests method sessionCookieConfiguration.

@Test
void sessionCookieConfiguration() {
    AbstractServletWebServerFactory factory = getFactory();
    factory.getSession().getCookie().setName("testname");
    factory.getSession().getCookie().setDomain("testdomain");
    factory.getSession().getCookie().setPath("/testpath");
    factory.getSession().getCookie().setComment("testcomment");
    factory.getSession().getCookie().setHttpOnly(true);
    factory.getSession().getCookie().setSecure(true);
    factory.getSession().getCookie().setMaxAge(Duration.ofSeconds(60));
    final AtomicReference<SessionCookieConfig> configReference = new AtomicReference<>();
    this.webServer = factory.getWebServer((context) -> configReference.set(context.getSessionCookieConfig()));
    SessionCookieConfig sessionCookieConfig = configReference.get();
    assertThat(sessionCookieConfig.getName()).isEqualTo("testname");
    assertThat(sessionCookieConfig.getDomain()).isEqualTo("testdomain");
    assertThat(sessionCookieConfig.getPath()).isEqualTo("/testpath");
    assertThat(sessionCookieConfig.getComment()).isEqualTo("testcomment");
    assertThat(sessionCookieConfig.isHttpOnly()).isTrue();
    assertThat(sessionCookieConfig.isSecure()).isTrue();
    assertThat(sessionCookieConfig.getMaxAge()).isEqualTo(60);
}
Also used : Arrays(java.util.Arrays) GZIPInputStream(java.util.zip.GZIPInputStream) SSLContext(javax.net.ssl.SSLContext) KeyStoreException(java.security.KeyStoreException) ServletException(jakarta.servlet.ServletException) Assertions.assertThatIOException(org.assertj.core.api.Assertions.assertThatIOException) InetAddress(java.net.InetAddress) ServerSocket(java.net.ServerSocket) HttpSession(jakarta.servlet.http.HttpSession) Future(java.util.concurrent.Future) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BDDMockito.given(org.mockito.BDDMockito.given) Duration(java.time.Duration) Map(java.util.Map) PortInUseException(org.springframework.boot.web.server.PortInUseException) ClientAuth(org.springframework.boot.web.server.Ssl.ClientAuth) EnumSet(java.util.EnumSet) ServletContextInitializer(org.springframework.boot.web.servlet.ServletContextInitializer) Resource(org.springframework.core.io.Resource) PrintWriter(java.io.PrintWriter) ClassUtils(org.springframework.util.ClassUtils) ErrorPage(org.springframework.boot.web.server.ErrorPage) Mockito.atLeastOnce(org.mockito.Mockito.atLeastOnce) BlockingQueue(java.util.concurrent.BlockingQueue) StandardCharsets(java.nio.charset.StandardCharsets) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) SSLException(javax.net.ssl.SSLException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ServletContextEvent(jakarta.servlet.ServletContextEvent) Awaitility(org.awaitility.Awaitility) InputStreamFactory(org.apache.http.client.entity.InputStreamFactory) TrustSelfSignedStrategy(org.apache.http.conn.ssl.TrustSelfSignedStrategy) FileCopyUtils(org.springframework.util.FileCopyUtils) ServletContextListener(jakarta.servlet.ServletContextListener) Mockito.mock(org.mockito.Mockito.mock) Assertions.fail(org.junit.jupiter.api.Assertions.fail) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) HttpClientTransportOverHTTP2(org.eclipse.jetty.http2.client.http.HttpClientTransportOverHTTP2) WebServerException(org.springframework.boot.web.server.WebServerException) FutureTask(java.util.concurrent.FutureTask) SameSite(org.springframework.boot.web.server.Cookie.SameSite) Callable(java.util.concurrent.Callable) ApplicationTemp(org.springframework.boot.system.ApplicationTemp) Supplier(java.util.function.Supplier) WebServer(org.springframework.boot.web.server.WebServer) ClientHttpRequest(org.springframework.http.client.ClientHttpRequest) ThrowingCallable(org.assertj.core.api.ThrowableAssert.ThrowingCallable) HttpClient(org.apache.http.client.HttpClient) Assertions.assertThatExceptionOfType(org.assertj.core.api.Assertions.assertThatExceptionOfType) StandardHttpRequestRetryHandler(org.apache.http.impl.client.StandardHttpRequestRetryHandler) GenericServlet(jakarta.servlet.GenericServlet) HttpMethod(org.springframework.http.HttpMethod) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) HttpServlet(jakarta.servlet.http.HttpServlet) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) GracefulShutdownResult(org.springframework.boot.web.server.GracefulShutdownResult) Ssl(org.springframework.boot.web.server.Ssl) File(java.io.File) ExecutionException(java.util.concurrent.ExecutionException) HttpStatus(org.springframework.http.HttpStatus) Cookie(jakarta.servlet.http.Cookie) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Assumptions(org.junit.jupiter.api.Assumptions) HttpContext(org.apache.http.protocol.HttpContext) Assertions.assertThatIllegalArgumentException(org.assertj.core.api.Assertions.assertThatIllegalArgumentException) HttpResponse(org.apache.http.HttpResponse) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) CapturedOutput(org.springframework.boot.testsupport.system.CapturedOutput) X509Certificate(java.security.cert.X509Certificate) FilterRegistrationBean(org.springframework.boot.web.servlet.FilterRegistrationBean) ExampleFilter(org.springframework.boot.testsupport.web.servlet.ExampleFilter) URL(java.net.URL) Date(java.util.Date) URISyntaxException(java.net.URISyntaxException) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) HTTP2Client(org.eclipse.jetty.http2.client.HTTP2Client) ExampleServlet(org.springframework.boot.testsupport.web.servlet.ExampleServlet) Filter(jakarta.servlet.Filter) FilterConfig(jakarta.servlet.FilterConfig) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Locale(java.util.Locale) DefaultHttpRequestRetryHandler(org.apache.http.impl.client.DefaultHttpRequestRetryHandler) URI(java.net.URI) SSLConnectionSocketFactory(org.apache.http.conn.ssl.SSLConnectionSocketFactory) JspServlet(org.apache.jasper.servlet.JspServlet) MimeMappings(org.springframework.boot.web.server.MimeMappings) ServletRequest(jakarta.servlet.ServletRequest) Collection(java.util.Collection) Http2(org.springframework.boot.web.server.Http2) FileSystemResource(org.springframework.core.io.FileSystemResource) KeyStore(java.security.KeyStore) Objects(java.util.Objects) Test(org.junit.jupiter.api.Test) List(java.util.List) HttpGet(org.apache.http.client.methods.HttpGet) ApplicationHome(org.springframework.boot.system.ApplicationHome) TempDir(org.junit.jupiter.api.io.TempDir) Mockito.inOrder(org.mockito.Mockito.inOrder) ServletResponse(jakarta.servlet.ServletResponse) ServletContext(jakarta.servlet.ServletContext) HttpClients(org.apache.http.impl.client.HttpClients) AsyncContext(jakarta.servlet.AsyncContext) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) TrustStrategy(org.apache.http.ssl.TrustStrategy) SessionCookieConfig(jakarta.servlet.SessionCookieConfig) ClassPathResource(org.springframework.core.io.ClassPathResource) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) Dynamic(jakarta.servlet.ServletRegistration.Dynamic) EnumSource(org.junit.jupiter.params.provider.EnumSource) AtomicReference(java.util.concurrent.atomic.AtomicReference) EmbeddedServletOptions(org.apache.jasper.EmbeddedServletOptions) SessionTrackingMode(org.springframework.boot.web.servlet.server.Session.SessionTrackingMode) Charset(java.nio.charset.Charset) OutputCaptureExtension(org.springframework.boot.testsupport.system.OutputCaptureExtension) Compression(org.springframework.boot.web.server.Compression) Shutdown(org.springframework.boot.web.server.Shutdown) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) TomcatURLStreamHandlerFactory(org.apache.catalina.webresources.TomcatURLStreamHandlerFactory) ServletRegistrationBean(org.springframework.boot.web.servlet.ServletRegistrationBean) ClientHttpResponse(org.springframework.http.client.ClientHttpResponse) RunnableFuture(java.util.concurrent.RunnableFuture) StreamUtils(org.springframework.util.StreamUtils) Assertions.assertThatIllegalStateException(org.assertj.core.api.Assertions.assertThatIllegalStateException) InOrder(org.mockito.InOrder) MalformedURLException(java.net.MalformedURLException) FileWriter(java.io.FileWriter) FilterChain(jakarta.servlet.FilterChain) ReflectionTestUtils(org.springframework.test.util.ReflectionTestUtils) BDDMockito.then(org.mockito.BDDMockito.then) CertificateException(java.security.cert.CertificateException) HttpComponentsClientHttpRequestFactory(org.springframework.http.client.HttpComponentsClientHttpRequestFactory) SslStoreProvider(org.springframework.boot.web.server.SslStoreProvider) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) Collections(java.util.Collections) InputStream(java.io.InputStream) SessionCookieConfig(jakarta.servlet.SessionCookieConfig) AtomicReference(java.util.concurrent.atomic.AtomicReference) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Test(org.junit.jupiter.api.Test)

Example 8 with SessionCookieConfig

use of jakarta.servlet.SessionCookieConfig in project tomcat by apache.

the class LoadBalancerDrainingValve method invoke.

@Override
public void invoke(Request request, Response response) throws IOException, ServletException {
    if ("DIS".equals(request.getAttribute(ATTRIBUTE_KEY_JK_LB_ACTIVATION)) && !request.isRequestedSessionIdValid()) {
        if (containerLog.isDebugEnabled()) {
            containerLog.debug("Load-balancer is in DISABLED state; draining this node");
        }
        boolean ignoreRebalance = false;
        Cookie sessionCookie = null;
        final Cookie[] cookies = request.getCookies();
        final String sessionCookieName = SessionConfig.getSessionCookieName(request.getContext());
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                final String cookieName = cookie.getName();
                if (containerLog.isTraceEnabled()) {
                    containerLog.trace("Checking cookie " + cookieName + "=" + cookie.getValue());
                }
                if (sessionCookieName.equals(cookieName) && request.getRequestedSessionId().equals(cookie.getValue())) {
                    sessionCookie = cookie;
                } else if (null != _ignoreCookieName && _ignoreCookieName.equals(cookieName) && null != _ignoreCookieValue && _ignoreCookieValue.equals(cookie.getValue())) {
                    // The client presenting a valid ignore-cookie value?
                    ignoreRebalance = true;
                }
            }
        }
        if (ignoreRebalance) {
            if (containerLog.isDebugEnabled()) {
                containerLog.debug("Client is presenting a valid " + _ignoreCookieName + " cookie, re-balancing is being skipped");
            }
            getNext().invoke(request, response);
            return;
        }
        // TODO: Consider implications of SSO cookies
        if (null != sessionCookie) {
            sessionCookie.setPath(SessionConfig.getSessionCookiePath(request.getContext()));
            // Delete
            sessionCookie.setMaxAge(0);
            // Purge the cookie's value
            sessionCookie.setValue("");
            // Replicate logic used to set secure attribute for session cookies
            SessionCookieConfig sessionCookieConfig = request.getContext().getServletContext().getSessionCookieConfig();
            sessionCookie.setSecure(request.isSecure() || sessionCookieConfig.isSecure());
            response.addCookie(sessionCookie);
        }
        // Re-write the URI if it contains a ;jsessionid parameter
        String uri = request.getRequestURI();
        String sessionURIParamName = SessionConfig.getSessionUriParamName(request.getContext());
        if (uri.contains(";" + sessionURIParamName + "=")) {
            uri = uri.replaceFirst(";" + sessionURIParamName + "=[^&?]*", "");
        }
        String queryString = request.getQueryString();
        if (null != queryString) {
            uri = uri + "?" + queryString;
        }
        // NOTE: Do not call response.encodeRedirectURL or the bad
        // sessionid will be restored
        response.setHeader("Location", uri);
        response.setStatus(_redirectStatusCode);
    } else {
        getNext().invoke(request, response);
    }
}
Also used : Cookie(jakarta.servlet.http.Cookie) SessionCookieConfig(jakarta.servlet.SessionCookieConfig)

Aggregations

SessionCookieConfig (jakarta.servlet.SessionCookieConfig)8 Cookie (jakarta.servlet.http.Cookie)4 ServletContext (jakarta.servlet.ServletContext)3 Filter (jakarta.servlet.Filter)2 ServletException (jakarta.servlet.ServletException)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 AsyncContext (jakarta.servlet.AsyncContext)1 FilterChain (jakarta.servlet.FilterChain)1 FilterConfig (jakarta.servlet.FilterConfig)1 GenericServlet (jakarta.servlet.GenericServlet)1 MultipartConfigElement (jakarta.servlet.MultipartConfigElement)1 Servlet (jakarta.servlet.Servlet)1 ServletContextEvent (jakarta.servlet.ServletContextEvent)1 ServletContextListener (jakarta.servlet.ServletContextListener)1 Dynamic (jakarta.servlet.ServletRegistration.Dynamic)1 ServletRequest (jakarta.servlet.ServletRequest)1 ServletResponse (jakarta.servlet.ServletResponse)1 HttpServlet (jakarta.servlet.http.HttpServlet)1 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)1