package plan3test import ( "amadan.net/oficina/equipo/internal/equipo/kernel" "bytes" "context" "crypto/sha256" "encoding/base64" "encoding/json" "errors" "gorm.io/gorm" "io" "log/slog" "net/http" "net/http/httptest" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/oficinaid" "amadan.net/oficina/equipo/internal/equipo/personapi" "amadan.net/oficina/home/connect" "amadan.net/oficina/home/handoff" "amadan.net/rastrillo/rastrillo/assertion" "amadan.net/rastrillo/rastrillo/crypto" "amadan.net/rastrillo/rastrillo/mail" "amadan.net/rastrillo/rastrillo/sessions" ) const nativeOrigin = "https://equipo-staging.bds.oncarlos.com" const nativeSubject = "pr_aaaaaaaaaaaaaaaaaaaaaaaaaa" func nativeIDFixture(t *testing.T) (*fixture, *oficinaid.Store, string, *crypto.Keypair) { t.Helper() f := newFixture(t) key, e := crypto.Generate() must(t, e) cfg := &connect.DecodedCredentials{Issuer: "https://id.example", ConsumerID: "equipo", Keys: map[string][]byte{"k": key.SignPub()}, DEK: bytes.Repeat([]byte{7}, 32)} s, e := oficinaid.New(f.DB.Writer(), nativeOrigin, cfg) must(t, e) now := time.Now().UTC().Truncate(time.Second) old := f.Cookies[owner.Address].Value proof, e := s.BeginReauth(ctx, old, "link", now) must(t, e) fresh, hash, e := sessions.NewToken() must(t, e) f.exec(t, "INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES(?,?,?,?,?,?)", hash, owner.Address, "magiclink", now.Format(time.RFC3339), now.Format(time.RFC3339), now.Add(time.Hour).Format(time.RFC3339)) init, _, e := s.CompleteReauth(ctx, proof, fresh, now) must(t, e) secret, nonce, e := s.Exchange.StartFresh(ctx, "/account/home/confirm", "", now) must(t, e) must(t, s.Bind(ctx, init, fresh, nonce, now)) sign := func(nonce string) string { id, e := assertion.RandomID() must(t, e) v, e := assertion.Sign(key, assertion.Claims{Version: 1, KeyID: "k", Issuer: cfg.Issuer, Audience: nativeOrigin, Subject: nativeSubject, ID: id, Nonce: nonce, IssuedAt: now.Unix(), ExpiresAt: now.Unix() + 120, AuthTime: now.Unix()}) must(t, e) return v } receipt, e := s.Exchange.ReceivePending(ctx, sign(nonce), now) must(t, e) confirmation, _, e := s.Finish(ctx, secret, receipt, fresh, init, now) must(t, e) must(t, s.Confirm(ctx, confirmation, fresh, now)) logger := slog.New(slog.NewTextHandler(io.Discard, nil)) router, e := equipo.RouterWithStore(f.DB, equipo.Config{Origin: nativeOrigin, InstanceKey: "plan3-fixture", Home: cfg, AllowLoggedMail: true, Owners: []string{owner.Address}}, mail.Logged(logger), logger, f.Store) must(t, e) f.Handler = equipo.Mux(router) verifier := base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{4}, 32)) challenge := sha256.Sum256([]byte(verifier)) nonce, _ = handoff.NativeNonce(base64.RawURLEncoding.EncodeToString(challenge[:])) body, _ := json.Marshal(map[string]string{"assertion": sign(nonce), "verifier": verifier}) r := httptest.NewRequest("POST", nativeOrigin+oficinaid.NativePath, bytes.NewReader(body)) r.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() f.Handler.ServeHTTP(w, r) expectNativeHTTP(t, w, 200) minted := apiValue[oficinaid.NativeSession](t, w) f.Cookies[owner.Address] = &http.Cookie{Name: minted.Name, Value: minted.Value} return f, s, fresh, key } func nativeDevicePost(f *fixture, body string, edit func(*http.Request)) *httptest.ResponseRecorder { r := httptest.NewRequest("POST", nativeOrigin+"/api/v1/auth/devices/native", strings.NewReader(body)) r.Header.Set("Content-Type", "application/json") r.Header.Set("Origin", nativeOrigin) r.AddCookie(f.Cookies[owner.Address]) if edit != nil { edit(r) } w := httptest.NewRecorder() f.Handler.ServeHTTP(w, r) return w } func nativeDeviceBody() string { return `{"public_key":"` + base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{3}, 32)) + `","label":"private-device-label"}` } func TestPersonAPINativeDevice(t *testing.T) { f, s, fresh, _ := nativeIDFixture(t) sourceAt := time.Now().UTC().Truncate(time.Second).Add(-2 * 24 * time.Hour) f.exec(t, "UPDATE sessions SET created_at=?,expires_at=? WHERE token_hash=?", sourceAt.Format(time.RFC3339), sourceAt.Add(7*24*time.Hour).Format(time.RFC3339), sessions.HashToken(f.Cookies[owner.Address].Value)) w := nativeDevicePost(f, nativeDeviceBody(), nil) expectNativeHTTP(t, w, 200) credential := apiValue[personapi.PersonCredential](t, w) var person, source, created string must(t, f.DB.Writer().QueryRow("SELECT person,native_session_hash FROM person_devices WHERE id=?", credential.ID).Scan(&person, &source)) must(t, f.DB.Writer().QueryRow("SELECT created_at FROM sessions WHERE token_hash=?", source).Scan(&created)) at, e := time.Parse(time.RFC3339, created) must(t, e) if person != owner.Address || source != sessions.HashToken(f.Cookies[owner.Address].Value) || !credential.ExpiresAt.Equal(at.Add(7*24*time.Hour)) { t.Fatal("wrong owner, source, or expiry") } if !strings.HasPrefix(credential.Token, personapi.PersonAudience+".") || credential.Audience != personapi.PersonAudience || credential.InstanceID == "" { t.Fatal("credential contract") } var audit string must(t, f.DB.Writer().QueryRow("SELECT group_concat(actor || kind || record_id) FROM audit_events").Scan(&audit)) for _, secret := range []string{credential.Token, source, f.Cookies[owner.Address].Value, "private-device-label"} { if strings.Contains(audit, secret) { t.Fatal("credential or label in audit") } } if !strings.Contains(audit, "person_device.native") { t.Fatal("missing native audit") } // Unlink uses the existing fresh local ceremony and cascades session deletion. proof, e := s.BeginReauth(ctx, fresh, "unlink", time.Now()) must(t, e) next, hash, e := sessions.NewToken() must(t, e) now := time.Now().UTC() f.exec(t, "INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES(?,?,?,?,?,?)", hash, owner.Address, "magiclink", now.Format(time.RFC3339), now.Format(time.RFC3339), now.Add(time.Hour).Format(time.RFC3339)) _, _, e = s.CompleteReauth(ctx, proof, next, now) must(t, e) must(t, s.Unlink(ctx, proof, next, now)) if f.count(t, "SELECT count(*) FROM person_devices WHERE id=? AND revoked_at IS NOT NULL", credential.ID) != 1 { t.Fatal("device survived unlink") } if f.count(t, "SELECT count(*) FROM sessions WHERE token_hash=?", source) != 0 { t.Fatal("session survived unlink") } } func TestPersonAPINativeDeviceGates(t *testing.T) { f, _, _, _ := nativeIDFixture(t) for _, gate := range []string{"own-person", "local-session", "web-session", "bearer", "no-origin", "cross-origin", "json", "key", "duplicate-cookie", "unknown-field", "removed", "expired", "revoked"} { t.Run(gate, func(t *testing.T) { token := f.Cookies[owner.Address].Value hash := sessions.HashToken(token) body := nativeDeviceBody() want := 401 switch gate { case "own-person", "unknown-field": body = body[:len(body)-1] + `,"person":"peer@example.com"}` want = 422 case "json", "key": want = 422 case "no-origin", "cross-origin", "local-session": want = 403 } if gate == "key" { body = `{"public_key":"` + base64.RawURLEncoding.EncodeToString(make([]byte, 31)) + `","label":"phone"}` } if gate == "local-session" || gate == "web-session" { method := "magiclink" if gate == "web-session" { method = oficinaid.Method } f.exec(t, "UPDATE sessions SET method=? WHERE token_hash=?", method, hash) defer f.exec(t, "UPDATE sessions SET method=? WHERE token_hash=?", oficinaid.NativeMethod, hash) } if gate == "removed" { f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address) defer f.exec(t, "UPDATE members SET active=1 WHERE address=?", owner.Address) } if gate == "expired" { f.exec(t, "UPDATE sessions SET created_at=? WHERE token_hash=?", time.Now().Add(-8*24*time.Hour).Format(time.RFC3339), hash) defer f.exec(t, "UPDATE sessions SET created_at=? WHERE token_hash=?", time.Now().Format(time.RFC3339), hash) } if gate == "revoked" { f.exec(t, "DELETE FROM sessions WHERE token_hash=?", hash) } w := nativeDevicePost(f, body, func(r *http.Request) { switch gate { case "bearer": r.Header.Set("Authorization", "Bearer device") case "no-origin": r.Header.Del("Origin") case "cross-origin": r.Header.Set("Origin", "https://other.example") case "json": r.Header.Set("Content-Type", "text/plain") case "duplicate-cookie": r.AddCookie(f.Cookies[owner.Address]) } }) expectNativeHTTP(t, w, want) if f.count(t, "SELECT count(*) FROM person_devices") != 0 { t.Fatal("refused request allocated a device") } }) } } func TestPersonAPINativeDeviceTransactionGuards(t *testing.T) { for _, gate := range []string{"actor", "session-person", "session-method", "session-expiry", "roster", "audit"} { t.Run(gate, func(t *testing.T) { f := newFixture(t) now := time.Now().UTC() p := personapi.PersonPrincipal{Address: owner.Address, SessionHash: "verified-hash", SessionEpoch: now.Unix()} actor := owner if gate == "actor" { actor = peer } ds := &personapi.DeviceStore{Key: "fixture-native-device-key", Now: func() time.Time { return now }, Invalid: equipo.ErrInvalid, Forbidden: equipo.ErrForbidden, Write: func(c context.Context, fn func(*gorm.DB) error) error { return f.DB.G.WithContext(c).Transaction(func(tx *gorm.DB) error { if gate == "roster" { if e := tx.Exec("UPDATE members SET active=0 WHERE address=?", owner.Address).Error; e != nil { return e } } return fn(tx) }) }, NativeSession: func(tx *gorm.DB, hash string) (sessions.Session, error) { sess := sessions.Session{Subject: owner.Address, Method: oficinaid.NativeMethod, At: now} if gate == "session-person" { sess.Subject = peer.Address } if gate == "session-method" { sess.Method = "magiclink" } if gate == "session-expiry" { sess.At = now.Add(-8 * 24 * time.Hour) } return sess, nil }, Member: func(tx *gorm.DB, person string) (kernel.Member, error) { var m kernel.Member e := tx.Where("address=?", person).Take(&m).Error return m, e }, Instance: func(*gorm.DB) (string, error) { return "instance", nil }, Audit: func(*gorm.DB, kernel.Actor, string, string) error { if gate == "audit" { return errors.New("audit unavailable") } return nil }} _, err := ds.RegisterNative(personapi.WithVerifiedPrincipal(ctx, p), actor, base64.RawURLEncoding.EncodeToString(make([]byte, 32)), "phone") if err == nil { t.Fatal("native device guard accepted", gate) } if f.count(t, "SELECT count(*) FROM person_devices") != 0 { t.Fatal("failed transaction retained credential") } }) } } func TestPersonAPINativeSessionRevocation(t *testing.T) { for _, action := range []string{"session", "link", "member", "address"} { t.Run(action, func(t *testing.T) { f, _, _, _ := nativeIDFixture(t) w := nativeDevicePost(f, nativeDeviceBody(), nil) expectNativeHTTP(t, w, 200) credential := apiValue[personapi.PersonCredential](t, w) // Pending pushes and tokens go away in the same transaction. f.exec(t, "INSERT INTO push_registrations(credential,person,token) VALUES(?,?,?)", credential.ID, owner.Address, "sealed-canary") f.exec(t, "INSERT INTO push_activities(credential,task_id,person,token) VALUES(?,?,?,?)", credential.ID, "task", owner.Address, "sealed-canary") f.exec(t, "INSERT INTO push_outbox(id,credential,person,state) VALUES(?,?,?,?)", "native-push", credential.ID, owner.Address, "pending") switch action { case "session": f.exec(t, "DELETE FROM sessions WHERE token_hash=?", sessions.HashToken(f.Cookies[owner.Address].Value)) case "link": f.exec(t, "DELETE FROM home_identity_links WHERE subject=?", nativeSubject) case "member": f.exec(t, "DELETE FROM members WHERE address=?", owner.Address) case "address": f.exec(t, "UPDATE members SET address=? WHERE address=?", "renamed@example.invalid", owner.Address) } if f.count(t, "SELECT count(*) FROM person_devices WHERE id=? AND revoked_at IS NOT NULL", credential.ID) != 1 { t.Fatal("native device remained live", action) } for _, table := range []string{"push_registrations", "push_activities"} { if f.count(t, "SELECT count(*) FROM "+table+" WHERE credential=?", credential.ID) != 0 { t.Fatal("push secret survived", table) } } if f.count(t, "SELECT count(*) FROM push_outbox WHERE id='native-push' AND state='dropped'") != 1 { t.Fatal("pending push survived") } }) } } func expectNativeHTTP(t *testing.T, w *httptest.ResponseRecorder, status int) { t.Helper() if w.Code != status { t.Fatalf("native HTTP %d, want %d", w.Code, status) } } func TestPersonAPINativeLiveExchange(t *testing.T) { f, s, _, key := nativeIDFixture(t) // Both listeners bind to loopback. Home is a signing fixture; the instance // runs the production router and database over a real TLS connection. fakeHome := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var in struct { Aud string `json:"aud"` Challenge string `json:"challenge"` } if json.NewDecoder(r.Body).Decode(&in) != nil || in.Aud != nativeOrigin { w.WriteHeader(400) return } nonce, ok := handoff.NativeNonce(in.Challenge) if !ok { w.WriteHeader(400) return } id, err := assertion.RandomID() if err != nil { w.WriteHeader(500) return } now := time.Now().Unix() signed, err := assertion.Sign(key, assertion.Claims{Version: 1, KeyID: "k", Issuer: s.Config.Issuer, Audience: in.Aud, Subject: nativeSubject, ID: id, Nonce: nonce, IssuedAt: now, ExpiresAt: now + 120, AuthTime: now}) if err != nil { w.WriteHeader(500) return } w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(map[string]string{"assertion": signed}) })) defer fakeHome.Close() instance := httptest.NewTLSServer(f.Handler) defer instance.Close() verifier := base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{12}, 32)) challenge := sha256.Sum256([]byte(verifier)) input, _ := json.Marshal(map[string]string{"aud": nativeOrigin, "challenge": base64.RawURLEncoding.EncodeToString(challenge[:])}) response, err := http.Post(fakeHome.URL+"/native/v1/assert", "application/json", bytes.NewReader(input)) must(t, err) var asserted struct { Assertion string `json:"assertion"` } must(t, json.NewDecoder(response.Body).Decode(&asserted)) response.Body.Close() if response.StatusCode != 200 { t.Fatal("fake Home status", response.StatusCode) } exchange, _ := json.Marshal(oficinaid.NativeRequest{Assertion: asserted.Assertion, Verifier: verifier}) req, err := http.NewRequest("POST", instance.URL+oficinaid.NativePath, bytes.NewReader(exchange)) must(t, err) req.Host = strings.TrimPrefix(nativeOrigin, "https://") req.Header.Set("Content-Type", "application/json") response, err = instance.Client().Do(req) must(t, err) defer response.Body.Close() if response.StatusCode != 200 || len(response.Cookies()) != 0 { t.Fatal("live exchange status or cookie", response.StatusCode) } var minted oficinaid.NativeSession must(t, json.NewDecoder(response.Body).Decode(&minted)) req, err = http.NewRequest("POST", instance.URL+"/api/v1/auth/devices/native", strings.NewReader(nativeDeviceBody())) must(t, err) req.Host = strings.TrimPrefix(nativeOrigin, "https://") req.Header.Set("Content-Type", "application/json") req.Header.Set("Origin", nativeOrigin) req.AddCookie(&http.Cookie{Name: minted.Name, Value: minted.Value}) response, err = instance.Client().Do(req) must(t, err) defer response.Body.Close() if response.StatusCode != 200 { t.Fatal("live device status", response.StatusCode) } var credential personapi.PersonCredential must(t, json.NewDecoder(response.Body).Decode(&credential)) if credential.Token == "" || credential.ExpiresAt.Unix() != minted.ExpiresAt { t.Fatal("live native credential expiry") } req, err = http.NewRequest("GET", instance.URL+"/api/v1/snapshot", nil) must(t, err) req.Host = strings.TrimPrefix(nativeOrigin, "https://") req.Header.Set("Authorization", "Bearer "+credential.Token) response, err = instance.Client().Do(req) must(t, err) defer response.Body.Close() if response.StatusCode != 200 { t.Fatal("device engine status", response.StatusCode) } } // A native session's devices expire with it (7 days). Approving a paired // device from it would mint a 30-day credential that outlives the session, so // both approval routes refuse it; the person's web session still approves. func TestPersonAPINativeSessionNeverApprovesPairing(t *testing.T) { f, _, fresh, _ := nativeIDFixture(t) pub := base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{5}, 32)) c, e := f.Store.BeginPersonDevice(ctx, pub, "paired phone", "native-approve-begin") must(t, e) native := f.Cookies[owner.Address] web := &http.Cookie{Name: native.Name, Value: fresh} approve := func(cookie *http.Cookie, form bool, key string) *httptest.ResponseRecorder { var r *http.Request if form { r = httptest.NewRequest("POST", nativeOrigin+"/auth/devices/"+c.ID+"/approve", strings.NewReader("typed_code="+c.UserCode+"&request_id="+key+"&revision=1")) r.Header.Set("Content-Type", "application/x-www-form-urlencoded") } else { r = httptest.NewRequest("POST", nativeOrigin+"/api/v1/auth/devices/"+c.ID+"/approve", strings.NewReader(`{"typed_code":"`+c.UserCode+`"}`)) r.Header.Set("Content-Type", "application/json") r.Header.Set("Idempotency-Key", key) r.Header.Set("If-Match", `"1"`) } r.Header.Set("Origin", nativeOrigin) r.AddCookie(cookie) w := httptest.NewRecorder() f.Handler.ServeHTTP(w, r) return w } expectNativeHTTP(t, approve(native, false, "native-api"), 403) expectNativeHTTP(t, approve(native, true, "native-form"), 403) if f.count(t, "SELECT count(*) FROM person_devices WHERE id=? AND approved_at IS NOT NULL", c.ID) != 0 { t.Fatal("native session approved a paired device") } expectNativeHTTP(t, approve(web, false, "web-api"), 200) }