| 1 | package oficinaid |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/home/connect" |
| 5 | "amadan.net/oficina/home/connect/linkstore" |
| 6 | "amadan.net/oficina/home/handoff" |
| 7 | "amadan.net/rastrillo/rastrillo/assertion" |
| 8 | "amadan.net/rastrillo/rastrillo/crypto" |
| 9 | "amadan.net/rastrillo/rastrillo/sessions" |
| 10 | "bytes" |
| 11 | "context" |
| 12 | "database/sql" |
| 13 | "encoding/base64" |
| 14 | "encoding/json" |
| 15 | _ "modernc.org/sqlite" |
| 16 | "path/filepath" |
| 17 | "testing" |
| 18 | "time" |
| 19 | ) |
| 20 | |
| 21 | func fixture(t *testing.T) (*Store, *crypto.Keypair) { |
| 22 | t.Helper() |
| 23 | db, e := sql.Open("sqlite", filepath.Join(t.TempDir(), "id.db")+"?_pragma=busy_timeout(5000)") |
| 24 | if e != nil { |
| 25 | t.Fatal(e) |
| 26 | } |
| 27 | t.Cleanup(func() { db.Close() }) |
| 28 | db.SetMaxOpenConns(1) |
| 29 | for _, fs := range []struct { |
| 30 | read func(string) ([]byte, error) |
| 31 | names []string |
| 32 | }{{handoff.Migrations.ReadFile, []string{"migrations/0001_exchange.sql"}}, {linkstore.Migrations.ReadFile, []string{"migrations/0001_links.sql", "migrations/0002_person_binding.sql", "migrations/0003_choice_proofs.sql"}}} { |
| 33 | for _, n := range fs.names { |
| 34 | b, e := fs.read(n) |
| 35 | if e != nil { |
| 36 | t.Fatal(e) |
| 37 | } |
| 38 | if _, e = db.Exec(string(b)); e != nil { |
| 39 | t.Fatal(e) |
| 40 | } |
| 41 | } |
| 42 | } |
| 43 | if _, e = db.Exec(`CREATE TABLE audit_events(id INTEGER PRIMARY KEY,actor TEXT,kind TEXT,record_id TEXT,at TEXT); CREATE TABLE members(address TEXT PRIMARY KEY,active INTEGER,session_epoch INTEGER,identity_key TEXT DEFAULT 'local-test-member'); CREATE TABLE sessions(token_hash TEXT PRIMARY KEY,subject TEXT,method TEXT,auth_time TEXT,created_at TEXT,expires_at TEXT);` + SchemaSQL); e != nil { |
| 44 | t.Fatal(e) |
| 45 | } |
| 46 | k, e := crypto.Generate() |
| 47 | if e != nil { |
| 48 | t.Fatal(e) |
| 49 | } |
| 50 | s, e := New(db, "https://equipo.example", &connect.DecodedCredentials{Issuer: "https://id.example", ConsumerID: "equipo", Keys: map[string][]byte{"k": k.SignPub()}, DEK: bytes.Repeat([]byte{7}, 32)}) |
| 51 | if e != nil { |
| 52 | t.Fatal(e) |
| 53 | } |
| 54 | return s, k |
| 55 | } |
| 56 | func TestIDReceiptGuards(t *testing.T) { |
| 57 | for _, kind := range []string{"valid", "replay", "audience", "expired", "nonce", "unlinked"} { |
| 58 | t.Run(kind, func(t *testing.T) { |
| 59 | s, k := fixture(t) |
| 60 | now := time.Now().Truncate(time.Second) |
| 61 | secret, nonce, e := s.Exchange.Start(context.Background(), "/work", "", now) |
| 62 | if e != nil { |
| 63 | t.Fatal(e) |
| 64 | } |
| 65 | c := assertion.Claims{Version: 1, KeyID: "k", Issuer: s.Config.Issuer, Audience: s.Origin, Subject: "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa", IssuedAt: now.Unix(), ExpiresAt: now.Unix() + 120, AuthTime: now.Unix(), Nonce: nonce} |
| 66 | c.ID, _ = assertion.RandomID() |
| 67 | switch kind { |
| 68 | case "audience": |
| 69 | c.Audience = "https://other.example" |
| 70 | case "expired": |
| 71 | c.AuthTime -= 121 |
| 72 | c.IssuedAt -= 121 |
| 73 | c.ExpiresAt -= 121 |
| 74 | case "nonce": |
| 75 | c.Nonce, _ = assertion.RandomID() |
| 76 | } |
| 77 | token, e := assertion.Sign(k, c) |
| 78 | if e != nil { |
| 79 | t.Fatal(e) |
| 80 | } |
| 81 | handle, e := s.Exchange.ReceivePending(context.Background(), token, now) |
| 82 | if kind == "audience" || kind == "expired" || kind == "nonce" { |
| 83 | if e == nil { |
| 84 | t.Fatal("accepted invalid receipt") |
| 85 | } |
| 86 | return |
| 87 | } |
| 88 | if e != nil { |
| 89 | t.Fatal(e) |
| 90 | } |
| 91 | if kind == "replay" { |
| 92 | if _, e = s.Exchange.ReceivePending(context.Background(), token, now); e == nil { |
| 93 | t.Fatal("replayed receipt") |
| 94 | } |
| 95 | } |
| 96 | if kind == "unlinked" { |
| 97 | if _, _, e = s.Finish(context.Background(), secret, handle, "", "", now); e != ErrUnlinked { |
| 98 | t.Fatal("unlinked identity admitted", e) |
| 99 | } |
| 100 | } |
| 101 | }) |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | func seedLocal(t *testing.T, s *Store, address string, now time.Time) string { |
| 106 | t.Helper() |
| 107 | if _, e := s.DB.Exec("INSERT OR IGNORE INTO members(address,active,session_epoch,identity_key) VALUES(?,1,0,?)", address, s.binding(address)); e != nil { |
| 108 | t.Fatal(e) |
| 109 | } |
| 110 | token, hash, e := sessions.NewToken() |
| 111 | if e != nil { |
| 112 | t.Fatal(e) |
| 113 | } |
| 114 | stamp := now.UTC().Format(time.RFC3339) |
| 115 | if _, e = s.DB.Exec("INSERT INTO sessions VALUES(?,?,?, ?,?,?)", hash, address, "magiclink", "", stamp, now.Add(time.Hour).UTC().Format(time.RFC3339)); e != nil { |
| 116 | t.Fatal(e) |
| 117 | } |
| 118 | return token |
| 119 | } |
| 120 | func readyLink(t *testing.T, s *Store, now time.Time) (string, string) { |
| 121 | t.Helper() |
| 122 | old := seedLocal(t, s, "local-canary@example.invalid", now.Add(-time.Hour)) |
| 123 | // Keep the initial session live for this test. |
| 124 | s.DB.Exec("UPDATE sessions SET expires_at=?", now.Add(time.Hour).UTC().Format(time.RFC3339)) |
| 125 | reauth, e := s.BeginReauth(context.Background(), old, "link", now.Add(-time.Second)) |
| 126 | if e != nil { |
| 127 | t.Fatal(e) |
| 128 | } |
| 129 | token := seedLocal(t, s, "local-canary@example.invalid", now) |
| 130 | init, purpose, e := s.CompleteReauth(context.Background(), reauth, token, now) |
| 131 | if e != nil || purpose != "link" { |
| 132 | t.Fatal("reauth", e) |
| 133 | } |
| 134 | return token, init |
| 135 | } |
| 136 | func receive(t *testing.T, s *Store, k *crypto.Keypair, init, token, subject string, auth, now time.Time) (string, string) { |
| 137 | t.Helper() |
| 138 | ctx := context.Background() |
| 139 | start := s.Exchange.Start |
| 140 | if init != "" { |
| 141 | start = s.Exchange.StartFresh |
| 142 | } |
| 143 | path := "/work" |
| 144 | if init != "" { |
| 145 | path = "/account/home/confirm" |
| 146 | } |
| 147 | secret, nonce, e := start(ctx, path, "", now) |
| 148 | if e != nil { |
| 149 | t.Fatal(e) |
| 150 | } |
| 151 | if init != "" { |
| 152 | if e = s.Bind(ctx, init, token, nonce, now); e != nil { |
| 153 | t.Fatal(e) |
| 154 | } |
| 155 | } |
| 156 | id, _ := assertion.RandomID() |
| 157 | signed, e := assertion.Sign(k, assertion.Claims{Version: 1, KeyID: "k", Issuer: s.Config.Issuer, Audience: s.Origin, Subject: subject, IssuedAt: now.Unix(), ExpiresAt: now.Unix() + 120, AuthTime: auth.Unix(), Nonce: nonce, ID: id}) |
| 158 | if e != nil { |
| 159 | t.Fatal(e) |
| 160 | } |
| 161 | handle, e := s.Exchange.ReceivePending(ctx, signed, now) |
| 162 | if e != nil { |
| 163 | t.Fatal(e) |
| 164 | } |
| 165 | return secret, handle |
| 166 | } |
| 167 | func TestIDLinkRequiresNewLocalAndHomeProofs(t *testing.T) { |
| 168 | ctx := context.Background() |
| 169 | now := time.Now().Truncate(time.Second) |
| 170 | for _, kind := range []string{"same-session", "wrong-account", "stale-local", "older-home", "valid"} { |
| 171 | t.Run(kind, func(t *testing.T) { |
| 172 | s, k := fixture(t) |
| 173 | old := seedLocal(t, s, "local-canary@example.invalid", now) |
| 174 | proof, e := s.BeginReauth(ctx, old, "link", now) |
| 175 | if e != nil { |
| 176 | t.Fatal(e) |
| 177 | } |
| 178 | token := old |
| 179 | switch kind { |
| 180 | case "wrong-account": |
| 181 | token = seedLocal(t, s, "other@example.invalid", now) |
| 182 | case "stale-local": |
| 183 | token = seedLocal(t, s, "local-canary@example.invalid", now.Add(-time.Second)) |
| 184 | case "older-home", "valid": |
| 185 | token = seedLocal(t, s, "local-canary@example.invalid", now) |
| 186 | } |
| 187 | init, _, e := s.CompleteReauth(ctx, proof, token, now) |
| 188 | if kind == "same-session" || kind == "wrong-account" || kind == "stale-local" { |
| 189 | if e == nil { |
| 190 | t.Fatal("accepted missing fresh local proof") |
| 191 | } |
| 192 | return |
| 193 | } |
| 194 | if e != nil { |
| 195 | t.Fatal(e) |
| 196 | } |
| 197 | homeAt := now |
| 198 | if kind == "older-home" { |
| 199 | homeAt = now.Add(-time.Second) |
| 200 | } |
| 201 | secret, handle := receive(t, s, k, init, token, "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa", homeAt, now) |
| 202 | pending, _, e := s.Finish(ctx, secret, handle, token, init, now) |
| 203 | if kind == "older-home" { |
| 204 | if e == nil { |
| 205 | t.Fatal("Home proof predates link start") |
| 206 | } |
| 207 | return |
| 208 | } |
| 209 | if e != nil { |
| 210 | t.Fatal(e) |
| 211 | } |
| 212 | if _, _, e = s.Links.Resolve(ctx, s.Config.Issuer, "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa"); e == nil { |
| 213 | t.Fatal("linked before explicit confirmation") |
| 214 | } |
| 215 | if e = s.Confirm(ctx, pending, token, now); e != nil { |
| 216 | t.Fatal(e) |
| 217 | } |
| 218 | if e = s.Confirm(ctx, pending, token, now); e == nil { |
| 219 | t.Fatal("replayed link confirmation") |
| 220 | } |
| 221 | }) |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | func TestIDRejectsAddressAsSubject(t *testing.T) { |
| 226 | s, k := fixture(t) |
| 227 | now := time.Now() |
| 228 | _, nonce, e := s.Exchange.Start(context.Background(), "/", "", now) |
| 229 | if e != nil { |
| 230 | t.Fatal(e) |
| 231 | } |
| 232 | id, _ := assertion.RandomID() |
| 233 | claims := assertion.Claims{Version: 1, KeyID: "k", Issuer: s.Config.Issuer, Audience: s.Origin, Subject: "home-private-canary@example.invalid", ID: id, Nonce: nonce, IssuedAt: now.Unix(), ExpiresAt: now.Unix() + 120, AuthTime: now.Unix()} |
| 234 | raw, e := json.Marshal(claims) |
| 235 | if e != nil { |
| 236 | t.Fatal(e) |
| 237 | } |
| 238 | sig, e := crypto.Sign(k, "rastrillo/assertion/v1", raw) |
| 239 | if e != nil { |
| 240 | t.Fatal(e) |
| 241 | } |
| 242 | wire := base64.RawURLEncoding.EncodeToString(raw) + "." + base64.RawURLEncoding.EncodeToString(sig) |
| 243 | if _, e = s.Exchange.ReceivePending(context.Background(), wire, now); e == nil { |
| 244 | t.Fatal("address accepted as opaque ref") |
| 245 | } |
| 246 | var n int |
| 247 | if e = s.DB.QueryRow("SELECT count(*) FROM oficina_handoff_inbox").Scan(&n); e != nil || n != 0 { |
| 248 | t.Fatal("address retained", n, e) |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | func establish(t *testing.T, s *Store, k *crypto.Keypair, now time.Time) (string, string) { |
| 253 | t.Helper() |
| 254 | token, init := readyLink(t, s, now) |
| 255 | secret, handle := receive(t, s, k, init, token, "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa", now, now) |
| 256 | proof, _, e := s.Finish(context.Background(), secret, handle, token, init, now) |
| 257 | if e != nil { |
| 258 | t.Fatal(e) |
| 259 | } |
| 260 | if e = s.Confirm(context.Background(), proof, token, now); e != nil { |
| 261 | t.Fatal(e) |
| 262 | } |
| 263 | secret, handle = receive(t, s, k, "", "", "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa", now, now) |
| 264 | home, _, e := s.Finish(context.Background(), secret, handle, "", "", now) |
| 265 | if e != nil { |
| 266 | t.Fatal(e) |
| 267 | } |
| 268 | return token, home |
| 269 | } |
| 270 | func TestIDAtomicMintFailureAndSwappedBrowser(t *testing.T) { |
| 271 | s, k := fixture(t) |
| 272 | now := time.Now().Truncate(time.Second) |
| 273 | establish(t, s, k, now) |
| 274 | secret, handle := receive(t, s, k, "", "", "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa", now, now) |
| 275 | other, _, e := s.Exchange.Start(context.Background(), "/", "", now) |
| 276 | if e != nil { |
| 277 | t.Fatal(e) |
| 278 | } |
| 279 | if _, _, e = s.Finish(context.Background(), other, handle, "", "", now); e == nil { |
| 280 | t.Fatal("swapped browser accepted") |
| 281 | } |
| 282 | if _, e = s.DB.Exec("CREATE TRIGGER reject_id_mint BEFORE INSERT ON sessions BEGIN SELECT RAISE(ABORT,'mint blocked'); END"); e != nil { |
| 283 | t.Fatal(e) |
| 284 | } |
| 285 | if _, _, e = s.Finish(context.Background(), secret, handle, "", "", now); e == nil { |
| 286 | t.Fatal("mint failure accepted") |
| 287 | } |
| 288 | if _, e = s.DB.Exec("DROP TRIGGER reject_id_mint"); e != nil { |
| 289 | t.Fatal(e) |
| 290 | } |
| 291 | if _, _, e = s.Finish(context.Background(), secret, handle, "", "", now); e != nil { |
| 292 | t.Fatal("proof consumed outside mint transaction", e) |
| 293 | } |
| 294 | if _, _, e = s.Finish(context.Background(), secret, handle, "", "", now); e == nil { |
| 295 | t.Fatal("finished proof replayed") |
| 296 | } |
| 297 | } |
| 298 | func TestIDUnlinkRevokesReceiptsAndRelinkCannotRevive(t *testing.T) { |
| 299 | s, k := fixture(t) |
| 300 | now := time.Now().Truncate(time.Second) |
| 301 | local, home := establish(t, s, k, now) |
| 302 | survivor := seedLocal(t, s, "local-canary@example.invalid", now) |
| 303 | secret, handle := receive(t, s, k, "", "", "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa", now, now) |
| 304 | proof, e := s.BeginReauth(context.Background(), local, "unlink", now) |
| 305 | if e != nil { |
| 306 | t.Fatal(e) |
| 307 | } |
| 308 | fresh := seedLocal(t, s, "local-canary@example.invalid", now) |
| 309 | if _, _, e = s.CompleteReauth(context.Background(), proof, fresh, now); e != nil { |
| 310 | t.Fatal(e) |
| 311 | } |
| 312 | if e = s.Unlink(context.Background(), proof, fresh, now); e != nil { |
| 313 | t.Fatal(e) |
| 314 | } |
| 315 | if _, e = s.Session(context.Background(), home, now); e == nil { |
| 316 | t.Fatal("Home session survived unlink") |
| 317 | } |
| 318 | if _, e = s.Session(context.Background(), survivor, now); e != nil { |
| 319 | t.Fatal("local session revoked") |
| 320 | } |
| 321 | establish(t, s, k, now) |
| 322 | if _, _, e = s.Finish(context.Background(), secret, handle, "", "", now); e == nil { |
| 323 | t.Fatal("old receipt revived after relink") |
| 324 | } |
| 325 | } |
| 326 | func TestIDReauthRejectsRevokedOriginalEpoch(t *testing.T) { |
| 327 | s, _ := fixture(t) |
| 328 | now := time.Now().Truncate(time.Second) |
| 329 | old := seedLocal(t, s, "local-canary@example.invalid", now.Add(-time.Second)) |
| 330 | proof, e := s.BeginReauth(context.Background(), old, "link", now) |
| 331 | if e != nil { |
| 332 | t.Fatal(e) |
| 333 | } |
| 334 | if _, e = s.DB.Exec("UPDATE members SET session_epoch=?", now.Unix()); e != nil { |
| 335 | t.Fatal(e) |
| 336 | } |
| 337 | fresh := seedLocal(t, s, "local-canary@example.invalid", now) |
| 338 | if _, _, e = s.CompleteReauth(context.Background(), proof, fresh, now); e == nil { |
| 339 | t.Fatal("revoked original session authorized linking") |
| 340 | } |
| 341 | } |
| 342 | func TestIDReauthClockRollback(t *testing.T) { |
| 343 | s, _ := fixture(t) |
| 344 | now := time.Now().Truncate(time.Second) |
| 345 | old := seedLocal(t, s, "local-canary@example.invalid", now) |
| 346 | proof, e := s.BeginReauth(context.Background(), old, "unlink", now) |
| 347 | if e != nil { |
| 348 | t.Fatal(e) |
| 349 | } |
| 350 | fresh := seedLocal(t, s, "local-canary@example.invalid", now) |
| 351 | if _, e = s.DB.Exec("UPDATE home_link_clock SET high_water=?", now.Unix()+400); e != nil { |
| 352 | t.Fatal(e) |
| 353 | } |
| 354 | if _, _, e = s.CompleteReauth(context.Background(), proof, fresh, now); e == nil { |
| 355 | t.Fatal("clock rollback revived reauthentication") |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | func TestIDConflictingConfirmationBurnsProof(t *testing.T) { |
| 360 | s, k := fixture(t) |
| 361 | now := time.Now().Truncate(time.Second) |
| 362 | establish(t, s, k, now) |
| 363 | token, init := readyLink(t, s, now) |
| 364 | secret, handle := receive(t, s, k, init, token, "pr_bbbbbbbbbbbbbbbbbbbbbbbbbb", now, now) |
| 365 | proof, _, e := s.Finish(context.Background(), secret, handle, token, init, now) |
| 366 | if e != nil { |
| 367 | t.Fatal(e) |
| 368 | } |
| 369 | if e = s.Confirm(context.Background(), proof, token, now); e == nil { |
| 370 | t.Fatal("conflicting link overwritten") |
| 371 | } |
| 372 | var n int |
| 373 | if e = s.DB.QueryRow("SELECT count(*) FROM home_link_flows WHERE stage='pending'").Scan(&n); e != nil || n != 0 { |
| 374 | t.Fatal("rejected proof restored", n, e) |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | func TestIDConcurrentUnlinkAndMint(t *testing.T) { |
| 379 | s, k := fixture(t) |
| 380 | now := time.Now().Truncate(time.Second) |
| 381 | local, _ := establish(t, s, k, now) |
| 382 | secret, handle := receive(t, s, k, "", "", "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa", now, now) |
| 383 | proof, e := s.BeginReauth(context.Background(), local, "unlink", now) |
| 384 | if e != nil { |
| 385 | t.Fatal(e) |
| 386 | } |
| 387 | fresh := seedLocal(t, s, "local-canary@example.invalid", now) |
| 388 | if _, _, e = s.CompleteReauth(context.Background(), proof, fresh, now); e != nil { |
| 389 | t.Fatal(e) |
| 390 | } |
| 391 | ready := make(chan struct{}) |
| 392 | type minted struct { |
| 393 | token string |
| 394 | err error |
| 395 | } |
| 396 | result := make(chan minted, 1) |
| 397 | unlinked := make(chan error, 1) |
| 398 | go func() { |
| 399 | <-ready |
| 400 | token, _, err := s.Finish(context.Background(), secret, handle, "", "", now) |
| 401 | result <- minted{token, err} |
| 402 | }() |
| 403 | go func() { <-ready; unlinked <- s.Unlink(context.Background(), proof, fresh, now) }() |
| 404 | close(ready) |
| 405 | got := <-result |
| 406 | if e = <-unlinked; e != nil { |
| 407 | t.Fatal(e) |
| 408 | } |
| 409 | if got.err == nil { |
| 410 | if _, e = s.Session(context.Background(), got.token, now); e == nil { |
| 411 | t.Fatal("concurrent mint survived unlink") |
| 412 | } |
| 413 | } |
| 414 | var n int |
| 415 | if e = s.DB.QueryRow("SELECT count(*) FROM sessions WHERE method=?", Method).Scan(&n); e != nil || n != 0 { |
| 416 | t.Fatal("Home sessions survived unlink", n, e) |
| 417 | } |
| 418 | } |
| 419 | |