Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
7 changes: 7 additions & 0 deletions agent/.vulture_allowlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,10 @@
# 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` is the only one vulture
# does not see used elsewhere.
newurl # unused variable (src/payload_bootstrap.py:31)
26 changes: 14 additions & 12 deletions agent/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,23 +244,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 @@ -270,7 +272,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` (region included), 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 @@ -288,9 +290,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`).

`/suspend` and `/resume` are deliberately **not** served — declaring a hook nothing answers fails the corresponding lifecycle transition, so the CDK construct declares exactly the hooks the agent serves. They land in P3 with the ComputeStrategy interface widening.

Expand Down
195 changes: 195 additions & 0 deletions agent/src/payload_bootstrap.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
"""Authenticate deployment settings before reading one task's payload.

The ambient worker role can GetObject only under its deployment's bootstrap/
prefix, with an explicit deny outside that prefix (including public buckets).
Only the coordinator can write those manifests. The payload itself is fetched
without worker credentials, using a single-object capability. Never log it.
"""

from __future__ import annotations

import hashlib
import json
import os
import re
from typing import Any, override
from urllib.error import HTTPError
from urllib.parse import parse_qs, urlsplit
from urllib.request import HTTPRedirectHandler, ProxyHandler, build_opener

from shared_constants import SHARED_CONSTANTS

CONTRACT = SHARED_CONSTANTS["payload_bootstrap"]


class PayloadFetchError(RuntimeError):
"""Authenticated bootstrap or payload bytes could not be read; contains no URL."""


class _NoRedirect(HTTPRedirectHandler):
@override
def redirect_request(self, req, fp, code, msg, headers, newurl):
return None


def _object(raw: bytes, label: str) -> dict:
try:
value = json.loads(raw)
except (UnicodeError, ValueError):
raise PayloadFetchError(f"{label} is not valid JSON") from None
if not isinstance(value, dict):
raise PayloadFetchError(f"{label} must contain an object")
return value


def _manifest(uri: str, backend: str) -> tuple[str, dict]:
parsed = urlsplit(uri)
if (
parsed.scheme != "s3"
or not re.fullmatch(r"[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]", parsed.netloc)
or parsed.query
or parsed.fragment
):
raise ValueError("bootstrap_s3_uri must identify a deployment manifest")
key = parsed.path.removeprefix("/")
expected = re.fullmatch(re.escape(CONTRACT["manifest_prefix"]) + r"([a-f0-9]{64})\.json", key)
if not expected:
raise ValueError("bootstrap_s3_uri has an invalid manifest key")

# Do not use a caller-supplied endpoint or default cached boto3 session.
from botocore.config import Config

from aws_session import platform_client

try:
client = platform_client(
"s3",
config=Config(connect_timeout=5, read_timeout=10, retries={"max_attempts": 2}),
)
response = client.get_object(Bucket=parsed.netloc, Key=key)
body = response["Body"]
try:
length = response.get("ContentLength")
if not isinstance(length, int) or not 0 < length <= CONTRACT["max_manifest_bytes"]:
raise PayloadFetchError("deployment manifest has an invalid length")
raw = body.read(CONTRACT["max_manifest_bytes"] + 1)
if len(raw) != length:
raise PayloadFetchError("deployment manifest body is incomplete")
finally:
body.close()
except PayloadFetchError:
raise
except Exception as exc:
# SDK/HTTP exception text can contain URLs. Expose only the class.
raise PayloadFetchError(f"deployment manifest read failed ({type(exc).__name__})") from None
if hashlib.sha256(raw).hexdigest() != expected[1]:
raise PayloadFetchError("deployment manifest digest does not match its key")
manifest = _object(raw, "deployment manifest")
if manifest.get("version") != CONTRACT["version"] or manifest.get("backend") != backend:
raise ValueError("deployment manifest version/backend does not match this worker")
if not isinstance(manifest.get("platform_config"), dict):
raise ValueError("deployment manifest has no platform configuration")
return parsed.netloc, manifest["platform_config"]


def _payload_url(url: str, bucket: str, task_id: str) -> None:
"""Permit only the exact object's regional S3 HTTPS endpoint, without redirects."""
try:
parsed = urlsplit(url)
query = parse_qs(parsed.query, keep_blank_values=True, strict_parsing=True)
if any(len(values) != 1 for values in query.values()):
raise ValueError
_access_key, _date, region, service, terminator = query["X-Amz-Credential"][0].split("/")
if (
service != "s3"
or terminator != "aws4_request"
or not re.fullmatch(r"[a-z]{2}(?:-[a-z]+)+-\d", region)
or query["X-Amz-Algorithm"] != ["AWS4-HMAC-SHA256"]
or query["X-Amz-SignedHeaders"] != ["host"]
or not re.fullmatch(r"[a-f0-9]{64}", query["X-Amz-Signature"][0])
or not 0 < int(query["X-Amz-Expires"][0]) <= CONTRACT["url_ttl_seconds"]
or parsed.scheme != "https"
or parsed.username is not None
or parsed.password is not None
or parsed.port is not None
or parsed.fragment
):
raise ValueError
suffix = "amazonaws.com.cn" if region.startswith("cn-") else "amazonaws.com"
host = f"s3.{region}.{suffix}"
valid = (
parsed.netloc == f"{bucket}.{host}" and parsed.path == f"/{task_id}/payload.json"
) or (parsed.netloc == host and parsed.path == f"/{bucket}/{task_id}/payload.json")
if not valid:
raise ValueError
except (KeyError, IndexError, TypeError, ValueError):
raise ValueError("payload reference must sign this task's exact S3 object") from None


def _download(url: str) -> dict:
# Disable environment proxies and redirects. No AWS credential provider is
# involved; S3 authorizes the coordinator's signature on this one object.
opener = build_opener(ProxyHandler({}), _NoRedirect())
try:
with opener.open(url, timeout=10) as response:
length = int(response.headers.get("Content-Length", "0"))
if not 0 < length <= CONTRACT["max_payload_bytes"]:
raise PayloadFetchError("task payload has an invalid length")
raw = response.read(CONTRACT["max_payload_bytes"] + 1)
if len(raw) != length:
raise PayloadFetchError("task payload body is incomplete")
return _object(raw, "task payload")
except PayloadFetchError:
raise
except HTTPError as exc:
raise PayloadFetchError(f"task payload download returned HTTP {exc.code}") from None
except Exception as exc:
raise PayloadFetchError(f"task payload download failed ({type(exc).__name__})") from None


def resolve_payload_reference(reference: Any, backend: str) -> tuple[dict, dict]:
if not isinstance(reference, dict) or reference.get("version") != CONTRACT["version"]:
raise ValueError(
"payload bootstrap v2 is required; deploy a matching coordinator and image"
)
task_id = reference.get("task_id")
uri = reference.get("bootstrap_s3_uri")
url = reference.get("payload_url")
if (
not isinstance(task_id, str)
or not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", task_id)
or not isinstance(uri, str)
or not isinstance(url, str)
):
raise ValueError("payload reference is missing task identity or download coordinates")
bucket, config = _manifest(uri, backend)
_payload_url(url, bucket, task_id)
document = _download(url)
payload = document.get("agent_payload")
if (
document.get("version") != CONTRACT["version"]
or document.get("task_id") != task_id
or not isinstance(payload, dict)
or payload.get("task_id") != task_id
):
raise ValueError("downloaded payload does not belong to the referenced task")
if document.get("platform_config") != config:
raise ValueError(
"payload configuration does not match the authenticated deployment manifest"
)
return payload, config


def load_ecs_payload() -> dict:
"""Consume the capability before task subprocesses can inherit the environment."""
raw = os.environ.pop("AGENT_PAYLOAD_REF", "")
if not raw:
raise ValueError("AGENT_PAYLOAD_REF is required; deploy a matching coordinator and image")
try:
reference = json.loads(raw)
except (UnicodeError, ValueError) as exc:
raise ValueError("AGENT_PAYLOAD_REF is not valid JSON") from exc
if not isinstance(reference, dict) or reference.get("task_id") != os.environ.get("TASK_ID"):
raise ValueError("payload reference does not match the ECS task identity")
payload, _ = resolve_payload_reference(reference, "ecs")
return payload
Loading
Loading