Repository navigation
feat(iam): Refinement drafts and an Analyst role that cannot approve them - #720
Conversation
There was a problem hiding this comment.
Caution
The Analyst role's core guarantee — "cannot move a draft out of Refinement / cannot assign or sprint it" — rests on require.TaskChange, and that guard is skipped entirely when the request body has trailing bytes after the JSON object. A PATCH /tasks/{id} with {"status_id":"<backlog>"} {} passes the old-state check and applies the new status, so the guarantee this PR documents and tests does not hold at runtime. The root cause is shared pre-existing middleware, but this PR is what makes it a security boundary, so it needs to be fixed (or explicitly scoped out) before the role ships.
Reviewed changes
task.status_categorycondition attribute — registered in the IAM schema, loaded fromtask_statuses.category, and derived by a newtaskLoader.Expandfrom a requestedtask.status_idso it applies on create and on the new state of an update; mismatch/cross-project status denies.- Analyst project role — new non-system template with read/docs/chat grants, an unconditioned
tasks:writecollection grant, atasks:writegrant onproject/P/task/*conditioned ontask.status_category = refinement, and Deny statements for any assignee or sprint. - Refinement status — seeded first for new projects (Backlog stays default) and added to existing projects by migration
000082, which also inserts the Analyst role; both steps idempotent. - Auto-assign now skips refinement-category tasks, and new sprint boards collapse the Refinement column alongside Backlog.
- Annotation create-task route now runs
require.TaskCreate(), and a new route-coverage test pins which routes carry the task-attribute gate. - Web quick-add on board/list views now prefers the project's default status instead of the first non-done status, so the new first-position Refinement column does not become the create target.
- Docs — PM-agent design doc,
roles-and-policies.mdAnalyst/attribute sections and opt-in Deny recipe,paca-role-policycondition-key entry.
🚨 The "agents cannot approve drafts" guarantee is bypassable by appending bytes to an update body
RequireRequestAttrsFromRequest treats a body it cannot parse as "no attributes" and, for an update, returns without calling AuthorizeChange at all. Its peek decoder flags trailing bytes (dec.More()), but the handler's own middleware.BindJSON decodes only the first JSON value and ignores what follows, so the two disagree: the guard skips the new-state check while the service applies the change. An agent that can reach the API with its own credentials (the MCP server already uses those credentials; a provider_cli sandbox can call the API directly) can therefore move a draft to Backlog, assign it, or put it in a sprint — exactly what the Analyst policy is supposed to prevent.
Technical details
# TaskChange is skipped for bodies with trailing bytes
## Affected sites
- `services/api/internal/transport/http/middleware/authz_attrs.go:70-75` — the peek decoder sets `body = nil` when `dec.Decode` fails **or `dec.More()`** (trailing bytes).
- `services/api/internal/transport/http/middleware/authz_attrs.go:86-94` — for `create=false`, `len(attrs) == 0` calls `next.ServeHTTP` without any `AuthorizeChange`.
- `services/api/internal/transport/http/middleware/validate.go:13-18` (`BindJSON`) and `services/api/internal/transport/http/handler/task_handler.go:1267-1304` — the handler decodes the first JSON value and applies `status_id` / `sprint_id` / `assignee_ids` straight into `taskdom.UpdateTaskInput`; trailing bytes are ignored.
- `services/api/internal/transport/http/middleware/authz_attrs.go:102-117` (`peekBodyLimit`) — restores the full body, so the handler still sees the trailing bytes.
- Route: `services/api/internal/transport/http/router/router.go:760` — `require.ProjectEntity(...)` (old state) + `require.TaskChange()`; the entity gate passes for a refinement task, `TaskChange` is skipped.
- Same shape in `RequireItemTasks` / `RequireViewIDs` (view positions), unrelated to approval but the same skip.
## Required outcome
- A request whose peeked body cannot be parsed as exactly one JSON object must **fail closed** on updates (deny or 400), never fall through to the handler with the attribute check skipped. `{"status_id":"<backlog>"} {}` must not reach `UpdateTask`.
- The peek decoder and the handler's decoder must agree on what is a valid body; otherwise the attribute gate can always be bypassed by a body the former rejects and the latter accepts.
## Suggested approach (optional)
- In `RequireRequestAttrsFromRequest`, distinguish "not a JSON object" (handler will 400) from "valid object plus trailing data" (handler will succeed). Reset the body and let the handler reject malformed JSON; for trailing data, deny (or return the same 400 the handler would if `BindJSON` rejected trailing bytes).
- Consider making `BindJSON` reject trailing values (`dec.Decode` then `dec.More()`) so the handler and the guard share one notion of a valid body; that is the durable fix and also closes the other `RequireRequestAttrs` users.
- Add a regression test that PATCHes a task with `{"status_id":"..."} {}` as a caller whose role is conditioned on a different status and asserts it is denied.
## Open questions for the human
- Is direct API access by an agent with its own token considered reachable in the `provider_cli` sandbox? If yes this is critical; if the threat model excludes it, the documented "guaranteed by IAM" claim in `docs/ai-agent/pm-agent.md` still needs to be narrowed.⚠️ Existing Playwright spec still asserts a project starts with exactly three roles
apps/e2e/tests/iam/role-scope-rules.spec.ts:301 compares the project role list to exactly Admin, Editor, Viewer, so it will fail as soon as the fourth built-in role exists. Because e2e-ci.yml only triggers on apps/e2e/** changes, this PR's CI stays green and the failure surfaces on the next full Playwright run — update the spec in this PR together with the role change.
Technical details
# Stale four-role expectation in the e2e suite
## Affected sites
- `apps/e2e/tests/iam/role-scope-rules.spec.ts:301-311` — `expect(roles.map((r) => r.name).sort()).toEqual(["Admin", "Editor", "Viewer"])`; `listProjectRoles` requests `page_size=100`, so the Analyst role is returned too.
- `apps/e2e/tests/iam/role-scope-rules.spec.ts:312-323` — the property loop would pass for Analyst; only the array equality is wrong.
- Trigger gap: `.github/workflows/e2e-ci.yml` runs only on `apps/e2e/**`, so this is not caught by PR CI.
## Required outcome
- The expectation includes `Analyst`, and the test title/description no longer says "exactly Admin, Editor and Viewer". If the intent is a fixed shipped set, match `["Admin", "Analyst", "Editor", "Viewer"]`.
## Suggested approach (optional)
- Update the array and title, and assert Analyst is the fourth non-system project role.ℹ️ Built-in role documentation still says every project gets three roles
The PR updates docs/guides/roles-and-policies.md, but the other role references still describe the pre-Analyst set, which is now wrong for users reading the authorization guide, not just for the code comments.
Technical details
# Stale three-role wording
## Affected sites
- `docs/guides/iam-authorization.md:222-228` — the built-in role table omits `Analyst`, and the following sentence says "Every new project gets its own `Admin`, `Editor` and `Viewer`".
- `docs/architecture/authorization.md:125` — "Project templates (`Admin`, `Editor`, `Viewer`) are instantiated into every new project".
- `services/api/internal/bootstrap/defaultroles/defaultroles.go:9` — package comment lists the project templates as `Admin, Editor, Viewer`.
- `services/api/internal/service/project/project_service.go:285-286` — `Create`'s comment lists `Admin, Editor, Member, Viewer`.
- `services/api/internal/transport/http/handler/sprint_handler.go:43` — says sprint default views collapse "backlog status collapsed columns"; it now includes refinement too.
- `apps/e2e/tests/helpers/e2e-api.ts:127` — comment says a project starts with the roles Admin, Editor and Viewer.
- `services/api/test/e2e/list_pagination_test.go:363` — failure message says "want the shipped three plus three more" (the guard is `TotalCount < 6`, so it still passes, but the message is wrong).
## Required outcome
- The user-facing authorization guide lists Analyst and describes its restriction; the remaining comments/docstrings say four templates (and `project_service.go` drops the stale `Member`).deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏
The attribute gates peeked at a request body and treated one with
trailing data as setting no attributes, so an update skipped
AuthorizeChange while the handler, decoding only the first JSON value,
applied it. `{"status_id":"<backlog>"} {}` let an Analyst move a draft
out of Refinement, assign it or put it in a sprint.
The gates also looked up exact lower-case keys in a map, while handlers
decode into structs, which encoding/json matches case-insensitively:
`{"STATUS_ID":...}` or `{"status_id":A,"Status_Id":B}` reached the
handler unchecked or checked against a different value.
- decodeSingleJSON: one JSON value, then only whitespace. BindJSON and
the gates both use it; the gates answer trailing data with a 400.
- jsonFoldKey / foldBodyKeys: the gates fold body keys as encoding/json
does, and two keys that fold alike are a 400. A test pins the folding
to the stdlib's struct-field matching.
- Annotation create-task binds through BindJSON.
There was a problem hiding this comment.
ℹ️ No critical issues — one minor suggestion below.
Reviewed changes
Reviewed the four commits since the prior pullfrog review (a4034b6), which close the trailing-bytes authorization bypass and finish the role and documentation updates.
- Single-value JSON decoding shared by gates and handlers — new
decodeSingleJSONmakesBindJSON,RequireRequestAttrs,RequireItemTasks, andRequireViewIDsreject anything but whitespace after the body's JSON value, so an update can no longer reach the handler with the attribute check skipped. Every task/doc/view/inventory route that carries an attribute gate now decodes through it, and the annotation create-task handler switched toBindJSON. encoding/json-compatible body-key folding —jsonFoldKey/foldBodyKeysre-key the peeked body the way struct decoding matches fields (ASCII case plus Unicode simple fold) and refuse two keys that fold alike, soSPRINT_ID,Status_Id, andſtatus_idcan no longer slip past the extractor. A test pins the folding against the standard library.- Trailing-data regression coverage — cases for a second JSON value, garbage bytes, mixed-case and long-s keys, duplicate spellings, and trailing whitespace were added to the task, view, and bulk-item gate tests.
- Four-role expectations — the Playwright project-roles spec now expects
Admin, Analyst, Editor, Viewerand assertsAnalystis non-system; the e2e helper comment, authorization docs,defaultrolescomment, project-service comment, sprint-board comment, and pagination message were updated to the four-template set. view-utilsdoc comment restored —applyStatusFilterToColumnDefs's doc block is back above its signature anddefaultCreateStatusIdkeeps its own; the prior inline thread is resolved.
ℹ️ Gherkin specs still describe a project as starting with three roles
The Playwright spec and the e2e helper comment were updated for the Analyst role, but the Gherkin feature files that the e2e suite treats as the specification of record still say a new project starts with Admin, Editor and Viewer. The suite is runner-plain Playwright (no Cucumber), so this will not fail CI, but the spec now contradicts the test it describes.
Technical details
# Gherkin specs still describe three roles
## Affected sites
- `apps/e2e/features/iam/role-scope-rules.feature:6` — the feature intro says new projects start with `Admin`, `Editor` and `Viewer`.
- `apps/e2e/features/iam/role-scope-rules.feature:58-59` — the scenario title and step say "exactly Admin, Editor and Viewer".
- `apps/e2e/features/iam/role-scope-rules.feature:61` — the is-system step lists only `Editor` and `Viewer` as non-system.
- `apps/e2e/features/projects/management.feature:342` — the scenario title says the three roles are pre-seeded.
- `apps/e2e/tests/projects/management.spec.ts:599` — the matching test title (the test only asserts presence, so it still passes).
## Required outcome
- The feature files and the remaining stale test title match the shipped four-role set, including `Analyst`.
## Suggested approach (optional)
- `apps/e2e/tests/iam/role-scope-rules.spec.ts` already expects `Admin, Analyst, Editor, Viewer`; mirror that in `role-scope-rules.feature` and add `Analyst` to the non-system list.deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏
pikann
left a comment
There was a problem hiding this comment.
LGTM! Thank you for the contribution! 🚀

Summary
First of two PRs for the PM / business analyst agent (part of #719). This one adds the permission model: a Refinement status for draft tasks and a seeded Analyst project role that can create and refine drafts but cannot approve them. The agent skill itself comes in the follow-up PR.
What changes:
task.status_category: registered in the attribute registry, loaded and expanded for task resources, and derived from the requested status on create/update so a policy can condition on where a task is going, not only where it is. Scope SQL supports it for list filtering.defaultroles/policies/project_analyst.json). Reads the project and code; task writes allowed only while the task is (and stays) in therefinementcategory; no assignment and no sprint changes, so drafts stay unassigned and out of sprints.000082_add_refinement_status_and_analyst_role.sqladds it (and the Analyst role) to existing projects. Idempotent, skips projects that already have a refinement-category status, and avoids a name clash with an existing "Refinement" status.docs/ai-agent/pm-agent.md(design, both PRs),docs/guides/roles-and-policies.mdand thepaca-role-policyskill document the Analyst role andtask.status_category, including an opt-in Deny recipe to stop Editor-role agents moving drafts.Type of Change
Tests
TestIAMAnalystRoleEndToEnd(authorization matrix through the HTTP API),TestRefinementAnalystMigration(incl. re-run and existing refinement status),TestScopedTaskListStatusCategory,TestProcessTask_SkipsDraftsInRefinement,TestDefaultSprintBoardCollapsesBacklogAndRefinement, route-coverage test for task-creating routes,defaultCreateStatusIdweb test.go test -p 1 ./...inservices/apiwithPACA_TEST_PG_DSNset: the only failures are tests that also fail on currentmasterlocally (TestGitStore_ChangeRequestsAndTaskLinks,TestIAMMigrationKeyMapping,TestPluginManifestActionsMigration,TestProjectRoleResourcesMigration,TestRolesAPI_EndToEnd,TestRolesAssignMigration,TestSeedPlatformRoles_ReconcilesMigratedRoles,TestServiceAccountsAPI_EndToEnd); no new failures.apps/web: 1490/1490 pass.services/agent-runner: pass.Checklist
refinementstatus category and IAM conditions.