Skip to content

fix(security): trusted approvals, payload bootstrap v2, exactly-once seats, and honest task endings - #1086

Draft
isadeks wants to merge 17 commits into
mainfrom
fix/1000-approvals-task-security
Draft

isadeks wants to merge 17 commits into
mainfrom
fix/1000-approvals-task-security

Conversation

@isadeks

@isadeks isadeks commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Combines three open PRs into one, rebased on current main, and brings over three agent fixes from a downstream deployment. Each piece is its own commit.

Area

  • cdk: infrastructure, handlers, constructs
  • agent: Python runtime and Docker image
  • cli: bgagent client
  • docs: guides and design sources (docs/guides/, docs/design/)
  • tooling: root mise.toml, scripts, CI workflows

Related

Changes

1. Exactly-once concurrency seat release (fix(orchestration), was #1009)

Each admitted task carries a concurrency_slot marker. Taking or returning a seat is one DynamoDB transaction with the per-user counter. A seat is released once under retries, finalizer replays, cancel and complete races, and lost replies. The design and upgrade note are as in #1009.

Rebase on #904. The MicroVM supervisor-failure path no longer decrements the counter. finalizeTask keeps the #904 worker-ownership check: a changed owner neither changes the task nor releases its seat. The seat is released in finally. Only shared/task-concurrency.ts changes active_count by one. The concurrency reconciler sets it to the counted reservations, guarded by the counter's revision.

2. Trusted approval writer (feat(security), was #1013)

Workers can no longer write approval records. The session role is read-only on the approvals table. Requests go through an IAM-authenticated API that allows two writes: create a PENDING request, and mark one TIMED_OUT. See ADR-025.

Rebase on #904:

  • The hook keeps the shared approval_deadline_epoch from main, and the writer checks it.
  • The orchestrator passes the MicroVM approvals table and APPROVAL_REQUESTS_API_URL.
  • The MicroVM checkpoint only condition-checks approval rows, which the read-only role allows.
  • The hook from feat(compute): add Lambda MicroVM P3 approval lifecycle #904 sets a ttl. It is removed before the request, because the writer sets retention.

A create whose response is lost no longer leaves the task waiting. The writer commits the request and the task's move to AWAITING_APPROVAL together, so a timeout or reset after the commit used to leave the task waiting on a request the worker had given up on. Now the writer answers a repeat of a committed create with the same success, but only when the row is for the same task, user and tool input and the task still waits on that request id. The worker repeats a create that got no answer or a 5xx up to two more times with the same request id. If it still has no answer, it marks the request TIMED_OUT and resumes the task, as after an unanswered gate, and denies the call.

3. Payload bootstrap v2 (fix(security), was #1015)

ECS and Lambda MicroVM workers get a per-task, short-lived, signed payload reference and an IAM-authenticated manifest. Every platform-config field that holds an ARN must be listed in arn_keys.

Rebase on #904:

  • deliverRunHookPayload writes the v2 launch reference after the start receipt is claimed, so a replayed start rewrites the same objects. The v1 inline and S3-pointer envelopes and their tests are removed. The fix(compute): registry MCP assets are not substrate-portable to lambda-microvm #818 large-assets test now checks v2 delivery.
  • Terminate-failure logs keep the identity-only fields from main. They hold no error text, so no signed URL reaches a log.
  • The MicroVM execution role keeps its description from main. The least-privilege bootstrap cannot update a role description, and a changed description fails the deploy and its rollback.
  • The orchestrator overflow-policy suppression keeps the scoped appliesTo list from main. The broader version from fix(security): payload bootstrap v2 with signed per-task payload references #1015 is dropped.
  • The stack tests follow the nested MicroVM layout. The resource counts include the approval writer's nested stack and Lambda.

4. Agents stop and report when a platform control blocks them (feat(prompts), new)

Seen live: GitHub refused an agent's push of a workflow file. The agent moved the file to .github/pending-workflows/ and pushed that. The base prompt now tells the agent to stop and say so when a policy denial, a denied approval, a refused push or a protected gate blocks it, and never to work around the control.

5. A temporary model API error resumes the session (fix(agent), new)

Seen live: a sub-task failed on "API Error: The system encountered an unexpected error during processing" (a Bedrock 5xx), and its orchestration stalled.

  • model_retry.run_agent_resilient resumes the same SDK session after 15 s, 60 s and 120 s (MODEL_RETRY_DELAYS_S). Each resume gets only the turns and budget the task has left, and writes a model_retry milestone.
  • A resumed run starts with the approval gates the task already opened, so retries do not reset the per-task approval gate cap.
  • run_agent gains resume_session_id with no new branches, so its complexity ceiling holds.
  • When the retries run out, the error reads "Temporary model API error after N retries". The classifier files it as transient and retryable.

6. "No change made" instead of lost work (fix(delivery), new)

Seen live twice: a reviewer denied deleting an existing test, and a policy blocked a write. Each time the agent changed nothing, and the delivery gate failed the task as deliverable=lost.

  • The policy engine keeps every denied approval and every intentional Cedar hard deny. A fail-closed engine error is not recorded.
  • A successful run after one of these completes with no_change_reason when it has no PR, no question, and a clone that matches its base: no commit, pushed or not, and a clean working tree. Example: "No change made: the platform policy blocked Write .git/config (write_git_internals). <the agent's first sentence>".
  • Work that stayed in the clone, such as a failed push or new untracked files, still fails as deliverable=lost.
  • The Linear final status shows ➖ No change made with that reason.
  • no_change_reason is screened like a log line before it is stored.

The downstream version also counted a shell test-guard and a protected-push hook as controls. Neither exists upstream, so those parts are not ported.

7. File rules also apply to shell writes (fix(policy))

Found in live testing. The agent's Cedar file rules (write_file with context.file_path: .env and credentials files, the .git hard-deny rules, and any blueprint file rule) applied only to the Write and Edit tools. A file written by a shell command was checked as execute_bash alone. Now:

  • agent/src/bash_writes.py lists the paths a Bash command writes. It reads redirects, tee, copy and move destinations including the path inside a destination directory, dd of=, in-place sed and perl, truncate and touch. It follows cd, bash -c, heredocs read by a shell, .., and prefixes such as sudo -u USER.
  • A heredoc body that a shell does not read is input, so text in a document written with cat > file <<EOF is not read as commands.
  • Each path is evaluated as a write_file request at the same tier as the command. A hard file rule denies. A soft one requires approval, with annotations merged as for any multi-match. Nothing turns a deny into an allow.
  • A command that shlex cannot split has every word treated as a possible target.
  • It reads the command text, so it is a heuristic. A target built at run time, or a file another program writes, is not recognised. CEDAR_HITL_GATES.md says so.

8. Setup progress (fix(cli))

The new ApprovalRequests nested stack is shown under Orchestration in bgagent setup progress.

Validation

  • mise run lint and mise run drift-prevention pass. They cover knip, type and constants sync, the coverage contract and the docs mirrors.
  • Agent suite (mise run //agent:quality): 3,377 passed, 11 skipped (DynamoDB Local is opt-in). ty, ruff and vulture are clean.
  • CDK full suite: 9,552 passed, 65 skipped. 23 tests in 3 suites (check-constants-sync, task-orchestrator, stacks/agent) failed with ENOENT on the shared ~/.cache/cdk-tmp directory while another worktree ran jest on the same host. Those 3 suites pass on their own: 274 passed.
  • CLI suite: 1,639 passed.
  • Emulator CDK suite: 29 passed in 4 suites.
  • Semgrep masking rules and the security rule packs report 0 findings against main. gitleaks finds no leaks.

New tests:

  • agent/tests/test_bash_writes.py;
  • agent/tests/test_model_retry.py, including the approval gate count on resume;
  • agent/tests/test_controlled_no_change.py, including a real Cedar hard deny through pre_tool_use_hook and a git clone with an unpushed commit and an untracked file;
  • a screened no_change_reason write in test_task_state.py;
  • the renderer cases in fanout-task-events.test.ts;
  • the classifier cases in error-classifier.test.ts.

Not deployed. The deploy notes from the three original PRs still apply: drain in-flight tasks, and deploy the stack and the worker image together. Older workers write approval rows directly and cannot read v2 payload references.

Acknowledgment

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of the project license.

Per-user concurrency was a counter incremented on admission and
decremented on completion; retries and races (finalizer replay, cancel
vs completion, a lost DynamoDB reply, the stranded-task reconciler) could
release a seat twice or never.

- Each admitted task carries a concurrency_slot marker (held -> released).
  acquireTaskSlot / releaseTaskSlot (shared/task-concurrency.ts) change the
  marker and the counter in one transaction: acquire needs SUBMITTED with
  no marker and room under the cap; release needs a held marker on a
  terminal task. Lost replies are recovered from the marker; transaction
  conflicts retry with bounded jitter.
- Admission, finalization (release in finally), failTask, the orchestrator's
  early-return paths and the stranded-task reconciler all release through
  the marker; no handler decrements active_count directly. confirm-uploads
  no longer reserves at submit; the orchestrator owns admission.
- A held task can never be re-queued (SUBMITTED -> QUEUED and the admission
  queue require no marker).
- An approval wait that outlives the poll window finalizes to FAILED. It
  used to attempt the invalid AWAITING_APPROVAL -> TIMED_OUT, leave the task
  active and still free its seat. A finalization that cannot reach a
  terminal state now throws and is retried, keeping the seat.
- The concurrency reconciler reads counters, then strongly reads every
  reservation, repairs only under the observed reservation_version, and
  releases terminal reservations left by interrupted cleanup. Users with
  unmarked active tasks (admitted before this change) are skipped until
  they settle.
- DynamoDB Local race suite (15 cases) runs when ABCA_DDB_LOCAL_ENDPOINT is
  set; ORCHESTRATOR.md documents the scheme and the upgrade/drain note.

Rebased onto main after the Lambda MicroVM approval lifecycle (#904): the
MicroVM supervisor-failure path no longer decrements the counter itself.
finalizeTask keeps the worker-ownership check (a changed owner neither
mutates the task nor releases its seat) and releases in `finally`; the
MicroVM finalization tests assert the release instead of the decrement.
…val records (#1000)

Workers wrote PENDING approval rows directly with task-scoped session
credentials that live alongside the repository's code, so malicious or
prompt-injected repo code could write any approval record for its task.

- ApprovalRequestService (nested stack): IAM-authenticated API Gateway +
  request-approval Lambda. POST /tasks/{task_id} accepts only "create"
  (PENDING request + RUNNING -> AWAITING_APPROVAL, one transaction) and
  "timeout" (PENDING -> TIMED_OUT, conditioned on the task still awaiting
  that request). It validates a fixed field set, ownership and
  deadline_epoch, and sets the row TTL itself.
- The session role may invoke only /tasks/${aws:PrincipalTag/task_id}; the
  approvals table moves to a task-scoped read-only grant (listing it as
  read/write as well fails synth).
- Every backend gets APPROVAL_REQUESTS_API_URL: AgentCore runtime env, ECS
  task env (reserved key), MicroVM platform config (new required contract
  key approval_requests_api_url).
- Agent: approval_requests.py signs requests (SigV4, no redirects, endpoint
  validated) and never sends retention; task_state routes create/timeout
  through it and refuses human statuses; hooks carry deadline_epoch.
- ADR-025 records the decision.

Also in this change: the orchestrator fixtures carry the required
approvalRequestsApiUrl; the approval-requests stack's state-bearing resources
are recorded in legacy-state-ids.json; the DynamoDB Local approval suite is
opt-in; the MicroVM network-extraction fixture leaves out the vault; the
AWAITING_APPROVAL transition keeps status_created_at; the emulator tier
follows the trusted writer.

Rebased onto main after the Lambda MicroVM approval lifecycle (#904): the
hook keeps main's shared approval_deadline_epoch (the writer cross-checks the
same created_at + timeout_s), the orchestrator passes both the MicroVM
approvals table and APPROVAL_REQUESTS_API_URL, and the MicroVM checkpoint only
condition-checks approval rows, which the read-only session role allows.
Workers no longer read a shared payload bucket or receive deployment
identifiers baked into images.

- The coordinator publishes an IAM-readable deployment manifest
  (bootstrap/<sha>.json) and a per-task payload, and hands the worker a
  small launch reference with a short-lived signed one-object URL for its
  own payload.json. MicroVM sends it as runHookPayload (always under the
  4 KB cap); ECS sends it as AGENT_PAYLOAD_REF, consumed by
  load_ecs_payload() before the pipeline imports.
- Worker credentials get GetObject on bootstrap/* only; other object reads
  and listing are denied, so a task cannot read another task's payload
  (#700). The coordinator signs reads and deletes payload.json/launch.json
  at finalize; lifecycle reaps leftovers.
- Signed URLs are redacted from MicroVM error messages and logs.
- Old unsigned envelopes (inline hook, S3 pointer, AGENT_PAYLOAD,
  AGENT_PAYLOAD_S3_URI) are rejected: deploy the coordinator and images
  together with in-flight tasks drained (docs/verification/645-payload-bootstrap.md).
- The orchestrator role now overflows its inline policy; its overflow
  policy gets the same documented cdk-nag suppression as the runtime and
  Linear webhook roles.

Extracted from the #904 working branch onto main's flat MicroVM layout,
without start receipts or P3 lifecycle code.

Also in this change: every ARN-shaped platform-config field must be listed in
the contract's arn_keys (#817 item 3, enforced both ways by the sync check);
the new lint, dead-code and typecheck gates pass; dead verification links are
dropped.

Rebased onto main after the Lambda MicroVM approval lifecycle (#904):
- the v2 launch reference is produced in deliverRunHookPayload, after the start
  receipt is claimed, so a replayed start rewrites the same objects; the v1
  inline/S3-pointer envelope and its tests are gone
- terminate-failure logs keep main's identity-only fields (no error text, so no
  signed URL can reach a log)
- the MicroVM execution role keeps main's description: the least-privilege
  bootstrap cannot update a role description
- the orchestrator overflow suppression keeps main's scoped appliesTo list
- vulture (newer on main) also allowlists the override's `req` parameter
- tests follow the nested MicroVM layout, and the stack counts include the
  trusted approval writer's nested stack and Lambda
…them

Seen live: GitHub refused an agent's push of a workflow file (no Workflows
permission), so the agent moved the file to .github/pending-workflows/ and
pushed that instead. The base prompt now says to stop and say so when a policy
denial, a denied or timed-out approval, a refused push or a gate it may not
change blocks it, and never to work around the control: no renaming or moving
files to dodge a check, no writing the same change another way, no disabling or
skipping checks or hooks.
…off instead of failing the task

Seen live: a sub-task failed on "API Error: The system encountered an
unexpected error during processing. Try your request again." (a Bedrock 5xx)
and the orchestration waiting on it stalled.

- model_retry.run_agent_resilient wraps run_agent for the workflow's run_agent
  step. A temporary model error (5xx, throttle, overload, stream error,
  connection reset) resumes the same SDK session after 15 s / 60 s / 120 s
  (MODEL_RETRY_DELAYS_S), with only the turns and budget the task has left, and
  writes a model_retry milestone per attempt.
- run_agent takes resume_session_id and passes it to the SDK's resume option.
- When the retries run out, the error reads "Temporary model API error after N
  retries: ...", which the error classifier now files as a transient, retryable
  model error (as it does a raw Bedrock 5xx) instead of a generic failure.
…as 'No change made', not as lost work

Seen live twice: a reviewer denied deleting an existing test, and a policy
blocked a write. Each time the agent correctly changed nothing and finished, and
the delivery gate failed the task as deliverable=lost ("No change was
delivered"), which reads as lost work and invites a retry that ends the same way.

- The policy engine keeps every request a person denied (the between-turns
  injection queue is drained, so it did not survive to the end of the run) and
  every intentional Cedar hard deny (a fail-closed engine error is not recorded).
  run_agent copies both onto the AgentResult; a model retry merges them.
- controlled_no_change_reason: a successful run with no PR, no commit and no
  question, after a denial or a block, gets "No change made: <what> was denied
  (<reason>)" or "No change made: the platform policy blocked <action> (<rule>)",
  followed by the agent's own first sentence. A denial wins over a block.
- The delivery gate lets such a run complete; a commit that reached the branch
  without a PR still fails as no_pr. write_terminal stores no_change_reason,
  screened like a log line (it quotes the agent and the blocked command).
- The Linear final status (comment and agent session) shows "➖ No change made"
  with the reason instead of "✅ Task completed".
- USER_GUIDE: the delivery-gate section names the exception.

deliverable=lost stays for runs where the work was genuinely lost.
…up progress

#1000 adds the ApprovalRequests nested stack at the top level of AgentStack;
without a component it would show as a platform helper.
Found in live testing: every Cedar file rule (write_file with
context.file_path: .env and credentials files, the .git hard-deny rules,
and any a blueprint adds) saw only the Write and Edit tools. A shell
command that wrote the same file was evaluated as execute_bash alone, so
no file rule applied to it.

- bash_writes.bash_written_paths reads the paths a command writes:
  redirects, tee, the destination of cp / mv / install / ln, dd of=,
  in-place sed -i / perl -i, truncate and touch, across ; && || | and
  parentheses, with quoted paths, sudo / env prefixes, bash -c scripts,
  cd DIR and .. segments. A heuristic over the command text: a target
  built at run time ("$F", $(...)) and files other programs write are not
  recognised.
- The engine evaluates each path as a write_file request at the same tier
  as the execute_bash request and keeps every match: a hard file rule
  denies, a soft one requires approval with the annotations merged as for
  any multi-match. Nothing here can turn a deny into an allow; the
  approval request shows the real command.
- CEDAR_HITL_GATES.md says what the file rules now cover.
…s nothing

Bash runs commands that shlex rejects, such as ANSI-C quoting ($'it\'s').
The extractor returned no paths for them, so `echo $'it\'s' > .env` passed
every file rule. Such a command's rough words now come back as possible
targets, so the file rules still see .env or .git/. The worst case is an
extra approval on a rare unsplittable command, never a missed one. The SAST
range scan had flagged the swallowed parse error.
…in tests

The replayed-finalize double release and the reconciler that dropped the
seat of a task awaiting approval were test.failing witnesses until this
fix. The leaked-seat test now writes the leak to the counter directly:
admission ties every seat to a task record.
controlled_no_change_reason took "no PR and no commit on the remote
branch" as "changed nothing". After a denial or a block, a run whose
push failed, whose safety-net commit was refused, or whose only work was
new untracked files completed as "No change made" instead of failing as
deliverable=lost. The reason now also requires the clone to match its
base: no local commit and a clean working tree.
…pened

run_agent builds a new policy engine for every call and seeds its
approval gate count from the task config. A model-retry resume reused
the original config, so each resume restarted the count and a task
could open up to four times the per-task approval gate cap. The result
now carries the engine's count and the resumed call is seeded with it.
bash_written_paths read every heredoc body line as a command. A body
that mentioned a protected path as text (a document written with
`cat > file <<EOF`) was denied, and an apostrophe in the body made
shlex fail, so every word of the body became a write target. A body is
now split off before the command is read; only a body that a shell
reads (`bash <<EOF`) is parsed as a script. A body with no closing line
stays part of the command.
Two forms the module says it covers were missed. A prefix option that
takes a value (`sudo -u USER`, `env -u NAME`) left the value as the
command name, so the real command was never read. A copy, move or link
with one source and a destination without a trailing slash listed only
the destination, though an existing directory receives the source by
name inside it. Prefix options with a value now consume it, and every
copy lists the in-directory path as well.
…s change

The platform-block recorder no longer checks that the engine has the
method it always has, nor swallows its own errors. An orphaned doc
comment on the approval writer, a history note in finalization and a
restating comment on the Bash evaluation are removed.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant