Skip to content

feat(AGX1-275): per-RPC task permission rewire and 404/403 wrap#249

Open
asherfink wants to merge 1 commit into
mainfrom
asher.fink/agx1-275-task-route-migration
Open

feat(AGX1-275): per-RPC task permission rewire and 404/403 wrap#249
asherfink wants to merge 1 commit into
mainfrom
asher.fink/agx1-275-task-route-migration

Conversation

@asherfink
Copy link
Copy Markdown

@asherfink asherfink commented May 26, 2026

Related work

Parent epic: AGX1-264 — per-task FGAC. Follow-ups bundled in AGX1-291.

This change is part of a 4-PR stack across 3 repos. Merge order: scaleapi/scaleapi#144783 (release sgp-authz 0.7.1) ✅ already merged → scaleapi/scaleapi#145000 → scaleapi/agentex#353 → #246this PR.

Repo PR Purpose
scaleapi/scaleapi scaleapi/scaleapi#144783 ✅ merged sgp-authz 0.7.1 — Action.CANCEL
scaleapi/scaleapi scaleapi/scaleapi#145000 register FGAC_AGENTEX_AUTH_SPARK flag
scaleapi/agentex scaleapi/agentex#353 agentex-auth per-account routing + cancel op
scaleapi/scale-agentex #246 task creator audit columns + FGAC dual-write + flag
scaleapi/scale-agentex this PR per-RPC operation rewire + 404/403 wrap

Last in the stack — this is the route-side change that actually exercises the permissions written by #246.

Summary

  • Routes each task-resource RPC to the correct AuthorizedOperationType instead of using execute everywhere: MESSAGE_SEND / EVENT_SENDupdate, TASK_CANCELcancel, TASK_CREATE stays create.
  • Broadens the execute → update swap across messages.py, checkpoints.py, and states.py so the editor role can send messages and update checkpoints/state without needing owner. The task SpiceDB schema defines permission update = (editor + owner) & internal_tenant_gate, so leaving these on execute (owner-only) would lock editors out of routine mutations.
  • Collapses every task-resource denial into 404 (via ItemDoesNotExist) across all surfaces — path id, query id, body id, and name routes — so callers can no longer distinguish "task present in another tenant" from "task absent" by comparing 403 vs 404.
  • Extracts the collapse helper to src/utils/task_authorization.py, reused from both the FastAPI dep factories and the RPC authorize hook.
  • Unknown AgentRPCMethod values now raise NotImplementedError rather than falling through authz-free — defense-in-depth so a new RPC must be explicitly wired before it can dispatch.

What changed

  • src/utils/task_authorization.py (new): check_task_or_collapse_to_404(authorization, task_id, operation) — the shared wrap.
  • src/utils/authorization_shortcuts.py: DAuthorizedId / DAuthorizedQuery / DAuthorizedBodyId route task checks through the wrap; their inner deps no longer take a task_repository (parameter was unused). DAuthorizedName now applies the wrap when resource_type == AgentexResourceType.task — previously the name surface leaked 403 vs 404 because tasks.name is globally unique, so a probe checked the whole system rather than a single tenant.
  • src/api/routes/agents.py _authorize_rpc_request: each task-resource branch routes through the wrap. The MESSAGE_SEND block with task_name is restructured to a try/else shape so a denied-update on an existing task surfaces as 404 (it must NOT fall through to the create-fallback except — that would silently promote a denied-update into a create check, which is a privilege escalation footgun). The unknown-method case (case _:) now raises NotImplementedError.
  • src/api/routes/messages.py / checkpoints.py / states.py: execute → update for routine mutations.
  • TASK_CREATE and the wildcard task("*") checks intentionally untouched.

AGX1-275 list deliverable — already covered

The AGX1-275 list-filtering deliverable (only return tasks the caller can read) is already met by existing infrastructure that this PR does not change:

  • DAuthorizedResourceIds(AgentexResourceType.task) at src/utils/authorization_shortcuts.py:130 resolves the per-principal accessible task id set.
  • It is wired into the list route at src/api/routes/tasks.py:82, which intersects user filters with the accessible set before hitting the repository.

No additional code is needed here — the list surface is already authorized end-to-end.

Pre-merge verification

The execute → update swap changes the operation literal that hits agentex-auth's check endpoint. The SGP gateway forwards the literal verbatim — this needs confirmation that the SGP permissions backend resolves update (and cancel) against the same owner row everyone hitting these routes today already has. Otherwise every running agent's RPCs break at deploy time.

Two acceptable forms before merge:

  • Direct: read the SGP permissions schema and document file + line here.
  • Indirect: one-off integration test against the real SGP adapter that issues a task update check on an account whose only grant is owner. The wire-contract test already pins the literal; this would pin the resolution.

If SGP's task permission map doesn't include update / cancel, this PR needs to either land behind a flag (keep execute for SGP-routed accounts) or backfill the schema first.

Tests

  • tests/unit/api/test_tasks_authz.py — 17 tests pass:
    • 8 TestPerRpcOperationRouting tests (incl. MESSAGE_SEND create-fallback preserved through the restructure).
    • 2 TestCheckTaskOrCollapseTo404 tests (allow + denied-collapses-to-404).
    • 3 TestDAuthorizedBodyIdTaskWrap tests.
    • 3 TestDAuthorizedNameTaskWrap tests (denied-task → 404, allow returns name, agent path unaffected).
    • Wire-contract test pins cancel → "cancel" (mirrors agentex-auth's).
  • Ruff + ruff-format clean (pre-commit hooks).

Out of scope / follow-ups (tracked in AGX1-291)

  • /agents/name/{agent_name} has the same leak shape — agent FGAC is outside AGX1-264.
  • Restoring the 403/404 split for same-tenant calls once tasks carry tenant/account_id scope at the data layer (AGX1-290).

Greptile Summary

This PR completes the per-task FGAC rewire for scale-agentex: it routes each task RPC to the correct AuthorizedOperationType (update for MESSAGE_SEND/EVENT_SEND, cancel for TASK_CANCEL), collapses all auth denials on task resources to 404 via a shared check_task_or_collapse_to_404 helper, and adds a NotImplementedError failsafe for unrecognized RPC methods.

  • task_authorization.py (new): check_task_or_collapse_to_404 centralises the deny-to-404 collapse across all task-resource surfaces (DAuthorizedId, DAuthorizedQuery, DAuthorizedBodyId, DAuthorizedName, and the RPC authorize hook); the docstring explains the UX trade-off and links the follow-up ticket.
  • agents.py: MESSAGE_SEND with task_name is restructured to a try/else shape so a denied update on an existing task surfaces as 404 and cannot fall through to the create-permission check — preventing a privilege-escalation path.
  • messages.py / checkpoints.py: execute → update so holders of the editor role can send messages and update checkpoints without owner.

Confidence Score: 4/5

The auth logic changes are internally consistent and well-tested, but the operation-literal switch from execute to update/cancel is only safe to deploy if SGP's task permission schema already grants those operations to the owner role that all in-flight agents hold today — this has not been documented in the PR.

The execute → update/cancel rewire changes what literal the SGP gateway forwards to the permissions backend on every MESSAGE_SEND, EVENT_SEND, and TASK_CANCEL call. If the SGP task schema does not map update and cancel to the owner grant, every active agent's RPCs will silently collapse to 404 at deploy time. The PR description identifies this as a required pre-merge gate but does not record verification of either the schema-doc reference or the one-off integration test it asks for.

agentex/src/api/routes/agents.py — the per-RPC operation routing is the most deployment-sensitive change; the wire contract between the new update/cancel literals and the SGP permissions schema needs to be confirmed before merge.

Important Files Changed

Filename Overview
agentex/src/utils/task_authorization.py New helper: collapses AuthorizationError → ItemDoesNotExist (404) for all task-resource checks; well-documented with rationale and follow-up ticket reference.
agentex/src/api/routes/agents.py Per-RPC operation routing rewired (execute → update/cancel); try/else shape for MESSAGE_SEND+task_name correctly blocks denied-update from falling through to create check; case _: now raises NotImplementedError instead of silently passing.
agentex/src/utils/authorization_shortcuts.py DAuthorizedId/Query/BodyId/Name all route task-resource checks through the collapse wrap; elif branch for AgentexResourceType.task is correctly placed; DTaskRepository import retained for DAuthorizedName's registry.
agentex/src/api/routes/messages.py execute → update for all four message mutation endpoints; straightforward change.
agentex/src/api/routes/checkpoints.py execute → update for put_checkpoint and put_writes; import block reordering (alphabetical) is the only other change.
agentex/src/api/schemas/authorization_types.py Adds cancel to AuthorizedOperationType StrEnum; wire-contract test locks the literal value "cancel".
agentex/tests/unit/api/test_tasks_authz.py 17 new unit tests covering per-RPC routing, 404-collapse, DAuthorizedBodyId/DAuthorizedName task-wrapping, wire-format contract; try/else create-fallback path is explicitly tested.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[RPC Request] --> B{AgentRPCMethod?}
    B -->|TASK_CREATE| C[check task/* create]
    B -->|MESSAGE_SEND / EVENT_SEND| D{task_id or task_name?}
    B -->|TASK_CANCEL| E{task_id or task_name?}
    B -->|unknown| F[raise NotImplementedError → 500]

    D -->|task_id| G[check_task_or_collapse_to_404\noperation=update]
    D -->|task_name — try get_task| H{task exists?}
    H -->|ItemDoesNotExist| I[check task/* create]
    H -->|exists — else branch| J[check_task_or_collapse_to_404\noperation=update]

    E -->|task_id| K[check_task_or_collapse_to_404\noperation=cancel]
    E -->|task_name| L[get_task then\ncheck_task_or_collapse_to_404\noperation=cancel]

    G --> M{AuthorizationError?}
    J --> M
    K --> M
    L --> M
    M -->|yes| N[raise ItemDoesNotExist → 404]
    M -->|no| O[dispatch RPC]
Loading

Reviews (2): Last reviewed commit: "feat(AGX1-275): per-RPC task permission ..." | Re-trigger Greptile

dm36 added a commit that referenced this pull request May 27, 2026
…se and two-factor mutations

Mirrors AGX1-275 (PR #249) for agent_api_keys. Wires Spark AuthZ checks
into every api_key route, collapses denials to 404 (so name/id probes
can't distinguish "present in another tenant" from "absent"), and relies
on SpiceDB's transitive expansion of api_key.{update,delete} (= editor &
parent_agent->update & tenant_gate) for two-factor mutations rather than
issuing two explicit checks at the route layer.

- src/utils/agent_api_key_authorization.py (new):
  _check_api_key_or_collapse_to_404 — catches AuthorizationError, raises
  ItemDoesNotExist. Same shape as Asher's task helper.
- src/utils/authorization_shortcuts.py: DAuthorizedId routes
  AgentexResourceType.api_key through the wrap. (DAuthorizedName isn't
  used for api_keys; the name lookup is (agent_id, name, api_key_type),
  not a single globally-unique path param — the route handlers call the
  collapse helper inline instead.)
- src/api/routes/agent_api_keys.py:
  * POST: explicit agent.update on parent (no api_key resource yet).
  * GET list: DAuthorizedResourceIds + filter; None passes through.
  * GET /name/{name}: inline collapse helper.
  * GET /{id}: DAuthorizedId(api_key, read).
  * DELETE /{id}: DAuthorizedId(api_key, delete). Two-factor via SpiceDB
    schema (api_key.delete expands to parent_agent.update); no second
    route-layer check.
  * DELETE /name/{api_key_name}: inline collapse helper.
- tests/unit/api/test_agent_api_keys_authz.py (new): 12 tests, all pass.

Stacked on dhruv/agx1-272-agent-api-keys-dual-write (PR A). Does NOT
touch dual-write logic. Does NOT modify agentex-auth.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
@asherfink asherfink force-pushed the asher.fink/agx1-275-task-route-migration branch from b936a08 to 7841696 Compare May 27, 2026 21:15
@asherfink asherfink marked this pull request as ready for review May 27, 2026 21:59
@asherfink asherfink requested a review from a team as a code owner May 27, 2026 21:59
dm36 added a commit that referenced this pull request May 28, 2026
…se and two-factor mutations

Mirrors AGX1-275 (PR #249) for agent_api_keys. Wires Spark AuthZ checks
into every api_key route, collapses denials to 404 (so name/id probes
can't distinguish "present in another tenant" from "absent"), and relies
on SpiceDB's transitive expansion of api_key.{update,delete} (= editor &
parent_agent->update & tenant_gate) for two-factor mutations rather than
issuing two explicit checks at the route layer.

- src/utils/agent_api_key_authorization.py (new):
  _check_api_key_or_collapse_to_404 — catches AuthorizationError, raises
  ItemDoesNotExist. Same shape as Asher's task helper.
- src/utils/authorization_shortcuts.py: DAuthorizedId routes
  AgentexResourceType.api_key through the wrap. (DAuthorizedName isn't
  used for api_keys; the name lookup is (agent_id, name, api_key_type),
  not a single globally-unique path param — the route handlers call the
  collapse helper inline instead.)
- src/api/routes/agent_api_keys.py:
  * POST: explicit agent.update on parent (no api_key resource yet).
  * GET list: DAuthorizedResourceIds + filter; None passes through.
  * GET /name/{name}: inline collapse helper.
  * GET /{id}: DAuthorizedId(api_key, read).
  * DELETE /{id}: DAuthorizedId(api_key, delete). Two-factor via SpiceDB
    schema (api_key.delete expands to parent_agent.update); no second
    route-layer check.
  * DELETE /name/{api_key_name}: inline collapse helper.
- tests/unit/api/test_agent_api_keys_authz.py (new): 12 tests, all pass.

Stacked on dhruv/agx1-272-agent-api-keys-dual-write (PR A). Does NOT
touch dual-write logic. Does NOT modify agentex-auth.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
dm36 added a commit that referenced this pull request May 28, 2026
…se and two-factor mutations

Mirrors AGX1-275 (PR #249) for agent_api_keys. Wires Spark AuthZ checks
into every api_key route, collapses denials to 404 (so name/id probes
can't distinguish "present in another tenant" from "absent"), and relies
on SpiceDB's transitive expansion of api_key.{update,delete} (= editor &
parent_agent->update & tenant_gate) for two-factor mutations rather than
issuing two explicit checks at the route layer.

- src/utils/agent_api_key_authorization.py (new):
  _check_api_key_or_collapse_to_404 — catches AuthorizationError, raises
  ItemDoesNotExist. Same shape as Asher's task helper.
- src/utils/authorization_shortcuts.py: DAuthorizedId routes
  AgentexResourceType.api_key through the wrap. (DAuthorizedName isn't
  used for api_keys; the name lookup is (agent_id, name, api_key_type),
  not a single globally-unique path param — the route handlers call the
  collapse helper inline instead.)
- src/api/routes/agent_api_keys.py:
  * POST: explicit agent.update on parent (no api_key resource yet).
  * GET list: DAuthorizedResourceIds + filter; None passes through.
  * GET /name/{name}: inline collapse helper.
  * GET /{id}: DAuthorizedId(api_key, read).
  * DELETE /{id}: DAuthorizedId(api_key, delete). Two-factor via SpiceDB
    schema (api_key.delete expands to parent_agent.update); no second
    route-layer check.
  * DELETE /name/{api_key_name}: inline collapse helper.
- tests/unit/api/test_agent_api_keys_authz.py (new): 12 tests, all pass.

Stacked on dhruv/agx1-272-agent-api-keys-dual-write (PR A). Does NOT
touch dual-write logic. Does NOT modify agentex-auth.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
@asherfink asherfink marked this pull request as draft May 28, 2026 18:00
Rewires the operation literal sent to agentex-auth on task RPC
routes so each RPC checks the permission that actually matches its
side effect, instead of using `execute` everywhere:

- `MESSAGE_SEND` / `EVENT_SEND` → `update`
- `TASK_CANCEL` → `cancel`
- `TASK_CREATE` stays `create`
- Unknown `AgentRPCMethod` values now raise `NotImplementedError`
  rather than falling through authz-free (defense-in-depth: a new
  RPC must be explicitly wired before it can dispatch).

The same `execute → update` swap is applied across `messages.py`,
`checkpoints.py`, and `states.py` so the editor role can perform
routine mutations without needing owner. The task SpiceDB schema
defines `permission update = (editor + owner) & internal_tenant_gate`,
so leaving these on `execute` (owner-only) would lock editors out
of normal flows.

Adds `check_task_or_collapse_to_404` in
`src/utils/task_authorization.py` and routes every task-resource
denial path through it: path id, query id, body id, and the name
surface in `authorization_shortcuts.py`. `tasks.name` is globally
unique, so a 403/404 split on the name route would let any
authenticated caller probe the whole system for task existence —
collapsing both denial cases into 404 closes that leak at the cost
of an in-tenant UX regression on permission-gap updates (tracked
under AGX1-290).

The `MESSAGE_SEND` task-name branch is restructured to
`try/else`: a denied update on an existing task must surface as 404
and NOT fall through to the create check, which would promote
"denied update" into create access.

Cross-repo wire dependency: the `update` and `cancel` literals
must resolve against the existing OWNER grant in SGP's task
permission schema before this deploys, otherwise every in-flight
agent's RPCs break at deploy time. Held behind that verification.

Part of the AGX1-264 stack: scaleapi/scaleapi NEW2
(per-account FF endpoint) → scaleapi/agentex#353 (agentex-auth
routing + cancel) → #246 (task FGAC
dual-write + audit columns) → this PR.
asherfink added a commit that referenced this pull request May 28, 2026
…n creation

Adds two nullable creator-audit columns to the `tasks` table —
`creator_user_id` and `creator_service_account_id` — populated from
the request principal in `AgentTaskService.create_task`. A CHECK
constraint `ck_tasks_at_most_one_creator` enforces that at most one
of the two is set; partial indexes back future "tasks created by X"
lookups.

Online migration: the CHECK is added `NOT VALID` then
`VALIDATE`d separately so the brief ACCESS EXCLUSIVE lock doesn't
have to wait on an existence scan. `tasks` is a high-write table;
a vanilla CHECK addition would queue behind in-flight transactions
and block readers until released. Indexes use
`CREATE INDEX CONCURRENTLY` inside `autocommit_block`.

Best-effort attribution: tasks created outside an HTTP request
context (Temporal activities, background workers, any path that
constructs `AgentTaskService` without `request.state.principal_context`)
leave both columns NULL. The CHECK constraint allows both-NULL,
and an integration test exercises the no-resolvable-creator path.

These columns are how the AGX1-291 operator runbook identifies
orphan rows for backfill when the dual-write call sites added in
the next commit fail under load.

Part of the AGX1-264 stack: scaleapi/scaleapi NEW2
(per-account FF endpoint) → scaleapi/agentex#353 (agentex-auth
routing + cancel) → this PR → #249 (per-RPC
route migration). Two commits land together in #246; this one is
the schema/audit change and is independent of the dual-write call
sites.
asherfink added a commit that referenced this pull request May 28, 2026
…TE flag

Wires `register_resource` / `deregister_resource` into
`AgentTaskService.create_task` / `delete_task`, gated by a new
`FGAC_TASKS_DUAL_WRITE` env-var (off by default; resolved at
DI-resolve time so mid-process flips are intentionally invisible —
rollout assumes a redeploy cycles pods).

- `create_task`: after the Postgres row persists, register the
  task in the authorization graph with `parent=agent` so the
  tenant + owner + parent_agent tuples are written atomically.
- `delete_task`: pre-resolves the task id by name before the
  Postgres delete (lookup-after-delete would race), then
  deregisters once the row is gone. The name-lookup
  `ItemDoesNotExist` is swallowed so the subsequent `delete()`
  surfaces its own native error — flipping the flag must not
  change the error contract for missing tasks.
- Both call sites share `_dual_write_with_retry(op_name, do_call,
  task_id)`, which retries transient
  `AuthenticationServiceUnavailableError` /
  `AuthenticationGatewayError` with exponential backoff + jitter
  (3 retries → 4 attempts max). Mirrors
  `agents_acp_use_case.grant_with_retry`, but with no `fail_task`
  fallback: the Postgres row is the durable record and orphan auth
  tuples are preferable to losing the task. The AGX1-291 operator
  runbook covers backfill using the creator-audit columns added in
  the parent commit.
- Emits `task_fgac_dual_write.{attempt,success,retry,failure}`
  statsd counters (tagged `op:register|deregister` and
  `exception_class` on failure) — the rollout signal for the
  FGAC_TASKS_DUAL_WRITE flip dashboard.

The `Port` interface gains `register_resource` /
`deregister_resource`, and the agentex-auth proxy adapter calls
`POST /v1/authz/register` and `POST /v1/authz/deregister`. The
endpoints themselves already live on agentex-auth `main` via #354;
per-account routing across them is set by scaleapi/agentex#353.

Part of the AGX1-264 stack: scaleapi/scaleapi NEW2
(per-account FF endpoint) → scaleapi/agentex#353 (agentex-auth
routing + cancel) → this PR → #249 (per-RPC
route migration).
@asherfink asherfink force-pushed the asher.fink/agx1-275-task-route-migration branch from 7841696 to fcce135 Compare May 28, 2026 20:08
@asherfink asherfink marked this pull request as ready for review May 28, 2026 20:32
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