| 1 | package home |
| 2 | |
| 3 | import ( |
| 4 | "encoding/hex" |
| 5 | "net/http" |
| 6 | "net/http/httptest" |
| 7 | "net/url" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | |
| 11 | "amadan.net/oficina/home/internal/home/seal" |
| 12 | "amadan.net/oficina/home/internal/home/sealtest" |
| 13 | "amadan.net/rastrillo/rastrillo/lastsignin" |
| 14 | "amadan.net/rastrillo/rastrillo/webauthn/authtest" |
| 15 | "github.com/keymaildev/signin" |
| 16 | ) |
| 17 | |
| 18 | // The smart door on id.* (door.go, smart-door spec step 5): every state |
| 19 | // the door answers, what it remembers and when, the same-person check, |
| 20 | // Forget, and the return memory across the chooser. |
| 21 | |
| 22 | const jarCookie = "__Host-rastrillo_last_signin" |
| 23 | |
| 24 | // sealedRecord is rec as this app's jar seals it: a validly sealed cookie. |
| 25 | func sealedRecord(t *testing.T, app *App, rec lastsignin.Record) *http.Cookie { |
| 26 | t.Helper() |
| 27 | w := httptest.NewRecorder() |
| 28 | app.door.jar.Remember(w, rec) |
| 29 | for _, c := range w.Result().Cookies() { |
| 30 | if c.Name == jarCookie && c.Value != "" { |
| 31 | return c |
| 32 | } |
| 33 | } |
| 34 | t.Fatalf("the jar sealed nothing for %+v", rec) |
| 35 | return nil |
| 36 | } |
| 37 | |
| 38 | // jarSet is the jar cookie a response set, or nil; cleared reports a |
| 39 | // deletion. |
| 40 | func jarSet(r *httptest.ResponseRecorder) (set *http.Cookie, cleared bool) { |
| 41 | for _, c := range r.Result().Cookies() { |
| 42 | if c.Name != jarCookie { |
| 43 | continue |
| 44 | } |
| 45 | if c.MaxAge < 0 || c.Value == "" { |
| 46 | cleared = true |
| 47 | continue |
| 48 | } |
| 49 | set = c |
| 50 | } |
| 51 | return set, cleared |
| 52 | } |
| 53 | |
| 54 | // readJar opens a jar cookie with the app's own jar. |
| 55 | func readJar(t *testing.T, app *App, c *http.Cookie) lastsignin.Record { |
| 56 | t.Helper() |
| 57 | req := httptest.NewRequest("GET", Origin+"/signin", nil) |
| 58 | req.AddCookie(c) |
| 59 | rec, res := app.door.jar.Read(req) |
| 60 | if res != lastsignin.Valid { |
| 61 | t.Fatalf("jar cookie reads as %v", res) |
| 62 | } |
| 63 | return rec |
| 64 | } |
| 65 | |
| 66 | func doorGet(t *testing.T, app *testApp, path string, cookies ...*http.Cookie) *httptest.ResponseRecorder { |
| 67 | t.Helper() |
| 68 | r := returnRequest(app, "GET", path, nil, cookies...) |
| 69 | if r.Header().Get("Cache-Control") != "no-store" { |
| 70 | t.Fatalf("GET %s: door response is cacheable (%d)", path, r.Code) |
| 71 | } |
| 72 | return r |
| 73 | } |
| 74 | |
| 75 | // The jar's key is HOME_DEK's, derived under home/lastsignin/v1, and its |
| 76 | // origin is the credential origin: a cookie sealed under another label, |
| 77 | // another DEK or another origin reads as Invalid, and the door clears it |
| 78 | // and shows nothing of it. |
| 79 | func TestDoorJarIsDerivedFromHomeDEKAndBoundToTheOrigin(t *testing.T) { |
| 80 | app := newTestApp(t) |
| 81 | if app.door.jar.CookieName() != jarCookie { |
| 82 | t.Fatalf("cookie %q, want the __Host- one", app.door.jar.CookieName()) |
| 83 | } |
| 84 | good := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "kept@example.invalid"}) |
| 85 | if !good.Secure || !good.HttpOnly || good.Path != "/" || good.Domain != "" || good.SameSite != http.SameSiteLaxMode { |
| 86 | t.Fatalf("jar cookie attributes: %+v", good) |
| 87 | } |
| 88 | if body := doorGet(t, app, "/signin", good).Body.String(); !strings.Contains(body, "Continue as <bdi>kept@example.invalid</bdi>") { |
| 89 | t.Fatal("a validly sealed cookie was not shown back") |
| 90 | } |
| 91 | dek := make([]byte, 32) |
| 92 | for i := range dek { |
| 93 | dek[i] = byte(i) |
| 94 | } |
| 95 | other := func(label string, dek []byte, origin string) *http.Cookie { |
| 96 | s, err := seal.New(dek) |
| 97 | if err != nil { |
| 98 | t.Fatal(err) |
| 99 | } |
| 100 | key, err := s.Derive(label) |
| 101 | if err != nil { |
| 102 | t.Fatal(err) |
| 103 | } |
| 104 | jar, err := lastsignin.New(lastsignin.Config{Origin: origin, InstanceKey: hex.EncodeToString(key), Mode: lastsignin.On}) |
| 105 | if err != nil { |
| 106 | t.Fatal(err) |
| 107 | } |
| 108 | w := httptest.NewRecorder() |
| 109 | jar.Remember(w, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "forged@example.invalid"}) |
| 110 | return w.Result().Cookies()[0] |
| 111 | } |
| 112 | // The control: the same construction with Home's own inputs is read. |
| 113 | if body := doorGet(t, app, "/signin", other(jarLabel, dek, Origin)).Body.String(); !strings.Contains(body, "forged@example.invalid") { |
| 114 | t.Fatal("the jar is not HOME_DEK under home/lastsignin/v1 at the credential origin") |
| 115 | } |
| 116 | wrongDEK := append([]byte(nil), dek...) |
| 117 | wrongDEK[0] ^= 1 |
| 118 | for name, c := range map[string]*http.Cookie{ |
| 119 | "label": other("home/lastsignin/v2", dek, Origin), |
| 120 | "dek": other(jarLabel, wrongDEK, Origin), |
| 121 | "origin": other(jarLabel, dek, directoryOrigin), |
| 122 | "junk": {Name: jarCookie, Value: "not-a-sealed-value"}, |
| 123 | } { |
| 124 | r := doorGet(t, app, "/signin", c) |
| 125 | if strings.Contains(r.Body.String(), "forged@example.invalid") { |
| 126 | t.Fatalf("%s: a cookie the jar did not seal was shown", name) |
| 127 | } |
| 128 | if _, cleared := jarSet(r); !cleared { |
| 129 | t.Fatalf("%s: an unbelievable cookie was not cleared", name) |
| 130 | } |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | // Every state of the door, drawn by rastrillo's partial: what the one |
| 135 | // option is, what Other ways lists, and that the address appears only |
| 136 | // where a sealed cookie put it. |
| 137 | func TestDoorStates(t *testing.T) { |
| 138 | app := newTestApp(t) |
| 139 | const addr = "remembered@example.invalid" |
| 140 | link := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: addr}) |
| 141 | keymail := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodKeymail, Address: addr}) |
| 142 | passkey := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodPasskey, Address: addr}) |
| 143 | bare := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodPasskey}) |
| 144 | const rt = "return_to=%2Fauthorize%2Fresume" |
| 145 | field := `<input rst-input type="email" id="rst-signin-email" name="address"` |
| 146 | conditional := `data-rst-passkey-conditional data-rst-passkey-begin="/passkey/direct/begin" data-rst-passkey-finish="/passkey/direct/finish?return_to=%2Fauthorize%2Fresume" data-rst-passkey-module="/static/webauthn.mjs"` |
| 147 | passkeyDoor := `<button rst-btn="primary block" type="button" disabled data-rst-passkey data-rst-passkey-begin="/passkey/direct/begin"` |
| 148 | cases := []struct { |
| 149 | name string |
| 150 | path string |
| 151 | cookie *http.Cookie |
| 152 | want []string |
| 153 | notWant []string |
| 154 | }{ |
| 155 | {"first visit: the field, passkeys in its autofill", "/signin?" + rt, nil, |
| 156 | []string{field, `autocomplete="username webauthn"`, conditional, `<script type="module" src="/static/signin.mjs"></script>`, `<button rst-btn="primary block" type="submit">Continue</button>`, |
| 157 | `href="/signin?return_to=%2Fauthorize%2Fresume&way=email&ways=1"><span>Other ways to sign in</span>`}, |
| 158 | []string{"Continue as", "data-rst-passkey-fallback", "@example.invalid"}}, |
| 159 | {"first visit's chooser: a passkey, and Back", "/signin?ways=1&way=email&" + rt, nil, |
| 160 | []string{"<h1 id=\"rst-signin-heading\">Other ways to sign in</h1>", `href="/signin?return_to=%2Fauthorize%2Fresume&way=passkey"`, "<span>Sign in with a passkey</span>", |
| 161 | `href="/signin?return_to=%2Fauthorize%2Fresume&way=email"><svg`, "<span>Back</span>"}, |
| 162 | []string{"Use a different email", field}}, |
| 163 | {"passkey remembered: the passkey, drawn visible and disabled", "/signin?" + rt, passkey, |
| 164 | []string{passkeyDoor, "<span>Sign in with your passkey</span>", `data-rst-passkey-fallback="/signin?return_to=%2Fauthorize%2Fresume&way=email"`, |
| 165 | "<noscript><p>To use a passkey, turn on JavaScript.</p></noscript>", `href="/signin?return_to=%2Fauthorize%2Fresume&way=passkey&ways=1"`}, |
| 166 | []string{field, addr, " hidden data-rst-passkey"}}, |
| 167 | {"passkey remembered, chooser: Email with the kept address, Use a different email", "/signin?ways=1&way=passkey&" + rt, passkey, |
| 168 | []string{"<span>Email <bdi>" + addr + "</bdi></span>", `action="/signin/forget"><input type="hidden" name="return_to" value="/authorize/resume">`, "<span>Use a different email</span>", "<span>Back</span>"}, |
| 169 | []string{"Sign in with a passkey"}}, |
| 170 | {"passkey remembered without an address", "/signin?ways=1&way=passkey", bare, |
| 171 | []string{"<span>Email</span>", "<span>Use a different email</span>"}, |
| 172 | []string{"<bdi>"}}, |
| 173 | {"link remembered: Continue as", "/signin?" + rt, link, |
| 174 | []string{"Continue as <bdi>" + addr + "</bdi>", `<input type="hidden" name="address" value="` + addr + `">`, "<span>Other ways to sign in</span>"}, |
| 175 | []string{field, passkeyDoor}}, |
| 176 | {"link remembered, chooser: a passkey and Use a different email", "/signin?ways=1&way=email&" + rt, link, |
| 177 | []string{"<span>Sign in with a passkey</span>", "<span>Use a different email</span>"}, |
| 178 | []string{"Continue as"}}, |
| 179 | {"keymail remembered: Continue to Keymail, as the address", "/signin", keymail, |
| 180 | []string{">Continue to Keymail</button>", "as <bdi>" + addr + "</bdi>", `name="expect" value="keymail"`}, |
| 181 | []string{field}}, |
| 182 | {"way=email on a remembered passkey: the address's one-tap", "/signin?way=email", passkey, |
| 183 | []string{"Continue as <bdi>" + addr + "</bdi>"}, []string{passkeyDoor}}, |
| 184 | {"way=passkey on a remembered link: the passkey door", "/signin?way=passkey", link, |
| 185 | []string{passkeyDoor, "<span>Sign in with a passkey</span>"}, []string{"Continue as"}}, |
| 186 | {"a way picks a method, never an address", "/signin?way=email&address=typed%40example.invalid", nil, |
| 187 | []string{field}, []string{"typed@example.invalid"}}, |
| 188 | {"force=1 (a failed Keymail): the field, force kept, prefilled from the cookie", "/signin?force=1", keymail, |
| 189 | []string{`action="/signin?force=1"`, `<input type="hidden" name="force" value="1">`, `value="` + addr + `"`, field}, |
| 190 | []string{"Continue to Keymail"}}, |
| 191 | {"err=keymail: the field and the problem", "/signin?err=keymail", link, |
| 192 | []string{"Keymail couldn't confirm it's you.", field, ">Send me a link instead</button>"}, []string{"Continue as"}}, |
| 193 | {"err=rate", "/signin?err=rate", nil, []string{"Too many tries. Try again in a few minutes.", field}, nil}, |
| 194 | {"err=expired", "/signin?err=expired", nil, []string{"That link has expired or was already used. Send a new one.", field}, nil}, |
| 195 | {"err=address", "/signin?err=address", nil, []string{"That doesn't look like an email address.", field}, nil}, |
| 196 | {"an unknown err is the generic problem", "/signin?err=whatever&ways=1", passkey, |
| 197 | []string{"Something went wrong. Try again.", field}, []string{"Other ways to sign in</h1>", passkeyDoor}}, |
| 198 | {"reauth=1: a step-up keeps the ways and says why", "/signin?reauth=1", passkey, |
| 199 | []string{"Sign in again to continue.", passkeyDoor, "reauth=1"}, nil}, |
| 200 | } |
| 201 | for _, c := range cases { |
| 202 | t.Run(c.name, func(t *testing.T) { |
| 203 | var cookies []*http.Cookie |
| 204 | if c.cookie != nil { |
| 205 | cookies = append(cookies, c.cookie) |
| 206 | } |
| 207 | r := doorGet(t, app, c.path, cookies...) |
| 208 | if r.Code != 200 { |
| 209 | t.Fatal(r.Code) |
| 210 | } |
| 211 | body := r.Body.String() |
| 212 | for _, w := range c.want { |
| 213 | if !strings.Contains(body, w) { |
| 214 | t.Errorf("missing %q", w) |
| 215 | } |
| 216 | } |
| 217 | for _, n := range c.notWant { |
| 218 | if strings.Contains(body, n) { |
| 219 | t.Errorf("unexpected %q", n) |
| 220 | } |
| 221 | } |
| 222 | if strings.Contains(body, `data-rst-passkey-legacy-rpid`) { |
| 223 | t.Error("a legacy RP ID on the door") |
| 224 | } |
| 225 | if t.Failed() { |
| 226 | t.Log(body) |
| 227 | } |
| 228 | }) |
| 229 | } |
| 230 | } |
| 231 | |
| 232 | // A fresh step-up (max_age) asks again on the same door: the reauth notice |
| 233 | // over the way this browser used last, every way still offered (each of |
| 234 | // id.*'s ways is local), and reauth carried on every link. |
| 235 | func TestDoorStepUpOffersLocalWays(t *testing.T) { |
| 236 | p := newExchangePair(t) |
| 237 | intent, navigation := freshSignInForm(t, p, nil) |
| 238 | remembered := sealedRecord(t, p.credential.App, lastsignin.Record{Method: lastsignin.MethodPasskey}) |
| 239 | r := exchangeRequest(p.credential.App, "GET", Origin+"/signin?return_to=%2Fauthorize%2Fresume", "", nil, intent, navigation, remembered) |
| 240 | body := r.Body.String() |
| 241 | for _, want := range []string{"Sign in again to continue.", "<span>Sign in with your passkey</span>", "way=passkey&ways=1"} { |
| 242 | if !strings.Contains(body, want) { |
| 243 | t.Errorf("step-up door missing %q", want) |
| 244 | } |
| 245 | } |
| 246 | chooser := exchangeRequest(p.credential.App, "GET", Origin+"/signin?return_to=%2Fauthorize%2Fresume&ways=1&way=passkey", "", nil, intent, navigation, remembered).Body.String() |
| 247 | if !strings.Contains(chooser, "reauth=1") || !strings.Contains(chooser, `name="reauth" value="1"`) { |
| 248 | t.Error("the chooser dropped the step-up") |
| 249 | } |
| 250 | if r.Header().Get("Cache-Control") != "no-store" { |
| 251 | t.Error("cacheable step-up door") |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | // A failed Begin redraws the field door with the problem and the right |
| 256 | // status, prefilled from the cookie and never from what was posted. |
| 257 | func TestDoorBeginFailures(t *testing.T) { |
| 258 | app := newTestApp(t) |
| 259 | keymail := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodKeymail, Address: "kept@example.invalid"}) |
| 260 | bad := returnRequest(app, "POST", "/signin", url.Values{"address": {"typed-not-an-address"}}, keymail) |
| 261 | body := bad.Body.String() |
| 262 | if bad.Code != 400 || bad.Header().Get("Cache-Control") != "no-store" || |
| 263 | !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") { |
| 264 | t.Fatalf("bad address: %d\n%s", bad.Code, body) |
| 265 | } |
| 266 | forced := returnRequest(app, "POST", "/signin?force=1", url.Values{"address": {"nope"}}) |
| 267 | if !strings.Contains(forced.Body.String(), `action="/signin?force=1"`) { |
| 268 | t.Fatal("a forced retry's error dropped force") |
| 269 | } |
| 270 | limited := app |
| 271 | var last *httptest.ResponseRecorder |
| 272 | for i := 0; i < 30; i++ { |
| 273 | last = returnRequest(limited, "POST", "/signin", url.Values{"address": {"many@example.invalid"}}) |
| 274 | if last.Code == http.StatusTooManyRequests { |
| 275 | break |
| 276 | } |
| 277 | } |
| 278 | 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" { |
| 279 | t.Fatal("rate limit", last.Code) |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | // Sent stays address-free (Home's is by design), even with a remembered |
| 284 | // address, and keeps "Use a different email". |
| 285 | func TestDoorSentIsAddressFree(t *testing.T) { |
| 286 | app := newTestApp(t) |
| 287 | link := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "kept@example.invalid"}) |
| 288 | r := doorGet(t, app, "/signin/sent?attempt=x&ways=1", link) |
| 289 | body := r.Body.String() |
| 290 | if !strings.Contains(body, "We sent a link to your inbox.") || strings.Contains(body, "kept@example.invalid") || !strings.Contains(body, "<span>Use a different email</span>") { |
| 291 | t.Fatal(body) |
| 292 | } |
| 293 | } |
| 294 | |
| 295 | // What the door remembers, and when: a proven link, a Keymail callback, |
| 296 | // and a passkey (direct, and a finished gate), with the address kept on a |
| 297 | // passkey record only for the same person. |
| 298 | func TestDoorRemembersProvenSignIns(t *testing.T) { |
| 299 | t.Run("magic link", func(t *testing.T) { |
| 300 | app := newTestApp(t) |
| 301 | signIn(t, app, "linked@example.invalid") |
| 302 | if c, _ := jarSet(redeem(t, app, "nope")); c != nil { |
| 303 | t.Fatal("a failed redemption remembered something") |
| 304 | } |
| 305 | r := redeem(t, app, capturedLink(t, app)) |
| 306 | c, _ := jarSet(r) |
| 307 | if c == nil { |
| 308 | t.Fatal("a proven link remembered nothing") |
| 309 | } |
| 310 | if got := readJar(t, app.App, c); got.Method != lastsignin.MethodMagicLink || got.Address != "linked@example.invalid" { |
| 311 | t.Fatalf("remembered %+v", got) |
| 312 | } |
| 313 | if c, _ := jarSet(signIn(t, app, "unproven@example.invalid")); c != nil { |
| 314 | t.Fatal("Begin remembered an address nobody has proved") |
| 315 | } |
| 316 | }) |
| 317 | t.Run("keymail", func(t *testing.T) { |
| 318 | app := newTestApp(t) |
| 319 | const addr = "person@keymail.invalid" |
| 320 | newKeymailStub(t, app, addr) |
| 321 | pending, state := beginKeymail(t, app, addr) |
| 322 | c, _ := jarSet(callback(t, app, "code-1", state, pending)) |
| 323 | if c == nil { |
| 324 | t.Fatal("a Keymail callback remembered nothing") |
| 325 | } |
| 326 | if got := readJar(t, app.App, c); got.Method != lastsignin.MethodKeymail || got.Address != addr { |
| 327 | t.Fatalf("remembered %+v", got) |
| 328 | } |
| 329 | if c, _ := jarSet(callback(t, app, "code-2", "bad-state", pending)); c != nil { |
| 330 | t.Fatal("a failed callback remembered something") |
| 331 | } |
| 332 | }) |
| 333 | for _, kind := range []string{"same person", "another person", "nothing remembered", "unbelievable"} { |
| 334 | t.Run("direct passkey, "+kind, func(t *testing.T) { |
| 335 | app := newTestApp(t) |
| 336 | owner := "owner@example.invalid" |
| 337 | key := enrol(t, app, signInFully(t, app, owner)) |
| 338 | signInFully(t, app, "someone-else@example.invalid") |
| 339 | var prior *http.Cookie |
| 340 | want := "" |
| 341 | switch kind { |
| 342 | case "same person": |
| 343 | prior = sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "OWNER@example.invalid"}) |
| 344 | want = "OWNER@example.invalid" |
| 345 | case "another person": |
| 346 | prior = sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "someone-else@example.invalid"}) |
| 347 | case "unbelievable": |
| 348 | prior = &http.Cookie{Name: jarCookie, Value: "junk"} |
| 349 | } |
| 350 | done := directPasskey(t, app, key, prior) |
| 351 | c, _ := jarSet(done) |
| 352 | if c == nil { |
| 353 | t.Fatal("a passkey sign-in remembered nothing") |
| 354 | } |
| 355 | if got := readJar(t, app.App, c); got.Method != lastsignin.MethodPasskey || got.Address != want { |
| 356 | t.Fatalf("remembered %+v, want passkey with %q", got, want) |
| 357 | } |
| 358 | }) |
| 359 | } |
| 360 | t.Run("a record the jar refuses clears the old one", func(t *testing.T) { |
| 361 | app := newTestApp(t) |
| 362 | prior := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "previous@example.invalid"}) |
| 363 | long := strings.Repeat("a", 250) + "@example.invalid" // over lastsignin's 254 bytes |
| 364 | w := httptest.NewRecorder() |
| 365 | req := httptest.NewRequest("GET", Origin+"/signin/verify", nil) |
| 366 | req.AddCookie(prior) |
| 367 | app.rememberEmail(w, signin.Identity{Method: signin.MethodMagicLink, Address: long}) |
| 368 | set, cleared := jarSet(w) |
| 369 | if set != nil || !cleared || w.Header().Get("Cache-Control") != "no-store" { |
| 370 | t.Fatal("a refused record left the previous person's record in place", set, cleared) |
| 371 | } |
| 372 | }) |
| 373 | t.Run("a refused passkey remembers nothing", func(t *testing.T) { |
| 374 | app := newTestApp(t) |
| 375 | enrol(t, app, signInFully(t, app, "owner@example.invalid")) |
| 376 | stranger, _ := authtest.New() |
| 377 | if c, _ := jarSet(directPasskey(t, app, stranger, nil)); c != nil { |
| 378 | t.Fatal("a refused finish remembered a passkey") |
| 379 | } |
| 380 | }) |
| 381 | t.Run("gate", func(t *testing.T) { |
| 382 | app := newTestApp(t) |
| 383 | const addr = "gated@example.invalid" |
| 384 | key := enrol(t, app, signInFully(t, app, addr)) |
| 385 | signIn(t, app, addr) |
| 386 | first := redeem(t, app, capturedLink(t, app)) |
| 387 | emailed, _ := jarSet(first) |
| 388 | if first.Header().Get("Location") != confirmPath || emailed == nil || readJar(t, app.App, emailed).Address != addr { |
| 389 | t.Fatal("the first factor was not remembered before the gate", first.Header().Get("Location")) |
| 390 | } |
| 391 | gate := namedCookie(t, first, gateCookie) |
| 392 | begin := idJSON(t, app, "/passkey/signin/begin", nil, gate) |
| 393 | zero := uint32(0) |
| 394 | done := idJSON(t, app, "/passkey/signin/finish", assertionBody(key, challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin, Count: &zero}), gate, emailed) |
| 395 | c, _ := jarSet(done) |
| 396 | if done.Code != 200 || c == nil { |
| 397 | t.Fatal("a finished gate remembered nothing", done.Code) |
| 398 | } |
| 399 | if got := readJar(t, app.App, c); got.Method != lastsignin.MethodPasskey || got.Address != addr { |
| 400 | t.Fatalf("remembered %+v", got) |
| 401 | } |
| 402 | if body := doorGet(t, app, "/signin", c).Body.String(); !strings.Contains(body, "<span>Sign in with your passkey</span>") { |
| 403 | t.Fatal("the next visit does not offer the passkey") |
| 404 | } |
| 405 | }) |
| 406 | } |
| 407 | |
| 408 | // directPasskey runs one discoverable sign-in with key, presenting prior |
| 409 | // (a jar cookie) on the finish. |
| 410 | func directPasskey(t *testing.T, app *testApp, key *authtest.Authenticator, prior *http.Cookie) *httptest.ResponseRecorder { |
| 411 | t.Helper() |
| 412 | begin := idJSON(t, app, directBegin, nil) |
| 413 | zero := uint32(0) |
| 414 | body := assertionBody(key, challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin, Count: &zero}) |
| 415 | return idJSON(t, app, directFinish, body, namedCookie(t, begin, ceremonyCookie), prior) |
| 416 | } |
| 417 | |
| 418 | // The passkey finish answers rastrillo's shape, which the door's module |
| 419 | // reads: {"ok":true,"to":<a local path>} on success, a non-2xx on refusal |
| 420 | // (so the conditional request re-begins once). |
| 421 | func TestDoorPasskeyFinishAnswersRastrillosShape(t *testing.T) { |
| 422 | app := newTestApp(t) |
| 423 | key := enrol(t, app, signInFully(t, app, "shape@example.invalid")) |
| 424 | 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 { |
| 425 | t.Fatal(err) |
| 426 | } |
| 427 | done := directPasskey(t, app, key, nil) |
| 428 | if done.Code != 200 || strings.TrimSpace(done.Body.String()) != `{"ok":true,"to":"/"}` || done.Header().Get("Cache-Control") != "no-store" { |
| 429 | t.Fatal(done.Code, done.Body.String()) |
| 430 | } |
| 431 | stranger, _ := authtest.New() |
| 432 | if refused := directPasskey(t, app, stranger, nil); refused.Code/100 == 2 { |
| 433 | t.Fatal("a refused finish answered 2xx", refused.Code) |
| 434 | } |
| 435 | } |
| 436 | |
| 437 | // The direct finish takes the door's return_to from its own URL (the |
| 438 | // module puts the page's return_to there), so a late autofill pick, with |
| 439 | // the ten-minute return cookie gone or replaced by another tab, still |
| 440 | // lands in the app's handoff. A hostile one is no destination, and it |
| 441 | // beats the cookie only when it names one. |
| 442 | func TestDoorDirectFinishKeepsTheDoorsReturn(t *testing.T) { |
| 443 | app := newTestApp(t) |
| 444 | key := enrol(t, app, signInFully(t, app, "late@example.invalid")) |
| 445 | 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 { |
| 446 | t.Fatal(err) |
| 447 | } |
| 448 | finish := func(query string, cookies ...*http.Cookie) string { |
| 449 | t.Helper() |
| 450 | begin := idJSON(t, app, directBegin, nil) |
| 451 | zero := uint32(0) |
| 452 | body := assertionBody(key, challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin, Count: &zero}) |
| 453 | done := idJSON(t, app, directFinish+query, body, append(cookies, namedCookie(t, begin, ceremonyCookie))...) |
| 454 | if done.Code != 200 { |
| 455 | t.Fatal("finish", done.Code) |
| 456 | } |
| 457 | return strings.TrimSpace(done.Body.String()) |
| 458 | } |
| 459 | if got := finish("?return_to=%2Fauthorize%2Fresume"); got != `{"ok":true,"to":"/authorize/resume"}` { |
| 460 | t.Fatal("no cookie: lost the door's return", got) |
| 461 | } |
| 462 | other := &http.Cookie{Name: returnCookie, Value: "/passkey/codes"} |
| 463 | if got := finish("?return_to=%2Fauthorize%2Fresume", other); got != `{"ok":true,"to":"/authorize/resume"}` { |
| 464 | t.Fatal("another tab's cookie won over the door's return", got) |
| 465 | } |
| 466 | if got := finish("?return_to=https%3A%2F%2Fevil.invalid%2F", other); got != `{"ok":true,"to":"/passkey/codes"}` { |
| 467 | t.Fatal("a hostile return_to displaced the cookie", got) |
| 468 | } |
| 469 | if got := finish("?return_to=https%3A%2F%2Fevil.invalid%2F"); got != `{"ok":true,"to":"/"}` { |
| 470 | t.Fatal("a hostile return_to was followed", got) |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | // The directory never holds the door's memory: it never serves the door. |
| 475 | func TestDirectoryHasNoDoorMemory(t *testing.T) { |
| 476 | p := newExchangePair(t) |
| 477 | if p.directory.door != nil { |
| 478 | t.Fatal("the directory built a jar") |
| 479 | } |
| 480 | if p.credential.door == nil { |
| 481 | t.Fatal("the credential origin has no jar") |
| 482 | } |
| 483 | } |
| 484 | |
| 485 | // Forget: "Use a different email" forgets this browser's record, opens the |
| 486 | // email field and keeps where the sign-in was going; it needs origin |
| 487 | // evidence, as every form here does. |
| 488 | func TestDoorForget(t *testing.T) { |
| 489 | app := newTestApp(t) |
| 490 | link := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "kept@example.invalid"}) |
| 491 | r := returnRequest(app, "POST", forgetPath, url.Values{"return_to": {"/authorize/resume"}, "way": {"email"}}, link) |
| 492 | 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" { |
| 493 | t.Fatal(r.Code, r.Header()) |
| 494 | } |
| 495 | // No posted return_to: the return cookie's, and a step-up kept. |
| 496 | keep := &http.Cookie{Name: returnCookie, Value: "/passkey/codes"} |
| 497 | r = returnRequest(app, "POST", forgetPath, url.Values{"way": {"email"}, "reauth": {"1"}}, link, keep) |
| 498 | if r.Header().Get("Location") != "/signin?reauth=1&return_to=%2Fpasskey%2Fcodes&way=email" { |
| 499 | t.Fatal(r.Header().Get("Location")) |
| 500 | } |
| 501 | // A hostile return_to is no destination. |
| 502 | r = returnRequest(app, "POST", forgetPath, url.Values{"return_to": {"https://evil.invalid/"}}, link) |
| 503 | if r.Header().Get("Location") != "/signin" { |
| 504 | t.Fatal(r.Header().Get("Location")) |
| 505 | } |
| 506 | req := httptest.NewRequest("POST", forgetPath, strings.NewReader("way=email")) |
| 507 | req.Host = credentialHost |
| 508 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 509 | req.Header.Set("Sec-Fetch-Site", "cross-site") |
| 510 | req.AddCookie(link) |
| 511 | w := httptest.NewRecorder() |
| 512 | app.Router().ServeHTTP(w, req) |
| 513 | if _, cleared := jarSet(w); cleared || w.Code != http.StatusForbidden { |
| 514 | t.Fatal("a cross-site Forget went through", w.Code) |
| 515 | } |
| 516 | // Forget, then the door: nothing remembered, the field. |
| 517 | after := doorGet(t, app, "/signin?way=email") |
| 518 | if strings.Contains(after.Body.String(), "kept@example.invalid") { |
| 519 | t.Fatal("still remembered") |
| 520 | } |
| 521 | } |
| 522 | |
| 523 | // The chained Forget: an app's signed-out page links to /forget?return=…; |
| 524 | // id.* asks once, forgets on a same-origin POST, and returns only to a |
| 525 | // registered consumer's /signed-out, else to its own signed-out page. |
| 526 | func TestDoorForgetChain(t *testing.T) { |
| 527 | p := newExchangePair(t) |
| 528 | app := p.credential |
| 529 | link := sealedRecord(t, app.App, lastsignin.Record{Method: lastsignin.MethodMagicLink, Address: "kept@example.invalid"}) |
| 530 | const back = "https://blue.docs.oficina.works/signed-out" |
| 531 | page := exchangeRequest(app.App, "GET", Origin+forgetChainPath+"?return="+url.QueryEscape(back), "", nil, link) |
| 532 | body := page.Body.String() |
| 533 | for _, want := range []string{`<form method="post" action="/forget"`, `<input type="hidden" name="return" value="` + back + `">`, ">Forget me on Oficina ID too</button>", `<a rst-btn="ghost" estilo-signin-action="quiet" href="` + back + `">Not now</a>`} { |
| 534 | if !strings.Contains(body, want) { |
| 535 | t.Errorf("confirm page missing %q", want) |
| 536 | } |
| 537 | } |
| 538 | if page.Code != 200 || page.Header().Get("Cache-Control") != "no-store" || !strings.Contains(page.Header().Get("Content-Security-Policy"), "https://blue.docs.oficina.works") { |
| 539 | t.Fatal("confirm page", page.Code, page.Header()) |
| 540 | } |
| 541 | if _, cleared := jarSet(page); cleared || strings.Contains(body, "kept@example.invalid") { |
| 542 | t.Fatal("the GET forgot, or showed the address") |
| 543 | } |
| 544 | done := exchangeRequest(app.App, "POST", Origin+forgetChainPath, Origin, url.Values{"return": {back}}, link) |
| 545 | if _, cleared := jarSet(done); !cleared || done.Code != 303 || done.Header().Get("Location") != back { |
| 546 | t.Fatal("forget", done.Code, done.Header()) |
| 547 | } |
| 548 | for _, bad := range []string{ |
| 549 | "", "https://evil.invalid/signed-out", "https://blue.docs.oficina.works/", "https://blue.docs.oficina.works/signed-out?x=1", |
| 550 | "https://blue.docs.oficina.works/signed-out#x", "https://u@blue.docs.oficina.works/signed-out", "http://blue.docs.oficina.works/signed-out", |
| 551 | "https://blue.docs.oficina.works:443/signed-out", "https://blue.docs.oficina.works/signed-out/", "//blue.docs.oficina.works/signed-out", |
| 552 | "https://blue.docs.oficina.works/%73igned-out", "/signed-out", "javascript:alert(1)", |
| 553 | } { |
| 554 | page := exchangeRequest(app.App, "GET", Origin+forgetChainPath+"?return="+url.QueryEscape(bad), "", nil) |
| 555 | if !strings.Contains(page.Body.String(), `<a rst-btn="ghost" estilo-signin-action="quiet" href="/signed-out">Not now</a>`) || strings.Contains(page.Body.String(), `name="return"`) || |
| 556 | strings.Contains(page.Header().Get("Content-Security-Policy"), "blue.docs") { |
| 557 | t.Errorf("GET %q was trusted", bad) |
| 558 | } |
| 559 | post := exchangeRequest(app.App, "POST", Origin+forgetChainPath, Origin, url.Values{"return": {bad}}, link) |
| 560 | if post.Header().Get("Location") != "/signed-out" { |
| 561 | t.Errorf("POST %q went to %q", bad, post.Header().Get("Location")) |
| 562 | } |
| 563 | } |
| 564 | if cross := exchangeRequest(app.App, "POST", Origin+forgetChainPath, "https://blue.docs.oficina.works", url.Values{"return": {back}}, link); cross.Code != http.StatusForbidden { |
| 565 | t.Fatal("a cross-origin chained Forget went through", cross.Code) |
| 566 | } |
| 567 | // The directory is a registered consumer too. |
| 568 | if r := exchangeRequest(app.App, "POST", Origin+forgetChainPath, Origin, url.Values{"return": {directoryOrigin + "/signed-out"}}); r.Header().Get("Location") != directoryOrigin+"/signed-out" { |
| 569 | t.Fatal("the directory's signed-out page refused", r.Header().Get("Location")) |
| 570 | } |
| 571 | // id.*'s own signed-out page offers its own Forget. |
| 572 | own := exchangeRequest(app.App, "GET", Origin+"/signed-out", "", nil).Body.String() |
| 573 | if !strings.Contains(own, `action="/signin/forget"`) || !strings.Contains(own, ">Forget me on this device</button>") { |
| 574 | t.Fatal("id.* signed-out page has no Forget") |
| 575 | } |
| 576 | } |
| 577 | |
| 578 | // The return memory survives the door: an app sends a person to id.*; they |
| 579 | // open Other ways, pick a passkey, sign in with it, and land back in the |
| 580 | // app. Every chooser link and the passkey finish carry return_to, so |
| 581 | // rememberReturn never forgets the handoff on the way. |
| 582 | func TestDoorAppToChooserToPasskeyAndBack(t *testing.T) { |
| 583 | p := newExchangePair(t) |
| 584 | app := p.credential |
| 585 | key := enrol(t, app, signInFully(t, app, sealtest.CanaryAddress)) |
| 586 | 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 { |
| 587 | t.Fatal(err) |
| 588 | } |
| 589 | pending, intent := p.start(t) // the app (here, the directory) asks id.* for an assertion |
| 590 | resume := exchangeRequest(app.App, "GET", Origin+"/authorize/resume", "", nil, intent) |
| 591 | if resume.Code != 303 { |
| 592 | t.Fatal("no sign-in asked for", resume.Code) |
| 593 | } |
| 594 | jar := &cookieJar{} |
| 595 | jar.add(intent) |
| 596 | follow := func(target string) *httptest.ResponseRecorder { |
| 597 | t.Helper() |
| 598 | r := exchangeRequest(app.App, "GET", Origin+target, "", nil, jar.all()...) |
| 599 | jar.take(r) |
| 600 | if r.Code != 200 { |
| 601 | t.Fatal("GET", target, r.Code) |
| 602 | } |
| 603 | return r |
| 604 | } |
| 605 | door := follow(resume.Header().Get("Location")) |
| 606 | ways := follow(hrefOf(t, door.Body.String(), "Other ways to sign in")) |
| 607 | passkeyDoor := follow(hrefOf(t, ways.Body.String(), "Sign in with a passkey")) |
| 608 | if !strings.Contains(passkeyDoor.Body.String(), `data-rst-passkey-finish="/passkey/direct/finish?return_to=%2Fauthorize%2Fresume"`) { |
| 609 | t.Fatal("the passkey door lost the return") |
| 610 | } |
| 611 | begin := exchangeRequest(app.App, "POST", Origin+directBegin, Origin, nil, jar.all()...) |
| 612 | jar.take(begin) |
| 613 | zero := uint32(0) |
| 614 | finish := idJSON(t, app, directFinish+"?return_to=%2Fauthorize%2Fresume", assertionBody(key, challengeFrom(t, begin), authtest.Options{RPID: credentialHost, Origin: Origin, Count: &zero}), jar.all()...) |
| 615 | jar.take(finish) |
| 616 | if finish.Code != 200 || strings.TrimSpace(finish.Body.String()) != `{"ok":true,"to":"/authorize/resume"}` { |
| 617 | t.Fatal("finish", finish.Code, finish.Body.String()) |
| 618 | } |
| 619 | token, _ := p.mint(t, intent, sessionCookie(finish)) |
| 620 | p.finish(t, token, pending) // back in the app, signed in |
| 621 | } |
| 622 | |
| 623 | // hrefOf is the href of the link whose text contains label. |
| 624 | func hrefOf(t *testing.T, body, label string) string { |
| 625 | t.Helper() |
| 626 | i := strings.Index(body, "<span>"+label+"</span>") |
| 627 | if i < 0 { |
| 628 | t.Fatalf("no link %q", label) |
| 629 | } |
| 630 | j := strings.LastIndex(body[:i], `href="`) |
| 631 | if j < 0 { |
| 632 | t.Fatalf("no href before %q", label) |
| 633 | } |
| 634 | rest := body[j+len(`href="`):] |
| 635 | return strings.ReplaceAll(rest[:strings.Index(rest, `"`)], "&", "&") |
| 636 | } |
| 637 | |
| 638 | // cookieJar is a browser's cookies for one origin, enough for a walk. |
| 639 | type cookieJar struct{ m map[string]*http.Cookie } |
| 640 | |
| 641 | func (j *cookieJar) add(c *http.Cookie) { |
| 642 | if j.m == nil { |
| 643 | j.m = map[string]*http.Cookie{} |
| 644 | } |
| 645 | j.m[c.Name] = c |
| 646 | } |
| 647 | |
| 648 | func (j *cookieJar) take(r *httptest.ResponseRecorder) { |
| 649 | for _, c := range r.Result().Cookies() { |
| 650 | if c.MaxAge < 0 || c.Value == "" { |
| 651 | delete(j.m, c.Name) |
| 652 | continue |
| 653 | } |
| 654 | j.add(c) |
| 655 | } |
| 656 | } |
| 657 | |
| 658 | func (j *cookieJar) all() []*http.Cookie { |
| 659 | var out []*http.Cookie |
| 660 | for _, c := range j.m { |
| 661 | out = append(out, &http.Cookie{Name: c.Name, Value: c.Value}) |
| 662 | } |
| 663 | return out |
| 664 | } |
| 665 | |