From c697b98619e7455436906eecc70d18ff88432ee9 Mon Sep 17 00:00:00 2001 From: Johan Lindh Date: Fri, 6 Nov 2026 09:59:48 +0100 Subject: [PATCH 1/7] Use __Host- cookies for HTTPS sessions --- doc/deployment.md | 2 + doc/sessions.md | 25 +++++- jaws.go | 13 +++- request_test.go | 28 ++++++- requestpool.go | 5 +- session.go | 58 ++++++++++---- session_test.go | 194 ++++++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 302 insertions(+), 23 deletions(-) diff --git a/doc/deployment.md b/doc/deployment.md index 6c403f08..8d82414a 100644 --- a/doc/deployment.md +++ b/doc/deployment.md @@ -74,6 +74,8 @@ Wrap page handlers in `jw.SecureHeadersMiddleware(page)` to apply the Behind a proxy that terminates TLS, set HSTS at the proxy: this middleware does not trust forwarded HTTPS headers, even when `TrustForwardedHeaders` is enabled for JaWS's other checks. +JaWS uses a [host-only cookie name](sessions.md#http-and-https-cookies) for +HTTPS Sessions. Ensure it recognizes the forwarded HTTPS scheme. `NewRequest` makes rendered pages non-cacheable. Keep callback and tail-script responses non-cacheable; hashed static assets may be cached. diff --git a/doc/sessions.md b/doc/sessions.md index 4d9d7135..c2ca23b0 100644 --- a/doc/sessions.md +++ b/doc/sessions.md @@ -7,6 +7,26 @@ cookie and the client IP seen by JaWS. They expire and do not survive an engine restart. A Session identifies stored state; application authentication and authorization remain separate concerns. +## HTTP and HTTPS cookies + +JaWS uses `jw.CookieName` for HTTP Sessions and prefixes it with `__Host-` for +recognized HTTPS Sessions. It never accepts one scheme's cookie for the other +scheme. Browsers that enforce the [`__Host-` prefix](https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-4.1.3.2) +accept the HTTPS cookie only with `Secure`, `Path=/`, and no `Domain`. JaWS sets +these attributes when it recognizes HTTPS. This prevents sibling domains and +browser-visible insecure HTTP responses from planting the HTTPS cookie name. + +Redirect browsers to HTTPS before creating Sessions for authentication. +HTTP Sessions remain exposed to plaintext network traffic. Behind a +TLS-terminating proxy, configure trusted forwarded scheme headers as described +in [deployment](deployment.md#reverse-proxies). + +An explicitly `__Host-`-prefixed `jw.CookieName` uses that name on HTTPS and +disables HTTP Session use: `GetSession` and `NewRequest` ignore matching cookies, +`NewSession` returns nil, `SessionMiddleware` returns HTTP 503, and `AutoSession` +skips creation. Existing browser sessions using an unprefixed HTTPS cookie name +are not recognized. + ## Create a session before rendering Wrap the page in `SessionMiddleware` when initial rendering needs a Session. @@ -89,8 +109,9 @@ and cookies are preserved. `MaxSessions` limits registered Sessions globally. `MaxSessionsPerIP` limits a client address bucket. Both default to zero, which disables the respective -limit. A lower per-IP cap reserves capacity for other buckets. Replacement needs -a free slot under both enabled caps and preserves the old Session on refusal. +limit. HTTP and HTTPS Sessions both count toward these limits. A lower per-IP cap +reserves capacity for other buckets. Replacement needs a free slot under both +enabled caps and preserves the old Session on refusal. When middleware cannot create a Session, it skips the page handler. A full per-IP bucket returns HTTP 429 while global capacity remains; the global limit diff --git a/jaws.go b/jaws.go index 4c2fa41a..8b7ef969 100644 --- a/jaws.go +++ b/jaws.go @@ -94,17 +94,24 @@ type Jid = jid.Jid // convenience alias // may be changed while serving. Methods document their own concurrency behavior // and may be called concurrently when stated. type Jaws struct { - // CookieName is the name used for session cookies. + // CookieName is the base name used for session cookies. // // It defaults to [assets.DefaultCookieName], which is derived from the // executable and falls back to "jaws". CookieName must be a valid, non-empty // HTTP cookie name; see [http.Cookie.Valid]. + // + // HTTP sessions use this name. Recognized HTTPS sessions use a "__Host-" + // prefix so supporting browsers enforce host-only cookies. The two schemes + // do not share Sessions. An explicitly prefixed name makes HTTP Sessions + // unavailable; see [Jaws.TrustForwardedHeaders] for proxy scheme detection. CookieName string // AutoSession creates a [Session] on a successful WebSocket upgrade. // // It applies when the [Request] has no Session and Session limits allow one. - // The cookie's Secure flag follows the initial page request's scheme, honoring - // [Jaws.TrustForwardedHeaders]. AutoSession defaults to false. + // The cookie name and Secure flag follow the initial page request's scheme, + // honoring [Jaws.TrustForwardedHeaders]. An explicitly "__Host-"-prefixed + // CookieName requires that request to be recognized as HTTPS. AutoSession + // defaults to false. AutoSession bool // TrustForwardedHeaders enables trusted proxy header processing. // diff --git a/request_test.go b/request_test.go index 39d996c3..b6d54dcd 100644 --- a/request_test.go +++ b/request_test.go @@ -4285,11 +4285,15 @@ func TestWS_AutoSessionSecureFollowsPage(t *testing.T) { pageScheme string upgradeScheme string wantSecure bool + hostPrefix bool }{ - {"HTTP page", "http", "", false}, - {"HTTPS scheme on both requests", "https", "https", true}, - {"HTTPS scheme only on page", "https", "", true}, - {"HTTPS scheme only on upgrade", "http", "https", false}, + {"HTTP page", "http", "", false, false}, + {"HTTPS scheme on both requests", "https", "https", true, false}, + {"HTTPS scheme only on page", "https", "", true, false}, + {"HTTPS scheme only on upgrade", "http", "https", false, false}, + {"__Host- HTTP page", "http", "", false, true}, + {"__Host- HTTPS page", "https", "https", true, true}, + {"__Host- HTTPS upgrade only", "http", "https", false, true}, } { t.Run(tc.name, func(t *testing.T) { jw, err := New() @@ -4298,6 +4302,9 @@ func TestWS_AutoSessionSecureFollowsPage(t *testing.T) { } jw.AutoSession = true jw.TrustForwardedHeaders = true + if tc.hostPrefix { + jw.CookieName = "__Host-" + jw.CookieName + } go jw.Serve() t.Cleanup(jw.Close) server := httptest.NewServer(jw) @@ -4327,12 +4334,25 @@ func TestWS_AutoSessionSecureFollowsPage(t *testing.T) { t.Fatalf("status = %d, want 101", resp.StatusCode) } cookies := resp.Cookies() + if tc.hostPrefix && !tc.wantSecure { + if len(cookies) != 0 || rq.Session() != nil { + t.Fatalf("insecure __Host- AutoSession: cookies=%v session=%p", cookies, rq.Session()) + } + return + } if len(cookies) != 1 { t.Fatalf("AutoSession cookies = %v, want one", cookies) } if cookies[0].Secure != tc.wantSecure { t.Fatalf("AutoSession cookie Secure = %v, want %v", cookies[0].Secure, tc.wantSecure) } + wantName := jw.CookieName + if tc.wantSecure && !tc.hostPrefix { + wantName = "__Host-" + wantName + } + if cookies[0].Name != wantName { + t.Fatalf("AutoSession cookie name = %q, want %q", cookies[0].Name, wantName) + } }) } } diff --git a/requestpool.go b/requestpool.go index 29263e04..8406621f 100644 --- a/requestpool.go +++ b/requestpool.go @@ -20,6 +20,7 @@ import ( "weak" "github.com/linkdata/jaws/lib/key" + "github.com/linkdata/secureheaders" ) // NewRequest returns a new JaWS Request. @@ -36,6 +37,7 @@ import ( // handling and rendering; see [Request]. // // If r is nil, the Request has no initial request, client address, or [Session]. +// Otherwise, its Session follows the request's scheme; see [Jaws.CookieName]. // // [Jaws.ServeWithTimeout] periodically retires idle Requests before WebSocket // processing starts; [Jaws.Serve] uses [DefaultWebSocketTimeout]. @@ -294,7 +296,8 @@ func (jw *Jaws) getRequestLocked(jawsKey key.Key, r *http.Request, remoteIP neti rq.remoteIP = remoteIP rq.ctx, rq.cancelFn = context.WithCancelCause(jw.BaseContext) if registered && r != nil { - if sess := jw.getSessionLocked(getCookieSessionsIDs(r.Header, jw.CookieName), rq.remoteIP); sess != nil { + cookieName := jw.sessionCookieName(secureheaders.RequestIsSecure(r, jw.TrustForwardedHeaders)) + if sess := jw.getSessionLocked(getCookieSessionsIDs(r.Header, cookieName), rq.remoteIP, cookieName); sess != nil { sess.addRequest(rq) rq.session = sess } diff --git a/session.go b/session.go index 26ee1458..5ecae8b0 100644 --- a/session.go +++ b/session.go @@ -17,11 +17,32 @@ import ( "github.com/linkdata/secureheaders" ) -const sessionGrace = time.Minute +const ( + sessionGrace = time.Minute + hostCookiePrefix = "__Host-" +) + +func hasHostCookiePrefix(name string) bool { + return strings.HasPrefix(name, hostCookiePrefix) +} + +func (jw *Jaws) sessionCookieName(secure bool) string { + if !secure { + if hasHostCookiePrefix(jw.CookieName) { + return "" + } + return jw.CookieName + } + if !hasHostCookiePrefix(jw.CookieName) { + return hostCookiePrefix + jw.CookieName + } + return jw.CookieName +} // Session stores server-side state shared by one or more Requests. // // Sessions live in memory and are bound to the remote IP that created them. +// HTTP and HTTPS requests use distinct cookie names and Sessions. // Their cookies have no explicit expiry or MaxAge. A Session starts with a // one-minute grace deadline; ExtendGrace can lengthen it for a bounded external // flow. Detaching a claimed Request refreshes the normal grace without shortening @@ -50,7 +71,7 @@ func newSession(jw *Jaws, sessionID key.Key, remoteIP netip.Addr, secure bool) * remoteIP: remoteIP, deadline: time.Now().Add(sessionGrace), cookie: http.Cookie{ // #nosec G124 -- Secure is set from the request scheme, and HttpOnly/SameSite are set below. - Name: jw.CookieName, + Name: jw.sessionCookieName(secure), Path: "/", Value: sessionID.String(), Secure: secure, @@ -345,16 +366,18 @@ func (jw *Jaws) Sessions() (sessions []*Session) { return } -func (jw *Jaws) getSessionByIDLocked(sessionID key.Key, remoteIP netip.Addr) (sess *Session) { - if found, ok := jw.sessions[sessionID]; ok && equalIP(remoteIP, found.remoteIP) && !found.isDead() { +func (jw *Jaws) getSessionByIDLocked(sessionID key.Key, remoteIP netip.Addr, cookieName string) (sess *Session) { + // A valid ID under the other scheme's cookie name must not cross the + // HTTP/HTTPS session boundary. The cookie name is fixed at creation. + if found, ok := jw.sessions[sessionID]; ok && found.cookie.Name == cookieName && equalIP(remoteIP, found.remoteIP) && !found.isDead() { sess = found } return } -func (jw *Jaws) getSessionLocked(sessionIDs []key.Key, remoteIP netip.Addr) (sess *Session) { +func (jw *Jaws) getSessionLocked(sessionIDs []key.Key, remoteIP netip.Addr, cookieName string) (sess *Session) { for _, sessionID := range sessionIDs { - if sess = jw.getSessionByIDLocked(sessionID, remoteIP); sess != nil { + if sess = jw.getSessionByIDLocked(sessionID, remoteIP, cookieName); sess != nil { break } } @@ -392,12 +415,14 @@ func getCookieSessionsIDs(h http.Header, wanted string) (cookies []key.Key) { // proxy that connects over loopback, every request appears to come from loopback // and IP binding is effectively disabled unless [Jaws.TrustForwardedHeaders] is // enabled so the forwarded client IP is used instead. +// HTTP cookies are ignored on HTTPS requests and vice versa; see [Jaws.CookieName]. func (jw *Jaws) GetSession(r *http.Request) (sess *Session) { if r != nil { - if sessionIDs := getCookieSessionsIDs(r.Header, jw.CookieName); len(sessionIDs) > 0 { + cookieName := jw.sessionCookieName(secureheaders.RequestIsSecure(r, jw.TrustForwardedHeaders)) + if sessionIDs := getCookieSessionsIDs(r.Header, cookieName); len(sessionIDs) > 0 { remoteIP := jw.clientIP(r) jw.mu.RLock() - sess = jw.getSessionLocked(sessionIDs, remoteIP) + sess = jw.getSessionLocked(sessionIDs, remoteIP, cookieName) jw.mu.RUnlock() } } @@ -429,7 +454,9 @@ func (jw *Jaws) GetSession(r *http.Request) (sess *Session) { // // It returns nil without closing matching Sessions if r is nil, shutdown has // begun, [Jaws.MaxSessions] or [Jaws.MaxSessionsPerIP] is reached, or cookie -// publication fails; w may be nil. +// publication fails. It also returns nil when an explicitly "__Host-"-prefixed +// [Jaws.CookieName] is used on a request JaWS does not recognize as HTTPS; +// w may be nil. Cookie names follow [Jaws.GetSession]. // // Replacing a Session requires a free slot under each enabled limit until the // new cookie is published and the old Session is closed. @@ -438,13 +465,14 @@ func (jw *Jaws) GetSession(r *http.Request) (sess *Session) { // generating the session ID. Go's default reader does not return errors. func (jw *Jaws) NewSession(w http.ResponseWriter, r *http.Request) (sess *Session) { if r != nil { - sessionIDs := getCookieSessionsIDs(r.Header, jw.CookieName) + cookieName := jw.sessionCookieName(secureheaders.RequestIsSecure(r, jw.TrustForwardedHeaders)) + sessionIDs := getCookieSessionsIDs(r.Header, cookieName) sess, _ = jw.newSession(w, r) if sess != nil && len(sessionIDs) > 0 { remoteIP := jw.clientIP(r) for _, sessionID := range sessionIDs { jw.mu.RLock() - oldSess := jw.getSessionByIDLocked(sessionID, remoteIP) + oldSess := jw.getSessionByIDLocked(sessionID, remoteIP, cookieName) jw.mu.RUnlock() if oldSess != nil { oldSess.Clear() @@ -474,12 +502,16 @@ func (jw *Jaws) newSession(w http.ResponseWriter, r *http.Request) (sess *Sessio } // newSessionLocked allocates a Session whose ID is absent from jw.sessions, or -// returns nil after shutdown begins or a Session limit is reached. limitIP -// distinguishes the per-client limit for SessionMiddleware's HTTP response. +// returns nil after shutdown begins, a Session limit is reached, or a "__Host-" +// cookie name would be used without Secure. limitIP distinguishes the per-client +// limit for SessionMiddleware's HTTP response. // // The caller must hold jw.mu and publish any returned Session before releasing // it. func (jw *Jaws) newSessionLocked(remoteIP netip.Addr, secure bool) (sess *Session, limitIP bool) { + if !secure && hasHostCookiePrefix(jw.CookieName) { + return + } select { case <-jw.closeCh: return diff --git a/session_test.go b/session_test.go index b3374ceb..16006895 100644 --- a/session_test.go +++ b/session_test.go @@ -990,6 +990,9 @@ func TestSession_CookieSecureMatchesRequest(t *testing.T) { if sHTTP.Cookie() == nil || sHTTP.Cookie().Secure { t.Fatal("expected insecure cookie for http request") } + if got := sHTTP.Cookie().Name; got != jw.CookieName { + t.Fatalf("HTTP cookie name = %q, want %q", got, jw.CookieName) + } sHTTPS := jw.NewSession(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "https://example.test/", nil)) if sHTTPS == nil { @@ -998,6 +1001,9 @@ func TestSession_CookieSecureMatchesRequest(t *testing.T) { if sHTTPS.Cookie() == nil || !sHTTPS.Cookie().Secure { t.Fatal("expected secure cookie for https request") } + if got := sHTTPS.Cookie().Name; got != "__Host-"+jw.CookieName { + t.Fatalf("HTTPS cookie name = %q, want __Host-%s", got, jw.CookieName) + } // By default forwarded headers are not trusted, so a forwarded-as-https // request over plain HTTP must still yield an insecure cookie. @@ -1010,6 +1016,9 @@ func TestSession_CookieSecureMatchesRequest(t *testing.T) { if sForwarded.Cookie() == nil || sForwarded.Cookie().Secure { t.Fatal("expected insecure cookie when forwarded headers are not trusted") } + if got := sForwarded.Cookie().Name; got != jw.CookieName { + t.Fatalf("untrusted proxy cookie name = %q, want %q", got, jw.CookieName) + } // With TrustForwardedHeaders enabled, the same request yields a secure cookie. jwTrust, _ := New() @@ -1024,6 +1033,191 @@ func TestSession_CookieSecureMatchesRequest(t *testing.T) { if sTrusted.Cookie() == nil || !sTrusted.Cookie().Secure { t.Fatal("expected secure cookie when forwarded headers are trusted") } + if got := sTrusted.Cookie().Name; got != "__Host-"+jwTrust.CookieName { + t.Fatalf("trusted proxy cookie name = %q, want __Host-%s", got, jwTrust.CookieName) + } +} + +func TestSession_CookiesSeparateSchemes(t *testing.T) { + jw, err := New() + if err != nil { + t.Fatal(err) + } + go jw.Serve() + t.Cleanup(jw.Close) + + httpRequest := httptest.NewRequest(http.MethodGet, "http://example.test/", nil) + httpSession := jw.NewSession(httptest.NewRecorder(), httpRequest) + httpsRequest := httptest.NewRequest(http.MethodGet, "https://example.test/", nil) + httpsSession := jw.NewSession(httptest.NewRecorder(), httpsRequest) + if httpSession == nil || httpsSession == nil { + t.Fatal("expected separate HTTP and HTTPS sessions") + } + httpCookie, httpsCookie := httpSession.Cookie(), httpsSession.Cookie() + if httpCookie.Name != jw.CookieName || httpsCookie.Name != "__Host-"+jw.CookieName || !httpsCookie.Secure || httpsCookie.Path != "/" || httpsCookie.Domain != "" { + t.Fatalf("HTTP cookie = %#v, HTTPS cookie = %#v", httpCookie, httpsCookie) + } + + for _, tc := range []struct { + name string + url string + cookies []*http.Cookie + want *Session + }{ + {name: "HTTP selects HTTP", url: "http://example.test/", cookies: []*http.Cookie{httpsCookie, httpCookie}, want: httpSession}, + {name: "HTTPS selects HTTPS", url: "https://example.test/", cookies: []*http.Cookie{httpCookie, httpsCookie}, want: httpsSession}, + {name: "HTTP ignores HTTPS", url: "http://example.test/", cookies: []*http.Cookie{httpsCookie}}, + {name: "HTTPS ignores HTTP", url: "https://example.test/", cookies: []*http.Cookie{httpCookie}}, + {name: "HTTP rejects renamed HTTPS ID", url: "http://example.test/", cookies: []*http.Cookie{{Name: jw.CookieName, Value: httpsSession.CookieValue()}}}, + {name: "HTTPS rejects renamed HTTP ID", url: "https://example.test/", cookies: []*http.Cookie{{Name: "__Host-" + jw.CookieName, Value: httpSession.CookieValue()}}}, + } { + t.Run(tc.name, func(t *testing.T) { + r := httptest.NewRequest(http.MethodGet, tc.url, nil) + for _, cookie := range tc.cookies { + r.AddCookie(cookie) + } + if got := jw.GetSession(r); got != tc.want { + t.Fatalf("GetSession = %p, want %p", got, tc.want) + } + rq := jw.NewRequest(httptest.NewRecorder(), r) + if got := rq.Session(); got != tc.want { + t.Fatalf("NewRequest().Session() = %p, want %p", got, tc.want) + } + rq.Cancel(nil) + }) + } + + r := httptest.NewRequest(http.MethodGet, "https://example.test/", nil) + r.AddCookie(httpCookie) + r.AddCookie(httpsCookie) + replacement := jw.NewSession(httptest.NewRecorder(), r) + if replacement == nil || jw.GetSession(r) != replacement { + t.Fatal("HTTPS rotation did not publish replacement") + } + if httpsSession.Cookie().MaxAge != -1 || httpSession.Cookie().MaxAge < 0 || jw.GetSession(httpRequest) != httpSession { + t.Fatal("HTTPS rotation closed the wrong Session") + } + httpsReplacement := replacement + + r = httptest.NewRequest(http.MethodGet, "http://example.test/", nil) + r.AddCookie(httpCookie) + r.AddCookie(httpsCookie) + replacement = jw.NewSession(httptest.NewRecorder(), r) + if replacement == nil || jw.GetSession(r) != replacement { + t.Fatal("HTTP rotation did not publish replacement") + } + probe := httptest.NewRequest(http.MethodGet, "https://example.test/", nil) + probe.AddCookie(httpsReplacement.Cookie()) + if httpSession.Cookie().MaxAge != -1 || jw.GetSession(probe) != httpsReplacement { + t.Fatal("HTTP rotation closed the wrong Session") + } +} + +func TestSession_HostCookiePrefix(t *testing.T) { + for _, tc := range []struct { + name string + cookieName string + url string + forwarded bool + trust bool + want bool + }{ + {name: "HTTPS", cookieName: "__Host-jaws", url: "https://example.test/", want: true}, + {name: "HTTP", cookieName: "__Host-jaws", url: "http://example.test/"}, + {name: "untrusted proxy", cookieName: "__Host-jaws", url: "http://example.test/", forwarded: true}, + {name: "trusted proxy", cookieName: "__Host-jaws", url: "http://example.test/", forwarded: true, trust: true, want: true}, + } { + t.Run(tc.name, func(t *testing.T) { + jw, err := New() + if err != nil { + t.Fatal(err) + } + defer jw.Close() + jw.CookieName = tc.cookieName + jw.TrustForwardedHeaders = tc.trust + r := httptest.NewRequest(http.MethodGet, tc.url, nil) + if tc.forwarded { + r.Header.Set("X-Forwarded-Proto", "https") + } + w := httptest.NewRecorder() + sess := jw.NewSession(w, r) + cookies := w.Result().Cookies() + if !tc.want { + if sess != nil || len(cookies) != 0 || len(jw.Sessions()) != 0 { + t.Fatalf("insecure request created session %p with cookies %v", sess, cookies) + } + return + } + if sess == nil || len(cookies) != 1 { + t.Fatalf("secure request created session %p with cookies %v", sess, cookies) + } + cookie := cookies[0] + if cookie.Name != tc.cookieName || !cookie.Secure || cookie.Path != "/" || cookie.Domain != "" || !cookie.HttpOnly || cookie.SameSite != http.SameSiteLaxMode { + t.Fatalf("invalid __Host- cookie: %#v", cookie) + } + if got := jw.GetSession(r); got != sess { + t.Fatalf("GetSession = %p, want %p", got, sess) + } + }) + } +} + +func TestSession_HostCookiePrefixCaseSensitive(t *testing.T) { + jw, err := New() + if err != nil { + t.Fatal(err) + } + defer jw.Close() + jw.CookieName = "__hOsT-jaws" + httpSession := jw.NewSession(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "http://example.test/", nil)) + httpsSession := jw.NewSession(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "https://example.test/", nil)) + if httpSession == nil || httpSession.Cookie().Name != jw.CookieName || httpSession.Cookie().Secure { + t.Fatalf("HTTP Session = %p", httpSession) + } + if httpsSession == nil || httpsSession.Cookie().Name != "__Host-"+jw.CookieName || !httpsSession.Cookie().Secure { + t.Fatalf("HTTPS Session = %p", httpsSession) + } +} + +func TestSession_HostCookiePrefixRejectsInsecureRead(t *testing.T) { + jw, err := New() + if err != nil { + t.Fatal(err) + } + defer jw.Close() + jw.CookieName = "__Host-jaws" + r := httptest.NewRequest(http.MethodGet, "https://example.test/", nil) + sess := jw.NewSession(httptest.NewRecorder(), r) + if sess == nil { + t.Fatal("expected HTTPS session") + } + insecure := httptest.NewRequest(http.MethodGet, "http://example.test/", nil) + insecure.AddCookie(sess.Cookie()) + if got := jw.GetSession(insecure); got != nil { + t.Fatalf("HTTP GetSession accepted HTTPS session %p", got) + } + rq := jw.NewRequest(httptest.NewRecorder(), insecure) + if got := rq.Session(); got != nil { + t.Fatalf("HTTP NewRequest accepted HTTPS session %p", got) + } + rq.Cancel(nil) +} + +func TestSessionMiddleware_HostCookieRequiresHTTPS(t *testing.T) { + jw, err := New() + if err != nil { + t.Fatal(err) + } + defer jw.Close() + jw.CookieName = "__Host-jaws" + called := false + w := httptest.NewRecorder() + jw.SessionMiddleware(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { + called = true + })).ServeHTTP(w, httptest.NewRequest(http.MethodGet, "http://example.test/", nil)) + if w.Code != http.StatusServiceUnavailable || called || len(w.Result().Cookies()) != 0 { + t.Fatalf("insecure host cookie: status=%d called=%v cookies=%v", w.Code, called, w.Result().Cookies()) + } } func TestSession_Use(t *testing.T) { From 8ae9d2dd70c3f7b4767b7d0e9470fc3ddca2a879 Mon Sep 17 00:00:00 2001 From: Johan Lindh Date: Fri, 6 Nov 2026 10:37:28 +0100 Subject: [PATCH 2/7] Document jawsauth session rotation policy for JaWS apps --- .agents/skills/jaws/SKILL.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/.agents/skills/jaws/SKILL.md b/.agents/skills/jaws/SKILL.md index 938bd4a3..d00ba6bf 100644 --- a/.agents/skills/jaws/SKILL.md +++ b/.agents/skills/jaws/SKILL.md @@ -141,9 +141,30 @@ Guide: `doc/sessions.md`, `doc/deployment.md`, `doc/ui/jsvar.md`. initialize its state atomically. Session storage supplies no dependency tags. - [ ] If templates use `$.Auth`, configure `MakeAuth`; enforce authorization independently in protected operations. +- [ ] With `jawsauth`, use its default of keeping the JaWS Session on login and + logout. Let JaWS and `jawsauth` handle cookie and page lifecycle; do not add + application JavaScript, cookie polling, or session monitoring for auth changes. + Use login and logout hooks for application side effects. +- [ ] Behind a trusted reverse proxy, configure `TrustForwardedHeaders` and have + the proxy replace client-supplied forwarding headers. JaWS then uses the + forwarded client IP for Session binding. A reverse proxy alone does not call + for login rotation. +- [ ] Keep login rotation off unless a concrete session-fixation path exists: + distinct clients share the IP JaWS sees, and an attacker can make a victim + use a known pre-login Session cookie without learning the post-login cookie. + Then opt in with `jawsauth.Server.RotateSessionOnLogin`. A shared IP alone is + insufficient. HTTPS with JaWS's `__Host-` cookie name blocks ordinary sibling + domain and HTTP cookie planting. Do not assume browser or traffic compromise; + an attacker who controls those can also obtain the rotated cookie. - [ ] For browser-writable `JsVarStore`, validate the complete proposed value and caller authorization in `ClientCheck`. +For comparison, [Gorilla sessions](https://github.com/gorilla/sessions/blob/main/store.go) +and [Gin sessions](https://github.com/gin-contrib/sessions/blob/master/sessions.go) +save existing sessions, while [Authboss OAuth2](https://github.com/aarondl/authboss/blob/master/oauth2/oauth2.go) +stores the user ID in the current session. [SCS](https://pkg.go.dev/github.com/alexedwards/scs/v2#SessionManager.RenewToken) +exposes explicit `RenewToken` and recommends calling it on privilege changes. + ### Pass content or attributes across a trust boundary Guide: `doc/bindings.md#html-and-attribute-safety`. From b8e9b3e83e8bdf0774403d57919e9b3394553f14 Mon Sep 17 00:00:00 2001 From: Johan Lindh Date: Fri, 6 Nov 2026 10:50:40 +0100 Subject: [PATCH 3/7] Recognize host cookie prefix case-insensitively --- doc/sessions.md | 10 +++++----- jaws.go | 9 +++++---- session.go | 14 +++++++------- session_test.go | 18 ++++++++++++------ 4 files changed, 29 insertions(+), 22 deletions(-) diff --git a/doc/sessions.md b/doc/sessions.md index c2ca23b0..a8e4bb58 100644 --- a/doc/sessions.md +++ b/doc/sessions.md @@ -21,11 +21,11 @@ HTTP Sessions remain exposed to plaintext network traffic. Behind a TLS-terminating proxy, configure trusted forwarded scheme headers as described in [deployment](deployment.md#reverse-proxies). -An explicitly `__Host-`-prefixed `jw.CookieName` uses that name on HTTPS and -disables HTTP Session use: `GetSession` and `NewRequest` ignore matching cookies, -`NewSession` returns nil, `SessionMiddleware` returns HTTP 503, and `AutoSession` -skips creation. Existing browser sessions using an unprefixed HTTPS cookie name -are not recognized. +An explicitly `__Host-`-prefixed `jw.CookieName` (in any letter case) uses that +name on HTTPS and disables HTTP Session use: `GetSession` and `NewRequest` +ignore matching cookies, `NewSession` returns nil, `SessionMiddleware` returns +HTTP 503, and `AutoSession` skips creation. Existing browser sessions using an +unprefixed HTTPS cookie name are not recognized. ## Create a session before rendering diff --git a/jaws.go b/jaws.go index 8b7ef969..266236dd 100644 --- a/jaws.go +++ b/jaws.go @@ -102,15 +102,16 @@ type Jaws struct { // // HTTP sessions use this name. Recognized HTTPS sessions use a "__Host-" // prefix so supporting browsers enforce host-only cookies. The two schemes - // do not share Sessions. An explicitly prefixed name makes HTTP Sessions - // unavailable; see [Jaws.TrustForwardedHeaders] for proxy scheme detection. + // do not share Sessions. A name with a case-insensitive "__Host-" prefix + // makes HTTP Sessions unavailable; see [Jaws.TrustForwardedHeaders] for + // proxy scheme detection. CookieName string // AutoSession creates a [Session] on a successful WebSocket upgrade. // // It applies when the [Request] has no Session and Session limits allow one. // The cookie name and Secure flag follow the initial page request's scheme, - // honoring [Jaws.TrustForwardedHeaders]. An explicitly "__Host-"-prefixed - // CookieName requires that request to be recognized as HTTPS. AutoSession + // honoring [Jaws.TrustForwardedHeaders]. A CookieName with a case-insensitive + // "__Host-" prefix requires the request to be recognized as HTTPS. AutoSession // defaults to false. AutoSession bool // TrustForwardedHeaders enables trusted proxy header processing. diff --git a/session.go b/session.go index 5ecae8b0..171595cf 100644 --- a/session.go +++ b/session.go @@ -23,7 +23,7 @@ const ( ) func hasHostCookiePrefix(name string) bool { - return strings.HasPrefix(name, hostCookiePrefix) + return len(name) >= len(hostCookiePrefix) && strings.EqualFold(name[:len(hostCookiePrefix)], hostCookiePrefix) } func (jw *Jaws) sessionCookieName(secure bool) string { @@ -454,9 +454,9 @@ func (jw *Jaws) GetSession(r *http.Request) (sess *Session) { // // It returns nil without closing matching Sessions if r is nil, shutdown has // begun, [Jaws.MaxSessions] or [Jaws.MaxSessionsPerIP] is reached, or cookie -// publication fails. It also returns nil when an explicitly "__Host-"-prefixed -// [Jaws.CookieName] is used on a request JaWS does not recognize as HTTPS; -// w may be nil. Cookie names follow [Jaws.GetSession]. +// publication fails. It also returns nil when a [Jaws.CookieName] with a +// case-insensitive "__Host-" prefix is used on a request JaWS does not recognize +// as HTTPS; w may be nil. Cookie names follow [Jaws.GetSession]. // // Replacing a Session requires a free slot under each enabled limit until the // new cookie is published and the old Session is closed. @@ -502,9 +502,9 @@ func (jw *Jaws) newSession(w http.ResponseWriter, r *http.Request) (sess *Sessio } // newSessionLocked allocates a Session whose ID is absent from jw.sessions, or -// returns nil after shutdown begins, a Session limit is reached, or a "__Host-" -// cookie name would be used without Secure. limitIP distinguishes the per-client -// limit for SessionMiddleware's HTTP response. +// returns nil after shutdown begins, a Session limit is reached, or a +// case-insensitive "__Host-" cookie name would be used without Secure. +// limitIP distinguishes the per-client limit for SessionMiddleware's HTTP response. // // The caller must hold jw.mu and publish any returned Session before releasing // it. diff --git a/session_test.go b/session_test.go index 16006895..cfe6830a 100644 --- a/session_test.go +++ b/session_test.go @@ -1162,21 +1162,27 @@ func TestSession_HostCookiePrefix(t *testing.T) { } } -func TestSession_HostCookiePrefixCaseSensitive(t *testing.T) { +func TestSession_HostCookiePrefixCaseInsensitive(t *testing.T) { jw, err := New() if err != nil { t.Fatal(err) } defer jw.Close() jw.CookieName = "__hOsT-jaws" - httpSession := jw.NewSession(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "http://example.test/", nil)) - httpsSession := jw.NewSession(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "https://example.test/", nil)) - if httpSession == nil || httpSession.Cookie().Name != jw.CookieName || httpSession.Cookie().Secure { - t.Fatalf("HTTP Session = %p", httpSession) + httpResponse := httptest.NewRecorder() + httpSession := jw.NewSession(httpResponse, httptest.NewRequest(http.MethodGet, "http://example.test/", nil)) + httpsRequest := httptest.NewRequest(http.MethodGet, "https://example.test/", nil) + httpsSession := jw.NewSession(httptest.NewRecorder(), httpsRequest) + httpCookies := httpResponse.Result().Cookies() + if httpSession != nil || len(httpCookies) != 0 { + t.Fatalf("HTTP Session = %p; cookies = %v", httpSession, httpCookies) } - if httpsSession == nil || httpsSession.Cookie().Name != "__Host-"+jw.CookieName || !httpsSession.Cookie().Secure { + if httpsSession == nil || httpsSession.Cookie().Name != jw.CookieName || !httpsSession.Cookie().Secure { t.Fatalf("HTTPS Session = %p", httpsSession) } + if got := jw.GetSession(httpsRequest); got != httpsSession { + t.Fatalf("GetSession = %p, want %p", got, httpsSession) + } } func TestSession_HostCookiePrefixRejectsInsecureRead(t *testing.T) { From 6145ef620308a5c1590779edab8aedd817adfacb Mon Sep 17 00:00:00 2001 From: Johan Lindh Date: Fri, 6 Nov 2026 11:00:51 +0100 Subject: [PATCH 4/7] Require HTTPS for reserved secure cookie prefixes --- doc/sessions.md | 9 +++++---- jaws.go | 10 +++++----- session.go | 27 +++++++++++++++----------- session_test.go | 50 +++++++++++++++++++++++++++++-------------------- 4 files changed, 56 insertions(+), 40 deletions(-) diff --git a/doc/sessions.md b/doc/sessions.md index a8e4bb58..341bb31f 100644 --- a/doc/sessions.md +++ b/doc/sessions.md @@ -22,10 +22,11 @@ TLS-terminating proxy, configure trusted forwarded scheme headers as described in [deployment](deployment.md#reverse-proxies). An explicitly `__Host-`-prefixed `jw.CookieName` (in any letter case) uses that -name on HTTPS and disables HTTP Session use: `GetSession` and `NewRequest` -ignore matching cookies, `NewSession` returns nil, `SessionMiddleware` returns -HTTP 503, and `AutoSession` skips creation. Existing browser sessions using an -unprefixed HTTPS cookie name are not recognized. +name on HTTPS. A name beginning with `__Host-` or `__Secure-` in any letter +case disables HTTP Session use: `GetSession` and `NewRequest` ignore matching +cookies, `NewSession` returns nil, `SessionMiddleware` returns HTTP 503, and +`AutoSession` skips creation. Existing browser sessions using an unprefixed +HTTPS cookie name are not recognized. ## Create a session before rendering diff --git a/jaws.go b/jaws.go index 266236dd..fd427993 100644 --- a/jaws.go +++ b/jaws.go @@ -102,16 +102,16 @@ type Jaws struct { // // HTTP sessions use this name. Recognized HTTPS sessions use a "__Host-" // prefix so supporting browsers enforce host-only cookies. The two schemes - // do not share Sessions. A name with a case-insensitive "__Host-" prefix - // makes HTTP Sessions unavailable; see [Jaws.TrustForwardedHeaders] for - // proxy scheme detection. + // do not share Sessions. A name beginning with "__Host-" or "__Secure-" + // in any letter case makes HTTP Sessions unavailable; see + // [Jaws.TrustForwardedHeaders] for proxy scheme detection. CookieName string // AutoSession creates a [Session] on a successful WebSocket upgrade. // // It applies when the [Request] has no Session and Session limits allow one. // The cookie name and Secure flag follow the initial page request's scheme, - // honoring [Jaws.TrustForwardedHeaders]. A CookieName with a case-insensitive - // "__Host-" prefix requires the request to be recognized as HTTPS. AutoSession + // honoring [Jaws.TrustForwardedHeaders]. A CookieName beginning with "__Host-" + // or "__Secure-" in any letter case requires recognized HTTPS. AutoSession // defaults to false. AutoSession bool // TrustForwardedHeaders enables trusted proxy header processing. diff --git a/session.go b/session.go index 171595cf..13e6ffdd 100644 --- a/session.go +++ b/session.go @@ -18,22 +18,27 @@ import ( ) const ( - sessionGrace = time.Minute - hostCookiePrefix = "__Host-" + sessionGrace = time.Minute + hostCookiePrefix = "__Host-" + secureCookiePrefix = "__Secure-" ) -func hasHostCookiePrefix(name string) bool { - return len(name) >= len(hostCookiePrefix) && strings.EqualFold(name[:len(hostCookiePrefix)], hostCookiePrefix) +func hasCookiePrefix(name, prefix string) bool { + return len(name) >= len(prefix) && strings.EqualFold(name[:len(prefix)], prefix) +} + +func requiresSecureCookie(name string) bool { + return hasCookiePrefix(name, hostCookiePrefix) || hasCookiePrefix(name, secureCookiePrefix) } func (jw *Jaws) sessionCookieName(secure bool) string { if !secure { - if hasHostCookiePrefix(jw.CookieName) { + if requiresSecureCookie(jw.CookieName) { return "" } return jw.CookieName } - if !hasHostCookiePrefix(jw.CookieName) { + if !hasCookiePrefix(jw.CookieName, hostCookiePrefix) { return hostCookiePrefix + jw.CookieName } return jw.CookieName @@ -454,9 +459,9 @@ func (jw *Jaws) GetSession(r *http.Request) (sess *Session) { // // It returns nil without closing matching Sessions if r is nil, shutdown has // begun, [Jaws.MaxSessions] or [Jaws.MaxSessionsPerIP] is reached, or cookie -// publication fails. It also returns nil when a [Jaws.CookieName] with a -// case-insensitive "__Host-" prefix is used on a request JaWS does not recognize -// as HTTPS; w may be nil. Cookie names follow [Jaws.GetSession]. +// publication fails. It also returns nil when a [Jaws.CookieName] beginning +// with "__Host-" or "__Secure-" in any letter case is used without recognized +// HTTPS; w may be nil. Cookie names follow [Jaws.GetSession]. // // Replacing a Session requires a free slot under each enabled limit until the // new cookie is published and the old Session is closed. @@ -503,13 +508,13 @@ func (jw *Jaws) newSession(w http.ResponseWriter, r *http.Request) (sess *Sessio // newSessionLocked allocates a Session whose ID is absent from jw.sessions, or // returns nil after shutdown begins, a Session limit is reached, or a -// case-insensitive "__Host-" cookie name would be used without Secure. +// browser secure-only cookie prefix would be used without Secure. // limitIP distinguishes the per-client limit for SessionMiddleware's HTTP response. // // The caller must hold jw.mu and publish any returned Session before releasing // it. func (jw *Jaws) newSessionLocked(remoteIP netip.Addr, secure bool) (sess *Session, limitIP bool) { - if !secure && hasHostCookiePrefix(jw.CookieName) { + if !secure && requiresSecureCookie(jw.CookieName) { return } select { diff --git a/session_test.go b/session_test.go index cfe6830a..9577c7ec 100644 --- a/session_test.go +++ b/session_test.go @@ -1162,26 +1162,36 @@ func TestSession_HostCookiePrefix(t *testing.T) { } } -func TestSession_HostCookiePrefixCaseInsensitive(t *testing.T) { - jw, err := New() - if err != nil { - t.Fatal(err) - } - defer jw.Close() - jw.CookieName = "__hOsT-jaws" - httpResponse := httptest.NewRecorder() - httpSession := jw.NewSession(httpResponse, httptest.NewRequest(http.MethodGet, "http://example.test/", nil)) - httpsRequest := httptest.NewRequest(http.MethodGet, "https://example.test/", nil) - httpsSession := jw.NewSession(httptest.NewRecorder(), httpsRequest) - httpCookies := httpResponse.Result().Cookies() - if httpSession != nil || len(httpCookies) != 0 { - t.Fatalf("HTTP Session = %p; cookies = %v", httpSession, httpCookies) - } - if httpsSession == nil || httpsSession.Cookie().Name != jw.CookieName || !httpsSession.Cookie().Secure { - t.Fatalf("HTTPS Session = %p", httpsSession) - } - if got := jw.GetSession(httpsRequest); got != httpsSession { - t.Fatalf("GetSession = %p, want %p", got, httpsSession) +func TestSession_ReservedCookiePrefixesRequireHTTPS(t *testing.T) { + for _, tc := range []struct { + name string + httpsName string + }{ + {"__hOsT-jaws", "__hOsT-jaws"}, + {"__sEcUrE-jaws", "__Host-__sEcUrE-jaws"}, + } { + t.Run(tc.name, func(t *testing.T) { + jw, err := New() + if err != nil { + t.Fatal(err) + } + defer jw.Close() + jw.CookieName = tc.name + httpResponse := httptest.NewRecorder() + httpSession := jw.NewSession(httpResponse, httptest.NewRequest(http.MethodGet, "http://example.test/", nil)) + httpsRequest := httptest.NewRequest(http.MethodGet, "https://example.test/", nil) + httpsSession := jw.NewSession(httptest.NewRecorder(), httpsRequest) + httpCookies := httpResponse.Result().Cookies() + if httpSession != nil || len(httpCookies) != 0 { + t.Fatalf("HTTP Session = %p; cookies = %v", httpSession, httpCookies) + } + if httpsSession == nil || httpsSession.Cookie().Name != tc.httpsName || !httpsSession.Cookie().Secure { + t.Fatalf("HTTPS Session = %p", httpsSession) + } + if got := jw.GetSession(httpsRequest); got != httpsSession { + t.Fatalf("GetSession = %p, want %p", got, httpsSession) + } + }) } } From 7ca08138f33aee2b1ee75025937f42f9be71ac26 Mon Sep 17 00:00:00 2001 From: Johan Lindh Date: Fri, 6 Nov 2026 11:10:24 +0100 Subject: [PATCH 5/7] Canonicalize host prefix and reserve secure cookie names --- doc/deployment.md | 13 ++++++++----- doc/sessions.md | 12 ++++++------ jaws.go | 11 ++++++----- session.go | 13 +++++++------ session_test.go | 3 ++- 5 files changed, 29 insertions(+), 23 deletions(-) diff --git a/doc/deployment.md b/doc/deployment.md index 8d82414a..8baedc0b 100644 --- a/doc/deployment.md +++ b/doc/deployment.md @@ -96,11 +96,14 @@ Sanitize all recognized headers: - `X-Forwarded-For` and `X-Real-IP` for client IP binding. - `X-Forwarded-Proto`, `X-Forwarded-Ssl`, `Front-End-Https`, and `Forwarded` for scheme resolution. -JaWS parses only the rightmost comma-separated element of each header's last -line. It prefers a valid `X-Forwarded-For` address, falling back to `X-Real-IP`. -If neither parses or both valid addresses disagree, it uses the transport peer. -Set or remove both IP headers. A TLS-terminating proxy forwarding plain HTTP must supply the trusted -scheme, or HTTPS-page upgrades fail with `ErrWebsocketOriginWrongScheme`. +For client IP, JaWS parses only the rightmost comma-separated element of each +header's last line. It prefers a valid `X-Forwarded-For` address, falling back +to `X-Real-IP`. If neither parses or both valid addresses disagree, it uses +the transport peer. For scheme, it reads the first header line and the first +comma-separated element of `X-Forwarded-Proto` or `Forwarded`. +Set or remove both IP headers. A TLS-terminating proxy forwarding plain HTTP +must supply the trusted scheme, or HTTPS-page upgrades fail with +`ErrWebsocketOriginWrongScheme`. Preserve the page host, `/jaws/` paths, and WebSocket upgrades. JaWS checks the Origin scheme and host against the initial request, binds the callback to the diff --git a/doc/sessions.md b/doc/sessions.md index 341bb31f..bf45b5c3 100644 --- a/doc/sessions.md +++ b/doc/sessions.md @@ -21,12 +21,12 @@ HTTP Sessions remain exposed to plaintext network traffic. Behind a TLS-terminating proxy, configure trusted forwarded scheme headers as described in [deployment](deployment.md#reverse-proxies). -An explicitly `__Host-`-prefixed `jw.CookieName` (in any letter case) uses that -name on HTTPS. A name beginning with `__Host-` or `__Secure-` in any letter -case disables HTTP Session use: `GetSession` and `NewRequest` ignore matching -cookies, `NewSession` returns nil, `SessionMiddleware` returns HTTP 503, and -`AutoSession` skips creation. Existing browser sessions using an unprefixed -HTTPS cookie name are not recognized. +An explicitly `__Host-`-prefixed `jw.CookieName` (in any letter case) uses the +canonical `__Host-` prefix on HTTPS. A name beginning with `__Host-`, +`__Secure-`, or `__Http-` in any letter case disables HTTP Session use: +`GetSession` and `NewRequest` ignore matching cookies, `NewSession` returns nil, +`SessionMiddleware` returns HTTP 503, and `AutoSession` skips creation. Existing +browser sessions using an unprefixed HTTPS cookie name are not recognized. ## Create a session before rendering diff --git a/jaws.go b/jaws.go index fd427993..034490cb 100644 --- a/jaws.go +++ b/jaws.go @@ -102,17 +102,18 @@ type Jaws struct { // // HTTP sessions use this name. Recognized HTTPS sessions use a "__Host-" // prefix so supporting browsers enforce host-only cookies. The two schemes - // do not share Sessions. A name beginning with "__Host-" or "__Secure-" - // in any letter case makes HTTP Sessions unavailable; see + // do not share Sessions. A name beginning with "__Host-", "__Secure-", or + // "__Http-" in any letter case makes HTTP Sessions unavailable; an explicit + // "__Host-" prefix is emitted in canonical case on HTTPS. See // [Jaws.TrustForwardedHeaders] for proxy scheme detection. CookieName string // AutoSession creates a [Session] on a successful WebSocket upgrade. // // It applies when the [Request] has no Session and Session limits allow one. // The cookie name and Secure flag follow the initial page request's scheme, - // honoring [Jaws.TrustForwardedHeaders]. A CookieName beginning with "__Host-" - // or "__Secure-" in any letter case requires recognized HTTPS. AutoSession - // defaults to false. + // honoring [Jaws.TrustForwardedHeaders]. A CookieName beginning with "__Host-", + // "__Secure-", or "__Http-" in any letter case requires recognized HTTPS. + // AutoSession defaults to false. AutoSession bool // TrustForwardedHeaders enables trusted proxy header processing. // diff --git a/session.go b/session.go index 13e6ffdd..aee7a8f6 100644 --- a/session.go +++ b/session.go @@ -21,6 +21,7 @@ const ( sessionGrace = time.Minute hostCookiePrefix = "__Host-" secureCookiePrefix = "__Secure-" + httpCookiePrefix = "__Http-" ) func hasCookiePrefix(name, prefix string) bool { @@ -28,7 +29,7 @@ func hasCookiePrefix(name, prefix string) bool { } func requiresSecureCookie(name string) bool { - return hasCookiePrefix(name, hostCookiePrefix) || hasCookiePrefix(name, secureCookiePrefix) + return hasCookiePrefix(name, hostCookiePrefix) || hasCookiePrefix(name, secureCookiePrefix) || hasCookiePrefix(name, httpCookiePrefix) } func (jw *Jaws) sessionCookieName(secure bool) string { @@ -38,10 +39,10 @@ func (jw *Jaws) sessionCookieName(secure bool) string { } return jw.CookieName } - if !hasCookiePrefix(jw.CookieName, hostCookiePrefix) { - return hostCookiePrefix + jw.CookieName + if hasCookiePrefix(jw.CookieName, hostCookiePrefix) { + return hostCookiePrefix + jw.CookieName[len(hostCookiePrefix):] } - return jw.CookieName + return hostCookiePrefix + jw.CookieName } // Session stores server-side state shared by one or more Requests. @@ -460,8 +461,8 @@ func (jw *Jaws) GetSession(r *http.Request) (sess *Session) { // It returns nil without closing matching Sessions if r is nil, shutdown has // begun, [Jaws.MaxSessions] or [Jaws.MaxSessionsPerIP] is reached, or cookie // publication fails. It also returns nil when a [Jaws.CookieName] beginning -// with "__Host-" or "__Secure-" in any letter case is used without recognized -// HTTPS; w may be nil. Cookie names follow [Jaws.GetSession]. +// with "__Host-", "__Secure-", or "__Http-" in any letter case is used without +// recognized HTTPS; w may be nil. Cookie names follow [Jaws.GetSession]. // // Replacing a Session requires a free slot under each enabled limit until the // new cookie is published and the old Session is closed. diff --git a/session_test.go b/session_test.go index 9577c7ec..55f06819 100644 --- a/session_test.go +++ b/session_test.go @@ -1167,8 +1167,9 @@ func TestSession_ReservedCookiePrefixesRequireHTTPS(t *testing.T) { name string httpsName string }{ - {"__hOsT-jaws", "__hOsT-jaws"}, + {"__hOsT-jaws", "__Host-jaws"}, {"__sEcUrE-jaws", "__Host-__sEcUrE-jaws"}, + {"__hTtP-jaws", "__Host-__hTtP-jaws"}, } { t.Run(tc.name, func(t *testing.T) { jw, err := New() From 23c0fc0e1953cd5a48aedf755049c41f0bde0a09 Mon Sep 17 00:00:00 2001 From: Johan Lindh Date: Fri, 6 Nov 2026 13:00:47 +0100 Subject: [PATCH 6/7] Tighten session cookie documentation --- .agents/skills/jaws/SKILL.md | 36 +++++++++++++---------------- doc/deployment.md | 10 ++++---- doc/sessions.md | 20 ++++++---------- jaws.go | 17 ++++++-------- requestpool.go | 2 +- session.go | 44 +++++++++++------------------------- 6 files changed, 49 insertions(+), 80 deletions(-) diff --git a/.agents/skills/jaws/SKILL.md b/.agents/skills/jaws/SKILL.md index d00ba6bf..da1f51a4 100644 --- a/.agents/skills/jaws/SKILL.md +++ b/.agents/skills/jaws/SKILL.md @@ -141,29 +141,25 @@ Guide: `doc/sessions.md`, `doc/deployment.md`, `doc/ui/jsvar.md`. initialize its state atomically. Session storage supplies no dependency tags. - [ ] If templates use `$.Auth`, configure `MakeAuth`; enforce authorization independently in protected operations. -- [ ] With `jawsauth`, use its default of keeping the JaWS Session on login and - logout. Let JaWS and `jawsauth` handle cookie and page lifecycle; do not add - application JavaScript, cookie polling, or session monitoring for auth changes. - Use login and logout hooks for application side effects. -- [ ] Behind a trusted reverse proxy, configure `TrustForwardedHeaders` and have - the proxy replace client-supplied forwarding headers. JaWS then uses the - forwarded client IP for Session binding. A reverse proxy alone does not call - for login rotation. -- [ ] Keep login rotation off unless a concrete session-fixation path exists: - distinct clients share the IP JaWS sees, and an attacker can make a victim - use a known pre-login Session cookie without learning the post-login cookie. - Then opt in with `jawsauth.Server.RotateSessionOnLogin`. A shared IP alone is - insufficient. HTTPS with JaWS's `__Host-` cookie name blocks ordinary sibling - domain and HTTP cookie planting. Do not assume browser or traffic compromise; - an attacker who controls those can also obtain the rotated cookie. +- [ ] `jawsauth` keeps the JaWS Session on login and logout by default. JaWS and + `jawsauth` manage cookies and page reloads; applications need no cookie polling + or JavaScript for auth changes. Use hooks for application side effects. +- [ ] Behind a trusted reverse proxy, set `TrustForwardedHeaders` and replace + client-supplied forwarding headers. JaWS then binds Sessions to the forwarded + client IP. A proxy alone does not require login rotation. +- [ ] Enable `jawsauth.Server.RotateSessionOnLogin` only when an attacker can + plant a known pre-login cookie in a victim browser, reach JaWS from the same + effective client IP, and cannot learn the later cookie. Browsers enforcing + the `__Host-` prefix block sibling-domain and HTTP planting on HTTPS. Do not + assume ongoing browser or traffic control; rotation does not protect against it. - [ ] For browser-writable `JsVarStore`, validate the complete proposed value and caller authorization in `ClientCheck`. -For comparison, [Gorilla sessions](https://github.com/gorilla/sessions/blob/main/store.go) -and [Gin sessions](https://github.com/gin-contrib/sessions/blob/master/sessions.go) -save existing sessions, while [Authboss OAuth2](https://github.com/aarondl/authboss/blob/master/oauth2/oauth2.go) -stores the user ID in the current session. [SCS](https://pkg.go.dev/github.com/alexedwards/scs/v2#SessionManager.RenewToken) -exposes explicit `RenewToken` and recommends calling it on privilege changes. +[Gorilla sessions](https://github.com/gorilla/sessions/blob/main/store.go) and +[Gin sessions](https://github.com/gin-contrib/sessions/blob/master/sessions.go) +save the current session; [Authboss OAuth2](https://github.com/aarondl/authboss/blob/master/oauth2/oauth2.go) +stores the user ID in its current session. [SCS](https://pkg.go.dev/github.com/alexedwards/scs/v2#SessionManager.RenewToken) +exposes `RenewToken` and recommends it for privilege changes. ### Pass content or attributes across a trust boundary diff --git a/doc/deployment.md b/doc/deployment.md index 8baedc0b..66bcf1e1 100644 --- a/doc/deployment.md +++ b/doc/deployment.md @@ -74,8 +74,6 @@ Wrap page handlers in `jw.SecureHeadersMiddleware(page)` to apply the Behind a proxy that terminates TLS, set HSTS at the proxy: this middleware does not trust forwarded HTTPS headers, even when `TrustForwardedHeaders` is enabled for JaWS's other checks. -JaWS uses a [host-only cookie name](sessions.md#http-and-https-cookies) for -HTTPS Sessions. Ensure it recognizes the forwarded HTTPS scheme. `NewRequest` makes rendered pages non-cacheable. Keep callback and tail-script responses non-cacheable; hashed static assets may be cached. @@ -99,10 +97,12 @@ Sanitize all recognized headers: For client IP, JaWS parses only the rightmost comma-separated element of each header's last line. It prefers a valid `X-Forwarded-For` address, falling back to `X-Real-IP`. If neither parses or both valid addresses disagree, it uses -the transport peer. For scheme, it reads the first header line and the first -comma-separated element of `X-Forwarded-Proto` or `Forwarded`. +the transport peer. For scheme, it reads the first value of each listed header +and the first hop of list-valued headers. Set or remove both IP headers. A TLS-terminating proxy forwarding plain HTTP -must supply the trusted scheme, or HTTPS-page upgrades fail with +must supply the trusted HTTPS scheme for +[host-prefixed session cookies](sessions.md#http-and-https-cookies) and +HTTPS-page WebSocket upgrades; otherwise upgrades fail with `ErrWebsocketOriginWrongScheme`. Preserve the page host, `/jaws/` paths, and WebSocket upgrades. JaWS checks the diff --git a/doc/sessions.md b/doc/sessions.md index bf45b5c3..d71fdcdc 100644 --- a/doc/sessions.md +++ b/doc/sessions.md @@ -9,24 +9,18 @@ authorization remain separate concerns. ## HTTP and HTTPS cookies -JaWS uses `jw.CookieName` for HTTP Sessions and prefixes it with `__Host-` for -recognized HTTPS Sessions. It never accepts one scheme's cookie for the other -scheme. Browsers that enforce the [`__Host-` prefix](https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-4.1.3.2) -accept the HTTPS cookie only with `Secure`, `Path=/`, and no `Domain`. JaWS sets -these attributes when it recognizes HTTPS. This prevents sibling domains and -browser-visible insecure HTTP responses from planting the HTTPS cookie name. - -Redirect browsers to HTTPS before creating Sessions for authentication. -HTTP Sessions remain exposed to plaintext network traffic. Behind a -TLS-terminating proxy, configure trusted forwarded scheme headers as described -in [deployment](deployment.md#reverse-proxies). +JaWS uses `jw.CookieName` on HTTP and `__Host-` on recognized HTTPS. +Sessions cannot cross schemes. HTTPS cookies carry `Secure`, `Path=/`, and no +`Domain`; browsers enforcing the [`__Host-` prefix](https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-4.1.3.2) +reject sibling-domain and insecure HTTP attempts to set them. HTTP exposes +session cookies to network traffic. For TLS-terminating proxies, see +[deployment](deployment.md#reverse-proxies). An explicitly `__Host-`-prefixed `jw.CookieName` (in any letter case) uses the canonical `__Host-` prefix on HTTPS. A name beginning with `__Host-`, `__Secure-`, or `__Http-` in any letter case disables HTTP Session use: `GetSession` and `NewRequest` ignore matching cookies, `NewSession` returns nil, -`SessionMiddleware` returns HTTP 503, and `AutoSession` skips creation. Existing -browser sessions using an unprefixed HTTPS cookie name are not recognized. +`SessionMiddleware` returns HTTP 503, and `AutoSession` skips creation. ## Create a session before rendering diff --git a/jaws.go b/jaws.go index 034490cb..b3f0e4c0 100644 --- a/jaws.go +++ b/jaws.go @@ -100,20 +100,17 @@ type Jaws struct { // executable and falls back to "jaws". CookieName must be a valid, non-empty // HTTP cookie name; see [http.Cookie.Valid]. // - // HTTP sessions use this name. Recognized HTTPS sessions use a "__Host-" - // prefix so supporting browsers enforce host-only cookies. The two schemes - // do not share Sessions. A name beginning with "__Host-", "__Secure-", or - // "__Http-" in any letter case makes HTTP Sessions unavailable; an explicit - // "__Host-" prefix is emitted in canonical case on HTTPS. See - // [Jaws.TrustForwardedHeaders] for proxy scheme detection. + // HTTP uses this name; recognized HTTPS uses a "__Host-" prefix. Sessions + // cannot cross schemes. A name starting with "__Host-", "__Secure-", or + // "__Http-" in any letter case disables HTTP Sessions; an explicit "__Host-" + // prefix is emitted in canonical case. See [Jaws.TrustForwardedHeaders] for + // proxy scheme detection. CookieName string // AutoSession creates a [Session] on a successful WebSocket upgrade. // // It applies when the [Request] has no Session and Session limits allow one. - // The cookie name and Secure flag follow the initial page request's scheme, - // honoring [Jaws.TrustForwardedHeaders]. A CookieName beginning with "__Host-", - // "__Secure-", or "__Http-" in any letter case requires recognized HTTPS. - // AutoSession defaults to false. + // Its cookie follows the initial page request's scheme; see [Jaws.CookieName] + // and [Jaws.TrustForwardedHeaders]. AutoSession defaults to false. AutoSession bool // TrustForwardedHeaders enables trusted proxy header processing. // diff --git a/requestpool.go b/requestpool.go index 8406621f..478fbec7 100644 --- a/requestpool.go +++ b/requestpool.go @@ -37,7 +37,7 @@ import ( // handling and rendering; see [Request]. // // If r is nil, the Request has no initial request, client address, or [Session]. -// Otherwise, its Session follows the request's scheme; see [Jaws.CookieName]. +// Otherwise, Session lookup follows the request's scheme; see [Jaws.CookieName]. // // [Jaws.ServeWithTimeout] periodically retires idle Requests before WebSocket // processing starts; [Jaws.Serve] uses [DefaultWebSocketTimeout]. diff --git a/session.go b/session.go index aee7a8f6..f1aa7e1d 100644 --- a/session.go +++ b/session.go @@ -48,7 +48,7 @@ func (jw *Jaws) sessionCookieName(secure bool) string { // Session stores server-side state shared by one or more Requests. // // Sessions live in memory and are bound to the remote IP that created them. -// HTTP and HTTPS requests use distinct cookie names and Sessions. +// Requests recognized as HTTP and HTTPS use distinct cookie names and Sessions. // Their cookies have no explicit expiry or MaxAge. A Session starts with a // one-minute grace deadline; ExtendGrace can lengthen it for a bounded external // flow. Detaching a claimed Request refreshes the normal grace without shortening @@ -373,8 +373,6 @@ func (jw *Jaws) Sessions() (sessions []*Session) { } func (jw *Jaws) getSessionByIDLocked(sessionID key.Key, remoteIP netip.Addr, cookieName string) (sess *Session) { - // A valid ID under the other scheme's cookie name must not cross the - // HTTP/HTTPS session boundary. The cookie name is fixed at creation. if found, ok := jw.sessions[sessionID]; ok && found.cookie.Name == cookieName && equalIP(remoteIP, found.remoteIP) && !found.isDead() { sess = found } @@ -417,11 +415,9 @@ func getCookieSessionsIDs(h http.Header, wanted string) (cookies []key.Key) { // GetSession returns the [Session] associated with the given [http.Request], or nil. // -// Sessions are bound to the client IP (see the clientIP method). Behind a reverse -// proxy that connects over loopback, every request appears to come from loopback -// and IP binding is effectively disabled unless [Jaws.TrustForwardedHeaders] is -// enabled so the forwarded client IP is used instead. -// HTTP cookies are ignored on HTTPS requests and vice versa; see [Jaws.CookieName]. +// It matches the request's cookie name and client IP; HTTP and HTTPS use separate +// names. Behind a proxy, [Jaws.TrustForwardedHeaders] can use a forwarded +// client IP; otherwise Sessions bind to the transport peer. func (jw *Jaws) GetSession(r *http.Request) (sess *Session) { if r != nil { cookieName := jw.sessionCookieName(secureheaders.RequestIsSecure(r, jw.TrustForwardedHeaders)) @@ -435,24 +431,14 @@ func (jw *Jaws) GetSession(r *http.Request) (sess *Session) { return } -// NewSession creates a new [Session]. +// NewSession creates and publishes a new [Session]. // -// When creation succeeds, live pre-existing [Session] values referenced by -// matching cookies and bound to the request's client IP are cleared and closed. -// Each is closed with [Session.Close], so the JaWS processing loop ([Jaws.Serve] -// or [Jaws.ServeWithTimeout]) must be running. -// -// Subsequent [Request] values created with [Jaws.NewRequest] that have the -// cookie set and originate from the same IP will be able to access the [Session]. -// The IP comparison is the same loopback-aware, optionally forwarded-header-based -// match used everywhere else; see [Jaws.GetSession] and [Jaws.TrustForwardedHeaders] -// for the reverse-proxy caveat. -// -// If the new [Session] remains current and live during cookie publication, its -// cookie is written to w when w is non-nil and added to r itself. This makes the -// [Session] visible to [Jaws.GetSession] and [Jaws.NewRequest] for the remainder -// of the same HTTP request. If a concurrent [Session.Close] wins first, neither -// w nor r receives its live cookie. +// On success, it writes the cookie to w when w is non-nil and adds it to r, so +// [Jaws.GetSession] and [Jaws.NewRequest] can use it in the same HTTP request. +// It clears and closes live Sessions referenced by matching cookies and bound +// to the request's client IP. The JaWS processing loop ([Jaws.Serve] or +// [Jaws.ServeWithTimeout]) must be running for [Session.Close]. Replacing a +// Session needs a free slot under each enabled limit until the old one closes. // // Callers that send the cookie must prevent shared caching of the response. // [Jaws.SessionMiddleware] applies Cache-Control: no-store when it creates the @@ -460,12 +446,8 @@ func (jw *Jaws) GetSession(r *http.Request) (sess *Session) { // // It returns nil without closing matching Sessions if r is nil, shutdown has // begun, [Jaws.MaxSessions] or [Jaws.MaxSessionsPerIP] is reached, or cookie -// publication fails. It also returns nil when a [Jaws.CookieName] beginning -// with "__Host-", "__Secure-", or "__Http-" in any letter case is used without -// recognized HTTPS; w may be nil. Cookie names follow [Jaws.GetSession]. -// -// Replacing a Session requires a free slot under each enabled limit until the -// new cookie is published and the old Session is closed. +// publication fails. It also returns nil when [Jaws.CookieName] requires HTTPS +// and the request is not recognized as secure. // // It panics if the [crypto/rand.Reader] captured by [New] returns an error while // generating the session ID. Go's default reader does not return errors. From d723398102fe9debda076f0ed3a39aaf02d97f03 Mon Sep 17 00:00:00 2001 From: Johan Lindh Date: Mon, 9 Nov 2026 09:08:12 +0100 Subject: [PATCH 7/7] Simplify session cookie naming --- doc/sessions.md | 9 +--- jaws.go | 9 ++-- request_test.go | 23 ++------- session.go | 36 +++----------- session_test.go | 125 +----------------------------------------------- 5 files changed, 17 insertions(+), 185 deletions(-) diff --git a/doc/sessions.md b/doc/sessions.md index d71fdcdc..2970033d 100644 --- a/doc/sessions.md +++ b/doc/sessions.md @@ -9,19 +9,14 @@ authorization remain separate concerns. ## HTTP and HTTPS cookies -JaWS uses `jw.CookieName` on HTTP and `__Host-` on recognized HTTPS. +`jw.CookieName` is an unprefixed base name. JaWS uses it on HTTP and +`__Host-` on recognized HTTPS. Sessions cannot cross schemes. HTTPS cookies carry `Secure`, `Path=/`, and no `Domain`; browsers enforcing the [`__Host-` prefix](https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-4.1.3.2) reject sibling-domain and insecure HTTP attempts to set them. HTTP exposes session cookies to network traffic. For TLS-terminating proxies, see [deployment](deployment.md#reverse-proxies). -An explicitly `__Host-`-prefixed `jw.CookieName` (in any letter case) uses the -canonical `__Host-` prefix on HTTPS. A name beginning with `__Host-`, -`__Secure-`, or `__Http-` in any letter case disables HTTP Session use: -`GetSession` and `NewRequest` ignore matching cookies, `NewSession` returns nil, -`SessionMiddleware` returns HTTP 503, and `AutoSession` skips creation. - ## Create a session before rendering Wrap the page in `SessionMiddleware` when initial rendering needs a Session. diff --git a/jaws.go b/jaws.go index b3f0e4c0..e52d5f3f 100644 --- a/jaws.go +++ b/jaws.go @@ -94,17 +94,14 @@ type Jid = jid.Jid // convenience alias // may be changed while serving. Methods document their own concurrency behavior // and may be called concurrently when stated. type Jaws struct { - // CookieName is the base name used for session cookies. + // CookieName is the unprefixed base name used for session cookies. // // It defaults to [assets.DefaultCookieName], which is derived from the // executable and falls back to "jaws". CookieName must be a valid, non-empty // HTTP cookie name; see [http.Cookie.Valid]. // - // HTTP uses this name; recognized HTTPS uses a "__Host-" prefix. Sessions - // cannot cross schemes. A name starting with "__Host-", "__Secure-", or - // "__Http-" in any letter case disables HTTP Sessions; an explicit "__Host-" - // prefix is emitted in canonical case. See [Jaws.TrustForwardedHeaders] for - // proxy scheme detection. + // HTTP uses this name; recognized HTTPS prepends "__Host-". Sessions cannot + // cross schemes. See [Jaws.TrustForwardedHeaders] for proxy scheme detection. CookieName string // AutoSession creates a [Session] on a successful WebSocket upgrade. // diff --git a/request_test.go b/request_test.go index b6d54dcd..2623b3b6 100644 --- a/request_test.go +++ b/request_test.go @@ -4285,15 +4285,11 @@ func TestWS_AutoSessionSecureFollowsPage(t *testing.T) { pageScheme string upgradeScheme string wantSecure bool - hostPrefix bool }{ - {"HTTP page", "http", "", false, false}, - {"HTTPS scheme on both requests", "https", "https", true, false}, - {"HTTPS scheme only on page", "https", "", true, false}, - {"HTTPS scheme only on upgrade", "http", "https", false, false}, - {"__Host- HTTP page", "http", "", false, true}, - {"__Host- HTTPS page", "https", "https", true, true}, - {"__Host- HTTPS upgrade only", "http", "https", false, true}, + {"HTTP page", "http", "", false}, + {"HTTPS scheme on both requests", "https", "https", true}, + {"HTTPS scheme only on page", "https", "", true}, + {"HTTPS scheme only on upgrade", "http", "https", false}, } { t.Run(tc.name, func(t *testing.T) { jw, err := New() @@ -4302,9 +4298,6 @@ func TestWS_AutoSessionSecureFollowsPage(t *testing.T) { } jw.AutoSession = true jw.TrustForwardedHeaders = true - if tc.hostPrefix { - jw.CookieName = "__Host-" + jw.CookieName - } go jw.Serve() t.Cleanup(jw.Close) server := httptest.NewServer(jw) @@ -4334,12 +4327,6 @@ func TestWS_AutoSessionSecureFollowsPage(t *testing.T) { t.Fatalf("status = %d, want 101", resp.StatusCode) } cookies := resp.Cookies() - if tc.hostPrefix && !tc.wantSecure { - if len(cookies) != 0 || rq.Session() != nil { - t.Fatalf("insecure __Host- AutoSession: cookies=%v session=%p", cookies, rq.Session()) - } - return - } if len(cookies) != 1 { t.Fatalf("AutoSession cookies = %v, want one", cookies) } @@ -4347,7 +4334,7 @@ func TestWS_AutoSessionSecureFollowsPage(t *testing.T) { t.Fatalf("AutoSession cookie Secure = %v, want %v", cookies[0].Secure, tc.wantSecure) } wantName := jw.CookieName - if tc.wantSecure && !tc.hostPrefix { + if tc.wantSecure { wantName = "__Host-" + wantName } if cookies[0].Name != wantName { diff --git a/session.go b/session.go index f1aa7e1d..d3dbc718 100644 --- a/session.go +++ b/session.go @@ -17,32 +17,13 @@ import ( "github.com/linkdata/secureheaders" ) -const ( - sessionGrace = time.Minute - hostCookiePrefix = "__Host-" - secureCookiePrefix = "__Secure-" - httpCookiePrefix = "__Http-" -) - -func hasCookiePrefix(name, prefix string) bool { - return len(name) >= len(prefix) && strings.EqualFold(name[:len(prefix)], prefix) -} - -func requiresSecureCookie(name string) bool { - return hasCookiePrefix(name, hostCookiePrefix) || hasCookiePrefix(name, secureCookiePrefix) || hasCookiePrefix(name, httpCookiePrefix) -} +const sessionGrace = time.Minute func (jw *Jaws) sessionCookieName(secure bool) string { - if !secure { - if requiresSecureCookie(jw.CookieName) { - return "" - } - return jw.CookieName - } - if hasCookiePrefix(jw.CookieName, hostCookiePrefix) { - return hostCookiePrefix + jw.CookieName[len(hostCookiePrefix):] + if secure { + return "__Host-" + jw.CookieName } - return hostCookiePrefix + jw.CookieName + return jw.CookieName } // Session stores server-side state shared by one or more Requests. @@ -446,8 +427,7 @@ func (jw *Jaws) GetSession(r *http.Request) (sess *Session) { // // It returns nil without closing matching Sessions if r is nil, shutdown has // begun, [Jaws.MaxSessions] or [Jaws.MaxSessionsPerIP] is reached, or cookie -// publication fails. It also returns nil when [Jaws.CookieName] requires HTTPS -// and the request is not recognized as secure. +// publication fails. // // It panics if the [crypto/rand.Reader] captured by [New] returns an error while // generating the session ID. Go's default reader does not return errors. @@ -490,16 +470,12 @@ func (jw *Jaws) newSession(w http.ResponseWriter, r *http.Request) (sess *Sessio } // newSessionLocked allocates a Session whose ID is absent from jw.sessions, or -// returns nil after shutdown begins, a Session limit is reached, or a -// browser secure-only cookie prefix would be used without Secure. +// returns nil after shutdown begins or a Session limit is reached. // limitIP distinguishes the per-client limit for SessionMiddleware's HTTP response. // // The caller must hold jw.mu and publish any returned Session before releasing // it. func (jw *Jaws) newSessionLocked(remoteIP netip.Addr, secure bool) (sess *Session, limitIP bool) { - if !secure && requiresSecureCookie(jw.CookieName) { - return - } select { case <-jw.closeCh: return diff --git a/session_test.go b/session_test.go index 55f06819..6142aa23 100644 --- a/session_test.go +++ b/session_test.go @@ -1043,6 +1043,7 @@ func TestSession_CookiesSeparateSchemes(t *testing.T) { if err != nil { t.Fatal(err) } + jw.CookieName = "appsession" go jw.Serve() t.Cleanup(jw.Close) @@ -1113,130 +1114,6 @@ func TestSession_CookiesSeparateSchemes(t *testing.T) { } } -func TestSession_HostCookiePrefix(t *testing.T) { - for _, tc := range []struct { - name string - cookieName string - url string - forwarded bool - trust bool - want bool - }{ - {name: "HTTPS", cookieName: "__Host-jaws", url: "https://example.test/", want: true}, - {name: "HTTP", cookieName: "__Host-jaws", url: "http://example.test/"}, - {name: "untrusted proxy", cookieName: "__Host-jaws", url: "http://example.test/", forwarded: true}, - {name: "trusted proxy", cookieName: "__Host-jaws", url: "http://example.test/", forwarded: true, trust: true, want: true}, - } { - t.Run(tc.name, func(t *testing.T) { - jw, err := New() - if err != nil { - t.Fatal(err) - } - defer jw.Close() - jw.CookieName = tc.cookieName - jw.TrustForwardedHeaders = tc.trust - r := httptest.NewRequest(http.MethodGet, tc.url, nil) - if tc.forwarded { - r.Header.Set("X-Forwarded-Proto", "https") - } - w := httptest.NewRecorder() - sess := jw.NewSession(w, r) - cookies := w.Result().Cookies() - if !tc.want { - if sess != nil || len(cookies) != 0 || len(jw.Sessions()) != 0 { - t.Fatalf("insecure request created session %p with cookies %v", sess, cookies) - } - return - } - if sess == nil || len(cookies) != 1 { - t.Fatalf("secure request created session %p with cookies %v", sess, cookies) - } - cookie := cookies[0] - if cookie.Name != tc.cookieName || !cookie.Secure || cookie.Path != "/" || cookie.Domain != "" || !cookie.HttpOnly || cookie.SameSite != http.SameSiteLaxMode { - t.Fatalf("invalid __Host- cookie: %#v", cookie) - } - if got := jw.GetSession(r); got != sess { - t.Fatalf("GetSession = %p, want %p", got, sess) - } - }) - } -} - -func TestSession_ReservedCookiePrefixesRequireHTTPS(t *testing.T) { - for _, tc := range []struct { - name string - httpsName string - }{ - {"__hOsT-jaws", "__Host-jaws"}, - {"__sEcUrE-jaws", "__Host-__sEcUrE-jaws"}, - {"__hTtP-jaws", "__Host-__hTtP-jaws"}, - } { - t.Run(tc.name, func(t *testing.T) { - jw, err := New() - if err != nil { - t.Fatal(err) - } - defer jw.Close() - jw.CookieName = tc.name - httpResponse := httptest.NewRecorder() - httpSession := jw.NewSession(httpResponse, httptest.NewRequest(http.MethodGet, "http://example.test/", nil)) - httpsRequest := httptest.NewRequest(http.MethodGet, "https://example.test/", nil) - httpsSession := jw.NewSession(httptest.NewRecorder(), httpsRequest) - httpCookies := httpResponse.Result().Cookies() - if httpSession != nil || len(httpCookies) != 0 { - t.Fatalf("HTTP Session = %p; cookies = %v", httpSession, httpCookies) - } - if httpsSession == nil || httpsSession.Cookie().Name != tc.httpsName || !httpsSession.Cookie().Secure { - t.Fatalf("HTTPS Session = %p", httpsSession) - } - if got := jw.GetSession(httpsRequest); got != httpsSession { - t.Fatalf("GetSession = %p, want %p", got, httpsSession) - } - }) - } -} - -func TestSession_HostCookiePrefixRejectsInsecureRead(t *testing.T) { - jw, err := New() - if err != nil { - t.Fatal(err) - } - defer jw.Close() - jw.CookieName = "__Host-jaws" - r := httptest.NewRequest(http.MethodGet, "https://example.test/", nil) - sess := jw.NewSession(httptest.NewRecorder(), r) - if sess == nil { - t.Fatal("expected HTTPS session") - } - insecure := httptest.NewRequest(http.MethodGet, "http://example.test/", nil) - insecure.AddCookie(sess.Cookie()) - if got := jw.GetSession(insecure); got != nil { - t.Fatalf("HTTP GetSession accepted HTTPS session %p", got) - } - rq := jw.NewRequest(httptest.NewRecorder(), insecure) - if got := rq.Session(); got != nil { - t.Fatalf("HTTP NewRequest accepted HTTPS session %p", got) - } - rq.Cancel(nil) -} - -func TestSessionMiddleware_HostCookieRequiresHTTPS(t *testing.T) { - jw, err := New() - if err != nil { - t.Fatal(err) - } - defer jw.Close() - jw.CookieName = "__Host-jaws" - called := false - w := httptest.NewRecorder() - jw.SessionMiddleware(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { - called = true - })).ServeHTTP(w, httptest.NewRequest(http.MethodGet, "http://example.test/", nil)) - if w.Code != http.StatusServiceUnavailable || called || len(w.Result().Cookies()) != 0 { - t.Fatalf("insecure host cookie: status=%d called=%v cookies=%v", w.Code, called, w.Result().Cookies()) - } -} - func TestSession_Use(t *testing.T) { jw, _ := New() defer jw.Close()