fix(backend): scope task state, move and delete to the calling user (#2503)

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
João Salavisa
2026-08-10 22:23:03 +02:00
committed by GitHub
parent 58b18bcb70
commit fbb04aed92
21 changed files with 1462 additions and 24 deletions
@@ -0,0 +1,145 @@
---
spec: docs/specs/auth/spec.md
created: 2026-08-10
status: building
---
# Implementation Plan: Task Lifecycle Authorization Gaps
## Overview
Four per-user authorization holes let one authenticated user mutate another user's
task by naming its ID. All four share one root cause: the entry point never asks
`authorizeTaskID`, and the structural backstops that would have caught it do not
see the request.
- **Gaps 1 & 2** — `Service.UpdateTaskState` and `Service.MoveTaskWithOptions` start
at `s.tasks.GetTask` with no authorize call. Their WS actions (`task.state`,
`task.move`) name the task `id`, and the gateway backstop only parses `task_id`,
`session_id` and `task_environment_id`, so it finds no refs and allows the action.
- **Gap 3** — `TaskHandlers.httpDeleteTask` builds its context from
`context.Background()`. The identity the auth middleware put on the request is
dropped, so `authorizeTaskID` sees an identity-less internal caller and permits
everything.
- **Gap 4** (found while verifying gap 3's fix) — the production delete/archive path
does not reach `Service.DeleteTask` / `Service.ArchiveTask` at all. When a
`HandoffService` is wired — which `backendapp` always does — the handlers call
`HandoffService.DeleteTaskTree` / `ArchiveTaskTree`, and `HandoffService` has no
identity awareness whatsoever. Fixing gap 3's context alone would leave the
shipped delete route wide open; the fixture in which gap 3 was reproduced has
`handoffSvc == nil`, which is why the sibling archive route looked correct.
Layering matters here. The service guards are the fix; the gateway backstop is a
structural net that makes the *next* `task.*` action safe by default rather than
only when its author remembers. Per `apps/backend/CLAUDE.md` neither substitutes for
the other, so both land.
Four tasks. 01 and 04 are independent; 02 is meaningless without 03 (the production
route bypasses the guarded service), so they land together in that order.
---
## Backend
### Service layer (`internal/task/service/service_workflow.go`)
`authorizeTaskID` first, before any repo, executor or event-bus use — matching
`UpdateTaskMetadata` (`service_tasks.go:1333`) and `deleteTaskWithReason`
(`service_tasks.go:1911`):
- `UpdateTaskState` — `if err := s.authorizeTaskID(ctx, id); err != nil { return nil, err }`
- `MoveTaskWithOptions` — same, ahead of `s.tasks.GetTask`. The destination
workflow needs no separate check: `validateTaskMove` already refuses a move
whose target workflow belongs to a different workspace.
- `UpdateRepositoryBaseBranch` — same, on `req.TaskID`. Its WS payload uses
`task_id`, so the gateway backstop does cover it today; the check lands anyway
because a backstop is not a substitute for a service-level guard and the method
is reachable from HTTP and MCP too.
Denials return the existing `repoerrors.ErrTaskNotFound` sentinel. No handler
change: `wsUpdateTaskState` and `wsMoveTask` already collapse every service error
to a generic `ErrorCodeInternalError` message, which is exactly what a nonexistent
task produces — the denial is indistinguishable from "no such task".
### Cascade layer (`internal/task/service/handoff_service.go`, `handoff_cascade.go`)
Mirror the orchestrator's checker pattern (`internal/orchestrator/service.go:982-1021`)
rather than inventing a second one:
```go
func (s *HandoffService) SetTaskAccessChecker(check func(ctx context.Context, taskID string) error)
func (s *HandoffService) authorizeTask(ctx context.Context, taskID string) error // no-op when unwired
```
Called first in `ArchiveTaskTree`, `DeleteTaskTree` and `UnarchiveTaskTree` — before
the `rootID == ""` and `s.tasks == nil` guards do their repo work. Installed by
`TaskHandlers.SetHandoffService`, which is the call that makes those routes prefer
the cascade over the guarded `Service` methods, so the substitution cannot happen
without the guard.
Unwired stays unscoped, so every existing fixture that builds a bare
`NewHandoffService(repo, nil, nil, nil, nil, nil)` is unaffected.
### HTTP layer (`internal/task/handlers/task_http_handlers.go`)
`httpDeleteTask` becomes:
```go
deleteCtx, cancel := context.WithTimeout(
context.WithoutCancel(c.Request.Context()), constants.TaskDeleteTimeout)
```
`WithoutCancel` keeps the request's values — the identity among them — while
detaching from the request's cancellation, so a client that disconnects mid-delete
cannot abort a half-finished subtree teardown. Swapping in `c.Request.Context()`
directly would fix the identity and reintroduce that abort.
### WS gateway backstop (`internal/gateway/websocket/dispatch_scope.go`)
`authorizeAction` gains the action name and one rule: for an action of the form
`task.<verb>` — exactly two dot-separated segments — a payload `id` is a task ID.
That covers `task.get/update/delete/move/state/archive` and any future sibling,
without a hand-maintained list to fall out of date.
Deeper namespaces are deliberately excluded: `task.plan.revision.get` and
`task.review.finding.update` also carry `id`, but it names a revision or a finding,
and treating it as a task ID would deny legitimate reads. `task.create` and
`task.list` carry no `id` and are unaffected.
---
## Docs
- `docs/specs/auth/spec.md` — the behavioral guarantee (lifecycle mutations are
ownership-checked below the transport; the backstop's `id` rule) plus two
scenarios.
- `apps/backend/CLAUDE.md` — the scoping-model section gains the `id`-vs-`task_id`
rule so the next author knows which payload names are covered.
---
## Testing
TDD throughout: denial test first, watched fail, then the guard.
Every denial test also issues the identical request **as the owner** and asserts it
succeeds. Without that witness a denial test passes for the wrong reason — a broken
fixture, a typo'd ID, a missing seed row — and several tests in this area were
vacuous for exactly that reason. Every denied mutation additionally asserts the
repository recorded no write; a guard that refuses the response after committing
the write is still data loss.
New symbols in `internal/task/handlers` are `authz`-prefixed so they cannot collide
with the fixtures PR #2500 adds to the same package while it is unmerged.
Mutation check: each guard is reverted one at a time and the new test must fail and
name itself.
## Tasks
| # | Task | Depends on |
|---|------|-----------|
| 01 | [Service-layer guards for state, move and base-branch](task-01-service-guards.md) | — |
| 02 | [HandoffService cascade authorization](task-02-handoff-cascade-authz.md) | — |
| 03 | [HTTP delete keeps the caller identity](task-03-http-delete-identity.md) | 02 |
| 04 | [WS backstop reads `id` on top-level `task.*` actions](task-04-ws-backstop-id.md) | — |
@@ -0,0 +1,54 @@
# Task 01 — Service-layer guards for state, move and base-branch
**Status:** done
**Depends on:** —
## Goal
`Service.UpdateTaskState`, `Service.MoveTaskWithOptions` and
`Service.UpdateRepositoryBaseBranch` refuse a task the caller cannot see, before
they read or write anything.
## Changes
`internal/task/service/service_workflow.go`
- `UpdateTaskState` — `authorizeTaskID(ctx, id)` as the first statement, ahead of
`s.tasks.GetTask`.
- `MoveTaskWithOptions` — same. `MoveTask` delegates here, so both entry points are
covered by one guard.
- `UpdateRepositoryBaseBranch` — `authorizeTaskID(ctx, req.TaskID)` first. Defense in
depth: the WS action names `task_id` so the gateway backstop already covers that
transport, but the method is also reachable from HTTP and MCP, and
`apps/backend/CLAUDE.md` requires the service-level check regardless.
No handler changes. `wsUpdateTaskState` and `wsMoveTask` map every service error to
a generic `ErrorCodeInternalError` message, which is byte-identical to what a
nonexistent task already produces — so the denial leaks no existence.
## Tests
`internal/task/service/service_workflow_authz_test.go` (new), using the
`ctxAs` / `seedScopedWorkspaces` / `createTestService` fixtures already in
`service_access_test.go`:
- `TestUpdateTaskStateDeniesForeignTask` — user-a is refused with
`repoerrors.ErrTaskNotFound`, the returned task is nil, and the repository state
is unchanged; **then user-b runs the identical call and it succeeds** and the
state actually changes.
- `TestMoveTaskDeniesForeignTask` — same shape; asserts the task's
workflow/step/position are untouched after the denial, and that the owner's move
lands.
- `TestUpdateRepositoryBaseBranchDeniesForeignTask` — same shape.
- `TestTaskWorkflowGuardsPrecedeRepositoryUse` — table over the three entry points
with a `Service` whose repos are nil except the two the guard itself needs; a
panic means the guard is placed after the first repo use.
## Verification
```
cd apps/backend && CGO_ENABLED=1 go test -tags fts5 -race -count=1 ./internal/task/service/...
```
Mutation: remove each `authorizeTaskID` line in turn; the matching test must fail
and name itself.
@@ -0,0 +1,67 @@
# Task 02 — HandoffService cascade authorization
**Status:** done
**Depends on:** —
## Why
`backendapp` always wires a `HandoffService` into `TaskHandlers`, so in a shipped
instance `DELETE /tasks/:id`, `POST /tasks/:id/archive` and the `task.archive` WS
action never reach the guarded `Service.DeleteTask` / `Service.ArchiveTask` — they
go to `HandoffService.DeleteTaskTree` / `ArchiveTaskTree`, which have no identity
awareness at all. Task 03's identity fix is inert without this.
This is why the sibling archive route looked correctly scoped: it was reproduced
against a fixture with `handoffSvc == nil`.
## Changes
`internal/task/service/handoff_service.go`
- `taskAccessCheck func(ctx context.Context, taskID string) error` field.
- `SetTaskAccessChecker(...)` — same contract as
`orchestrator.Service.SetTaskAccessChecker`: the checker returns nil for
identity-less contexts, and leaving it unwired keeps the pre-auth behavior.
- `authorizeTask(ctx, taskID)` — no-op when unwired or when taskID is empty.
`internal/task/service/handoff_cascade.go`
- `authorizeTask` as the first statement of `ArchiveTaskTree`, `DeleteTaskTree` and
`UnarchiveTaskTree`.
`internal/task/handlers/task_handlers.go`
- `TaskHandlers.SetHandoffService` installs the checker
(`svc.SetTaskAccessChecker(h.service.AuthorizeTaskAccess)`).
The wiring lives there rather than in `backendapp` on purpose: `SetHandoffService`
is the call that makes archive/delete/unarchive use the cascade *instead of* the
guarded `Service` methods, and every user-facing cascade call site is in this
package. Installing the guard as part of that substitution means it cannot be
wired without it, and it is reachable from a package test — a separate
`backendapp` line would have had no pin short of booting the whole route table.
The integration watch-reset callers share the same instance and are identity-free,
so the checker no-ops for them.
## Tests
`internal/task/service/handoff_cascade_authz_test.go` (new):
- `TestCascadeEntryPointsDenyForeignTask` — table over the three entry points with a
checker that admits `task-mine` and refuses `task-b`. Each asserts the denial, that
the outcome is nil, and that the recording repo saw **no** archive/delete/unarchive
call; **then re-runs the same entry point on the owned task** and asserts it
proceeds past the guard.
- `TestCascadeEntryPointsGuardBeforeDependencies` — the same table with `s.tasks`
nil; a panic means the guard runs too late.
- `TestCascadeEntryPointsUnscopedWhenUnwired` — no checker installed, the denial
sentinel must not appear, so every existing fixture that builds a bare
`NewHandoffService(...)` keeps working.
## Verification
```
cd apps/backend && CGO_ENABLED=1 go test -tags fts5 -race -count=1 ./internal/task/... ./internal/backendapp/...
```
Mutation: remove each `authorizeTask` call in turn.
@@ -0,0 +1,52 @@
# Task 03 — HTTP delete keeps the caller identity
**Status:** done
**Depends on:** 02
## Goal
`DELETE /api/v1/tasks/:id` authorizes the caller, without reintroducing the
client-disconnect abort that `context.Background()` was there to prevent.
## Changes
`internal/task/handlers/task_http_handlers.go` — `httpDeleteTask`:
```go
deleteCtx, cancel := context.WithTimeout(
context.WithoutCancel(c.Request.Context()), constants.TaskDeleteTimeout)
```
`context.WithoutCancel` keeps the request context's *values* — the identity the auth
middleware attached is one of them — while dropping its cancellation and deadline.
A browser that navigates away mid-delete no longer aborts a half-finished subtree
teardown, which is what plain `c.Request.Context()` would have reintroduced.
## Tests
`internal/task/handlers/task_delete_authz_test.go` (new). Symbols are `authz`-prefixed
so they cannot collide with the fixtures PR #2500 adds to this package while it is
unmerged.
- `TestHTTPDeleteTaskDeniesForeignTask` — user-a gets 404 with the sanitized body,
the recording repo saw no delete; **then user-b issues the identical request and
gets 200**, with the delete recorded.
- `TestHTTPDeleteTaskDeniesForeignTaskThroughCascade` — the same pair with a
`HandoffService` wired (the production shape), proving task 02's guard is what
carries this route.
- `TestWSArchiveTaskDeniesForeignTaskThroughCascade` — the third route the cascade
substitution unscoped.
- `TestHTTPDeleteTaskSurvivesClientDisconnect` — the request context is cancelled
before the handler runs; the delete must still reach the repository **on a live
context**. Asserting the status code alone was vacuous (the fake repository
ignores its context, so a cancelled one still "succeeds") — the mutation run
caught that, and the test now records `ctx.Err()` at the repository boundary.
## Verification
```
cd apps/backend && CGO_ENABLED=1 go test -tags fts5 -race -count=1 ./internal/task/handlers/...
```
Mutation: restore `context.Background()`; the denial tests must fail. Replace with a
bare `c.Request.Context()`; the disconnect test must fail.
@@ -0,0 +1,58 @@
# Task 04 — WS backstop reads `id` on top-level `task.*` actions
**Status:** done
**Depends on:** —
## Why
`dispatch_scope.go` exists so a *newly added* WS action is scoped by default rather
than only when its author remembers. It reads `task_id`, `session_id` and
`task_environment_id`. `task.state` and `task.move` name their task `id`, so the
backstop parsed no refs and allowed them — the file's own comment predicted this
("an action that invents a fourth name … silently opts out").
The service guards in task 01 are the fix. This closes the class.
## Changes
`internal/gateway/websocket/dispatch_scope.go`
- `authorizeAction(ctx, action, payload)` — takes the action name.
- `scopedActionRefs` gains `ID string \`json:"id"\``, used **only** when
`isTopLevelTaskAction(action)`: the action is `task.` + exactly one more segment.
- Deeper namespaces stay excluded on purpose. `task.plan.revision.get` and
`task.review.finding.update` also carry `id`, but it names a revision or a finding;
treating it as a task ID would deny legitimate reads. Rather than a hand-maintained
action list — which has the same "someone forgot" failure mode the backstop exists
to remove — the rule keys off the namespace depth, so a future `task.<verb>` is
covered without an edit.
- `parseScopedActionRefs` returns ok when any of the four names is present.
`internal/gateway/websocket/client.go` — pass `msg.Action` through.
## Tests
`internal/gateway/websocket/dispatch_scope_test.go`:
- `task.state` / `task.move` / `task.archive` with `{"id": "task-b"}` are refused,
and the task checker is called with `task-b`.
- The owner's identical action is allowed (the checker admits it), so the rule is not
a blanket deny.
- `task.plan.revision.get` and `task.review.finding.update` with `{"id": …}` are
**allowed** — the regression this rule could plausibly cause.
- `task.create` / `task.list` (no `id`) are unaffected.
- A synthetic or identity-less client is unaffected.
## Docs
`apps/backend/CLAUDE.md` — the scoping-model section records which payload names the
backstop reads, including the `task.<verb>` + `id` rule, so the next author knows
what is and is not covered.
## Verification
```
cd apps/backend && CGO_ENABLED=1 go test -tags fts5 -race -count=1 ./internal/gateway/...
```
Mutation: drop the `isTopLevelTaskAction` branch; the `task.state` case must fail.
+22
View File
@@ -51,6 +51,19 @@ the local single-user install with a login screen it never asked for.
from another user's workspace does not grant access. Admins do NOT see other
users' workspaces (hard privacy; admin is a management role, not a
visibility role). Pre-auth data is claimed by the admin at setup.
- **Task lifecycle mutations are ownership-checked at the service layer.**
Changing a task's state, moving it between workflows/steps, updating a task
repository's base branch, and archiving or deleting a task (including the
cascade that walks its subtree) all refuse a foreign task before any read or
write reaches the repository. This holds on every transport — HTTP, WebSocket
and MCP — because the check lives below them, and it holds for long-running
deletes, which detach from request cancellation but keep the caller identity.
- **The WebSocket backstop reads `id` on top-level `task.*` actions.** In
addition to `task_id` / `session_id` / `task_environment_id`, an action named
`task.<verb>` (exactly two segments — `task.state`, `task.move`, `task.get`, …)
has its payload `id` treated as a task ID. Deeper namespaces (`task.plan.*`,
`task.review.*`) are untouched: their `id` names a plan, revision or finding,
not a task.
- **Shared surfaces (instance-global by design).** Executors, executor
profiles, environment definitions, agent profiles/agents, editors, prompts,
sprites, voice, notification providers, and system pages remain shared
@@ -99,6 +112,15 @@ the local single-user install with a login screen it never asked for.
## Scenarios
- **GIVEN** two users A and B and a task owned by B, **WHEN** A sends
`task.state` or `task.move` over the WebSocket naming that task by `id`,
**THEN** the call is refused, B's task DTO is not serialized into the
response, and no state, position or workflow write reaches the repository.
- **GIVEN** the same pair, **WHEN** A sends `DELETE /api/v1/tasks/{B's task}`
or `POST /api/v1/tasks/{B's task}/archive`, **THEN** the response is 404 and
no task row, subtree row, or workspace-group membership is touched — while
the owner's own delete still runs to completion if the owner's browser
disconnects mid-request.
- **GIVEN** an authenticated Kandev browser session, **WHEN** a protected API
request receives a Kandev session challenge, **THEN** the browser clears the
stale Kandev identity and navigates to `/login`.