Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
adb9b2c
fix(orchestration): exactly-once concurrency seat release (#1003)
isadeks Nov 25, 2026
07c917f
feat(security): trusted approval writer so workers cannot write appro…
isadeks Nov 25, 2026
21ebe93
fix(security): payload bootstrap v2 for ECS and Lambda MicroVMs (#1002)
isadeks Nov 25, 2026
582cf8c
feat(prompts): agents stop and report when a platform control blocks …
isadeks Nov 25, 2026
3a7f456
fix(agent): a temporary model API error resumes the session with back…
isadeks Nov 25, 2026
5ae8c47
fix(delivery): a task stopped by a person or a platform control ends …
isadeks Nov 25, 2026
2376a9b
fix(cli): show the approval writer's stack under Orchestration in set…
isadeks Nov 25, 2026
6dc5d3d
fix(policy): file rules also apply to paths a Bash command writes
isadeks Nov 25, 2026
5ac702e
chore: no change (re-sync the pull request head)
isadeks Nov 25, 2026
92930e6
fix(policy): a command shlex cannot split is not a command that write…
isadeks Nov 26, 2026
2487167
test(emulator): the seat defects fixed by #1003 pass, so they are pla…
isadeks Nov 26, 2026
b9cee44
fix(delivery): work left in the clone is not "No change made"
isadeks Nov 26, 2026
c79f216
fix(agent): a resumed run keeps the approval gates the task already o…
isadeks Nov 26, 2026
83922e7
fix(policy): a heredoc body is input, not shell commands
isadeks Nov 26, 2026
05e5177
fix(policy): read prefix option values and copies into a directory
isadeks Nov 26, 2026
167ee66
refactor: drop speculative guards and narrating comments added by thi…
isadeks Nov 26, 2026
4ae3ce0
Merge branch 'main' into fix/1000-approvals-task-security
isadeks Nov 26, 2026
19c92ac
fix(security): repeat of a committed approval create reports its success
isadeks Nov 26, 2026
143850e
fix(agent): repeat an unanswered approval create and never leave the …
isadeks Nov 26, 2026
6a0d6ea
fix(agent): a resumed run keeps the scopes a person approved during t…
isadeks Nov 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions agent/.vulture_allowlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,11 @@
# cd agent && uv run vulture src --make-whitelist
#
# Keep this list MINIMAL. Prefer deleting dead code over allowlisting it.

# payload_bootstrap._NoRedirect.redirect_request overrides urllib's
# HTTPRedirectHandler.redirect_request and refuses every redirect, so it reads
# none of its arguments. The parameter names are fixed by the override (renaming
# one fails ty's invalid-method-override), and `newurl` and `req` are the ones vulture
# does not see used elsewhere.
newurl # unused variable (src/payload_bootstrap.py:31)
req # unused variable (src/payload_bootstrap.py:31)
27 changes: 15 additions & 12 deletions agent/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,7 @@ The `run.sh` script overrides the container's default CMD to run `python /app/sr
| `AWS_PROFILE` | No | | Profile for `aws configure export-credentials` in `run.sh`, or default profile when using the `~/.aws` mount fallback |
| `ANTHROPIC_MODEL` | No | `global.anthropic.claude-opus-5-5` | Bedrock **inference profile** ID for `InvokeModel` (see [inference profiles](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-use.html)). Must be a geo-prefixed profile ID matching the deployment's `bedrockGeoRegion`, not a bare foundation-model ID — see [Model configuration](../docs/guides/DEVELOPER_GUIDE.md#model-configuration) |
| `MAX_TURNS` | No | `100` | Max agent turns before stopping |
| `MODEL_RETRY_DELAYS_S` | No | `15,60,120` | Seconds to wait before each resume of the session after a temporary model API error (a Bedrock 5xx, throttle or overload); one retry per entry, within the task's remaining turns and budget |
| `MAX_BUDGET_USD` | No | | **Local batch only** (shell env when running `entrypoint.py` directly). Range 0.01–100; agent stops when the budget is reached. For deployed AgentCore **server** mode and production tasks, set **`max_budget_usd`** on task creation (REST API, CLI `--max-budget`, or Blueprint default); the orchestrator sends it in the `/invocations` JSON body — server mode does not read `MAX_BUDGET_USD` from the environment. |
| `DRY_RUN` | No | | Set to `1` to validate config and print the length and hash of the prompts without running the agent |
| `ANTHROPIC_DEFAULT_HAIKU_MODEL` | No | `global.anthropic.claude-haiku-5-5` | Bedrock **inference profile** ID for the small/fast auxiliary model — the pre-flight safety check and WebFetch summarization (see below). Set by the CDK stack (`cdk/src/stacks/agent.ts` (the runtime environment block)), which derives the prefix from `bedrockGeoRegion` — a geo prefix is required |
Expand Down Expand Up @@ -265,23 +266,25 @@ Baked secrets are **reported, not enforced**: `warnings` lists the names (never

`microvmId` is parsed defensively and **arrives empty in practice**: the service sends `""` here, unlike `/run` where it is populated (live-verified, ADR-021 P2-F8). So an empty id is expected-normal, not a degraded read — and this hook therefore **cannot** join the guest's record to the control-plane one. `/run`'s `hook accepted task_id=… microvm_id=…` line carries that correlation; `/terminate`'s value is the pipeline-state snapshot it reports.

**`POST /aws/lambda-microvms/runtime/v1/run`** — Payload delivery. Validates the body, installs `platform_config` (below), starts the pipeline in a background thread (the same `_extract_invocation_params` → `_spawn_background` path `/invocations` uses), and returns 200 inside the 1–60 s hook budget. Body:
**`POST /aws/lambda-microvms/runtime/v1/run`** — Authenticate and download a task, install `platform_config` (below), start the pipeline in a background thread, and return 200 inside the hook budget. Protocol v2 is implemented locally; real AWS permission/network/expiry verification remains pending (repository runbook: `docs/verification/645-payload-bootstrap.md`).

`runHookPayload` is a JSON **string** passed through by `RunMicrovm`, containing:

```json
{
"microvmId": "microvm-b44b69d9-…",
"runHookPayload": "{\"agent_payload_s3_uri\": \"s3://bucket/<task_id>/payload.json\", \"platform_config\": {…}}"
"version": 2,
"task_id": "TASK001",
"bootstrap_s3_uri": "s3://deployment-bucket/bootstrap/<sha256>.json",
"payload_url": "<redacted single-object HTTPS URL>",
"expires_at": 1789312500000
}
```

`runHookPayload` is an opaque **string** the service passes through from `RunMicrovm`. ABCA's contract for it is one of two shapes, mirroring the ECS container env contract (`AGENT_PAYLOAD` / `AGENT_PAYLOAD_S3_URI`):
The worker reads the deployment manifest with its ambient AWS role, which explicitly denies object reads outside that bucket's `bootstrap/*` prefix. It downloads the task using the coordinator's short-lived signed URL, verifies the task identity, and requires the task's configuration to equal the manifest. The digest in the manifest filename checks its bytes; IAM authenticates its origin. The entire reference must fit **4,096 bytes**. Manifests and task payloads are capped at **16 KiB** and **8 MiB**. Redirects, environment proxies and hosts/paths other than the task's regional S3 object are rejected.

| Envelope | When |
|---|---|
| `{"agent_payload": {…}, "platform_config": {…}}` | the whole orchestrator payload inline — only when it fits |
| `{"agent_payload_s3_uri": "s3://bucket/key", "platform_config": {…}}` | pointer to the payload in the platform payload bucket |
ECS uses the same reference in `AGENT_PAYLOAD_REF`, with an empty manifest config because deployment settings already come from its task definition/overrides. `load_ecs_payload()` removes the capability environment variable before importing the pipeline. Neither backend accepts the old unsigned `AGENT_PAYLOAD`, `AGENT_PAYLOAD_S3_URI`, inline hook or S3-pointer formats. Roll out the matching coordinator, worker images and policies with admissions paused and old tasks drained; the runbook records upgrade and rollback steps.

The service caps `runHookPayload` at **4 096 bytes**, so the **pointer form is the normal one** — a hydrated payload is essentially always larger. Fetching it needs no new env var: the MicroVM execution role holds read-only access to that bucket and the URI carries bucket + key.
A presigned URL is a temporary download permission: **never log it**. Its requested lifetime is at most 900 seconds, shortened by known signer credential expiry; initial creation requires at least 300 seconds. The coordinator privately saves the exact URL for retries and deletes the payload and saved launch reference at finalization. An expired saved reference fails rather than being silently re-signed.

#### `platform_config` — the agent's env, delivered per task (P2)

Expand All @@ -291,7 +294,7 @@ On AgentCore and ECS the agent's non-secret platform env arrives as runtime env
{ "platform_config": { "task_table_name": "…", "github_token_secret_arn": "arn:…" } }
```

Each snake_case key installs into its UPPER_SNAKE env var, and a payload value **wins** over any image/pre-existing value (the payload describes the live deployment; the snapshot describes a past one). Installation happens **before** any credential or pipeline initialisation — the very next step resolves the GitHub token from `GITHUB_TOKEN_SECRET_ARN`. Everything the hook logs before that point goes to stdout only (`[server/run-pre-config]`), for the same reason the build hooks do: the CloudWatch writer resolves AWS credentials and pins `boto3.DEFAULT_SESSION` (its credentials; the region is re-resolved per client), and until the install has run the only environment available is whatever the snapshot baked. The single AWS call allowed before the install is the S3 payload fetch, because the config is inside the object being fetched. The allowlist lives in `contracts/constants.json` → `microvm_platform_config` (produced by the orchestrator, consumed here; shape enforced by `mise run check:constants-sync`):
Each snake_case key installs into its UPPER_SNAKE env var, and a payload value **wins** over any image/pre-existing value (the payload describes the live deployment; the snapshot describes a past one). Installation happens **before** task credential, secret or pipeline initialisation — the very next step resolves the GitHub token from `GITHUB_TOKEN_SECRET_ARN`. Everything the hook logs before that point goes to stdout only (`[server/run-pre-config]`), for the same reason the build hooks do: the CloudWatch writer resolves AWS credentials and can cache credential state in `boto3.DEFAULT_SESSION` (environment-derived region is re-read for new clients), and until the install has run the only environment available is whatever the snapshot baked. Before installation, bootstrap reads the deployment manifest through the attributed S3 client and downloads the single task object over signed HTTPS. Other pre-install diagnostics remain stdout-only. The allowlist lives in `contracts/constants.json` → `microvm_platform_config` (produced by the orchestrator, consumed here; shape enforced by `mise run check:constants-sync`):

| Key | Env var | Required |
|---|---|---|
Expand All @@ -309,9 +312,9 @@ Each snake_case key installs into its UPPER_SNAKE env var, and a payload value *
| `aws_sdk_ua_app_id` | `AWS_SDK_UA_APP_ID` | |
| `anthropic_default_haiku_model` | `ANTHROPIC_DEFAULT_HAIKU_MODEL` | |

Values are **non-secret identifiers only** — secrets are still fetched at `/run` time from Secrets Manager using the ARNs delivered here, so the snapshot stays secret-free. The allowlist **fails closed**: these values land in `os.environ` of the process that spawns the agent's tool subprocesses, so an unrecognised key is an env-injection attempt (`LD_PRELOAD`, `AWS_ENDPOINT_URL`, …) and the whole run is rejected with nothing installed. Blank/`null` values for optional keys are skipped rather than clobbering an image value; blank required keys are rejected. An envelope with no `platform_config` at all is accepted with a loud warning (the image and the orchestrator deploy on independent cadences).
Values are **non-secret identifiers only** — secrets are still fetched at `/run` time from Secrets Manager using the ARNs delivered here, so task secrets need not be baked into the snapshot. The build-hook warning is not proof that a hand-built image contains no secrets. The allowlist **fails closed**: these values land in `os.environ` of the process that spawns the agent's tool subprocesses, so an unrecognised key is an env-injection attempt (`LD_PRELOAD`, `AWS_ENDPOINT_URL`, …) and the whole run is rejected with nothing installed. Blank/`null` values for optional keys are skipped rather than clobbering an image value; blank required keys are rejected. A verified MicroVM payload must contain `platform_config`; there is no baked-environment fallback. Control characters and inconsistent ARN account/partition fields are also rejected. ARN consistency alone is not deployment authentication: v2 supplies that through the IAM-read manifest and exact configuration comparison, including same-account workspace identifiers ([#817](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/817)).

Rejections are structured so they are readable in the MicroVM log group: `400 MICROVM_RUN_PAYLOAD_INVALID` (unusable envelope — retrying the same body cannot help), `500 MICROVM_RUN_PAYLOAD_UNREADABLE` (the S3 fetch failed), `400 MICROVM_RUN_PLATFORM_CONFIG_INVALID` (key off the allowlist, non-object block, or non-string value — fix the producer), `400 MICROVM_RUN_PLATFORM_CONFIG_INCOMPLETE` (a required key missing or blank — fix the deployment wiring), `400 TASK_RECORD_INCOMPLETE` (same validator and vocabulary as `/invocations`).
Rejections are structured so they are readable in the MicroVM log group: `400 MICROVM_RUN_PAYLOAD_INVALID` (unusable envelope — retrying the same body cannot help), `500 MICROVM_RUN_PAYLOAD_UNREADABLE` (manifest/payload read or stored bytes failed), `400 MICROVM_RUN_PLATFORM_CONFIG_INVALID` (key off the allowlist, non-object block, or non-string value — fix the producer), `400 MICROVM_RUN_PLATFORM_CONFIG_INCOMPLETE` (a required key missing or blank — fix the deployment wiring), `400 TASK_RECORD_INCOMPLETE` (same validator and vocabulary as `/invocations`).

**`POST /aws/lambda-microvms/runtime/v1/suspend`** and **`/resume`** — Runtime hooks (P3, `microvm_http.py`). `/suspend` drains acknowledged progress and verifies the task is safely parked at its approval gate within the hook budget; when that is unsafe it answers **200 `declined`** and the guest keeps working, because any non-200 answer makes the service terminate the VM. `/resume` refreshes task-scoped and ambient credentials, re-reads the gate and reseeds CSPRNGs before the coding barrier opens; after a declined suspend it answers 200 `not-suspended`. `/terminate` closes the coding barrier first. Inside the guest, the Claude CLI gets credentials from a loopback container-credential broker (`microvm_credentials.py`) that renews them before signing with expired keys.

Expand Down
120 changes: 120 additions & 0 deletions agent/src/approval_requests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0

"""IAM-signed requests to the control-plane approval writer."""

import json
import os
import re
from http import HTTPStatus
from urllib.parse import urlsplit

import requests
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
from botocore.exceptions import ClientError

from aws_session import get_session
from ua import sanitize_ua_value, static_user_agent_extra

API_ENV = "APPROVAL_REQUESTS_API_URL"


def configured() -> bool:
available = bool(os.environ.get(API_ENV))
if not available and os.environ.get("AGENT_SESSION_ROLE_ARN"):
raise RuntimeError(
"APPROVAL_REQUESTS_API_URL is required for cloud approval requests; "
"deploy matching CDK and worker images"
)
return available


def record_request(
operation: str,
task_id: str,
request_id: str,
*,
approval: dict | None = None,
reason: str | None = None,
) -> None:
"""Sign the task path with scoped credentials; never follow redirects."""
endpoint = os.environ.get(API_ENV, "").rstrip("/")
parsed = urlsplit(endpoint)
match = re.fullmatch(
r"[a-z0-9]+\.execute-api\.([a-z0-9-]+)\.amazonaws\.com(?:\.cn)?", parsed.hostname or ""
)
if (
parsed.scheme != "https"
or not match
or parsed.username
or parsed.password
or parsed.port not in (None, 443)
or parsed.query
or parsed.fragment
or not re.fullmatch(r"/[A-Za-z0-9_-]+", parsed.path)
or not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", task_id)
or operation not in {"create", "timeout"}
):
raise ValueError("Invalid approval request endpoint, task id or operation")
payload = {"operation": operation, "task_id": task_id, "request_id": request_id}
if approval is not None:
# Retention is set by the trusted writer, never by the worker.
payload["approval"] = {key: value for key, value in approval.items() if key != "ttl"}
if reason is not None:
payload["reason"] = reason
body = json.dumps(payload, separators=(",", ":")).encode()
user_agent = static_user_agent_extra()
app_id = os.environ.get("AWS_SDK_UA_APP_ID")
if app_id:
user_agent += f" app/{sanitize_ua_value(app_id)}"
url = f"{endpoint}/tasks/{task_id}"
request = AWSRequest(
method="POST",
url=url,
data=body,
headers={"Content-Type": "application/json", "User-Agent": user_agent},
)
credentials = get_session().get_credentials()
if credentials is None:
raise RuntimeError("Approval request credentials unavailable")
SigV4Auth(credentials.get_frozen_credentials(), "execute-api", match.group(1)).add_auth(request)
response = requests.post(
url,
data=body,
headers=dict(request.headers),
timeout=(5, 20),
allow_redirects=False,
)
try:
result = response.json()
except ValueError as exc:
raise RuntimeError(
f"Approval service returned invalid JSON (HTTP {response.status_code})"
) from exc
data = result.get("data") if isinstance(result, dict) else None
if response.status_code == HTTPStatus.OK and isinstance(data, dict) and data.get("ok") is True:
return
error = result.get("error") if isinstance(result, dict) else None
code = (
error.get("code", "ApprovalServiceUnavailable")
if isinstance(error, dict)
else "ApprovalServiceUnavailable"
)
details = error.get("details") if isinstance(error, dict) else None
reasons = details.get("cancellation_reasons", []) if isinstance(details, dict) else []
message = "Control plane did not acknowledge the approval write"
raise ClientError(
{
"Error": {
"Code": code,
"Message": message,
},
"CancellationReasons": reasons,
"ResponseMetadata": {
"HTTPStatusCode": response.status_code,
"RequestId": error.get("request_id") if isinstance(error, dict) else None,
},
},
"RecordApprovalRequest",
)
Loading
Loading