Sign-ins finish only in the browser that started them

A Core sign-in, and a posting account's or Search Console's OAuth sign-in,
now sets a short-lived cookie whose hash the flow keeps on the server. The
callback refuses one without it (constant-time compare), clears the cookie
either way, and the flow is used up regardless. This stops login CSRF: a
callback URL brought to another browser signs nobody in.

The cookie uses the __Host- prefix over https, so its Path is "/".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-04 08:07:21 -07:00
co-authored by Claude Opus 5.5
parent 005c4ac800
commit cd2dc6145b
9 changed files with 240 additions and 9 deletions
+3 -2
View File
@@ -33,8 +33,9 @@ type Pending struct {
Verifier string // PKCE, X only
RedirectURI string
Started time.Time
For int64 `json:",omitempty"` // a person signing in their own posting account; 0: the company's
Team int64 `json:",omitempty"` // the team it was started in (multi-tenant)
For int64 `json:",omitempty"` // a person signing in their own posting account; 0: the company's
Team int64 `json:",omitempty"` // the team it was started in (multi-tenant)
Browser string `json:",omitempty"` // the hash of the cookie that ties it to a browser
}
// --- X ---
+1
View File
@@ -87,6 +87,7 @@ type Flow struct {
Verifier string `json:"verifier"`
Started time.Time `json:"started"`
Next string `json:"next,omitempty"`
Browser string `json:"browser,omitempty"` // the hash of the cookie that ties it to a browser
}
func random() (string, error) {
+14 -1
View File
@@ -351,6 +351,10 @@ func (s *Server) signinCore(w http.ResponseWriter, r *http.Request) {
return
}
f.Next = next
if f.Browser, err = s.bindFlow(w, coreFlowCookie, coreFlowTTL); err != nil {
s.serverError(w, err)
return
}
if err := ts.DB.PutJSON(coreFlowKey+f.State, f); err != nil {
s.serverError(w, err)
return
@@ -374,6 +378,13 @@ func (s *Server) takeCoreFlow(state string) *oidc.Flow {
return &f
}
func flowBrowser(f *oidc.Flow) string {
if f == nil {
return ""
}
return f.Browser
}
// coreCallbackPage finishes a sign-in with the Core.
func (s *Server) coreCallbackPage(w http.ResponseWriter, r *http.Request) {
if !s.signsIn() {
@@ -401,7 +412,9 @@ func (s *Server) coreCallbackPage(w http.ResponseWriter, r *http.Request) {
s.signinFail(w, r, signinForm{Problem: msg}, code)
}
f := ts.takeCoreFlow(state)
if f == nil {
// Taken either way, and the cookie cleared: a callback opened in
// another browser can't sign it in, nor be tried again.
if fromHere := s.flowFromThisBrowser(w, r, coreFlowCookie, flowBrowser(f)); f == nil || !fromHere {
fail("That sign-in took too long or was already used. Try again.", http.StatusBadRequest)
return
}
+110 -1
View File
@@ -74,7 +74,21 @@ func (f *fakeCore) signInWithCore(t *testing.T, h http.Handler, form url.Values)
f.mu.Lock()
f.challenge[code], f.nonce[code] = q.Get("code_challenge"), q.Get("nonce")
f.mu.Unlock()
return do(h, http.MethodGet, "/auth/core/callback?state="+url.QueryEscape(q.Get("state"))+"&code="+code, nil, nil)
return getWith(h, "/auth/core/callback?state="+url.QueryEscape(q.Get("state"))+"&code="+code, cookieOf(rec, coreFlowCookie))
}
// getWith GETs a page with cookies (nil ones left out).
func getWith(h http.Handler, target string, cs ...*http.Cookie) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodGet, target, nil)
req.Host = "localhost:8470"
for _, c := range cs {
if c != nil {
req.AddCookie(c)
}
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
// setUpCore makes the team's client and turns sign-in with the Core on.
@@ -173,6 +187,101 @@ func TestSignInWithCore(t *testing.T) {
}
}
// A Core sign-in finishes only in the browser that started it: a callback
// URL brought to another (login CSRF) signs nobody in.
func TestCoreCallbackNeedsItsBrowser(t *testing.T) {
s, h := newServerEdition(t)
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
oc := sessionFor(t, s, owner)
f := newFakeCore(t)
setUpCore(t, s, h, oc, f, nil)
f.who = map[string]any{"sub": "owner-sub", "email": "owner@example.com", "email_verified": true}
start := func() (string, *http.Cookie) {
t.Helper()
rec := postForm(h, "/signin/core", url.Values{})
u, _ := url.Parse(rec.Header().Get("Location"))
q := u.Query()
code := "code-" + q.Get("state")[:6]
f.mu.Lock()
f.challenge[code], f.nonce[code] = q.Get("code_challenge"), q.Get("nonce")
f.mu.Unlock()
return "/auth/core/callback?state=" + url.QueryEscape(q.Get("state")) + "&code=" + code, cookieOf(rec, coreFlowCookie)
}
refused := func(rec *httptest.ResponseRecorder) bool {
return rec.Code == http.StatusBadRequest && cookieOf(rec, sessionCookie) == nil &&
strings.Contains(rec.Body.String(), "took too long or was already used")
}
cb, c := start()
if c == nil || !c.HttpOnly || c.SameSite != http.SameSiteLaxMode || c.Path != "/" || c.MaxAge != int(coreFlowTTL/time.Second) || c.Secure {
t.Fatalf("cookie %+v", c)
}
var flows int
s.DB.QueryRow(`SELECT COUNT(*) FROM settings WHERE key LIKE 'oidc:flow:%'`).Scan(&flows)
if flows != 1 {
t.Fatalf("flows: %d", flows)
}
// Another browser: refused, and the flow is gone.
rec := getWith(h, cb)
if !refused(rec) {
t.Errorf("without the cookie: %d %s", rec.Code, rec.Body.String())
}
if !clears(rec, coreFlowCookie) {
t.Error("the cookie isn't cleared on a refusal")
}
if rec := getWith(h, cb, c); !refused(rec) {
t.Errorf("its browser, after a refusal: %d", rec.Code)
}
// Another flow's cookie.
cbA, _ := start()
_, cB := start()
if rec := getWith(h, cbA, cB); !refused(rec) {
t.Errorf("another flow's cookie: %d", rec.Code)
}
// Its own browser: signed in, the cookie cleared; replayed: refused.
cb, c = start()
rec = getWith(h, cb, c)
if rec.Code != http.StatusSeeOther || cookieOf(rec, sessionCookie) == nil || !clears(rec, coreFlowCookie) {
t.Fatalf("its own browser: %d %s", rec.Code, rec.Body.String())
}
if rec := getWith(h, cb, c); !refused(rec) {
t.Errorf("replayed: %d", rec.Code)
}
// Refusals are in the log.
var n int
s.DB.QueryRow(`SELECT COUNT(*) FROM audit_log WHERE action = 'signin-failed'`).Scan(&n)
if n < 4 {
t.Errorf("logged refusals: %d", n)
}
}
// clears says whether a response removes a cookie.
func clears(rec *httptest.ResponseRecorder, name string) bool {
for _, c := range rec.Result().Cookies() {
if c.Name == name && c.MaxAge < 0 {
return true
}
}
return false
}
// Over https the cookie has the __Host- prefix, and is Secure.
func TestCoreFlowCookieOverHTTPS(t *testing.T) {
s, _ := newServerEdition(t)
s.PublicURL = "https://sm.example.com"
rec := httptest.NewRecorder()
hash, err := s.bindFlow(rec, coreFlowCookie, coreFlowTTL)
c := cookieOf(rec, "__Host-"+coreFlowCookie)
if err != nil || c == nil || !c.Secure || c.Path != "/" || hash == "" || hash == c.Value {
t.Fatalf("%v %+v", err, c)
}
req := httptest.NewRequest(http.MethodGet, "/auth/core/callback", nil)
req.AddCookie(c)
if !s.flowFromThisBrowser(httptest.NewRecorder(), req, coreFlowCookie, hash) {
t.Error("its own cookie refused")
}
}
func TestCoreOnlyAndAutoJoin(t *testing.T) {
s, h := newServerEdition(t)
owner := addUser(t, s, "owner@example.com", users.Owner, nil)
+59
View File
@@ -0,0 +1,59 @@
package web
import (
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"net/http"
"time"
)
// A sign-in that finishes at a callback URL (the Core's, a posting
// account's) is tied to the browser that started it: a random cookie, of
// which the flow on the server keeps the hash. A callback brought to
// another browser (a link, an image) lacks the cookie and is refused, so
// nobody can be signed in as someone else, or have someone else's account
// connected, by opening a URL.
const (
coreFlowCookie = "sm_oidc"
oauthFlowCookie = "sm_oauth"
)
// The cookie's Path is "/": over https it has the __Host- prefix (so no
// other subdomain can set it), which browsers only take with Path "/".
// SameSite Lax: it must come back on the provider's top-level redirect.
// bindFlow sets the cookie and gives the hash for the flow to keep.
func (s *Server) bindFlow(w http.ResponseWriter, name string, ttl time.Duration) (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", err
}
v := base64.RawURLEncoding.EncodeToString(b)
http.SetCookie(w, &http.Cookie{
Name: s.cookieName(name), Value: v, Path: "/", MaxAge: int(ttl / time.Second),
Secure: s.secureCookies(), HttpOnly: true, SameSite: http.SameSiteLaxMode,
})
return flowHash(v), nil
}
// flowFromThisBrowser says whether the request carries the cookie whose
// hash a flow kept, and clears the cookie either way.
func (s *Server) flowFromThisBrowser(w http.ResponseWriter, r *http.Request, name, hash string) bool {
http.SetCookie(w, &http.Cookie{
Name: s.cookieName(name), Value: "", Path: "/", MaxAge: -1,
Secure: s.secureCookies(), HttpOnly: true, SameSite: http.SameSiteLaxMode,
})
c, err := r.Cookie(s.cookieName(name))
if err != nil || c.Value == "" || hash == "" {
return false
}
return subtle.ConstantTimeCompare([]byte(flowHash(c.Value)), []byte(hash)) == 1
}
func flowHash(v string) string {
sum := sha256.Sum256([]byte(v))
return base64.RawURLEncoding.EncodeToString(sum[:])
}
+1 -1
View File
@@ -187,7 +187,7 @@ func TestOwnAccountSignIn(t *testing.T) {
}
// Another person can't finish Jo's sign-in.
other := sessionFor(t, s, seo)
if rec := as(h, other, http.MethodGet, "/auth/x/callback?code=c&state="+loc.Query().Get("state"), nil); rec.Code != http.StatusForbidden {
if rec := getWith(h, "/auth/x/callback?code=c&state="+loc.Query().Get("state"), other, cookieOf(rec, oauthFlowCookie)); rec.Code != http.StatusForbidden {
t.Errorf("someone else's callback: %d", rec.Code)
}
}
+1 -1
View File
@@ -80,7 +80,7 @@ func TestSearchConsole(t *testing.T) {
if !strings.HasPrefix(loc.String(), srv.URL+"/auth") || q.Get("access_type") != "offline" || !strings.Contains(q.Get("scope"), "webmasters.readonly") || q.Get("code_challenge") == "" {
t.Fatalf("start: %s", loc)
}
rec = do(h, http.MethodGet, "/auth/google/callback?state="+url.QueryEscape(q.Get("state"))+"&code=c0de", nil, nil)
rec = getWith(h, "/auth/google/callback?state="+url.QueryEscape(q.Get("state"))+"&code=c0de", cookieOf(rec, oauthFlowCookie))
if rec.Code != http.StatusSeeOther || !strings.HasPrefix(rec.Header().Get("Location"), "/settings/search?msg=google-connected") {
t.Fatalf("callback: %d %s %s", rec.Code, rec.Header().Get("Location"), rec.Body)
}
+37 -3
View File
@@ -350,15 +350,49 @@ func TestCallbackURLs(t *testing.T) {
func TestOAuthErrorIsShownOnce(t *testing.T) {
s, h := newTestServer(t, nil)
_ = s.Secrets.Set(map[string]string{secrets.LinkedInClientID: "cid", secrets.LinkedInClientSecret: "cs"})
loc, _ := url.Parse(postForm(h, "/auth/linkedin/start", nil).Header().Get("Location"))
start := postForm(h, "/auth/linkedin/start", nil)
loc, _ := url.Parse(start.Header().Get("Location"))
state := loc.Query().Get("state")
body := do(h, http.MethodGet, "/auth/linkedin/callback?state="+state+"&error=unauthorized_scope_error&error_description="+
url.QueryEscape("Scope &quot;openid&quot; is not authorized"), nil, nil).Body.String()
body := getWith(h, "/auth/linkedin/callback?state="+state+"&error=unauthorized_scope_error&error_description="+
url.QueryEscape("Scope &quot;openid&quot; is not authorized"), cookieOf(start, oauthFlowCookie)).Body.String()
if !strings.Contains(body, "Scope &#34;openid&#34; is not authorized") || strings.Contains(body, "&amp;quot;") {
t.Errorf("error page:\n%s", body)
}
}
// A posting account's sign-in finishes only in the browser that started it.
func TestOAuthCallbackNeedsItsBrowser(t *testing.T) {
s, h := newTestServer(t, nil)
_ = s.Secrets.Set(map[string]string{secrets.LinkedInClientID: "cid", secrets.LinkedInClientSecret: "cs"})
start := func() (string, *http.Cookie) {
rec := postForm(h, "/auth/linkedin/start", nil)
loc, _ := url.Parse(rec.Header().Get("Location"))
return loc.Query().Get("state"), cookieOf(rec, oauthFlowCookie)
}
refused := func(rec *httptest.ResponseRecorder) bool {
return rec.Code == http.StatusSeeOther && strings.Contains(rec.Header().Get("Location"), "oauth-expired")
}
state, c := start()
if c == nil || !c.HttpOnly || c.SameSite != http.SameSiteLaxMode || c.Path != "/" || c.MaxAge != int(oauthTTL/time.Second) {
t.Fatalf("cookie %+v", c)
}
cb := "/auth/linkedin/callback?error=access_denied&state="
if rec := getWith(h, cb+state); !refused(rec) {
t.Errorf("without the cookie: %d %s", rec.Code, rec.Header().Get("Location"))
}
if rec := getWith(h, cb+state, c); !refused(rec) {
t.Errorf("tried again after a refusal: %d", rec.Code)
}
state2, _ := start()
if rec := getWith(h, cb+state2, c); !refused(rec) {
t.Errorf("with another flow's cookie: %d", rec.Code)
}
state3, c3 := start()
if rec := getWith(h, cb+state3, c3); refused(rec) {
t.Errorf("its own browser: %d %s", rec.Code, rec.Header().Get("Location"))
}
}
func TestOAuthCallbackRejectsUnknownState(t *testing.T) {
_, h := newTestServer(t, nil)
rec := do(h, http.MethodGet, "/auth/x/callback?state=nope&code=c", nil, nil)
+14
View File
@@ -401,6 +401,10 @@ func (s *Server) oauthStart(w http.ResponseWriter, r *http.Request) {
return
}
p.For, p.Team = forUser, s.team()
if p.Browser, err = s.bindFlow(w, oauthFlowCookie, oauthTTL); err != nil {
s.serverError(w, err)
return
}
// Kept in the database: the callback may reach another copy of the app.
if err := s.DB.PutJSON(oauthFlowKey+p.State, p); err != nil {
s.serverError(w, err)
@@ -466,6 +470,16 @@ func (s *Server) oauthCallback(w http.ResponseWriter, r *http.Request) {
if p != nil && p.For != 0 {
back, nav = "/settings/account#posting", "settings/account"
}
browser := ""
if p != nil {
browser = p.Browser
}
// Only in the browser that started it (the cookie is cleared either way).
if !s.flowFromThisBrowser(w, r, oauthFlowCookie, browser) {
s.Log.Warn("oauth: callback from another browser", "provider", provider)
redirect(w, r, back, "oauth-expired")
return
}
if p == nil || p.Provider != provider || time.Since(p.Started) > oauthTTL || (p.Team != 0 && p.Team != s.team()) {
s.Log.Warn("oauth: callback with an unknown or expired state", "provider", provider)
redirect(w, r, back, "oauth-expired")