This is an automated email from the ASF dual-hosted git repository.

coheigea pushed a commit to branch 4.1.x-fixes
in repository https://gitbox.apache.org/repos/asf/cxf.git

commit 2de76beb4587257058bf4a9dd9fcd5ddf63d884d
Author: Naveed Khan <[email protected]>
AuthorDate: Mon Nov 16 19:15:31 2026 +0530

    set HttpOnly and Secure on SAML SSO SP cookies (#3691)
    
    * set HttpOnly and Secure on SAML SSO SP cookies
    
    * check servlet request for https and add SameSite=Lax to SAML SSO SP 
cookies
    
    (cherry picked from commit d7e438980b603e8433494c39734eb070965eab38)
---
 .../rs/security/saml/sso/AbstractSSOSpHandler.java | 101 +++++++++++++-
 .../saml/sso/AbstractSSOSpHandlerTest.java         | 155 +++++++++++++++++++++
 2 files changed, 255 insertions(+), 1 deletion(-)

diff --git 
a/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/AbstractSSOSpHandler.java
 
b/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/AbstractSSOSpHandler.java
index 5460dcfa5c4..3952dda841b 100644
--- 
a/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/AbstractSSOSpHandler.java
+++ 
b/rt/rs/security/sso/saml/src/main/java/org/apache/cxf/rs/security/saml/sso/AbstractSSOSpHandler.java
@@ -29,12 +29,15 @@ import java.util.logging.Logger;
 import javax.security.auth.callback.CallbackHandler;
 
 import jakarta.annotation.PreDestroy;
+import jakarta.servlet.http.HttpServletRequest;
 import org.apache.cxf.common.logging.LogUtils;
 import org.apache.cxf.jaxrs.impl.UriInfoImpl;
 import org.apache.cxf.jaxrs.utils.HttpUtils;
+import org.apache.cxf.jaxrs.utils.JAXRSUtils;
 import org.apache.cxf.message.Message;
 import org.apache.cxf.rs.security.saml.sso.state.SPStateManager;
 import org.apache.cxf.rt.security.utils.SecurityUtils;
+import org.apache.cxf.transport.http.AbstractHTTPDestination;
 import org.apache.wss4j.common.crypto.Crypto;
 import org.apache.wss4j.common.crypto.CryptoFactory;
 import org.apache.wss4j.common.ext.WSSecurityException;
@@ -54,6 +57,9 @@ public class AbstractSSOSpHandler {
     private String idpServiceAddress;
     private String issuerId;
     private boolean supportUnsolicited;
+    private boolean httpOnlyCookie = true;
+    private boolean secureCookie;
+    private String sameSite = "Lax";
 
     static {
         OpenSAMLUtil.initSamlEngine();
@@ -134,11 +140,104 @@ public class AbstractSSOSpHandler {
             contextCookie += ";Expires=" + cookieExpires;
         }
 
-        //TODO: Consider adding an 'HttpOnly' attribute
+        if (httpOnlyCookie) {
+            // The cookie value is the key to the security context or relay 
state
+            // held by the SP, so keep it out of reach of scripts
+            contextCookie += ";HttpOnly";
+        }
+
+        if (secureCookie || isSecureRequest(JAXRSUtils.getCurrentMessage())) {
+            contextCookie += ";Secure";
+        }
+
+        if (sameSite != null) {
+            contextCookie += ";SameSite=" + sameSite;
+        }
 
         return contextCookie;
     }
 
+    /**
+     * Determine whether the current request was received over HTTPS, in which 
case the
+     * cookies created by this handler get the Secure attribute.
+     * <p>
+     * The servlet request is checked first, so that a container configured 
for a TLS
+     * terminating proxy (e.g. Tomcat's RemoteIpValve) is honored. Without a 
servlet
+     * request this falls back on a best-effort check of the scheme of the 
request URL
+     * or base path.
+     * @param m the current message, may be null
+     * @return true if the request was received over HTTPS, false otherwise, 
including
+     *         when m is null or the scheme cannot be determined
+     */
+    protected boolean isSecureRequest(Message m) {
+        if (m == null) {
+            return false;
+        }
+        Object request = m.get(AbstractHTTPDestination.HTTP_REQUEST);
+        if (request instanceof HttpServletRequest) {
+            return ((HttpServletRequest) request).isSecure();
+        }
+        Object address = m.get(Message.REQUEST_URL);
+        if (address == null) {
+            address = m.get(Message.BASE_PATH);
+        }
+        return address != null && address.toString().regionMatches(true, 0, 
"https://";, 0, 8);
+    }
+
+    /**
+     * Set whether the cookies created by this handler have the HttpOnly 
attribute.
+     * The default is true.
+     * @param httpOnlyCookie whether to add the HttpOnly attribute
+     */
+    public void setHttpOnlyCookie(boolean httpOnlyCookie) {
+        this.httpOnlyCookie = httpOnlyCookie;
+    }
+
+    /**
+     * Get whether the cookies created by this handler have the HttpOnly 
attribute.
+     * @return whether the HttpOnly attribute is added
+     */
+    public boolean isHttpOnlyCookie() {
+        return httpOnlyCookie;
+    }
+
+    /**
+     * Set whether the cookies created by this handler always have the Secure 
attribute.
+     * The default is false, in which case the attribute is added only when 
the current
+     * request was received over HTTPS.
+     * @param secureCookie whether to always add the Secure attribute
+     */
+    public void setSecureCookie(boolean secureCookie) {
+        this.secureCookie = secureCookie;
+    }
+
+    /**
+     * Get whether the cookies created by this handler always have the Secure 
attribute.
+     * @return whether the Secure attribute is always added, regardless of the 
request scheme
+     */
+    public boolean isSecureCookie() {
+        return secureCookie;
+    }
+
+    /**
+     * Set the value of the SameSite attribute of the cookies created by this 
handler.
+     * The default is "Lax", which still lets the browser send the cookies on 
the top-level
+     * redirect back to the application after the IdP has posted to the RACS. 
"Strict" breaks
+     * that first request. A null value leaves the attribute out.
+     * @param sameSite the SameSite attribute value, or null to leave the 
attribute out
+     */
+    public void setSameSite(String sameSite) {
+        this.sameSite = sameSite;
+    }
+
+    /**
+     * Get the value of the SameSite attribute of the cookies created by this 
handler.
+     * @return the SameSite attribute value, or null if the attribute is left 
out
+     */
+    public String getSameSite() {
+        return sameSite;
+    }
+
     public void setStateProvider(SPStateManager stateProvider) {
         this.stateProvider = stateProvider;
     }
diff --git 
a/rt/rs/security/sso/saml/src/test/java/org/apache/cxf/rs/security/saml/sso/AbstractSSOSpHandlerTest.java
 
b/rt/rs/security/sso/saml/src/test/java/org/apache/cxf/rs/security/saml/sso/AbstractSSOSpHandlerTest.java
new file mode 100644
index 00000000000..f4412d89ef4
--- /dev/null
+++ 
b/rt/rs/security/sso/saml/src/test/java/org/apache/cxf/rs/security/saml/sso/AbstractSSOSpHandlerTest.java
@@ -0,0 +1,155 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.cxf.rs.security.saml.sso;
+
+import java.lang.reflect.Proxy;
+
+import jakarta.servlet.http.HttpServletRequest;
+import org.apache.cxf.message.Message;
+import org.apache.cxf.message.MessageImpl;
+import org.apache.cxf.transport.http.AbstractHTTPDestination;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+public class AbstractSSOSpHandlerTest {
+
+    @Test
+    public void testDefaultCookieAttributes() {
+        TestHandler handler = new TestHandler();
+        handler.setStateTimeToLive(0);
+
+        assertTrue(handler.isHttpOnlyCookie());
+        assertFalse(handler.isSecureCookie());
+        assertEquals("Lax", handler.getSameSite());
+
+        String cookie = 
handler.createCookie(SSOConstants.SECURITY_CONTEXT_TOKEN, "key", "/app", null);
+
+        assertEquals(SSOConstants.SECURITY_CONTEXT_TOKEN + 
"=key;Path=/app;HttpOnly;SameSite=Lax", cookie);
+    }
+
+    @Test
+    public void testHttpOnlyAndSameSiteCanBeDisabled() {
+        TestHandler handler = new TestHandler();
+        handler.setStateTimeToLive(0);
+        handler.setHttpOnlyCookie(false);
+        handler.setSameSite(null);
+        assertNull(handler.getSameSite());
+
+        String cookie = handler.createCookie(SSOConstants.RELAY_STATE, 
"state", "/app", "example.com");
+
+        assertEquals(SSOConstants.RELAY_STATE + 
"=state;Path=/app;Domain=example.com", cookie);
+    }
+
+    @Test
+    public void testSecureCookieWithCustomSameSite() {
+        TestHandler handler = new TestHandler();
+        handler.setStateTimeToLive(0);
+        handler.setSecureCookie(true);
+        handler.setSameSite("Strict");
+
+        String cookie = 
handler.createCookie(SSOConstants.SECURITY_CONTEXT_TOKEN, "key", "/app", 
"example.com");
+
+        assertEquals(SSOConstants.SECURITY_CONTEXT_TOKEN
+            + 
"=key;Path=/app;Domain=example.com;HttpOnly;Secure;SameSite=Strict", cookie);
+    }
+
+    @Test
+    public void testCookieWithExpires() {
+        TestHandler handler = new TestHandler();
+
+        String cookie = 
handler.createCookie(SSOConstants.SECURITY_CONTEXT_TOKEN, "key", "/app", null);
+
+        String prefix = SSOConstants.SECURITY_CONTEXT_TOKEN + 
"=key;Path=/app;Expires=";
+        assertTrue(cookie, cookie.startsWith(prefix));
+        assertTrue(cookie, cookie.endsWith(";HttpOnly;SameSite=Lax"));
+    }
+
+    @Test
+    public void testIsSecureRequestFromUrl() {
+        TestHandler handler = new TestHandler();
+
+        assertFalse(handler.isSecureRequest(null));
+
+        Message m = new MessageImpl();
+        assertFalse(handler.isSecureRequest(m));
+
+        m.put(Message.REQUEST_URL, "http://sp.example.com/app/sso";);
+        assertFalse(handler.isSecureRequest(m));
+
+        m.put(Message.REQUEST_URL, "https://sp.example.com/app/sso";);
+        assertTrue(handler.isSecureRequest(m));
+
+        m.put(Message.REQUEST_URL, "HTTPS://sp.example.com/app/sso");
+        assertTrue(handler.isSecureRequest(m));
+
+        Message m2 = new MessageImpl();
+        m2.put(Message.BASE_PATH, "https://sp.example.com/app";);
+        assertTrue(handler.isSecureRequest(m2));
+
+        // the configured endpoint address says nothing about the scheme of 
the current request
+        Message m3 = new MessageImpl();
+        m3.put(Message.ENDPOINT_ADDRESS, "https://sp.example.com/app";);
+        assertFalse(handler.isSecureRequest(m3));
+    }
+
+    @Test
+    public void testIsSecureRequestFromServletRequest() {
+        TestHandler handler = new TestHandler();
+
+        // TLS terminated at a proxy: the request URL is http but the 
container reports a secure request
+        Message m = new MessageImpl();
+        m.put(Message.REQUEST_URL, "http://sp.example.com/app/sso";);
+        m.put(AbstractHTTPDestination.HTTP_REQUEST, servletRequest(true));
+        assertTrue(handler.isSecureRequest(m));
+
+        Message m2 = new MessageImpl();
+        m2.put(Message.REQUEST_URL, "https://sp.example.com/app/sso";);
+        m2.put(AbstractHTTPDestination.HTTP_REQUEST, servletRequest(false));
+        assertFalse(handler.isSecureRequest(m2));
+    }
+
+    private static HttpServletRequest servletRequest(boolean secure) {
+        return (HttpServletRequest) Proxy.newProxyInstance(
+            AbstractSSOSpHandlerTest.class.getClassLoader(),
+            new Class<?>[] {HttpServletRequest.class},
+            (proxy, method, args) -> {
+                if ("isSecure".equals(method.getName())) {
+                    return secure;
+                }
+                throw new UnsupportedOperationException(method.getName());
+            });
+    }
+
+    private static final class TestHandler extends AbstractSSOSpHandler {
+        @Override
+        protected String createCookie(String name, String value, String path, 
String domain) {
+            return super.createCookie(name, value, path, domain);
+        }
+
+        @Override
+        protected boolean isSecureRequest(Message m) {
+            return super.isSecureRequest(m);
+        }
+    }
+}

Reply via email to