diff --git a/.agents/skills/jaws/SKILL.md b/.agents/skills/jaws/SKILL.md index 938bd4a3..da1f51a4 100644 --- a/.agents/skills/jaws/SKILL.md +++ b/.agents/skills/jaws/SKILL.md @@ -141,9 +141,26 @@ 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. +- [ ] `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`. +[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 Guide: `doc/bindings.md#html-and-attribute-safety`. diff --git a/doc/deployment.md b/doc/deployment.md index 6c403f08..66bcf1e1 100644 --- a/doc/deployment.md +++ b/doc/deployment.md @@ -94,11 +94,16 @@ 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 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 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 Origin scheme and host against the initial request, binds the callback to the diff --git a/doc/sessions.md b/doc/sessions.md index 4d9d7135..2970033d 100644 --- a/doc/sessions.md +++ b/doc/sessions.md @@ -7,6 +7,16 @@ 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 + +`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). + ## Create a session before rendering Wrap the page in `SessionMiddleware` when initial rendering needs a Session. @@ -89,8 +99,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..e52d5f3f 100644 --- a/jaws.go +++ b/jaws.go @@ -94,17 +94,20 @@ 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 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 prepends "__Host-". Sessions cannot + // cross schemes. 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. + // 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/request_test.go b/request_test.go index 39d996c3..2623b3b6 100644 --- a/request_test.go +++ b/request_test.go @@ -4333,6 +4333,13 @@ func TestWS_AutoSessionSecureFollowsPage(t *testing.T) { 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 { + 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..478fbec7 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, Session lookup 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..d3dbc718 100644 --- a/session.go +++ b/session.go @@ -19,9 +19,17 @@ import ( const sessionGrace = time.Minute +func (jw *Jaws) sessionCookieName(secure bool) string { + if secure { + return "__Host-" + 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. +// 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 @@ -50,7 +58,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 +353,16 @@ 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) { + 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 } } @@ -388,40 +396,30 @@ 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. +// 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 { - 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() } } 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 @@ -429,22 +427,20 @@ 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. -// -// 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 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. 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,8 +470,8 @@ 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 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. diff --git a/session_test.go b/session_test.go index b3374ceb..6142aa23 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,85 @@ 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) + } + jw.CookieName = "appsession" + 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_Use(t *testing.T) {