package plan3test import ( "context" "crypto/ed25519" "encoding/json" "errors" "fmt" "net/http/httptest" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/equipo" "amadan.net/oficina/equipo/internal/equipo/personapi" "gorm.io/gorm" ) func TestPersonAPIDeviceInvalidProofIsolation(t *testing.T) { f := newFixture(t) c, key := deviceChallenge(t, f) proof := signedDevice(t, f, c, key) expectHTTP(t, deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", proof, "poll", ""), 409) old := time.Now().UTC().Add(-6 * time.Second) f.exec(t, "UPDATE person_devices SET last_poll=? WHERE id=?", old, c.ID) bad := apiProof(t, proof) bad.Signature = "invalid" raw, err := json.Marshal(bad) must(t, err) for i := 0; i < 65; i++ { w := deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", string(raw), "attack", "") if i < 60 { expectHTTP(t, w, 403) } else { expectHTTP(t, w, 429) } } var row personapi.DeviceRecord must(t, f.DB.G.First(&row, "id=?", c.ID).Error) if row.LastPoll == nil || !row.LastPoll.Equal(old) { t.Fatal("invalid proof changed challenge timer") } expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/auth/devices/"+c.ID+"/approve", fmt.Sprintf(`{"typed_code":%q}`, c.UserCode), "approve", `"1"`), 200) // Even clients sharing a source must not let failed proofs throttle valid ones. expectHTTP(t, deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", proof, "legitimate", ""), 200) } func apiProof(t *testing.T, raw string) personapi.PersonDeviceProof { t.Helper() var p personapi.PersonDeviceProof must(t, json.Unmarshal([]byte(raw), &p)) return p } func TestPersonAPIDeviceApprovalPrincipal(t *testing.T) { f := newFixture(t) c, _ := deviceChallenge(t, f) err := f.Store.ApprovePersonDevice(ctx, owner, c.ID, c.UserCode, equipo.Mutation{RequestID: "missing", Revision: 1}) if !errors.Is(err, personapi.ErrUnauthenticated) { t.Fatal("approval without verified principal", err) } pctx := personapi.WithVerifiedPrincipal(ctx, personapi.PersonPrincipal{Address: peer.Address, SessionEpoch: time.Now().Unix()}) err = f.Store.ApprovePersonDevice(pctx, owner, c.ID, c.UserCode, equipo.Mutation{RequestID: "mismatch", Revision: 1}) if err == nil { t.Fatal("principal and actor mismatch approved") } } func TestPersonAPIDeviceNormalizedApproval(t *testing.T) { f := newFixture(t) c, _ := deviceChallenge(t, f) form := actionForm("approve", 1) form.Set("typed_code", " "+strings.ToLower(c.UserCode)+" ") expectHTTP(t, formPost(t, f, owner, "/auth/devices/"+c.ID+"/approve", form), 303) list := apiRequest(t, f, owner, "GET", "/api/v1/auth/devices", "", "", "") expectHTTP(t, list, 200) devices := apiValue[personapi.Page[personapi.Device]](t, list) if len(devices.Items) != 1 || !devices.Items[0].ExpiresAt.Equal(c.ExpiresAt) { t.Fatal("unexchanged device has no challenge expiry") } page := f.get(t, owner, "/auth/devices/"+c.ID) expectHTTP(t, page, 200) if strings.Contains(page.Body.String(), `name="typed_code"`) || !strings.Contains(page.Body.String(), "Device approved") { t.Fatal("approved page still offers approval", page.Body.String()) } } func TestPersonAPIDeviceWebRevocation(t *testing.T) { f := newFixture(t) cred := approvedDevice(t, f) expectHTTP(t, deviceRequest(t, f, cred.Token, "GET", "/api/v1/me", "", "", ""), 200) var row personapi.DeviceRecord must(t, f.DB.G.First(&row, "id=?", cred.ID).Error) if row.LastUsedAt == nil || time.Since(*row.LastUsedAt) > time.Minute { t.Fatal("bearer use did not record last use") } settings := f.get(t, owner, "/settings") expectHTTP(t, settings, 200) if !strings.Contains(settings.Body.String(), `href="/settings/devices"`) { t.Fatal("settings omits devices link") } page := f.get(t, owner, "/settings/devices") expectHTTP(t, page, 200) for _, want := range []string{"My phone", "Revoke device", "Requested at", "Last used", "Expires at", cred.ExpiresAt.Format(time.RFC3339)} { if !strings.Contains(page.Body.String(), want) { t.Fatal("device page omits", want) } } if page.Header().Get("Cache-Control") != "no-store" || strings.Contains(page.Body.String(), cred.Token) { t.Fatal("unsafe device page") } other := f.get(t, peer, "/settings/devices") expectHTTP(t, other, 200) if strings.Contains(other.Body.String(), cred.ID) { t.Fatal("other person's device listed") } path := "/settings/devices/" + cred.ID + "/revoke" expectHTTP(t, formPost(t, f, peer, path, actionForm("other", 3)), 404) r := httptest.NewRequest("POST", path, strings.NewReader(actionForm("csrf", 3).Encode())) r.AddCookie(f.Cookies[owner.Address]) r.Header.Set("Content-Type", "application/x-www-form-urlencoded") r.Header.Set("Origin", "https://evil.example") w := httptest.NewRecorder() f.Handler.ServeHTTP(w, r) expectHTTP(t, w, 403) expectHTTP(t, deviceRequest(t, f, cred.Token, "GET", "/api/v1/me", "", "", ""), 200) expectHTTP(t, formPost(t, f, owner, path, actionForm("web-revoke", 3)), 303) expectHTTP(t, deviceRequest(t, f, cred.Token, "GET", "/api/v1/me", "", "", ""), 401) if f.count(t, "SELECT count(*) FROM audit_events WHERE kind='person_device.revoke' AND record_id=?", cred.ID) != 1 { t.Fatal("missing revoke audit") } } func TestPersonAPIDeviceExchangeLostRace(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) f.exec(t, `CREATE TRIGGER ignore_exchange BEFORE UPDATE OF token_hash ON person_devices BEGIN SELECT RAISE(IGNORE); END`) w := deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", signedDevice(t, f, c, key), "exchange", "") if w.Code < 400 || strings.Contains(w.Body.String(), `"token":`) { t.Fatal("lost exchange race returned an unstored token") } if f.count(t, "SELECT count(*) FROM audit_events WHERE kind='person_device.exchange'") != 0 { t.Fatal("lost race audited exchange") } } func TestPersonAPIDeviceCleanupBounded(t *testing.T) { f := newFixture(t) cred := approvedDevice(t, f) old := time.Now().Add(-time.Hour) f.exec(t, "UPDATE person_devices SET expires_at=? WHERE id=?", old, cred.ID) rows := make([]personapi.DeviceRecord, 206) for i := range rows { rows[i] = personapi.DeviceRecord{ID: fmt.Sprint(i), RequestHash: fmt.Sprint(i), ExpiresAt: old, Revision: 1} } rows[205].ExpiresAt = time.Now().Add(time.Hour) must(t, f.DB.G.Create(&rows).Error) // Retain approved and revoked history, even if exchange never completed. f.exec(t, "UPDATE person_devices SET approved_at=? WHERE id='0'", old) f.exec(t, "UPDATE person_devices SET revoked_at=? WHERE id='1'", old) maintenance := personapi.DeviceStore{Now: time.Now, Write: func(c context.Context, fn func(*gorm.DB) error) error { return f.DB.G.WithContext(c).Transaction(fn) }} must(t, maintenance.Sweep(ctx)) n := f.count(t, "SELECT count(*) FROM person_devices WHERE approved_at IS NULL AND revoked_at IS NULL") if n != 104 { t.Fatal("cleanup must remove at most 100 abandoned challenges", n) } must(t, maintenance.Sweep(ctx)) must(t, maintenance.Sweep(ctx)) if f.count(t, "SELECT count(*) FROM person_devices") != 4 { t.Fatal("cleanup removed history or retained abandoned challenges") } expectHTTP(t, deviceRequest(t, f, cred.Token, "GET", "/api/v1/me", "", "", ""), 200) } func TestPersonAPIAuthAudiencesRealDevice(t *testing.T) { f := newFixture(t) cred := approvedDevice(t, f) c, key := deviceChallenge(t, f) expectHTTP(t, deviceRequest(t, f, c.DeviceSecret, "GET", "/api/v1/me", "", "", ""), 401) expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/auth/devices/"+c.ID+"/approve", fmt.Sprintf(`{"typed_code":%q}`, c.UserCode), "approve-second", `"1"`), 200) c.DeviceSecret = cred.Token expectHTTP(t, deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", signedDevice(t, f, c, ed25519.PrivateKey(key)), "wrong-audience", ""), 403) }