fix: report current revisions and stop unbounded person API cursors
24 files changed,
+993
−145
docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+114 −0internal/equipo/app.go+1 −0internal/equipo/conversation/read_only.go+57 −0internal/equipo/conversation/store.go+25 −6internal/equipo/conversation/threads.go+5 −1internal/equipo/kernel/cursor.go+83 −0internal/equipo/kernel/cursor_test.go+38 −0internal/equipo/migrations/0023_person_api_requests.sql+2 −2internal/equipo/migrations/schema.sql+2 −2internal/equipo/person_api.go+11 −14internal/equipo/personapi/auth.go+11 −2internal/equipo/personapi/conversation.go+4 −26internal/equipo/personapi/handler.go+39 −7internal/equipo/personapi/reads.go+51 −1internal/equipo/personapi/requests.go+65 −51internal/equipo/personapi/types.go+1 −2internal/equipo/questions.go+11 −12internal/equipo/store.go+1 −0internal/plan3test/person_api_audiences_test.go+135 −0internal/plan3test/person_api_fixes_test.go+304 −0internal/plan3test/person_api_migration_test.go+16 −0internal/plan3test/person_api_operations_test.go+1 −1internal/plan3test/person_api_test.go+0 −18internal/runnerproto/question_answer_json.go+16 −0
CI failed — run details
Intent
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index 822f79fd..9809365e 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -3171,3 +3171,117 @@ All final commands exited 0: |
| - **merge-owner-replay**: `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPIRenderedAndMerge$ -count=1`. Exit 1; person_api_evidence_test.go:71: HTTP 200, want 409. Restored byte-for-byte: yes. |
| Full report: `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-10-report.md`. No agents, live provider runs, sign-ins, enrolment, credential homes, make ci or full suite. Scratch stayed under on-disk TMPDIR and host Go caches stayed at their defaults. No persistent process was started. |
| + |
| + |
| +## Fix round 1 |
| + |
| +Status: DONE_WITH_CONCERNS. The requested Task 10 findings are fixed and the targeted tests pass. Five existing staticcheck warnings in unchanged conversation files remain outside this fix. No push, merge, deployment, provider session, sign-in, enrolment, server or other agent was started. |
| + |
| +Commit subject: `fix: report current revisions and stop unbounded person API cursors`. |
| +Author: `codex <codex~paul@keymail.dev>`. |
| + |
| +### Changes and review evidence |
| + |
| +The earlier report's claim about `current_revision` was wrong. `serve` now calls the revision reader after the failed mutation transaction and authenticates again before that read. Every mutation operation maps to its authoritative resource or creation scope. Plan edits, approvals and project correction use the plan revision; task actions use the task revision; preferences (including deletion tombstones), private source messages, coordinator bindings, turns, target-person limits and settings use their own revisions. A failed or unauthorized revision lookup returns the corresponding error instead of a revision-less conflict. Tests advance the plan, preference, binding and settings to revision 2, submit a conflicting revision and check the returned value. They also check limits and a deleted preference, and deny foreign preference access. |
| + |
| +The earlier snapshot description is superseded. Person API list GETs use the read transaction path, including preferences, cards, conversations and threads. Existing streams are read without lazy inserts. Missing private streams return empty data; API reads no longer create historical task threads. HTML's existing lazy initialization remains in place. List pagination creates no rows. The test installs INSERT, UPDATE and DELETE refusal triggers on every app table, pages each list repeatedly at limit=1, and also reads another person's uninitialized private streams. |
| + |
| +Cursors carry only positions and an expiry. AES-GCM authenticates and encrypts them using a key derived from the configured instance key. Scope includes the principal and route; conversation/thread cursors also bind the stream and preserve the sequence upper bound. There are no supported list filters in 3a: unknown query/filter fields are rejected with 422. The codec separately tests filter scope binding. Generic lists use ascending immutable IDs (address for people), and each page reads current projections. Inserts before the position cannot repeat prior items; inserts after it can appear. The deterministic interleaving test reads b, deletes d, inserts a and c, then gets c,f without deleted text. Wrong principal, wrong route, foreign instance, modified tokens and expired tokens are rejected. Cursors expire after 24 hours; changing the instance key invalidates them. |
| + |
| +Migration 0023 was the last migration on this branch, with no later migration depending on it, so it was edited in place as authorized. It now creates only person_api_requests; the stored-items cursor model/table is removed. All request columns are NOT NULL. Replay metadata has expires_at and an index, expires after 30 days, and expired rows are deleted in successful API mutation transactions. The migration upgrade/reopen/schema tests and the model/schema gate pass. This is an unreleased branch migration edit, not an upgrade for databases that already recorded the previous 0023 checksum. |
| + |
| +Native answer replay now checks current membership, task ownership/owner authority and exact canonical API request metadata before checking question revision or whether the question is still current. The result is saved in the answer transaction, including when an existing HTML answer matches. A retry returns the saved acknowledgement after the question is resolved and its assignment ends. Changed input and fresh requests still conflict; loss of answer permission denies replay. The existing answer canonicalization moved unchanged to QuestionAnswer.CanonicalJSON in runnerproto to keep the root package within its source budget. |
| + |
| +Encoded slashes are rejected before choosing a lane. Registered route matching uses RawPath when present, matching chi. Tests exercise encoded person, runner and enrolment paths through the real outer handler with a cross-origin cookie. |
| + |
| +The audience test now installs a deterministic person verifier, accepts a valid signed person credential, and checks distinct rejection reasons. Runner and cleanup tokens are registered in their production credential tables and first succeed on heartbeat/receipt lanes. Coordinator HTTP operations use runner credentials plus coordinator.v1 and fenced claims; there is no separate coordinator bearer format. A separately registered real runner credential succeeds on the coordinator poll lane and is refused by the person verifier for runner audience. A signed person token for another instance is refused for instance mismatch. Mixed cookie/bearer, invalid tokens, forged person fields and revoked sessions are also checked. |
| + |
| +Duplicate Idempotency-Key tests for plan edit, message route, coordinator binding and coordinator limits return byte-identical results with the original revision after it becomes stale. New keys with that stale revision and changed canonical bodies are rejected. Removal denies replay. Routing does not normally increment its source revision, so that test explicitly advances the source between first response and retry. Task selection parity compares the API and rendered /journey task list for owner and peer tasks, recent finished work and old finished work. |
| + |
| +### Base preference invalidation finding |
| + |
| +Created a detached throwaway worktree with `git worktree add --detach "$TMPDIR/equipo-task10-base-09aff24" 09aff24`. In that worktree, ran `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPreferencesAtomicInvalidation$' -count=1`: exit 1, `preferences_test.go:266: missing private invalidation [conversation/<topic> personal/<topic>]` (0.320s package time). Thus the old single-topic expectation already failed at 09aff24, before Task 10. The Task 10 expectations are retained; this fix does not edit preferences_test.go. The current test passes. Removed the temporary checkout with `git worktree remove "$TMPDIR/equipo-task10-base-09aff24"`; no prune was run. |
| + |
| +### Red and green verification |
| + |
| +The first new regression run reproduced writes on list reads (503 under refusal triggers), deleted preference text from a cursor, native replay returning 409 after resolution, and encoded-path routing returning 404. Initial fixture setup errors in revision/replay/parity tests were corrected before assessing behavior. |
| + |
| +To establish the pre-fix result with the final test fixtures, temporarily restored all changed production Go/SQL files to HEAD 03cef4b, removed the new read-only adapter, ran the following command, and restored every file in a finally block: |
| + |
| +`CGO_ENABLED=0 go test ./internal/plan3test -run '^TestPersonAPI(CurrentRevision|ReplayBeforeStale|ListReadsNoWrites|CursorFreshnessAndOrder|NativeReplayAfterResolution|EncodedPathCSRF|TaskListParity|RequestMetadataConstraintsAndExpiry)$' -count=1` |
| + |
| +Exit 1. CurrentRevision failed for plan, preference, binding, settings and limits (nil instead of 2/1). List reads failed with 503 on write-refusal triggers. CursorFreshnessAndOrder served deleted text. NativeReplayAfterResolution returned 409 instead of 200. EncodedPathCSRF returned 404. Metadata constraints were nullable. Replay ordering and task selection parity passed on the old implementation, settling those unverified findings without unnecessary behavior changes. |
| + |
| +Final restored checks: |
| + |
| +- `CGO_ENABLED=0 go test ./internal/equipo/kernel ./internal/equipo/personapi ./internal/plan3test -run '^Test(PersonAPI|CursorScope|PreferencesAtomicInvalidation)' -count=1`: exit 0; kernel 0.003s, personapi 0.004s, plan3test 5.461s. Includes OpenAPI route parity, migration upgrade, request expiry, real-handler authentication and all new regressions. |
| +- `CGO_ENABLED=0 go test ./internal/plan3test -run '^Test(ConversationPrivateAndThreadShared|ConversationCursorScopeAndExpiry|ConversationRouteRevisionAndCardResource|PreferencesCorrectionAndDelete|PreferencesSourcePrivacy|PreferencesForms|ConversationScriptlessSettings)$' -count=1`: exit 0, 2.075s. |
| +- `CGO_ENABLED=0 go test ./internal/equipotest -run '^Test(QuestionStaleAnswer|QuestionBrowserAuthorityHTTP|QuestionCurrentOwnerAndPolling|QuestionResolvedPermission|QuestionAnswererRoster|ClaudePermissionResponseBrowser)$' -count=1`: exit 0, 8.553s. |
| +- `make migration-check`: exit 0; runs only `CGO_ENABLED=0 go test ./internal/equipo -run '^TestMigrationModels$' -count=1`, 0.156s. |
| +- `make budget`: exit 0, all 31 directories within existing limits. An intermediate check found the root 23 lines over; the read composition and unchanged answer canonicalization were moved to their feature packages. No budget exemption changed. |
| +- `CGO_ENABLED=0 go vet ./internal/equipo ./internal/equipo/personapi ./internal/equipo/conversation ./internal/equipo/kernel ./internal/runnerproto ./internal/plan3test`: exit 0. |
| +- `CGO_ENABLED=0 go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./internal/equipo/personapi ./internal/equipo/kernel ./internal/runnerproto ./internal/equipo ./internal/plan3test`: exit 0. The unused currentRevision finding is resolved. |
| +- `gofmt -l` on every changed/new Go file: exit 0, no output. `git diff --check`: exit 0. |
| + |
| +A broader staticcheck command adding `./internal/equipo/conversation` exited 1 with existing ST1013 warnings at handlers.go:72,87,102 and settings.go:143, plus SA4006 at preferences.go:207. `git diff --exit-code HEAD -- internal/equipo/conversation/handlers.go internal/equipo/conversation/preferences.go internal/equipo/conversation/settings.go` exits 0, confirming these files were unchanged. No full suite or make ci was run. |
| + |
| +### Guard mutations |
| + |
| +Each mutation below was applied alone, the named test failed at an assertion (exit 1), and the original file was restored in a finally block before the next mutation. The final green commands above ran after restoration. |
| + |
| +| Guard disabled | Exact command | Observed failure | |
| +| --- | --- | --- | |
| +| current_revision | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPICurrentRevision$ -count=1` | current_revision nil for plan, preference, binding, settings and limits | |
| +| read_only | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPIListReadsNoWrites$ -count=1` | HTTP 503 instead of 200 when lazy writes hit refusal triggers | |
| +| keyset | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPICursorFreshnessAndOrder$ -count=1` | cursor never advanced | |
| +| scope | `CGO_ENABLED=0 go test ./internal/equipo/kernel -run ^TestCursorScopeIntegrityAndExpiry$ -count=1` | cursor scope ignored for another principal | |
| +| integrity | `CGO_ENABLED=0 go test ./internal/equipo/kernel -run ^TestCursorScopeIntegrityAndExpiry$ -count=1` | altered authenticated scope accepted | |
| +| cursor_expiry | `CGO_ENABLED=0 go test ./internal/equipo/kernel -run ^TestCursorScopeIntegrityAndExpiry$ -count=1` | expired cursor accepted | |
| +| native_replay | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPINativeReplayAfterResolution$ -count=1` | HTTP 409 instead of saved 200 after resolution | |
| +| encoded_path | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPIEncodedPathCSRF$ -count=1` | encoded person GET reached 404 | |
| +| metadata_expiry | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPIRequestMetadataConstraintsAndExpiry$ -count=1` | expired replay metadata retained | |
| +| not_null | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPIRequestMetadataConstraintsAndExpiry$ -count=1` | nullable required metadata | |
| +| canonical_body | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPINativeReplayAfterResolution$ -count=1` | changed native body returned 200 instead of 409 | |
| +| native_authority | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestPersonAPINativeReplayAfterResolution$ -count=1` | replay without answer permission returned 200 instead of 403 | |
| + |
| +### Copy and remaining limits |
| + |
| +New or changed user-facing runtime strings: none. Existing API copy keys and their pending review markers are unchanged. The relevant reused strings are: |
| + |
| +- `api.revision_conflict`: “This item changed. Fetch its current revision and try again.” |
| +- `api.cursor_expired`: “This page link expired. Fetch the list again.” |
| +- `api.invalid_input`: “Check the request fields and try again.” |
| + |
| +No copy-review server was started; the controller instruction overrides the generic copy workflow. README prose and OpenAPI wording were unchanged. |
| + |
| +Generic lists currently build their authorized projections before applying the keyset position in memory. This removes stored copies and write amplification, but does not add SQL-level paging of those projections. Conversation/thread paging applies its sequence position in the query. Existing HTML conversation cursor storage is unchanged. Existing application replay records remain authoritative across HTML and API; the 30-day expiry applies to the new API metadata only. |
| + |
| +The unrequested review nits (acknowledgement revision calculation, null native inputs, HEAD support and earlier layering decisions) remain outside this fix. The earlier live-release and copy-review gates remain in force. The staticcheck warnings listed above are the remaining verification concern. |
| + |
| +### Files changed in this round |
| + |
| +- `internal/equipo/app.go` |
| +- `internal/equipo/conversation/read_only.go` |
| +- `internal/equipo/conversation/store.go` |
| +- `internal/equipo/conversation/threads.go` |
| +- `internal/equipo/kernel/cursor.go` |
| +- `internal/equipo/kernel/cursor_test.go` |
| +- `internal/equipo/migrations/0023_person_api_requests.sql` |
| +- `internal/equipo/migrations/schema.sql` |
| +- `internal/equipo/person_api.go` |
| +- `internal/equipo/personapi/auth.go` |
| +- `internal/equipo/personapi/conversation.go` |
| +- `internal/equipo/personapi/handler.go` |
| +- `internal/equipo/personapi/reads.go` |
| +- `internal/equipo/personapi/requests.go` |
| +- `internal/equipo/personapi/types.go` |
| +- `internal/equipo/questions.go` |
| +- `internal/equipo/store.go` |
| +- `internal/plan3test/person_api_audiences_test.go` |
| +- `internal/plan3test/person_api_fixes_test.go` |
| +- `internal/plan3test/person_api_migration_test.go` |
| +- `internal/plan3test/person_api_operations_test.go` |
| +- `internal/plan3test/person_api_test.go` |
| +- `internal/runnerproto/question_answer_json.go` |
| + |
| +The tracked controller report and this ignored coordinator report were appended, preserving earlier entries. Work is saved on plan-3. Temporary worktrees and task scratch are removed before handoff; no task process remains running. |
diff --git a/internal/equipo/app.go b/internal/equipo/app.go| index 0d63df90..93651346 100644 |
| --- a/internal/equipo/app.go |
| +++ b/internal/equipo/app.go |
| @@ -145,6 +145,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.personCookie = func(r *http.Request) (personapi.PersonPrincipal, error) { |
| id, ok := authentication.SessionFrom(r) |
| if !ok { |
diff --git a/internal/equipo/conversation/read_only.go b/internal/equipo/conversation/read_only.go| new file mode 100644 |
| index 00000000..5713c638 |
| --- /dev/null |
| +++ b/internal/equipo/conversation/read_only.go |
| @@ -0,0 +1,57 @@ |
| +package conversation |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| + "context" |
| + "errors" |
| + "gorm.io/gorm" |
| +) |
| + |
| +// ReadOnly uses existing streams and authenticated positions without lazy writes. |
| +func (s *Store) ReadOnly(codec kernel.CursorCodec) *Store { |
| + s.readOnly = true |
| + s.cursorCodec = codec |
| + return s |
| +} |
| +func (s *Store) readMain(teamID string, actor kernel.Actor) (Main, error) { |
| + var row Main |
| + err := s.tx.Where("team_id=? AND person=?", teamID, actor.Address).First(&row).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return Main{TeamID: teamID, Person: actor.Address, Revision: 1}, nil |
| + } |
| + return row, err |
| +} |
| +func (s *Store) readThread(task TaskAccess) (Thread, error) { |
| + var row Thread |
| + err := s.tx.Where("task_id=? AND team_id=?", task.ID, task.TeamID).First(&row).Error |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return Thread{TaskID: task.ID, TeamID: task.TeamID, Revision: 1}, nil |
| + } |
| + return row, err |
| +} |
| + |
| +// ReadOnly retains application queries while replacing their transaction runner. |
| +func (s *Application) ReadOnly(read func(context.Context, func(*gorm.DB) error) error, codec kernel.CursorCodec) *Application { |
| + out := *s |
| + out.Write = read |
| + out.Conversation = func(tx *gorm.DB) *Store { return s.Conversation(tx).ReadOnly(codec) } |
| + return &out |
| +} |
| + |
| +func (s *Application) PreferenceRevision(ctx context.Context, a Actor, id string) (revision int64, err error) { |
| + err = s.Write(ctx, func(tx *gorm.DB) error { |
| + cs := s.Conversation(tx) |
| + main, e := cs.main(a) |
| + if e != nil { |
| + return e |
| + } |
| + if id == "" { |
| + revision = main.Revision |
| + return nil |
| + } |
| + row, _, e := cs.preference(main, id) |
| + revision = row.Revision |
| + return e |
| + }) |
| + return |
| +} |
diff --git a/internal/equipo/conversation/store.go b/internal/equipo/conversation/store.go| index 930d57e1..52e048e8 100644 |
| --- a/internal/equipo/conversation/store.go |
| +++ b/internal/equipo/conversation/store.go |
| @@ -27,8 +27,10 @@ type Dependencies struct { |
| ProposedCopy, RoutedCopy string |
| } |
| type Store struct { |
| - tx *gorm.DB |
| - deps Dependencies |
| + tx *gorm.DB |
| + deps Dependencies |
| + readOnly bool |
| + cursorCodec kernel.CursorCodec |
| } |
| func New(tx *gorm.DB, deps Dependencies) *Store { return &Store{tx: tx, deps: deps} } |
| @@ -37,6 +39,9 @@ func (s *Store) main(actor kernel.Actor) (Main, error) { |
| if err != nil { |
| return Main{}, err |
| } |
| + if s.readOnly { |
| + return s.readMain(teamID, actor) |
| + } |
| row := Main{ID: rand.Text(), TeamID: teamID, Person: actor.Address, Revision: 1} |
| if err = s.tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "team_id"}, {Name: "person"}}, DoNothing: true}).Create(&row).Error; err != nil { |
| return Main{}, err |
| @@ -181,7 +186,13 @@ func (s *Store) pageAfter(actor kernel.Actor, stream string, through, revision i |
| if limit < 1 || limit > 100 { |
| return page, s.deps.Invalid |
| } |
| - if cursor != "" { |
| + if cursor != "" && s.readOnly { |
| + var c cursorRecord |
| + if err := s.cursorCodec.Open(actor.Address+"\x00stream:"+stream, cursor, &c); err != nil { |
| + return page, s.deps.CursorExpired |
| + } |
| + after, through, page.Revision = c.After, c.Through, c.Revision |
| + } else if cursor != "" { |
| var c cursorRecord |
| err := s.tx.Where("id=? AND principal=? AND stream_id=?", cursor, actor.Address, stream).First(&c).Error |
| if errors.Is(err, gorm.ErrRecordNotFound) { |
| @@ -240,10 +251,18 @@ func (s *Store) pageAfter(actor kernel.Actor, stream string, through, revision i |
| } |
| if more { |
| c := cursorRecord{ID: rand.Text(), Principal: actor.Address, StreamID: stream, After: end, Through: through, Revision: page.Revision, ExpiresAt: time.Now().UTC().Add(24 * time.Hour)} |
| - if err := s.tx.Create(&c).Error; err != nil { |
| - return page, err |
| + if s.readOnly { |
| + token, err := s.cursorCodec.Seal(actor.Address+"\x00stream:"+stream, struct{ After, Through, Revision int64 }{end, through, page.Revision}) |
| + if err != nil { |
| + return page, err |
| + } |
| + page.NextCursor = token |
| + } else { |
| + if err := s.tx.Create(&c).Error; err != nil { |
| + return page, err |
| + } |
| + page.NextCursor = c.ID |
| } |
| - page.NextCursor = c.ID |
| } |
| } |
| return page, nil |
diff --git a/internal/equipo/conversation/threads.go b/internal/equipo/conversation/threads.go| index 97c6b1eb..99a42624 100644 |
| --- a/internal/equipo/conversation/threads.go |
| +++ b/internal/equipo/conversation/threads.go |
| @@ -40,7 +40,11 @@ func (s *Store) thread(actor kernel.Actor, id string) (Thread, TaskAccess, error |
| if task.TeamID != teamID { |
| return Thread{}, task, s.deps.NotFound |
| } |
| - row, err = EnsureThread(s.tx, task.ID, teamID) |
| + if s.readOnly { |
| + row, err = s.readThread(task) |
| + } else { |
| + row, err = EnsureThread(s.tx, task.ID, teamID) |
| + } |
| return row, task, err |
| } |
| func (s *Store) TaskThread(actor kernel.Actor, taskID, cursor string, limit int) (ConversationPage, error) { |
diff --git a/internal/equipo/kernel/cursor.go b/internal/equipo/kernel/cursor.go| new file mode 100644 |
| index 00000000..765ffc11 |
| --- /dev/null |
| +++ b/internal/equipo/kernel/cursor.go |
| @@ -0,0 +1,83 @@ |
| +package kernel |
| + |
| +import ( |
| + "crypto/aes" |
| + "crypto/cipher" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "time" |
| +) |
| + |
| +// CursorCodec authenticates opaque positions, never copies of resource contents. |
| +// The caller binds the principal, route and filters through scope. |
| +type CursorCodec struct { |
| + Key string |
| + Now func() time.Time |
| +} |
| + |
| +type cursorEnvelope struct { |
| + Position json.RawMessage |
| + ExpiresAt time.Time |
| +} |
| + |
| +func (c CursorCodec) now() time.Time { |
| + if c.Now != nil { |
| + return c.Now() |
| + } |
| + return time.Now() |
| +} |
| +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[:]) |
| + if err != nil { |
| + return nil, err |
| + } |
| + return cipher.NewGCM(block) |
| +} |
| +func (c CursorCodec) Seal(scope string, position any) (string, error) { |
| + a, err := c.aead() |
| + if err != nil { |
| + return "", err |
| + } |
| + raw, err := json.Marshal(position) |
| + if err != nil { |
| + return "", err |
| + } |
| + raw, err = json.Marshal(cursorEnvelope{raw, c.now().UTC().Add(24 * time.Hour)}) |
| + if err != nil { |
| + return "", err |
| + } |
| + nonce := make([]byte, a.NonceSize()) |
| + if _, err = rand.Read(nonce); err != nil { |
| + return "", err |
| + } |
| + return base64.RawURLEncoding.EncodeToString(a.Seal(nonce, nonce, raw, []byte(scope))), nil |
| +} |
| +func (c CursorCodec) Open(scope, token string, position any) error { |
| + a, err := c.aead() |
| + if err != nil { |
| + return err |
| + } |
| + raw, err := base64.RawURLEncoding.Strict().DecodeString(token) |
| + if err != nil || len(raw) < a.NonceSize() || len(raw) > 4096 { |
| + return errors.New("invalid cursor") |
| + } |
| + raw, err = a.Open(nil, raw[:a.NonceSize()], raw[a.NonceSize():], []byte(scope)) |
| + if err != nil { |
| + return err |
| + } |
| + var envelope cursorEnvelope |
| + if err = json.Unmarshal(raw, &envelope); err != nil { |
| + return err |
| + } |
| + if !c.now().Before(envelope.ExpiresAt) { |
| + return errors.New("expired cursor") |
| + } |
| + return json.Unmarshal(envelope.Position, position) |
| +} |
diff --git a/internal/equipo/kernel/cursor_test.go b/internal/equipo/kernel/cursor_test.go| new file mode 100644 |
| index 00000000..b462b4bf |
| --- /dev/null |
| +++ b/internal/equipo/kernel/cursor_test.go |
| @@ -0,0 +1,38 @@ |
| +package kernel |
| + |
| +import ( |
| + "strings" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestCursorScopeIntegrityAndExpiry(t *testing.T) { |
| + now := time.Now() |
| + codec := CursorCodec{Key: "instance-one", Now: func() time.Time { return now }} |
| + token, err := codec.Seal("person\x00route\x00filter", "last-id") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var pos string |
| + if err = codec.Open("person\x00route\x00filter", token, &pos); err != nil || pos != "last-id" { |
| + t.Fatal(pos, err) |
| + } |
| + for _, scope := range []string{"other\x00route\x00filter", "person\x00other\x00filter", "person\x00route\x00other"} { |
| + if codec.Open(scope, token, &pos) == nil { |
| + t.Fatal("cursor scope ignored", scope) |
| + } |
| + } |
| + for _, bad := range []string{token + "x", token[:len(token)-3], strings.Repeat("x", 10000)} { |
| + if codec.Open("person\x00route\x00filter", bad, &pos) == nil { |
| + t.Fatal("tamper accepted") |
| + } |
| + } |
| + other := CursorCodec{Key: "instance-two"} |
| + if other.Open("person\x00route\x00filter", token, &pos) == nil { |
| + t.Fatal("foreign instance cursor accepted") |
| + } |
| + now = now.Add(24 * time.Hour) |
| + if codec.Open("person\x00route\x00filter", token, &pos) == nil { |
| + t.Fatal("expired cursor accepted") |
| + } |
| +} |
diff --git a/internal/equipo/migrations/0023_person_api_requests.sql b/internal/equipo/migrations/0023_person_api_requests.sql| index 74e74a2b..558c62a2 100644 |
| --- a/internal/equipo/migrations/0023_person_api_requests.sql |
| +++ b/internal/equipo/migrations/0023_person_api_requests.sql |
| @@ -1,2 +1,2 @@ |
| -CREATE TABLE person_api_requests (principal text, operation text, resource text, request_id text, input_hash text, result text, created_at datetime, PRIMARY KEY (principal,operation,resource,request_id)); |
| -CREATE TABLE person_api_cursors (id text PRIMARY KEY, principal text, scope text, items text, revision integer, expires_at datetime); |
| +CREATE TABLE person_api_requests (principal text NOT NULL, operation text NOT NULL, resource text NOT NULL, request_id text NOT NULL, input_hash text NOT NULL, result text NOT NULL, created_at datetime NOT NULL, expires_at datetime NOT NULL, PRIMARY KEY (principal,operation,resource,request_id)); |
| +CREATE INDEX person_api_requests_expiry ON person_api_requests(expires_at); |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index cdbbbcc4..17990489 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -383,5 +383,5 @@ ALTER TABLE audit_events ADD COLUMN delegating_person text; |
| CREATE UNIQUE INDEX coordinator_active ON coordinator_turns(team_id,person) WHERE state='running'; |
| CREATE TABLE personal_preferences (id text PRIMARY KEY, text text, status text, source_message_id text, revision integer, team_id text, person text, source_revision integer, deleted_at datetime); |
| CREATE TABLE personal_settings (team_id text, person text, landing text, revision integer, PRIMARY KEY (team_id,person)); |
| -CREATE TABLE person_api_requests (principal text, operation text, resource text, request_id text, input_hash text, result text, created_at datetime, PRIMARY KEY (principal,operation,resource,request_id)); |
| -CREATE TABLE person_api_cursors (id text PRIMARY KEY, principal text, scope text, items text, revision integer, expires_at datetime); |
| +CREATE TABLE person_api_requests (principal text NOT NULL, operation text NOT NULL, resource text NOT NULL, request_id text NOT NULL, input_hash text NOT NULL, result text NOT NULL, created_at datetime NOT NULL, expires_at datetime NOT NULL, PRIMARY KEY (principal,operation,resource,request_id)); |
| +CREATE INDEX person_api_requests_expiry ON person_api_requests(expires_at); |
diff --git a/internal/equipo/person_api.go b/internal/equipo/person_api.go| index a03bcde6..786ffb47 100644 |
| --- a/internal/equipo/person_api.go |
| +++ b/internal/equipo/person_api.go |
| @@ -5,6 +5,8 @@ import ( |
| "errors" |
| "net/http" |
| + "amadan.net/oficina/equipo/internal/equipo/conversation" |
| + "amadan.net/oficina/equipo/internal/equipo/kernel" |
| "amadan.net/oficina/equipo/internal/equipo/personapi" |
| "github.com/go-chi/chi/v5" |
| "gorm.io/gorm" |
| @@ -31,26 +33,21 @@ func (s *Store) personAPIRouter() chi.Router { |
| } |
| return nil |
| }} |
| - return (&personapi.Handler{App: s, Authenticate: auth.Authenticate, Invalid: ErrInvalid, Forbidden: ErrForbidden, NotFound: ErrNotFound, Conflict: ErrConflict, Unavailable: ErrUnavailable, CursorExpired: ErrCursorExpired}).Router() |
| + return (&personapi.Handler{App: s, CursorCodec: kernel.CursorCodec{Key: s.personCursorKey}, Authenticate: auth.Authenticate, Invalid: ErrInvalid, Forbidden: ErrForbidden, NotFound: ErrNotFound, Conflict: ErrConflict, Unavailable: ErrUnavailable, CursorExpired: ErrCursorExpired}).Router() |
| } |
| -func (s *Store) PersonAPIPage(ctx context.Context, a Actor, scope, cursor string, limit int, in personapi.Result) (out personapi.Result, err error) { |
| - err = s.write(ctx, func(tx *gorm.DB) error { |
| - if _, e := currentRunnerMember(tx, a.Address); e != nil { |
| - return e |
| - } |
| - var e error |
| - out, e = personapi.Paginate(tx, a.Address, scope, cursor, limit, in, ErrCursorExpired) |
| - return e |
| - }) |
| - return |
| +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}) |
| } |
| -func (s *Store) PersonAPIRead(ctx context.Context, a Actor, op, id string) (personapi.Result, error) { |
| - reader := personapi.Reader{Conversation: s.coordinatorApplication(), TaskView: s.TaskView, Journey: s.Journey, NotFound: ErrNotFound, ReadTeam: func(ctx context.Context, a Actor, fn func(*gorm.DB, personapi.Team) error) error { |
| + |
| +func (s *Store) PersonAPIRead(ctx context.Context, a Actor, op, id, cursor string, limit int) (personapi.Result, error) { |
| + reader := personapi.Reader{Conversation: s.personAPIReader(a), TaskView: s.TaskView, Journey: s.Journey, NotFound: ErrNotFound, ReadTeam: func(ctx context.Context, a Actor, fn func(*gorm.DB, personapi.Team) error) error { |
| return s.readTeam(ctx, a, func(tx *gorm.DB, t Team) error { |
| return fn(tx, personapi.Team{ID: t.ID, Name: t.Name, RosterEpoch: t.RosterEpoch}) |
| }) |
| }} |
| - return reader.Read(ctx, a, op, id) |
| + return reader.Read(ctx, a, op, id, cursor, limit) |
| } |
| func (s *Store) PersonAPICancel(ctx context.Context, a Actor, id string, m Mutation) (personapi.Ack, error) { |
| _, err := s.cancelTask(ctx, a, id, &m) |
diff --git a/internal/equipo/personapi/auth.go b/internal/equipo/personapi/auth.go| index 37b7b8d0..5a6d4087 100644 |
| --- a/internal/equipo/personapi/auth.go |
| +++ b/internal/equipo/personapi/auth.go |
| @@ -83,6 +83,11 @@ func Dispatcher(origin string, runner, person chi.Routes, refuseRunner func(http |
| return func(next http.Handler) http.Handler { |
| browser := csrf.Protect(origin)(next) |
| return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + // Escaped separators must never select a different lane than chi's RawPath. |
| + if strings.Contains(strings.ToLower(r.URL.RawPath), "%2f") { |
| + WriteError(w, r, 422, "invalid_input", nil) |
| + return |
| + } |
| protocol := registered(r, runner, "/api/runner/v2") |
| personRoute := registered(r, person, "/api/v1") |
| public := r.Method == "POST" && (r.URL.Path == "/api/enrolments" || r.URL.Path == "/api/enrolments/token") |
| @@ -116,10 +121,14 @@ func Dispatcher(origin string, runner, person chi.Routes, refuseRunner func(http |
| } |
| } |
| func registered(r *http.Request, routes chi.Routes, prefix string) bool { |
| - if !strings.HasPrefix(r.URL.Path, prefix+"/") { |
| + path := r.URL.RawPath |
| + if path == "" { |
| + path = r.URL.Path |
| + } |
| + if !strings.HasPrefix(path, prefix+"/") { |
| return false |
| } |
| - return routes.Match(chi.NewRouteContext(), r.Method, strings.TrimPrefix(r.URL.Path, prefix)) |
| + return routes.Match(chi.NewRouteContext(), r.Method, strings.TrimPrefix(path, prefix)) |
| } |
| func PrincipalFrom(ctx context.Context) (PersonPrincipal, bool) { |
| p, ok := ctx.Value(principalKey{}).(PersonPrincipal) |
diff --git a/internal/equipo/personapi/conversation.go b/internal/equipo/personapi/conversation.go| index 8565a8e5..3e74f4fc 100644 |
| --- a/internal/equipo/personapi/conversation.go |
| +++ b/internal/equipo/personapi/conversation.go |
| @@ -55,31 +55,9 @@ func ProjectPlan(p taskplan.Plan) Plan { |
| } |
| func (h *Handler) read(ctx context.Context, a kernel.Actor, op, id, cursor string, limit int) (Result, error) { |
| switch op { |
| - case "conversation", "thread": |
| - var p conversation.ConversationPage |
| - var err error |
| - if op == "conversation" { |
| - p, err = h.App.Conversation(ctx, a, cursor, limit) |
| - } else { |
| - p, err = h.App.TaskThread(ctx, a, id, cursor, limit) |
| - } |
| - return Result{projectConversation(p), p.Revision}, err |
| - case "settings": |
| - v, err := h.App.PersonalSettings(ctx, a) |
| - return Result{Settings{v.Landing, v.Revision}, v.Revision}, err |
| case "plan": |
| v, err := h.App.TaskPlan(ctx, a, id) |
| return Result{ProjectPlan(v), v.Revision}, err |
| - case "preferences": |
| - v, err := h.App.Preferences(ctx, a) |
| - if err != nil { |
| - return Result{}, err |
| - } |
| - items := []Preference{} |
| - for _, p := range v { |
| - items = append(items, ProjectPreference(p)) |
| - } |
| - return h.App.PersonAPIPage(ctx, a, op, cursor, limit, Result{Value: items}) |
| case "capabilities": |
| return Result{struct { |
| Version string `json:"version"` |
| @@ -88,15 +66,15 @@ func (h *Handler) read(ctx context.Context, a kernel.Actor, op, id, cursor strin |
| Part string `json:"part"` |
| }{"1.0.0", true, false, "3a"}, 1}, nil |
| } |
| - out, err := h.App.PersonAPIRead(ctx, a, op, id) |
| + out, err := h.App.PersonAPIRead(ctx, a, op, id, cursor, limit) |
| if err != nil { |
| return out, err |
| } |
| switch op { |
| - case "people", "cards", "tasks", "journey", "needs_you": |
| - return h.App.PersonAPIPage(ctx, a, op, cursor, limit, out) |
| + case "preferences", "people", "cards", "tasks", "journey", "needs_you": |
| + return Paginate(h.CursorCodec, a.Address, op, cursor, limit, out, h.CursorExpired) |
| } |
| - if cursor != "" { |
| + if cursor != "" && op != "conversation" && op != "thread" { |
| return Result{}, h.Invalid |
| } |
| return out, nil |
diff --git a/internal/equipo/personapi/handler.go b/internal/equipo/personapi/handler.go| index 1de9eb9c..ff35f783 100644 |
| --- a/internal/equipo/personapi/handler.go |
| +++ b/internal/equipo/personapi/handler.go |
| @@ -16,6 +16,7 @@ import ( |
| type Handler struct { |
| App Application |
| + CursorCodec kernel.CursorCodec |
| Authenticate func(*http.Request) (PersonPrincipal, error) |
| Invalid, Forbidden, NotFound, Conflict, Unavailable, CursorExpired error |
| } |
| @@ -76,6 +77,7 @@ func (h *Handler) serve(route Route) http.Handler { |
| id := chi.URLParam(r, "id") |
| var out Result |
| var err error |
| + var input any |
| if route.Input == nil { |
| cursor, limit, e := ListQuery(r) |
| if e != nil { |
| @@ -97,7 +99,7 @@ func (h *Handler) serve(route Route) http.Handler { |
| WriteError(w, r, status, code, nil) |
| return |
| } |
| - input := route.Input() |
| + input = route.Input() |
| media, _, e := mime.ParseMediaType(r.Header.Get("Content-Type")) |
| if e != nil || media != "application/json" || Decode(r.Body, input) != nil { |
| WriteError(w, r, 422, "invalid_input", nil) |
| @@ -113,7 +115,20 @@ func (h *Handler) serve(route Route) http.Handler { |
| } |
| } |
| if err != nil { |
| - h.Failure(w, r, err) |
| + if h.revisionConflict(err) { |
| + if _, authErr := h.Authenticate(r); authErr != nil { |
| + h.Failure(w, r, authErr) |
| + return |
| + } |
| + current, readErr := h.currentRevision(r.Context(), a, route.Operation, id, input) |
| + if readErr != nil { |
| + h.Failure(w, r, readErr) |
| + return |
| + } |
| + WriteError(w, r, 409, "revision_conflict", current) |
| + } else { |
| + h.Failure(w, r, err) |
| + } |
| return |
| } |
| w.Header().Set("ETag", `"`+strconv.FormatInt(out.Revision, 10)+`"`) |
| @@ -145,7 +160,7 @@ func (h *Handler) Failure(w http.ResponseWriter, r *http.Request, err error) { |
| code, status = "forbidden", 403 |
| case errors.Is(err, h.NotFound): |
| code, status = "not_found", 404 |
| - case errors.Is(err, h.Conflict), errors.Is(err, team.ErrRevision), errors.Is(err, team.ErrConflict), errors.Is(err, team.ErrState): |
| + case h.revisionConflict(err): |
| code, status = "revision_conflict", 409 |
| case errors.Is(err, h.CursorExpired): |
| code, status = "cursor_expired", 410 |
| @@ -155,7 +170,10 @@ func (h *Handler) Failure(w http.ResponseWriter, r *http.Request, err error) { |
| type principalKey struct{} |
| -func (h *Handler) currentRevision(ctx context.Context, a kernel.Actor, op, id string) *int64 { |
| +func (h *Handler) revisionConflict(err error) bool { |
| + return errors.Is(err, h.Conflict) || errors.Is(err, team.ErrRevision) || errors.Is(err, team.ErrConflict) || errors.Is(err, team.ErrState) |
| +} |
| +func (h *Handler) currentRevision(ctx context.Context, a kernel.Actor, op, id string, input any) (*int64, error) { |
| switch op { |
| case "edit_plan", "approve_plan", "project": |
| op = "plan" |
| @@ -165,13 +183,27 @@ func (h *Handler) currentRevision(ctx context.Context, a kernel.Actor, op, id st |
| op = "question" |
| case "reset", "binding": |
| op = "coordinator" |
| + case "preference", "delete_preference": |
| + op = "preference" |
| + case "route": |
| + op = "message" |
| + case "retry": |
| + op, id = "turn", input.(*RetryInput).TurnID |
| + case "limits": |
| + id = input.(*LimitsInput).Person |
| + case "send": |
| + op = "conversation" |
| + case "send_thread": |
| + op = "thread" |
| + case "propose": |
| + op = "conversation" |
| case "settings": |
| default: |
| - return nil |
| + return nil, h.Unavailable |
| } |
| out, err := h.read(ctx, a, op, id, "", 50) |
| if err != nil { |
| - return nil |
| + return nil, err |
| } |
| - return &out.Revision |
| + return &out.Revision, nil |
| } |
diff --git a/internal/equipo/personapi/reads.go b/internal/equipo/personapi/reads.go| index f36ef232..f561e5e7 100644 |
| --- a/internal/equipo/personapi/reads.go |
| +++ b/internal/equipo/personapi/reads.go |
| @@ -30,8 +30,58 @@ func (s *Reader) member(tx *gorm.DB, address string) (out member, err error) { |
| err = tx.Table("members").Select("address,role,active,revision").Where("address=? AND active=?", address, true).Take(&out).Error |
| return |
| } |
| -func (s *Reader) Read(ctx context.Context, a kernel.Actor, op, id string) (Result, error) { |
| +func (s *Reader) Read(ctx context.Context, a kernel.Actor, op, id, cursor string, limit int) (Result, error) { |
| switch op { |
| + case "conversation", "thread": |
| + var page conversation.ConversationPage |
| + var err error |
| + if op == "conversation" { |
| + page, err = s.Conversation.ConversationPage(ctx, a, cursor, limit) |
| + } else { |
| + page, err = s.Conversation.TaskThread(ctx, a, id, cursor, limit) |
| + } |
| + return Result{projectConversation(page), page.Revision}, err |
| + case "preference": |
| + rev, err := s.Conversation.PreferenceRevision(ctx, a, id) |
| + return Result{Ack{rev}, rev}, err |
| + case "preferences": |
| + prefs, err := s.Conversation.Preferences(ctx, a) |
| + if err != nil { |
| + return Result{}, err |
| + } |
| + items := []Preference{} |
| + for _, p := range prefs { |
| + items = append(items, ProjectPreference(p)) |
| + } |
| + return Result{Value: items}, nil |
| + case "settings": |
| + v, err := s.Conversation.PersonalSettings(ctx, a) |
| + return Result{Settings{v.Landing, v.Revision}, v.Revision}, err |
| + |
| + case "message", "turn", "limits": |
| + var revision int64 |
| + err := s.ReadTeam(ctx, a, func(tx *gorm.DB, t Team) error { |
| + query := tx |
| + switch op { |
| + case "message": |
| + query = tx.Table("conversation_messages m").Joins("JOIN conversations c ON c.id=m.conversation_id").Where("m.id=? AND c.team_id=? AND c.person=?", id, t.ID, a.Address).Select("m.revision") |
| + case "turn": |
| + query = tx.Table("coordinator_turns").Where("id=? AND team_id=? AND person=?", id, t.ID, a.Address).Select("revision") |
| + case "limits": |
| + if err := s.Conversation.LimitsAuthority(tx, a, id); err != nil { |
| + return err |
| + } |
| + query = tx.Table("coordinator_limits").Where("account=? AND person=?", t.ID, id).Select("revision") |
| + } |
| + var row struct{ Revision int64 } |
| + err := query.Take(&row).Error |
| + if op == "limits" && errors.Is(err, gorm.ErrRecordNotFound) { |
| + return nil |
| + } |
| + revision = row.Revision |
| + return err |
| + }) |
| + return Result{Value: Ack{revision}, Revision: revision}, err |
| case "me", "people": |
| var out Result |
| err := s.ReadTeam(ctx, a, func(tx *gorm.DB, t Team) error { |
diff --git a/internal/equipo/personapi/requests.go b/internal/equipo/personapi/requests.go| index 09383007..10cc0b72 100644 |
| --- a/internal/equipo/personapi/requests.go |
| +++ b/internal/equipo/personapi/requests.go |
| @@ -4,38 +4,30 @@ import ( |
| "amadan.net/oficina/equipo/internal/equipo/kernel" |
| "bytes" |
| "context" |
| - "crypto/rand" |
| "crypto/sha256" |
| "encoding/binary" |
| "encoding/json" |
| "errors" |
| + "sort" |
| "time" |
| "gorm.io/gorm" |
| ) |
| type Request struct { |
| - Principal string `gorm:"primaryKey"` |
| - Operation string `gorm:"primaryKey"` |
| - Resource string `gorm:"primaryKey"` |
| - RequestID string `gorm:"primaryKey"` |
| - InputHash string |
| - Result string |
| - CreatedAt time.Time |
| + Principal string `gorm:"primaryKey;not null"` |
| + Operation string `gorm:"primaryKey;not null"` |
| + Resource string `gorm:"primaryKey;not null"` |
| + RequestID string `gorm:"primaryKey;not null"` |
| + InputHash string `gorm:"not null"` |
| + Result string `gorm:"not null"` |
| + CreatedAt time.Time `gorm:"not null"` |
| + ExpiresAt time.Time `gorm:"not null;index:person_api_requests_expiry"` |
| } |
| func (Request) TableName() string { return "person_api_requests" } |
| -type Cursor struct { |
| - ID string `gorm:"primaryKey"` |
| - Principal, Scope, Items string |
| - Revision int64 |
| - ExpiresAt time.Time |
| -} |
| - |
| -func (Cursor) TableName() string { return "person_api_cursors" } |
| - |
| -var Models = []any{&Request{}, &Cursor{}} |
| +var Models = []any{&Request{}} |
| type requestKey struct{} |
| @@ -54,6 +46,9 @@ func Record(tx *gorm.DB, ctx context.Context, conflict error) error { |
| if !ok { |
| return nil |
| } |
| + if err := tx.Where("expires_at <= ?", time.Now().UTC()).Delete(&Request{}).Error; err != nil { |
| + return err |
| + } |
| var old Request |
| err := tx.Where("principal=? AND operation=? AND resource=? AND request_id=?", r.Principal, r.Operation, r.Resource, r.RequestID).Take(&old).Error |
| if err == nil { |
| @@ -66,6 +61,7 @@ func Record(tx *gorm.DB, ctx context.Context, conflict error) error { |
| return err |
| } |
| r.CreatedAt = time.Now().UTC() |
| + r.ExpiresAt = r.CreatedAt.Add(30 * 24 * time.Hour) |
| return tx.Create(&r).Error |
| } |
| @@ -83,6 +79,9 @@ func Replay(tx *gorm.DB, ctx context.Context, out any, conflict error) (bool, er |
| if err != nil { |
| return false, err |
| } |
| + if !time.Now().Before(old.ExpiresAt) { |
| + return false, nil |
| + } |
| if old.InputHash != r.InputHash { |
| return false, conflict |
| } |
| @@ -110,51 +109,66 @@ func Revision(v any) int64 { |
| sum := sha256.Sum256(b) |
| return int64(binary.BigEndian.Uint64(sum[:8])>>1) | 1 |
| } |
| -func Paginate(tx *gorm.DB, principal, scope, cursor string, limit int, in Result, expired error) (Result, error) { |
| +func Paginate(codec kernel.CursorCodec, principal, scope, cursor string, limit int, in Result, expired error) (Result, error) { |
| var items []json.RawMessage |
| - revision := in.Revision |
| - if cursor != "" { |
| - var row Cursor |
| - err := tx.Where("id=? AND principal=? AND scope=?", cursor, principal, scope).Take(&row).Error |
| - if errors.Is(err, gorm.ErrRecordNotFound) || err == nil && !time.Now().Before(row.ExpiresAt) { |
| - return Result{}, expired |
| - } |
| - if err != nil { |
| - return Result{}, err |
| + raw, err := json.Marshal(in.Value) |
| + if err != nil { |
| + return Result{}, err |
| + } |
| + if err = json.Unmarshal(raw, &items); err != nil { |
| + return Result{}, err |
| + } |
| + if items == nil { |
| + items = []json.RawMessage{} |
| + } |
| + type entry struct { |
| + key string |
| + value json.RawMessage |
| + } |
| + entries := make([]entry, 0, len(items)) |
| + for _, item := range items { |
| + var key struct { |
| + ID string `json:"id"` |
| + Address string `json:"address"` |
| } |
| - if err = json.Unmarshal([]byte(row.Items), &items); err != nil { |
| + if err = json.Unmarshal(item, &key); err != nil { |
| return Result{}, err |
| } |
| - revision = row.Revision |
| - } else { |
| - b, err := json.Marshal(in.Value) |
| - if err != nil { |
| - return Result{}, err |
| + k := key.ID |
| + if scope == "people" { |
| + k = key.Address |
| } |
| - if err = json.Unmarshal(b, &items); err != nil { |
| - return Result{}, err |
| + if k == "" { |
| + return Result{}, errors.New("missing pagination key") |
| } |
| - if revision < 1 { |
| - revision = Revision(in.Value) |
| + entries = append(entries, entry{k, item}) |
| + } |
| + sort.Slice(entries, func(i, j int) bool { return entries[i].key < entries[j].key }) |
| + binding := principal + "\x00" + scope |
| + var after string |
| + if cursor != "" { |
| + if err = codec.Open(binding, cursor, &after); err != nil { |
| + return Result{}, expired |
| } |
| } |
| - if items == nil { |
| - items = []json.RawMessage{} |
| + revision := in.Revision |
| + if revision < 1 { |
| + revision = Revision(in.Value) |
| } |
| - out := Page[json.RawMessage]{Items: items, Revision: revision} |
| - if len(items) > limit { |
| - b, err := json.Marshal(items[limit:]) |
| - if err != nil { |
| - return Result{}, err |
| + out := Page[json.RawMessage]{Items: []json.RawMessage{}, Revision: revision} |
| + for i, e := range entries { |
| + if e.key <= after { |
| + continue |
| } |
| - row := Cursor{ID: rand.Text(), Principal: principal, Scope: scope, Items: string(b), Revision: revision, ExpiresAt: time.Now().UTC().Add(24 * time.Hour)} |
| - if err = tx.Create(&row).Error; err != nil { |
| - return Result{}, err |
| + out.Items = append(out.Items, e.value) |
| + if len(out.Items) == limit { |
| + if i < len(entries)-1 { |
| + out.NextCursor, err = codec.Seal(binding, e.key) |
| + } |
| + break |
| } |
| - out.Items = items[:limit] |
| - out.NextCursor = row.ID |
| } |
| - return Result{out, revision}, nil |
| + return Result{out, revision}, err |
| } |
| func CanonicalHash(input any) (string, error) { |
diff --git a/internal/equipo/personapi/types.go b/internal/equipo/personapi/types.go| index 6125effc..f959618a 100644 |
| --- a/internal/equipo/personapi/types.go |
| +++ b/internal/equipo/personapi/types.go |
| @@ -255,7 +255,6 @@ type Application interface { |
| AnswerQuestion(context.Context, kernel.Actor, string, int64, runnerproto.QuestionAnswer) error |
| ApproveRenderedChange(context.Context, kernel.Actor, string, string, string, string, string, kernel.Mutation) error |
| AcknowledgeMerge(context.Context, kernel.Actor, string, int64, string) error |
| - PersonAPIRead(context.Context, kernel.Actor, string, string) (Result, error) |
| + PersonAPIRead(context.Context, kernel.Actor, string, string, string, int) (Result, error) |
| PersonAPICancel(context.Context, kernel.Actor, string, kernel.Mutation) (Ack, error) |
| - PersonAPIPage(context.Context, kernel.Actor, string, string, int, Result) (Result, error) |
| } |
diff --git a/internal/equipo/questions.go b/internal/equipo/questions.go| index cffbfe98..e85922f0 100644 |
| --- a/internal/equipo/questions.go |
| +++ b/internal/equipo/questions.go |
| @@ -6,6 +6,7 @@ import ( |
| "errors" |
| "time" |
| + "amadan.net/oficina/equipo/internal/equipo/personapi" |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| "amadan.net/oficina/equipo/internal/runner" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| @@ -163,6 +164,10 @@ func (s *Store) answerQuestion(ctx context.Context, actor Actor, taskID, id stri |
| if !questionAnswerAllowed(member, task) { |
| return ErrForbidden |
| } |
| + var saved personapi.Ack |
| + if ok, err := personapi.Replay(tx, ctx, &saved, ErrConflict); ok || err != nil { |
| + return err |
| + } |
| if q.Revision != revision { |
| return ErrConflict |
| } |
| @@ -176,16 +181,7 @@ func (s *Store) answerQuestion(ctx context.Context, actor Actor, taskID, id stri |
| if value.ValidateAnswer(answer) != nil { |
| return ErrInvalid |
| } |
| - raw, err := json.Marshal(answer) |
| - if err != nil { |
| - return ErrInvalid |
| - } |
| - // Canonicalize opaque answers so object key order cannot create new effects. |
| - var canonical any |
| - if err := json.Unmarshal(raw, &canonical); err != nil { |
| - return ErrInvalid |
| - } |
| - raw, err = json.Marshal(canonical) |
| + raw, err := answer.CanonicalJSON() |
| if err != nil { |
| return ErrInvalid |
| } |
| @@ -193,7 +189,7 @@ func (s *Store) answerQuestion(ctx context.Context, actor Actor, taskID, id stri |
| if q.Answer != string(raw) || q.AnsweredBy != member.Address { |
| return ErrConflict |
| } |
| - return nil |
| + return personapi.SaveResult(tx, ctx, personapi.Ack{Revision: revision}, ErrConflict) |
| } |
| q.State = "answered" |
| q.Answer = string(raw) |
| @@ -207,7 +203,10 @@ func (s *Store) answerQuestion(ctx context.Context, actor Actor, taskID, id stri |
| return err |
| } |
| } |
| - return appendAudit(tx, actor, "question.answer", id) |
| + if err := appendAudit(tx, actor, "question.answer", id); err != nil { |
| + return err |
| + } |
| + return personapi.SaveResult(tx, ctx, personapi.Ack{Revision: revision}, ErrConflict) |
| }) |
| } |
| func (e *Execution) questionAnswers(ctx context.Context, tx *gorm.DB, a runnerAssignment) ([]runnerproto.Question, error) { |
diff --git a/internal/equipo/store.go b/internal/equipo/store.go| index 00796412..dd3bfa6a 100644 |
| --- a/internal/equipo/store.go |
| +++ b/internal/equipo/store.go |
| @@ -49,6 +49,7 @@ type Store struct { |
| personBearer personapi.VerifyPersonBearer |
| personCookie func(*http.Request) (personapi.PersonPrincipal, error) |
| personOrigin string |
| + personCursorKey string |
| notifier JobNotifier |
| db *db.DB |
| execution *Execution |
diff --git a/internal/plan3test/person_api_audiences_test.go b/internal/plan3test/person_api_audiences_test.go| new file mode 100644 |
| index 00000000..dff98875 |
| --- /dev/null |
| +++ b/internal/plan3test/person_api_audiences_test.go |
| @@ -0,0 +1,135 @@ |
| +package plan3test |
| + |
| +import ( |
| + "context" |
| + "crypto/hmac" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "fmt" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +func TestPersonAPIAuthAudiences(t *testing.T) { |
| + f, x, principal, request, _ := nativeConversationFixture(t) |
| + token := func(b byte) string { |
| + return base64.RawURLEncoding.EncodeToString([]byte(strings.Repeat(string(b), 32))) |
| + } |
| + runner, cleanup, coordinator := token('r'), token('c'), token('o') |
| + hash := func(aud, token string) string { |
| + sum := sha256.Sum256([]byte(aud + "\x00" + token)) |
| + return hex.EncodeToString(sum[:]) |
| + } |
| + f.exec(t, "UPDATE runner_credentials SET token_hash=?,expires_at=? WHERE id='fixture-credential'", hash(runnerproto.RunnerAudience, runner), time.Now().Add(time.Hour)) |
| + f.exec(t, `INSERT INTO runner_credentials(id,runner_id,instance_id,audience,person,machine_key_hash,token_hash,expires_at) |
| + SELECT 'coordinator-credential',runner_id,instance_id,audience,person,machine_key_hash,?,expires_at FROM runner_credentials WHERE id='fixture-credential'`, hash(runnerproto.RunnerAudience, coordinator)) |
| + f.exec(t, "UPDATE runner_cleanups SET token_hash=? WHERE assignment_id=?", hash(runnerproto.CleanupAudience, cleanup), request.AssignmentID) |
| + type claims struct{ Instance, Audience, Address string } |
| + sign := func(c claims) string { |
| + payload := base64.RawURLEncoding.EncodeToString([]byte(jsonBody(t, c))) |
| + mac := hmac.New(sha256.New, []byte("deterministic-person-test-key")) |
| + mac.Write([]byte(payload)) |
| + return payload + "." + base64.RawURLEncoding.EncodeToString(mac.Sum(nil)) |
| + } |
| + native := sign(claims{f.TeamID, "person", owner.Address}) |
| + foreign := sign(claims{"other-instance", "person", owner.Address}) |
| + reason := "" |
| + verifier := func(_ context.Context, token string) (personapi.PersonPrincipal, error) { |
| + deny := func(why string) (personapi.PersonPrincipal, error) { |
| + reason = why |
| + return personapi.PersonPrincipal{}, fmt.Errorf("fixture: %s", why) |
| + } |
| + for _, c := range []struct{ table, aud, why string }{{"runner_credentials", runnerproto.RunnerAudience, "runner_audience"}, {"runner_cleanups", runnerproto.CleanupAudience, "cleanup_audience"}} { |
| + if f.count(t, "SELECT count(*) FROM "+c.table+" WHERE token_hash=?", hash(c.aud, token)) > 0 { |
| + return deny(c.why) |
| + } |
| + } |
| + parts := strings.Split(token, ".") |
| + if len(parts) != 2 { |
| + return deny("invalid_token") |
| + } |
| + mac := hmac.New(sha256.New, []byte("deterministic-person-test-key")) |
| + mac.Write([]byte(parts[0])) |
| + sig, err := base64.RawURLEncoding.DecodeString(parts[1]) |
| + if err != nil || !hmac.Equal(sig, mac.Sum(nil)) { |
| + return deny("invalid_signature") |
| + } |
| + raw, err := base64.RawURLEncoding.DecodeString(parts[0]) |
| + if err != nil { |
| + return deny("invalid_token") |
| + } |
| + var c claims |
| + if json.Unmarshal(raw, &c) != nil { |
| + return deny("invalid_token") |
| + } |
| + if c.Audience != "person" { |
| + return deny("wrong_audience") |
| + } |
| + if c.Instance != f.TeamID { |
| + return deny("other_instance") |
| + } |
| + reason = "accepted" |
| + return personapi.PersonPrincipal{Address: c.Address, CredentialID: "test-device", SessionEpoch: time.Now().Unix()}, nil |
| + } |
| + apiRouter(t, f, verifier) |
| + do := func(method, path, auth, body string, cookie bool) *httptest.ResponseRecorder { |
| + r := httptest.NewRequest(method, path, strings.NewReader(body)) |
| + r.Header.Set("Authorization", auth) |
| + r.Header.Set("Content-Type", "application/json") |
| + if cookie { |
| + r.AddCookie(f.Cookies[owner.Address]) |
| + r.Header.Set("Origin", origin) |
| + } |
| + w := httptest.NewRecorder() |
| + f.Handler.ServeHTTP(w, r) |
| + return w |
| + } |
| + // Prove each protocol credential is valid on its own production lane. |
| + expectHTTP(t, do("POST", "/api/runner/v2/heartbeat", "Bearer "+runner, `{"version":2,"request_id":"heartbeat"}`, false), 200) |
| + // Coordinator operations use runner credentials plus coordinator.v1 and a fenced claim, |
| + // not a separate person-compatible coordinator bearer format. |
| + expectHTTP(t, do("POST", "/api/runner/v2/coordinator/poll", "Bearer "+coordinator, `{"version":2,"capabilities":["coordinator.v1"]}`, false), 200) |
| + request.RequestID = "audience-intent" |
| + request.Intent = &team.IntentSpec{Key: "audience-turn", Operation: team.OpProviderCall, Payload: []byte(`{"task":"research"}`), Reserve: team.Usage{InputTokens: 10, OutputTokens: 10}} |
| + action, err := x.Mutate(ctx, principal, "intend", request) |
| + must(t, err) |
| + request.ActionID = action.(team.ActionID) |
| + request.Intent = nil |
| + request.RequestID = "audience-observation" |
| + request.Receipt = &team.Receipt{ID: "audience-receipt", Outcome: "success"} |
| + wire, err := runnerproto.Marshal(request) |
| + must(t, err) |
| + expectHTTP(t, do("POST", "/api/runner/v2/receipts", "Bearer "+runner, string(wire), false), 200) |
| + request.RequestID = "audience-cleanup" |
| + wire, err = runnerproto.Marshal(request) |
| + must(t, err) |
| + expectHTTP(t, do("POST", "/api/runner/v2/receipts", "Cleanup "+cleanup, string(wire), false), 200) |
| + expectHTTP(t, do("GET", "/api/v1/me", "Bearer "+native, "", false), 200) |
| + for _, tc := range []struct{ name, token, reason string }{{"runner", runner, "runner_audience"}, {"cleanup", cleanup, "cleanup_audience"}, {"coordinator", coordinator, "runner_audience"}, {"other-instance", foreign, "other_instance"}, {"invalid", "invalid", "invalid_token"}} { |
| + t.Run(tc.name, func(t *testing.T) { |
| + reason = "" |
| + w := do("GET", "/api/v1/me", "Bearer "+tc.token, "", false) |
| + expectHTTP(t, w, 401) |
| + if reason != tc.reason { |
| + t.Fatalf("rejection reason %q, want %q", reason, tc.reason) |
| + } |
| + if !strings.HasPrefix(w.Header().Get("Content-Type"), "application/json") { |
| + t.Fatal("auth returned HTML") |
| + } |
| + }) |
| + } |
| + expectHTTP(t, do("GET", "/api/v1/me", "Bearer "+native, "", true), 401) |
| + expectHTTP(t, apiRequest(t, f, equipo.Actor{}, "GET", "/api/v1/me", "", "", ""), 401) |
| + expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/conversation/messages", `{"body":"x","person":"peer@example.com"}`, "forged", ""), 422) |
| + f.exec(t, "DELETE FROM sessions WHERE subject=?", owner.Address) |
| + expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/me", "", "", ""), 401) |
| +} |
diff --git a/internal/plan3test/person_api_fixes_test.go b/internal/plan3test/person_api_fixes_test.go| new file mode 100644 |
| index 00000000..989e652a |
| --- /dev/null |
| +++ b/internal/plan3test/person_api_fixes_test.go |
| @@ -0,0 +1,304 @@ |
| +package plan3test |
| + |
| +import ( |
| + "fmt" |
| + "net/http/httptest" |
| + "net/url" |
| + "sort" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| +) |
| + |
| +func TestPersonAPICurrentRevision(t *testing.T) { |
| + f, _, _, b := coordinatorFixture(t) |
| + apiRouter(t, f, nil) |
| + p := apiFixPlan(t, f) |
| + pref, err := f.Store.SetPreference(ctx, owner, equipo.Preference{Text: "original", Status: "confirmed"}, equipo.Mutation{RequestID: "pref"}) |
| + must(t, err) |
| + p.Steps[0].Instructions = "updated" |
| + p, err = f.Store.EditPlan(ctx, owner, p, equipo.Mutation{RequestID: "advance-plan", Revision: p.Revision}) |
| + must(t, err) |
| + pref.Text = "updated" |
| + pref, err = f.Store.SetPreference(ctx, owner, pref, equipo.Mutation{RequestID: "advance-pref", Revision: pref.Revision}) |
| + must(t, err) |
| + b, err = f.Store.SaveCoordinatorBinding(ctx, owner, "fixture-runner", "codex", equipo.Mutation{RequestID: "advance-binding", Revision: b.Revision}) |
| + must(t, err) |
| + expectHTTP(t, apiRequest(t, f, owner, "PATCH", "/api/v1/me/settings", `{"landing":"work"}`, "advance-settings", `"1"`), 200) |
| + cases := []struct { |
| + name, path, body, rev string |
| + want int64 |
| + }{ |
| + {"plan", "/tasks/" + p.TaskID + "/plan", jsonBody(t, personapi.ProjectPlan(p).PlanInput), `"99"`, p.Revision}, |
| + {"preference", "/preferences/" + pref.ID, `{"text":"changed"}`, `"99"`, pref.Revision}, |
| + {"binding", "/coordinator", `{"runner_id":"fixture-runner","connection_id":"codex"}`, `"99"`, b.Revision}, |
| + {"settings", "/me/settings", `{"landing":"work"}`, `"99"`, 2}, |
| + {"limits", "/coordinator/limits", `{"person":"owner@example.com","limits":{"calls":23,"input_tokens":200000,"output_tokens":40000,"seconds":10000}}`, `"99"`, 1}, |
| + } |
| + for _, tc := range cases { |
| + t.Run(tc.name, func(t *testing.T) { |
| + w := apiRequest(t, f, owner, "PATCH", "/api/v1"+tc.path, tc.body, tc.name, tc.rev) |
| + expectHTTP(t, w, 409) |
| + e := apiValue[personapi.Error](t, w) |
| + if e.Code != "revision_conflict" || e.CurrentRevision == nil || *e.CurrentRevision != tc.want { |
| + t.Fatalf("current revision: %+v; want %d", e, tc.want) |
| + } |
| + }) |
| + } |
| + expectHTTP(t, apiRequest(t, f, owner, "DELETE", "/api/v1/preferences/"+pref.ID, `{}`, "delete-pref", fmt.Sprintf(`"%d"`, pref.Revision)), 200) |
| + conflict := apiRequest(t, f, owner, "PATCH", "/api/v1/preferences/"+pref.ID, `{"text":"restore"}`, "stale-deleted", `"1"`) |
| + expectHTTP(t, conflict, 409) |
| + e := apiValue[personapi.Error](t, conflict) |
| + if e.CurrentRevision == nil || *e.CurrentRevision != pref.Revision+1 { |
| + t.Fatal("missing deleted preference revision", e) |
| + } |
| + expectHTTP(t, apiRequest(t, f, peer, "PATCH", "/api/v1/preferences/"+pref.ID, `{"text":"foreign"}`, "foreign", `"1"`), 404) |
| + |
| +} |
| + |
| +func TestPersonAPIReplayBeforeStale(t *testing.T) { |
| + for _, op := range []string{"plan", "route", "binding", "limits"} { |
| + t.Run(op, func(t *testing.T) { |
| + f, _, _, b := coordinatorFixture(t) |
| + apiRouter(t, f, nil) |
| + p := apiFixPlan(t, f) |
| + method, path, body, changed, rev := "PATCH", "", "", "", `"1"` |
| + switch op { |
| + case "plan": |
| + path = "/api/v1/tasks/" + p.TaskID + "/plan" |
| + in := personapi.ProjectPlan(p).PlanInput |
| + in.Steps[0].Instructions = "First edit" |
| + body = jsonBody(t, in) |
| + in.Steps[0].Instructions = "Different edit" |
| + changed = jsonBody(t, in) |
| + case "route": |
| + msg, err := f.Store.SendMessage(ctx, owner, "", "route source", equipo.Mutation{RequestID: "source"}) |
| + must(t, err) |
| + method, path = "POST", "/api/v1/conversation/messages/"+msg.ID+"/route" |
| + body = jsonBody(t, personapi.RouteInput{TaskID: p.TaskID}) |
| + other := apiFixPlan(t, f) |
| + changed = jsonBody(t, personapi.RouteInput{TaskID: other.TaskID}) |
| + case "binding": |
| + path = "/api/v1/coordinator" |
| + body = `{"runner_id":"fixture-runner","connection_id":"codex"}` |
| + changed = `{"runner_id":"fixture-runner","connection_id":"claude"}` |
| + rev = fmt.Sprintf(`"%d"`, b.Revision) |
| + case "limits": |
| + path = "/api/v1/coordinator/limits" |
| + body = `{"person":"owner@example.com","limits":{"calls":23,"input_tokens":200000,"output_tokens":40000,"seconds":10000}}` |
| + changed = strings.Replace(body, `"calls":23`, `"calls":22`, 1) |
| + } |
| + first := apiRequest(t, f, owner, method, path, body, "retry", rev) |
| + expectHTTP(t, first, 200) |
| + if op == "route" { |
| + f.exec(t, "UPDATE conversation_messages SET revision=revision+1 WHERE id=?", strings.Split(path, "/")[5]) |
| + } |
| + replay := apiRequest(t, f, owner, method, path, body, "retry", rev) |
| + expectHTTP(t, replay, 200) |
| + if first.Body.String() != replay.Body.String() { |
| + t.Fatal("saved result changed") |
| + } |
| + expectHTTP(t, apiRequest(t, f, owner, method, path, changed, "retry", rev), 409) |
| + expectHTTP(t, apiRequest(t, f, owner, method, path, body, "new-key", rev), 409) |
| + f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address) |
| + expectHTTP(t, apiRequest(t, f, owner, method, path, body, "retry", rev), 403) |
| + }) |
| + } |
| +} |
| + |
| +func TestPersonAPIListReadsNoWrites(t *testing.T) { |
| + f := newFixture(t) |
| + p := proposed(t, f) |
| + for i := 0; i < 3; i++ { |
| + _, err := f.Store.SetPreference(ctx, owner, equipo.Preference{Text: fmt.Sprintf("private %d", i), Status: "confirmed"}, equipo.Mutation{RequestID: fmt.Sprint(i)}) |
| + must(t, err) |
| + _, err = f.Store.SendMessage(ctx, owner, "", "message", equipo.Mutation{RequestID: fmt.Sprintf("main-%d", i)}) |
| + must(t, err) |
| + _, err = f.Store.SendMessage(ctx, owner, p.TaskID, "thread", equipo.Mutation{RequestID: fmt.Sprintf("thread-%d", i)}) |
| + must(t, err) |
| + } |
| + // Reject every attempted write, including lazy stream creation and cursor inserts. |
| + rows, err := f.DB.Writer().Query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'") |
| + must(t, err) |
| + var tables []string |
| + for rows.Next() { |
| + var table string |
| + must(t, rows.Scan(&table)) |
| + tables = append(tables, table) |
| + } |
| + must(t, rows.Close()) |
| + for _, table := range tables { |
| + for _, event := range []string{"INSERT", "UPDATE", "DELETE"} { |
| + f.exec(t, fmt.Sprintf(`CREATE TRIGGER "deny_%s_%s" BEFORE %s ON "%s" BEGIN SELECT RAISE(ABORT,'read attempted write'); END`, table, event, event, table)) |
| + } |
| + } |
| + for _, path := range []string{"people", "preferences", "conversation/cards", "tasks", "journey", "needs-you", "conversation", "tasks/" + p.TaskID + "/thread"} { |
| + t.Run(path, func(t *testing.T) { |
| + for repeat := 0; repeat < 3; repeat++ { |
| + cursor := "" |
| + for page := 0; page < 20; page++ { |
| + w := apiRequest(t, f, owner, "GET", "/api/v1/"+path+"?limit=1&cursor="+url.QueryEscape(cursor), "", "", "") |
| + expectHTTP(t, w, 200) |
| + value := apiValue[struct { |
| + NextCursor string `json:"next_cursor"` |
| + }](t, w) |
| + cursor = value.NextCursor |
| + if cursor == "" { |
| + break |
| + } |
| + if page == 19 { |
| + t.Fatal("paging did not terminate") |
| + } |
| + } |
| + } |
| + }) |
| + } |
| + for _, path := range []string{"conversation", "preferences", "conversation/cards"} { |
| + expectHTTP(t, apiRequest(t, f, peer, "GET", "/api/v1/"+path, "", "", ""), 200) |
| + } |
| + if f.count(t, "SELECT count(*) FROM sqlite_master WHERE type='table' AND name='person_api_cursors'") != 0 && f.count(t, "SELECT count(*) FROM person_api_cursors") != 0 { |
| + t.Fatal("paging persisted cursor rows") |
| + } |
| +} |
| + |
| +func TestPersonAPICursorFreshnessAndOrder(t *testing.T) { |
| + f := newFixture(t) |
| + for _, id := range []string{"b", "d", "f"} { |
| + _, err := f.Store.SetPreference(ctx, owner, equipo.Preference{Text: "secret-" + id, Status: "confirmed"}, equipo.Mutation{RequestID: id}) |
| + must(t, err) |
| + f.exec(t, "UPDATE personal_preferences SET id=? WHERE text=?", id, "secret-"+id) |
| + } |
| + read := func(cursor string) personapi.Page[personapi.Preference] { |
| + w := apiRequest(t, f, owner, "GET", "/api/v1/preferences?limit=1&cursor="+url.QueryEscape(cursor), "", "", "") |
| + expectHTTP(t, w, 200) |
| + return apiValue[personapi.Page[personapi.Preference]](t, w) |
| + } |
| + first := read("") |
| + if len(first.Items) != 1 || first.Items[0].ID != "b" { |
| + t.Fatal(first) |
| + } |
| + expectHTTP(t, apiRequest(t, f, owner, "DELETE", "/api/v1/preferences/d", `{}`, "delete", `"1"`), 200) |
| + for _, id := range []string{"a", "c"} { |
| + _, err := f.Store.SetPreference(ctx, owner, equipo.Preference{Text: "secret-" + id, Status: "confirmed"}, equipo.Mutation{RequestID: id}) |
| + must(t, err) |
| + f.exec(t, "UPDATE personal_preferences SET id=? WHERE text=?", id, "secret-"+id) |
| + } |
| + var ids []string |
| + cursor := first.NextCursor |
| + for pages := 0; cursor != ""; pages++ { |
| + if pages > 20 { |
| + t.Fatal("cursor never advanced") |
| + } |
| + page := read(cursor) |
| + for _, item := range page.Items { |
| + if item.Text == "secret-d" { |
| + t.Fatal("deleted text served") |
| + } |
| + ids = append(ids, item.ID) |
| + } |
| + cursor = page.NextCursor |
| + } |
| + if strings.Join(ids, ",") != "c,f" { |
| + t.Fatalf("unstable keyset: %v", ids) |
| + } |
| + expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/preferences?cursor="+url.QueryEscape(first.NextCursor+"x"), "", "", ""), 410) |
| +} |
| + |
| +func TestPersonAPINativeReplayAfterResolution(t *testing.T) { |
| + f, _, _, _, q := nativeConversationFixture(t) |
| + apiRouter(t, f, nil) |
| + path := "/api/v1/questions/" + q.ID + "/answer" |
| + body := `{"kind":"native","behavior":"allow","updated_input":{"answers":{"Which?":"Blue"}}}` |
| + first := apiRequest(t, f, owner, "POST", path, body, "answer", `"1"`) |
| + expectHTTP(t, first, 200) |
| + f.exec(t, "UPDATE questions SET state='invalid',expires_at=? WHERE id=?", time.Now().Add(-time.Hour), q.ID) |
| + f.exec(t, "UPDATE runner_assignments SET state='finished' WHERE id=?", q.AssignmentID) |
| + replay := apiRequest(t, f, owner, "POST", path, body, "answer", `"1"`) |
| + expectHTTP(t, replay, 200) |
| + if first.Body.String() != replay.Body.String() { |
| + t.Fatal("replay result changed") |
| + } |
| + expectHTTP(t, apiRequest(t, f, owner, "POST", path, strings.Replace(body, "Blue", "Red", 1), "answer", `"1"`), 409) |
| + expectHTTP(t, apiRequest(t, f, owner, "POST", path, body, "new", `"1"`), 409) |
| + f.exec(t, "UPDATE members SET role='member' WHERE address=?", owner.Address) |
| + f.exec(t, "UPDATE tasks SET requester=? WHERE id=?", peer.Address, q.TaskID) |
| + expectHTTP(t, apiRequest(t, f, owner, "POST", path, body, "answer", `"1"`), 403) |
| + f.exec(t, "UPDATE members SET active=0 WHERE address=?", owner.Address) |
| + expectHTTP(t, apiRequest(t, f, owner, "POST", path, body, "answer", `"1"`), 403) |
| +} |
| + |
| +func TestPersonAPIEncodedPathCSRF(t *testing.T) { |
| + f := newFixture(t) |
| + for _, path := range []string{"/api%2Fv1/me", "/api%2fv1/conversation/messages", "/api%2Frunner/v2/heartbeat", "/api%2Fenrolments"} { |
| + for _, method := range []string{"GET", "POST"} { |
| + r := httptest.NewRequest(method, path, strings.NewReader(`{}`)) |
| + r.AddCookie(f.Cookies[owner.Address]) |
| + r.Header.Set("Origin", "https://evil.example") |
| + w := httptest.NewRecorder() |
| + f.Handler.ServeHTTP(w, r) |
| + if w.Code != 422 && w.Code != 403 { |
| + t.Fatalf("%s %s bypassed dispatcher protection: %d", method, path, w.Code) |
| + } |
| + } |
| + } |
| +} |
| + |
| +func TestPersonAPITaskListParity(t *testing.T) { |
| + f := newFixture(t) |
| + base := f.createTask(t) |
| + f.exec(t, "DELETE FROM tasks WHERE id=?", base.ID) |
| + for _, id := range []string{"active", "peer-task", "old-finished", "recent-finished"} { |
| + task := base |
| + task.PlanRevision = 0 |
| + task.ID = id |
| + task.RequestID = id |
| + if id == "peer-task" { |
| + task.Requester = peer.Address |
| + } |
| + must(t, f.DB.G.Create(&task).Error) |
| + f.exec(t, "INSERT INTO task_outboxes(task_id,state,engineering,review) VALUES(?,?,?,?)", id, "pending", "", "") |
| + } |
| + for _, id := range []string{"old-finished", "recent-finished"} { |
| + f.exec(t, "UPDATE tasks SET state='cancelled' WHERE id=?", id) |
| + at := time.Now() |
| + if id == "old-finished" { |
| + at = at.Add(-14 * 24 * time.Hour) |
| + } |
| + f.exec(t, "INSERT INTO audit_events(actor,kind,record_id,at) VALUES(?,?,?,?)", owner.Address, "task.cancel", id, at) |
| + } |
| + w := apiRequest(t, f, owner, "GET", "/api/v1/tasks", "", "", "") |
| + expectHTTP(t, w, 200) |
| + page := apiValue[personapi.Page[personapi.Task]](t, w) |
| + var ids []string |
| + for _, task := range page.Items { |
| + ids = append(ids, task.ID) |
| + } |
| + sort.Strings(ids) |
| + if strings.Join(ids, ",") != "active,peer-task,recent-finished" { |
| + t.Fatal(ids) |
| + } |
| + html := f.get(t, owner, "/journey") |
| + expectHTTP(t, html, 200) |
| + for _, id := range []string{"active", "peer-task", "old-finished", "recent-finished"} { |
| + present := strings.Contains(html.Body.String(), `href="/tasks/`+id+`"`) |
| + if present != (id != "old-finished") { |
| + t.Fatalf("HTML selection differs for %s", id) |
| + } |
| + } |
| +} |
| + |
| +func apiFixPlan(t *testing.T, f *fixture) taskplan.Plan { |
| + t.Helper() |
| + var project int64 |
| + must(t, f.DB.Writer().QueryRow("SELECT project_id FROM tasks LIMIT 1").Scan(&project)) |
| + p := taskplan.BugPlan("", project) |
| + p.Steps[0].Instructions = "fixture symptom" |
| + p.Revision = 0 |
| + out, err := f.Store.ProposePlan(ctx, owner, p, equipo.Mutation{RequestID: fmt.Sprintf("plan-%d", time.Now().UnixNano())}) |
| + must(t, err) |
| + return out |
| +} |
diff --git a/internal/plan3test/person_api_migration_test.go b/internal/plan3test/person_api_migration_test.go| index 9e02de26..248d03e0 100644 |
| --- a/internal/plan3test/person_api_migration_test.go |
| +++ b/internal/plan3test/person_api_migration_test.go |
| @@ -56,3 +56,19 @@ func TestPersonAPIMigrationUpgrade(t *testing.T) { |
| t.Fatal("historical message lost") |
| } |
| } |
| + |
| +func TestPersonAPIRequestMetadataConstraintsAndExpiry(t *testing.T) { |
| + f := newFixture(t) |
| + if f.count(t, "SELECT count(*) FROM pragma_table_info('person_api_requests') WHERE \"notnull\"=0") != 0 { |
| + t.Fatal("nullable required metadata") |
| + } |
| + if f.count(t, "SELECT count(*) FROM pragma_index_info('person_api_requests_expiry') WHERE name='expires_at'") != 1 { |
| + t.Fatal("missing expiry index") |
| + } |
| + expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/conversation/messages", `{"body":"old"}`, "old", ""), 200) |
| + f.exec(t, "UPDATE person_api_requests SET expires_at='2000-01-01T00:00:00Z' WHERE request_id='old'") |
| + expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/conversation/messages", `{"body":"new"}`, "new", ""), 200) |
| + if f.count(t, "SELECT count(*) FROM person_api_requests WHERE request_id='old'") != 0 { |
| + t.Fatal("expired replay metadata retained") |
| + } |
| +} |
diff --git a/internal/plan3test/person_api_operations_test.go b/internal/plan3test/person_api_operations_test.go| index fdfadd22..d1b8ad7e 100644 |
| --- a/internal/plan3test/person_api_operations_test.go |
| +++ b/internal/plan3test/person_api_operations_test.go |
| @@ -128,7 +128,7 @@ func TestPersonAPIPaginationAndValidation(t *testing.T) { |
| expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/people?cursor="+page.NextCursor, "", "", ""), 200) |
| expectHTTP(t, apiRequest(t, f, peer, "GET", "/api/v1/people?cursor="+page.NextCursor, "", "", ""), 410) |
| expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/preferences?cursor="+page.NextCursor, "", "", ""), 410) |
| - f.exec(t, "UPDATE person_api_cursors SET expires_at='2000-01-01T00:00:00Z'") |
| + page.NextCursor += "x" |
| expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/people?cursor="+page.NextCursor, "", "", ""), 410) |
| for _, query := range []string{"limit=0", "limit=101", "limit=x", "limit=1&limit=2", "person=peer@example.com"} { |
| expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/people?"+query, "", "", ""), 422) |
diff --git a/internal/plan3test/person_api_test.go b/internal/plan3test/person_api_test.go| index b4d32f65..31ad5b3d 100644 |
| --- a/internal/plan3test/person_api_test.go |
| +++ b/internal/plan3test/person_api_test.go |
| @@ -51,24 +51,6 @@ func apiRouter(t *testing.T, f *fixture, verifier personapi.VerifyPersonBearer) |
| must(t, err) |
| f.Handler = equipo.Mux(r) |
| } |
| -func TestPersonAPIAuthAudiences(t *testing.T) { |
| - f := newFixture(t) |
| - expectHTTP(t, apiRequest(t, f, equipo.Actor{}, "GET", "/api/v1/me", "", "", ""), 401) |
| - for _, token := range []string{"runner", "cleanup", "coordinator", "other-instance", "invalid"} { |
| - r := httptest.NewRequest("GET", "/api/v1/me", nil) |
| - r.Header.Set("Authorization", "Bearer "+token) |
| - r.Header.Set("Origin", origin) |
| - w := httptest.NewRecorder() |
| - f.Handler.ServeHTTP(w, r) |
| - expectHTTP(t, w, 401) |
| - if !strings.HasPrefix(w.Header().Get("Content-Type"), "application/json") { |
| - t.Fatal("auth returned HTML") |
| - } |
| - } |
| - expectHTTP(t, apiRequest(t, f, owner, "POST", "/api/v1/conversation/messages", `{"body":"x","person":"peer@example.com"}`, "forged", ""), 422) |
| - f.exec(t, "DELETE FROM sessions WHERE subject=?", owner.Address) |
| - expectHTTP(t, apiRequest(t, f, owner, "GET", "/api/v1/me", "", "", ""), 401) |
| -} |
| func TestPersonAPIBrowserCSRF(t *testing.T) { |
| f := newFixture(t) |
| apiRouter(t, f, func(_ context.Context, token string) (personapi.PersonPrincipal, error) { |
diff --git a/internal/runnerproto/question_answer_json.go b/internal/runnerproto/question_answer_json.go| new file mode 100644 |
| index 00000000..89c63e97 |
| --- /dev/null |
| +++ b/internal/runnerproto/question_answer_json.go |
| @@ -0,0 +1,16 @@ |
| +package runnerproto |
| + |
| +import "encoding/json" |
| + |
| +// CanonicalJSON keeps stored answer comparisons independent of object key order. |
| +func (a QuestionAnswer) CanonicalJSON() ([]byte, error) { |
| + raw, err := json.Marshal(a) |
| + if err != nil { |
| + return nil, err |
| + } |
| + var value any |
| + if err = json.Unmarshal(raw, &value); err != nil { |
| + return nil, err |
| + } |
| + return json.Marshal(value) |
| +} |