package home import ( "encoding/hex" "net/http" "net/http/httptest" "net/url" "strings" "testing" "amadan.net/oficina/home/internal/home/seal" "amadan.net/oficina/home/internal/home/sealtest" "amadan.net/rastrillo/rastrillo/lastsignin" "amadan.net/rastrillo/rastrillo/webauthn/authtest" "github.com/keymaildev/signin" ) // The smart door on id.* (door.go, smart-door spec step 5): every state // the door answers, what it remembers and when, the same-person check, // Forget, and the return memory across the chooser. const jarCookie = "__Host-rastrillo_last_signin" // sealedRecord is rec as this app's jar seals it: a validly sealed cookie. func sealedRecord(t *testing.T, app *App, rec lastsignin.Record) *http.Cookie { t.Helper() w := httptest.NewRecorder() app.door.jar.Remember(w, rec) for _, c := range w.Result().Cookies() { if c.Name == jarCookie && c.Value != "" { return c } } t.Fatalf("the jar sealed nothing for %+v", rec) return nil } // jarSet is the jar cookie a response set, or nil; cleared reports a // deletion. func jarSet(r *httptest.ResponseRecorder) (set *http.Cookie, cleared bool) { for _, c := range r.Result().Cookies() { if c.Name != jarCookie { continue } if c.MaxAge < 0 || c.Value == "" { cleared = true continue } set = c } return set, cleared } // readJar opens a jar cookie with the app's own jar. func readJar(t *testing.T, app *App, c *http.Cookie) lastsignin.Record { t.Helper() req := httptest.NewRequest("GET", Origin+"/signin", nil) req.AddCookie(c) rec, res := app.door.jar.Read(req) if res != lastsignin.Valid { t.Fatalf("jar cookie reads as %v", res) } return rec } func doorGet(t *testing.T, app *testApp, path string, cookies ...*http.Cookie) *httptest.ResponseRecorder { t.Helper() r := returnRequest(app, "GET", path, nil, cookies...) if r.Header().Get("Cache-Control") != "no-store" { t.Fatalf("GET %s: door response is cacheable (%d)", path, r.Code) } return r } // The jar's key is HOME_DEK's, derived under home/lastsignin/v1, and its // origin is the credential origin: a cookie sealed under another label, // another DEK or another origin reads as Invalid, and the door clears it // and shows nothing of it. func TestDoorJarIsDerivedFromHomeDEKAndBoundToTheOrigin(t *testing.T) { app := newTestApp(t) if app.door.jar.CookieName() != jarCookie { t.Fatalf("cookie %q, want the __Host- one", app.door.jar.CookieName()) } good := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "kept@example.invalid"}) if !good.Secure || !good.HttpOnly || good.Path != "/" || good.Domain != "" || good.SameSite != http.SameSiteLaxMode { t.Fatalf("jar cookie attributes: %+v", good) } if body := doorGet(t, app, "/signin", good).Body.String(); !strings.Contains(body, "Continue as kept@example.invalid") { t.Fatal("a validly sealed cookie was not shown back") } dek := make([]byte, 32) for i := range dek { dek[i] = byte(i) } other := func(label string, dek []byte, origin string) *http.Cookie { s, err := seal.New(dek) if err != nil { t.Fatal(err) } key, err := s.Derive(label) if err != nil { t.Fatal(err) } jar, err := lastsignin.New(lastsignin.Config{Origin: origin, InstanceKey: hex.EncodeToString(key), Mode: lastsignin.On}) if err != nil { t.Fatal(err) } w := httptest.NewRecorder() jar.Remember(w, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "forged@example.invalid"}) return w.Result().Cookies()[0] } // The control: the same construction with Home's own inputs is read. if body := doorGet(t, app, "/signin", other(jarLabel, dek, Origin)).Body.String(); !strings.Contains(body, "forged@example.invalid") { t.Fatal("the jar is not HOME_DEK under home/lastsignin/v1 at the credential origin") } wrongDEK := append([]byte(nil), dek...) wrongDEK[0] ^= 1 for name, c := range map[string]*http.Cookie{ "label": other("home/lastsignin/v2", dek, Origin), "dek": other(jarLabel, wrongDEK, Origin), "origin": other(jarLabel, dek, directoryOrigin), "junk": {Name: jarCookie, Value: "not-a-sealed-value"}, } { r := doorGet(t, app, "/signin", c) if strings.Contains(r.Body.String(), "forged@example.invalid") { t.Fatalf("%s: a cookie the jar did not seal was shown", name) } if _, cleared := jarSet(r); !cleared { t.Fatalf("%s: an unbelievable cookie was not cleared", name) } } } // Every state of the door, drawn by rastrillo's partial: what the one // option is, what Other ways lists, and that the address appears only // where a sealed cookie put it. func TestDoorStates(t *testing.T) { app := newTestApp(t) const addr = "remembered@example.invalid" link := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: addr}) keymail := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodKeymail, Address: addr}) passkey := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodPasskey, Address: addr}) bare := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodPasskey}) const rt = "return_to=%2Fauthorize%2Fresume" field := ``, ``, `href="/signin?return_to=%2Fauthorize%2Fresume&way=email&ways=1">Other ways to sign in`}, []string{"Continue as", "data-rst-passkey-fallback", "@example.invalid"}}, {"first visit's chooser: a passkey, and Back", "/signin?ways=1&way=email&" + rt, nil, []string{"

Other ways to sign in

", `href="/signin?return_to=%2Fauthorize%2Fresume&way=passkey"`, "Sign in with a passkey", `href="/signin?return_to=%2Fauthorize%2Fresume&way=email">Back"}, []string{"Use a different email", field}}, {"passkey remembered: the passkey, drawn visible and disabled", "/signin?" + rt, passkey, []string{passkeyDoor, "Sign in with your passkey", `data-rst-passkey-fallback="/signin?return_to=%2Fauthorize%2Fresume&way=email"`, "", `href="/signin?return_to=%2Fauthorize%2Fresume&way=passkey&ways=1"`}, []string{field, addr, " hidden data-rst-passkey"}}, {"passkey remembered, chooser: Email with the kept address, Use a different email", "/signin?ways=1&way=passkey&" + rt, passkey, []string{"Email " + addr + "", `action="/signin/forget">`, "Use a different email", "Back"}, []string{"Sign in with a passkey"}}, {"passkey remembered without an address", "/signin?ways=1&way=passkey", bare, []string{"Email", "Use a different email"}, []string{""}}, {"link remembered: Continue as", "/signin?" + rt, link, []string{"Continue as " + addr + "", ``, "Other ways to sign in"}, []string{field, passkeyDoor}}, {"link remembered, chooser: a passkey and Use a different email", "/signin?ways=1&way=email&" + rt, link, []string{"Sign in with a passkey", "Use a different email"}, []string{"Continue as"}}, {"keymail remembered: Continue to Keymail, as the address", "/signin", keymail, []string{">Continue to Keymail", "as " + addr + "", `name="expect" value="keymail"`}, []string{field}}, {"way=email on a remembered passkey: the address's one-tap", "/signin?way=email", passkey, []string{"Continue as " + addr + ""}, []string{passkeyDoor}}, {"way=passkey on a remembered link: the passkey door", "/signin?way=passkey", link, []string{passkeyDoor, "Sign in with a passkey"}, []string{"Continue as"}}, {"a way picks a method, never an address", "/signin?way=email&address=typed%40example.invalid", nil, []string{field}, []string{"typed@example.invalid"}}, {"force=1 (a failed Keymail): the field, force kept, prefilled from the cookie", "/signin?force=1", keymail, []string{`action="/signin?force=1"`, ``, `value="` + addr + `"`, field}, []string{"Continue to Keymail"}}, {"err=keymail: the field and the problem", "/signin?err=keymail", link, []string{"Keymail couldn't confirm it's you.", field, ">Send me a link instead"}, []string{"Continue as"}}, {"err=rate", "/signin?err=rate", nil, []string{"Too many tries. Try again in a few minutes.", field}, nil}, {"err=expired", "/signin?err=expired", nil, []string{"That link has expired or was already used. Send a new one.", field}, nil}, {"err=address", "/signin?err=address", nil, []string{"That doesn't look like an email address.", field}, nil}, {"an unknown err is the generic problem", "/signin?err=whatever&ways=1", passkey, []string{"Something went wrong. Try again.", field}, []string{"Other ways to sign in", passkeyDoor}}, {"reauth=1: a step-up keeps the ways and says why", "/signin?reauth=1", passkey, []string{"Sign in again to continue.", passkeyDoor, "reauth=1"}, nil}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { var cookies []*http.Cookie if c.cookie != nil { cookies = append(cookies, c.cookie) } r := doorGet(t, app, c.path, cookies...) if r.Code != 200 { t.Fatal(r.Code) } body := r.Body.String() for _, w := range c.want { if !strings.Contains(body, w) { t.Errorf("missing %q", w) } } for _, n := range c.notWant { if strings.Contains(body, n) { t.Errorf("unexpected %q", n) } } if strings.Contains(body, `data-rst-passkey-legacy-rpid`) { t.Error("a legacy RP ID on the door") } if t.Failed() { t.Log(body) } }) } } // A fresh step-up (max_age) asks again on the same door: the reauth notice // over the way this browser used last, every way still offered (each of // id.*'s ways is local), and reauth carried on every link. func TestDoorStepUpOffersLocalWays(t *testing.T) { p := newExchangePair(t) intent, navigation := freshSignInForm(t, p, nil) remembered := sealedRecord(t, p.credential.App, lastsignin.Record{Method: lastsignin.MethodPasskey}) r := exchangeRequest(p.credential.App, "GET", Origin+"/signin?return_to=%2Fauthorize%2Fresume", "", nil, intent, navigation, remembered) body := r.Body.String() for _, want := range []string{"Sign in again to continue.", "Sign in with your passkey", "way=passkey&ways=1"} { if !strings.Contains(body, want) { t.Errorf("step-up door missing %q", want) } } chooser := exchangeRequest(p.credential.App, "GET", Origin+"/signin?return_to=%2Fauthorize%2Fresume&ways=1&way=passkey", "", nil, intent, navigation, remembered).Body.String() if !strings.Contains(chooser, "reauth=1") || !strings.Contains(chooser, `name="reauth" value="1"`) { t.Error("the chooser dropped the step-up") } if r.Header().Get("Cache-Control") != "no-store" { t.Error("cacheable step-up door") } } // A failed Begin redraws the field door with the problem and the right // status, prefilled from the cookie and never from what was posted. func TestDoorBeginFailures(t *testing.T) { app := newTestApp(t) keymail := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodKeymail, Address: "kept@example.invalid"}) bad := returnRequest(app, "POST", "/signin", url.Values{"address": {"typed-not-an-address"}}, keymail) body := bad.Body.String() if bad.Code != 400 || bad.Header().Get("Cache-Control") != "no-store" || !strings.Contains(body, "That doesn't look like an email address.") || !strings.Contains(body, `value="kept@example.invalid"`) || strings.Contains(body, "typed-not-an-address") { t.Fatalf("bad address: %d\n%s", bad.Code, body) } forced := returnRequest(app, "POST", "/signin?force=1", url.Values{"address": {"nope"}}) if !strings.Contains(forced.Body.String(), `action="/signin?force=1"`) { t.Fatal("a forced retry's error dropped force") } limited := app var last *httptest.ResponseRecorder for i := 0; i < 30; i++ { last = returnRequest(limited, "POST", "/signin", url.Values{"address": {"many@example.invalid"}}) if last.Code == http.StatusTooManyRequests { break } } if last.Code != http.StatusTooManyRequests || !strings.Contains(last.Body.String(), "Too many tries. Try again in a few minutes.") || last.Header().Get("Cache-Control") != "no-store" { t.Fatal("rate limit", last.Code) } } // Sent stays address-free (Home's is by design), even with a remembered // address, and keeps "Use a different email". func TestDoorSentIsAddressFree(t *testing.T) { app := newTestApp(t) link := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "kept@example.invalid"}) r := doorGet(t, app, "/signin/sent?attempt=x&ways=1", link) body := r.Body.String() if !strings.Contains(body, "We sent a link to your inbox.") || strings.Contains(body, "kept@example.invalid") || !strings.Contains(body, "Use a different email") { t.Fatal(body) } } // What the door remembers, and when: a proven link, a Keymail callback, // and a passkey (direct, and a finished gate), with the address kept on a // passkey record only for the same person. func TestDoorRemembersProvenSignIns(t *testing.T) { t.Run("magic link", func(t *testing.T) { app := newTestApp(t) signIn(t, app, "linked@example.invalid") if c, _ := jarSet(redeem(t, app, "nope")); c != nil { t.Fatal("a failed redemption remembered something") } r := redeem(t, app, capturedLink(t, app)) c, _ := jarSet(r) if c == nil { t.Fatal("a proven link remembered nothing") } if got := readJar(t, app.App, c); got.Method != lastsignin.MethodMagicLink || got.Address != "linked@example.invalid" { t.Fatalf("remembered %+v", got) } if c, _ := jarSet(signIn(t, app, "unproven@example.invalid")); c != nil { t.Fatal("Begin remembered an address nobody has proved") } }) t.Run("keymail", func(t *testing.T) { app := newTestApp(t) const addr = "person@keymail.invalid" newKeymailStub(t, app, addr) pending, state := beginKeymail(t, app, addr) c, _ := jarSet(callback(t, app, "code-1", state, pending)) if c == nil { t.Fatal("a Keymail callback remembered nothing") } if got := readJar(t, app.App, c); got.Method != lastsignin.MethodKeymail || got.Address != addr { t.Fatalf("remembered %+v", got) } if c, _ := jarSet(callback(t, app, "code-2", "bad-state", pending)); c != nil { t.Fatal("a failed callback remembered something") } }) for _, kind := range []string{"same person", "another person", "nothing remembered", "unbelievable"} { t.Run("direct passkey, "+kind, func(t *testing.T) { app := newTestApp(t) owner := "owner@example.invalid" key := enrol(t, app, signInFully(t, app, owner)) signInFully(t, app, "someone-else@example.invalid") var prior *http.Cookie want := "" switch kind { case "same person": prior = sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "OWNER@example.invalid"}) want = "OWNER@example.invalid" case "another person": prior = sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "someone-else@example.invalid"}) case "unbelievable": prior = &http.Cookie{Name: jarCookie, Value: "junk"} } done := directPasskey(t, app, key, prior) c, _ := jarSet(done) if c == nil { t.Fatal("a passkey sign-in remembered nothing") } if got := readJar(t, app.App, c); got.Method != lastsignin.MethodPasskey || got.Address != want { t.Fatalf("remembered %+v, want passkey with %q", got, want) } }) } t.Run("a record the jar refuses clears the old one", func(t *testing.T) { app := newTestApp(t) prior := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "previous@example.invalid"}) long := strings.Repeat("a", 250) + "@example.invalid" // over lastsignin's 254 bytes w := httptest.NewRecorder() req := httptest.NewRequest("GET", Origin+"/signin/verify", nil) req.AddCookie(prior) app.rememberEmail(w, signin.Identity{Method: signin.MethodMagicLink, Address: long}) set, cleared := jarSet(w) if set != nil || !cleared || w.Header().Get("Cache-Control") != "no-store" { t.Fatal("a refused record left the previous person's record in place", set, cleared) } }) t.Run("a refused passkey remembers nothing", func(t *testing.T) { app := newTestApp(t) enrol(t, app, signInFully(t, app, "owner@example.invalid")) stranger, _ := authtest.New() if c, _ := jarSet(directPasskey(t, app, stranger, nil)); c != nil { t.Fatal("a refused finish remembered a passkey") } }) t.Run("gate", func(t *testing.T) { app := newTestApp(t) const addr = "gated@example.invalid" key := enrol(t, app, signInFully(t, app, addr)) signIn(t, app, addr) first := redeem(t, app, capturedLink(t, app)) emailed, _ := jarSet(first) if first.Header().Get("Location") != confirmPath || emailed == nil || readJar(t, app.App, emailed).Address != addr { t.Fatal("the first factor was not remembered before the gate", first.Header().Get("Location")) } gate := namedCookie(t, first, gateCookie) begin := idJSON(t, app, "/passkey/signin/begin", nil, gate) zero := uint32(0) done := idJSON(t, app, "/passkey/signin/finish", assertionBody(key, challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin, Count: &zero}), gate, emailed) c, _ := jarSet(done) if done.Code != 200 || c == nil { t.Fatal("a finished gate remembered nothing", done.Code) } if got := readJar(t, app.App, c); got.Method != lastsignin.MethodPasskey || got.Address != addr { t.Fatalf("remembered %+v", got) } if body := doorGet(t, app, "/signin", c).Body.String(); !strings.Contains(body, "Sign in with your passkey") { t.Fatal("the next visit does not offer the passkey") } }) } // directPasskey runs one discoverable sign-in with key, presenting prior // (a jar cookie) on the finish. func directPasskey(t *testing.T, app *testApp, key *authtest.Authenticator, prior *http.Cookie) *httptest.ResponseRecorder { t.Helper() begin := idJSON(t, app, directBegin, nil) zero := uint32(0) body := assertionBody(key, challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin, Count: &zero}) return idJSON(t, app, directFinish, body, namedCookie(t, begin, ceremonyCookie), prior) } // The passkey finish answers rastrillo's shape, which the door's module // reads: {"ok":true,"to":} on success, a non-2xx on refusal // (so the conditional request re-begins once). func TestDoorPasskeyFinishAnswersRastrillosShape(t *testing.T) { app := newTestApp(t) key := enrol(t, app, signInFully(t, app, "shape@example.invalid")) if _, err := app.db.Writer().Exec("INSERT INTO passkey_recovery_codes(subject,code_hash,created_at) SELECT subject,'x','2026-01-01T00:00:00Z' FROM passkey_credentials"); err != nil { t.Fatal(err) } done := directPasskey(t, app, key, nil) if done.Code != 200 || strings.TrimSpace(done.Body.String()) != `{"ok":true,"to":"/"}` || done.Header().Get("Cache-Control") != "no-store" { t.Fatal(done.Code, done.Body.String()) } stranger, _ := authtest.New() if refused := directPasskey(t, app, stranger, nil); refused.Code/100 == 2 { t.Fatal("a refused finish answered 2xx", refused.Code) } } // The direct finish takes the door's return_to from its own URL (the // module puts the page's return_to there), so a late autofill pick, with // the ten-minute return cookie gone or replaced by another tab, still // lands in the app's handoff. A hostile one is no destination, and it // beats the cookie only when it names one. func TestDoorDirectFinishKeepsTheDoorsReturn(t *testing.T) { app := newTestApp(t) key := enrol(t, app, signInFully(t, app, "late@example.invalid")) if _, err := app.db.Writer().Exec("INSERT INTO passkey_recovery_codes(subject,code_hash,created_at) SELECT subject,'x','2026-01-01T00:00:00Z' FROM passkey_credentials"); err != nil { t.Fatal(err) } finish := func(query string, cookies ...*http.Cookie) string { t.Helper() begin := idJSON(t, app, directBegin, nil) zero := uint32(0) body := assertionBody(key, challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin, Count: &zero}) done := idJSON(t, app, directFinish+query, body, append(cookies, namedCookie(t, begin, ceremonyCookie))...) if done.Code != 200 { t.Fatal("finish", done.Code) } return strings.TrimSpace(done.Body.String()) } if got := finish("?return_to=%2Fauthorize%2Fresume"); got != `{"ok":true,"to":"/authorize/resume"}` { t.Fatal("no cookie: lost the door's return", got) } other := &http.Cookie{Name: returnCookie, Value: "/passkey/codes"} if got := finish("?return_to=%2Fauthorize%2Fresume", other); got != `{"ok":true,"to":"/authorize/resume"}` { t.Fatal("another tab's cookie won over the door's return", got) } if got := finish("?return_to=https%3A%2F%2Fevil.invalid%2F", other); got != `{"ok":true,"to":"/passkey/codes"}` { t.Fatal("a hostile return_to displaced the cookie", got) } if got := finish("?return_to=https%3A%2F%2Fevil.invalid%2F"); got != `{"ok":true,"to":"/"}` { t.Fatal("a hostile return_to was followed", got) } } // The directory never holds the door's memory: it never serves the door. func TestDirectoryHasNoDoorMemory(t *testing.T) { p := newExchangePair(t) if p.directory.door != nil { t.Fatal("the directory built a jar") } if p.credential.door == nil { t.Fatal("the credential origin has no jar") } } // Forget: "Use a different email" forgets this browser's record, opens the // email field and keeps where the sign-in was going; it needs origin // evidence, as every form here does. func TestDoorForget(t *testing.T) { app := newTestApp(t) link := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "kept@example.invalid"}) r := returnRequest(app, "POST", forgetPath, url.Values{"return_to": {"/authorize/resume"}, "way": {"email"}}, link) if _, cleared := jarSet(r); !cleared || r.Code != 303 || r.Header().Get("Location") != "/signin?return_to=%2Fauthorize%2Fresume&way=email" || r.Header().Get("Cache-Control") != "no-store" { t.Fatal(r.Code, r.Header()) } // No posted return_to: the return cookie's, and a step-up kept. keep := &http.Cookie{Name: returnCookie, Value: "/passkey/codes"} r = returnRequest(app, "POST", forgetPath, url.Values{"way": {"email"}, "reauth": {"1"}}, link, keep) if r.Header().Get("Location") != "/signin?reauth=1&return_to=%2Fpasskey%2Fcodes&way=email" { t.Fatal(r.Header().Get("Location")) } // A hostile return_to is no destination. r = returnRequest(app, "POST", forgetPath, url.Values{"return_to": {"https://evil.invalid/"}}, link) if r.Header().Get("Location") != "/signin" { t.Fatal(r.Header().Get("Location")) } req := httptest.NewRequest("POST", forgetPath, strings.NewReader("way=email")) req.Host = credentialHost req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("Sec-Fetch-Site", "cross-site") req.AddCookie(link) w := httptest.NewRecorder() app.Router().ServeHTTP(w, req) if _, cleared := jarSet(w); cleared || w.Code != http.StatusForbidden { t.Fatal("a cross-site Forget went through", w.Code) } // Forget, then the door: nothing remembered, the field. after := doorGet(t, app, "/signin?way=email") if strings.Contains(after.Body.String(), "kept@example.invalid") { t.Fatal("still remembered") } } // The chained Forget: an app's signed-out page links to /forget?return=…; // id.* asks once, forgets on a same-origin POST, and returns only to a // registered consumer's /signed-out, else to its own signed-out page. func TestDoorForgetChain(t *testing.T) { p := newExchangePair(t) app := p.credential link := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "kept@example.invalid"}) const back = "https://blue.docs.oficina.works/signed-out" page := exchangeRequest(app.App, "GET", Origin+forgetChainPath+"?return="+url.QueryEscape(back), "", nil, link) body := page.Body.String() for _, want := range []string{`
`, ">Forget me on Oficina ID too", `Not now`} { if !strings.Contains(body, want) { t.Errorf("confirm page missing %q", want) } } if page.Code != 200 || page.Header().Get("Cache-Control") != "no-store" || !strings.Contains(page.Header().Get("Content-Security-Policy"), "https://blue.docs.oficina.works") { t.Fatal("confirm page", page.Code, page.Header()) } if _, cleared := jarSet(page); cleared || strings.Contains(body, "kept@example.invalid") { t.Fatal("the GET forgot, or showed the address") } done := exchangeRequest(app.App, "POST", Origin+forgetChainPath, Origin, url.Values{"return": {back}}, link) if _, cleared := jarSet(done); !cleared || done.Code != 303 || done.Header().Get("Location") != back { t.Fatal("forget", done.Code, done.Header()) } for _, bad := range []string{ "", "https://evil.invalid/signed-out", "https://blue.docs.oficina.works/", "https://blue.docs.oficina.works/signed-out?x=1", "https://blue.docs.oficina.works/signed-out#x", "https://u@blue.docs.oficina.works/signed-out", "http://blue.docs.oficina.works/signed-out", "https://blue.docs.oficina.works:443/signed-out", "https://blue.docs.oficina.works/signed-out/", "//blue.docs.oficina.works/signed-out", "https://blue.docs.oficina.works/%73igned-out", "/signed-out", "javascript:alert(1)", } { page := exchangeRequest(app.App, "GET", Origin+forgetChainPath+"?return="+url.QueryEscape(bad), "", nil) if !strings.Contains(page.Body.String(), `Not now`) || strings.Contains(page.Body.String(), `name="return"`) || strings.Contains(page.Header().Get("Content-Security-Policy"), "blue.docs") { t.Errorf("GET %q was trusted", bad) } post := exchangeRequest(app.App, "POST", Origin+forgetChainPath, Origin, url.Values{"return": {bad}}, link) if post.Header().Get("Location") != "/signed-out" { t.Errorf("POST %q went to %q", bad, post.Header().Get("Location")) } } if cross := exchangeRequest(app.App, "POST", Origin+forgetChainPath, "https://blue.docs.oficina.works", url.Values{"return": {back}}, link); cross.Code != http.StatusForbidden { t.Fatal("a cross-origin chained Forget went through", cross.Code) } // The directory is a registered consumer too. if r := exchangeRequest(app.App, "POST", Origin+forgetChainPath, Origin, url.Values{"return": {directoryOrigin + "/signed-out"}}); r.Header().Get("Location") != directoryOrigin+"/signed-out" { t.Fatal("the directory's signed-out page refused", r.Header().Get("Location")) } // id.*'s own signed-out page offers its own Forget. own := exchangeRequest(app.App, "GET", Origin+"/signed-out", "", nil).Body.String() if !strings.Contains(own, `action="/signin/forget"`) || !strings.Contains(own, ">Forget me on this device") { t.Fatal("id.* signed-out page has no Forget") } } // The return memory survives the door: an app sends a person to id.*; they // open Other ways, pick a passkey, sign in with it, and land back in the // app. Every chooser link and the passkey finish carry return_to, so // rememberReturn never forgets the handoff on the way. func TestDoorAppToChooserToPasskeyAndBack(t *testing.T) { p := newExchangePair(t) app := p.credential key := enrol(t, app, signInFully(t, app, sealtest.CanaryAddress)) if _, err := app.db.Writer().Exec("INSERT INTO passkey_recovery_codes(subject,code_hash,created_at) SELECT subject,'x','2026-01-01T00:00:00Z' FROM passkey_credentials"); err != nil { t.Fatal(err) } pending, intent := p.start(t) // the app (here, the directory) asks id.* for an assertion resume := exchangeRequest(app.App, "GET", Origin+"/authorize/resume", "", nil, intent) if resume.Code != 303 { t.Fatal("no sign-in asked for", resume.Code) } jar := &cookieJar{} jar.add(intent) follow := func(target string) *httptest.ResponseRecorder { t.Helper() r := exchangeRequest(app.App, "GET", Origin+target, "", nil, jar.all()...) jar.take(r) if r.Code != 200 { t.Fatal("GET", target, r.Code) } return r } door := follow(resume.Header().Get("Location")) ways := follow(hrefOf(t, door.Body.String(), "Other ways to sign in")) passkeyDoor := follow(hrefOf(t, ways.Body.String(), "Sign in with a passkey")) if !strings.Contains(passkeyDoor.Body.String(), `data-rst-passkey-finish="/passkey/direct/finish?return_to=%2Fauthorize%2Fresume"`) { t.Fatal("the passkey door lost the return") } begin := exchangeRequest(app.App, "POST", Origin+directBegin, Origin, nil, jar.all()...) jar.take(begin) zero := uint32(0) finish := idJSON(t, app, directFinish+"?return_to=%2Fauthorize%2Fresume", assertionBody(key, challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin, Count: &zero}), jar.all()...) jar.take(finish) if finish.Code != 200 || strings.TrimSpace(finish.Body.String()) != `{"ok":true,"to":"/authorize/resume"}` { t.Fatal("finish", finish.Code, finish.Body.String()) } token, _ := p.mint(t, intent, sessionCookie(finish)) p.finish(t, token, pending) // back in the app, signed in } // hrefOf is the href of the link whose text contains label. func hrefOf(t *testing.T, body, label string) string { t.Helper() i := strings.Index(body, ""+label+"") if i < 0 { t.Fatalf("no link %q", label) } j := strings.LastIndex(body[:i], `href="`) if j < 0 { t.Fatalf("no href before %q", label) } rest := body[j+len(`href="`):] return strings.ReplaceAll(rest[:strings.Index(rest, `"`)], "&", "&") } // cookieJar is a browser's cookies for one origin, enough for a walk. type cookieJar struct{ m map[string]*http.Cookie } func (j *cookieJar) add(c *http.Cookie) { if j.m == nil { j.m = map[string]*http.Cookie{} } j.m[c.Name] = c } func (j *cookieJar) take(r *httptest.ResponseRecorder) { for _, c := range r.Result().Cookies() { if c.MaxAge < 0 || c.Value == "" { delete(j.m, c.Name) continue } j.add(c) } } func (j *cookieJar) all() []*http.Cookie { var out []*http.Cookie for _, c := range j.m { out = append(out, &http.Cookie{Name: c.Name, Value: c.Value}) } return out }