fix: harden device throttling and add web device revocation
27 files changed,
+810
−128
.rastrillo/budgets.txt+1 −1docs/api/equipo-v1.openapi.json+13 −3docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+102 −0internal/equipo/app.go+5 −3internal/equipo/copy.go+25 −0internal/equipo/handlers.go+1 −0internal/equipo/kernel/cursor.go+9 −2internal/equipo/migrations/0030_person_devices_usage.sql+1 −0internal/equipo/migrations/schema.sql+1 −0internal/equipo/person_api.go+3 −41internal/equipo/person_devices.go+12 −8internal/equipo/personapi/auth.go+48 −5internal/equipo/personapi/device_browser.go+47 −0internal/equipo/personapi/device_keys_test.go+74 −0internal/equipo/personapi/devices.go+60 −53internal/equipo/personapi/extended_reads.go+1 −1internal/equipo/personapi/extended_types.go+2 −2internal/equipo/personapi/handler.go+26 −4internal/equipo/render.go+1 −1internal/equipo/store.go+1 −1internal/equipo/templates/person_device.html+3 −1internal/equipo/templates/person_devices.html+21 −0internal/equipo/templates/settings.html+1 −0internal/plan3test/person_api_key_source_fixes_test.go+89 −0internal/plan3test/person_api_migration_test.go+29 −2internal/plan3test/person_api_owner_test.go+57 −0internal/plan3test/person_device_fixes_test.go+177 −0
CI failed — run details
Intent
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index eeecc7df..0937d332 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -28,4 +28,4 @@ time internal/runner/provider/codex 15s Task 11a full branch gate measured 11.65 |
| time internal/directlive 360s Task 5 adds both coordinator policy cases to the fake certification matrix. The targeted 19-case fixture measured 287.275s; 360s leaves 25 percent headroom for namespaces, both adapters, journal, MCP probes and package siblings. Full-package timing is deferred by the targeted-only dispatch. |
| time internal/plan3test 300s Initial cap for combined browser and runner acceptance; measure at both usable stops. |
| -size internal/plan3test - 9500 Task 20 adds real device proof, API contract, owner rollback, shared-operation and privacy regressions in the mandated integration package. Measured 9342 test lines; targeted person API tests take 11.287s within the unchanged 300s time ceiling. |
| +size internal/plan3test - 10000 Task 20 fix round 1 adds invalid-proof isolation, browser revocation, purpose-key, runner scope, migration, decision-owner and API budget-admission regressions in the mandated integration package. Measured 9692 test lines; the final targeted API gate measured 15.826s. The 300s time ceiling is unchanged. |
diff --git a/docs/api/equipo-v1.openapi.json b/docs/api/equipo-v1.openapi.json| index 10a846a8..de3aed0e 100644 |
| --- a/docs/api/equipo-v1.openapi.json |
| +++ b/docs/api/equipo-v1.openapi.json |
| @@ -10450,8 +10450,6 @@ |
| "id", |
| "label", |
| "revision", |
| - "created_at", |
| - "last_seen", |
| "revoked_at" |
| ], |
| "type": "object" |
| @@ -10782,6 +10780,17 @@ |
| "type": "null" |
| } |
| ] |
| + }, |
| + "last_used_at": { |
| + "anyOf": [ |
| + { |
| + "format": "date-time", |
| + "type": "string" |
| + }, |
| + { |
| + "type": "null" |
| + } |
| + ] |
| } |
| }, |
| "required": [ |
| @@ -10790,7 +10799,8 @@ |
| "created_at", |
| "expires_at", |
| "revoked_at", |
| - "revision" |
| + "revision", |
| + "last_used_at" |
| ], |
| "type": "object" |
| }, |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index e0d69acd..dbab418f 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -4527,3 +4527,105 @@ Measured root source: 10795/10800, with the original ceiling retained by extract |
| Implementation subject: `feat: complete the versioned person API contract`, author `codex <codex~paul@keymail.dev>`. |
| Idle-expiry follow-up: `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPersonAPIDeviceIdleExpiry$' -count=1` first exited 1 because Sweep was undefined. After implementation it passed in 0.578s. Its independent cleanup mutation failed at the retained-ciphertext assertion and was restored. The existing application background group owns and stops the sweep; no server was started in this task. |
| + |
| + |
| +## Fix round 1 |
| + |
| +Task 20 status: DONE_WITH_CONCERNS. The requested review fixes are implemented and verified offline. Copy remains pending the controller's review. Commit subject: `fix: harden device throttling and add web device revocation`; author: `codex <codex~paul@keymail.dev>`. Nothing was pushed. |
| + |
| +### Changes |
| + |
| +Device creation now uses Rastrillo v0.30.1's `clientip.From`. Its trust policy matches Rastrillo auth: one trusted hop when `carlos.Running()` is true, zero otherwise. Forwarded addresses are selected from the right. Tests cover two clients behind the CARLOS edge, forged leading addresses, and ignored forwarded headers off CARLOS. Other reverse-proxy deployments still use the socket peer unless their deployment trust policy is explicitly extended; arbitrary forwarded headers are not trusted. |
| + |
| +Only a valid key-bound proof can advance a challenge's five-second polling clock. Invalid proofs consume a source-only limit of 60 per minute and never change challenge counters or timestamps. The redundant 12-per-minute challenge bucket is removed. The attack test sends 65 invalid proofs against a known ID, confirms its prior timestamp is unchanged, then exchanges a valid proof successfully from the same source. Valid lost-response replay retains its existing nonce and expiry checks. |
| + |
| +The scriptless `/settings/devices` page is linked from settings. It lists only the current person's device labels, creation times, last use and expiry, with CSRF-protected POST revocation through `RevokePersonDevice`. Tests cover cross-person access, cross-origin rejection, no-store, secret omission, the audit event, and immediate bearer rejection after web revocation. Last successful bearer authentication is stored in nullable `last_used_at`; unknown use is shown as not used yet. Approved devices that have not exchanged show their challenge expiry instead of the zero time. Successful HTML approval replaces the form with an approved state. |
| + |
| +Approval now requires a matching verified browser principal and uses its session epoch without fallback. Typed codes are trimmed and uppercased before comparison. Exchange checks `RowsAffected == 1`; a trigger that discards the guarded update cannot produce an unstored token or an exchange audit. Cleanup deletes at most 100 expired challenges per sweep when they have no approval, exchange or revocation history. Approved, exchanged and revoked rows remain for audit, including approved requests that were never exchanged. Ciphertext expiry cleanup remains in place. |
| + |
| +Cursor sealing, device HMAC and encrypted results now use separate HKDF-SHA256 purposes. Tests independently derive each key, check the resulting ciphertext/HMAC, reject cross-purpose decryption, and send a real legacy cursor through the API to require HTTP 410. Real audience tests present a device secret as a person bearer (401) and a person bearer as the secret in a correctly signed device exchange (403). |
| + |
| +Runner reads now filter by both person and instance. Unsupported `created_at` and `last_seen` fields are omitted, and OpenAPI no longer requires them. Device responses document nullable `last_used_at`. Roster and budget validation, authority and conflict responses have their own pending copy keys while retaining the existing status codes and current-revision behavior. |
| + |
| +The owner tests now exercise both missing cases through PUT. Team-role demotion preserves project decision assignments; deactivation of an assigned decision owner is refused with the existing 409 conflict and leaves the member unchanged. A budget lowered through PUT is synchronized to the attached execution core, preserves already reserved usage and refuses the next claim with `team.ErrBudget`. |
| + |
| +Migration `0030_person_devices_usage.sql` adds only nullable `last_used_at`. It follows the existing 0030 device migration and leaves 0031 available for Task 19. Tests cover both pre-device upgrade/reopen and an already-installed 0030 database with retained device history. The schema snapshot matches the models. |
| + |
| +The route authentication implementation moved unchanged from the root adapter into `personapi.Authenticator.AuthenticateRoute`; the root still supplies current membership and verified-cookie callbacks. This keeps the root at 10,789 source lines within its unchanged 10,800 ceiling. Integration tests measure 9,692 lines, so their existing exception rises from 9,500 to 10,000. The 300-second time ceiling is unchanged. |
| + |
| +### Test-first and development evidence |
| + |
| +Before the implementation changes, this command exited 1: |
| + |
| +`CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPersonAPI(Device(InvalidProofIsolation|ApprovalPrincipal|NormalizedApproval|WebRevocation|ExchangeLostRace|CleanupBounded)|AuthAudiencesRealDevice|Owner(DecisionOwners|BudgetNextAdmission))$' -count=1` |
| + |
| +It reproduced premature 429 responses to invalid proofs, approval without a principal, rejected normalized codes, the missing settings link, an unstored exchange token, 203 retained abandoned challenges, and generic budget copy. The initial decision-owner expectation was corrected from 403 to the established 409 contract; protection itself already worked. Budget admission protection also already worked and is now covered through PUT. |
| + |
| +A preliminary compile failure used a nonexistent `job.Spec` fixture field; the fixture now constructs the second job from the returned job's public fields. The first implementation run found the new template missing from the explicit template registry; registration fixed the panic. The same regression command then passed in 2.485s. Follow-up tests cover proxy trust, real purpose keys, legacy cursor rejection, instance-filtered runners, pre-exchange expiry and additive last-use migration. |
| + |
| +The first size gate failed at 10,840 root source lines and 9,658 integration-test lines. Route-auth extraction restored the root limit; the final measured integration exception includes the additional migration test. No production guard was weakened to satisfy a test. |
| + |
| +### Final verification |
| + |
| +All final commands below exited 0: |
| + |
| +- `CGO_ENABLED=0 go test ./internal/equipo/personapi ./internal/equipo/kernel ./internal/plan3test -run '^(TestPersonAPI|TestCursorScopeIntegrityAndExpiry)' -count=1`: personapi 0.011s, kernel 0.008s, plan3test 15.826s. Includes the Task 10 API regressions and every new fix test. |
| +- The required Task 20 operation prefix, extended with `LegacyCursor|RunnerInstance`, passed before final extraction: `CGO_ENABLED=0 go test ./internal/equipo/personapi ./internal/plan3test -run '^TestPersonAPI(Contract|Shared|Native|Pagination|Schema|Device|Owner|BrowserCSRF|AuthAudiences|LegacyCursor|RunnerInstance)' -count=1`: personapi 0.004s, plan3test 8.341s. The final command above includes all of these tests. |
| +- `make migration-check`: its targeted `CGO_ENABLED=0 go test ./internal/equipo -run '^TestMigrationModels$' -count=1` passed in 0.337s. |
| +- `CGO_ENABLED=0 make budget`: all 34 directories within budget. |
| +- `CGO_ENABLED=0 go vet ./internal/equipo ./internal/equipo/kernel ./internal/equipo/personapi ./internal/plan3test`: no findings. |
| +- `CGO_ENABLED=0 go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./internal/equipo ./internal/equipo/kernel ./internal/equipo/personapi ./internal/plan3test`: no findings. |
| +- `gofmt -l internal/equipo/*.go internal/equipo/personapi/*.go internal/equipo/kernel/*.go internal/plan3test/*.go`: no output. |
| +- `git diff --check`: no findings. |
| + |
| +### Independent guard mutations |
| + |
| +Each mutation ran alone and exited 1 at an assertion. Every changed file was restored byte-for-byte in a finally block. The final passing tests above ran after all sixteen restorations. |
| + |
| +| Mutation | Command | Failure | |
| +| --- | --- | --- | |
| +| invalid-proof-timer | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPIDeviceInvalidProofIsolation$ -count=1` | `person_device_fixes_test.go:41: invalid proof changed challenge timer` | |
| +| valid-proof-source-bucket | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPIDeviceInvalidProofIsolation$ -count=1` | `person_device_fixes_test.go:33: HTTP 429, want 403` | |
| +| trusted-proxy | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPIDeviceTrustedProxySource$ -count=1` | `person_api_key_source_fixes_test.go:50: HTTP 429, want 200` | |
| +| verified-approval | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPIDeviceApprovalPrincipal$ -count=1` | `person_device_fixes_test.go:58: approval without verified principal <nil>` | |
| +| exchange-row-guard | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPIDeviceExchangeLostRace$ -count=1` | `person_device_fixes_test.go:136: lost exchange race returned an unstored token` | |
| +| abandoned-cleanup | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPIDeviceCleanupBounded$ -count=1` | `person_device_fixes_test.go:160: cleanup must remove at most 100 abandoned challenges 204` | |
| +| typed-code-normalization | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPIDeviceNormalizedApproval$ -count=1` | `person_device_fixes_test.go:71: HTTP 422, want 303: <!doctype html>` | |
| +| hmac-purpose-key | `CGO_ENABLED=0 go test ./internal/equipo/personapi -run ^TestPersonAPIDevicePurposeKeys$ -count=1` | `device_keys_test.go:36: device HMAC does not use purpose key` | |
| +| result-purpose-key | `CGO_ENABLED=0 go test ./internal/equipo/personapi -run ^TestPersonAPIDevicePurposeKeys$ -count=1` | `device_keys_test.go:59: result does not use purpose key cipher: message authentication failed` | |
| +| cursor-purpose-key | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPILegacyCursorFailsClosed$ -count=1` | `person_api_key_source_fixes_test.go:70: HTTP 200, want 410` | |
| +| runner-instance | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPIRunnerInstanceProjection$ -count=1` | `person_api_key_source_fixes_test.go:81: runner list crossed instance boundary` | |
| +| approved-state | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPIDeviceNormalizedApproval$ -count=1` | `person_device_fixes_test.go:81: approved page still offers approval <!doctype html>` | |
| +| web-revocation | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPIDeviceWebRevocation$ -count=1` | `person_device_fixes_test.go:114: HTTP 303, want 404:` | |
| +| decision-owner | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPIOwnerDecisionOwners$ -count=1` | `person_api_owner_test.go:64: HTTP 200, want 409` | |
| +| budget-sync | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPIOwnerBudgetNextAdmission$ -count=1` | `person_api_owner_test.go:97: API-lowered budget allowed next admission <nil>` | |
| +| immediate-revocation | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPIDeviceWebRevocation$ -count=1` | `person_device_fixes_test.go:124: HTTP 200, want 401` | |
| + |
| +### Pending copy |
| + |
| +All twelve new entries below are individually marked `COPY REVIEW REQUIRED` in `internal/equipo/copy.go`. No copy-review server or drafting agent was started, as directed. |
| + |
| +- `device.list`: Your devices |
| +- `device.last_used`: Last used |
| +- `device.unused`: Not used yet |
| +- `device.empty`: You have no approved devices. |
| +- `device.revoked`: Device revoked |
| +- `device.approved`: Device approved |
| +- `roster.invalid_input`: Check the person, role and active state. |
| +- `roster.forbidden`: Only a team owner can change the roster. Keep at least one owner. |
| +- `roster.revision_conflict`: The roster changed or this person still owns project decisions. Check the roster and project owners before trying again. |
| +- `budgets.invalid_input`: Use positive whole numbers for each limit and keep project limits within the team limits. |
| +- `budgets.forbidden`: Only a team owner can view or change budgets. |
| +- `budgets.revision_conflict`: The budgets changed. Fetch the current limits before trying again. |
| + |
| +The page also renders the existing pending `device.created`, `device.expires`, `device.revoke`, `device.label`, `device.title`, `device.typed_code` and `device.approve` text unchanged, plus the existing settings navigation label. The API guide is unchanged and still headed `Draft: pending copy review`. Its pending sections remain: introductory conversation example; Sign in a device; Browser requests and invitation acceptance; Retry writes and handle revisions; Read lists and private setup state; Reconnect and answer questions. OpenAPI changes in this round are field/schema declarations, with no new prose. |
| + |
| +### Self-review and remaining limits |
| + |
| +Reviewed the public/browser/bearer lanes after extraction, transaction-bound roster checks, the proof-before-pacing order, guarded exchange result, cleanup selection, web ownership and CSRF, schema ordering, and the API-to-core budget path. The sixteen negative mutations cover the relevant guards. No unresolved requested finding remains. |
| + |
| +The HKDF change intentionally invalidates old cursors. It also invalidates pre-fix device credentials and pending challenges because their hashes/ciphertext used the previous keys; those clients must start device approval again. The new migration preserves historical rows. Non-CARLOS reverse proxies retain peer-based limits unless an explicit trusted deployment policy is added. Approved and revoked history is retained indefinitely for audit; only abandoned expired challenges are deleted. Each successful bearer authentication now records last use in a write transaction. |
| + |
| +Copy approval remains a release gate. Review minors 9 and 10 (project-rules web scope and broader OpenAPI response/field coverage) were not requested in this fix round and remain unchanged. Notifications stay with Task 19; inherited live-provider/certification gates remain outside this offline task. |
| + |
| +No agents, copy-review server, provider runs, sign-ins, live enrolment, full suite, make ci, merge, deployment or push. No server or watcher was started. Scratch stayed under on-disk TMPDIR and is removed before handoff. Go caches remain at their defaults. No `.claude/HANDOFF.md` was created. |
diff --git a/internal/equipo/app.go b/internal/equipo/app.go| index c867a059..226a7894 100644 |
| --- a/internal/equipo/app.go |
| +++ b/internal/equipo/app.go |
| @@ -154,7 +154,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| a.Use(a.live.Middleware) |
| runner := a.store.runnerRouter() |
| store.personOrigin = cfg.Origin |
| - store.personCursorKey = cfg.InstanceKey |
| + store.personKey = cfg.InstanceKey |
| store.personCookie = func(r *http.Request) (personapi.PersonPrincipal, error) { |
| id, ok := authentication.SessionFrom(r) |
| if !ok { |
| @@ -181,8 +181,8 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| a.Post("/invites/{id}/accept", ih.Accept) |
| a.Group(func(r chi.Router) { |
| r.Use(a.requireMember) |
| - r.Get("/auth/devices/{id}", a.personDevicePage) |
| - r.Post("/auth/devices/{id}/approve", a.approvePersonDevice) |
| + r.Get("/auth/devices/{id}", a.deviceBrowser().Page) |
| + r.Post("/auth/devices/{id}/approve", a.deviceBrowser().ApproveForm) |
| if a.live != nil { |
| r.Handle("/live", a.live.Handler()) |
| } |
| @@ -225,6 +225,8 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| r.Post("/runners/{id}/revoke", a.revokeRunner) |
| r.Post("/projects/{id}/connections", a.saveConnectionChoice) |
| r.Get("/settings", a.settings) |
| + r.Get("/settings/devices", a.deviceBrowser().Devices) |
| + r.Post("/settings/devices/{id}/revoke", a.deviceBrowser().RevokeForm) |
| lh := a.libraryHandler() |
| lh.Routes(r) |
| r.Post("/accounts", a.saveAccount) |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 64aa55b9..be621fbc 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -48,6 +48,31 @@ const BootLog = "Equipo could not start." |
| // COPY APPROVED BY DELEGATION (Luna pass, 2026-11-01, house rules). |
| var pageCopy = map[string]string{ |
| + // COPY REVIEW REQUIRED |
| + "device.list": "Your devices", |
| + // COPY REVIEW REQUIRED |
| + "device.last_used": "Last used", |
| + // COPY REVIEW REQUIRED |
| + "device.unused": "Not used yet", |
| + // COPY REVIEW REQUIRED |
| + "device.empty": "You have no approved devices.", |
| + // COPY REVIEW REQUIRED |
| + "device.revoked": "Device revoked", |
| + // COPY REVIEW REQUIRED |
| + "device.approved": "Device approved", |
| + // COPY REVIEW REQUIRED |
| + "roster.invalid_input": "Check the person, role and active state.", |
| + // COPY REVIEW REQUIRED |
| + "roster.forbidden": "Only a team owner can change the roster. Keep at least one owner.", |
| + // COPY REVIEW REQUIRED |
| + "roster.revision_conflict": "The roster changed or this person still owns project decisions. Check the roster and project owners before trying again.", |
| + // COPY REVIEW REQUIRED |
| + "budgets.invalid_input": "Use positive whole numbers for each limit and keep project limits within the team limits.", |
| + // COPY REVIEW REQUIRED |
| + "budgets.forbidden": "Only a team owner can view or change budgets.", |
| + // COPY REVIEW REQUIRED |
| + "budgets.revision_conflict": "The budgets changed. Fetch the current limits before trying again.", |
| + |
| // COPY REVIEW REQUIRED |
| "device.title": "Approve a device", |
| // COPY REVIEW REQUIRED |
diff --git a/internal/equipo/handlers.go b/internal/equipo/handlers.go| index ac7792b4..a04c4867 100644 |
| --- a/internal/equipo/handlers.go |
| +++ b/internal/equipo/handlers.go |
| @@ -29,6 +29,7 @@ type budgetForm struct { |
| Fields []budgetField |
| } |
| type pageData struct { |
| + PersonDevices []personapi.Device |
| PersonDevice personapi.Device |
| PersonDeviceRequest string |
| Teams setup.TeamLinkView |
diff --git a/internal/equipo/kernel/cursor.go b/internal/equipo/kernel/cursor.go| index 765ffc11..9a459d75 100644 |
| --- a/internal/equipo/kernel/cursor.go |
| +++ b/internal/equipo/kernel/cursor.go |
| @@ -3,6 +3,7 @@ package kernel |
| import ( |
| "crypto/aes" |
| "crypto/cipher" |
| + "crypto/hkdf" |
| "crypto/rand" |
| "crypto/sha256" |
| "encoding/base64" |
| @@ -33,8 +34,8 @@ func (c CursorCodec) aead() (cipher.AEAD, error) { |
| if c.Key == "" { |
| return nil, errors.New("missing cursor key") |
| } |
| - key := sha256.Sum256([]byte("equipo.person-api.cursor.v1\x00" + c.Key)) |
| - block, err := aes.NewCipher(key[:]) |
| + key := PurposeKey(c.Key, "person-api-cursor") |
| + block, err := aes.NewCipher(key) |
| if err != nil { |
| return nil, err |
| } |
| @@ -81,3 +82,9 @@ func (c CursorCodec) Open(scope, token string, position any) error { |
| } |
| return json.Unmarshal(envelope.Position, position) |
| } |
| + |
| +// PurposeKey separates instance secrets by use. SHA-256 permits the fixed 32-byte length. |
| +func PurposeKey(root, purpose string) []byte { |
| + key, _ := hkdf.Key(sha256.New, []byte(root), nil, "equipo.v1/"+purpose, 32) |
| + return key |
| +} |
diff --git a/internal/equipo/migrations/0030_person_devices_usage.sql b/internal/equipo/migrations/0030_person_devices_usage.sql| new file mode 100644 |
| index 00000000..31f85c9d |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0030_person_devices_usage.sql |
| @@ -0,0 +1 @@ |
| +ALTER TABLE person_devices ADD COLUMN last_used_at datetime; |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index 211f9b75..49bbf246 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -487,3 +487,4 @@ CREATE INDEX person_device_token ON person_devices(token_hash); |
| CREATE TABLE person_device_rates (key text PRIMARY KEY, started_at datetime, count integer); |
| CREATE TABLE project_rules (project_id integer PRIMARY KEY, text text, revision integer); |
| +ALTER TABLE person_devices ADD COLUMN last_used_at datetime; |
diff --git a/internal/equipo/person_api.go b/internal/equipo/person_api.go| index 8891b6cf..a7a62690 100644 |
| --- a/internal/equipo/person_api.go |
| +++ b/internal/equipo/person_api.go |
| @@ -1,7 +1,6 @@ |
| package equipo |
| import ( |
| - "amadan.net/rastrillo/rastrillo/csrf" |
| "context" |
| "errors" |
| "net/http" |
| @@ -25,7 +24,7 @@ func (s *Store) personAPIRouter() chi.Router { |
| if verify == nil { |
| verify = s.personDevices().Verify |
| } |
| - auth := personapi.Authenticator{Origin: s.personOrigin, Cookie: s.personCookie, Bearer: verify, Forbidden: ErrForbidden, Member: func(r *http.Request, p PersonPrincipal) error { |
| + auth := personapi.Authenticator{LookupMember: s.Member, NotFound: ErrNotFound, Origin: s.personOrigin, Cookie: s.personCookie, Bearer: verify, Forbidden: ErrForbidden, Member: func(r *http.Request, p PersonPrincipal) error { |
| m, err := s.Member(r.Context(), p.Address) |
| if errors.Is(err, ErrNotFound) { |
| return ErrForbidden |
| @@ -38,49 +37,12 @@ func (s *Store) personAPIRouter() chi.Router { |
| } |
| return nil |
| }} |
| - return (&personapi.Handler{App: s, CursorCodec: kernel.CursorCodec{Key: s.personCursorKey}, Authenticate: auth.Authenticate, AuthenticateRoute: func(r *http.Request, route personapi.Route) (PersonPrincipal, error) { |
| - switch route.Operation { |
| - case "begin_device", "exchange_device": |
| - if len(r.Header.Values("Cookie")) != 0 || len(r.Header.Values("Authorization")) != 0 { |
| - return PersonPrincipal{}, personapi.ErrUnauthenticated |
| - } |
| - if !personapi.OriginAllowed(r, s.personOrigin) { |
| - return PersonPrincipal{}, ErrForbidden |
| - } |
| - return PersonPrincipal{}, nil |
| - case "approve_device", "accept_invite", "invite": |
| - if route.Operation == "invite" && len(r.Header.Values("Authorization")) != 0 { |
| - return auth.Authenticate(r) |
| - } |
| - if len(r.Header.Values("Authorization")) != 0 { |
| - return PersonPrincipal{}, personapi.ErrUnauthenticated |
| - } |
| - if personapi.Mutating(r.Method) && !csrf.SameOrigin(r, s.personOrigin) || !personapi.OriginAllowed(r, s.personOrigin) { |
| - return PersonPrincipal{}, ErrForbidden |
| - } |
| - if route.Operation == "accept_invite" || route.Operation == "invite" { |
| - p, e := s.personCookie(r) |
| - if e != nil { |
| - return p, e |
| - } |
| - member, e := s.Member(r.Context(), p.Address) |
| - if e != nil && !errors.Is(e, ErrNotFound) { |
| - return p, e |
| - } |
| - if e == nil && p.SessionEpoch < member.SessionEpoch { |
| - return p, ErrForbidden |
| - } |
| - p.Pending = errors.Is(e, ErrNotFound) || !member.Active |
| - return p, nil |
| - } |
| - } |
| - return auth.Authenticate(r) |
| - }, Invalid: ErrInvalid, Forbidden: ErrForbidden, NotFound: ErrNotFound, Conflict: ErrConflict, Unavailable: ErrUnavailable, CursorExpired: ErrCursorExpired}).Router() |
| + return (&personapi.Handler{App: s, CursorCodec: kernel.CursorCodec{Key: s.personKey}, Authenticate: auth.Authenticate, AuthenticateRoute: auth.AuthenticateRoute, Invalid: ErrInvalid, Forbidden: ErrForbidden, NotFound: ErrNotFound, Conflict: ErrConflict, Unavailable: ErrUnavailable, CursorExpired: ErrCursorExpired}).Router() |
| } |
| func (s *Store) personAPIReader(a Actor) *conversation.Application { |
| return s.coordinatorApplication().ReadOnly(func(ctx context.Context, fn func(*gorm.DB) error) error { |
| return s.readTeam(ctx, a, func(tx *gorm.DB, _ Team) error { return fn(tx) }) |
| - }, kernel.CursorCodec{Key: s.personCursorKey}) |
| + }, kernel.CursorCodec{Key: s.personKey}) |
| } |
| func (s *Store) PersonAPIRead(ctx context.Context, a Actor, op, id, cursor string, limit int) (personapi.Result, error) { |
diff --git a/internal/equipo/person_devices.go b/internal/equipo/person_devices.go| index 23570b26..2d5320dd 100644 |
| --- a/internal/equipo/person_devices.go |
| +++ b/internal/equipo/person_devices.go |
| @@ -12,7 +12,7 @@ type PersonDeviceProof = personapi.PersonDeviceProof |
| type PersonCredential = personapi.PersonCredential |
| func (s *Store) personDevices() *personapi.DeviceStore { |
| - return &personapi.DeviceStore{Write: s.write, Read: s.invitationRead, Member: memberAt, Instance: runnerInstance, Audit: appendAudit, Key: s.personCursorKey, Origin: s.personOrigin, Now: s.runnerClock.Now, Invalid: ErrInvalid, Forbidden: ErrForbidden, NotFound: ErrNotFound, Conflict: ErrConflict} |
| + return &personapi.DeviceStore{Write: s.write, Read: s.invitationRead, Member: memberAt, Instance: runnerInstance, Audit: appendAudit, Key: s.personKey, Origin: s.personOrigin, Now: s.runnerClock.Now, Invalid: ErrInvalid, Forbidden: ErrForbidden, NotFound: ErrNotFound, Conflict: ErrConflict} |
| } |
| func (s *Store) BeginPersonDevice(ctx context.Context, key, label, request string) (PersonDeviceChallenge, error) { |
| return s.personDevices().Begin(ctx, key, label, request) |
| @@ -28,7 +28,17 @@ func (s *Store) RevokePersonDevice(ctx context.Context, a Actor, id string, m Mu |
| } |
| func (a *application) deviceBrowser() *personapi.DeviceBrowser { |
| - return &personapi.DeviceBrowser{Cookie: a.store.personCookie, Member: a.store.Member, Read: a.store.personDevices().Approval, Approve: a.store.ApprovePersonDevice, Invalid: ErrInvalid, Forbidden: ErrForbidden, Failure: a.failure, Render: func(w http.ResponseWriter, r *http.Request, d personapi.Device, request string) { |
| + return &personapi.DeviceBrowser{Cookie: a.store.personCookie, List: a.store.personDevices().List, Revoke: a.store.RevokePersonDevice, RenderList: func(w http.ResponseWriter, r *http.Request, devices []personapi.Device, request string) { |
| + data, err := a.page(r, "settings") |
| + if err != nil { |
| + a.failure(w, r, err) |
| + return |
| + } |
| + data.PersonDevices = devices |
| + data.PersonDeviceRequest = request |
| + data.Title = "device.list" |
| + render(w, "person_devices", data) |
| + }, Member: a.store.Member, Read: a.store.personDevices().Approval, Approve: a.store.ApprovePersonDevice, Invalid: ErrInvalid, Forbidden: ErrForbidden, Failure: a.failure, Render: func(w http.ResponseWriter, r *http.Request, d personapi.Device, request string) { |
| data, err := a.page(r, "connections") |
| if err != nil { |
| a.failure(w, r, err) |
| @@ -40,9 +50,3 @@ func (a *application) deviceBrowser() *personapi.DeviceBrowser { |
| render(w, "person_device", data) |
| }} |
| } |
| -func (a *application) personDevicePage(w http.ResponseWriter, r *http.Request) { |
| - a.deviceBrowser().Page(w, r) |
| -} |
| -func (a *application) approvePersonDevice(w http.ResponseWriter, r *http.Request) { |
| - a.deviceBrowser().ApproveForm(w, r) |
| -} |
diff --git a/internal/equipo/personapi/auth.go b/internal/equipo/personapi/auth.go| index 47943229..d2049116 100644 |
| --- a/internal/equipo/personapi/auth.go |
| +++ b/internal/equipo/personapi/auth.go |
| @@ -1,7 +1,9 @@ |
| package personapi |
| import ( |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| "context" |
| + "errors" |
| "net/http" |
| "net/url" |
| "strings" |
| @@ -11,11 +13,13 @@ import ( |
| ) |
| type Authenticator struct { |
| - Origin string |
| - Cookie func(*http.Request) (PersonPrincipal, error) |
| - Bearer VerifyPersonBearer |
| - Member func(*http.Request, PersonPrincipal) error |
| - Forbidden error |
| + LookupMember func(context.Context, string) (kernel.Member, error) |
| + NotFound error |
| + Origin string |
| + Cookie func(*http.Request) (PersonPrincipal, error) |
| + Bearer VerifyPersonBearer |
| + Member func(*http.Request, PersonPrincipal) error |
| + Forbidden error |
| } |
| func (a Authenticator) Authenticate(r *http.Request) (PersonPrincipal, error) { |
| @@ -147,3 +151,42 @@ func CurrentSession(ctx context.Context, address string, epoch int64) bool { |
| func WithVerifiedPrincipal(ctx context.Context, p PersonPrincipal) context.Context { |
| return context.WithValue(ctx, principalKey{}, p) |
| } |
| + |
| +func (auth Authenticator) AuthenticateRoute(r *http.Request, route Route) (PersonPrincipal, error) { |
| + switch route.Operation { |
| + case "begin_device", "exchange_device": |
| + if len(r.Header.Values("Cookie")) != 0 || len(r.Header.Values("Authorization")) != 0 { |
| + return PersonPrincipal{}, ErrUnauthenticated |
| + } |
| + if !OriginAllowed(r, auth.Origin) { |
| + return PersonPrincipal{}, auth.Forbidden |
| + } |
| + return PersonPrincipal{}, nil |
| + case "approve_device", "accept_invite", "invite": |
| + if route.Operation == "invite" && len(r.Header.Values("Authorization")) != 0 { |
| + return auth.Authenticate(r) |
| + } |
| + if len(r.Header.Values("Authorization")) != 0 { |
| + return PersonPrincipal{}, ErrUnauthenticated |
| + } |
| + if Mutating(r.Method) && !csrf.SameOrigin(r, auth.Origin) || !OriginAllowed(r, auth.Origin) { |
| + return PersonPrincipal{}, auth.Forbidden |
| + } |
| + if route.Operation == "accept_invite" || route.Operation == "invite" { |
| + p, e := auth.Cookie(r) |
| + if e != nil { |
| + return p, e |
| + } |
| + member, e := auth.LookupMember(r.Context(), p.Address) |
| + if e != nil && !errors.Is(e, auth.NotFound) { |
| + return p, e |
| + } |
| + if e == nil && p.SessionEpoch < member.SessionEpoch { |
| + return p, auth.Forbidden |
| + } |
| + p.Pending = errors.Is(e, auth.NotFound) || !member.Active |
| + return p, nil |
| + } |
| + } |
| + return auth.Authenticate(r) |
| +} |
diff --git a/internal/equipo/personapi/device_browser.go b/internal/equipo/personapi/device_browser.go| index 51e92183..97372fa2 100644 |
| --- a/internal/equipo/personapi/device_browser.go |
| +++ b/internal/equipo/personapi/device_browser.go |
| @@ -14,6 +14,9 @@ type DeviceBrowser struct { |
| Cookie func(*http.Request) (PersonPrincipal, error) |
| Member func(context.Context, string) (kernel.Member, error) |
| Read func(context.Context, string) (Device, error) |
| + List func(context.Context, kernel.Actor) ([]Device, error) |
| + Revoke func(context.Context, kernel.Actor, string, kernel.Mutation) error |
| + RenderList func(http.ResponseWriter, *http.Request, []Device, string) |
| Approve func(context.Context, kernel.Actor, string, string, kernel.Mutation) error |
| Failure func(http.ResponseWriter, *http.Request, error) |
| Render func(http.ResponseWriter, *http.Request, Device, string) |
| @@ -68,3 +71,47 @@ func (a *DeviceBrowser) ApproveForm(w http.ResponseWriter, r *http.Request) { |
| } |
| http.Redirect(w, r, fmt.Sprintf("/auth/devices/%s", chi.URLParam(r, "id")), http.StatusSeeOther) |
| } |
| + |
| +func (a *DeviceBrowser) Devices(w http.ResponseWriter, r *http.Request) { |
| + p, err := a.Cookie(r) |
| + if err != nil { |
| + a.Failure(w, r, a.Forbidden) |
| + return |
| + } |
| + devices, err := a.List(WithVerifiedPrincipal(r.Context(), p), kernel.Actor{Address: p.Address}) |
| + if err != nil { |
| + a.Failure(w, r, err) |
| + return |
| + } |
| + w.Header().Set("Cache-Control", "no-store") |
| + a.RenderList(w, r, devices, rand.Text()) |
| +} |
| +func (a *DeviceBrowser) RevokeForm(w http.ResponseWriter, r *http.Request) { |
| + p, err := a.Cookie(r) |
| + if err != nil { |
| + a.Failure(w, r, a.Forbidden) |
| + return |
| + } |
| + r.Body = http.MaxBytesReader(w, r.Body, 65536) |
| + if r.ParseForm() != nil || len(r.URL.Query()) != 0 { |
| + a.Failure(w, r, a.Invalid) |
| + return |
| + } |
| + for key, values := range r.PostForm { |
| + if len(values) != 1 || (key != "request_id" && key != "revision") { |
| + a.Failure(w, r, a.Invalid) |
| + return |
| + } |
| + } |
| + rev, err := strconv.ParseInt(r.PostForm.Get("revision"), 10, 64) |
| + if err != nil || r.PostForm.Get("request_id") == "" { |
| + a.Failure(w, r, a.Invalid) |
| + return |
| + } |
| + err = a.Revoke(WithVerifiedPrincipal(r.Context(), p), kernel.Actor{Address: p.Address}, chi.URLParam(r, "id"), kernel.Mutation{RequestID: r.PostForm.Get("request_id"), Revision: rev}) |
| + if err != nil { |
| + a.Failure(w, r, err) |
| + return |
| + } |
| + http.Redirect(w, r, "/settings/devices", http.StatusSeeOther) |
| +} |
diff --git a/internal/equipo/personapi/device_keys_test.go b/internal/equipo/personapi/device_keys_test.go| new file mode 100644 |
| index 00000000..9e10e602 |
| --- /dev/null |
| +++ b/internal/equipo/personapi/device_keys_test.go |
| @@ -0,0 +1,74 @@ |
| +package personapi |
| + |
| +import ( |
| + "bytes" |
| + "crypto/aes" |
| + "crypto/cipher" |
| + "crypto/hkdf" |
| + "crypto/hmac" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| +) |
| + |
| +func TestPersonAPIDevicePurposeKeys(t *testing.T) { |
| + root := "fixture-instance-key" |
| + derive := func(purpose string) []byte { |
| + key, err := hkdf.Key(sha256.New, []byte(root), nil, "equipo.v1/"+purpose, 32) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return key |
| + } |
| + macKey := derive("person-device-hmac") |
| + resultKey := derive("person-device-results") |
| + cursorKey := derive("person-api-cursor") |
| + if bytes.Equal(macKey, resultKey) || bytes.Equal(macKey, cursorKey) || bytes.Equal(resultKey, cursorKey) { |
| + t.Fatal("purpose keys overlap") |
| + } |
| + s := DeviceStore{Key: root} |
| + h := hmac.New(sha256.New, macKey) |
| + h.Write([]byte("fixture\x00value")) |
| + if s.mac("fixture", "value") != hex.EncodeToString(h.Sum(nil)) { |
| + t.Fatal("device HMAC does not use purpose key") |
| + } |
| + sealed, err := s.seal("row", "value") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + decrypt := func(key []byte, raw, scope string) error { |
| + block, e := aes.NewCipher(key) |
| + if e != nil { |
| + return e |
| + } |
| + g, e := cipher.NewGCM(block) |
| + if e != nil { |
| + return e |
| + } |
| + b, e := base64.RawURLEncoding.DecodeString(raw) |
| + if e != nil { |
| + return e |
| + } |
| + _, e = g.Open(nil, b[:g.NonceSize()], b[g.NonceSize():], []byte(scope)) |
| + return e |
| + } |
| + if err = decrypt(resultKey, sealed, "row"); err != nil { |
| + t.Fatal("result does not use purpose key", err) |
| + } |
| + if decrypt(macKey, sealed, "row") == nil { |
| + t.Fatal("HMAC key decrypted result") |
| + } |
| + token, err := (kernel.CursorCodec{Key: root}).Seal("scope", "position") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = decrypt(cursorKey, token, "scope"); err != nil { |
| + t.Fatal("cursor does not use purpose key", err) |
| + } |
| + if decrypt(resultKey, token, "scope") == nil { |
| + t.Fatal("result key decrypted cursor") |
| + } |
| +} |
diff --git a/internal/equipo/personapi/devices.go b/internal/equipo/personapi/devices.go| index a5d7e5af..9e08c39f 100644 |
| --- a/internal/equipo/personapi/devices.go |
| +++ b/internal/equipo/personapi/devices.go |
| @@ -51,12 +51,14 @@ type PersonCredential struct { |
| ExpiresAt time.Time `json:"expires_at"` |
| } |
| type Device struct { |
| - ID string `json:"id"` |
| - Label string `json:"label"` |
| - CreatedAt time.Time `json:"created_at"` |
| - ExpiresAt time.Time `json:"expires_at"` |
| - RevokedAt *time.Time `json:"revoked_at"` |
| - Revision int64 `json:"revision"` |
| + ID string `json:"id"` |
| + Label string `json:"label"` |
| + CreatedAt time.Time `json:"created_at"` |
| + ExpiresAt time.Time `json:"expires_at"` |
| + RevokedAt *time.Time `json:"revoked_at"` |
| + Revision int64 `json:"revision"` |
| + LastUsedAt *time.Time `json:"last_used_at"` |
| + Approved bool `json:"-"` |
| } |
| type DeviceRecord struct { |
| ID string `gorm:"primaryKey"` |
| @@ -67,6 +69,7 @@ type DeviceRecord struct { |
| CreatedAt, ExpiresAt time.Time |
| ApprovedAt, ExchangedAt, RevokedAt *time.Time |
| LastPoll *time.Time |
| + LastUsedAt *time.Time |
| TokenHash string `gorm:"index:person_device_token"` |
| TokenExpiresAt time.Time |
| NonceHash, BeginCipher, ResultCipher string |
| @@ -95,7 +98,7 @@ type DeviceStore struct { |
| } |
| func (s *DeviceStore) mac(domain, value string) string { |
| - h := hmac.New(sha256.New, []byte(s.Key)) |
| + h := hmac.New(sha256.New, kernel.PurposeKey(s.Key, "person-device-hmac")) |
| h.Write([]byte(domain + "\x00" + value)) |
| return hex.EncodeToString(h.Sum(nil)) |
| } |
| @@ -104,8 +107,8 @@ func (s *DeviceStore) seal(domain string, v any) (string, error) { |
| if err != nil { |
| return "", err |
| } |
| - key := sha256.Sum256([]byte(s.Key + "\x00person-device-results")) |
| - block, err := aes.NewCipher(key[:]) |
| + key := kernel.PurposeKey(s.Key, "person-device-results") |
| + block, err := aes.NewCipher(key) |
| if err != nil { |
| return "", err |
| } |
| @@ -124,8 +127,8 @@ func (s *DeviceStore) open(domain, raw string, v any) error { |
| if err != nil { |
| return err |
| } |
| - key := sha256.Sum256([]byte(s.Key + "\x00person-device-results")) |
| - block, err := aes.NewCipher(key[:]) |
| + key := kernel.PurposeKey(s.Key, "person-device-results") |
| + block, err := aes.NewCipher(key) |
| if err != nil { |
| return err |
| } |
| @@ -170,6 +173,9 @@ func (s *DeviceStore) clean(tx *gorm.DB, now time.Time) error { |
| if err := tx.Model(&DeviceRecord{}).Where("result_expires_at<=? AND result_cipher<>''", now).Update("result_cipher", "").Error; err != nil { |
| return err |
| } |
| + if err := tx.Where("id IN (?)", tx.Model(&DeviceRecord{}).Select("id").Where("expires_at<=? AND approved_at IS NULL AND exchanged_at IS NULL AND revoked_at IS NULL", now).Order("expires_at, id").Limit(100)).Delete(&DeviceRecord{}).Error; err != nil { |
| + return err |
| + } |
| return tx.Where("started_at<?", now.Add(-time.Hour)).Delete(&DeviceRate{}).Error |
| } |
| @@ -252,6 +258,11 @@ func (s *DeviceStore) member(tx *gorm.DB, person string, epoch int64) error { |
| return nil |
| } |
| func (s *DeviceStore) Approve(ctx context.Context, a kernel.Actor, id, code string, m kernel.Mutation) error { |
| + p, ok := PrincipalFrom(ctx) |
| + if !ok || p.Address == "" || p.Address != a.Address || p.CredentialID != "" || p.Pending { |
| + return ErrUnauthenticated |
| + } |
| + code = strings.ToUpper(strings.TrimSpace(code)) |
| if !m.Valid() { |
| return s.Invalid |
| } |
| @@ -270,13 +281,7 @@ func (s *DeviceStore) Approve(ctx context.Context, a kernel.Actor, id, code stri |
| var denied error |
| err := s.Write(WithoutRequest(ctx), func(tx *gorm.DB) error { |
| now := s.Now().UTC() |
| - epoch := now.Unix() |
| - if p, ok := PrincipalFrom(ctx); ok { |
| - if p.CredentialID != "" { |
| - return ErrUnauthenticated |
| - } |
| - epoch = p.SessionEpoch |
| - } |
| + epoch := p.SessionEpoch |
| if err := s.member(tx, a.Address, epoch); err != nil { |
| return err |
| } |
| @@ -334,27 +339,22 @@ func (s *DeviceStore) Exchange(ctx context.Context, p PersonDeviceProof) (out Pe |
| if e := s.clean(tx, now); e != nil { |
| return e |
| } |
| - ok, e := s.rate(tx, "exchange/"+source(ctx), now, 60) |
| - if e != nil { |
| - return e |
| - } |
| - if !ok { |
| - denied = ErrSlowDown |
| - return nil |
| - } |
| - ok, e = s.rate(tx, "challenge/"+p.ID, now, 12) |
| - if e != nil { |
| - return e |
| - } |
| - if !ok { |
| - denied = ErrSlowDown |
| + // Failed proofs share a source limit, never the real device's polling clock. |
| + invalidProof := func() error { |
| + ok, e := s.rate(tx, "exchange/"+source(ctx), now, 60) |
| + if e != nil { |
| + return e |
| + } |
| + denied = s.Forbidden |
| + if !ok { |
| + denied = ErrSlowDown |
| + } |
| return nil |
| } |
| var row DeviceRecord |
| - if e = tx.First(&row, "id=?", p.ID).Error; e != nil { |
| + if e := tx.First(&row, "id=?", p.ID).Error; e != nil { |
| if errors.Is(e, gorm.ErrRecordNotFound) { |
| - denied = s.Forbidden |
| - return nil |
| + return invalidProof() |
| } |
| return e |
| } |
| @@ -362,22 +362,14 @@ func (s *DeviceStore) Exchange(ctx context.Context, p PersonDeviceProof) (out Pe |
| sig, _ := base64.RawURLEncoding.DecodeString(p.Signature) |
| valid := hmac.Equal([]byte(row.SecretHash), []byte(s.mac(DeviceAudience, p.DeviceSecret))) && p.Challenge == row.Challenge && len(pub) == ed25519.PublicKeySize && ed25519.Verify(pub, DeviceProofMessage(row.InstanceID, p), sig) |
| if !valid { |
| - if row.LastPoll != nil && now.Sub(*row.LastPoll) < 5*time.Second { |
| - denied = ErrSlowDown |
| - return nil |
| - } |
| - if e = tx.Model(&DeviceRecord{}).Where("id=?", row.ID).Update("last_poll", now).Error; e != nil { |
| - return e |
| - } |
| - denied = s.Forbidden |
| - return nil |
| + return invalidProof() |
| } |
| if row.RevokedAt != nil { |
| denied = s.Forbidden |
| return nil |
| } |
| if row.ExchangedAt != nil { |
| - if e = s.member(tx, row.Person, row.SessionEpoch); e != nil { |
| + if e := s.member(tx, row.Person, row.SessionEpoch); e != nil { |
| denied = e |
| return nil |
| } |
| @@ -399,14 +391,14 @@ func (s *DeviceStore) Exchange(ctx context.Context, p PersonDeviceProof) (out Pe |
| denied = ErrSlowDown |
| return nil |
| } |
| - if e = tx.Model(&DeviceRecord{}).Where("id=?", row.ID).Update("last_poll", now).Error; e != nil { |
| + if e := tx.Model(&DeviceRecord{}).Where("id=?", row.ID).Update("last_poll", now).Error; e != nil { |
| return e |
| } |
| if row.ApprovedAt == nil { |
| denied = ErrPending |
| return nil |
| } |
| - if e = s.member(tx, row.Person, row.SessionEpoch); e != nil { |
| + if e := s.member(tx, row.Person, row.SessionEpoch); e != nil { |
| denied = e |
| return nil |
| } |
| @@ -423,8 +415,12 @@ func (s *DeviceStore) Exchange(ctx context.Context, p PersonDeviceProof) (out Pe |
| row.ResultExpiresAt = now.Add(10 * time.Minute) |
| row.ExchangedAt = &now |
| row.Revision++ |
| - if e = tx.Model(&DeviceRecord{}).Where("id=? AND exchanged_at IS NULL", row.ID).Select("token_hash", "token_expires_at", "nonce_hash", "result_cipher", "result_expires_at", "exchanged_at", "revision").Updates(&row).Error; e != nil { |
| - return e |
| + result := tx.Model(&DeviceRecord{}).Where("id=? AND exchanged_at IS NULL", row.ID).Select("token_hash", "token_expires_at", "nonce_hash", "result_cipher", "result_expires_at", "exchanged_at", "revision").Updates(&row) |
| + if result.Error != nil { |
| + return result.Error |
| + } |
| + if result.RowsAffected != 1 { |
| + return s.Conflict |
| } |
| return s.Audit(tx, kernel.Actor{Address: row.Person}, "person_device.exchange", row.ID) |
| }) |
| @@ -452,13 +448,20 @@ func (s *DeviceStore) VerifyAt(tx *gorm.DB, id, token string) (p PersonPrincipal |
| if e != nil || instance != row.InstanceID || row.ExchangedAt == nil || row.RevokedAt != nil || !s.Now().Before(row.TokenExpiresAt) { |
| return p, ErrUnauthenticated |
| } |
| - if e = s.member(tx, row.Person, row.SessionEpoch); e != nil { |
| + if e := s.member(tx, row.Person, row.SessionEpoch); e != nil { |
| return p, ErrUnauthenticated |
| } |
| return PersonPrincipal{Address: row.Person, CredentialID: row.ID, SessionEpoch: row.SessionEpoch}, nil |
| } |
| func (s *DeviceStore) Verify(ctx context.Context, token string) (p PersonPrincipal, err error) { |
| - err = s.Read(ctx, func(tx *gorm.DB) error { p, err = s.VerifyAt(tx, "", token); return err }) |
| + err = s.Write(WithoutRequest(ctx), func(tx *gorm.DB) error { |
| + var e error |
| + p, e = s.VerifyAt(tx, "", token) |
| + if e != nil { |
| + return e |
| + } |
| + return tx.Model(&DeviceRecord{}).Where("id=?", p.CredentialID).Update("last_used_at", s.Now().UTC()).Error |
| + }) |
| return |
| } |
| func (s *DeviceStore) List(ctx context.Context, a kernel.Actor) (out []Device, err error) { |
| @@ -481,7 +484,11 @@ func (s *DeviceStore) List(ctx context.Context, a kernel.Actor) (out []Device, e |
| return e |
| } |
| for _, r := range rows { |
| - out = append(out, Device{r.ID, r.Label, r.CreatedAt, r.TokenExpiresAt, r.RevokedAt, r.Revision}) |
| + expiry := r.TokenExpiresAt |
| + if r.ExchangedAt == nil { |
| + expiry = r.ExpiresAt |
| + } |
| + out = append(out, Device{ID: r.ID, Label: r.Label, CreatedAt: r.CreatedAt, ExpiresAt: expiry, RevokedAt: r.RevokedAt, Revision: r.Revision, LastUsedAt: r.LastUsedAt, Approved: r.ApprovedAt != nil}) |
| } |
| return nil |
| }) |
| @@ -496,7 +503,7 @@ func (s *DeviceStore) Approval(ctx context.Context, id string) (out Device, err |
| if !s.Now().Before(r.ExpiresAt) { |
| return ErrDeviceExpired |
| } |
| - out = Device{ID: r.ID, Label: r.Label, CreatedAt: r.CreatedAt, ExpiresAt: r.ExpiresAt, Revision: r.Revision} |
| + out = Device{ID: r.ID, Label: r.Label, CreatedAt: r.CreatedAt, ExpiresAt: r.ExpiresAt, Revision: r.Revision, Approved: r.ApprovedAt != nil} |
| return nil |
| }) |
| return |
diff --git a/internal/equipo/personapi/extended_reads.go b/internal/equipo/personapi/extended_reads.go| index 4d97c2d9..428accda 100644 |
| --- a/internal/equipo/personapi/extended_reads.go |
| +++ b/internal/equipo/personapi/extended_reads.go |
| @@ -268,7 +268,7 @@ func (s *Native) Read(ctx context.Context, a kernel.Actor, op, id string) (out R |
| return nil |
| case "runners", "runner": |
| var rows []setup.RunnerRecord |
| - if e := tx.Where("person=?", a.Address).Find(&rows).Error; e != nil { |
| + if e := tx.Where("person=? AND instance_id=?", a.Address, t.ID).Find(&rows).Error; e != nil { |
| return e |
| } |
| items := []Runner{} |
diff --git a/internal/equipo/personapi/extended_types.go b/internal/equipo/personapi/extended_types.go| index 829709d3..3f2c089c 100644 |
| --- a/internal/equipo/personapi/extended_types.go |
| +++ b/internal/equipo/personapi/extended_types.go |
| @@ -170,8 +170,8 @@ type Runner struct { |
| ID string `json:"id"` |
| Label string `json:"label"` |
| Revision int64 `json:"revision"` |
| - CreatedAt *time.Time `json:"created_at"` |
| - LastSeen *time.Time `json:"last_seen"` |
| + CreatedAt *time.Time `json:"created_at,omitempty"` |
| + LastSeen *time.Time `json:"last_seen,omitempty"` |
| RevokedAt *time.Time `json:"revoked_at"` |
| } |
| type RunnerApproveInput struct { |
diff --git a/internal/equipo/personapi/handler.go b/internal/equipo/personapi/handler.go| index 2ccdefd1..3fd4dce9 100644 |
| --- a/internal/equipo/personapi/handler.go |
| +++ b/internal/equipo/personapi/handler.go |
| @@ -1,12 +1,13 @@ |
| package personapi |
| import ( |
| + "amadan.net/rastrillo/rastrillo/carlos" |
| + "amadan.net/rastrillo/rastrillo/clientip" |
| "context" |
| "crypto/rand" |
| "encoding/json" |
| "errors" |
| "mime" |
| - "net" |
| "net/http" |
| "strconv" |
| @@ -57,13 +58,18 @@ func (h *Handler) Router() chi.Router { |
| for _, route := range Routes { |
| r.Method(route.Method, route.Path, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| w.Header().Set("Cache-Control", "no-store") |
| + req = req.WithContext(context.WithValue(req.Context(), errorScopeKey{}, route.Operation)) |
| p, err := h.AuthenticateRoute(req, route) |
| if err != nil { |
| h.Failure(w, req, err) |
| return |
| } |
| - host, _, _ := net.SplitHostPort(req.RemoteAddr) |
| - ctx := WithDeviceSource(req.Context(), host) |
| + // Match Rastrillo auth: trust the CARLOS edge, and no headers off CARLOS. |
| + hops := 0 |
| + if carlos.Running() { |
| + hops = clientip.DefaultHops |
| + } |
| + ctx := WithDeviceSource(req.Context(), clientip.From(req, hops)) |
| if !p.Pending { |
| ctx = context.WithValue(ctx, principalKey{}, p) |
| } |
| @@ -174,7 +180,7 @@ func WriteError(w http.ResponseWriter, r *http.Request, status int, code string, |
| request = rand.Text() |
| } |
| w.WriteHeader(status) |
| - _ = json.NewEncoder(w).Encode(Error{Code: code, CopyKey: "api." + code, RequestID: request, CurrentRevision: current}) |
| + _ = json.NewEncoder(w).Encode(Error{Code: code, CopyKey: errorCopyKey(r, code), RequestID: request, CurrentRevision: current}) |
| } |
| var ErrUnauthenticated = errors.New("api.unauthenticated") |
| @@ -244,3 +250,19 @@ func (h *Handler) currentRevision(ctx context.Context, a kernel.Actor, op, id st |
| } |
| return &out.Revision, nil |
| } |
| + |
| +type errorScopeKey struct{} |
| + |
| +func errorCopyKey(r *http.Request, code string) string { |
| + op, _ := r.Context().Value(errorScopeKey{}).(string) |
| + switch code { |
| + case "invalid_input", "forbidden", "revision_conflict": |
| + switch op { |
| + case "roster", "set_roster": |
| + return "roster." + code |
| + case "budgets", "save_budgets": |
| + return "budgets." + code |
| + } |
| + } |
| + return "api." + code |
| +} |
diff --git a/internal/equipo/render.go b/internal/equipo/render.go| index 7ad4d781..59f587e7 100644 |
| --- a/internal/equipo/render.go |
| +++ b/internal/equipo/render.go |
| @@ -27,7 +27,7 @@ var assets = rastrillo.NewAssets(appFS) |
| var pages = map[string]*template.Template{} |
| func init() { |
| - for _, name := range []string{"person_device", "teams", "onboarding", "invite", "playbooks", "playbook_form", "playbook_diff", "specialist_form", "template_library", "template_diff", "conversation", "thread", "plan", "coordinator", "preferences", "index", "empty", "projects", "project", "project_form", "people", "settings", "specialist", "errors", "signin_page", "form_error", "runners", "tasks", "task", "task_form", "question", "merge", "connections", "recovery", "recovery_form", "rendered_approval"} { |
| + for _, name := range []string{"person_devices", "person_device", "teams", "onboarding", "invite", "playbooks", "playbook_form", "playbook_diff", "specialist_form", "template_library", "template_diff", "conversation", "thread", "plan", "coordinator", "preferences", "index", "empty", "projects", "project", "project_form", "people", "settings", "specialist", "errors", "signin_page", "form_error", "runners", "tasks", "task", "task_form", "question", "merge", "connections", "recovery", "recovery_form", "rendered_approval"} { |
| page := template.Must(template.New("layout"). |
| Funcs(ui.Funcs(ui.WithIcons(icons.Icon, icons.Assets))). |
| Funcs(template.FuncMap{"projectAllows": library.ProjectAllowed, "asset": assets.Path, "copy": copyText, "taskGroups": func() []string { return []string{"needs-person", "running", "queued", "finished"} }, |
diff --git a/internal/equipo/store.go b/internal/equipo/store.go| index 689f0693..859c720c 100644 |
| --- a/internal/equipo/store.go |
| +++ b/internal/equipo/store.go |
| @@ -60,7 +60,7 @@ type Store struct { |
| personCookie func(*http.Request) (personapi.PersonPrincipal, error) |
| invitationKey string |
| personOrigin string |
| - personCursorKey string |
| + personKey string |
| notifier JobNotifier |
| db *db.DB |
| execution *Execution |
diff --git a/internal/equipo/templates/person_device.html b/internal/equipo/templates/person_device.html| index 514ac230..1b74ce4f 100644 |
| --- a/internal/equipo/templates/person_device.html |
| +++ b/internal/equipo/templates/person_device.html |
| @@ -2,11 +2,13 @@ |
| <h1>{{copy "device.title"}}</h1> |
| <section equipo-card> |
| <dl><dt>{{copy "device.label"}}</dt><dd>{{.PersonDevice.Label}}</dd><dt>{{copy "device.created"}}</dt><dd>{{.PersonDevice.CreatedAt.Format "2006-01-02T15:04:05Z07:00"}}</dd><dt>{{copy "device.expires"}}</dt><dd>{{.PersonDevice.ExpiresAt.Format "2006-01-02T15:04:05Z07:00"}}</dd></dl> |
| +{{if .PersonDevice.Approved}}<p role="status">{{copy "device.approved"}}</p>{{else}} |
| <form method="post" action="/auth/devices/{{.PersonDevice.ID}}/approve" equipo-form> |
| <input type="hidden" name="request_id" value="{{.PersonDeviceRequest}}"> |
| <input type="hidden" name="revision" value="{{.PersonDevice.Revision}}"> |
| -<label>{{copy "device.typed_code"}}<input name="typed_code" maxlength="8" autocomplete="off" required rst-input></label> |
| +<label>{{copy "device.typed_code"}}<input name="typed_code" autocomplete="off" required rst-input></label> |
| <button rst-btn type="submit">{{copy "device.approve"}}</button> |
| </form> |
| +{{end}} |
| </section> |
| {{end}} |
diff --git a/internal/equipo/templates/person_devices.html b/internal/equipo/templates/person_devices.html| new file mode 100644 |
| index 00000000..b818aff3 |
| --- /dev/null |
| +++ b/internal/equipo/templates/person_devices.html |
| @@ -0,0 +1,21 @@ |
| +{{define "content"}} |
| +<a href="/settings" rel="up">{{copy "nav.settings"}}</a> |
| +<h1>{{copy "device.list"}}</h1> |
| +{{range .PersonDevices}} |
| +<section equipo-card> |
| +<h2>{{.Label}}</h2> |
| +<dl> |
| +<dt>{{copy "device.created"}}</dt><dd>{{.CreatedAt.Format "2006-01-02T15:04:05Z07:00"}}</dd> |
| +<dt>{{copy "device.last_used"}}</dt><dd>{{if .LastUsedAt}}{{.LastUsedAt.Format "2006-01-02T15:04:05Z07:00"}}{{else}}{{copy "device.unused"}}{{end}}</dd> |
| +<dt>{{copy "device.expires"}}</dt><dd>{{.ExpiresAt.Format "2006-01-02T15:04:05Z07:00"}}</dd> |
| +</dl> |
| +{{if .RevokedAt}}<p>{{copy "device.revoked"}}</p>{{else}} |
| +<form method="post" action="/settings/devices/{{.ID}}/revoke" equipo-form> |
| +<input type="hidden" name="request_id" value="{{$.PersonDeviceRequest}}"> |
| +<input type="hidden" name="revision" value="{{.Revision}}"> |
| +<button rst-btn type="submit">{{copy "device.revoke"}}</button> |
| +</form> |
| +{{end}} |
| +</section> |
| +{{else}}<p>{{copy "device.empty"}}</p>{{end}} |
| +{{end}} |
diff --git a/internal/equipo/templates/settings.html b/internal/equipo/templates/settings.html| index 15b66ecf..3b04eb13 100644 |
| --- a/internal/equipo/templates/settings.html |
| +++ b/internal/equipo/templates/settings.html |
| @@ -1,4 +1,5 @@ |
| {{define "content"}} |
| +<a href="/settings/devices">{{copy "device.list"}}</a> |
| <a href="/settings/coordinator">{{copy "coordinator.settings"}}</a> |
| <a href="/preferences">{{copy "preferences.title"}}</a>{{if .Owner}}<a href="/settings/recovery">{{copy "recovery.title"}}</a>{{end}} |
| <h1>{{copy "nav.settings"}}</h1> |
diff --git a/internal/plan3test/person_api_key_source_fixes_test.go b/internal/plan3test/person_api_key_source_fixes_test.go| new file mode 100644 |
| index 00000000..c26c01e0 |
| --- /dev/null |
| +++ b/internal/plan3test/person_api_key_source_fixes_test.go |
| @@ -0,0 +1,89 @@ |
| +package plan3test |
| + |
| +import ( |
| + "crypto/aes" |
| + "crypto/cipher" |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/json" |
| + "fmt" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "amadan.net/oficina/equipo/internal/equipo/setup" |
| +) |
| + |
| +func TestPersonAPIDeviceTrustedProxySource(t *testing.T) { |
| + for _, proxied := range []bool{false, true} { |
| + t.Run(fmt.Sprint(proxied), func(t *testing.T) { |
| + f := newFixture(t) |
| + control := "" |
| + if proxied { |
| + control = "fixture-socket" |
| + } |
| + t.Setenv("CARLOS_CONTROL_SOCKET", control) |
| + pub, _, err := ed25519.GenerateKey(rand.Reader) |
| + must(t, err) |
| + request := func(xff string) *httptest.ResponseRecorder { |
| + r := httptest.NewRequest("POST", "/api/v1/auth/devices", strings.NewReader(fmt.Sprintf(`{"public_key":%q,"label":"phone"}`, base64.RawURLEncoding.EncodeToString(pub)))) |
| + r.RemoteAddr = "127.0.0.1:1234" |
| + r.Header.Set("X-Forwarded-For", xff) |
| + r.Header.Set("Content-Type", "application/json") |
| + r.Header.Set("Idempotency-Key", rand.Text()) |
| + w := httptest.NewRecorder() |
| + f.Handler.ServeHTTP(w, r) |
| + return w |
| + } |
| + for i := 0; i < 10; i++ { |
| + expectHTTP(t, request(fmt.Sprintf("198.51.100.%d, 192.0.2.1", i)), 200) |
| + } |
| + expectHTTP(t, request("198.51.100.99, 192.0.2.1"), 429) |
| + want := 429 |
| + if proxied { |
| + want = 200 |
| + } |
| + expectHTTP(t, request("198.51.100.99, 192.0.2.2"), want) |
| + }) |
| + } |
| +} |
| +func TestPersonAPILegacyCursorFailsClosed(t *testing.T) { |
| + f := newFixture(t) |
| + key := sha256.Sum256([]byte("equipo.person-api.cursor.v1\x00plan3-fixture")) |
| + block, err := aes.NewCipher(key[:]) |
| + must(t, err) |
| + g, err := cipher.NewGCM(block) |
| + must(t, err) |
| + raw, err := json.Marshal(struct { |
| + Position any |
| + ExpiresAt time.Time |
| + }{map[string]any{"ID": "", "Sequence": 0}, time.Now().Add(time.Hour)}) |
| + must(t, err) |
| + nonce := make([]byte, g.NonceSize()) |
| + _, err = rand.Read(nonce) |
| + must(t, err) |
| + token := base64.RawURLEncoding.EncodeToString(g.Seal(nonce, nonce, raw, []byte(owner.Address+"\x00people"))) |
| + expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/people?cursor="+token, "", "", ""), 410) |
| +} |
| +func TestPersonAPIRunnerInstanceProjection(t *testing.T) { |
| + f := newFixture(t) |
| + for _, instance := range []string{f.TeamID, "foreign"} { |
| + must(t, f.DB.G.Create(&setup.RunnerRecord{Runner: setup.Runner{ID: instance, Person: owner.Address, Label: instance, Revision: 1}, InstanceID: instance}).Error) |
| + } |
| + w := apiRequest(t, f, owner, "GET", "/api/v1/runners", "", "", "") |
| + expectHTTP(t, w, 200) |
| + page := apiValue[personapi.Page[map[string]any]](t, w) |
| + if len(page.Items) != 1 || page.Items[0]["id"] != f.TeamID { |
| + t.Fatal("runner list crossed instance boundary") |
| + } |
| + for _, key := range []string{"created_at", "last_seen"} { |
| + if _, ok := page.Items[0][key]; ok { |
| + t.Fatal("unavailable runner time should be omitted", key) |
| + } |
| + } |
| + expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/runners/foreign", "", "", ""), 404) |
| +} |
diff --git a/internal/plan3test/person_api_migration_test.go b/internal/plan3test/person_api_migration_test.go| index 7214f8c2..cbf85906 100644 |
| --- a/internal/plan3test/person_api_migration_test.go |
| +++ b/internal/plan3test/person_api_migration_test.go |
| @@ -80,7 +80,7 @@ func TestPersonAPIDeviceMigrationUpgrade(t *testing.T) { |
| must(t, err) |
| old := &migrate.Set{} |
| for _, m := range equipo.BootSchema.All() { |
| - if m.ID != "equipo/0030_person_devices" { |
| + if m.ID != "equipo/0030_person_devices" && m.ID != "equipo/0030_person_devices_usage" { |
| old.Add(m) |
| } |
| } |
| @@ -92,7 +92,7 @@ func TestPersonAPIDeviceMigrationUpgrade(t *testing.T) { |
| must(t, err) |
| result, err := migrate.Apply(ctx, d, equipo.BootSchema) |
| must(t, err) |
| - if len(result.Applied) != 1 || result.Applied[0] != "equipo/0030_person_devices" { |
| + if len(result.Applied) != 2 || result.Applied[0] != "equipo/0030_person_devices" || result.Applied[1] != "equipo/0030_person_devices_usage" { |
| t.Fatal(result.Applied) |
| } |
| f := newFixture(t) |
| @@ -118,3 +118,30 @@ func TestPersonAPIDeviceMigrationUpgrade(t *testing.T) { |
| t.Fatal("historical message lost") |
| } |
| } |
| + |
| +func TestPersonAPIDeviceUsageMigration(t *testing.T) { |
| + path := filepath.Join(t.TempDir(), "device-usage.db") |
| + d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil))) |
| + must(t, err) |
| + t.Cleanup(func() { must(t, d.Close()) }) |
| + old := &migrate.Set{} |
| + for _, m := range equipo.BootSchema.All() { |
| + if m.ID != "equipo/0030_person_devices_usage" { |
| + old.Add(m) |
| + } |
| + } |
| + _, err = migrate.Apply(ctx, d, old) |
| + must(t, err) |
| + _, err = d.Writer().Exec(`INSERT INTO person_devices(id,request_hash,person,token_hash,revision) VALUES('history','request','person','hash',3)`) |
| + must(t, err) |
| + result, err := migrate.Apply(ctx, d, equipo.BootSchema) |
| + must(t, err) |
| + if len(result.Applied) != 1 || result.Applied[0] != "equipo/0030_person_devices_usage" { |
| + t.Fatal(result.Applied) |
| + } |
| + var count int |
| + must(t, d.Writer().QueryRow(`SELECT count(*) FROM person_devices WHERE id='history' AND token_hash='hash' AND revision=3 AND last_used_at IS NULL`).Scan(&count)) |
| + if count != 1 { |
| + t.Fatal("usage migration lost device history") |
| + } |
| +} |
diff --git a/internal/plan3test/person_api_owner_test.go b/internal/plan3test/person_api_owner_test.go| index 1c50cc72..82bfd7bb 100644 |
| --- a/internal/plan3test/person_api_owner_test.go |
| +++ b/internal/plan3test/person_api_owner_test.go |
| @@ -2,8 +2,12 @@ package plan3test |
| import ( |
| "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "errors" |
| + "fmt" |
| "strings" |
| "testing" |
| + "time" |
| ) |
| func TestPersonAPIOwnerRosterBudgets(t *testing.T) { |
| @@ -45,3 +49,56 @@ func TestPersonAPIOwnerRosterBudgets(t *testing.T) { |
| f.exec(t, "UPDATE members SET role='member' WHERE address=?", owner.Address) |
| expectHTTP(t, apiRequest(t, f, owner, "PUT", "/api/v1/budgets", budget, "budget", `"0"`), 403) |
| } |
| + |
| +func TestPersonAPIOwnerDecisionOwners(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + must(t, f.DB.G.Create(&equipo.DecisionOwner{ProjectID: p.ProjectID, Decision: "copy", Address: peer.Address}).Error) |
| + path := "/api/v1/roster/" + peer.Address |
| + // Team role and project decision ownership are independent. Demotion retains the assignment. |
| + expectHTTP(t, apiRequest(t, f, owner, "PUT", path, `{"role":"member","active":true}`, "demote", `"1"`), 200) |
| + if f.count(t, "SELECT count(*) FROM decision_owners WHERE address=?", peer.Address) != 1 { |
| + t.Fatal("demotion removed decision assignment") |
| + } |
| + w := apiRequest(t, f, owner, "PUT", path, `{"role":"member","active":false}`, "remove", `"2"`) |
| + expectHTTP(t, w, 409) |
| + if !strings.Contains(w.Body.String(), `"copy_key":"roster.revision_conflict"`) { |
| + t.Fatal("missing roster failure copy", w.Body.String()) |
| + } |
| + m, err := f.Store.Member(ctx, peer.Address) |
| + must(t, err) |
| + if !m.Active || m.Revision != 2 { |
| + t.Fatal("failed removal changed decision owner", m) |
| + } |
| +} |
| +func TestPersonAPIOwnerBudgetNextAdmission(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + x, _, scope := f.planCore(t, p) |
| + job, err := x.Core.GetJob(ctx, scope) |
| + must(t, err) |
| + _, err = x.Core.Claim(ctx, scope, "reproduce", "runner", "workspace") |
| + must(t, err) |
| + before, err := x.Core.PeriodUsage(ctx, scope.Account, 0, time.Now()) |
| + must(t, err) |
| + w := apiRequest(t, f, owner, "GET", "/api/v1/budgets", "", "", "") |
| + expectHTTP(t, w, 200) |
| + body := fmt.Sprintf(`{"team":{"calls":1,"input_tokens":1,"output_tokens":1,"seconds":1},"projects":{"%d":{"calls":1,"input_tokens":1,"output_tokens":1,"seconds":1}}}`, p.ProjectID) |
| + expectHTTP(t, apiRequest(t, f, owner, "PUT", "/api/v1/budgets", body, "lower", w.Header().Get("ETag")), 200) |
| + after, err := x.Core.PeriodUsage(ctx, scope.Account, 0, time.Now()) |
| + must(t, err) |
| + if before != after { |
| + t.Fatal("lowering budget changed usage") |
| + } |
| + other, err := x.Core.CreateJob(ctx, team.JobSpec{Account: job.Account, Project: job.Project, Requester: job.Requester, Target: job.Target, Evidence: job.Evidence, Policy: job.Policy, GrantRef: job.Grant.Ref, Steps: team.SoftwareSteps(false)}) |
| + must(t, err) |
| + _, err = x.Core.Claim(ctx, team.Scope{Account: scope.Account, Job: other.ID}, "reproduce", "runner", "workspace") |
| + if !errors.Is(err, team.ErrBudget) { |
| + t.Fatal("API-lowered budget allowed next admission", err) |
| + } |
| + w = apiRequest(t, f, owner, "PUT", "/api/v1/budgets", `{"team":{"calls":0,"input_tokens":1,"output_tokens":1,"seconds":1},"projects":{}}`, "invalid", `"2"`) |
| + expectHTTP(t, w, 422) |
| + if !strings.Contains(w.Body.String(), `"copy_key":"budgets.invalid_input"`) { |
| + t.Fatal("missing budget failure copy", w.Body.String()) |
| + } |
| +} |
diff --git a/internal/plan3test/person_device_fixes_test.go b/internal/plan3test/person_device_fixes_test.go| new file mode 100644 |
| index 00000000..a4bd38d6 |
| --- /dev/null |
| +++ b/internal/plan3test/person_device_fixes_test.go |
| @@ -0,0 +1,177 @@ |
| +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) |
| +} |