| 1 | package home |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "net/http" |
| 7 | "regexp" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/home/handoff" |
| 13 | "amadan.net/rastrillo/rastrillo/sessions" |
| 14 | ) |
| 15 | |
| 16 | // Review finding 1: a native directory session reads teams and nothing else. |
| 17 | // Its auth_time is a (possibly code-only) sign-in's, and the directory's |
| 18 | // browser routes trust auth_time for roster and operator freshness. |
| 19 | func TestNativeDirectorySessionIsConfined(t *testing.T) { |
| 20 | t.Parallel() |
| 21 | f := newMountedChooser(t) |
| 22 | cred := f.p.credential |
| 23 | d := newDevice(t) |
| 24 | grant, _ := d.signInByCode(t, cred, "confined@example.invalid") |
| 25 | var person string |
| 26 | cred.db.Writer().QueryRow("SELECT person_ref FROM home_id_grants").Scan(&person) |
| 27 | f.team(t, "AAA111", "blue", "Blue team", person) |
| 28 | if _, err := f.p.directory.db.Writer().Exec("UPDATE memberships SET role='owner' WHERE person_ref=?", person); err != nil { |
| 29 | t.Fatal(err) |
| 30 | } |
| 31 | verifier, challenge := verifierFor(50) |
| 32 | token := decodeReply(t, d.assert(t, cred, grant, directoryOrigin, challenge))["assertion"].(string) |
| 33 | out := decodeReply(t, directoryCall(t, f, "POST", nativeExchangePath, exchangeBody(token, verifier), nil, nil)) |
| 34 | native := &http.Cookie{Name: out["name"].(string), Value: out["value"].(string)} |
| 35 | |
| 36 | if w := directoryCall(t, f, "GET", nativeTeamsPath, "", native, nil); w.Code != 200 { |
| 37 | t.Fatal("the native route refused its own session", w.Code) |
| 38 | } |
| 39 | // Every browser route sees no session: the front page, not the |
| 40 | // directory; no Team page; no account menu. |
| 41 | home := exchangeRequest(f.p.directory, "GET", directoryOrigin+"/", "", nil, native) |
| 42 | browser := exchangeRequest(f.p.directory, "GET", directoryOrigin+"/", "", nil, f.session(t, person)) |
| 43 | if strings.Contains(home.Body.String(), "Sign out all devices") || home.Body.String() == browser.Body.String() { |
| 44 | t.Fatal("a native session opened the directory") |
| 45 | } |
| 46 | if w := exchangeRequest(f.p.directory, "GET", directoryOrigin+teamPath+"?team=AAA111", "", nil, native); w.Code == 200 && strings.Contains(w.Body.String(), "Blue team") { |
| 47 | t.Fatal("a native session opened the Team page") |
| 48 | } |
| 49 | // Fable's re-review F1: a duplicate cookie name hides nothing. The |
| 50 | // session middleware takes the first of two; both are stripped. |
| 51 | junk := &http.Cookie{Name: native.Name, Value: "junk"} |
| 52 | dup := exchangeRequest(f.p.directory, "GET", directoryOrigin+"/", "", nil, native, junk) |
| 53 | if strings.Contains(dup.Body.String(), "Sign out all devices") || dup.Body.String() == browser.Body.String() { |
| 54 | t.Fatal("a duplicated native cookie opened the directory") |
| 55 | } |
| 56 | if w := exchangeRequest(f.p.directory, "POST", directoryOrigin+signoutPath, directoryOrigin, map[string][]string{}, native, junk); w.Code == 303 { |
| 57 | var n int |
| 58 | f.p.directory.db.Writer().QueryRow("SELECT count(*) FROM sessions WHERE method=?", nativeSessionMethod).Scan(&n) |
| 59 | if n == 0 { |
| 60 | t.Fatal("a duplicated native cookie used the browser sign-out") |
| 61 | } |
| 62 | } |
| 63 | // A forged same-origin roster write carries it in vain. |
| 64 | exchangeRequest(f.p.directory, "POST", directoryOrigin+teamNamePath, directoryOrigin, map[string][]string{"team": {"AAA111"}, "name": {"Renamed"}}, native) |
| 65 | if w := directoryCall(t, f, "GET", nativeTeamsPath, "", native, nil); !strings.Contains(w.Body.String(), `"name":"Blue team"`) { |
| 66 | t.Fatal("a native session wrote the roster", w.Body.String()) |
| 67 | } |
| 68 | // And it is never fresh, whatever its auth_time. |
| 69 | s := sessions.Session{Subject: person, Method: nativeSessionMethod, AuthTime: time.Now()} |
| 70 | if teamFresh(s, time.Now()) || directoryFresh(s, time.Now()) { |
| 71 | t.Fatal("a native session counts as fresh") |
| 72 | } |
| 73 | s.Method = "assertion" |
| 74 | if !teamFresh(s, time.Now()) || !directoryFresh(s, time.Now()) { |
| 75 | t.Fatal("control: a fresh browser session") |
| 76 | } |
| 77 | // Its own sign-out still works. |
| 78 | if w := directoryCall(t, f, "POST", nativeDirectorySignout, "{}", native, nil); w.Code != 200 { |
| 79 | t.Fatal(w.Code) |
| 80 | } |
| 81 | if w := directoryCall(t, f, "GET", nativeTeamsPath, "", native, nil); w.Code != 401 { |
| 82 | t.Fatal("signed-out native session", w.Code) |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | // Review finding 2: any live grant makes a key returning; otherwise the most |
| 87 | // recently ENDED grant decides, not the most recently created one. |
| 88 | func TestNativeReturningKeyRule(t *testing.T) { |
| 89 | t.Parallel() |
| 90 | app := newNativeApp(t) |
| 91 | insert := func(hash string, created int64, ended any, reason any) { |
| 92 | t.Helper() |
| 93 | if _, err := app.db.Writer().Exec("INSERT INTO home_id_grants(grant_hash,person_ref,identity_id,device_key,platform,method,auth_time,created_at,last_used_day,expires_at,ended_at,end_reason) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)", |
| 94 | hash, "pr_person", "i", "key", "macos", "email", 1, created, dayOf(time.Now().Unix()), time.Now().Unix()+day, ended, reason); err != nil { |
| 95 | t.Fatal(err) |
| 96 | } |
| 97 | } |
| 98 | check := func(want bool) { |
| 99 | t.Helper() |
| 100 | tx, err := app.db.Writer().Begin() |
| 101 | if err != nil { |
| 102 | t.Fatal(err) |
| 103 | } |
| 104 | defer tx.Rollback() |
| 105 | got, err := returningKey(tx, "pr_person", "key") |
| 106 | if err != nil || got != want { |
| 107 | t.Fatal("returning", got, want, err) |
| 108 | } |
| 109 | } |
| 110 | // An older grant still live; a newer one cut off by sign-out-all. |
| 111 | insert("a", 100, nil, nil) |
| 112 | insert("b", 200, 300, "all_devices") |
| 113 | check(true) |
| 114 | // Nothing live: the newer-created grant ended by expiry first, the older |
| 115 | // one was cut off later. The cut-off is the last word. |
| 116 | if _, err := app.db.Writer().Exec("DELETE FROM home_id_grants"); err != nil { |
| 117 | t.Fatal(err) |
| 118 | } |
| 119 | insert("c", 100, 500, "revoke") |
| 120 | insert("d", 200, 300, "expiry") |
| 121 | check(false) |
| 122 | // And the other way round. |
| 123 | if _, err := app.db.Writer().Exec("DELETE FROM home_id_grants"); err != nil { |
| 124 | t.Fatal(err) |
| 125 | } |
| 126 | insert("e", 100, 300, "replacement") |
| 127 | insert("f", 200, 500, "lru") |
| 128 | check(true) |
| 129 | // Each end_reason on its own. |
| 130 | for reason, want := range map[string]bool{"expiry": true, "lru": true, "enrolment": true, "signout": false, "all_devices": false, "revoke": false, "replacement": false} { |
| 131 | if _, err := app.db.Writer().Exec("DELETE FROM home_id_grants"); err != nil { |
| 132 | t.Fatal(err) |
| 133 | } |
| 134 | insert("g", 100, 300, reason) |
| 135 | check(want) |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | // Review finding 3: expired sealed addresses are swept at boot and by |
| 140 | // verify and resend, not only by the next start. |
| 141 | func TestNativeExpiredStartsSwept(t *testing.T) { |
| 142 | t.Parallel() |
| 143 | app := newNativeApp(t) |
| 144 | d := newDevice(t) |
| 145 | d.start(t, app, "swept@example.invalid") |
| 146 | if _, err := app.db.Writer().Exec("UPDATE home_id_native_starts SET expires_at=1"); err != nil { |
| 147 | t.Fatal(err) |
| 148 | } |
| 149 | app.restart(t) |
| 150 | if n := count(t, app, "SELECT count(*) FROM home_id_native_starts"); n != 0 { |
| 151 | t.Fatal("boot left an expired sealed address", n) |
| 152 | } |
| 153 | start := d.start(t, app, "swept2@example.invalid") |
| 154 | e := newDevice(t) |
| 155 | e.start(t, app, "swept3@example.invalid") |
| 156 | if _, err := app.db.Writer().Exec("UPDATE home_id_native_starts SET expires_at=1 WHERE device_key=?", e.public()); err != nil { |
| 157 | t.Fatal(err) |
| 158 | } |
| 159 | d.verify(t, app, start, "000000") |
| 160 | if n := count(t, app, "SELECT count(*) FROM home_id_native_starts WHERE device_key=?", e.public()); n != 0 { |
| 161 | t.Fatal("verify left an expired sealed address", n) |
| 162 | } |
| 163 | if err := app.sweepNativeAtBoot(context.Background()); err != nil { |
| 164 | t.Fatal(err) |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | // Review finding 4: rotating addresses inside one network buys nothing, and |
| 169 | // a device key holds one live native challenge. |
| 170 | func TestNativeNetworkBucketsAndBeginDedupe(t *testing.T) { |
| 171 | t.Parallel() |
| 172 | a := httpRequestFrom("[2001:db8:7:1::1]:1") |
| 173 | b := httpRequestFrom("[2001:db8:7:ffff::9]:1") |
| 174 | c := httpRequestFrom("[2001:db8:8::1]:1") |
| 175 | if nativeNetBucket(a) != nativeNetBucket(b) || nativeNetBucket(a) == nativeNetBucket(c) || nativeNetBucket(httpRequestFrom("192.0.2.77:1")) != "192.0.2.0/24" { |
| 176 | t.Fatal("network buckets", nativeNetBucket(a), nativeNetBucket(b), nativeNetBucket(c)) |
| 177 | } |
| 178 | if startsPerNetDay.limit != 1000 || passkeyBeginsPerIP.limit != 60 { |
| 179 | t.Fatal("limits moved") |
| 180 | } |
| 181 | app := newNativeApp(t) |
| 182 | d := newDevice(t) |
| 183 | for range 3 { |
| 184 | if w := d.call(t, app, nativePrefix+"/passkey/begin", map[string]string{"device_key": d.public(), "platform": "ios"}, ""); w.Code != 200 { |
| 185 | t.Fatal(w.Code) |
| 186 | } |
| 187 | } |
| 188 | if n := count(t, app, "SELECT count(*) FROM home_id_ceremonies WHERE purpose='native'"); n != 1 { |
| 189 | t.Fatal("one key holds several challenges", n) |
| 190 | } |
| 191 | if n := count(t, app, "SELECT count(*) FROM home_id_native_ceremonies"); n != 1 { |
| 192 | t.Fatal("native ceremony rows", n) |
| 193 | } |
| 194 | // Native challenges may hold half the shared table, never the web's half. |
| 195 | tx, err := app.db.Writer().Begin() |
| 196 | if err != nil { |
| 197 | t.Fatal(err) |
| 198 | } |
| 199 | for i := range nativeCeremonyShare { |
| 200 | if _, err := tx.Exec("INSERT INTO home_id_ceremonies VALUES(?,?,?,?,?)", fmt.Sprint("fill", i), "b", "", nativeCeremonyPurpose, time.Now().Unix()+300); err != nil { |
| 201 | t.Fatal(err) |
| 202 | } |
| 203 | } |
| 204 | if err := tx.Commit(); err != nil { |
| 205 | t.Fatal(err) |
| 206 | } |
| 207 | e := newDevice(t) |
| 208 | if w := e.call(t, app, nativePrefix+"/passkey/begin", map[string]string{"device_key": e.public(), "platform": "ios"}, "", proofOpts{ip: "198.51.100.9:1"}); w.Code != 503 { |
| 209 | t.Fatal("native took more than its share", w.Code) |
| 210 | } |
| 211 | if w := postJSON(t, app, "/passkey/register/begin", signInFully(t, app, "web-share@example.invalid"), nil); w.Code != 200 { |
| 212 | t.Fatal("the web's passkey ceremonies were locked out", w.Code) |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | // Fable's re-review F2: an assertion minted before "Sign out all devices" |
| 217 | // (up to 120 s earlier, by /authorize or native assert) buys no directory |
| 218 | // session afterwards; one minted after does. |
| 219 | func TestNativeSignOutAllRefusesEarlierAssertions(t *testing.T) { |
| 220 | t.Parallel() |
| 221 | f := newMountedChooser(t) |
| 222 | cred := f.p.credential |
| 223 | session := signInFully(t, cred, "early@example.invalid") |
| 224 | person := subjectOf(t, cred, session) |
| 225 | // Minted before the press: a browser handoff and a native assertion. |
| 226 | pending, intent := f.p.start(t) |
| 227 | browserToken, _ := f.p.mint(t, intent, session) |
| 228 | d := newDevice(t) |
| 229 | grant, _ := d.signInByCode(t, cred.restart(t), "early@example.invalid") |
| 230 | verifier, challenge := verifierFor(60) |
| 231 | nativeToken := decodeReply(t, d.assert(t, cred, grant, directoryOrigin, challenge))["assertion"].(string) |
| 232 | |
| 233 | // The press, one second later so the marks are strictly after. |
| 234 | time.Sleep(1100 * time.Millisecond) |
| 235 | press := exchangeRequest(cred.App, "POST", Origin+signoutAllPath, Origin, map[string][]string{}, session) |
| 236 | hop := regexp.MustCompile(`name="assertion" value="([^"]+)"`).FindStringSubmatch(press.Body.String()) |
| 237 | if press.Code != 200 || hop == nil || !strings.Contains(press.Body.String(), "Finishing signing out of oficina.works") { |
| 238 | t.Fatal("press", press.Code) |
| 239 | } |
| 240 | if w := exchangeRequest(f.p.directory, "POST", directoryOrigin+signedOutAllPath, Origin, map[string][]string{"assertion": {hop[1]}}); w.Code != 303 { |
| 241 | t.Fatal("hop", w.Code) |
| 242 | } |
| 243 | var n int |
| 244 | cred.db.Writer().QueryRow("SELECT count(*) FROM home_id_signed_out_all WHERE person_ref=?", person).Scan(&n) |
| 245 | if n != 1 { |
| 246 | t.Fatal("no mark on id.*") |
| 247 | } |
| 248 | // The earlier browser assertion cannot finish a sign-in. |
| 249 | callback := exchangeRequest(f.p.directory, "POST", directoryOrigin+handoff.CallbackPath, Origin, map[string][]string{"assertion": {browserToken}}) |
| 250 | if inbox := namedCookieOrNil(callback, "__Host-oficina-assertion-inbox"); inbox != nil { |
| 251 | if fin := exchangeRequest(f.p.directory, "GET", directoryOrigin+handoff.FinishPath, "", nil, pending, inbox); sessionCookie(fin) != nil { |
| 252 | t.Fatal("an assertion from before the press signed the directory in") |
| 253 | } |
| 254 | } |
| 255 | // Nor the earlier native one. |
| 256 | if w := directoryCall(t, f, "POST", nativeExchangePath, exchangeBody(nativeToken, verifier), nil, nil); w.Code != 401 { |
| 257 | t.Fatal("a native assertion from before the press exchanged", w.Code) |
| 258 | } |
| 259 | // After the press, signing in works again. |
| 260 | time.Sleep(1100 * time.Millisecond) |
| 261 | again := signInFully(t, cred.restart(t), "early@example.invalid") |
| 262 | pending, intent = f.p.start(t) |
| 263 | token, _ := f.p.mint(t, intent, again) |
| 264 | f.p.finish(t, token, pending) |
| 265 | } |
| 266 | |
| 267 | // F4 and F5: a refused receipt lands on the failure page, which says what |
| 268 | // did and did not sign out; and a browser holding someone else's directory |
| 269 | // session keeps it. |
| 270 | func TestNativeSignOutAllHopFailureAndOtherCookie(t *testing.T) { |
| 271 | t.Parallel() |
| 272 | f := newMountedChooser(t) |
| 273 | w := exchangeRequest(f.p.directory, "POST", directoryOrigin+signedOutAllPath, Origin, map[string][]string{"assertion": {"nonsense"}}) |
| 274 | if w.Code != 403 || !strings.Contains(w.Body.String(), "id.oficina.works is signed out") || !strings.Contains(w.Body.String(), Origin+signoutAllPath) { |
| 275 | t.Fatal("failure page", w.Code) |
| 276 | } |
| 277 | cred := f.p.credential |
| 278 | session := signInFully(t, cred, "owner@example.invalid") |
| 279 | press := exchangeRequest(cred.App, "POST", Origin+signoutAllPath, Origin, map[string][]string{}, session) |
| 280 | hop := regexp.MustCompile(`name="assertion" value="([^"]+)"`).FindStringSubmatch(press.Body.String()) |
| 281 | someoneElse := f.session(t, chooserOther) |
| 282 | done := exchangeRequest(f.p.directory, "POST", directoryOrigin+signedOutAllPath, Origin, map[string][]string{"assertion": {hop[1]}}, someoneElse) |
| 283 | if done.Code != 303 { |
| 284 | t.Fatal("hop", done.Code) |
| 285 | } |
| 286 | if c := namedCookieOrNil(done, f.p.directory.sessions.CookieName()); c != nil { |
| 287 | t.Fatal("cleared another person's directory cookie") |
| 288 | } |
| 289 | var n int |
| 290 | f.p.directory.db.Writer().QueryRow("SELECT count(*) FROM sessions WHERE subject=?", chooserOther).Scan(&n) |
| 291 | if n != 1 { |
| 292 | t.Fatal("another person's directory session ended") |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | // Fable's final check N1: a receipt that commits between a sign-in's first |
| 297 | // mark check and its session write still wins, on both directory doors. |
| 298 | // Serial: it swaps the afterMarkCheck seam. |
| 299 | func TestNativeSignOutAllRaceOrderings(t *testing.T) { |
| 300 | prev := afterMarkCheck |
| 301 | t.Cleanup(func() { afterMarkCheck = prev }) |
| 302 | f := newMountedChooser(t) |
| 303 | cred := f.p.credential |
| 304 | dirSessions := func(person string) int { |
| 305 | var n int |
| 306 | f.p.directory.db.Writer().QueryRow("SELECT count(*) FROM sessions WHERE subject=?", person).Scan(&n) |
| 307 | return n |
| 308 | } |
| 309 | pressNow := func(person string) func() { |
| 310 | return func() { |
| 311 | if _, err := f.p.directory.db.Writer().Exec("INSERT INTO home_directory_signed_out_all(person_ref,at) VALUES(?,?) ON CONFLICT(person_ref) DO UPDATE SET at=excluded.at", person, time.Now().Unix()+5); err != nil { |
| 312 | t.Error(err) |
| 313 | } |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | // (a) The native exchange: the in-transaction check refuses. |
| 318 | d := newDevice(t) |
| 319 | grant, _ := d.signInByCode(t, cred, "race-native@example.invalid") |
| 320 | var person string |
| 321 | cred.db.Writer().QueryRow("SELECT person_ref FROM home_id_grants").Scan(&person) |
| 322 | verifier, challenge := verifierFor(70) |
| 323 | token := decodeReply(t, d.assert(t, cred, grant, directoryOrigin, challenge))["assertion"].(string) |
| 324 | afterMarkCheck = pressNow(person) |
| 325 | if w := directoryCall(t, f, "POST", nativeExchangePath, exchangeBody(token, verifier), nil, nil); w.Code != 401 { |
| 326 | t.Fatal("native exchange minted across a press", w.Code, w.Body.String()) |
| 327 | } |
| 328 | if n := dirSessions(person); n != 0 { |
| 329 | t.Fatal("native session survived the press", n) |
| 330 | } |
| 331 | |
| 332 | // (b) The browser finish: the re-check after SignIn undoes the session. |
| 333 | afterMarkCheck = func() {} |
| 334 | session := signInFully(t, cred, "race-web@example.invalid") |
| 335 | webPerson := subjectOf(t, cred, session) |
| 336 | pending, intent := f.p.start(t) |
| 337 | browserToken, _ := f.p.mint(t, intent, session) |
| 338 | callback := exchangeRequest(f.p.directory, "POST", directoryOrigin+handoff.CallbackPath, Origin, map[string][]string{"assertion": {browserToken}}) |
| 339 | inbox := namedCookie(t, callback, "__Host-oficina-assertion-inbox") |
| 340 | afterMarkCheck = pressNow(webPerson) |
| 341 | fin := exchangeRequest(f.p.directory, "GET", directoryOrigin+handoff.FinishPath, "", nil, pending, inbox) |
| 342 | if sessionCookie(fin) != nil || fin.Code != 403 || !strings.Contains(fin.Body.String(), "All devices are signed out") { |
| 343 | t.Fatal("browser finish across a press", fin.Code, sessionCookie(fin) != nil) |
| 344 | } |
| 345 | if n := dirSessions(webPerson); n != 0 { |
| 346 | t.Fatal("browser session survived the press", n) |
| 347 | } |
| 348 | } |
| 349 | |