| 1 | package home |
| 2 | |
| 3 | import ( |
| 4 | "crypto/sha256" |
| 5 | "encoding/base64" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "strings" |
| 9 | "testing" |
| 10 | "time" |
| 11 | |
| 12 | "amadan.net/oficina/home/handoff" |
| 13 | "amadan.net/oficina/home/internal/home/sealtest" |
| 14 | ) |
| 15 | |
| 16 | const teamDocs = "https://blue.docs.oficina.works" |
| 17 | |
| 18 | // §13 Proof: every way a proof can be wrong is refused, and no jti is |
| 19 | // recorded before the grant and the signature verify. |
| 20 | func TestNativeProofRefusals(t *testing.T) { |
| 21 | t.Parallel() |
| 22 | app := newNativeApp(t) |
| 23 | d := newDevice(t) |
| 24 | grant, _ := d.signInByCode(t, app, "p@example.invalid") |
| 25 | _, challenge := verifierFor(1) |
| 26 | for name, o := range map[string]proofOpts{ |
| 27 | "wrong key": {signer: newDevice(t)}, |
| 28 | "skewed iat": {iat: time.Now().Unix() - 31}, |
| 29 | "future iat": {iat: time.Now().Unix() + 31}, |
| 30 | "wrong htu": {htu: Origin + nativePrefix + "/signout"}, |
| 31 | "other host": {htu: "https://oficina.works" + nativePrefix + "/assert"}, |
| 32 | "swapped body": {signedBody: []byte(`{"aud":"https://directory.example","challenge":"x"}`)}, |
| 33 | "origin header": {headers: map[string]string{"Origin": Origin}}, |
| 34 | "sec-fetch-site": {headers: map[string]string{"Sec-Fetch-Site": "none"}}, |
| 35 | "malformed proof": {headers: map[string]string{"Oficina-Proof": "e30.AAAA"}}, |
| 36 | } { |
| 37 | w := d.assert(t, app, grant, teamDocs, challenge, o) |
| 38 | if w.Code == 200 { |
| 39 | t.Fatalf("%s: accepted", name) |
| 40 | } |
| 41 | if n := count(t, app, "SELECT count(*) FROM home_id_native_replay"); n != 0 { |
| 42 | t.Fatalf("%s: a jti row before the proof verified", name) |
| 43 | } |
| 44 | } |
| 45 | // An unknown or ended grant writes no jti either. |
| 46 | if w := d.assert(t, app, strings.Repeat("A", 43), teamDocs, challenge); w.Code != 401 { |
| 47 | t.Fatal("unknown grant", w.Code) |
| 48 | } |
| 49 | if n := count(t, app, "SELECT count(*) FROM home_id_native_replay"); n != 0 { |
| 50 | t.Fatal("a jti row for an unknown grant") |
| 51 | } |
| 52 | // A 401 carries the server clock, and every answer a Date. |
| 53 | w := d.assert(t, app, grant, teamDocs, challenge, proofOpts{iat: time.Now().Unix() - 100}) |
| 54 | if w.Code != 401 || decodeReply(t, w)["now"] == nil || w.Header().Get("Date") == "" || w.Header().Get("Cache-Control") != "no-store" { |
| 55 | t.Fatal("401 without now/Date", w.Code, w.Header()) |
| 56 | } |
| 57 | if w.Header().Get("Access-Control-Allow-Origin") != "" { |
| 58 | t.Fatal("CORS on a native endpoint") |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | // §13 Proof: a replayed jti is refused, also across a restart. |
| 63 | func TestNativeProofReplay(t *testing.T) { |
| 64 | t.Parallel() |
| 65 | app := newNativeApp(t) |
| 66 | d := newDevice(t) |
| 67 | grant, _ := d.signInByCode(t, app, "r@example.invalid") |
| 68 | _, challenge := verifierFor(2) |
| 69 | o := proofOpts{jti: "replay-me-0123456789", iat: time.Now().Unix()} |
| 70 | if w := d.assert(t, app, grant, teamDocs, challenge, o); w.Code != 200 { |
| 71 | t.Fatal("first", w.Code, w.Body.String()) |
| 72 | } |
| 73 | if w := d.assert(t, app, grant, teamDocs, challenge, o); w.Code != 401 || decodeReply(t, w)["error"] != nativeProofRejected { |
| 74 | t.Fatal("replay accepted", w.Code) |
| 75 | } |
| 76 | app = app.restart(t) |
| 77 | if w := d.assert(t, app, grant, teamDocs, challenge, o); w.Code != 401 { |
| 78 | t.Fatal("replay accepted after a restart", w.Code) |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | // §13 Proof: the table fails closed when full, and each grant is limited to |
| 83 | // 120 calls a minute. |
| 84 | func TestNativeProofTableLimits(t *testing.T) { |
| 85 | app := newNativeApp(t) |
| 86 | d := newDevice(t) |
| 87 | grant, _ := d.signInByCode(t, app, "l@example.invalid") |
| 88 | _, challenge := verifierFor(3) |
| 89 | for i := range nativeReplayPerMin { |
| 90 | if w := d.assert(t, app, grant, teamDocs, challenge); w.Code != 200 { |
| 91 | t.Fatal("call", i, w.Code) |
| 92 | } |
| 93 | } |
| 94 | if w := d.assert(t, app, grant, teamDocs, challenge); w.Code != 429 { |
| 95 | t.Fatal("call 121 in a minute", w.Code) |
| 96 | } |
| 97 | other := newDevice(t) |
| 98 | grant2, _ := other.signInByCode(t, app, "m@example.invalid") |
| 99 | if nativeReplayCap != 250000 { |
| 100 | t.Fatal("the replay table's size moved", nativeReplayCap) |
| 101 | } |
| 102 | prev := nativeReplayCap |
| 103 | nativeReplayCap = 200 |
| 104 | t.Cleanup(func() { nativeReplayCap = prev }) |
| 105 | tx, err := app.db.Writer().Begin() |
| 106 | if err != nil { |
| 107 | t.Fatal(err) |
| 108 | } |
| 109 | for i := range nativeReplayCap { |
| 110 | if _, err := tx.Exec("INSERT INTO home_id_native_replay VALUES(?,?,?,?)", fmt.Sprint("fill", i), "x", "p", int64(1<<40)); err != nil { |
| 111 | t.Fatal(err) |
| 112 | } |
| 113 | } |
| 114 | if err := tx.Commit(); err != nil { |
| 115 | t.Fatal(err) |
| 116 | } |
| 117 | if w := other.assert(t, app, grant2, teamDocs, challenge); w.Code != 503 { |
| 118 | t.Fatal("a full replay table admitted a proof", w.Code) |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | // §13 Assert: the assertion is slice 1's v1 for the registered audience, |
| 123 | // with the grant's auth_time and a nonce Home derived from the challenge. |
| 124 | func TestNativeAssert(t *testing.T) { |
| 125 | t.Parallel() |
| 126 | app := newNativeApp(t) |
| 127 | d := newDevice(t) |
| 128 | grant, _ := d.signInByCode(t, app, sealtest.CanaryAddress) |
| 129 | var authTime int64 |
| 130 | app.db.Writer().QueryRow("SELECT auth_time FROM home_id_grants").Scan(&authTime) |
| 131 | _, challenge := verifierFor(4) |
| 132 | w := d.assert(t, app, grant, teamDocs, challenge) |
| 133 | if w.Code != 200 { |
| 134 | t.Fatal(w.Code, w.Body.String()) |
| 135 | } |
| 136 | token := decodeReply(t, w)["assertion"].(string) |
| 137 | c := verifyAssertion(t, app, token, teamDocs) |
| 138 | session := signInFully(t, app, sealtest.CanaryAddress) |
| 139 | if c.Subject != subjectOf(t, app, session) || c.AuthTime != authTime || c.ExpiresAt-c.IssuedAt != 120 || c.Nonce != mustNativeNonce(t, challenge) { |
| 140 | t.Fatalf("claims %+v", c) |
| 141 | } |
| 142 | // The nonce is derived, never the caller's: no challenge yields a nonce |
| 143 | // equal to its own encoding, so a web nonce cannot be requested. |
| 144 | if c.Nonce == base64.RawURLEncoding.EncodeToString(challenge[:16]) { |
| 145 | t.Fatal("nonce is the challenge") |
| 146 | } |
| 147 | sum := sha256.Sum256(append([]byte("oficina-id/native/v1\x00"), challenge...)) |
| 148 | if c.Nonce != base64.RawURLEncoding.EncodeToString(sum[:16]) { |
| 149 | t.Fatal("nonce derivation drifted from the wire notes") |
| 150 | } |
| 151 | // Unregistered, near-miss and operator audiences are refused. |
| 152 | for _, aud := range []string{"https://evil.example", teamDocs + "/", "https://BLUE.docs.oficina.works", "https://green.docs.oficina.works", operatorConfirmConsumer} { |
| 153 | if w := d.assert(t, app, grant, aud, challenge); w.Code != 400 { |
| 154 | t.Fatal("unregistered audience", aud, w.Code) |
| 155 | } |
| 156 | } |
| 157 | if w := d.call(t, app, nativePrefix+"/assert", map[string]string{"aud": teamDocs, "challenge": "short"}, grant); w.Code != 400 { |
| 158 | t.Fatal("short challenge", w.Code) |
| 159 | } |
| 160 | if w := d.call(t, app, nativePrefix+"/assert", map[string]string{"aud": teamDocs, "challenge": base64.RawURLEncoding.EncodeToString(challenge), "nonce": "chosen"}, grant); w.Code != 400 { |
| 161 | t.Fatal("a caller-chosen nonce field was accepted", w.Code) |
| 162 | } |
| 163 | sealtest.AssertNoPlaintext(t, app.dbPath) |
| 164 | } |
| 165 | |
| 166 | // §13 Assert: mintPolicy is one function shared with /authorize. |
| 167 | func TestNativeMintPolicyShared(t *testing.T) { |
| 168 | refused := errors.New("refused") |
| 169 | prev := mintPolicy |
| 170 | var seen []string |
| 171 | mintPolicy = func(consumer, method string) error { seen = append(seen, consumer+"/"+method); return refused } |
| 172 | t.Cleanup(func() { mintPolicy = prev }) |
| 173 | |
| 174 | p := newExchangePair(t) |
| 175 | d := newDevice(t) |
| 176 | grant, _ := d.signInByCode(t, p.credential, "policy@example.invalid") |
| 177 | _, challenge := verifierFor(5) |
| 178 | if w := d.assert(t, p.credential, grant, directoryOrigin, challenge); w.Code != 403 { |
| 179 | t.Fatal("native assert ignored mintPolicy", w.Code) |
| 180 | } |
| 181 | session := signInFully(t, p.credential, "policy@example.invalid") |
| 182 | _, intent := p.start(t) |
| 183 | r := exchangeRequest(p.credential.App, "POST", Origin+"/authorize/resume", Origin, nil, intent, session) |
| 184 | if strings.Contains(r.Body.String(), `name="assertion"`) { |
| 185 | t.Fatal("/authorize ignored mintPolicy") |
| 186 | } |
| 187 | if fmt.Sprint(seen) != "[directory/email directory/magiclink]" { |
| 188 | t.Fatal("policy inputs", seen) |
| 189 | } |
| 190 | // And both call sites name it: a second rule cannot appear beside it. |
| 191 | for _, f := range []string{"exchange.go", "native_assert.go"} { |
| 192 | found := false |
| 193 | for _, g := range grepPackage(t, "mintPolicy(") { |
| 194 | found = found || g == f |
| 195 | } |
| 196 | if !found { |
| 197 | t.Fatal("mintPolicy not called from", f) |
| 198 | } |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | // §3: a 21st grant ends the least recently used; lapsed grants expire. |
| 203 | func TestNativeGrantLimitsAndExpiry(t *testing.T) { |
| 204 | t.Parallel() |
| 205 | app := newNativeApp(t) |
| 206 | d := newDevice(t) |
| 207 | first, _ := d.signInByCode(t, app, "many@example.invalid") |
| 208 | var person string |
| 209 | app.db.Writer().QueryRow("SELECT person_ref FROM home_id_grants").Scan(&person) |
| 210 | // The oldest-used grant, then eighteen more used today: twenty live. |
| 211 | if _, err := app.db.Writer().Exec("UPDATE home_id_grants SET last_used_day=?", dayOf(time.Now().Unix()-2*day)); err != nil { |
| 212 | t.Fatal(err) |
| 213 | } |
| 214 | for i := range nativeGrantsPerID - 1 { |
| 215 | 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) VALUES(?,?,'i','k','macos','email',1,?,?,?)", |
| 216 | fmt.Sprint("g", i), person, time.Now().Unix(), dayOf(time.Now().Unix()), time.Now().Unix()+day); err != nil { |
| 217 | t.Fatal(err) |
| 218 | } |
| 219 | } |
| 220 | newDevice(t).signInByCode(t, app, "many@example.invalid") // the 21st |
| 221 | if ended, reason := grantState(t, app, first); !ended || reason != "lru" { |
| 222 | t.Fatal("21st grant did not end the LRU", ended, reason) |
| 223 | } |
| 224 | if n := count(t, app, "SELECT count(*) FROM home_id_grants WHERE ended_at IS NULL"); n != nativeGrantsPerID { |
| 225 | t.Fatal("live grants", n) |
| 226 | } |
| 227 | // Absolute and idle expiry. |
| 228 | app2 := newNativeApp(t) |
| 229 | for i, q := range []string{"UPDATE home_id_grants SET expires_at=1", "UPDATE home_id_grants SET last_used_day=?"} { |
| 230 | e := newDevice(t) |
| 231 | g, _ := e.signInByCode(t, app2, fmt.Sprintf("exp-%d@example.invalid", i)) |
| 232 | args := []any{} |
| 233 | if strings.Contains(q, "last_used_day") { |
| 234 | args = append(args, idleCutoff(time.Now().Unix())) |
| 235 | } |
| 236 | if _, err := app2.db.Writer().Exec(q+" WHERE grant_hash='"+nativeHash(g)+"'", args...); err != nil { |
| 237 | t.Fatal(err) |
| 238 | } |
| 239 | _, challenge := verifierFor(6) |
| 240 | if w := e.assert(t, app2, g, teamDocs, challenge); w.Code != 401 { |
| 241 | t.Fatal("expired grant used", q, w.Code) |
| 242 | } |
| 243 | if ended, reason := grantState(t, app2, g); !ended || reason != "expiry" { |
| 244 | t.Fatal("expired grant not ended", reason) |
| 245 | } |
| 246 | } |
| 247 | // A grant used yesterday is still live. |
| 248 | e := newDevice(t) |
| 249 | g, _ := e.signInByCode(t, app2, "fresh@example.invalid") |
| 250 | if _, err := app2.db.Writer().Exec("UPDATE home_id_grants SET last_used_day=? WHERE grant_hash=?", dayOf(time.Now().Unix()-nativeGrantIdleDays*day), nativeHash(g)); err != nil { |
| 251 | t.Fatal(err) |
| 252 | } |
| 253 | _, challenge := verifierFor(7) |
| 254 | if w := e.assert(t, app2, g, teamDocs, challenge); w.Code != 200 { |
| 255 | t.Fatal("a grant inside its idle window was refused", w.Code) |
| 256 | } |
| 257 | } |
| 258 | |
| 259 | // §10: the device's own sign-out ends its grant; a late, pre-signed one is |
| 260 | // refused by the 30-second window. |
| 261 | func TestNativeSignout(t *testing.T) { |
| 262 | t.Parallel() |
| 263 | app := newNativeApp(t) |
| 264 | d := newDevice(t) |
| 265 | grant, _ := d.signInByCode(t, app, "s@example.invalid") |
| 266 | late := d.call(t, app, nativePrefix+"/signout", map[string]string{}, grant, proofOpts{iat: time.Now().Unix() - 40}) |
| 267 | if late.Code != 401 { |
| 268 | t.Fatal("late sign-out accepted", late.Code) |
| 269 | } |
| 270 | if w := d.call(t, app, nativePrefix+"/signout", map[string]string{}, grant); w.Code != 200 { |
| 271 | t.Fatal("signout", w.Code, w.Body.String()) |
| 272 | } |
| 273 | if ended, reason := grantState(t, app, grant); !ended || reason != "signout" { |
| 274 | t.Fatal("grant", reason) |
| 275 | } |
| 276 | _, challenge := verifierFor(8) |
| 277 | if w := d.assert(t, app, grant, teamDocs, challenge); w.Code != 401 { |
| 278 | t.Fatal("a signed-out grant asserted", w.Code) |
| 279 | } |
| 280 | } |
| 281 | |
| 282 | // The derivation's shared vector (verifier = base64url of 0x00..0x1f). The |
| 283 | // challenge is SHA-256 of the verifier's base64url STRING, the convention the |
| 284 | // coordinator fixed for all three halves (Home, connect, the Swift client). |
| 285 | func TestNativeNonceVector(t *testing.T) { |
| 286 | t.Parallel() |
| 287 | raw := make([]byte, 32) |
| 288 | for i := range raw { |
| 289 | raw[i] = byte(i) |
| 290 | } |
| 291 | verifier := base64.RawURLEncoding.EncodeToString(raw) |
| 292 | if verifier != "AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8" { |
| 293 | t.Fatal(verifier) |
| 294 | } |
| 295 | challenge := sha256.Sum256([]byte(verifier)) |
| 296 | if c := base64.RawURLEncoding.EncodeToString(challenge[:]); c != "6oZqdX5MOLq_qBJ8vppAnT4fk6AP8UiP9zX8-Rev_9A" { |
| 297 | t.Fatal("challenge", c) |
| 298 | } |
| 299 | if n := mustNativeNonce(t, challenge[:]); n != "ZVVVj2zbBfhkAIwAOKNylg" { |
| 300 | t.Fatal("nonce", n) |
| 301 | } |
| 302 | // And handoff's, which assert and every exchange use, agrees. |
| 303 | c, ok := handoff.NativeChallenge(verifier) |
| 304 | if n, _ := handoff.NativeNonce(c); !ok || n != "ZVVVj2zbBfhkAIwAOKNylg" { |
| 305 | t.Fatal("handoff derivation", c, n) |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | // The two 401 markers: the client wipes the identity only on grant_ended. |
| 310 | func TestNativeUnauthorizedMarkers(t *testing.T) { |
| 311 | t.Parallel() |
| 312 | app := newNativeApp(t) |
| 313 | d := newDevice(t) |
| 314 | grant, _ := d.signInByCode(t, app, "markers@example.invalid") |
| 315 | _, challenge := verifierFor(40) |
| 316 | for name, o := range map[string]proofOpts{"skew": {iat: time.Now().Unix() - 60}, "key": {signer: newDevice(t)}} { |
| 317 | w := d.assert(t, app, grant, teamDocs, challenge, o) |
| 318 | if out := decodeReply(t, w); w.Code != 401 || out["error"] != nativeProofRejected || out["now"] == nil { |
| 319 | t.Fatal(name, w.Code, out) |
| 320 | } |
| 321 | } |
| 322 | if w := d.assert(t, app, strings.Repeat("A", 43), teamDocs, challenge); decodeReply(t, w)["error"] != nativeGrantEnded { |
| 323 | t.Fatal("unknown grant", w.Body.String()) |
| 324 | } |
| 325 | if w := d.call(t, app, nativePrefix+"/signout", map[string]string{}, grant); w.Code != 200 { |
| 326 | t.Fatal(w.Code) |
| 327 | } |
| 328 | w := d.assert(t, app, grant, teamDocs, challenge) |
| 329 | if out := decodeReply(t, w); w.Code != 401 || out["error"] != nativeGrantEnded || out["now"] == nil { |
| 330 | t.Fatal("ended grant", w.Code, out) |
| 331 | } |
| 332 | // A gone start is 410 expired, on verify and resend alike. |
| 333 | start := d.start(t, app, "gone@example.invalid") |
| 334 | if _, err := app.db.Writer().Exec("UPDATE home_id_native_starts SET expires_at=1"); err != nil { |
| 335 | t.Fatal(err) |
| 336 | } |
| 337 | for _, path := range []string{"/code/verify", "/code/resend"} { |
| 338 | body := map[string]string{"start": start} |
| 339 | if path == "/code/verify" { |
| 340 | body["code"] = "123456" |
| 341 | } |
| 342 | if w := d.call(t, app, nativePrefix+path, body, ""); w.Code != 410 || decodeReply(t, w)["error"] != "expired" { |
| 343 | t.Fatal(path, w.Code, w.Body.String()) |
| 344 | } |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | func mustNativeNonce(t *testing.T, challenge []byte) string { |
| 349 | t.Helper() |
| 350 | n, ok := handoff.NativeNonce(base64.RawURLEncoding.EncodeToString(challenge)) |
| 351 | if !ok { |
| 352 | t.Fatal("challenge") |
| 353 | } |
| 354 | return n |
| 355 | } |
| 356 | |