package plan3test import ( "context" "crypto/ed25519" "crypto/rand" "encoding/base64" "encoding/json" "fmt" "gorm.io/gorm" "net/http/httptest" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/personapi" ) func deviceRequest(t *testing.T, f *fixture, token, method, path, body, key, rev string) *httptest.ResponseRecorder { t.Helper() r := httptest.NewRequest(method, path, strings.NewReader(body)) r.RemoteAddr = "127.0.0.1:1234" r.Header.Set("Content-Type", "application/json") r.Header.Set("Idempotency-Key", key) if rev != "" { r.Header.Set("If-Match", rev) } if token != "" { r.Header.Set("Authorization", "Bearer "+token) } w := httptest.NewRecorder() f.Handler.ServeHTTP(w, r) return w } func deviceChallenge(t *testing.T, f *fixture) (personapi.PersonDeviceChallenge, ed25519.PrivateKey) { t.Helper() pub, key, err := ed25519.GenerateKey(rand.Reader) must(t, err) body := fmt.Sprintf(`{"public_key":%q,"label":"My phone"}`, base64.RawURLEncoding.EncodeToString(pub)) w := deviceRequest(t, f, "", "POST", "/api/v1/auth/devices", body, rand.Text(), "") expectHTTP(t, w, 200) c := apiValue[personapi.PersonDeviceChallenge](t, w) if c.ID == "" || c.DeviceSecret == "" || c.UserCode == "" || c.Challenge == "" || c.PollIntervalSeconds != 5 { t.Fatal("incomplete device challenge", c) } return c, key } func signedDevice(t *testing.T, f *fixture, c personapi.PersonDeviceChallenge, key ed25519.PrivateKey) string { t.Helper() p := personapi.PersonDeviceProof{ID: c.ID, DeviceSecret: c.DeviceSecret, Challenge: c.Challenge, Nonce: rand.Text()} p.Signature = base64.RawURLEncoding.EncodeToString(ed25519.Sign(key, personapi.DeviceProofMessage(f.TeamID, p))) b, err := json.Marshal(p) must(t, err) return string(b) } func approvedDevice(t *testing.T, f *fixture) personapi.PersonCredential { t.Helper() c, key := deviceChallenge(t, f) w := apiRequest(t, f, owner, "POST", "/api/v1/auth/devices/"+c.ID+"/approve", fmt.Sprintf(`{"typed_code":%q}`, c.UserCode), "approve", `"1"`) expectHTTP(t, w, 200) w = deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", signedDevice(t, f, c, key), "exchange", "") expectHTTP(t, w, 200) return apiValue[personapi.PersonCredential](t, w) } func TestPersonAPIDeviceApproval(t *testing.T) { f := newFixture(t) c, key := deviceChallenge(t, f) page := f.get(t, owner, "/auth/devices/"+c.ID) expectHTTP(t, page, 200) if !strings.Contains(page.Body.String(), "My phone") || !strings.Contains(page.Body.String(), c.ExpiresAt.Add(-10*time.Minute).Format(time.RFC3339)) { t.Fatal("approval omits label or server creation time", page.Body.String()) } if strings.Contains(page.Body.String(), c.UserCode) || strings.Contains(page.Body.String(), c.DeviceSecret) { t.Fatal("approval prefills secret or code") } path := "/api/v1/auth/devices/" + c.ID + "/approve" expectHTTP(t, apiRequest(t, f, owner, "POST", path, `{}`, "missing", `"1"`), 422) expectHTTP(t, apiRequest(t, f, owner, "POST", path+"?typed_code="+c.UserCode, `{}`, "link", `"1"`), 422) expectHTTP(t, apiRequest(t, f, owner, "POST", path, fmt.Sprintf(`{"typed_code":%q}`, c.UserCode), "approve", `"1"`), 200) proof := signedDevice(t, f, c, key) w := deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", proof, "exchange", "") expectHTTP(t, w, 200) cred := apiValue[personapi.PersonCredential](t, w) if cred.Audience != "equipo.person.v1" || cred.InstanceID != f.TeamID { t.Fatal("wrong credential binding", cred) } replay := deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", proof, "exchange", "") expectHTTP(t, replay, 200) if replay.Body.String() != w.Body.String() { t.Fatal("lost response replay minted a new credential") } expectHTTP(t, deviceRequest(t, f, cred.Token, "GET", "/api/v1/me", "", "", ""), 200) list := deviceRequest(t, f, cred.Token, "GET", "/api/v1/auth/devices", "", "", "") expectHTTP(t, list, 200) for _, secret := range []string{cred.Token, c.DeviceSecret, c.UserCode, c.Challenge, "token_hash", "public_key", "result_cipher"} { if strings.Contains(list.Body.String(), secret) { t.Fatal("private device field leaked", secret) } } expectHTTP(t, deviceRequest(t, f, cred.Token, "POST", path, fmt.Sprintf(`{"typed_code":%q}`, c.UserCode), "bearer-approval", `"1"`), 401) expectHTTP(t, deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", signedDevice(t, f, c, key), "new-nonce", ""), 403) expectHTTP(t, deviceRequest(t, f, cred.Token, "DELETE", "/api/v1/auth/devices/"+cred.ID, `{}`, "revoke", `"3"`), 200) expectHTTP(t, deviceRequest(t, f, cred.Token, "GET", "/api/v1/me", "", "", ""), 401) } func TestPersonAPIDeviceGuards(t *testing.T) { for _, kind := range []string{"key", "challenge", "expiry", "epoch", "removed", "audience"} { t.Run(kind, func(t *testing.T) { f := newFixture(t) c, key := deviceChallenge(t, f) expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/auth/devices/"+c.ID+"/approve", fmt.Sprintf(`{"typed_code":%q}`, c.UserCode), "approve", `"1"`), 200) switch kind { case "key": _, key, _ = ed25519.GenerateKey(rand.Reader) case "challenge": c.Challenge = "wrong" case "expiry": f.exec(t, "UPDATE person_devices SET expires_at=? WHERE id=?", time.Now().Add(-time.Hour), c.ID) case "epoch": f.exec(t, "UPDATE members SET session_epoch=? WHERE address=?", time.Now().Add(time.Hour).Unix(), owner.Address) case "removed": f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address) case "audience": c.DeviceSecret = "equipo.runner.v2.secret" } w := deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", signedDevice(t, f, c, key), "exchange", "") if w.Code < 400 { t.Fatal("device guard bypassed", kind, w.Body.String()) } }) } } func TestPersonAPIBrowserCSRFRealDevice(t *testing.T) { f := newFixture(t) c := approvedDevice(t, f) expectHTTP(t, deviceRequest(t, f, c.Token, "POST", "/api/v1/conversation/messages", `{"body":"native"}`, "native", ""), 200) r := httptest.NewRequest("POST", "/api/v1/conversation/messages", strings.NewReader(`{"body":"cross"}`)) r.Header.Set("Authorization", "Bearer "+c.Token) r.Header.Set("Origin", "https://evil.example") r.Header.Set("Content-Type", "application/json") r.Header.Set("Idempotency-Key", "cross") w := httptest.NewRecorder() f.Handler.ServeHTTP(w, r) expectHTTP(t, w, 403) r.Header.Set("Origin", origin) r.AddCookie(f.Cookies[owner.Address]) w = httptest.NewRecorder() f.Handler.ServeHTTP(w, r) expectHTTP(t, w, 401) f.exec(t, "UPDATE members SET session_epoch=? WHERE address=?", time.Now().Add(time.Hour).Unix(), owner.Address) expectHTTP(t, deviceRequest(t, f, c.Token, "GET", "/api/v1/me", "", "", ""), 401) } var _ = equipo.Mutation{} func TestPersonAPIDeviceThrottleAndExpiry(t *testing.T) { f := newFixture(t) c, key := deviceChallenge(t, f) path := "/api/v1/auth/devices/" + c.ID + "/approve" expectHTTP(t, apiRequest(t, f, owner, "POST", path, `{"typed_code":"WRONG123"}`, "wrong", `"1"`), 403) proof := signedDevice(t, f, c, key) expectHTTP(t, deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", proof, "poll", ""), 409) expectHTTP(t, deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", proof, "poll", ""), 429) expectHTTP(t, apiRequest(t, f, owner, "POST", path, fmt.Sprintf(`{"typed_code":%q}`, c.UserCode), "approve", `"1"`), 200) f.exec(t, "UPDATE person_devices SET last_poll=? WHERE id=?", time.Now().Add(-6*time.Second), c.ID) w := deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", proof, "poll", "") expectHTTP(t, w, 200) cred := apiValue[personapi.PersonCredential](t, w) var saved string must(t, f.DB.Writer().QueryRow("SELECT token_hash||secret_hash||code_hash||result_cipher||begin_cipher FROM person_devices WHERE id=?", c.ID).Scan(&saved)) for _, secret := range []string{cred.Token, c.DeviceSecret, c.UserCode} { if strings.Contains(saved, secret) { t.Fatal("credential stored in plaintext") } } f.exec(t, "UPDATE person_devices SET result_expires_at=? WHERE id=?", time.Now().Add(-time.Second), c.ID) expectHTTP(t, deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", proof, "poll", ""), 410) if f.count(t, "SELECT count(*) FROM person_devices WHERE id=? AND result_cipher<>''", c.ID) != 0 { t.Fatal("expired replay result retained") } f.exec(t, "UPDATE person_devices SET token_expires_at=? WHERE id=?", time.Now().Add(-time.Second), c.ID) expectHTTP(t, deviceRequest(t, f, cred.Token, "GET", "/api/v1/me", "", "", ""), 401) for i := 0; i < 9; i++ { deviceChallenge(t, f) } pub, _, err := ed25519.GenerateKey(rand.Reader) must(t, err) expectHTTP(t, deviceRequest(t, f, "", "POST", "/api/v1/auth/devices", fmt.Sprintf(`{"public_key":%q,"label":"extra"}`, base64.RawURLEncoding.EncodeToString(pub)), "extra", ""), 429) } func TestPersonAPIDeviceIdleExpiry(t *testing.T) { f := newFixture(t) cred := approvedDevice(t, f) f.exec(t, "UPDATE person_devices SET result_expires_at=? WHERE id=?", time.Now().Add(-time.Second), cred.ID) maintenance := personapi.DeviceStore{Now: time.Now, Write: func(ctx context.Context, fn func(*gorm.DB) error) error { return f.DB.G.WithContext(ctx).Transaction(fn) }} must(t, maintenance.Sweep(ctx)) if f.count(t, "SELECT count(*) FROM person_devices WHERE id=? AND result_cipher<>''", cred.ID) != 0 { t.Fatal("idle expired replay result retained") } expectHTTP(t, deviceRequest(t, f, cred.Token, "GET", "/api/v1/me", "", "", ""), 200) }