Skip to content

fix(platform): org-scope task loads and gate task mutations - #3130

Merged
larryro merged 3 commits into
mainfrom
fix/tasks-org-scoping
Sep 3, 2026
Merged

larryro merged 3 commits into
mainfrom
fix/tasks-org-scoping

Conversation

@larryro

@larryro larryro commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Closes the cross-org tenant-isolation and missing-authorization class in the tasks domain. An agent drafted part of this and was killed mid-task; every draft hunk was re-verified against main before completion.

Findings and fixes

1. Task guards never check org (critical) — domains/tasks/service.ts
loadTaskOrThrow now takes the organization and filters org_id (service.ts:251); assertTaskReadable/assertTaskWritable refuse a foreign-org project as PROJECT_NOT_FOUND 404 before the org-relative role matrix runs (service.ts:175-214) — the projects-domain assertSameOrg idiom, so a leaked id confirms nothing and the checkProjectAccess admin bypass can no longer cross orgs. All ~20 /:taskId routes inherit the fix through the loaders; createTask's bespoke ORG_FORBIDDEN 403 collapsed into the shared 404-opaque guard. Callers swept across the workspace (comments, reviews, external-ref route lanes, connectors task store, agent-turn shim, REST v1) — typecheck-verified.
Regression: domains/tasks/service.test.ts (foreign-org owner → 404 on read and write; opacity equality) + integration probes (foreign org owner GET/status/DELETE by id → 404, task untouched).

2. task_upsert_by_external_ref dedupes without org (critical) — domains/tasks/external-ref.ts:63
The dedupeScope:'project' branch now rides org_id beside the caller-supplied project_id (the org branch already did; the create lane already validated the project's org at external-ref.ts:326) — a foreign project id can neither resolve, update, nor create across the boundary, including through the sandbox bridge (workspace_domain_tools → workspace-write-shim), which passes a trusted org and a caller-influenced project.
Regression: integration probe — upsert naming a foreign project → PROJECT_NOT_FOUND, foreign task untouched.

3. respondToTaskReview had no project access check (high) — domains/tasks/reviews.ts:534
The respond door now loads the project and asserts task-edit access before recording anything: deciding a review IS deciding the task (approve completes it, request-changes kicks the agent). The review_policy file checks only narrow WHO among the writers.
Regression: integration probe — a read-only member's respond → RBAC_FORBIDDEN, approval stays pending.

4. Run start/cancel behind the read gate, cancel before authz (high) — domains/tasks/routes.ts:996,1036
POST /:taskId/workflow/{start,cancel} assert writable before any side effect (starting spends budget and moves the card; cancelling killed the live run before the status write's assert could throw). The run cancel and the cancelled status flip now share one transactSerializable — a refused flip (open subtasks, archived) rolls the cancel back instead of leaving a dead run behind an error response. REST POST /tasks/{id}/start gets the same write gate (rest/v1-tasks.ts:301).
Regression: integration probes — read-only member start/cancel → 403 with the run still running; foreign-org cancel → 404, run and task untouched.

5. Check-then-insert dedupe with no unique index (high) — external-ref.ts:360, migration 0059
db/migrations/0059_tasks_external_ref_unique.sql adds the partial unique index tasks_project_external_unique (project_id, external_system, external_id) WHERE both NOT NULL, deterministically resolving existing duplicates first: per group the oldest row (created_at_ms, id tiebreak) keeps the binding; newer duplicates are detached (refs nulled), never deleted, keeping external_url for traceability. The insert becomes ON CONFLICT … DO NOTHING with a reconcile-the-winner lane, so a lost race updates the surviving task (created:false) instead of duplicating the task and its workflow run; serializable callers converge through the 40001 retry. Per-project key on purpose: dedupeScope:'project' legitimately allows the same ref in two projects, so org-scope dedupe stays lookup-only.
Regression: integration probe — two concurrent intakes land exactly one task (created=[false,true]), replay reconciles. Migration dirty-data lane proven by replaying 0059 over a pre-0059 schema seeded with a 3-row duplicate group, a created_at tie, a sibling-project row, and null-ref rows: oldest kept, tie broken by id, others detached with data intact, re-run idempotent (UPDATE 0, index skip).

6. Collab task subscriptions unverified (high) — domains/collab/routes.ts:131
GET/POST /collab/tasks/:taskId/subscription now load the task org-scoped and assert the project read gate; a foreign or invisible task answers 404 exactly like the task surface, and a garbage id answers 404 instead of a 500 on the FK.
Regression: integration probes — cross-org get/set → 404 with the subscription set unchanged; garbage id → 404.

Draft hunks reverted

None. Every draft hunk verified in-class and kept. The two out-of-class-looking files are the blast radius of the loadTaskOrThrow/handTaskToInProgressForKick signature changes:

  • domains/connectors/service.ts — the workflow task store's get now passes the org into the loader; behavior identical (org-miss → null via the existing catch).
  • domains/tasks/comments.ts + agent-turn-shim.ts — same sweep; the shim handler already binds args.organizationId.

Examined, deliberately unchanged (out of this class)

  • GET /tasks/pending-reviews and GET /:taskId/review — org-filtered reads returning opaque ids; with the respond door now gated they enable no mutation. Same-org cross-team read narrowing is a separate (lower-sev) concern.
  • POST /tasks/from-external-issue stays read-gated: the desk "file a request" door, same deliberate READ-level posture as task commenting (comments.ts documents it). Its project-org validation is covered by fix 1/2.
  • The steer-miss kickFallback missing organizationId (separate triage finding; that lane already throws on main before reaching the swept call).

Verification

  • bun run --filter @tale/platform typecheck — clean (proves the caller sweep).
  • bun run --filter @tale/platform lint — clean.
  • bun run --filter @tale/platform test — 373 files / 72280 tests green (includes the new service.test.ts; the cross-org case fails on main by construction — main's guards never throw there).
  • bun run --filter @tale/platform backend:integration against a throwaway tale-db + MinIO — full suite green including the six new probes, matching a control run of main's tip in the same environment. (An earlier probe draft had the suite's main user own the rival org; that flipped the user multi-org and poisoned later REST sections, whose API keys resolve their org implicitly — the shipped probes give the rival org a dedicated attacker user, which is also the more faithful attack shape.)
  • migrations:check (named in the task) does not exist in this repo — the migration proof is backend:integration (boot-migrates twice concurrently) per .agents/skills/create-migration/SKILL.md, plus the manual dirty-data replay above.

Every task-by-id load is now org-scoped (loadTaskOrThrow takes the
organization and filters on org_id), and assertTaskReadable/Writable
refuse a project from another org as PROJECT_NOT_FOUND 404 (the
projects-domain assertSameOrg idiom) before the org-relative role
matrix runs — an org-A admin was passing checkProjectAccess for every
project in the deployment.

- respondToTaskReview asserts project write access before recording:
  deciding a review is deciding the task.
- POST /:taskId/workflow/{start,cancel} are write-gated before any side
  effect, and the run cancel + status flip share one transaction so a
  refused flip rolls the cancel back; REST /tasks/{id}/start matches.
- Collab task subscriptions follow the task's own org + visibility
  (foreign or garbage ids answer 404 instead of subscribing or 500ing).
- Callers swept: comments, reviews, connectors task store, agent-turn
  shim (handTaskToInProgressForKick now takes the org), REST v1.
The dedupeScope:'project' lookup matched (project_id, external_system,
external_id) with no org filter and patched the row by bare id, so an
org-level caller naming a foreign project id could update another
org's task. The project branch now rides org_id like the org branch
(the create lane already validated the project's org).

The check-then-insert dedupe had no unique index behind it: two
concurrent intakes of the same external item (a retried webhook, a
double-submitted sync) both inserted, duplicating the task and the
workflow run started for it. Migration 0059 adds the partial unique
index tasks_project_external_unique on (project_id, external_system,
external_id) — deterministically detaching existing duplicates first
(oldest row keeps the binding; newer ones lose the ref, never their
data) — and the insert becomes ON CONFLICT DO NOTHING with a
reconcile-the-winner lane, so a lost race updates the surviving task
instead of erroring or duplicating. Serializable callers reach the
same lane through the 40001 retry.
One integration section for the tasks-org-scoping class, run right
after the tasks suite: a second org owned by the same user (the exact
admin-bypass shape) gets 404 on read/mutate/delete/subscribe/cancel by
a leaked task id with the run and task untouched; a read-only member
reads but cannot start or cancel runs; responding to a review without
project edit access refuses and the approval stays pending; two
concurrent external-ref intakes land exactly one task and a replay
reconciles; an upsert naming a foreign project refuses without
touching the foreign org's task.
larryro added a commit that referenced this pull request Sep 2, 2026
The parallel fix branch fix/tasks-org-scoping (PR #3130, opened first)
already claims 0059 off the same main; filename order IS apply order and
the number must never be reused, so this branch takes the next slot.
Nothing has shipped under the old name.
@larryro
larryro marked this pull request as ready for review September 2, 2026 11:17
@larryro
larryro merged commit 878ed7f into main Sep 3, 2026
23 checks passed
@larryro
larryro deleted the fix/tasks-org-scoping branch September 3, 2026 03:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant