| 1 | package plan3test |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/ed25519" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "net/http/httptest" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/equipo" |
| 15 | "amadan.net/oficina/equipo/internal/equipo/personapi" |
| 16 | "gorm.io/gorm" |
| 17 | ) |
| 18 | |
| 19 | func TestPersonAPIDeviceInvalidProofIsolation(t *testing.T) { |
| 20 | f := newFixture(t) |
| 21 | c, key := deviceChallenge(t, f) |
| 22 | proof := signedDevice(t, f, c, key) |
| 23 | expectHTTP(t, deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", proof, "poll", ""), 409) |
| 24 | old := time.Now().UTC().Add(-6 * time.Second) |
| 25 | f.exec(t, "UPDATE person_devices SET last_poll=? WHERE id=?", old, c.ID) |
| 26 | bad := apiProof(t, proof) |
| 27 | bad.Signature = "invalid" |
| 28 | raw, err := json.Marshal(bad) |
| 29 | must(t, err) |
| 30 | for i := 0; i < 65; i++ { |
| 31 | w := deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", string(raw), "attack", "") |
| 32 | if i < 60 { |
| 33 | expectHTTP(t, w, 403) |
| 34 | } else { |
| 35 | expectHTTP(t, w, 429) |
| 36 | } |
| 37 | } |
| 38 | var row personapi.DeviceRecord |
| 39 | must(t, f.DB.G.First(&row, "id=?", c.ID).Error) |
| 40 | if row.LastPoll == nil || !row.LastPoll.Equal(old) { |
| 41 | t.Fatal("invalid proof changed challenge timer") |
| 42 | } |
| 43 | expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/auth/devices/"+c.ID+"/approve", fmt.Sprintf(`{"typed_code":%q}`, c.UserCode), "approve", `"1"`), 200) |
| 44 | // Even clients sharing a source must not let failed proofs throttle valid ones. |
| 45 | expectHTTP(t, deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", proof, "legitimate", ""), 200) |
| 46 | } |
| 47 | func apiProof(t *testing.T, raw string) personapi.PersonDeviceProof { |
| 48 | t.Helper() |
| 49 | var p personapi.PersonDeviceProof |
| 50 | must(t, json.Unmarshal([]byte(raw), &p)) |
| 51 | return p |
| 52 | } |
| 53 | func TestPersonAPIDeviceApprovalPrincipal(t *testing.T) { |
| 54 | f := newFixture(t) |
| 55 | c, _ := deviceChallenge(t, f) |
| 56 | err := f.Store.ApprovePersonDevice(ctx, owner, c.ID, c.UserCode, equipo.Mutation{RequestID: "missing", Revision: 1}) |
| 57 | if !errors.Is(err, personapi.ErrUnauthenticated) { |
| 58 | t.Fatal("approval without verified principal", err) |
| 59 | } |
| 60 | pctx := personapi.WithVerifiedPrincipal(ctx, personapi.PersonPrincipal{Address: peer.Address, SessionEpoch: time.Now().Unix()}) |
| 61 | err = f.Store.ApprovePersonDevice(pctx, owner, c.ID, c.UserCode, equipo.Mutation{RequestID: "mismatch", Revision: 1}) |
| 62 | if err == nil { |
| 63 | t.Fatal("principal and actor mismatch approved") |
| 64 | } |
| 65 | } |
| 66 | func TestPersonAPIDeviceNormalizedApproval(t *testing.T) { |
| 67 | f := newFixture(t) |
| 68 | c, _ := deviceChallenge(t, f) |
| 69 | form := actionForm("approve", 1) |
| 70 | form.Set("typed_code", " "+strings.ToLower(c.UserCode)+" ") |
| 71 | expectHTTP(t, formPost(t, f, owner, "/auth/devices/"+c.ID+"/approve", form), 303) |
| 72 | list := apiRequest(t, f, owner, "GET", "/api/v1/auth/devices", "", "", "") |
| 73 | expectHTTP(t, list, 200) |
| 74 | devices := apiValue[personapi.Page[personapi.Device]](t, list) |
| 75 | if len(devices.Items) != 1 || !devices.Items[0].ExpiresAt.Equal(c.ExpiresAt) { |
| 76 | t.Fatal("unexchanged device has no challenge expiry") |
| 77 | } |
| 78 | page := f.get(t, owner, "/auth/devices/"+c.ID) |
| 79 | expectHTTP(t, page, 200) |
| 80 | if strings.Contains(page.Body.String(), `name="typed_code"`) || !strings.Contains(page.Body.String(), "Device approved") { |
| 81 | t.Fatal("approved page still offers approval", page.Body.String()) |
| 82 | } |
| 83 | } |
| 84 | func TestPersonAPIDeviceWebRevocation(t *testing.T) { |
| 85 | f := newFixture(t) |
| 86 | cred := approvedDevice(t, f) |
| 87 | expectHTTP(t, deviceRequest(t, f, cred.Token, "GET", "/api/v1/me", "", "", ""), 200) |
| 88 | var row personapi.DeviceRecord |
| 89 | must(t, f.DB.G.First(&row, "id=?", cred.ID).Error) |
| 90 | if row.LastUsedAt == nil || time.Since(*row.LastUsedAt) > time.Minute { |
| 91 | t.Fatal("bearer use did not record last use") |
| 92 | } |
| 93 | settings := f.get(t, owner, "/settings") |
| 94 | expectHTTP(t, settings, 200) |
| 95 | if !strings.Contains(settings.Body.String(), `href="/settings/devices"`) { |
| 96 | t.Fatal("settings omits devices link") |
| 97 | } |
| 98 | page := f.get(t, owner, "/settings/devices") |
| 99 | expectHTTP(t, page, 200) |
| 100 | for _, want := range []string{"My phone", "Revoke device", "Requested at", "Last used", "Expires at", cred.ExpiresAt.Format(time.RFC3339)} { |
| 101 | if !strings.Contains(page.Body.String(), want) { |
| 102 | t.Fatal("device page omits", want) |
| 103 | } |
| 104 | } |
| 105 | if page.Header().Get("Cache-Control") != "no-store" || strings.Contains(page.Body.String(), cred.Token) { |
| 106 | t.Fatal("unsafe device page") |
| 107 | } |
| 108 | other := f.get(t, peer, "/settings/devices") |
| 109 | expectHTTP(t, other, 200) |
| 110 | if strings.Contains(other.Body.String(), cred.ID) { |
| 111 | t.Fatal("other person's device listed") |
| 112 | } |
| 113 | path := "/settings/devices/" + cred.ID + "/revoke" |
| 114 | expectHTTP(t, formPost(t, f, peer, path, actionForm("other", 3)), 404) |
| 115 | r := httptest.NewRequest("POST", path, strings.NewReader(actionForm("csrf", 3).Encode())) |
| 116 | r.AddCookie(f.Cookies[owner.Address]) |
| 117 | r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 118 | r.Header.Set("Origin", "https://evil.example") |
| 119 | w := httptest.NewRecorder() |
| 120 | f.Handler.ServeHTTP(w, r) |
| 121 | expectHTTP(t, w, 403) |
| 122 | expectHTTP(t, deviceRequest(t, f, cred.Token, "GET", "/api/v1/me", "", "", ""), 200) |
| 123 | expectHTTP(t, formPost(t, f, owner, path, actionForm("web-revoke", 3)), 303) |
| 124 | expectHTTP(t, deviceRequest(t, f, cred.Token, "GET", "/api/v1/me", "", "", ""), 401) |
| 125 | if f.count(t, "SELECT count(*) FROM audit_events WHERE kind='person_device.revoke' AND record_id=?", cred.ID) != 1 { |
| 126 | t.Fatal("missing revoke audit") |
| 127 | } |
| 128 | } |
| 129 | func TestPersonAPIDeviceExchangeLostRace(t *testing.T) { |
| 130 | f := newFixture(t) |
| 131 | c, key := deviceChallenge(t, f) |
| 132 | expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/auth/devices/"+c.ID+"/approve", fmt.Sprintf(`{"typed_code":%q}`, c.UserCode), "approve", `"1"`), 200) |
| 133 | f.exec(t, `CREATE TRIGGER ignore_exchange BEFORE UPDATE OF token_hash ON person_devices BEGIN SELECT RAISE(IGNORE); END`) |
| 134 | w := deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", signedDevice(t, f, c, key), "exchange", "") |
| 135 | if w.Code < 400 || strings.Contains(w.Body.String(), `"token":`) { |
| 136 | t.Fatal("lost exchange race returned an unstored token") |
| 137 | } |
| 138 | if f.count(t, "SELECT count(*) FROM audit_events WHERE kind='person_device.exchange'") != 0 { |
| 139 | t.Fatal("lost race audited exchange") |
| 140 | } |
| 141 | } |
| 142 | func TestPersonAPIDeviceCleanupBounded(t *testing.T) { |
| 143 | f := newFixture(t) |
| 144 | cred := approvedDevice(t, f) |
| 145 | old := time.Now().Add(-time.Hour) |
| 146 | f.exec(t, "UPDATE person_devices SET expires_at=? WHERE id=?", old, cred.ID) |
| 147 | rows := make([]personapi.DeviceRecord, 206) |
| 148 | for i := range rows { |
| 149 | rows[i] = personapi.DeviceRecord{ID: fmt.Sprint(i), RequestHash: fmt.Sprint(i), ExpiresAt: old, Revision: 1} |
| 150 | } |
| 151 | rows[205].ExpiresAt = time.Now().Add(time.Hour) |
| 152 | must(t, f.DB.G.Create(&rows).Error) |
| 153 | // Retain approved and revoked history, even if exchange never completed. |
| 154 | f.exec(t, "UPDATE person_devices SET approved_at=? WHERE id='0'", old) |
| 155 | f.exec(t, "UPDATE person_devices SET revoked_at=? WHERE id='1'", old) |
| 156 | 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) }} |
| 157 | must(t, maintenance.Sweep(ctx)) |
| 158 | n := f.count(t, "SELECT count(*) FROM person_devices WHERE approved_at IS NULL AND revoked_at IS NULL") |
| 159 | if n != 104 { |
| 160 | t.Fatal("cleanup must remove at most 100 abandoned challenges", n) |
| 161 | } |
| 162 | must(t, maintenance.Sweep(ctx)) |
| 163 | must(t, maintenance.Sweep(ctx)) |
| 164 | if f.count(t, "SELECT count(*) FROM person_devices") != 4 { |
| 165 | t.Fatal("cleanup removed history or retained abandoned challenges") |
| 166 | } |
| 167 | expectHTTP(t, deviceRequest(t, f, cred.Token, "GET", "/api/v1/me", "", "", ""), 200) |
| 168 | } |
| 169 | func TestPersonAPIAuthAudiencesRealDevice(t *testing.T) { |
| 170 | f := newFixture(t) |
| 171 | cred := approvedDevice(t, f) |
| 172 | c, key := deviceChallenge(t, f) |
| 173 | expectHTTP(t, deviceRequest(t, f, c.DeviceSecret, "GET", "/api/v1/me", "", "", ""), 401) |
| 174 | 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) |
| 175 | c.DeviceSecret = cred.Token |
| 176 | expectHTTP(t, deviceRequest(t, f, "", "POST", "/api/v1/auth/devices/exchange", signedDevice(t, f, c, ed25519.PrivateKey(key)), "wrong-audience", ""), 403) |
| 177 | } |
| 178 | |