From 5c72601d7676e145694d25743e09bbec784f2ceb Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 5 Nov 2026 15:54:15 +0000 Subject: [PATCH 1/5] fix(security): payload bootstrap v2 for ECS and Lambda MicroVMs (#1002) Workers no longer read a shared payload bucket or receive deployment identifiers baked into images. - The coordinator publishes an IAM-readable deployment manifest (bootstrap/.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. --- agent/README.md | 26 +- agent/src/payload_bootstrap.py | 194 +++++ agent/src/server.py | 342 +------- agent/tests/test_payload_bootstrap.py | 301 +++++++ agent/tests/test_server.py | 817 ++---------------- cdk/src/constructs/ecs-agent-cluster.ts | 32 +- cdk/src/constructs/ecs-payload-bucket.ts | 25 +- cdk/src/constructs/lambda-microvm-compute.ts | 41 +- .../payload-bootstrap-permissions.ts | 67 ++ cdk/src/constructs/task-orchestrator.ts | 38 +- cdk/src/handlers/shared/payload-bootstrap.ts | 183 ++++ .../shared/strategies/ecs-strategy.ts | 142 +-- .../strategies/lambda-microvm-strategy.ts | 167 +--- cdk/src/stacks/agent.ts | 19 +- cdk/test/constructs/ecs-agent-cluster.test.ts | 10 +- .../constructs/lambda-microvm-compute.test.ts | 18 +- .../payload-bootstrap-permissions.test.ts | 67 ++ cdk/test/constructs/task-orchestrator.test.ts | 13 +- .../handlers/orchestrate-task-microvm.test.ts | 32 +- .../handlers/shared/payload-bootstrap.test.ts | 160 ++++ .../shared/strategies/ecs-strategy.test.ts | 196 ++--- .../lambda-microvm-strategy.test.ts | 365 ++------ .../start-session-composition.test.ts | 15 +- cdk/test/scripts/check-constants-sync.test.ts | 26 + cdk/test/stacks/agent.test.ts | 13 +- contracts/constants.json | 9 + contracts/constants.md | 35 +- ...ADR-021-lambda-microvms-compute-backend.md | 37 +- docs/design/COMPUTE.md | 2 +- docs/design/SECURITY.md | 5 +- docs/src/content/docs/architecture/Compute.md | 2 +- .../src/content/docs/architecture/Security.md | 5 +- ...Adr-021-lambda-microvms-compute-backend.md | 37 +- docs/verification/645-payload-bootstrap.md | 127 +++ scripts/check-constants-sync.ts | 34 +- 35 files changed, 1703 insertions(+), 1899 deletions(-) create mode 100644 agent/src/payload_bootstrap.py create mode 100644 agent/tests/test_payload_bootstrap.py create mode 100644 cdk/src/constructs/payload-bootstrap-permissions.ts create mode 100644 cdk/src/handlers/shared/payload-bootstrap.ts create mode 100644 cdk/test/constructs/payload-bootstrap-permissions.test.ts create mode 100644 cdk/test/handlers/shared/payload-bootstrap.test.ts create mode 100644 docs/verification/645-payload-bootstrap.md diff --git a/agent/README.md b/agent/README.md index 9386a46e7..869958b59 100644 --- a/agent/README.md +++ b/agent/README.md @@ -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//payload.json\", \"platform_config\": {…}}" + "version": 2, + "task_id": "TASK001", + "bootstrap_s3_uri": "s3://deployment-bucket/bootstrap/.json", + "payload_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) @@ -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 | |---|---|---| @@ -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. diff --git a/agent/src/payload_bootstrap.py b/agent/src/payload_bootstrap.py new file mode 100644 index 000000000..b5133731b --- /dev/null +++ b/agent/src/payload_bootstrap.py @@ -0,0 +1,194 @@ +"""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 +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): + 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 diff --git a/agent/src/server.py b/agent/src/server.py index 50942d8f8..b03809f1c 100644 --- a/agent/src/server.py +++ b/agent/src/server.py @@ -857,7 +857,6 @@ async def invoke_agent(request: Request, body: InvocationRequest): MICROVM_HOOK_PREFIX = "/aws/lambda-microvms/runtime/v1" #: ``s3://`` scheme prefix for the out-of-band payload pointer. -_S3_URI_SCHEME = "s3://" # --- platform_config allowlist (ADR-021 P2) -------------------------------- # WHY the agent's platform env arrives in the ``/run`` payload at all, instead of @@ -909,70 +908,15 @@ async def invoke_agent(request: Request, body: InvocationRequest): #: WHAT THIS BUYS, STATED PRECISELY — because the honest answer is narrower than #: "stops secret exfiltration", and overstating it would hide the residual gap. #: -#: The key allowlist above stops a payload setting ``LD_PRELOAD``; it does not stop -#: a payload pointing an *allowlisted* key at a different resource. The value that -#: matters most is ``github_token_secret_arn``: ``config.resolve_github_token`` -#: fetches whatever ARN it names using the UNSCOPED execution role and caches the -#: raw ``SecretString`` into ``os.environ["GITHUB_TOKEN"]``, from which ``shell.py`` -#: hands the environment to every repo subprocess — i.e. into the model's tool -#: surface. So the value is worth validating. -#: -#: This check is DEFENCE IN DEPTH AND FAIL-FAST, not the primary control: -#: -#: * What actually stops a cross-account read today is IAM. Every grant on the -#: execution role is account-scoped by construction — ``grantRead`` on the GitHub -#: PAT secret, and the ``bgagent-linear-oauth-*`` / ``bgagent-jira-oauth-*`` -#: prefix grants built with ``stack.formatArn`` (``lambda-microvm-compute.ts``). -#: A foreign-account ARN therefore AccessDenies with or without this check. What -#: this adds is a structured 400 at the door instead of an opaque -#: ``AccessDeniedException`` mid-startup, and a guard that still holds if a -#: future grant is ever widened. -#: * What this check does NOT stop is an IN-ACCOUNT redirect. The channel-OAuth -#: grants are prefix grants (unavoidable: the CLI mints ``bgagent-*-oauth-`` -#: at setup, so the names are unknown at synth), so a block whose anchor and -#: whose ``github_token_secret_arn`` name the SAME account but a DIFFERENT -#: workspace's OAuth secret is accepted here. Partition + account is the only -#: boundary this check enforces; it is not a per-workspace authorization check. -#: * That residual gap is currently unreachable from the guest, which is why it is -#: left open. ``platform_config`` is produced by the orchestrator Lambda and the -#: MicroVM execution role holds ``grantRead`` ONLY on the payload bucket -#: (``payloadBucket.grantRead``), so a running MicroVM can read another task's -#: payload but cannot write one. Reaching the in-account case requires already -#: controlling the orchestrator's environment or the bucket's write path. -#: -#: ESCALATION: if the payload path ever becomes less trusted — a third-party -#: producer, an operator-editable envelope, or any grant that lets the guest write -#: the payload bucket — this must grow into a name-shape check that ties -#: ``github_token_secret_arn`` to the task's own channel/workspace, because -#: partition+account pinning provably does not cover that case. -#: -#: The prefix grant itself is at ECS parity. The ASYMMETRY that makes value -#: validation worth doing here at all is new to this backend: on ECS these ARNs -#: arrive as deploy-time container env; here they arrive in a network payload. +#: The allowlist restricts environment-variable names; ARN shape/account checks +#: below are defense in depth. Startup settings come from an IAM-authenticated +#: bootstrap manifest read before the task payload. That independent manifest +#: pins the exact GitHub secret and other deployment identifiers, including valid +#: cross-region secrets. A same-payload account anchor alone cannot do that. MICROVM_PLATFORM_CONFIG_ARN_KEYS: frozenset[str] = frozenset(_PLATFORM_CONFIG_CONTRACT["arn_keys"]) -#: The key whose ARN supplies the partition/account every other ARN is checked -#: against. -#: -#: Deliberately a payload key rather than ``os.environ`` or an STS call. -#: ``os.environ`` is empty here by construction (nothing is baked into the -#: snapshot — see ``imageEnvironmentVariables``), so anchoring on the environment -#: would silently degrade this whole check to shape-only in the intended -#: deployment. An ``sts:GetCallerIdentity`` is not available either: this runs -#: BEFORE ``platform_config`` is installed, on the path that must make zero AWS -#: calls beyond the S3 payload fetch. -#: -#: CONSEQUENCE, stated plainly: because the anchor travels in the same block as the -#: values it validates, this check enforces INTERNAL CONSISTENCY of the block, not -#: agreement with the account the guest is actually running in. A block that names -#: one foreign account throughout is self-consistent and passes here — it then -#: fails at IAM, which is the control that really holds (see -#: :data:`MICROVM_PLATFORM_CONFIG_ARN_KEYS`). ``agent_session_role_arn`` is still -#: the best available anchor: it is REQUIRED (so always present when this check -#: runs, which is what stops disarm-by-omission) and it is the one value whose -#: misdirection costs the attacker the run rather than gaining them anything — a -#: foreign session role fails closed at ``sts:AssumeRole`` -#: (``SessionScopingError``). +#: Consistency anchor after manifest authentication, not deployment identity. +#: Required membership is enforced by the shared contract. MICROVM_PLATFORM_CONFIG_ACCOUNT_ANCHOR_KEY: str = _PLATFORM_CONFIG_CONTRACT["account_anchor_key"] _PLATFORM_CONFIG_KEY_RE = re.compile(r"^[a-z][a-z0-9_]*$") @@ -1135,25 +1079,6 @@ def __init__(self, code: str, message: str) -> None: self.code = code -def _absent_required_platform_env() -> list[str]: - """Required ``platform_config`` env vars that are unset in the LIVE environment. - - The no-``platform_config`` path's audit. Checks the ENV VAR names rather than - the contract keys, because on that path the only possible source is whatever - the image snapshot baked — so the effective environment is the thing to - interrogate, and a value that arrived by any route counts. - - Blank/whitespace-only counts as absent, matching - :func:`_install_platform_config`'s own rule: CloudFormation renders an - unresolved value as ``""``, and an empty table name is not a table name. - """ - return sorted( - MICROVM_PLATFORM_CONFIG_ENV_BY_KEY[key] - for key in MICROVM_PLATFORM_CONFIG_REQUIRED_KEYS - if not os.environ.get(MICROVM_PLATFORM_CONFIG_ENV_BY_KEY[key], "").strip() - ) - - def _reject_foreign_arns(resolved: dict[str, str]) -> None: """Require every ARN-shaped value to agree with the anchor's partition + account. @@ -1456,176 +1381,27 @@ def _parse_terminate_microvm_id(raw: bytes) -> str: class MicrovmRunHookRequest(BaseModel): - """Body the MicroVM service POSTs to the ``/run`` hook. - - ``runHookPayload`` is the opaque STRING the orchestrator passed to - ``RunMicrovm`` — the service does not parse it. ABCA's contract for that - string (``lambda-microvm-strategy.ts``) is one of two shapes, mirroring the - ECS container env contract (``AGENT_PAYLOAD`` / ``AGENT_PAYLOAD_S3_URI``): - - * ``{"agent_payload": {...}, "platform_config": {...}}`` — inline. - * ``{"agent_payload_s3_uri": "s3://bucket/key", "platform_config": {...}}`` — - a pointer; the object at the URI carries the task payload (and a - ``platform_config`` copy, so either end of the fetch yields it). - - The pointer form is the DOMINANT one: the service caps ``runHookPayload`` at - 4 096 bytes and a hydrated payload is essentially always larger. - - ``platform_config`` (ADR-021 P2) is a SIBLING of ``agent_payload``, not a - field inside it: it configures the agent's *process*, whereas - ``agent_payload`` describes the *task* (``memory_id`` and friends stay - inside ``agent_payload``, unchanged). See ``_install_platform_config``. - - Both fields default to empty so a malformed call produces this module's - structured 400 rather than FastAPI's 422 — the service surfaces a 4xx as a - generic "client error" hook failure either way, and our own body is what ends - up in the MicroVM log group. + """Service request containing a serialized v2 payload reference. + + The reference identifies an IAM-authenticated deployment manifest and one + task's signed download URL. Unsigned inline and legacy S3 envelopes are + refused: this protocol requires a matching coordinator and agent image. + Missing fields reach our structured 400 instead of FastAPI's 422. """ microvmId: str = "" # service field name; camelCase on the wire runHookPayload: str = "" # service field name; camelCase on the wire -class _PayloadFetchError(Exception): - """A ``/run`` payload the agent could not READ, as opposed to could not PARSE. - - Exists purely to be *not* a ``ValueError``, because the ``/run`` handler - discriminates its 400 from its 500 on exactly that type and the two answers - make opposite promises to the operator: - - * 400 ``MICROVM_RUN_PAYLOAD_INVALID`` — "the orchestrator built a bad - envelope; retrying an identical body cannot help." - * 500 ``MICROVM_RUN_PAYLOAD_UNREADABLE`` — "the payload could not be read; - retrying CAN help." - - A truncated, racing, or half-written S3 object is the SECOND kind, but its - natural exception is ``json.JSONDecodeError`` — a ``ValueError`` subclass — so - it landed in the 400 branch and told the operator the orchestrator was at - fault when the orchestrator was fine and the object was bad. Only the - *pre-fetch* URI-shape check legitimately raises ``ValueError`` on this path, - which is why a blanket ``except ValueError`` is the wrong discriminator and - this type exists. - """ +def _resolve_microvm_run_payload(run_hook_payload: str) -> tuple[dict, dict]: + """Authenticate deployment settings and resolve the v2 task reference.""" + from payload_bootstrap import resolve_payload_reference - -def _fetch_microvm_payload_from_s3(uri: str) -> dict: - """Read and parse the out-of-band ``/run`` payload from S3. - - Same fetch the ECS boot command performs for ``AGENT_PAYLOAD_S3_URI``; the - MicroVM **execution role** holds the read grant, scoped to the platform - payload bucket. Errors propagate to the caller, which turns them into a - structured 400/500 — silently starting a pipeline with no payload would - produce a task that runs with an empty prompt. - - The URI-SHAPE check raises ``ValueError`` (the orchestrator's envelope is - wrong → 400). Everything AFTER the fetch raises :class:`_PayloadFetchError` - (the object is wrong → 500, retryable). See that class. - - Built through ``aws_session.platform_client`` so the call carries the ABCA - ``md/`` solution-attribution segment (#319). Platform, not tenant: the bucket - is platform-owned and — decisively — this is the ONE call that must happen - BEFORE ``platform_config`` is installed (the config is inside the object - being fetched), so ``AGENT_SESSION_ROLE_ARN`` may not be set yet and a - tenant-scoped client could not be built. ``platform_client`` does not touch - the cached session, so this call also cannot pin an unscoped session for the - rest of the task. The ``app/`` UA segment (native, from ``AWS_SDK_UA_APP_ID``) - is the one attribution field this single call can miss for the same - chicken-and-egg reason. - """ - remainder = uri[len(_S3_URI_SCHEME) :] - bucket, _, key = remainder.partition("/") - if not bucket or not key: - raise ValueError(f"agent_payload_s3_uri is not a bucket/key URI: {uri!r}") - - from aws_session import platform_client - - region = os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION") - client = platform_client("s3", region_name=region) - body = client.get_object(Bucket=bucket, Key=key)["Body"].read() try: - payload = json.loads(body) - except ValueError as exc: - # ``JSONDecodeError`` IS a ``ValueError``, so without this re-raise a - # truncated or half-written object would be reported as an orchestrator - # envelope bug and marked non-retryable. Re-raised as the type the handler - # routes to its retryable 500. - raise _PayloadFetchError( - f"S3 payload at {uri!r} is not valid JSON ({exc}); the object may be " - "truncated or still being written" - ) from exc - if not isinstance(payload, dict): - raise _PayloadFetchError( - f"S3 payload at {uri!r} is {type(payload).__name__}, expected an object" - ) - return payload - - -def _resolve_microvm_run_payload(run_hook_payload: str) -> tuple[dict, Any]: - """Split the ``runHookPayload`` string into (agent payload, platform config). - - The second element is returned RAW (unvalidated) — ``_install_platform_config`` - owns its allowlist checks so the two failure classes get distinct wire codes. - ``None`` means the envelope carried no ``platform_config`` at all. - - Raises ``ValueError`` for every ENVELOPE shape the agent cannot act on — the - caller maps that onto its 400 ("the orchestrator built this; a retry cannot - help"). Problems with the CONTENT of a fetched S3 object raise - :class:`_PayloadFetchError` instead, which the caller maps onto its retryable - 500: the orchestrator's envelope was fine and the object was not. - """ - if not run_hook_payload.strip(): - raise ValueError("runHookPayload is empty") - - try: - envelope = json.loads(run_hook_payload) - except json.JSONDecodeError as exc: - raise ValueError(f"runHookPayload is not valid JSON: {exc}") from exc - - if not isinstance(envelope, dict): - raise ValueError(f"runHookPayload must be a JSON object, got {type(envelope).__name__}") - - inline = envelope.get("agent_payload") - if inline is not None: - if not isinstance(inline, dict): - raise ValueError(f"agent_payload must be an object, got {type(inline).__name__}") - return inline, envelope.get("platform_config") - - uri = envelope.get("agent_payload_s3_uri") - if isinstance(uri, str) and uri.startswith(_S3_URI_SCHEME): - fetched = _fetch_microvm_payload_from_s3(uri) - # ``platform_config`` may sit beside the pointer (outer envelope) or - # inside the fetched object — the producer writes it in BOTH places on - # this path deliberately, so the agent gets it whichever end it reads. - # Inner first, outer as the fallback. - platform_config = fetched.get("platform_config") - if platform_config is None: - platform_config = envelope.get("platform_config") - # The fetched object is EITHER the same envelope shape as the inline form - # ({"agent_payload": …}) or the task payload itself with ``platform_config`` - # merged in at the top level (what the strategy writes today, and what P1 - # wrote without the config). Both are accepted because the image snapshot - # and the orchestrator Lambda deploy on independent cadences — a new image - # must not require a same-instant orchestrator. Discriminating on the - # ``agent_payload`` key is unambiguous: no orchestrator task payload has a - # field by that name. A stray ``platform_config`` key left in the bare - # form is inert — ``_extract_invocation_params`` reads named fields only. - nested = fetched.get("agent_payload") - if nested is None: - return fetched, platform_config - if not isinstance(nested, dict): - # Content of the FETCHED OBJECT, not of the envelope — so this is the - # retryable class, same as a truncated body. See ``_PayloadFetchError``. - raise _PayloadFetchError( - f"agent_payload in the S3 payload must be an object, got {type(nested).__name__}" - ) - return nested, platform_config - if uri is not None: - raise ValueError(f"agent_payload_s3_uri must be an s3:// URI, got {uri!r}") - - raise ValueError( - "runHookPayload envelope has neither agent_payload nor agent_payload_s3_uri " - f"(keys: {sorted(envelope)})" - ) + reference = json.loads(run_hook_payload) + except (UnicodeError, ValueError) as exc: + raise ValueError("runHookPayload is not valid JSON") from exc + return resolve_payload_reference(reference, "lambda-microvm") #: The ONE executable whose warm-up gates the snapshot, exec'd FIRST. @@ -2079,7 +1855,7 @@ def microvm_run(request: Request, body: MicrovmRunHookRequest): mechanism ``/invocations`` uses — ``_extract_invocation_params`` → ``_validate_required_params`` → ``_spawn_background`` — rather than a second, drifting payload mapper. The orchestrator payload is byte-identical across - substrates (AgentCore receives it as ``input``, ECS as ``AGENT_PAYLOAD``, + substrates (AgentCore receives it as ``input``, ECS through the authenticated payload reference, MicroVMs inside this envelope), which is what makes that reuse correct. ``platform_config`` (P2) is installed into ``os.environ`` FIRST — before @@ -2096,15 +1872,15 @@ def microvm_run(request: Request, body: MicrovmRunHookRequest): has, per ADR-021 sub-decision 3's identity delta. Sync ``def`` for the same reason as ``/ready``, and additionally because the - S3 payload fetch is a blocking boto3 call: in a threadpool it cannot stall + manifest read and signed download are blocking calls: in a threadpool it cannot stall the event loop. **Every log line before the install goes through ``_pre_config_log``** (stdout only). Until ``platform_config`` is in the environment, a ``_debug_cw`` here would resolve AWS credentials and pin ``boto3.DEFAULT_SESSION`` off whatever the snapshot happens to carry — the same defect the build hooks avoid, one - phase later. The single AWS call this phase is allowed to make is the S3 - payload fetch, because the config is inside the object being fetched. + phase later. Pre-install operations are the IAM-authenticated manifest read + and the single-object HTTPS download. Build hooks remain AWS-silent. """ _pre_config_log( f"/run hook received: microvm_id={body.microvmId!r} bytes={len(body.runHookPayload)}" @@ -2125,16 +1901,14 @@ def microvm_run(request: Request, body: MicrovmRunHookRequest): ) except Exception as exc: # Payload could not be READ: S3 AccessDenied / NoSuchKey / transient, or a - # `_PayloadFetchError` for an object that fetched but was truncated, + # `PayloadFetchError` for an object that fetched but was truncated, # non-JSON, or not an object. 500 so the failure is distinguishable from a - # malformed ENVELOPE (the 400 above) and is correctly reported as - # retryable, and loud enough to find in the MicroVM log group — via the - # response body, since the CloudWatch writer is off-limits until the config - # is installed. - _pre_config_log( - f"/run hook payload fetch FAILED [{type(exc).__name__}: {exc}]\n" - f"{traceback.format_exc()}" - ) + # malformed reference (the 400 above). The response body preserves the + # distinction while CloudWatch is off-limits before config installation. + # Corrupt stored bytes require repair, not an assumption that retry helps. + # A chained HTTP error may contain the bearer URL. Log only the + # bootstrap reader's sanitized message, never its exception chain. + _pre_config_log(f"/run hook payload fetch FAILED [{type(exc).__name__}: {exc}]") return JSONResponse( status_code=500, content={ @@ -2146,6 +1920,11 @@ def microvm_run(request: Request, body: MicrovmRunHookRequest): task_id_log = str(payload.get("task_id", "")) try: + if platform_config is None: + raise _PlatformConfigError( + "MICROVM_RUN_PLATFORM_CONFIG_INVALID", + "Authenticated platform configuration is required", + ) installed_env = _install_platform_config(platform_config) except _PlatformConfigError as exc: _pre_config_log(f"/run hook rejected: {exc}") @@ -2163,55 +1942,6 @@ def microvm_run(request: Request, body: MicrovmRunHookRequest): f"/run hook installed platform_config env: {installed_env}", task_id=task_id_log or None, ) - else: - # No `platform_config` — the legacy P1 envelope. This branch must NOT simply - # shrug: the required keys exist because without them the agent cannot write - # status/progress, resolve the GitHub token, or (decisively) - # tenant-scope its credentials — `aws_session.get_session` falls back to the - # ambient compute role with scoping silently OFF when - # `AGENT_SESSION_ROLE_ARN` is unset. So the check is re-run against the - # EFFECTIVE environment: a legacy or hand-built image that bakes those - # values still runs (that is the compatibility this branch is for), while - # version skew — a pre-Stage-B orchestrator launching a P2 image, which - # bakes nothing — is REJECTED instead of running unscoped. - # - # STILL pre-install, so the line is stdout only. A `_warn_cw` here would - # spawn the CloudWatch writer thread and pin `boto3.DEFAULT_SESSION` off the - # snapshot's baked env, which is the very defect this branch is reporting. - # Nothing is lost: on the intended deployment (no baked `LOG_GROUP_NAME`) - # `_warn_cw` would have degraded to this same stdout line, on a legacy image - # the log group would be the wrong one anyway, and the rejection reason also - # travels in the structured response body the service surfaces. - absent = _absent_required_platform_env() - if absent: - _pre_config_log( - f"/run hook REJECTED: no platform_config and the image snapshot does " - f"not supply required value(s) either: {absent}" - + (f" task_id={task_id_log!r}" if task_id_log else "") - ) - return JSONResponse( - status_code=400, - content={ - "code": "MICROVM_RUN_PLATFORM_CONFIG_INCOMPLETE", - "message": ( - "The /run envelope carried no platform_config and the image " - "snapshot does not carry the required values either, so this " - f"MicroVM cannot run a task: {absent} are unset. This is a " - "version skew — an orchestrator predating ADR-021 P2 launching " - "a P2 image, which bakes no environment by design. Refusing " - "rather than running with tenant scoping disabled. Redeploy the " - "orchestrator so it sends platform_config." - ), - "missing_env": absent, - }, - ) - _pre_config_log( - "/run hook received no platform_config; running on the image snapshot's " - "own environment, which is frozen at build time and which DOES supply " - "every required value. Expected only from an orchestrator that predates " - "ADR-021 P2 paired with an image that bakes its own configuration." - + (f" task_id={task_id_log!r}" if task_id_log else "") - ) try: params = _extract_invocation_params(payload, request) diff --git a/agent/tests/test_payload_bootstrap.py b/agent/tests/test_payload_bootstrap.py new file mode 100644 index 000000000..04af816b0 --- /dev/null +++ b/agent/tests/test_payload_bootstrap.py @@ -0,0 +1,301 @@ +"""Real bootstrap parsing/stream handling with AWS and HTTPS service boundaries stubbed.""" + +import hashlib +import json +import traceback +from email.message import Message +from io import BytesIO +from unittest.mock import MagicMock +from urllib.error import HTTPError +from urllib.parse import urlencode + +import pytest +from botocore.response import StreamingBody +from fastapi.testclient import TestClient + +import aws_session +import payload_bootstrap as bootstrap +import server + + +class HttpBody(BytesIO): + def __init__(self, raw: bytes, length: int): + super().__init__(raw) + self.headers = {"Content-Length": str(length)} + + +def signed_url(task_id="task-1", bucket="payload-bucket", region="us-east-1"): + suffix = "amazonaws.com.cn" if region.startswith("cn-") else "amazonaws.com" + query = urlencode( + { + "X-Amz-Algorithm": "AWS4-HMAC-SHA256", + "X-Amz-Credential": f"EXAMPLE/20260913/{region}/s3/aws4_request", + "X-Amz-Date": "20260913T120000Z", + "X-Amz-Expires": "900", + "X-Amz-SignedHeaders": "host", + "X-Amz-Signature": "a" * 64, + "X-Amz-Security-Token": "BEARER-SECRET", + } + ) + return f"https://{bucket}.s3.{region}.{suffix}/{task_id}/payload.json?{query}" + + +@pytest.fixture +def transport(monkeypatch): + config = { + "task_table_name": "Tasks", + "task_events_table_name": "Events", + "agent_session_role_arn": "arn:aws:iam::123456789012:role/AgentSession", + "github_token_secret_arn": ( + "arn:aws:secretsmanager:us-west-2:123456789012:secret:github-token-123456" + ), + } + manifest = {"version": 2, "backend": "lambda-microvm", "platform_config": config} + raw_manifest = json.dumps(manifest).encode() + key = "bootstrap/" + hashlib.sha256(raw_manifest).hexdigest() + ".json" + reference = { + "version": 2, + "task_id": "task-1", + "bootstrap_s3_uri": f"s3://payload-bucket/{key}", + "payload_url": signed_url(), + "expires_at": 1800000000000, + } + payload = { + "task_id": "task-1", + "repo_url": "org/repo", + "prompt": "do it", + "github_token": "fake", + } + document = { + "version": 2, + "task_id": "task-1", + "agent_payload": payload, + "platform_config": config, + } + streams = [] + s3 = MagicMock() + + def get_object(**kwargs): + assert kwargs == {"Bucket": "payload-bucket", "Key": key} + body = StreamingBody(BytesIO(raw_manifest), len(raw_manifest)) + streams.append(body) + return {"Body": body, "ContentLength": len(raw_manifest)} + + s3.get_object.side_effect = get_object + platform = MagicMock(return_value=s3) + monkeypatch.setattr(aws_session, "platform_client", platform) + opener = MagicMock() + + def response(_url, **kwargs): + assert kwargs == {"timeout": 10} + raw = json.dumps(document).encode() + return HttpBody(raw, len(raw)) + + opener.open.side_effect = response + build = MagicMock(return_value=opener) + monkeypatch.setattr(bootstrap, "build_opener", build) + return { + "reference": reference, + "config": config, + "payload": payload, + "document": document, + "manifest": manifest, + "s3": s3, + "platform": platform, + "opener": opener, + "build": build, + "streams": streams, + } + + +def test_authenticates_manifest_before_downloading_and_preserves_cross_region_secret(transport): + payload, config = bootstrap.resolve_payload_reference(transport["reference"], "lambda-microvm") + assert payload == transport["payload"] + assert config == transport["config"] + assert ":us-west-2:" in config["github_token_secret_arn"] + transport["platform"].assert_called_once() + assert transport["platform"].call_args.args == ("s3",) + assert len(transport["streams"]) == 1 + assert transport["streams"][0]._raw_stream.closed + assert transport["opener"].open.call_args.args == (transport["reference"]["payload_url"],) + assert isinstance(transport["build"].call_args.args[1], bootstrap._NoRedirect) + assert transport["build"].call_args.args[0].proxies == {} + + +@pytest.mark.parametrize("reference", [{}, {"agent_payload": {}}, {"version": 1}, [], "raw"]) +def test_legacy_and_malformed_envelopes_never_read_or_start(reference, transport): + with pytest.raises(ValueError, match="v2 is required"): + bootstrap.resolve_payload_reference(reference, "lambda-microvm") + transport["platform"].assert_not_called() + + +@pytest.mark.parametrize( + "uri", + [ + "http://169.254.169.254/metadata", + "s3://payload-bucket/task-2/payload.json", + "s3://payload-bucket/bootstrap/../task-2/payload.json", + "s3://payload-bucket/bootstrap/not-a-digest.json", + "s3://payload-bucket/bootstrap/" + "a" * 64 + ".json?versionId=evil", + ], +) +def test_manifest_shape_rejects_other_objects_before_aws(transport, uri): + transport["reference"]["bootstrap_s3_uri"] = uri + with pytest.raises(ValueError): + bootstrap.resolve_payload_reference(transport["reference"], "lambda-microvm") + transport["platform"].assert_not_called() + + +def test_foreign_manifest_denial_prevents_download_and_config_install( + transport, monkeypatch, capfd +): + transport["s3"].get_object.side_effect = PermissionError("AccessDenied") + install = MagicMock() + spawn = MagicMock() + monkeypatch.setattr(server, "_install_platform_config", install) + monkeypatch.setattr(server, "_spawn_background", spawn) + with TestClient(server.app) as client: + response = client.post( + server.MICROVM_HOOK_PREFIX + "/run", + json={ + "microvmId": "mvm", + "runHookPayload": json.dumps(transport["reference"]), + }, + ) + assert response.status_code == 500 + assert response.json()["code"] == "MICROVM_RUN_PAYLOAD_UNREADABLE" + install.assert_not_called() + spawn.assert_not_called() + transport["opener"].open.assert_not_called() + assert "BEARER-SECRET" not in capfd.readouterr().out + + +def test_run_hook_never_logs_the_chained_http_error_url(transport, monkeypatch, capfd): + url = transport["reference"]["payload_url"] + transport["opener"].open.side_effect = HTTPError(url, 403, url, Message(), None) + install = MagicMock() + monkeypatch.setattr(server, "_install_platform_config", install) + with TestClient(server.app) as client: + response = client.post( + server.MICROVM_HOOK_PREFIX + "/run", + json={ + "microvmId": "mvm", + "runHookPayload": json.dumps(transport["reference"]), + }, + ) + assert response.status_code == 500 + install.assert_not_called() + assert "BEARER-SECRET" not in response.text + assert "BEARER-SECRET" not in capfd.readouterr().out + + +@pytest.mark.parametrize( + "mutate", + [ + lambda d: d["platform_config"].update( + github_token_secret_arn="arn:aws:secretsmanager:us-west-2:123456789012:secret:bgagent-linear-oauth-victim" + ), + lambda d: d.update(task_id="task-2"), + lambda d: d["agent_payload"].update(task_id="task-2"), + lambda d: d.update(platform_config=None), + ], +) +def test_same_account_workspace_redirect_or_task_substitution_is_rejected(transport, mutate): + # Detach the document from the fixture's authenticated manifest values. + transport["document"]["platform_config"] = dict(transport["config"]) + mutate(transport["document"]) + with pytest.raises(ValueError): + bootstrap.resolve_payload_reference(transport["reference"], "lambda-microvm") + + +@pytest.mark.parametrize( + "url", + [ + "http://169.254.169.254/latest/meta-data", + signed_url(task_id="task-2"), + signed_url(bucket="another-bucket"), + signed_url().replace("amazonaws.com/", "amazonaws.com.evil.example/"), + signed_url().replace("https://", "https://user@"), + signed_url().replace("amazonaws.com/", "amazonaws.com:443/"), + signed_url() + "#fragment", + signed_url() + "&X-Amz-Signature=" + "b" * 64, + signed_url().replace("X-Amz-Expires=900", "X-Amz-Expires=999999"), + ], +) +def test_download_reference_rejects_wrong_task_hosts_redirect_coordinates_and_ambiguity( + transport, url +): + transport["reference"]["payload_url"] = url + with pytest.raises(ValueError, match="exact S3 object"): + bootstrap.resolve_payload_reference(transport["reference"], "lambda-microvm") + transport["opener"].open.assert_not_called() + + +@pytest.mark.parametrize( + "raw,length", + [ + (b'{"truncated":', 13), + (b"\xff", 1), + (b"[]", 2), + (b"{}", 40), + (b"{}", 0), + (b"{}", bootstrap.CONTRACT["max_payload_bytes"] + 1), + ], +) +def test_bad_payload_bytes_are_unreadable_not_bad_envelopes(transport, raw, length): + body = HttpBody(raw, length) + transport["opener"].open.side_effect = None + transport["opener"].open.return_value = body + with pytest.raises(bootstrap.PayloadFetchError): + bootstrap.resolve_payload_reference(transport["reference"], "lambda-microvm") + assert body.closed + + +@pytest.mark.parametrize("mode", ["digest", "short", "closed", "too_large", "array"]) +def test_bad_manifest_streams_fail_before_download_and_are_closed(transport, mode): + raw = b"[]" if mode == "array" else b"{}" + length = 100 if mode == "short" else len(raw) + if mode == "too_large": + length = bootstrap.CONTRACT["max_manifest_bytes"] + 1 + body = StreamingBody(BytesIO(raw), length) + if mode == "closed": + body.close() + transport["s3"].get_object.side_effect = None + transport["s3"].get_object.return_value = {"Body": body, "ContentLength": length} + with pytest.raises(bootstrap.PayloadFetchError): + bootstrap.resolve_payload_reference(transport["reference"], "lambda-microvm") + assert body._raw_stream.closed + transport["opener"].open.assert_not_called() + + +@pytest.mark.parametrize("code", [301, 307, 403, 500]) +def test_redirect_expiry_and_service_errors_do_not_echo_capabilities(transport, code): + url = transport["reference"]["payload_url"] + transport["opener"].open.side_effect = HTTPError(url, code, url, Message(), None) + with pytest.raises(bootstrap.PayloadFetchError, match=f"HTTP {code}") as error: + bootstrap.resolve_payload_reference(transport["reference"], "lambda-microvm") + assert "BEARER-SECRET" not in str(error.value) + # ECS's Python boot command can print an uncaught exception. Its formatted + # traceback must be safe too, not just the MicroVM route's JSON response. + assert "BEARER-SECRET" not in "".join(traceback.format_exception(error.value)) + assert bootstrap._NoRedirect().redirect_request(None, None, code, "", {}, url) is None + + +def test_ecs_consumes_reference_before_running_code(transport, monkeypatch): + monkeypatch.setenv("TASK_ID", "task-1") + monkeypatch.setenv("AGENT_PAYLOAD_REF", json.dumps(transport["reference"])) + resolve = MagicMock(return_value=(transport["payload"], {})) + monkeypatch.setattr(bootstrap, "resolve_payload_reference", resolve) + assert bootstrap.load_ecs_payload() == transport["payload"] + import os + + assert "AGENT_PAYLOAD_REF" not in os.environ + assert resolve.call_args.args[1] == "ecs" + + +def test_ecs_rejects_another_tasks_reference(transport, monkeypatch): + monkeypatch.setenv("TASK_ID", "task-2") + monkeypatch.setenv("AGENT_PAYLOAD_REF", json.dumps(transport["reference"])) + with pytest.raises(ValueError, match="ECS task identity"): + bootstrap.load_ecs_payload() + transport["platform"].assert_not_called() diff --git a/agent/tests/test_server.py b/agent/tests/test_server.py index 0ac6990ea..c128af8ae 100644 --- a/agent/tests/test_server.py +++ b/agent/tests/test_server.py @@ -9,7 +9,6 @@ import threading import time from pathlib import Path -from types import SimpleNamespace from typing import Any from unittest.mock import MagicMock @@ -926,13 +925,45 @@ def _platform_config(**overrides) -> dict: return config -def _run_hook_body(envelope: dict, microvm_id: str = "microvm-abc") -> dict: - """Wrap an ABCA payload envelope in the service's ``/run`` request body. +# Route tests isolate the authenticated transport boundary. The real manifest +# IAM/stream/URL consumer is exercised in test_payload_bootstrap.py. +_run_documents: dict[str, tuple[dict, Any]] = {} - The service passes ``runHookPayload`` through as an opaque STRING (it never - parses it), so the double encoding here is the real wire shape, not a test - artifact. - """ + +@pytest.fixture(autouse=True) +def _authenticated_test_transport(monkeypatch): + import payload_bootstrap + + _run_documents.clear() + monkeypatch.setattr( + payload_bootstrap, + "_manifest", + lambda uri, backend: ("payload-bucket", _run_documents[uri][1]), + ) + monkeypatch.setattr(payload_bootstrap, "_download", lambda url: _run_documents[url][0]) + yield + _run_documents.clear() + + +def _run_hook_body(envelope: dict, microvm_id: str = "microvm-abc") -> dict: + """Wrap pipeline/config fixtures in the current v2 service envelope.""" + from tests.test_payload_bootstrap import signed_url + + if "agent_payload" in envelope and isinstance(envelope["agent_payload"], dict): + payload = envelope["agent_payload"] + task_id = payload.get("task_id", "invalid") + config = envelope.get("platform_config", _platform_config()) + uri = f"s3://payload-bucket/bootstrap/{'a' * 64}.json" + url = signed_url(task_id=task_id) + document = { + "version": 2, + "task_id": task_id, + "agent_payload": payload, + "platform_config": config, + } + _run_documents[uri] = (document, config) + _run_documents[url] = (document, config) + envelope = {"version": 2, "task_id": task_id, "bootstrap_s3_uri": uri, "payload_url": url} return {"microvmId": microvm_id, "runHookPayload": json.dumps(envelope)} @@ -1320,21 +1351,16 @@ def fake_run(argv, **kwargs): assert "skipping best-effort warm-up of 'opt'" in capfd.readouterr().out -class TestMicrovmRunHookInlinePayload: - """Inline envelope: ``{"agent_payload": {...}}``. +class TestMicrovmRunHookVerifiedPayload: + """Map an authenticated v2 payload to the asynchronous task pipeline. - The exception rather than the rule — the service caps ``runHookPayload`` at - 4 096 bytes and a hydrated payload is larger — but it is the branch that - proves the payload→pipeline mapping without any S3 involvement. + The module fixture supplies manifest/download bytes; the shared consumer's + authentication and transport checks have their own regression suite. """ def test_accepts_the_payload_and_starts_the_pipeline_asynchronously( - self, client, monkeypatch, baked_platform_env + self, client, monkeypatch, cached_github_token ): - # `baked_platform_env`: this envelope carries no `platform_config`, which - # since review N2 requires the effective env to supply the required values - # (a legacy image that bakes its own). This class is about the - # payload->pipeline mapping, not about config delivery. started = threading.Event() seen: dict = {} @@ -1357,7 +1383,7 @@ def fake_run_task(**kwargs): "aws_region": "us-east-1", } }, - microvm_id="microvm-inline", + microvm_id="microvm-verified", ), ) @@ -1366,7 +1392,7 @@ def fake_run_task(**kwargs): assert body["status"] == "accepted" assert body["task_id"] == "t-microvm-1" # Echoed so a MicroVM log line can be joined to the control-plane id. - assert body["microvm_id"] == "microvm-inline" + assert body["microvm_id"] == "microvm-verified" assert started.wait(timeout=5.0), "pipeline thread did not start" # Same mapping the /invocations path performs: prompt→task_description, @@ -1375,11 +1401,7 @@ def fake_run_task(**kwargs): assert seen["repo_url"] == "org/repo" assert seen["task_description"] == "Fix the bug" - def test_returns_before_the_pipeline_finishes(self, client, monkeypatch, baked_platform_env): - # `baked_platform_env`: this envelope carries no `platform_config`, which - # since review N2 requires the effective env to supply the required values - # (a legacy image that bakes its own). This class is about the - # payload->pipeline mapping, not about config delivery. + def test_returns_before_the_pipeline_finishes(self, client, monkeypatch, cached_github_token): release = threading.Event() entered = threading.Event() @@ -1407,12 +1429,8 @@ def slow_run_task(**_kwargs): release.set() def test_uses_the_same_model_id_and_prompt_aliases_as_invocations( - self, client, monkeypatch, baked_platform_env + self, client, monkeypatch, cached_github_token ): - # `baked_platform_env`: this envelope carries no `platform_config`, which - # since review N2 requires the effective env to supply the required values - # (a legacy image that bakes its own). This class is about the - # payload->pipeline mapping, not about config delivery. seen: dict = {} started = threading.Event() @@ -1444,118 +1462,6 @@ def fake_run_task(**kwargs): assert seen["channel_source"] == "linear" -class TestMicrovmRunHookS3Payload: - """S3-pointer envelope: ``{"agent_payload_s3_uri": "s3://bucket/key"}``. - - The DOMINANT path on this backend: with a 4 096-byte ``runHookPayload`` cap, - any hydrated payload is offloaded to the platform payload bucket and only the - pointer travels in the hook body. - """ - - def test_fetches_the_payload_from_s3_and_starts_the_pipeline( - self, client, monkeypatch, baked_platform_env - ): - # `baked_platform_env`: this envelope carries no `platform_config`, which - # since review N2 requires the effective env to supply the required values - # (a legacy image that bakes its own). This class is about the - # payload->pipeline mapping, not about config delivery. - seen: dict = {} - started = threading.Event() - - def fake_run_task(**kwargs): - seen.update(kwargs) - started.set() - - fetched: dict = {} - - def fake_fetch(uri): - fetched["uri"] = uri - return {"task_id": "t-s3", "repo_url": "org/repo", "prompt": "from s3"} - - monkeypatch.setattr(server, "_fetch_microvm_payload_from_s3", fake_fetch) - monkeypatch.setattr(server, "run_task", fake_run_task) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - - r = client.post( - RUN_HOOK, - json=_run_hook_body({"agent_payload_s3_uri": "s3://payload-bucket/t-s3/payload.json"}), - ) - - assert r.status_code == 200 - assert r.json()["task_id"] == "t-s3" - assert fetched["uri"] == "s3://payload-bucket/t-s3/payload.json" - assert started.wait(timeout=5.0) - assert seen["task_description"] == "from s3" - - def test_parses_bucket_and_key_out_of_the_uri(self, monkeypatch): - captured: dict = {} - - class _Body: - @staticmethod - def read(): - return b'{"task_id": "t-1", "repo_url": "o/r"}' - - class _S3: - @staticmethod - def get_object(**kwargs): - captured.update(kwargs) - return {"Body": _Body} - - import boto3 - - monkeypatch.setattr(boto3, "client", lambda *_a, **_k: _S3) - - payload = server._fetch_microvm_payload_from_s3("s3://my-bucket/prefix/t-1/payload.json") - - # Key keeps every slash after the bucket — a naive split would truncate it. - assert captured == {"Bucket": "my-bucket", "Key": "prefix/t-1/payload.json"} - assert payload == {"task_id": "t-1", "repo_url": "o/r"} - - def test_rejects_a_uri_with_no_key(self, monkeypatch): - with pytest.raises(ValueError, match="not a bucket/key URI"): - server._fetch_microvm_payload_from_s3("s3://bucket-only") - - def test_rejects_a_non_object_s3_body(self, monkeypatch): - class _Body: - @staticmethod - def read(): - return b"[1, 2, 3]" - - class _S3: - @staticmethod - def get_object(**_kwargs): - return {"Body": _Body} - - import boto3 - - monkeypatch.setattr(boto3, "client", lambda *_a, **_k: _S3) - - # `_PayloadFetchError`, NOT `ValueError` (review N1): the object is bad, not - # the orchestrator's envelope, so the handler must route it to its RETRYABLE - # 500 rather than the "retrying cannot help" 400. Asserting the type is the - # point — `ValueError` here would silently restore the misclassification. - with pytest.raises(server._PayloadFetchError, match="expected an object"): - server._fetch_microvm_payload_from_s3("s3://b/k") - assert not issubclass(server._PayloadFetchError, ValueError) - - def test_s3_failure_returns_500_and_starts_nothing(self, client, monkeypatch): - def boom(_uri): - raise RuntimeError("AccessDenied") - - monkeypatch.setattr(server, "_fetch_microvm_payload_from_s3", boom) - monkeypatch.setattr(server, "run_task", MagicMock()) - - r = client.post(RUN_HOOK, json=_run_hook_body({"agent_payload_s3_uri": "s3://bucket/key"})) - - # 500, not 400: the body was well-formed, the fetch was not. Retrying an - # identical body CAN help here, unlike a malformed envelope. - assert r.status_code == 500 - assert r.json()["code"] == "MICROVM_RUN_PAYLOAD_UNREADABLE" - assert "AccessDenied" in r.json()["message"] - with server._threads_lock: - assert server._active_threads == [] - - class TestMicrovmRunHookRejections: """Every shape the agent cannot act on must fail LOUDLY, before spawning. @@ -1566,15 +1472,15 @@ class TestMicrovmRunHookRejections: @pytest.mark.parametrize( "run_hook_payload,expected_fragment", [ - ("", "runHookPayload is empty"), - (" ", "runHookPayload is empty"), + ("", "not valid JSON"), + (" ", "not valid JSON"), ("not json at all", "not valid JSON"), - ('"a string"', "must be a JSON object"), - ("[1,2,3]", "must be a JSON object"), - ('{"agent_payload": "not-an-object"}', "agent_payload must be an object"), - ('{"agent_payload_s3_uri": "https://example.com/x"}', "must be an s3:// URI"), - ('{"agent_payload_s3_uri": 42}', "must be an s3:// URI"), - ('{"something_else": 1}', "neither agent_payload nor agent_payload_s3_uri"), + ('"a string"', "v2 is required"), + ("[1,2,3]", "v2 is required"), + ('{"agent_payload": "not-an-object"}', "v2 is required"), + ('{"agent_payload_s3_uri": "https://example.com/x"}', "v2 is required"), + ('{"agent_payload_s3_uri": 42}', "v2 is required"), + ('{"something_else": 1}', "v2 is required"), ], ) def test_returns_400_with_a_named_code( @@ -1603,9 +1509,9 @@ def test_a_missing_body_field_is_a_400_not_a_422(self, client, monkeypatch): assert r.json()["code"] == "MICROVM_RUN_PAYLOAD_INVALID" def test_incomplete_task_record_reuses_the_invocations_rejection_shape( - self, client, monkeypatch, baked_platform_env + self, client, monkeypatch, cached_github_token ): - # `baked_platform_env` so the run gets PAST config delivery and reaches the + # Cache the GitHub token so this test reaches the # task-record check this test is actually about. monkeypatch.setattr(server, "run_task", MagicMock()) @@ -1633,12 +1539,8 @@ class TestMicrovmRunHookHeaderPosture: """ def test_session_id_and_workload_token_resolve_empty( - self, client, monkeypatch, baked_platform_env + self, client, monkeypatch, cached_github_token ): - # `baked_platform_env`: this envelope carries no `platform_config`, which - # since review N2 requires the effective env to supply the required values - # (a legacy image that bakes its own). This class is about the - # payload->pipeline mapping, not about config delivery. seen: dict = {} started = threading.Event() @@ -1744,26 +1646,9 @@ def test_merge_branches_non_string_entries_filtered(self): @pytest.fixture -def baked_platform_env(env_guard): - """Simulate a legacy/hand-built image that BAKES its own required config. - - Needed by every ``/run`` test whose envelope carries no ``platform_config``. - Since review N2 the no-config branch re-runs the required-key check against the - EFFECTIVE environment and rejects when it is unsatisfied — because - ``aws_session`` silently drops tenant scoping when ``AGENT_SESSION_ROLE_ARN`` - is unset, and running a task unscoped is worse than refusing it. That check is - what this fixture satisfies, and satisfying it is exactly what a real legacy - image does: the compatibility path is "the snapshot supplies the values", not - "nobody supplies them". - - Depends on ``env_guard`` so the writes are reverted with everything else. - """ - for key in server.MICROVM_PLATFORM_CONFIG_REQUIRED_KEYS: - os.environ[server.MICROVM_PLATFORM_CONFIG_ENV_BY_KEY[key]] = _platform_config_value(key) - # A baked GITHUB_TOKEN_SECRET_ARN makes `resolve_github_token` reach for real - # Secrets Manager; pre-seeding its cache keeps these tests offline. Realistic - # for the image this fixture models, and it changes nothing they assert. - os.environ["GITHUB_TOKEN"] = "ghp_baked_for_tests" # noqa: S105 -- test placeholder, not a secret +def cached_github_token(env_guard): + """Keep pipeline mapping tests offline after authenticated config installation.""" + os.environ["GITHUB_TOKEN"] = "ghp_cached_for_tests" # noqa: S105 -- test placeholder yield @@ -2204,20 +2089,10 @@ def test_an_arn_in_a_foreign_account_is_rejected(self, env_guard): assert "GITHUB_TOKEN_SECRET_ARN" not in os.environ def test_an_in_account_redirect_is_NOT_rejected(self, env_guard): - # The KNOWN LIMITATION, pinned as a test so it cannot be quietly mistaken for - # coverage. This check compares partition + account only, so a block naming - # another workspace's channel-OAuth secret in the SAME account is accepted — - # and the `bgagent-*-oauth-*` grants are prefix grants, so IAM would allow - # that read too. - # - # It is left open because it is currently unreachable from the guest: - # `platform_config` is produced by the orchestrator Lambda, and the MicroVM - # execution role holds `grantRead` ONLY on the payload bucket, so a running - # MicroVM can read another task's payload but cannot write one. - # - # If this test ever needs to flip to `pytest.raises`, the escalation is a - # name-shape check tying `github_token_secret_arn` to the task's own - # channel/workspace — see `MICROVM_PLATFORM_CONFIG_ARN_KEYS`. + # Unit scope: the installer checks internal ARN agreement, not origin. + # The v2 resolver authenticates the manifest and compares the downloaded + # config BEFORE calling this installer. Its own route/transport tests + # reject same-account workspace substitutions. installed = server._install_platform_config( _platform_config( github_token_secret_arn=( @@ -2229,10 +2104,8 @@ def test_an_in_account_redirect_is_NOT_rejected(self, env_guard): assert "GITHUB_TOKEN_SECRET_ARN" in installed def test_a_wholesale_partition_swap_is_NOT_rejected(self, env_guard): - # The other half of the same limitation, and the reason the docstrings say - # "internally consistent" rather than "pinned to this deployment": the anchor - # travels in the block it validates, so a payload that moves EVERY ARN to - # another partition agrees with itself and passes. IAM is what refuses it. + # A self-consistent block passes this internal-consistency helper. + # Deployment provenance is enforced earlier by the v2 bootstrap resolver. installed = server._install_platform_config( _platform_config( agent_session_role_arn=f"arn:aws-cn:iam::{_TEST_ACCOUNT}:role/r", @@ -2398,7 +2271,7 @@ def _payload(self, **extra) -> dict: **extra, } - def test_inline_envelope_installs_the_config_and_accepts_the_task( + def test_verified_payload_installs_the_config_and_accepts_the_task( self, client, monkeypatch, env_guard ): monkeypatch.setattr(server, "run_task", MagicMock()) @@ -2509,194 +2382,6 @@ def test_a_non_object_block_returns_400(self, client, monkeypatch, env_guard): assert r.status_code == 400 assert r.json()["code"] == "MICROVM_RUN_PLATFORM_CONFIG_INVALID" - def test_an_envelope_without_platform_config_is_accepted_when_the_image_bakes_it( - self, client, monkeypatch, baked_platform_env, capfd - ): - # P1 compatibility, PRECISELY scoped (review N2): image snapshot and - # orchestrator Lambda deploy on independent cadences, so a new image must not - # require a Stage-B orchestrator — PROVIDED the values come from somewhere. - # Here the image bakes them, which is what the compatibility path is for. - monkeypatch.setattr(server, "run_task", MagicMock()) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - - r = client.post(RUN_HOOK, json=_run_hook_body({"agent_payload": self._payload()})) - - assert r.status_code == 200 - # Still pre-install (nothing was installed), so the warning is stdout-only: - # `_warn_cw` here would spawn the CloudWatch thread off the snapshot's own - # baked env — the very thing it is warning about. See `TestMicrovmRunHook - # PreInstallAwsSilence`. - assert "[server/run-pre-config] /run hook received no platform_config" in ( - capfd.readouterr().out - ) - - def test_no_platform_config_and_no_baked_env_is_refused_not_run_unscoped( - self, client, monkeypatch, env_guard, capfd - ): - # Review N2, the version-skew case: a pre-Stage-B orchestrator launching a P2 - # image. The image bakes NOTHING by design (`imageEnvironmentVariables` - # defaults to `{}`), so nothing supplies `AGENT_SESSION_ROLE_ARN` — and - # `aws_session.get_session` silently falls back to the ambient compute role - # with tenant scoping OFF when it is unset. Refusing is the only correct - # answer; the previous behaviour was a 200 and a stdout breadcrumb. - run_task = MagicMock() - monkeypatch.setattr(server, "run_task", run_task) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - for key in server.MICROVM_PLATFORM_CONFIG_REQUIRED_KEYS: - os.environ.pop(server.MICROVM_PLATFORM_CONFIG_ENV_BY_KEY[key], None) - - r = client.post(RUN_HOOK, json=_run_hook_body({"agent_payload": self._payload()})) - - assert r.status_code == 400 - body = r.json() - assert body["code"] == "MICROVM_RUN_PLATFORM_CONFIG_INCOMPLETE" - # The response NAMES the unset variables — the whole point is that a skewed - # deployment is diagnosable rather than mysterious. - assert body["missing_env"] == sorted( - server.MICROVM_PLATFORM_CONFIG_ENV_BY_KEY[key] - for key in server.MICROVM_PLATFORM_CONFIG_REQUIRED_KEYS - ) - assert "AGENT_SESSION_ROLE_ARN" in body["missing_env"] - # Nothing was started. - run_task.assert_not_called() - # And the rejection is attributable in the log, not just in the response. - assert "/run hook REJECTED: no platform_config" in capfd.readouterr().out - - def test_a_partially_baked_env_names_only_what_is_actually_missing( - self, client, monkeypatch, baked_platform_env - ): - # The realistic skew: an image that bakes SOME config. The rejection must - # name only the genuinely-unset variables, or an operator chases the wrong - # one. - monkeypatch.setattr(server, "run_task", MagicMock()) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - os.environ.pop("AGENT_SESSION_ROLE_ARN", None) - - r = client.post(RUN_HOOK, json=_run_hook_body({"agent_payload": self._payload()})) - - assert r.status_code == 400 - assert r.json()["missing_env"] == ["AGENT_SESSION_ROLE_ARN"] - - def test_s3_pointer_takes_the_config_from_the_outer_envelope( - self, client, monkeypatch, env_guard - ): - # The producer's pointer form: the bare task payload lands in S3 and the - # config rides beside the pointer, inside the 4 KB hook body. - monkeypatch.setattr( - server, - "_fetch_microvm_payload_from_s3", - lambda _uri: self._payload(task_id="t-outer"), - ) - monkeypatch.setattr(server, "run_task", MagicMock()) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - - r = client.post( - RUN_HOOK, - json=_run_hook_body( - { - "agent_payload_s3_uri": "s3://bucket/t-outer/payload.json", - "platform_config": _platform_config(task_table_name="outer-table"), - } - ), - ) - - assert r.status_code == 200 - assert r.json()["task_id"] == "t-outer" - assert os.environ["TASK_TABLE_NAME"] == "outer-table" - - def test_s3_pointer_takes_the_config_merged_into_the_fetched_object( - self, client, monkeypatch, env_guard - ): - # The producer ALSO merges the config into the S3 object, so the agent - # gets it whichever end of the fetch it reads. A stray platform_config key - # left in the bare payload is inert — the extractor reads named fields. - fetched = self._payload(task_id="t-inner") - fetched["platform_config"] = _platform_config(task_table_name="inner-table") - monkeypatch.setattr(server, "_fetch_microvm_payload_from_s3", lambda _uri: fetched) - monkeypatch.setattr(server, "run_task", MagicMock()) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - - r = client.post( - RUN_HOOK, - json=_run_hook_body({"agent_payload_s3_uri": "s3://bucket/t-inner/payload.json"}), - ) - - assert r.status_code == 200 - assert r.json()["task_id"] == "t-inner" - assert os.environ["TASK_TABLE_NAME"] == "inner-table" - - def test_s3_object_may_itself_be_the_full_envelope(self, client, monkeypatch, env_guard): - monkeypatch.setattr( - server, - "_fetch_microvm_payload_from_s3", - lambda _uri: { - "agent_payload": self._payload(task_id="t-nested"), - "platform_config": _platform_config(task_table_name="nested-table"), - }, - ) - monkeypatch.setattr(server, "run_task", MagicMock()) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - - r = client.post( - RUN_HOOK, - json=_run_hook_body({"agent_payload_s3_uri": "s3://bucket/t-nested/payload.json"}), - ) - - assert r.status_code == 200 - assert r.json()["task_id"] == "t-nested" - assert os.environ["TASK_TABLE_NAME"] == "nested-table" - - def test_the_fetched_object_wins_over_the_outer_envelope(self, client, monkeypatch, env_guard): - fetched = self._payload(task_id="t-prec") - fetched["platform_config"] = _platform_config(task_table_name="inner-wins") - monkeypatch.setattr(server, "_fetch_microvm_payload_from_s3", lambda _uri: fetched) - monkeypatch.setattr(server, "run_task", MagicMock()) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - - r = client.post( - RUN_HOOK, - json=_run_hook_body( - { - "agent_payload_s3_uri": "s3://bucket/t-prec/payload.json", - "platform_config": _platform_config(task_table_name="outer-loses"), - } - ), - ) - - assert r.status_code == 200 - assert os.environ["TASK_TABLE_NAME"] == "inner-wins" - - def test_a_nested_agent_payload_of_the_wrong_type_is_a_retryable_500(self, client, monkeypatch): - # Review N1: this is a problem with the FETCHED OBJECT, not with the envelope - # the orchestrator built, so it belongs on the retryable 500 branch. The old - # 400 told the operator "the orchestrator built a bad envelope; retrying - # cannot help" — both halves wrong for a racing or half-written S3 object. - monkeypatch.setattr( - server, - "_fetch_microvm_payload_from_s3", - lambda _uri: {"agent_payload": "not-an-object"}, - ) - monkeypatch.setattr(server, "run_task", MagicMock()) - - r = client.post(RUN_HOOK, json=_run_hook_body({"agent_payload_s3_uri": "s3://b/k"})) - - assert r.status_code == 500 - assert r.json()["code"] == "MICROVM_RUN_PAYLOAD_UNREADABLE" - assert "agent_payload in the S3 payload must be an object" in r.json()["message"] - - def test_resolve_returns_the_config_alongside_the_payload(self): - payload, config = server._resolve_microvm_run_payload( - json.dumps({"agent_payload": {"task_id": "t"}, "platform_config": {"a": "b"}}) - ) - assert payload == {"task_id": "t"} - assert config == {"a": "b"} - - def test_resolve_returns_none_for_an_envelope_without_a_config(self): - _payload, config = server._resolve_microvm_run_payload( - json.dumps({"agent_payload": {"task_id": "t"}}) - ) - assert config is None - # -------------------------------------------------------------------------- # /validate + /terminate (ADR-021 P2) @@ -2915,12 +2600,8 @@ def test_never_writes_terminal_task_status(self, client, monkeypatch): write_heartbeat.assert_not_called() def test_returns_200_without_joining_a_running_pipeline( - self, client, monkeypatch, baked_platform_env + self, client, monkeypatch, cached_github_token ): - # `baked_platform_env`: this envelope carries no `platform_config`, which - # since review N2 requires the effective env to supply the required values - # (a legacy image that bakes its own). This class is about the - # payload->pipeline mapping, not about config delivery. # A drain can take minutes (that is lifespan's job on graceful shutdown); # the hook budget is 1-60 s, so /terminate must observe and return. release = threading.Event() @@ -2998,56 +2679,6 @@ def __iter__(self): assert "best-effort step failed" in capfd.readouterr().out -class TestMicrovmPayloadFetchAttribution: - """Every outbound AWS call carries ABCA's solution attribution (#319).""" - - def test_the_s3_payload_fetch_goes_through_the_attributed_factory(self, monkeypatch): - captured: dict = {} - - class _Body: - @staticmethod - def read(): - return b'{"task_id": "t-1"}' - - def fake_platform_client(service_name, **kwargs): - captured["service"] = service_name - captured["kwargs"] = kwargs - return SimpleNamespace(get_object=lambda **_kw: {"Body": _Body}) - - import aws_session - - monkeypatch.setattr(aws_session, "platform_client", fake_platform_client) - - assert server._fetch_microvm_payload_from_s3("s3://b/k") == {"task_id": "t-1"} - assert captured["service"] == "s3" - - def test_the_fetch_client_carries_the_md_user_agent_segment(self, monkeypatch): - # A naked boto3.client('s3') would silently drop the md/ segment. Assert on - # the OUTCOME (the UA on the config) rather than on which helper was used. - captured: dict = {} - - class _Body: - @staticmethod - def read(): - return b'{"task_id": "t-1"}' - - def fake_boto3_client(service_name, **kwargs): - captured["service"] = service_name - captured["config"] = kwargs.get("config") - return SimpleNamespace(get_object=lambda **_kw: {"Body": _Body}) - - import boto3 - - monkeypatch.setattr(boto3, "client", fake_boto3_client) - - server._fetch_microvm_payload_from_s3("s3://b/k") - - import ua - - assert captured["service"] == "s3" - assert ua.static_user_agent_extra() in captured["config"].user_agent_extra - - class TestSnapshotCredentialHygiene: """Nothing on the server's import or /ready path may cache an SDK session. @@ -3133,316 +2764,6 @@ def test_import_and_build_hooks_create_no_boto3_session(self): } -class TestMicrovmRunHookPreInstallAwsSilence: - """Before ``platform_config`` is installed, ``/run`` may touch exactly ONE AWS seam. - - Same defect class the build hooks avoid, one phase later: until the install has - run, ``LOG_GROUP_NAME`` is whatever the snapshot happens to carry, so a - ``_debug_cw`` on this path would resolve credentials and pin - ``boto3.DEFAULT_SESSION`` *before* the orchestrator's own region / - ``AWS_SDK_UA_APP_ID`` / session role are in the environment. The sole permitted - pre-install call is the S3 payload fetch, because the config is inside the - object being fetched. - - Every test here runs with a **baked ``LOG_GROUP_NAME``** — the hostile case the - fix exists for. Without it, ``_debug_cw`` degrades to stdout on its own and the - assertions would pass vacuously. - """ - - def _payload(self, **extra) -> dict: - return { - "task_id": "t-silent", - "repo_url": "org/repo", - "prompt": "do it", - "github_token": "ghp_x", - **extra, - } - - @pytest.fixture(autouse=True) - def _disable_background_pipeline(self, monkeypatch): - """Keep handler-only assertions isolated from asynchronous pipeline work. - - Mocking ``run_task`` is insufficient because ``_spawn_background`` returns - before its thread necessarily dereferences that global. Pytest can restore - the mock between parametrized cases while the prior thread is still - starting, letting it run the real pipeline under the next case's AWS seam - guard. Stub the spawn boundary instead: these tests specify only the - pre-install handler phase and none need a pipeline thread. - """ - monkeypatch.setattr(server, "_spawn_background", MagicMock()) - - @pytest.fixture - def seam_guard(self, monkeypatch): - """Arm every AWS/credential seam to raise until the pre-install phase is OVER. - - Two things end that phase, and only two: - - * ``_install_platform_config`` returning a **non-empty** env list — a real - install. Flipping on *any* return would be a hole big enough to drive B2 - through: the ``raw is None`` early return installs nothing and returns - ``[]``, so treating it as "installed" disarms the guard for the entire - legacy no-``platform_config`` path — which is exactly where a ``_warn_cw`` - was spawning the CloudWatch thread off the snapshot's baked env. - * ``_extract_invocation_params`` being entered. Past that point the legacy - path is *allowed* to talk to AWS: running on the snapshot's own env is the - documented P1-compatibility behaviour, so the accepted-line ``_debug_cw`` - and the pipeline below it are legitimate. Everything the handler does - *before* it — including the "no platform_config" warning — is not. - - A rejection path reaches neither, so the seams stay armed for the whole - request: a rejected run installed nothing and has no more right to an AWS - call than it had before. - """ - state: dict[str, Any] = { - "install_phase_done": False, - "installed_env": None, - "violations": [], - } - real_install = server._install_platform_config - real_extract = server._extract_invocation_params - - def spy_install(raw): - result = real_install(raw) - state["installed_env"] = result - if result: - state["install_phase_done"] = True - return result - - def spy_extract(*args, **kwargs): - state["install_phase_done"] = True - return real_extract(*args, **kwargs) - - monkeypatch.setattr(server, "_install_platform_config", spy_install) - monkeypatch.setattr(server, "_extract_invocation_params", spy_extract) - - def guard(name): - def _seam(*_args, **_kwargs): - if not state["install_phase_done"]: - state["violations"].append(name) - raise AssertionError(f"{name} touched before platform_config was installed") - return MagicMock() - - return _seam - - import boto3 - - import aws_session - - # Kept so a test can re-enable exactly the ONE permitted pre-install seam - # (the S3 payload fetch) and assert on it positively. - state["real_platform_client"] = aws_session.platform_client - - for module, attr in ( - (boto3, "client"), - (boto3, "Session"), - (aws_session, "platform_client"), - (aws_session, "tenant_client"), - (aws_session, "tenant_resource"), - (aws_session, "get_session"), - (server, "_debug_cw"), - (server, "_warn_cw"), - (server, "_debug_cw_exc"), - ): - monkeypatch.setattr(module, attr, guard(f"{module.__name__}.{attr}")) - - monkeypatch.setenv("LOG_GROUP_NAME", "/abca/agent") - return state - - @pytest.mark.parametrize("with_config", [True, False], ids=["with-config", "no-config"]) - def test_no_cloudwatch_or_credential_seam_is_touched_before_the_install( - self, client, monkeypatch, baked_platform_env, seam_guard, capfd, with_config - ): - # The ``no-config`` arm is the legacy P1 envelope, and it is the harder case: - # nothing is ever installed, so EVERY line up to param extraction — including - # the "running on the snapshot's frozen env" warning itself — is still - # pre-install. A ``_warn_cw`` there would spawn the CloudWatch writer thread - # and pin ``boto3.DEFAULT_SESSION`` off the baked ``LOG_GROUP_NAME`` this - # fixture sets, which is precisely the defect the warning is reporting. - # - # ``baked_platform_env`` (rather than ``env_guard``) so that arm reaches the - # ACCEPT path: since review N2 a no-config run with an unsatisfied effective - # env is refused, and a rejected run installs nothing and so proves nothing - # about the seams staying silent all the way to param extraction. Baking the - # env is also the only shape in which the no-config path is legitimate. - monkeypatch.setattr(server, "run_task", MagicMock()) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - - envelope: dict[str, Any] = {"agent_payload": self._payload()} - if with_config: - envelope["platform_config"] = _platform_config() - - r = client.post(RUN_HOOK, json=_run_hook_body(envelope)) - - assert r.status_code == 200 - assert seam_guard["violations"] == [] - assert seam_guard["install_phase_done"] is True - if with_config: - assert seam_guard["installed_env"] - else: - # Vacuously "installed": the early return the flag must NOT trust. - assert seam_guard["installed_env"] == [] - # The warning still reaches an operator — stdout, via the pre-install sink. - assert ( - "[server/run-pre-config] /run hook received no platform_config" - in capfd.readouterr().out - ) - - def test_the_no_config_REJECTION_also_touches_no_seam( - self, client, monkeypatch, env_guard, seam_guard, capfd - ): - # Review N2's rejection is itself a pre-install path, and it emits a NEW log - # line — so it needs the same guarantee as every other rejection here: the - # refusal must not be the thing that pins `boto3.DEFAULT_SESSION` off the - # snapshot's baked `LOG_GROUP_NAME` (which `seam_guard` sets). - monkeypatch.setattr(server, "run_task", MagicMock()) - for key in server.MICROVM_PLATFORM_CONFIG_REQUIRED_KEYS: - os.environ.pop(server.MICROVM_PLATFORM_CONFIG_ENV_BY_KEY[key], None) - - r = client.post(RUN_HOOK, json=_run_hook_body({"agent_payload": self._payload()})) - - assert r.status_code == 400 - assert r.json()["code"] == "MICROVM_RUN_PLATFORM_CONFIG_INCOMPLETE" - assert seam_guard["violations"] == [] - assert "/run hook REJECTED: no platform_config" in capfd.readouterr().out - - def test_the_received_line_is_stdout_only( - self, client, monkeypatch, env_guard, seam_guard, capfd - ): - monkeypatch.setattr(server, "run_task", MagicMock()) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - - client.post( - RUN_HOOK, - json=_run_hook_body( - {"agent_payload": self._payload(), "platform_config": _platform_config()}, - microvm_id="microvm-quiet", - ), - ) - - out = capfd.readouterr().out - assert "[server/run-pre-config] /run hook received:" in out - assert "microvm-quiet" in out - - def test_the_s3_payload_fetch_is_the_only_pre_install_aws_call( - self, client, monkeypatch, env_guard, seam_guard - ): - # The permitted exception, asserted positively: exactly one client, for s3, - # while the CloudWatch/credential seams stay armed. - services: list[str] = [] - - class _Body: - @staticmethod - def read(): - return json.dumps(self._payload(task_id="t-from-s3")).encode() - - def recording_client(service_name, **_kwargs): - services.append(service_name) - return SimpleNamespace(get_object=lambda **_kw: {"Body": _Body}) - - import boto3 - - import aws_session - - # Re-enable the one permitted seam, and only it: the fetch must still go - # through the attributed factory (#319), which delegates to boto3.client. - monkeypatch.setattr(aws_session, "platform_client", seam_guard["real_platform_client"]) - monkeypatch.setattr(boto3, "client", recording_client) - monkeypatch.setattr(server, "run_task", MagicMock()) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - - r = client.post( - RUN_HOOK, - json=_run_hook_body( - { - "agent_payload_s3_uri": "s3://payload-bucket/t-from-s3/payload.json", - "platform_config": _platform_config(), - } - ), - ) - - assert r.status_code == 200 - assert r.json()["task_id"] == "t-from-s3" - assert services == ["s3"] - assert seam_guard["violations"] == [] - - def test_a_malformed_envelope_is_rejected_without_touching_a_seam( - self, client, monkeypatch, seam_guard, capfd - ): - monkeypatch.setattr(server, "run_task", MagicMock()) - - r = client.post(RUN_HOOK, json={"microvmId": "m", "runHookPayload": "not json"}) - - assert r.status_code == 400 - assert r.json()["code"] == "MICROVM_RUN_PAYLOAD_INVALID" - assert seam_guard["violations"] == [] - assert seam_guard["install_phase_done"] is False - # The reason still reaches an operator: stdout here, and the response body - # (which the MicroVM service surfaces) in every case. - assert "[server/run-pre-config] /run hook rejected:" in capfd.readouterr().out - - def test_a_failed_payload_fetch_is_reported_without_touching_a_seam( - self, client, monkeypatch, seam_guard, capfd - ): - def boom(_uri): - raise RuntimeError("AccessDenied") - - monkeypatch.setattr(server, "_fetch_microvm_payload_from_s3", boom) - monkeypatch.setattr(server, "run_task", MagicMock()) - - r = client.post(RUN_HOOK, json=_run_hook_body({"agent_payload_s3_uri": "s3://b/k"})) - - assert r.status_code == 500 - assert r.json()["code"] == "MICROVM_RUN_PAYLOAD_UNREADABLE" - assert seam_guard["violations"] == [] - out = capfd.readouterr().out - assert "[server/run-pre-config] /run hook payload fetch FAILED" in out - # The traceback is preserved on the stdout line (it is the only diagnostic - # the response body does not carry). - assert "Traceback" in out - - @pytest.mark.parametrize( - "config,expected_code", - [ - ({"ld_preload": "/tmp/evil.so"}, "MICROVM_RUN_PLATFORM_CONFIG_INVALID"), - ({"log_group_name": "lg"}, "MICROVM_RUN_PLATFORM_CONFIG_INCOMPLETE"), - ], - ) - def test_a_rejected_platform_config_touches_no_seam( - self, client, monkeypatch, env_guard, seam_guard, config, expected_code - ): - monkeypatch.setattr(server, "run_task", MagicMock()) - - r = client.post( - RUN_HOOK, - json=_run_hook_body({"agent_payload": self._payload(), "platform_config": config}), - ) - - assert r.status_code == 400 - assert r.json()["code"] == expected_code - # Nothing was installed, so nothing earned the right to an AWS call. - assert seam_guard["violations"] == [] - assert seam_guard["install_phase_done"] is False - - def test_the_accepted_line_correlates_task_and_microvm_ids( - self, client, monkeypatch, env_guard, capfd - ): - # The pre-install "received" line is stdout-only now, so the first line that - # reaches the task's log group has to join both ids by itself. - monkeypatch.setattr(server, "run_task", MagicMock()) - monkeypatch.setattr(server.task_state, "write_terminal", MagicMock()) - - client.post( - RUN_HOOK, - json=_run_hook_body( - {"agent_payload": self._payload(), "platform_config": _platform_config()}, - microvm_id="microvm-joined", - ), - ) - - out = capfd.readouterr().out - assert "/run hook accepted task_id='t-silent' microvm_id='microvm-joined'" in out - - class TestTerminateHookBodyTolerance: """``/terminate`` must answer 200 for ANY body — that is why it takes the raw request. diff --git a/cdk/src/constructs/ecs-agent-cluster.ts b/cdk/src/constructs/ecs-agent-cluster.ts index 8a0ba3799..48a98bcc9 100644 --- a/cdk/src/constructs/ecs-agent-cluster.ts +++ b/cdk/src/constructs/ecs-agent-cluster.ts @@ -38,6 +38,7 @@ import { resolveBedrockModelIds, } from './bedrock-models'; import { LinearIdentityVault } from './linear-identity-vault'; +import { grantWorkerBootstrap } from './payload-bootstrap-permissions'; import { buildAppId } from './solution-ua-aspect'; import { ToolGateway } from './tool-gateway'; @@ -58,14 +59,12 @@ export interface EcsAgentClusterProps { readonly taskSizing?: EcsTaskSizing; /** - * S3 bucket holding per-task ECS payloads. The orchestrator writes the - * payload (incl. the large hydrated_context, which can't fit in the 8 KB - * RunTask containerOverrides limit) here and passes only an - * `AGENT_PAYLOAD_S3_URI` pointer; the container fetches it on boot. The task - * role gets **read-only** on this bucket — the container runs untrusted repo - * code, so it must not be able to delete payloads (the trusted orchestrator - * owns write + delete). When omitted (isolated construct tests / deployments - * that still pass the payload inline), no grant or env var is added. + * S3 storage for deployment manifests, task payloads and private launch + * references. The v2 coordinator sends AGENT_PAYLOAD_REF, containing a + * single-object signed download URL. The task role can read only bootstrap/*; + * object reads elsewhere and bucket listing are explicitly denied. The + * coordinator owns writes and cleanup. Optional for isolated construct tests; + * production ECS launches require this bucket and a matching v2 image. */ readonly payloadBucket?: s3.IBucket; @@ -408,9 +407,8 @@ export class EcsAgentCluster extends Construct { LOG_GROUP_NAME: logGroup.logGroupName, GITHUB_TOKEN_SECRET_ARN: props.githubTokenSecret.secretArn, ...(props.memoryId && { MEMORY_ID: props.memoryId }), - // The payload bucket name so the orchestrator-issued AGENT_PAYLOAD_S3_URI - // can be fetched. (The orchestrator sets the URI per-task via container - // override; this is set here for parity with the runtime env.) + // Deployment metadata; the per-task AGENT_PAYLOAD_REF supplies the + // manifest URI and signed payload URL. IAM authenticates the manifest. ...(props.payloadBucket && { ECS_PAYLOAD_BUCKET: props.payloadBucket.bucketName }), // Artifact workflows (planning/analysis) deliver their document to // this bucket. The AgentCore runtime has ARTIFACTS_BUCKET_NAME; the ECS task @@ -557,13 +555,11 @@ export class EcsAgentCluster extends Construct { // agent assumes the SessionRole — stays on the task role). props.githubTokenSecret.grantRead(taskRole); - // Read-only on the ECS payload bucket so the container can fetch its payload - // (AGENT_PAYLOAD_S3_URI) at boot. READ only — the container runs untrusted - // repo code, so it must not be able to write or delete payloads (the trusted - // orchestrator owns write + delete). Stays on the task role (read once at - // startup, before the agent assumes any SessionRole). + // Only deployment manifests use worker credentials. The boot helper reads + // its exact task object through a signed URL and removes that capability + // from the environment before starting repository code. if (props.payloadBucket) { - props.payloadBucket.grantRead(taskRole); + grantWorkerBootstrap(props.payloadBucket, taskRole); } // Artifact workflows (planning/analysis) deliver their document to the @@ -701,7 +697,7 @@ export class EcsAgentCluster extends Construct { NagSuppressions.addResourceSuppressions(taskRole, [ { id: 'AwsSolutions-IAM5', - reason: 'DynamoDB index/* wildcards from CDK grantReadWriteData (UserConcurrencyTable, and task tables only when no SessionRole is wired); Secrets Manager wildcards from CDK grantRead (GitHub token) and the bgagent-linear-oauth-*/bgagent-jira-oauth-* prefix grant (ABCA-488 — per-workspace channel OAuth tokens are created by the CLI at setup, name unknown at synth, GetSecretValue only); CloudWatch Logs wildcards from CDK grantWrite; S3 object/* wildcard from CDK grantRead on the ECS payload bucket (read-only, scoped to that bucket — #502). Bedrock InvokeModel is scoped to explicit model/inference-profile ARNs (no wildcard resource). ec2:DescribeAvailabilityZones requires Resource:* (EC2 describe actions have no resource-level scoping) — read-only, no mutation/data access; needed so a CDK target repo\'s `cdk synth` build gate can resolve AZ context on a fresh clone (ECS-parity, no cdk.context.json cache in the container).', + reason: 'DynamoDB index/* wildcards from CDK grantReadWriteData (UserConcurrencyTable, and task tables only when no SessionRole is wired); Secrets Manager wildcards from CDK grantRead (GitHub token) and the bgagent-linear-oauth-*/bgagent-jira-oauth-* prefix grant (ABCA-488 — per-workspace channel OAuth tokens are created by the CLI at setup, name unknown at synth, GetSecretValue only); CloudWatch Logs wildcards from CDK grantWrite; Worker S3 GetObject is restricted to bootstrap/*; other object reads and payload-bucket listing are explicitly denied (#700). Bedrock InvokeModel is scoped to explicit model/inference-profile ARNs (no wildcard resource). ec2:DescribeAvailabilityZones requires Resource:* (EC2 describe actions have no resource-level scoping) — read-only, no mutation/data access; needed so a CDK target repo\'s `cdk synth` build gate can resolve AZ context on a fresh clone (ECS-parity, no cdk.context.json cache in the container).', }, { id: 'AwsSolutions-ECS2', diff --git a/cdk/src/constructs/ecs-payload-bucket.ts b/cdk/src/constructs/ecs-payload-bucket.ts index 87dc47553..4c1b07402 100644 --- a/cdk/src/constructs/ecs-payload-bucket.ts +++ b/cdk/src/constructs/ecs-payload-bucket.ts @@ -55,24 +55,17 @@ export interface EcsPayloadBucketProps { } /** - * S3 bucket for ECS task payloads (#502). + * Storage for ECS v2 bootstrap manifests, task payloads and private references. * - * The ECS compute strategy cannot pass the orchestrator payload (repo URL, - * prompt, and the large ``hydrated_context``) inline: a Fargate ``RunTask`` - * caps the entire ``containerOverrides`` blob at 8192 bytes, and the hydrated - * context routinely exceeds that, so the call is rejected with - * ``InvalidParameterException``. (AgentCore is unaffected — it passes the - * payload in the ``InvokeAgentRuntime`` request body, which has no comparable - * limit.) Instead, the orchestrator writes the payload to - * ``s3:////payload.json`` and passes only a small - * ``AGENT_PAYLOAD_S3_URI`` pointer in the override; the container fetches and - * parses it on boot. + * RunTask caps the entire overrides object at 8192 bytes. The coordinator + * writes task instructions to /payload.json and passes AGENT_PAYLOAD_REF, + * containing an authenticated-manifest URI and a signed one-object URL. + * EcsAgentCluster grants the worker only bootstrap/* reads and explicitly denies + * other object reads/listing. The coordinator owns writes, signing and cleanup. * - * Dedicated (not co-tenant with attachments/traces) so the boundary is - * structural: the ECS task role gets S3 **read** here and nowhere else, the - * attachments feature can never collide with payload keys, and the tight - * 1-day TTL is whole-bucket rather than a prefix-scoped rule grafted onto a - * shared bucket. + * A dedicated bucket separates boot data from attachments/traces and gives it + * a one-day lifecycle backstop. Finalize deletes payload.json and launch.json; + * shared deployment manifests expire through the lifecycle rule. * * Security / hygiene (parity with TraceArtifactsBucket): * - ``blockPublicAccess: BLOCK_ALL`` + ``enforceSSL: true`` — no public read, diff --git a/cdk/src/constructs/lambda-microvm-compute.ts b/cdk/src/constructs/lambda-microvm-compute.ts index ea5e0d2ba..c2d2d016f 100644 --- a/cdk/src/constructs/lambda-microvm-compute.ts +++ b/cdk/src/constructs/lambda-microvm-compute.ts @@ -41,18 +41,17 @@ import { Construct } from 'constructs'; import { AgentMemory } from './agent-memory'; import { AgentSessionRole } from './agent-session-role'; import { inferenceProfileId, resolveBedrockGeoRegion, resolveBedrockModelIds } from './bedrock-models'; +import { grantWorkerBootstrap } from './payload-bootstrap-permissions'; import sharedConstants from '../../../contracts/constants.json'; import { LAMBDA_MICROVM_SUPPORTED_REGIONS, isLambdaMicrovmRegionSupported } from '../handlers/shared/microvm-regions'; /** * Lifecycle expiry for MicroVM `/run` hook payloads, in days. * - * Mirrors {@link ECS_PAYLOAD_TTL_DAYS} in shape but NOT in role: on ECS the - * orchestrator deletes the payload at finalize and the rule is only a crash - * backstop, whereas the MicroVM strategy never deletes (ADR-021 sub-decision 3 - * / `microvmPayloadKey`) — so on this backend the lifecycle rule is the ONLY - * reaper. Payloads carry the hydrated prompt context, so the TTL stays as tight - * as the read-once-at-`/run` access pattern allows. + * Mirrors {@link ECS_PAYLOAD_TTL_DAYS}. Finalization deletes payload.json and + * the private launch.json; shared manifests expire through lifecycle cleanup. + * Lifecycle expiry also removes task objects when finalization fails. S3 processes expiry asynchronously, not exactly 24 hours after + * upload. Payloads carry hydrated prompt context and are read once at `/run`. */ export const MICROVM_PAYLOAD_TTL_DAYS = 1; @@ -660,15 +659,15 @@ export interface LambdaMicrovmComputeProps extends LambdaMicrovmImageInputs { * `apt-get`, which is plain HTTP; a 443-only build path fails every * snapshot build (see {@link HTTP_PORT}). Runtime egress stays 443-only. * 2. **Artifact bucket** for the zip + Dockerfile the service builds the - * snapshot from, and a **payload bucket** for `/run` payloads that exceed - * the 4 KB `runHookPayload` cap (which is nearly all of them). + * snapshot from, and a **payload bucket** for deployment manifests, task instructions and private + * launch references. Every task uses the authenticated v2 transport. * 3. **Build role** — assumed by Lambda during image creation: `s3:GetObject` * on the artifact object and CloudWatch Logs writes. Without it Lambda * cannot emit build logs, which makes a failed snapshot build undebuggable. * 4. **Execution role** — assumed by the running MicroVM: CloudWatch Logs (both * the service's own `/aws/lambda-microvms/*` namespace and the platform - * APPLICATION_LOGS group whose name `platform_config` delivers), read-only on - * the payload bucket, the P2 runtime-parity grants (GitHub PAT + + * APPLICATION_LOGS group whose name `platform_config` delivers), read access only to + * the payload bucket's bootstrap manifests, the P2 runtime-parity grants (GitHub PAT + * channel-OAuth secret reads, scoped Bedrock invocation, AgentCore Memory, * `ec2:DescribeAvailabilityZones` for a CDK repo's synth gate), and — when a * SessionRole is wired — admission to the per-task SessionRole, which is the @@ -741,7 +740,7 @@ export class LambdaMicrovmCompute extends Construct { /** Key of the artifact object inside {@link artifactBucket}. */ public readonly artifactObjectKey: string; - /** S3 bucket holding oversized `/run` payloads (S3-pointer delivery). */ + /** S3 bucket holding bootstrap manifests, task payloads and private launch references. */ public readonly payloadBucket: s3.Bucket; /** Role Lambda assumes while building the snapshot image. */ @@ -1098,7 +1097,7 @@ export class LambdaMicrovmCompute extends Construct { assumedBy: microvmAssumedBy, description: 'ABCA Lambda MicroVMs execution role: assumed by the running MicroVM and its runtime ' - + 'lifecycle hooks; writes logs and reads out-of-band /run payloads.', + + 'lifecycle hooks; writes logs and reads deployment bootstrap manifests.', }); grantTagSession(this.executionRole, microvmAssumedBy); // Execution role: NO `logs:CreateLogGroup`. It runs untrusted repo code and @@ -1117,12 +1116,10 @@ export class LambdaMicrovmCompute extends Construct { // See `applicationLogGroup` for the denial this fixes. props.applicationLogGroup?.grantWrite(this.executionRole); - // READ-ONLY on the payload bucket (ADR-021: "The MicroVM execution role - // shall hold read-only access to the payload bucket, scoped to that - // bucket"). Read-only is not a nicety: the MicroVM runs untrusted repo - // code, so it must not be able to clobber another task's payload. Write + - // lifecycle stay with the trusted orchestrator. - this.payloadBucket.grantRead(this.executionRole); + // Authenticate only this deployment's manifests. Payload and launch reads + // using worker credentials are explicitly denied; one-object signed URLs + // carry the coordinator's authorization instead. + grantWorkerBootstrap(this.payloadBucket, this.executionRole); // Tenant-data access is delegated to the per-task SessionRole, exactly as // EcsAgentCluster does for the Fargate task role. NOTE the asymmetry with @@ -1408,8 +1405,8 @@ export class LambdaMicrovmCompute extends Construct { id: 'AwsSolutions-S1', reason: 'Artifact bucket holds a single build input (the agent zip+Dockerfile) read only by ' + 'the Lambda MicroVMs build role; the payload bucket holds ephemeral per-task /run payloads ' - + `with a ${MICROVM_PAYLOAD_TTL_DAYS}-day TTL, written only by the orchestrator (grantPut) and ` - + 'read only by the MicroVM execution role, both scoped to the bucket. Object-level access ' + + `with a ${MICROVM_PAYLOAD_TTL_DAYS}-day TTL, written only by the orchestrator and ` + + 'read through single-object signed URLs; the worker reads only bootstrap manifests. Object-level access ' + 'logging (a second log bucket + CloudTrail data events) is not justified for a single ' + 'build input or for transient boot payloads.', }, @@ -1420,8 +1417,8 @@ export class LambdaMicrovmCompute extends Construct { id: 'AwsSolutions-IAM5', reason: 'CloudWatch Logs wildcard is the service-owned ' + `${MICROVM_LOG_GROUP_PREFIX}/* namespace (log stream names are minted per MicroVM, so no ` - + 'synth-time ARN exists); S3 object/* wildcard comes from CDK grantRead on the dedicated ' - + 'payload bucket (read-only, scoped to that bucket — ADR-021 sub-decision 3). The build ' + + 'synth-time ARN exists); worker S3 GetObject is limited to bootstrap/* in its payload bucket, ' + + 'with explicit denial outside that prefix and for bucket listing. The build ' + 'role\'s s3:GetObject is scoped to a single object key, not a wildcard. On the execution ' + 'role (ADR-021 P2 runtime parity, mirroring the ECS task role): the second Logs grant is ' + 'CDK grantWrite (CreateLogStream + PutLogEvents only) on the SINGLE platform ' diff --git a/cdk/src/constructs/payload-bootstrap-permissions.ts b/cdk/src/constructs/payload-bootstrap-permissions.ts new file mode 100644 index 000000000..c6f215c0e --- /dev/null +++ b/cdk/src/constructs/payload-bootstrap-permissions.ts @@ -0,0 +1,67 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import * as iam from 'aws-cdk-lib/aws-iam'; +import * as s3 from 'aws-cdk-lib/aws-s3'; +import constants from '../../../contracts/constants.json'; + +/** Authenticate deployment settings with IAM; task payloads require a one-object capability. */ +export function grantWorkerBootstrap(bucket: s3.IBucket, worker: iam.IGrantable): void { + const manifests = bucket.arnForObjects(`${constants.payload_bootstrap.manifest_prefix}*`); + worker.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({ + actions: ['s3:GetObject'], + resources: [manifests], + })); + // An Allow alone is not an authentication boundary: another bucket could + // publicly grant access to an attacker's fake deployment manifest. + worker.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({ + effect: iam.Effect.DENY, + actions: ['s3:GetObject*'], + notResources: [manifests], + })); + worker.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({ + effect: iam.Effect.DENY, + actions: ['s3:List*'], + resources: [bucket.bucketArn], + })); +} + +export function grantCoordinatorPayloads(bucket: s3.IBucket, coordinator: iam.IGrantable): void { + // S3 returns AccessDenied rather than NoSuchKey for an absent launch record + // without ListBucket. Only the trusted coordinator needs this permission. + coordinator.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({ + actions: ['s3:ListBucket'], + resources: [bucket.bucketArn], + })); + const taskObjects = [ + bucket.arnForObjects('*/payload.json'), + bucket.arnForObjects(`*/${constants.payload_bootstrap.launch_filename}`), + ]; + coordinator.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({ + actions: ['s3:PutObject'], + resources: [ + ...taskObjects, + bucket.arnForObjects(`${constants.payload_bootstrap.manifest_prefix}*`), + ], + })); + coordinator.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({ + actions: ['s3:GetObject', 's3:DeleteObject'], + resources: taskObjects, + })); +} diff --git a/cdk/src/constructs/task-orchestrator.ts b/cdk/src/constructs/task-orchestrator.ts index ddd429ce2..9a1de83b7 100644 --- a/cdk/src/constructs/task-orchestrator.ts +++ b/cdk/src/constructs/task-orchestrator.ts @@ -51,6 +51,8 @@ const ORCHESTRATOR_TIMEOUT_SECONDS = 60; /** Orchestrator Lambda memory (MB). */ const ORCHESTRATOR_MEMORY_MB = 1024; +import { grantCoordinatorPayloads } from './payload-bootstrap-permissions'; + /** * Properties for TaskOrchestrator construct. */ @@ -180,12 +182,11 @@ export interface TaskOrchestratorProps { }; /** - * S3 bucket for per-task ECS payloads. When provided (alongside - * ``ecsConfig``), the orchestrator writes the payload here and passes only an - * ``AGENT_PAYLOAD_S3_URI`` pointer in the RunTask override (the full payload - * exceeds the 8 KB containerOverrides limit), then deletes the object in the - * finalize step. The orchestrator gets write + delete; the ECS task role gets - * read-only (granted on the bucket by ``EcsAgentCluster``). + * S3 storage for ECS v2 bootstrap manifests, task payloads and private launch + * references. The coordinator publishes/signs/replays the reference delivered + * in AGENT_PAYLOAD_REF, then deletes both task objects at finalization. + * EcsAgentCluster separately grants worker bootstrap-only reads and denies + * other object reads and payload-bucket listing. */ readonly ecsPayloadBucket?: s3.IBucket; @@ -438,7 +439,6 @@ export class TaskOrchestrator extends Construct { '@aws-sdk/client-ecs', '@aws-sdk/client-lambda', '@aws-sdk/client-bedrock-runtime', - '@aws-sdk/client-s3', '@aws-sdk/client-secrets-manager', '@aws-sdk/lib-dynamodb', '@aws-sdk/util-dynamodb', @@ -556,24 +556,10 @@ export class TaskOrchestrator extends Construct { props.attachmentsBucket.grantReadWrite(this.fn); } - // ECS payload bucket — the orchestrator writes the payload before - // RunTask and deletes it at finalize. Write + delete only (it never reads - // its own payload back; the ECS container is the reader, with its own - // read-only grant from EcsAgentCluster). - if (props.ecsPayloadBucket) { - props.ecsPayloadBucket.grantPut(this.fn); - props.ecsPayloadBucket.grantDelete(this.fn); - } - - // ADR-021: MicroVM payload bucket. WRITE only — the strategy uploads an - // oversized /run payload and never reads it back (the MicroVM execution - // role is the reader, with its own read-only grant), and it never deletes - // (the bucket's lifecycle rule reaps). No grantDelete, deliberately: the ECS - // path has one because the orchestrator deletes at finalize; this one does - // not, so the grant would be dead permission. - if (props.microvmConfig) { - props.microvmConfig.payloadBucket.grantPut(this.fn); - } + // Publish manifests/payloads, sign one-object reads and persist private + // launch references for replay. Workers cannot read the launch records. + if (props.ecsPayloadBucket) grantCoordinatorPayloads(props.ecsPayloadBucket, this.fn); + if (props.microvmConfig) grantCoordinatorPayloads(props.microvmConfig.payloadBucket, this.fn); // Durable execution managed policy this.fn.role!.addManagedPolicy( @@ -844,7 +830,7 @@ export class TaskOrchestrator extends Construct { }, { id: 'AwsSolutions-IAM5', - reason: 'DynamoDB index/* wildcards generated by CDK grantReadWriteData; AgentCore runtime/* required for sub-resource invocation; Secrets Manager wildcards generated by CDK grantRead; AgentCore Memory wildcards generated by CDK grantRead/grantWrite; ECS RunTask/DescribeTasks/StopTask conditioned on cluster ARN; iam:PassRole scoped to ECS task/execution roles and conditioned on ecs-tasks.amazonaws.com; S3 object/* wildcard from CDK grantPut on the dedicated MicroVM payload bucket; MicroVM lifecycle actions (RunMicrovm/GetMicrovm/TerminateMicrovm) are scoped to the single platform MicroVM image ARN plus a :* version-suffix sibling (every one of them authorizes against the image resource, not the per-session instance; no account-wide wildcard is used); lambda:PassNetworkConnector requires Resource:* because the action supports no resource-level permissions and the AWS-managed connectors live outside this account; iam:PassRole is scoped to the MicroVM execution role and conditioned on lambda.amazonaws.com; Agent Registry read scoped to the wired registry ARN, with a record/* suffix wildcard because record ids are server-assigned and unknown at synth (#246)', + reason: 'DynamoDB index/* wildcards generated by CDK grantReadWriteData; AgentCore runtime/* required for sub-resource invocation; Secrets Manager wildcards generated by CDK grantRead; AgentCore Memory wildcards generated by CDK grantRead/grantWrite; ECS RunTask/DescribeTasks/StopTask conditioned on cluster ARN; iam:PassRole scoped to ECS task/execution roles and conditioned on ecs-tasks.amazonaws.com; S3 writes restricted to bootstrap manifests and task payload/launch objects; GetObject and DeleteObject restricted to */payload.json and */launch.json for signing, replay and cleanup; ListBucket is scoped to each payload bucket so absent launch records return NoSuchKey; MicroVM lifecycle actions (RunMicrovm/GetMicrovm/TerminateMicrovm) are scoped to the single platform MicroVM image ARN plus a :* version-suffix sibling (every one of them authorizes against the image resource, not the per-session instance; no account-wide wildcard is used); lambda:PassNetworkConnector requires Resource:* because the action supports no resource-level permissions and the AWS-managed connectors live outside this account; iam:PassRole is scoped to the MicroVM execution role and conditioned on lambda.amazonaws.com; Agent Registry read scoped to the wired registry ARN, with a record/* suffix wildcard because record ids are server-assigned and unknown at synth (#246)', }, ], true); } diff --git a/cdk/src/handlers/shared/payload-bootstrap.ts b/cdk/src/handlers/shared/payload-bootstrap.ts new file mode 100644 index 000000000..8134d3835 --- /dev/null +++ b/cdk/src/handlers/shared/payload-bootstrap.ts @@ -0,0 +1,183 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { createHash } from 'node:crypto'; +import { DeleteObjectCommand, GetObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3'; +import { getSignedUrl } from '@aws-sdk/s3-request-presigner'; +import { logger } from './logger'; +import { makeClient } from './ua'; +import constants from '../../../../contracts/constants.json'; + +export const PAYLOAD_BOOTSTRAP = constants.payload_bootstrap; +type Backend = 'ecs' | 'lambda-microvm'; + +export interface PayloadReference { + version: number; + task_id: string; + bootstrap_s3_uri: string; + payload_url: string; + expires_at: number; +} + +interface LaunchRecord { + fingerprint: string; + reference: PayloadReference; +} + +let client: S3Client | undefined; +function s3(): S3Client { + return client ??= makeClient(S3Client); +} + +function canonical(value: unknown): string { + return JSON.stringify(value, (_key, item: unknown) => + item && typeof item === 'object' && !Array.isArray(item) + ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) + : item); +} + +function sha256(value: string): string { + return createHash('sha256').update(value).digest('hex'); +} + +/** Never let SDK errors echo bearer URLs into task records or logs. */ +export function redactPayloadUrls(message: string): string { + return message.replace(/https?:\/\/[^\s"'<>\\]+/gi, url => + /X-Amz-/i.test(url) ? '[redacted payload URL]' : url); +} + +async function readObject(bucket: string, key: string): Promise { + try { + const response = await s3().send(new GetObjectCommand({ Bucket: bucket, Key: key })); + if (!response.Body) throw new Error('PAYLOAD_BOOTSTRAP_UNREADABLE: empty object response'); + return await response.Body.transformToString(); + } catch (error) { + if ((error as { name?: string }).name === 'NoSuchKey') return undefined; + throw error; + } +} + +/** Conditional creation, including recovery after a committed write loses its reply. */ +async function createOnce(bucket: string, key: string, body: string): Promise { + try { + await s3().send(new PutObjectCommand({ + Bucket: bucket, Key: key, Body: body, ContentType: 'application/json', IfNoneMatch: '*', + })); + return body; + } catch (error) { + const saved = await readObject(bucket, key); + if (saved !== undefined) return saved; + throw error; + } +} + +/** + * Save a single-object capability outside the agent-readable task table. + * Replays read the same launch.json; re-signing would change Run's request + * while reusing its clientToken. The worker can read only bootstrap/* using + * its own credentials, never payload.json or launch.json. + */ +export async function preparePayloadReference(input: { + bucket: string; + taskId: string; + backend: Backend; + payload: Record; + platformConfig?: Record; +}): Promise { + const { bucket, taskId, backend, payload } = input; + if (!/^[A-Za-z0-9_-]{1,128}$/.test(taskId) || payload.task_id !== taskId) { + throw new Error('PAYLOAD_BOOTSTRAP_INVALID: task identity does not match the payload'); + } + const manifest = canonical({ + version: PAYLOAD_BOOTSTRAP.version, backend, platform_config: input.platformConfig ?? {}, + }); + const manifestKey = `${PAYLOAD_BOOTSTRAP.manifest_prefix}${sha256(manifest)}.json`; + const payloadBody = canonical({ + version: PAYLOAD_BOOTSTRAP.version, + task_id: taskId, + agent_payload: payload, + platform_config: input.platformConfig ?? {}, + }); + if (Buffer.byteLength(manifest) > PAYLOAD_BOOTSTRAP.max_manifest_bytes + || Buffer.byteLength(payloadBody) > PAYLOAD_BOOTSTRAP.max_payload_bytes) { + throw new Error('PAYLOAD_BOOTSTRAP_TOO_LARGE: bootstrap manifest or task payload exceeds its byte limit'); + } + const fingerprint = sha256(canonical({ bucket, backend, manifest, payloadBody })); + const launchKey = `${taskId}/${PAYLOAD_BOOTSTRAP.launch_filename}`; + const accept = (saved: string): PayloadReference => { + const record = JSON.parse(saved) as LaunchRecord; + if (record.fingerprint !== fingerprint || record.reference?.task_id !== taskId) { + throw new Error('PAYLOAD_BOOTSTRAP_CONFLICT: task already has different launch instructions'); + } + if (record.reference.expires_at <= Date.now()) { + throw new Error('PAYLOAD_BOOTSTRAP_EXPIRED: inspect the existing launch; do not start a replacement task'); + } + return record.reference; + }; + + // Refresh only identical, public deployment settings so bucket lifecycle + // expiry cannot reap an old manifest just as a new task starts using it. + await s3().send(new PutObjectCommand({ + Bucket: bucket, Key: manifestKey, Body: manifest, ContentType: 'application/json', + })); + const existing = await readObject(bucket, launchKey); + if (existing !== undefined) return accept(existing); + + const payloadKey = `${taskId}/payload.json`; + const savedPayload = await createOnce(bucket, payloadKey, payloadBody); + if (savedPayload !== payloadBody) { + throw new Error('PAYLOAD_BOOTSTRAP_CONFLICT: task already has different stored instructions'); + } + const now = Date.now(); + const credentials = await s3().config.credentials(); + const lifetime = Math.min( + PAYLOAD_BOOTSTRAP.url_ttl_seconds, + credentials.expiration + ? Math.floor((credentials.expiration.getTime() - now) / 1000) + : PAYLOAD_BOOTSTRAP.url_ttl_seconds, + ); + if (lifetime < PAYLOAD_BOOTSTRAP.minimum_url_lifetime_seconds) { + throw new Error('PAYLOAD_BOOTSTRAP_CREDENTIALS_EXPIRING: refresh coordinator credentials before launch'); + } + const url = await getSignedUrl(s3(), new GetObjectCommand({ + Bucket: bucket, Key: payloadKey, + }), { expiresIn: lifetime }); + const reference: PayloadReference = { + version: PAYLOAD_BOOTSTRAP.version, + task_id: taskId, + bootstrap_s3_uri: `s3://${bucket}/${manifestKey}`, + payload_url: url, + expires_at: now + lifetime * 1000, + }; + const record = canonical({ fingerprint, reference }); + return accept(await createOnce(bucket, launchKey, record)); +} + +/** Delete both task instructions and their saved capability; shared manifests expire by lifecycle. */ +export async function deletePayloadReference(bucket: string, taskId: string): Promise { + for (const filename of ['payload.json', PAYLOAD_BOOTSTRAP.launch_filename]) { + try { + await s3().send(new DeleteObjectCommand({ Bucket: bucket, Key: `${taskId}/${filename}` })); + } catch (error) { + logger.warn('Payload bootstrap cleanup failed (non-fatal)', { + task_id: taskId, filename, error: (error as { name?: string }).name ?? 'UnknownError', + }); + } + } +} diff --git a/cdk/src/handlers/shared/strategies/ecs-strategy.ts b/cdk/src/handlers/shared/strategies/ecs-strategy.ts index 75853ee39..0718f8b34 100644 --- a/cdk/src/handlers/shared/strategies/ecs-strategy.ts +++ b/cdk/src/handlers/shared/strategies/ecs-strategy.ts @@ -18,9 +18,9 @@ */ import { ECSClient, RunTaskCommand, DescribeTasksCommand, StopTaskCommand } from '@aws-sdk/client-ecs'; -import { S3Client, PutObjectCommand, DeleteObjectCommand } from '@aws-sdk/client-s3'; import type { ComputeStrategy, SessionHandle, SessionStatus } from '../compute-strategy'; import { logger } from '../logger'; +import { deletePayloadReference, preparePayloadReference, redactPayloadUrls } from '../payload-bootstrap'; import type { BlueprintConfig } from '../repo-config'; import { makeClient } from '../ua'; import { DEFAULT_MAX_TURNS } from '../validation'; @@ -33,14 +33,6 @@ function getClient(): ECSClient { return sharedClient; } -let sharedS3Client: S3Client | undefined; -function getS3Client(): S3Client { - if (!sharedS3Client) { - sharedS3Client = makeClient(S3Client); - } - return sharedS3Client; -} - const ECS_CLUSTER_ARN = process.env.ECS_CLUSTER_ARN; const ECS_TASK_DEFINITION_ARN = process.env.ECS_TASK_DEFINITION_ARN; /** @@ -79,45 +71,23 @@ export function toTaskDefinitionFamily(ref: string): string { const ECS_SECURITY_GROUP = process.env.ECS_SECURITY_GROUP; const ECS_CONTAINER_NAME = process.env.ECS_CONTAINER_NAME ?? 'AgentContainer'; const ECS_PAYLOAD_BUCKET = process.env.ECS_PAYLOAD_BUCKET; +const ECS_OVERRIDES_LIMIT_BYTES = 8192; -/** - * Inline-payload size (bytes) above which we warn that RunTask will likely - * reject the call when no payload bucket is configured. ECS caps the TOTAL - * containerOverrides blob at 8192 bytes; the other env vars + command consume - * some of that, so 6 KB of payload is the practical danger line. - */ -const INLINE_PAYLOAD_WARN_BYTES = 6144; - -/** - * S3 object key for a task's ECS payload. One object per task under its own - * task-id prefix; deleted by the orchestrator at finalize (see - * ``deleteEcsPayload``), with the bucket's 1-day lifecycle rule as a backstop. - */ -export function ecsPayloadKey(taskId: string): string { - return `${taskId}/payload.json`; +function safeLaunchError(error: unknown): Error { + const safe = new Error(redactPayloadUrls(error instanceof Error ? error.message : String(error))); + safe.name = error instanceof Error ? error.name : 'Error'; + return safe; } /** - * Delete a task's ECS payload object. Best-effort: a failed delete must never + * Delete a task's ECS payload and private launch reference. A failed delete must never * fail the task — the bucket's 1-day lifecycle rule reaps it regardless. Called * from the orchestrator's ``finalize`` step once the task is terminal. No-ops * when the payload bucket isn't configured (AgentCore-only deployments). */ export async function deleteEcsPayload(taskId: string): Promise { if (!ECS_PAYLOAD_BUCKET) return; - try { - await getS3Client().send(new DeleteObjectCommand({ - Bucket: ECS_PAYLOAD_BUCKET, - Key: ecsPayloadKey(taskId), - })); - logger.info('Deleted ECS payload object', { task_id: taskId }); - } catch (err) { - // Non-fatal — the lifecycle rule is the backstop. - logger.warn('Failed to delete ECS payload object (non-fatal)', { - task_id: taskId, - error: err instanceof Error ? err.message : String(err), - }); - } + await deletePayloadReference(ECS_PAYLOAD_BUCKET, taskId); } export class EcsComputeStrategy implements ComputeStrategy { @@ -170,43 +140,18 @@ export class EcsComputeStrategy implements ComputeStrategy { // that request. We override the container command to invoke run_task() // directly with the full orchestrator payload (including hydrated_context). // This avoids the server entirely and runs the agent in batch mode. - const payloadJson = JSON.stringify(payload); - - // The payload (especially hydrated_context) routinely exceeds the 8192-byte - // cap that ECS RunTask enforces on the TOTAL containerOverrides blob, which - // rejected the call with InvalidParameterException. Write the payload to S3 - // and pass only a small pointer (AGENT_PAYLOAD_S3_URI); the container fetches - // it on boot. The inline AGENT_PAYLOAD remains as a fallback for small - // payloads / deployments without a payload bucket configured. - let payloadS3Uri: string | undefined; - if (ECS_PAYLOAD_BUCKET) { - const key = ecsPayloadKey(taskId); - await getS3Client().send(new PutObjectCommand({ - Bucket: ECS_PAYLOAD_BUCKET, - Key: key, - Body: payloadJson, - ContentType: 'application/json', - })); - payloadS3Uri = `s3://${ECS_PAYLOAD_BUCKET}/${key}`; - logger.info('Wrote ECS payload to S3', { - task_id: taskId, - bytes: payloadJson.length, - uri: payloadS3Uri, - }); - } else if (payloadJson.length > INLINE_PAYLOAD_WARN_BYTES) { - // No bucket configured AND the payload is large enough that the inline - // path will almost certainly blow the 8192-byte overrides cap. Surface a - // clear cause rather than a raw InvalidParameterException from RunTask. - logger.warn('ECS payload is large but ECS_PAYLOAD_BUCKET is not set — RunTask may reject it (see #502)', { - task_id: taskId, - bytes: payloadJson.length, - }); + if (!ECS_PAYLOAD_BUCKET) { + throw new Error('PAYLOAD_BOOTSTRAP_INVALID: ECS_PAYLOAD_BUCKET is required; deploy matching infrastructure'); } + const reference = await preparePayloadReference({ + bucket: ECS_PAYLOAD_BUCKET, taskId, backend: 'ecs', payload, + }).catch((error: unknown) => { + throw safeLaunchError(error); + }); const containerEnv = [ { name: 'TASK_ID', value: taskId }, { name: 'REPO_URL', value: String(payload.repo_url ?? '') }, - ...(payload.prompt ? [{ name: 'TASK_DESCRIPTION', value: String(payload.prompt) }] : []), ...(payload.issue_number ? [{ name: 'ISSUE_NUMBER', value: String(payload.issue_number) }] : []), // Single source of truth with the hydrate path in `orchestrator.ts`, which // resolves the same default via `DEFAULT_MAX_TURNS`. A literal here would @@ -217,47 +162,34 @@ export class EcsComputeStrategy implements ComputeStrategy { ...(blueprintConfig.model_id ? [{ name: 'ANTHROPIC_MODEL', value: blueprintConfig.model_id }] : []), ...(blueprintConfig.system_prompt_overrides ? [{ name: 'SYSTEM_PROMPT_OVERRIDES', value: blueprintConfig.system_prompt_overrides }] : []), { name: 'CLAUDE_CODE_USE_BEDROCK', value: '1' }, - // Prefer the S3 pointer; fall back to the inline payload when no bucket is - // configured (keeps small-payload / AgentCore-only deployments working with - // no behavior change). - ...(payloadS3Uri - ? [{ name: 'AGENT_PAYLOAD_S3_URI', value: payloadS3Uri }] - : [{ name: 'AGENT_PAYLOAD', value: payloadJson }]), + { name: 'AGENT_PAYLOAD_REF', value: JSON.stringify(reference) }, ...(payload.github_token_secret_arn ? [{ name: 'GITHUB_TOKEN_SECRET_ARN', value: String(payload.github_token_secret_arn) }] : []), ...(payload.memory_id ? [{ name: 'MEMORY_ID', value: String(payload.memory_id) }] : []), ]; - // Override the container command to run a Python one-liner that: - // 1. Loads the payload — from S3 (AGENT_PAYLOAD_S3_URI) when set, else the - // inline AGENT_PAYLOAD env var (fallback). - // 2. Calls entrypoint.run_task_from_payload(p), which maps the WHOLE payload - // dict to run_task's signature (rename prompt→task_description / - // model_id→anthropic_model, filter to accepted params, coerce str/int). - // This replaces an older hand-listed kwarg subset that silently dropped - // fields such as channel_source/channel_metadata (which meant no - // Linear/Jira reactions or channel MCP on ECS), build_command, - // cedar_policies, base_branch/merge_branches, attachments, trace, user_id, - // etc. Single source of truth in the agent, unit-tested (see - // test_run_task_from_payload). - // 3. Exits with code 0 on success, 1 on failure. - // This bypasses the uvicorn server entirely — no HTTP, no OTEL noise. + // Consume the one-object capability before importing/running the pipeline. + // The helper removes it from os.environ so repo subprocesses do not inherit it. const bootCommand = [ 'python', '-c', - 'import json, os, sys; ' - + 'sys.path.insert(0, "/app/src"); ' + 'import sys; sys.path.insert(0, "/app/src"); ' + + 'from payload_bootstrap import load_ecs_payload; p = load_ecs_payload(); ' + 'from entrypoint import run_task_from_payload; ' - + '_uri = os.environ.get("AGENT_PAYLOAD_S3_URI"); ' - + 'p = (' - + 'json.loads(__import__("boto3").client("s3").get_object(' - + 'Bucket=_uri.split("/",3)[2], Key=_uri.split("/",3)[3])["Body"].read()) ' - + 'if _uri else json.loads(os.environ["AGENT_PAYLOAD"])' - + '); ' + 'r = run_task_from_payload(p); ' + 'sys.exit(0 if r.get("status")=="success" else 1)', ]; + const overrides = { + containerOverrides: [{ + name: ECS_CONTAINER_NAME, + environment: containerEnv, + command: bootCommand, + }], + }; + if (Buffer.byteLength(JSON.stringify(overrides), 'utf8') > ECS_OVERRIDES_LIMIT_BYTES) { + throw new Error('PAYLOAD_BOOTSTRAP_TOO_LARGE: ECS container overrides exceed 8192 bytes'); + } const command = new RunTaskCommand({ cluster: ECS_CLUSTER_ARN, taskDefinition, @@ -278,21 +210,17 @@ export class EcsComputeStrategy implements ComputeStrategy { assignPublicIp: 'DISABLED', }, }, - overrides: { - containerOverrides: [{ - name: ECS_CONTAINER_NAME, - environment: containerEnv, - command: bootCommand, - }], - }, + overrides, }); - const result = await getClient().send(command); + const result = await getClient().send(command).catch((error: unknown) => { + throw safeLaunchError(error); + }); const ecsTask = result.tasks?.[0]; if (!ecsTask?.taskArn) { const failures = result.failures?.map(f => `${f.arn}: ${f.reason}`).join('; ') ?? 'unknown'; - throw new Error(`ECS RunTask returned no task: ${failures}`); + throw new Error(`ECS RunTask returned no task: ${redactPayloadUrls(failures)}`); } logger.info('ECS Fargate task started', { diff --git a/cdk/src/handlers/shared/strategies/lambda-microvm-strategy.ts b/cdk/src/handlers/shared/strategies/lambda-microvm-strategy.ts index 6e3e8a0ef..963b04caf 100644 --- a/cdk/src/handlers/shared/strategies/lambda-microvm-strategy.ts +++ b/cdk/src/handlers/shared/strategies/lambda-microvm-strategy.ts @@ -24,13 +24,13 @@ import { RunMicrovmCommand, TerminateMicrovmCommand, } from '@aws-sdk/client-lambda-microvms'; -import { DeleteObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3'; // Cross-language contract (S9): `microvm_platform_config` is read by BOTH this // producer and `agent/src/server.py`'s `/run` consumer. Imported (not copied) so // `tsc` fails on a renamed field — see `contracts/constants.md`. import sharedConstants from '../../../../../contracts/constants.json'; import type { ComputeStrategy, SessionHandle, SessionStatus } from '../compute-strategy'; import { logger } from '../logger'; +import { deletePayloadReference, preparePayloadReference, redactPayloadUrls } from '../payload-bootstrap'; import type { BlueprintConfig } from '../repo-config'; import { makeClient } from '../ua'; @@ -42,14 +42,6 @@ function getClient(): LambdaMicrovmsClient { return sharedClient; } -let sharedS3Client: S3Client | undefined; -function getS3Client(): S3Client { - if (!sharedS3Client) { - sharedS3Client = makeClient(S3Client); - } - return sharedS3Client; -} - /** * Fully-qualified MicroVM image **ARN** passed as `imageIdentifier` on every * `RunMicrovm`. @@ -364,12 +356,16 @@ export const MICROVM_ERROR_MARKER = 'MicroVM'; * marker first, which is the order the classifier patterns document. */ function wrapMicrovmError(operation: string, err: unknown): Error { - const name = err instanceof Error ? err.name : undefined; - const message = err instanceof Error ? err.message : String(err); + // SDK errors and their nested causes can contain signed payload URLs, so both + // the message and the retained cause are redacted copies (#1002). + const name = err instanceof Error ? redactPayloadUrls(err.name) : undefined; + const message = redactPayloadUrls(err instanceof Error ? err.message : String(err)); const detail = name && name !== 'Error' && !message.includes(name) ? `${name}: ${message}` : message; - return new Error(`${MICROVM_ERROR_MARKER} ${operation} failed: ${detail}`, { cause: err }); + const safeCause = new Error(message); + safeCause.name = name ?? 'Error'; + return new Error(`${MICROVM_ERROR_MARKER} ${operation} failed: ${detail}`, { cause: safeCause }); } /** @@ -383,59 +379,12 @@ export function microvmPayloadKey(taskId: string): string { return `${taskId}/payload.json`; } -/** - * Delete a task's MicroVM ``/run`` payload object. Best-effort: a failed delete - * must never fail the task — the bucket's 1-day lifecycle rule reaps it - * regardless. Called from the orchestrator's ``finalize`` step once the task is - * terminal. No-ops when the payload bucket isn't configured. - * - * WHY this exists rather than leaning on the TTL alone (ECS parity, and a real - * exposure delta): the execution role's payload-bucket grant is - * ``grantRead`` on the WHOLE bucket — it cannot be per-task scoped, because the - * MicroVM has to read its own object before any tenant identity is installed. - * The key shape is ``/payload.json``, so any running MicroVM that knows - * (or guesses) another task's id can read that task's HYDRATED PROMPT — issue - * body, comment thread, repo context. The MicroVM also runs untrusted repo code. - * Relying only on ``MICROVM_PAYLOAD_TTL_DAYS = 1`` left that window open for up - * to ~24 h; deleting at finalize closes it to the task's own lifetime, which is - * exactly the posture ``deleteEcsPayload`` already gives the ECS backend. - * - * ISSUED UNCONDITIONALLY, including for a task whose payload went INLINE (under - * the {@link RUN_HOOK_PAYLOAD_LIMIT_BYTES} cap, so no object was ever written). - * That is on purpose: ``DeleteObject`` on a missing key succeeds, so the call is - * harmless and idempotent, whereas *deciding* to skip it would mean trusting a - * per-task record of the delivery mode — and if that record were ever wrong or - * absent, the skip would leave a real payload behind for the full TTL. Attempting - * always is the fail-safe direction. - * - * The consequence is that a successful call proves a delete was ISSUED, never that - * an object existed — S3 returns nothing that distinguishes the two on an - * unversioned bucket. The log line below says exactly that and no more; an earlier - * "Deleted MicroVM payload object" asserted a deletion that never happened on - * every inline task. +/** Remove task instructions and their saved download capability after finalization. + * Best-effort; bucket lifecycle reaps leftovers. Deployment manifests are shared. */ export async function deleteMicrovmPayload(taskId: string): Promise { if (!MICROVM_PAYLOAD_BUCKET) return; - const key = microvmPayloadKey(taskId); - try { - await getS3Client().send(new DeleteObjectCommand({ - Bucket: MICROVM_PAYLOAD_BUCKET, - Key: key, - })); - // "issued", not "deleted": see the docstring. An inline-delivered task has no - // object here and the call still succeeds. - logger.info('MicroVM payload delete issued', { - task_id: taskId, - bucket: MICROVM_PAYLOAD_BUCKET, - key, - }); - } catch (err) { - // Non-fatal — the lifecycle rule is the backstop. - logger.warn('Failed to delete MicroVM payload object (non-fatal)', { - task_id: taskId, - error: err instanceof Error ? err.message : String(err), - }); - } + await deletePayloadReference(MICROVM_PAYLOAD_BUCKET, taskId); } /** Split a comma-separated env-var list into trimmed, non-empty entries. */ @@ -557,83 +506,18 @@ export class LambdaMicrovmComputeStrategy implements ComputeStrategy { // inline branch is the exception. The MicroVM EXECUTION role holds the read // grant, exactly as the ECS task role does today. // - // Three keys, deliberately mirroring the ECS container env contract - // (AGENT_PAYLOAD / AGENT_PAYLOAD_S3_URI) so the agent's `/run` hook has one - // self-describing shape to branch on: - // { "agent_payload": {...}, "platform_config": {...} } — inline - // { "agent_payload_s3_uri": "…", "platform_config": {...} } — pointer - // - // `platform_config` (see MICROVM_PLATFORM_CONFIG_KEYS) rides in BOTH forms, - // and is ALSO merged into the S3 object on the pointer path: - // s3://…//payload.json = { ...agent_payload, "platform_config": {…} } - // The duplication is deliberate and cheap (a few hundred bytes). It is the - // agent's env-block substitute — nothing else delivers it, because the - // snapshot must not bake it in — so it must be reachable whether the agent - // reads it off the hook body before fetching S3 or out of the fetched object. + // Payload bootstrap v2 (#700, #1002): the hook body carries only a small, + // task-scoped launch reference. The worker reads the deployment manifest with + // IAM (no deployment identifiers live in the image snapshot) and downloads its + // own task payload through a short-lived signed one-object URL, so it cannot + // read other tasks' payloads. const platformConfig = buildMicrovmPlatformConfig(); - const inlineEnvelope = JSON.stringify({ agent_payload: payload, platform_config: platformConfig }); - // Measure the SERIALIZED envelope, not the bare payload: the envelope is - // what the service counts against the 4 KB cap, and `platform_config` is part - // of it — which is precisely why nearly everything lands on the S3 path. - // Byte length (not String.length) because a multi-byte prompt/diff makes - // chars an undercount. - const inlineBytes = Buffer.byteLength(inlineEnvelope, 'utf8'); - - let runHookPayload: string; - let payloadS3Uri: string | undefined; - // EXACT boundary: `<= limit` inlines, `> limit` uploads. The service accepts - // 4 096 bytes and rejects 4 097 (measured), so 4 096 must still go inline. - if (inlineBytes <= RUN_HOOK_PAYLOAD_LIMIT_BYTES) { - runHookPayload = inlineEnvelope; - } else { - const key = microvmPayloadKey(taskId); - const uri = `s3://${MICROVM_PAYLOAD_BUCKET}/${key}`; - const pointerEnvelope = JSON.stringify({ - agent_payload_s3_uri: uri, - platform_config: platformConfig, - }); - // The pointer envelope is the LAST RESORT — there is no smaller shape to - // fall back to — so check it BEFORE the upload (an upload followed by a - // throw would leave an orphan object for the lifecycle rule to reap) and - // name the one thing an operator can actually act on. Unreachable in - // practice: the pointer plus all thirteen identifiers is well under 4 KB. - const pointerBytes = Buffer.byteLength(pointerEnvelope, 'utf8'); - if (pointerBytes > RUN_HOOK_PAYLOAD_LIMIT_BYTES) { - throw new Error( - `The MicroVM /run pointer envelope is ${pointerBytes} bytes, over the service's ` - + `${RUN_HOOK_PAYLOAD_LIMIT_BYTES}-byte runHookPayload cap, with the payload already moved ` - + 'to S3. The remaining size is the S3 URI plus the platform_config identifiers, so a ' - + 'pathologically long table/bucket/ARN name is the only possible cause — shorten the ' - + 'stack name (physical resource names derive from it) and redeploy.', - ); - } - // The S3 object carries the payload with `platform_config` merged in at the - // top level, so an agent that fetches the object gets the config with it. - // Platform config wins on a key collision — the payload has no - // `platform_config` key today, and if one ever appeared the platform's - // value is the authoritative one. - const payloadJson = JSON.stringify({ ...payload, platform_config: platformConfig }); - try { - await getS3Client().send(new PutObjectCommand({ - Bucket: MICROVM_PAYLOAD_BUCKET, - Key: key, - Body: payloadJson, - ContentType: 'application/json', - })); - } catch (err) { - // Marked so the classifier attributes an upload failure to this backend - // rather than letting a bare S3 exception name fall through to UNKNOWN. - throw wrapMicrovmError('payload upload', err); - } - payloadS3Uri = uri; - runHookPayload = pointerEnvelope; - logger.info('Wrote MicroVM run-hook payload to S3', { - task_id: taskId, - bytes: Buffer.byteLength(payloadJson, 'utf8'), - inline_bytes: inlineBytes, - inline_limit_bytes: RUN_HOOK_PAYLOAD_LIMIT_BYTES, - uri: payloadS3Uri, - }); + const reference = await preparePayloadReference({ + bucket: MICROVM_PAYLOAD_BUCKET, taskId, backend: 'lambda-microvm', payload, platformConfig, + }).catch((error: unknown) => { throw wrapMicrovmError('payload bootstrap', error); }); + const runHookPayload = JSON.stringify(reference); + if (Buffer.byteLength(runHookPayload, 'utf8') > RUN_HOOK_PAYLOAD_LIMIT_BYTES) { + throw new Error('PAYLOAD_BOOTSTRAP_TOO_LARGE: launch reference exceeds the MicroVM hook limit'); } // Explicit ingress control (F7, live 2026-07-31): `RunMicrovm` does NOT @@ -729,8 +613,7 @@ export class LambdaMicrovmComputeStrategy implements ComputeStrategy { image_arn: result.imageArn, image_version: result.imageVersion ?? MICROVM_IMAGE_VERSION, maximum_duration_seconds: MICROVM_MAX_DURATION_SECONDS, - payload_delivery: payloadS3Uri ? 's3_pointer' : 'inline', - ...(payloadS3Uri && { payload_s3_uri: payloadS3Uri }), + payload_delivery: 'bootstrap_v2', // KEY NAMES only, never values: this is the one operator-visible record of // which optional platform identifiers a given session actually received, and // "the agent said ARTIFACTS_BUCKET_NAME is not configured" is otherwise a @@ -936,13 +819,13 @@ export class LambdaMicrovmComputeStrategy implements ComputeStrategy { microvm_id: microvmId, reason, error_type: errName, - error: err instanceof Error ? err.message : String(err), + error: redactPayloadUrls(err instanceof Error ? err.message : String(err)), }); } else { logger.warn('Failed to terminate MicroVM (best-effort)', { microvm_id: microvmId, reason, - error: err instanceof Error ? err.message : String(err), + error: redactPayloadUrls(err instanceof Error ? err.message : String(err)), }); } } diff --git a/cdk/src/stacks/agent.ts b/cdk/src/stacks/agent.ts index 01e7b3d6b..bb6951d0f 100644 --- a/cdk/src/stacks/agent.ts +++ b/cdk/src/stacks/agent.ts @@ -873,6 +873,15 @@ export class AgentStack extends Stack { reason: 'CDK-generated overflow policy on the Linear webhook processor role carries the kms:GenerateDataKey* that SNS Topic.grantPublish emits for the CMK-encrypted operational-alerts topic. Scoped to that single topic key; the wildcard only spans the GenerateDataKey/GenerateDataKeyWithoutPlaintext pair.', }, + { + // #1002: payload bootstrap v2's coordinator grants (manifest/payload/launch + // object writes, signed-read GetObject, scoped ListBucket) pushed the + // orchestrator role over the same limit, spilling statements whose + // wildcards the base policy already justifies. + pathFragment: '/TaskOrchestrator/OrchestratorFn/ServiceRole/OverflowPolicy', + reason: + 'CDK-generated overflow policy on the orchestrator role carries statements suppressed on its base policy: CDK-generated DynamoDB index/* and Secrets Manager wildcards, and the bgagent-linear-oauth-*/bgagent-jira-oauth-* prefix grant for per-workspace channel tokens created by the CLI at setup (names unknown at synth, GetSecretValue only). Payload object writes, reads and deletes are restricted to bootstrap manifests and per-task payload.json/launch.json keys.', + }, ]; const overflowSuppressionAspect = { visit(node: IConstruct) { @@ -981,10 +990,10 @@ export class AgentStack extends Stack { // includes ecs or the legacy `compute_type=ecs` context is used. Default // synthesis remains AgentCore-only. The backend list is resolved near the // top of this constructor so TaskApi can apply the same cancellation gates. - // Ephemeral bucket for ECS task payloads — the orchestrator writes the - // payload here (it exceeds the 8 KB RunTask containerOverrides limit) and - // passes only an S3 URI pointer; the container fetches it on boot, the - // orchestrator deletes it at finalize. Only synthesized under the ecs gate. + // ECS v2 bootstrap storage: deployment manifests, task instructions and + // private launch references. Workers read manifests with IAM and download + // their task through a signed one-object URL. Finalize deletes task objects; + // the one-day lifecycle reaps leftovers. Synthesized only under the ECS gate. const ecsPayloadBucket = ecsEnabled ? new EcsPayloadBucket(this, 'EcsPayloadBucket') : undefined; @@ -992,7 +1001,7 @@ export class AgentStack extends Stack { NagSuppressions.addResourceSuppressions(ecsPayloadBucket.bucket, [ { id: 'AwsSolutions-S1', - reason: 'Ephemeral per-task payloads with a 1-day TTL; writes confined to the orchestrator IAM role by grantPut, reads to the ECS task role by grantRead, both scoped to this bucket. Object deleted at finalize. Object-level audit intentionally omitted — CloudTrail data events / a log bucket are not justified for transient boot payloads.', + reason: 'Ephemeral bootstrap storage with a 1-day TTL. The coordinator writes manifests and task objects, signs task reads and deletes task objects at finalize. Workers read only bootstrap/* with IAM and use single-object signed URLs for payloads; other object reads and bucket listing are explicitly denied. Object-level audit intentionally omitted — CloudTrail data events / a log bucket are not justified for transient boot payloads.', }, ]); } diff --git a/cdk/test/constructs/ecs-agent-cluster.test.ts b/cdk/test/constructs/ecs-agent-cluster.test.ts index 98eafdf89..7600c671e 100644 --- a/cdk/test/constructs/ecs-agent-cluster.test.ts +++ b/cdk/test/constructs/ecs-agent-cluster.test.ts @@ -872,7 +872,7 @@ describe('EcsAgentCluster payload bucket (#502)', () => { }); }); - test('grants the task role READ on the payload bucket, never write/delete', () => { + test('allows only bootstrap reads and explicitly denies other objects and listing', () => { const template = createWithPayloadBucket(); const policies = template.findResources('AWS::IAM::Policy'); const s3Actions = new Set(); @@ -884,7 +884,13 @@ describe('EcsAgentCluster payload bucket (#502)', () => { } } } - // Read actions present... + const statements = Object.values(policies).flatMap(p => p.Properties.PolicyDocument.Statement); + const allow = statements.find(s => s.Effect === 'Allow' && s.Action === 's3:GetObject'); + expect(JSON.stringify(allow.Resource)).toContain('/bootstrap/*'); + expect(statements).toEqual(expect.arrayContaining([ + expect.objectContaining({ Effect: 'Deny', Action: 's3:GetObject*', NotResource: allow.Resource }), + expect.objectContaining({ Effect: 'Deny', Action: 's3:List*' }), + ])); expect([...s3Actions].some(a => a === 's3:GetObject' || a === 's3:GetObject*')).toBe(true); // ...and NO write/delete on the payload bucket from the task role. expect(s3Actions.has('s3:PutObject')).toBe(false); diff --git a/cdk/test/constructs/lambda-microvm-compute.test.ts b/cdk/test/constructs/lambda-microvm-compute.test.ts index 54ddf8f35..94ad1854d 100644 --- a/cdk/test/constructs/lambda-microvm-compute.test.ts +++ b/cdk/test/constructs/lambda-microvm-compute.test.ts @@ -716,19 +716,23 @@ describe('LambdaMicrovmCompute — image provisioned from a managed base image', expect(JSON.stringify(s3Statement.Resource)).toContain(MICROVM_ARTIFACT_OBJECT_KEY); }); - test('execution role gets READ-ONLY on the payload bucket and no write/delete', () => { + test('execution role gets only bootstrap reads, explicit payload/list denies and no writes', () => { const policies = Object.entries(template.findResources('AWS::IAM::Policy')) .filter(([id]) => id.includes('LambdaMicrovmComputeExecutionRole')); const statements = policies.flatMap(([, p]) => p.Properties.PolicyDocument.Statement); const actions: string[] = statements.flatMap((s: { Action: string | string[] }) => Array.isArray(s.Action) ? s.Action : [s.Action]); - // CDK's grantRead renders the Get*/List* read set. - expect(actions).toContain('s3:GetObject*'); + const allowed = statements.filter((s: { Effect: string }) => s.Effect === 'Allow' && s.Action === 's3:GetObject'); + expect(allowed).toHaveLength(1); + expect(JSON.stringify(allowed[0].Resource)).toContain('/bootstrap/*'); + const denied = statements.find((s: { NotResource?: unknown }) => s.NotResource); + expect(denied.Effect).toBe('Deny'); + expect(denied.NotResource).toEqual(allowed[0].Resource); // The MicroVM runs untrusted repo code — it must not be able to clobber // another task's payload, so nothing mutating may appear. const s3Actions = actions.filter(a => a.startsWith('s3:')); - expect(s3Actions).toEqual(['s3:GetObject*', 's3:GetBucket*', 's3:List*']); + expect(s3Actions).toEqual(['s3:GetObject', 's3:GetObject*', 's3:List*']); for (const action of s3Actions) { expect(action).not.toMatch(/Put|Delete|Abort|Write|^s3:\*$/); } @@ -780,7 +784,7 @@ describe('LambdaMicrovmCompute — image provisioned from a managed base image', // ecs-agent-cluster). Without it a Linear/Jira task's 👀→✅ reaction and the // channel MCP silently no-op. const prefixStatement = executionRoleStatements().find( - statement => JSON.stringify(statement.Resource).includes('bgagent-linear-oauth-*'), + statement => JSON.stringify(statement.Resource ?? '').includes('bgagent-linear-oauth-*'), )!; expect(prefixStatement).toBeDefined(); expect(prefixStatement.Action).toBe('secretsmanager:GetSecretValue'); @@ -835,7 +839,7 @@ describe('LambdaMicrovmCompute — image provisioned from a managed base image', // why it survived P2: the substrate looked fine while the platform's canonical // observability streams were empty. const statements = executionRoleStatements().filter((statement) => { - const resource = JSON.stringify(statement.Resource); + const resource = JSON.stringify(statement.Resource ?? ''); return resource.includes('ApplicationLogGroup'); }); expect(statements).toHaveLength(1); @@ -928,7 +932,7 @@ describe('LambdaMicrovmCompute — image provisioned from a managed base image', const s3Resources = executionRoleStatements() .flatMap(st => (Array.isArray(st.Action) ? st.Action : [st.Action])) .filter(action => action.startsWith('s3:')); - expect(s3Resources).toEqual(['s3:GetObject*', 's3:GetBucket*', 's3:List*']); + expect(s3Resources).toEqual(['s3:GetObject', 's3:GetObject*', 's3:List*']); const rendered = JSON.stringify( executionRoleStatements().filter((st) => { const actions = Array.isArray(st.Action) ? st.Action : [st.Action]; diff --git a/cdk/test/constructs/payload-bootstrap-permissions.test.ts b/cdk/test/constructs/payload-bootstrap-permissions.test.ts new file mode 100644 index 000000000..20bfddfba --- /dev/null +++ b/cdk/test/constructs/payload-bootstrap-permissions.test.ts @@ -0,0 +1,67 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { App, Stack } from 'aws-cdk-lib'; +import { Template } from 'aws-cdk-lib/assertions'; +import * as iam from 'aws-cdk-lib/aws-iam'; +import * as s3 from 'aws-cdk-lib/aws-s3'; +import { grantCoordinatorPayloads, grantWorkerBootstrap } from '../../src/constructs/payload-bootstrap-permissions'; + +describe('payload bootstrap permission boundary', () => { + let template: Template; + beforeAll(() => { + const stack = new Stack(new App(), 'PayloadPermissions'); + const bucket = new s3.Bucket(stack, 'Payloads'); + const worker = new iam.Role(stack, 'Worker', { assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com') }); + const coordinator = new iam.Role(stack, 'Coordinator', { assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com') }); + grantWorkerBootstrap(bucket, worker); + grantCoordinatorPayloads(bucket, coordinator); + template = Template.fromStack(stack); + }); + + test('worker can read only deployment manifests, including against another public bucket', () => { + const policy = Object.entries(template.findResources('AWS::IAM::Policy')) + .find(([id]) => id.startsWith('Worker'))![1].Properties.PolicyDocument.Statement; + expect(policy).toHaveLength(3); + const allow = policy.find((s: { Effect: string }) => s.Effect === 'Allow'); + expect(allow.Action).toBe('s3:GetObject'); + expect(JSON.stringify(allow.Resource)).toContain('/bootstrap/*'); + const deny = policy.find((s: { NotResource?: unknown }) => s.NotResource); + expect(deny.Effect).toBe('Deny'); + expect(deny.Action).toBe('s3:GetObject*'); + expect(deny.NotResource).toEqual(allow.Resource); + expect(policy.find((s: { Action: string }) => s.Action === 's3:List*').Effect).toBe('Deny'); + expect(JSON.stringify(policy)).not.toContain('s3:Put'); + expect(JSON.stringify(policy)).not.toContain('s3:Delete'); + }); + + test('coordinator publishes manifests and privately persists, signs and deletes task references', () => { + const policy = Object.entries(template.findResources('AWS::IAM::Policy')) + .find(([id]) => id.startsWith('Coordinator'))![1].Properties.PolicyDocument.Statement; + const writes = policy.find((s: { Action: string }) => s.Action === 's3:PutObject'); + expect(JSON.stringify(writes.Resource)).toContain('/bootstrap/*'); + const reads = policy.find((s: { Action: string[] }) => Array.isArray(s.Action) && s.Action.includes('s3:GetObject')); + expect(reads.Action).toEqual(['s3:GetObject', 's3:DeleteObject']); + expect(JSON.stringify(reads.Resource)).toContain('*/payload.json'); + expect(JSON.stringify(reads.Resource)).toContain('*/launch.json'); + expect(JSON.stringify(reads.Resource)).not.toContain('/bootstrap/*'); + const list = policy.find((s: { Action: string }) => s.Action === 's3:ListBucket'); + expect(list.Resource).toEqual({ 'Fn::GetAtt': [expect.stringMatching(/^Payloads/), 'Arn'] }); + }); +}); diff --git a/cdk/test/constructs/task-orchestrator.test.ts b/cdk/test/constructs/task-orchestrator.test.ts index a7b2e9cf2..8f37466c5 100644 --- a/cdk/test/constructs/task-orchestrator.test.ts +++ b/cdk/test/constructs/task-orchestrator.test.ts @@ -813,7 +813,18 @@ describe('TaskOrchestrator with the Lambda MicroVMs backend (ADR-021)', () => { const actions = payloadStatements.flatMap(s => Array.isArray(s.Action) ? s.Action : [s.Action]); expect(actions).toContain('s3:PutObject'); - expect(actions).not.toContain('s3:DeleteObject'); + expect(actions).toContain('s3:DeleteObject'); + expect(actions).toContain('s3:GetObject'); + expect(actions.filter(action => action.startsWith('s3:List'))).toEqual(['s3:ListBucket']); + const list = payloadStatements.find(s => s.Action === 's3:ListBucket'); + expect(list!.Resource).toEqual({ 'Fn::GetAtt': [expect.stringMatching(/^MicrovmPayloadBucket/), 'Arn'] }); + const deletes = payloadStatements.filter(s => + (Array.isArray(s.Action) ? s.Action : [s.Action]).some(action => action.startsWith('s3:Delete'))); + expect(deletes).toHaveLength(1); + expect(deletes[0]!.Action).toEqual(['s3:GetObject', 's3:DeleteObject']); + expect(JSON.stringify(deletes[0]!.Resource)).toContain('/*/payload.json'); + expect(JSON.stringify(deletes[0]!.Resource)).toContain('/*/launch.json'); + expect(JSON.stringify(deletes[0]!.Resource)).not.toContain('/bootstrap/*'); }); test('adds no MicroVM statements when microvmConfig is omitted', () => { diff --git a/cdk/test/handlers/orchestrate-task-microvm.test.ts b/cdk/test/handlers/orchestrate-task-microvm.test.ts index 1023238fd..efdaa459e 100644 --- a/cdk/test/handlers/orchestrate-task-microvm.test.ts +++ b/cdk/test/handlers/orchestrate-task-microvm.test.ts @@ -58,8 +58,11 @@ jest.mock('@aws-sdk/client-lambda-microvms', () => ({ // PUT and the finalize DELETE are both assertions this file needs to make, and a // per-instance mock silently discards them. const mockS3Send = jest.fn().mockResolvedValue({}); +jest.mock('@aws-sdk/s3-request-presigner', () => ({ getSignedUrl: async () => 'https://payloads.s3.us-east-1.amazonaws.com/task/payload.json?X-Amz-Signature=' + Date.now() })); +const mockObjects = new Map(); jest.mock('@aws-sdk/client-s3', () => ({ - S3Client: jest.fn(() => ({ send: mockS3Send })), + GetObjectCommand: jest.fn((input: unknown) => ({ _type: 'GetObject', input })), + S3Client: jest.fn(() => ({ send: mockS3Send, config: { credentials: async () => ({ accessKeyId: 'EXAMPLE', secretAccessKey: 'unused' }) } })), PutObjectCommand: jest.fn((input: unknown) => ({ _type: 'PutObject', input })), DeleteObjectCommand: jest.fn((input: unknown) => ({ _type: 'DeleteObject', input })), })); @@ -218,8 +221,17 @@ function s3CommandsOfType(type: string) { beforeEach(() => { jest.clearAllMocks(); - mockS3Send.mockReset(); - mockS3Send.mockResolvedValue({}); + mockObjects.clear(); + mockS3Send.mockReset().mockImplementation(async ({ _type: type, input: command }) => { + if (type === 'GetObject') { + if (!mockObjects.has(command.Key)) throw Object.assign(new Error('missing'), { name: 'NoSuchKey' }); + return { Body: { transformToString: async () => mockObjects.get(command.Key) } }; + } + if (type === 'DeleteObject') { mockObjects.delete(command.Key); return {}; } + if (command.IfNoneMatch === '*' && mockObjects.has(command.Key)) throw Object.assign(new Error('exists'), { name: 'PreconditionFailed' }); + mockObjects.set(command.Key, command.Body); + return {}; + }); mockMicrovmSend.mockReset(); mockPollTaskStatus.mockResolvedValue({ attempts: 1, lastStatus: TaskStatus.COMPLETED }); mockReconcile.mockResolvedValue({ taskFailed: false }); @@ -299,21 +311,23 @@ describe('orchestrate-task for a lambda-microvm task', () => { // --- finalize-time payload delete (review NB3) --- - test('deletes its OWN payload object on finalize, closing the cross-task read window', async () => { - // The execution role's payload-bucket grant is bucket-wide `grantRead`, so a - // TTL-only reaper left every finished task's hydrated prompt readable by any - // running MicroVM for ~24 h. ECS already deleted at finalize; this is the parity - // that matters. + test('deletes its own payload and saved capability on finalize', async () => { + // Revoke the signed payload link and remove its private replay record. + // The one-day lifecycle remains a cleanup backstop. runMicrovmOk(); await handler({ task_id: 'TASK001' }, fakeContext().ctx as never); const deletes = s3CommandsOfType('DeleteObject'); - expect(deletes).toHaveLength(1); + expect(deletes).toHaveLength(2); expect(deletes[0].input).toEqual({ Bucket: 'test-microvm-payload-bucket', Key: 'TASK001/payload.json', }); + expect(deletes[1].input).toEqual({ + Bucket: 'test-microvm-payload-bucket', + Key: 'TASK001/launch.json', + }); // ...and it did not reach for the ECS deleter. expect(mockDeleteEcsPayload).not.toHaveBeenCalled(); }); diff --git a/cdk/test/handlers/shared/payload-bootstrap.test.ts b/cdk/test/handlers/shared/payload-bootstrap.test.ts new file mode 100644 index 000000000..091c58f07 --- /dev/null +++ b/cdk/test/handlers/shared/payload-bootstrap.test.ts @@ -0,0 +1,160 @@ +/** + * MIT No Attribution + * + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +import { createHash } from 'node:crypto'; + +const mockSend = jest.fn(); +const mockSign = jest.fn(); +const mockCredentials = jest.fn(); +jest.mock('@aws-sdk/client-s3', () => ({ + S3Client: jest.fn(() => ({ send: mockSend, config: { credentials: mockCredentials } })), + PutObjectCommand: jest.fn(input => ({ kind: 'put', input })), + GetObjectCommand: jest.fn(input => ({ kind: 'get', input })), + DeleteObjectCommand: jest.fn(input => ({ kind: 'delete', input })), +})); +jest.mock('@aws-sdk/s3-request-presigner', () => ({ + getSignedUrl: (...args: unknown[]) => mockSign(...args), +})); + +import { deletePayloadReference, PAYLOAD_BOOTSTRAP, preparePayloadReference, redactPayloadUrls } from '../../../src/handlers/shared/payload-bootstrap'; + +const objects = new Map(); +const input = { + bucket: 'payload-bucket', + taskId: 'task-1', + backend: 'lambda-microvm' as const, + payload: { task_id: 'task-1', prompt: 'hello' }, + platformConfig: { github_token_secret_arn: 'arn:aws:secretsmanager:us-west-2:123456789012:secret:github' }, +}; +let loseReplyFor: string | undefined; + +beforeEach(() => { + jest.clearAllMocks(); + objects.clear(); + loseReplyFor = undefined; + mockCredentials.mockResolvedValue({ accessKeyId: 'EXAMPLE', secretAccessKey: 'unused' }); + mockSign.mockImplementation(async () => `https://payload-bucket.s3.us-east-1.amazonaws.com/task-1/payload.json?X-Amz-Security-Token=secret&X-Amz-Signature=${mockSign.mock.calls.length}`); + mockSend.mockImplementation(async ({ kind, input: request }) => { + if (kind === 'get') { + if (!objects.has(request.Key)) throw Object.assign(new Error('missing'), { name: 'NoSuchKey' }); + return { Body: { transformToString: async () => objects.get(request.Key)! } }; + } + if (kind === 'delete') { objects.delete(request.Key); return {}; } + if (request.IfNoneMatch === '*' && objects.has(request.Key)) { + throw Object.assign(new Error('exists'), { name: 'PreconditionFailed' }); + } + objects.set(request.Key, request.Body); + if (loseReplyFor === request.Key) { + loseReplyFor = undefined; + throw new Error('lost committed reply'); + } + return {}; + }); +}); + +test('separates public manifest from private payload and saved capability', async () => { + const ref = await preparePayloadReference(input); + const key = ref.bootstrap_s3_uri.split('/').slice(3).join('/'); + const manifest = objects.get(key)!; + expect(key).toBe(`bootstrap/${createHash('sha256').update(manifest).digest('hex')}.json`); + expect(JSON.parse(manifest)).toEqual({ + version: 2, backend: 'lambda-microvm', platform_config: input.platformConfig, + }); + expect(manifest).not.toContain('hello'); + expect(manifest).not.toContain('X-Amz'); + expect(JSON.parse(objects.get('task-1/payload.json')!).agent_payload).toEqual(input.payload); + expect(JSON.parse(objects.get('task-1/launch.json')!).reference).toEqual(ref); + expect(mockSign).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ + input: { Bucket: input.bucket, Key: 'task-1/payload.json' }, + }), { expiresIn: 900 }); +}); + +test('replay and concurrent preparation return identical launch bytes without resigning on replay', async () => { + const first = await preparePayloadReference(input); + const replay = await preparePayloadReference({ ...input, payload: { prompt: 'hello', task_id: 'task-1' } }); + expect(JSON.stringify(replay)).toBe(JSON.stringify(first)); + expect(mockSign).toHaveBeenCalledTimes(1); + // Fixed pair, covering conditional object publication by competing callers. + objects.clear(); + // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism + const [a, b] = await Promise.all([preparePayloadReference(input), preparePayloadReference(input)]); + expect(JSON.stringify(a)).toBe(JSON.stringify(b)); +}); + +test.each(['task-1/payload.json', 'task-1/launch.json'])('recovers a lost committed response for %s', async key => { + loseReplyFor = key; + const first = await preparePayloadReference(input); + expect(await preparePayloadReference(input)).toEqual(first); +}); + +test('changed instructions cannot overwrite an existing payload or launch reference', async () => { + await preparePayloadReference(input); + const before = objects.get('task-1/payload.json'); + await expect(preparePayloadReference({ ...input, payload: { ...input.payload, prompt: 'changed' } })) + .rejects.toThrow('PAYLOAD_BOOTSTRAP_CONFLICT'); + expect(objects.get('task-1/payload.json')).toBe(before); +}); + +test('orphaned payload after a crash cannot be overwritten with changed instructions', async () => { + await preparePayloadReference(input); + objects.delete('task-1/launch.json'); + await expect(preparePayloadReference({ ...input, payload: { ...input.payload, prompt: 'changed' } })) + .rejects.toThrow('PAYLOAD_BOOTSTRAP_CONFLICT'); + expect(JSON.parse(objects.get('task-1/payload.json')!).agent_payload.prompt).toBe('hello'); +}); + +test('expired references fail closed without signing a replacement', async () => { + await preparePayloadReference(input); + const record = JSON.parse(objects.get('task-1/launch.json')!); + record.reference.expires_at = Date.now() - 1; + objects.set('task-1/launch.json', JSON.stringify(record)); + await expect(preparePayloadReference(input)).rejects.toThrow('PAYLOAD_BOOTSTRAP_EXPIRED'); + expect(mockSign).toHaveBeenCalledTimes(1); +}); + +test('credential lifetime bounds the link and refuses credentials expiring too soon', async () => { + mockCredentials.mockResolvedValue({ expiration: new Date(Date.now() + 20_000) }); + await expect(preparePayloadReference(input)).rejects.toThrow('CREDENTIALS_EXPIRING'); + expect(mockSign).not.toHaveBeenCalled(); +}); + +test.each(['../bootstrap', 'task/other', ''])('invalid task key %s performs no S3 writes', async taskId => { + await expect(preparePayloadReference({ ...input, taskId })).rejects.toThrow('identity'); + expect(mockSend).not.toHaveBeenCalled(); +}); + +test('oversized payload fails before uploading or signing', async () => { + await expect(preparePayloadReference({ + ...input, payload: { ...input.payload, prompt: 'x'.repeat(PAYLOAD_BOOTSTRAP.max_payload_bytes) }, + })).rejects.toThrow('TOO_LARGE'); + expect(mockSend).not.toHaveBeenCalled(); +}); + +test('cleanup removes the capability and payload, preserving shared configuration', async () => { + const ref = await preparePayloadReference(input); + await deletePayloadReference(input.bucket, input.taskId); + expect(objects.has('task-1/payload.json')).toBe(false); + expect(objects.has('task-1/launch.json')).toBe(false); + expect(objects.has(ref.bootstrap_s3_uri.split('/').slice(3).join('/'))).toBe(true); +}); + +test('error redaction removes the whole signed URL including the session token', () => { + expect(redactPayloadUrls('failed https://b.s3.us-east-1.amazonaws.com/key?X-Amz-Security-Token=secret&X-Amz-Signature=abc end')) + .toBe('failed [redacted payload URL] end'); +}); diff --git a/cdk/test/handlers/shared/strategies/ecs-strategy.test.ts b/cdk/test/handlers/shared/strategies/ecs-strategy.test.ts index db474ddd3..904e133cd 100644 --- a/cdk/test/handlers/shared/strategies/ecs-strategy.test.ts +++ b/cdk/test/handlers/shared/strategies/ecs-strategy.test.ts @@ -27,13 +27,9 @@ process.env.ECS_TASK_DEFINITION_ARN = TASK_DEF_ARN; process.env.ECS_SUBNETS = 'subnet-aaa,subnet-bbb'; process.env.ECS_SECURITY_GROUP = 'sg-12345'; process.env.ECS_CONTAINER_NAME = 'AgentContainer'; -// The top-of-file import's inline-fallback / no-op tests assume these OPTIONAL -// vars are ABSENT at load time. They are unset in a dev shell but the real ECS -// agent container HAS ECS_PAYLOAD_BUCKET set (#502) — so leaving this to ambient -// env made the build pass locally yet FAIL on ECS ("works local, dies on ECS"). -// The #502 / #299 describe blocks below set these via isolateModules; delete them -// here so the top-of-file import is hermetic regardless of the runner's env. -delete process.env.ECS_PAYLOAD_BUCKET; +// Pin the payload bucket and optional planning definition at import time so the +// test runner's own deployment environment cannot change these expectations. +process.env.ECS_PAYLOAD_BUCKET = 'payload-bucket'; delete process.env.ECS_PLANNING_TASK_DEFINITION_ARN; const mockSend = jest.fn(); @@ -44,17 +40,20 @@ jest.mock('@aws-sdk/client-ecs', () => ({ StopTaskCommand: jest.fn((input: unknown) => ({ _type: 'StopTask', input })), })); -const mockS3Send = jest.fn(); -jest.mock('@aws-sdk/client-s3', () => ({ - S3Client: jest.fn(() => ({ send: mockS3Send })), - PutObjectCommand: jest.fn((input: unknown) => ({ _type: 'PutObject', input })), - DeleteObjectCommand: jest.fn((input: unknown) => ({ _type: 'DeleteObject', input })), +const mockPrepare = jest.fn(); +const mockDelete = jest.fn(); +jest.mock('../../../../src/handlers/shared/payload-bootstrap', () => ({ + ...jest.requireActual('../../../../src/handlers/shared/payload-bootstrap'), + preparePayloadReference: (...args: unknown[]) => mockPrepare(...args), + deletePayloadReference: (...args: unknown[]) => mockDelete(...args), })); import { EcsComputeStrategy } from '../../../../src/handlers/shared/strategies/ecs-strategy'; beforeEach(() => { jest.clearAllMocks(); + mockPrepare.mockReset().mockImplementation(async ({ taskId }: { taskId: string }) => ({ version: 2, task_id: taskId, bootstrap_s3_uri: 's3://b/bootstrap/example.json', payload_url: 'https://signed.example/task', expires_at: Date.now()+900000 })); + mockDelete.mockResolvedValue(undefined); }); describe('EcsComputeStrategy', () => { @@ -103,21 +102,14 @@ describe('EcsComputeStrategy', () => { expect(envVars).toEqual(expect.arrayContaining([ { name: 'TASK_ID', value: 'TASK001' }, { name: 'REPO_URL', value: 'org/repo' }, - { name: 'TASK_DESCRIPTION', value: 'Fix the bug' }, { name: 'ISSUE_NUMBER', value: '42' }, { name: 'MAX_TURNS', value: '50' }, { name: 'CLAUDE_CODE_USE_BEDROCK', value: '1' }, ])); - // No ECS_PAYLOAD_BUCKET in this module's env → inline fallback (#502): the - // full payload rides in AGENT_PAYLOAD and nothing is written to S3. - const agentPayload = envVars.find((e: { name: string }) => e.name === 'AGENT_PAYLOAD'); - expect(agentPayload).toBeDefined(); - const parsed = JSON.parse(agentPayload.value); - expect(parsed.repo_url).toBe('org/repo'); - expect(parsed.prompt).toBe('Fix the bug'); - expect(envVars.find((e: { name: string }) => e.name === 'AGENT_PAYLOAD_S3_URI')).toBeUndefined(); - expect(mockS3Send).not.toHaveBeenCalled(); + const reference = envVars.find((e: { name: string }) => e.name === 'AGENT_PAYLOAD_REF'); + expect(JSON.parse(reference.value).task_id).toBe('TASK001'); + expect(mockPrepare).toHaveBeenCalledWith(expect.objectContaining({ payload: expect.objectContaining({ repo_url: 'org/repo', prompt: 'Fix the bug' }) })); // Container command override — runs Python directly instead of uvicorn expect(override.command).toBeDefined(); @@ -379,113 +371,47 @@ describe('EcsComputeStrategy', () => { }); }); -// #502: the S3-pointer path requires ECS_PAYLOAD_BUCKET to be set BEFORE the -// module is imported (it's a module-level constant). Re-import under -// jest.isolateModules with the env var set so these tests don't perturb the -// inline-fallback tests above. -describe('EcsComputeStrategy with ECS_PAYLOAD_BUCKET (S3-pointer path, #502)', () => { - const PAYLOAD_BUCKET = 'test-ecs-payload-bucket'; - - function loadStrategyWithBucket(): { - EcsComputeStrategy: typeof import('../../../../src/handlers/shared/strategies/ecs-strategy').EcsComputeStrategy; - deleteEcsPayload: typeof import('../../../../src/handlers/shared/strategies/ecs-strategy').deleteEcsPayload; - ecsPayloadKey: typeof import('../../../../src/handlers/shared/strategies/ecs-strategy').ecsPayloadKey; - } { - let mod!: ReturnType; - jest.isolateModules(() => { - process.env.ECS_PAYLOAD_BUCKET = PAYLOAD_BUCKET; - process.env.ECS_CLUSTER_ARN = CLUSTER_ARN; - process.env.ECS_TASK_DEFINITION_ARN = TASK_DEF_ARN; - process.env.ECS_SUBNETS = 'subnet-aaa,subnet-bbb'; - process.env.ECS_SECURITY_GROUP = 'sg-12345'; - process.env.ECS_CONTAINER_NAME = 'AgentContainer'; - // eslint-disable-next-line @typescript-eslint/no-require-imports - mod = require('../../../../src/handlers/shared/strategies/ecs-strategy'); - }); - return mod; - } - - afterEach(() => { - delete process.env.ECS_PAYLOAD_BUCKET; - }); - - test('writes payload to S3 and passes AGENT_PAYLOAD_S3_URI, not the inline blob', async () => { - mockS3Send.mockResolvedValueOnce({}); +describe('ECS v2 bootstrap integration', () => { + test('passes the prepared capability and consumes it before entering the pipeline', async () => { mockSend.mockResolvedValueOnce({ tasks: [{ taskArn: TASK_ARN }] }); + await new EcsComputeStrategy().startSession({ taskId: 'TASK001', userId: 'u1', payload: { task_id: 'TASK001', prompt: 'x'.repeat(10000) }, blueprintConfig: { compute_type: 'ecs', runtime_arn: '' } }); + expect(mockPrepare).toHaveBeenCalledWith(expect.objectContaining({ backend: 'ecs', taskId: 'TASK001', bucket: 'payload-bucket' })); + const override=mockSend.mock.calls[0][0].input.overrides.containerOverrides[0]; + expect(override.environment.some((e: { name: string }) => ['AGENT_PAYLOAD', 'AGENT_PAYLOAD_S3_URI', 'TASK_DESCRIPTION'].includes(e.name))).toBe(false); + const source=override.command[2]; + expect(source).toContain('load_ecs_payload()'); + expect(source.indexOf('load_ecs_payload()')).toBeLessThan(source.indexOf('from entrypoint')); + }); + test('delegates deletion of the payload and private launch capability', async () => { + const { deleteEcsPayload }=await import('../../../../src/handlers/shared/strategies/ecs-strategy'); + await deleteEcsPayload('TASK001'); + expect(mockDelete).toHaveBeenCalledWith('payload-bucket', 'TASK001'); + }); - const { EcsComputeStrategy: Strategy } = loadStrategyWithBucket(); - const strategy = new Strategy(); - await strategy.startSession({ + test('rejects oversized UTF-8 overrides before RunTask', async () => { + await expect(new EcsComputeStrategy().startSession({ taskId: 'TASK001', - userId: 'cognito-test', - payload: { repo_url: 'org/repo', prompt: 'Fix the bug', hydrated_context: { big: 'x'.repeat(10000) } }, - blueprintConfig: { compute_type: 'ecs', runtime_arn: '' }, - }); - - // PutObject to the payload bucket at /payload.json - expect(mockS3Send).toHaveBeenCalledTimes(1); - const put = mockS3Send.mock.calls[0][0]; - expect(put._type).toBe('PutObject'); - expect(put.input.Bucket).toBe(PAYLOAD_BUCKET); - expect(put.input.Key).toBe('TASK001/payload.json'); - expect(JSON.parse(put.input.Body).repo_url).toBe('org/repo'); - - // Override carries the URI pointer, NOT the inline payload - const envVars = mockSend.mock.calls[0][0].input.overrides.containerOverrides[0].environment; - const uri = envVars.find((e: { name: string }) => e.name === 'AGENT_PAYLOAD_S3_URI'); - expect(uri.value).toBe(`s3://${PAYLOAD_BUCKET}/TASK001/payload.json`); - expect(envVars.find((e: { name: string }) => e.name === 'AGENT_PAYLOAD')).toBeUndefined(); + userId: 'u1', + payload: { task_id: 'TASK001' }, + blueprintConfig: { compute_type: 'ecs', runtime_arn: '', system_prompt_overrides: '🌍'.repeat(2100) }, + })).rejects.toThrow('ECS container overrides exceed 8192 bytes'); + expect(mockSend).not.toHaveBeenCalled(); }); - test('boot command loads payload from S3 when the URI is set, else inline', async () => { - mockS3Send.mockResolvedValueOnce({}); - mockSend.mockResolvedValueOnce({ tasks: [{ taskArn: TASK_ARN }] }); - - const { EcsComputeStrategy: Strategy } = loadStrategyWithBucket(); - await new Strategy().startSession({ + test('redacts a capability even when preparation fails before RunTask', async () => { + mockPrepare.mockRejectedValueOnce(new Error('failed https://bucket.example/key?X-Amz-Signature=BEARER-SECRET')); + await expect(new EcsComputeStrategy().startSession({ taskId: 'TASK001', - userId: 'cognito-test', - payload: { repo_url: 'org/repo' }, + userId: 'u1', + payload: { task_id: 'TASK001' }, blueprintConfig: { compute_type: 'ecs', runtime_arn: '' }, - }); - - const cmd = mockSend.mock.calls[0][0].input.overrides.containerOverrides[0].command; - const src = cmd[2]; - // Reads the URI, fetches via boto3 S3 when set, falls back to inline env. - expect(src).toContain('AGENT_PAYLOAD_S3_URI'); - expect(src).toContain('get_object'); - expect(src).toContain('AGENT_PAYLOAD'); - // ABCA-487: the boot command maps the WHOLE payload via - // run_task_from_payload (not a hand-listed kwarg subset that dropped - // channel_source/channel_metadata → no Linear reactions on ECS). Assert we - // call the mapper and no longer hand-pick the old prompt/model_id kwargs. - expect(src).toContain('run_task_from_payload(p)'); - expect(src).not.toContain('task_description=p.get'); - expect(src).not.toContain('channel_source'); // never hand-listed; the mapper forwards it - }); - - test('deleteEcsPayload deletes the task payload object', async () => { - mockS3Send.mockResolvedValueOnce({}); - const { deleteEcsPayload, ecsPayloadKey } = loadStrategyWithBucket(); - await deleteEcsPayload('TASK001'); - expect(mockS3Send).toHaveBeenCalledTimes(1); - const del = mockS3Send.mock.calls[0][0]; - expect(del._type).toBe('DeleteObject'); - expect(del.input.Bucket).toBe(PAYLOAD_BUCKET); - expect(del.input.Key).toBe(ecsPayloadKey('TASK001')); - expect(ecsPayloadKey('TASK001')).toBe('TASK001/payload.json'); - }); - - test('deleteEcsPayload swallows S3 errors (best-effort — lifecycle is the backstop)', async () => { - mockS3Send.mockRejectedValueOnce(new Error('AccessDenied')); - const { deleteEcsPayload } = loadStrategyWithBucket(); - await expect(deleteEcsPayload('TASK001')).resolves.toBeUndefined(); + })).rejects.toThrow('failed [redacted payload URL]'); + expect(mockSend).not.toHaveBeenCalled(); }); }); // #299 ECS_RIGHTSIZED_PLANNING: the planning task def ARN is a module-level -// constant, so set it BEFORE import via isolateModules (mirrors the #502 bucket -// pattern above) — this keeps it out of the inline tests at the top. +// constant, so set it BEFORE import via isolateModules. describe('EcsComputeStrategy read-only planning-def selection (#299 ECS_RIGHTSIZED_PLANNING)', () => { const PLANNING_DEF_ARN = 'arn:aws:ecs:us-east-1:123456789012:task-definition/agent-planning:1'; @@ -548,12 +474,34 @@ describe('EcsComputeStrategy read-only planning-def selection (#299 ECS_RIGHTSIZ }); }); -describe('deleteEcsPayload without ECS_PAYLOAD_BUCKET', () => { +describe('ECS without ECS_PAYLOAD_BUCKET', () => { + let isolated: typeof import('../../../../src/handlers/shared/strategies/ecs-strategy'); + beforeEach(() => { + const bucket = process.env.ECS_PAYLOAD_BUCKET; + delete process.env.ECS_PAYLOAD_BUCKET; + try { + jest.isolateModules(() => { + // eslint-disable-next-line @typescript-eslint/no-require-imports + isolated = require('../../../../src/handlers/shared/strategies/ecs-strategy'); + }); + } finally { + process.env.ECS_PAYLOAD_BUCKET = bucket; + } + }); + test('no-ops when no payload bucket is configured', async () => { - // The top-of-file import has no ECS_PAYLOAD_BUCKET set. - // eslint-disable-next-line @typescript-eslint/no-require-imports - const { deleteEcsPayload } = require('../../../../src/handlers/shared/strategies/ecs-strategy'); - await expect(deleteEcsPayload('TASK001')).resolves.toBeUndefined(); - expect(mockS3Send).not.toHaveBeenCalled(); + await expect(isolated.deleteEcsPayload('TASK001')).resolves.toBeUndefined(); + expect(mockDelete).not.toHaveBeenCalled(); + }); + + test('rejects a launch before preparing or running anything', async () => { + await expect(new isolated.EcsComputeStrategy().startSession({ + taskId: 'TASK001', + userId: 'u1', + payload: { task_id: 'TASK001' }, + blueprintConfig: { compute_type: 'ecs', runtime_arn: '' }, + })).rejects.toThrow('ECS_PAYLOAD_BUCKET is required'); + expect(mockPrepare).not.toHaveBeenCalled(); + expect(mockSend).not.toHaveBeenCalled(); }); }); diff --git a/cdk/test/handlers/shared/strategies/lambda-microvm-strategy.test.ts b/cdk/test/handlers/shared/strategies/lambda-microvm-strategy.test.ts index 087758077..cbda31ea3 100644 --- a/cdk/test/handlers/shared/strategies/lambda-microvm-strategy.test.ts +++ b/cdk/test/handlers/shared/strategies/lambda-microvm-strategy.test.ts @@ -98,11 +98,12 @@ jest.mock('@aws-sdk/client-lambda-microvms', () => ({ }, })); -const mockS3Send = jest.fn(); -jest.mock('@aws-sdk/client-s3', () => ({ - S3Client: jest.fn(() => ({ send: mockS3Send })), - PutObjectCommand: jest.fn((input: unknown) => ({ _type: 'PutObject', input })), - DeleteObjectCommand: jest.fn((input: unknown) => ({ _type: 'DeleteObject', input })), +const mockPrepare = jest.fn(); +const mockDelete = jest.fn(); +jest.mock('../../../../src/handlers/shared/payload-bootstrap', () => ({ + ...jest.requireActual('../../../../src/handlers/shared/payload-bootstrap'), + preparePayloadReference: (...args: unknown[]) => mockPrepare(...args), + deletePayloadReference: (...args: unknown[]) => mockDelete(...args), })); // The real logger writes JSON to process.stdout/stderr, so level assertions need @@ -126,7 +127,6 @@ import { buildMicrovmPlatformConfig, deleteMicrovmPayload, microvmNoIngressConnectorArnForRegion, - microvmPayloadKey, } from '../../../../src/handlers/shared/strategies/lambda-microvm-strategy'; const BLUEPRINT: BlueprintConfig = { compute_type: 'lambda-microvm', runtime_arn: '' }; @@ -142,31 +142,6 @@ const EXPECTED_PLATFORM_CONFIG = { agent_session_role_arn: AGENT_SESSION_ROLE_ARN, }; -/** - * Build a payload whose serialized `{"agent_payload": …, "platform_config": …}` - * envelope is EXACTLY `targetBytes` long, so the 4 KB boundary can be probed on - * both sides. - * - * `platform_config` is part of the counted envelope (ADR-021 P2), so its bytes are - * subtracted from the payload's budget here. Asserts its own arithmetic — if the - * envelope shape or the platform block ever changes, this fails loudly rather than - * silently testing the wrong boundary. - */ -function payloadWithEnvelopeBytes(targetBytes: number): Record { - const overhead = Buffer.byteLength( - JSON.stringify({ agent_payload: { p: '' }, platform_config: EXPECTED_PLATFORM_CONFIG }), - 'utf8', - ); - const payload = { p: 'x'.repeat(targetBytes - overhead) }; - expect( - Buffer.byteLength( - JSON.stringify({ agent_payload: payload, platform_config: EXPECTED_PLATFORM_CONFIG }), - 'utf8', - ), - ).toBe(targetBytes); - return payload; -} - function runMicrovmOk() { mockSend.mockResolvedValueOnce({ microvmId: MICROVM_ID, @@ -254,22 +229,10 @@ async function withoutEnvAsync(keys: string[], body: () => Promise): Promi } } -/** {@link withoutEnvAsync}'s inverse: run `body` with extra env vars SET. */ -async function withEnvAsync(env: Record, body: () => Promise): Promise { - const saved = Object.fromEntries(Object.keys(env).map(key => [key, process.env[key]])); - try { - Object.assign(process.env, env); - await body(); - } finally { - for (const [key, value] of Object.entries(saved)) { - if (value === undefined) delete process.env[key]; - else process.env[key] = value; - } - } -} - beforeEach(() => { jest.clearAllMocks(); + mockPrepare.mockReset().mockImplementation(async ({ taskId }: { taskId: string }) => ({ version: 2, task_id: taskId, bootstrap_s3_uri: 's3://b/bootstrap/example.json', payload_url: 'https://signed.example/task', expires_at: Date.now()+900000 })); + mockDelete.mockResolvedValue(undefined); }); describe('LambdaMicrovmComputeStrategy', () => { @@ -417,142 +380,17 @@ describe('LambdaMicrovmComputeStrategy', () => { ]); }); - test('inlines a small payload in runHookPayload and never touches S3', async () => { - runMicrovmOk(); - - await new LambdaMicrovmComputeStrategy().startSession({ - taskId: 'TASK001', - userId: 'cognito-test', - payload: { repo_url: 'org/repo', prompt: 'Fix the bug', max_turns: 50 }, - blueprintConfig: BLUEPRINT, - }); - - expect(mockS3Send).not.toHaveBeenCalled(); - const envelope = JSON.parse(mockSend.mock.calls[0][0].input.runHookPayload); - expect(envelope.agent_payload).toEqual({ repo_url: 'org/repo', prompt: 'Fix the bug', max_turns: 50 }); - expect(envelope.agent_payload_s3_uri).toBeUndefined(); - // The MicroVM's substitute for the env block the other two backends get at - // deploy time — a snapshot must not bake it in (ADR-021 sub-decision 3), so - // it rides the envelope alongside the payload. - expect(envelope.platform_config).toEqual(EXPECTED_PLATFORM_CONFIG); - }); - - test('uploads an oversized payload to S3 and inlines only the pointer', async () => { - mockS3Send.mockResolvedValueOnce({}); - runMicrovmOk(); - - const big = { repo_url: 'org/repo', hydrated_context: { blob: 'x'.repeat(20_000) } }; - await new LambdaMicrovmComputeStrategy().startSession({ - taskId: 'TASK001', - userId: 'cognito-test', - payload: big, - blueprintConfig: BLUEPRINT, - }); - - // Same key shape as the ECS payload bucket: /payload.json - expect(mockS3Send).toHaveBeenCalledTimes(1); - const put = mockS3Send.mock.calls[0][0]; - expect(put._type).toBe('PutObject'); - expect(put.input.Bucket).toBe(PAYLOAD_BUCKET); - expect(put.input.Key).toBe('TASK001/payload.json'); - expect(put.input.ContentType).toBe('application/json'); - // The S3 object carries the payload with platform_config merged in at the top - // level, so an agent that resolves the pointer gets the config with it. - expect(JSON.parse(put.input.Body)).toEqual({ ...big, platform_config: EXPECTED_PLATFORM_CONFIG }); - - const runHookPayload = mockSend.mock.calls[0][0].input.runHookPayload; - const envelope = JSON.parse(runHookPayload); - expect(envelope.agent_payload_s3_uri).toBe(`s3://${PAYLOAD_BUCKET}/TASK001/payload.json`); - expect(envelope.agent_payload).toBeUndefined(); - // ...and ALSO inline on the pointer envelope, deliberately duplicated: the - // agent must be able to read its platform configuration whether it takes it - // off the hook body before fetching S3 or out of the fetched object. - expect(envelope.platform_config).toEqual(EXPECTED_PLATFORM_CONFIG); - // The whole point: the hook body must sit far under the 4 KB cap. - expect(Buffer.byteLength(runHookPayload, 'utf8')).toBeLessThan(MICROVM_RUN_HOOK_PAYLOAD_LIMIT_BYTES); - }); - - test('the inline/S3 branch point IS the 4096-byte service cap, with no headroom', () => { - // Live-measured, NOT read off the SDK docs (which say 16,384): the service - // rejects 4097 with "Member must have length less than or equal to 4096". - // Unlike ECS (whose 8192-byte cap is shared with env vars + command, so it - // needs a margin), runHookPayload is the entire counted string. - expect(MICROVM_RUN_HOOK_PAYLOAD_LIMIT_BYTES).toBe(4_096); - }); - - test('a payload whose envelope is EXACTLY 4096 bytes stays inline', async () => { - runMicrovmOk(); - - await new LambdaMicrovmComputeStrategy().startSession({ - taskId: 'TASK001', - userId: 'cognito-test', - payload: payloadWithEnvelopeBytes(4_096), - blueprintConfig: BLUEPRINT, - }); - - // Boundary is `<=`: 4096 passed the service's length validation live. - expect(mockS3Send).not.toHaveBeenCalled(); - const runHookPayload = mockSend.mock.calls[0][0].input.runHookPayload; - expect(Buffer.byteLength(runHookPayload, 'utf8')).toBe(4_096); - expect(JSON.parse(runHookPayload).agent_payload).toBeDefined(); - }); - - test('a payload whose envelope is 4097 bytes — one over — goes to S3', async () => { - mockS3Send.mockResolvedValueOnce({}); - runMicrovmOk(); - - await new LambdaMicrovmComputeStrategy().startSession({ - taskId: 'TASK001', - userId: 'cognito-test', - payload: payloadWithEnvelopeBytes(4_097), - blueprintConfig: BLUEPRINT, - }); - - expect(mockS3Send).toHaveBeenCalledTimes(1); - const envelope = JSON.parse(mockSend.mock.calls[0][0].input.runHookPayload); - expect(envelope.agent_payload_s3_uri).toBe(`s3://${PAYLOAD_BUCKET}/TASK001/payload.json`); - expect(envelope.agent_payload).toBeUndefined(); - }); - - test('a mid-sized envelope the SDK-documented 16KB cap would have inlined goes to S3', async () => { - mockS3Send.mockResolvedValueOnce({}); - runMicrovmOk(); - - // Regression guard for the live-verification fix: anything from 4,097 to - // 16,384 bytes used to be inlined and would be REJECTED by the service. - await new LambdaMicrovmComputeStrategy().startSession({ - taskId: 'TASK001', - userId: 'cognito-test', - payload: payloadWithEnvelopeBytes(13_000), - blueprintConfig: BLUEPRINT, - }); - - expect(mockS3Send).toHaveBeenCalledTimes(1); - const envelope = JSON.parse(mockSend.mock.calls[0][0].input.runHookPayload); - expect(envelope.agent_payload_s3_uri).toBeDefined(); + test.each(['small', 'x'.repeat(20000)])('delivers a persisted v2 reference for every payload size', async prompt => { + mockSend.mockResolvedValueOnce({ microvmId: MICROVM_ID, endpoint: ENDPOINT }); + await new LambdaMicrovmComputeStrategy().startSession({ taskId: 'TASK001', userId: 'u1', payload: { prompt }, blueprintConfig: BLUEPRINT }); + expect(mockPrepare).toHaveBeenCalledWith(expect.objectContaining({ bucket: PAYLOAD_BUCKET, backend: 'lambda-microvm', platformConfig: EXPECTED_PLATFORM_CONFIG, payload: { prompt } })); + const envelope=JSON.parse(mockSend.mock.calls[0][0].input.runHookPayload); + expect(envelope.version).toBe(2); + expect(envelope.task_id).toBe('TASK001'); + expect(envelope.platform_config).toBeUndefined(); expect(envelope.agent_payload).toBeUndefined(); }); - test('measures the serialized envelope in BYTES, so a multi-byte payload still goes to S3', async () => { - mockS3Send.mockResolvedValueOnce({}); - runMicrovmOk(); - - // 3-byte UTF-8 characters: 2000 chars is ~6 KB of bytes but only 2 KB of - // chars, so measuring String.length would have wrongly inlined this. - const payload = { prompt: '\u4f60'.repeat(2_000) }; - expect(JSON.stringify({ agent_payload: payload, platform_config: EXPECTED_PLATFORM_CONFIG }).length) - .toBeLessThan(MICROVM_RUN_HOOK_PAYLOAD_LIMIT_BYTES); - await new LambdaMicrovmComputeStrategy().startSession({ - taskId: 'TASK001', - userId: 'cognito-test', - payload, - blueprintConfig: BLUEPRINT, - }); - - expect(mockS3Send).toHaveBeenCalledTimes(1); - expect(JSON.parse(mockSend.mock.calls[0][0].input.runHookPayload).agent_payload_s3_uri).toBeDefined(); - }); - test('throws when RunMicrovm returns no microvmId', async () => { mockSend.mockResolvedValueOnce({ endpoint: ENDPOINT, state: 'PENDING' }); @@ -649,34 +487,6 @@ describe('LambdaMicrovmComputeStrategy', () => { expect(mockSend.mock.calls.filter(c => c[0]._type === 'TerminateMicrovm')).toHaveLength(0); }); - test('platform_config COUNTS toward the 4 KB boundary — an otherwise-inlineable payload goes to S3', async () => { - // The regression this locks: measuring `{agent_payload}` alone and then - // sending `{agent_payload, platform_config}` would inline an envelope the - // service rejects outright. So the branch decision has to be made on the - // FULL envelope. This payload is exactly 4 096 bytes WITHOUT the platform - // block — i.e. the old code would have inlined it — and must now upload. - mockS3Send.mockResolvedValueOnce({}); - runMicrovmOk(); - - const overheadWithoutConfig = Buffer.byteLength(JSON.stringify({ agent_payload: { p: '' } }), 'utf8'); - const payload = { p: 'x'.repeat(MICROVM_RUN_HOOK_PAYLOAD_LIMIT_BYTES - overheadWithoutConfig) }; - expect(Buffer.byteLength(JSON.stringify({ agent_payload: payload }), 'utf8')) - .toBe(MICROVM_RUN_HOOK_PAYLOAD_LIMIT_BYTES); - - await new LambdaMicrovmComputeStrategy().startSession({ - taskId: 'TASK001', - userId: 'cognito-test', - payload, - blueprintConfig: BLUEPRINT, - }); - - expect(mockS3Send).toHaveBeenCalledTimes(1); - const runHookPayload = mockSend.mock.calls[0][0].input.runHookPayload; - expect(JSON.parse(runHookPayload).agent_payload_s3_uri).toBeDefined(); - expect(Buffer.byteLength(runHookPayload, 'utf8')) - .toBeLessThanOrEqual(MICROVM_RUN_HOOK_PAYLOAD_LIMIT_BYTES); - }); - test.each(MICROVM_PLATFORM_CONFIG_REQUIRED_KEYS.map(key => [key]))( 'refuses to start — before any AWS call — when required platform config %s is missing', async (key) => { @@ -688,14 +498,14 @@ describe('LambdaMicrovmComputeStrategy', () => { userId: 'cognito-test', // Oversized on purpose: the guard must fire before the payload upload, // or a misconfiguration leaves orphan objects in the payload bucket. - payload: payloadWithEnvelopeBytes(20_000), + payload: { prompt: 'x'.repeat(20_000) }, blueprintConfig: BLUEPRINT, }); await expect(start).rejects.toThrow(new RegExp(`${key} <- ${envVar}`)); await expect(start).rejects.toThrow(/redeploy the stack/); expect(mockSend).not.toHaveBeenCalled(); - expect(mockS3Send).not.toHaveBeenCalled(); + expect(mockPrepare).not.toHaveBeenCalled(); }); }, ); @@ -718,72 +528,47 @@ describe('LambdaMicrovmComputeStrategy', () => { expect(JSON.stringify(started[1])).not.toContain(GITHUB_TOKEN_SECRET_ARN); }); - test('fails BEFORE the upload when even the POINTER envelope cannot fit (no orphan object)', async () => { - // The one shape with no smaller fallback: the payload has already been moved - // to S3, so if `{pointer + platform_config}` still exceeds 4 096 bytes there - // is nothing left to shed. Only a pathological identifier length can cause it - // — hence the check, and hence its placement BEFORE the PutObject so a - // misconfiguration cannot leave objects behind for the lifecycle rule to reap. - await withEnvAsync({ LOG_GROUP_NAME: `/aws/${'x'.repeat(5_000)}` }, async () => { - const start = new LambdaMicrovmComputeStrategy().startSession({ - taskId: 'TASK001', - userId: 'cognito-test', - payload: payloadWithEnvelopeBytes(20_000), - blueprintConfig: BLUEPRINT, - }); + test('rejects a saved reference exceeding the service cap before RunMicrovm', async () => { + mockPrepare.mockResolvedValueOnce({ version: 2, task_id: 'TASK001', payload_url: 'x'.repeat(MICROVM_RUN_HOOK_PAYLOAD_LIMIT_BYTES + 1) }); + await expect(new LambdaMicrovmComputeStrategy().startSession({ taskId: 'TASK001', userId: 'u1', payload: {}, blueprintConfig: BLUEPRINT })).rejects.toThrow('hook limit'); + expect(mockSend).not.toHaveBeenCalled(); + }); - await expect(start).rejects.toThrow(/pointer envelope is \d+ bytes/); - await expect(start).rejects.toThrow(/shorten the stack name/); - expect(mockS3Send).not.toHaveBeenCalled(); - expect(mockSend).not.toHaveBeenCalled(); + test.each(['bootstrap', 'run'])('redacts signed URLs throughout the %s error chain', async stage => { + const { inspect } = await import('node:util'); + const original = new Error('request failed https://bucket.example/key?X-Amz-Signature=BEARER-SECRET', { + cause: new Error('nested BEARER-SECRET'), }); + if (stage === 'bootstrap') mockPrepare.mockRejectedValueOnce(original); + else mockSend.mockRejectedValueOnce(original); + await new LambdaMicrovmComputeStrategy().startSession({ + taskId: 'TASK001', userId: 'u1', payload: {}, blueprintConfig: BLUEPRINT, + }).catch(error => { + expect(inspect(error, { depth: null })).not.toContain('BEARER-SECRET'); + }); + expect.assertions(1); }); - test('microvmPayloadKey matches the ECS payload key shape', () => { - expect(microvmPayloadKey('TASK001')).toBe('TASK001/payload.json'); + test('keeps the capability out of ordinary logs', async () => { + mockPrepare.mockResolvedValueOnce({ version: 2, task_id: 'TASK001', payload_url: 'BEARER-SECRET' }); + runMicrovmOk(); + await new LambdaMicrovmComputeStrategy().startSession({ + taskId: 'TASK001', userId: 'u1', payload: {}, blueprintConfig: BLUEPRINT, + }); + expect(JSON.stringify([ + mockLogger.info.mock.calls, mockLogger.warn.mock.calls, mockLogger.error.mock.calls, + ])).not.toContain('BEARER-SECRET'); }); }); // --- finalize-time payload delete (review NB3 / ayushtr nit 2) --- // - // Not cosmetic parity with ECS. The execution role's payload-bucket grant is - // `grantRead` on the WHOLE bucket (the guest must read its object before any - // tenant identity exists) and keys are `/payload.json`, so a TTL-only - // reaper left every finished task's HYDRATED PROMPT readable by any concurrently - // running MicroVM — which runs untrusted repo code — for up to ~24 h. - describe('deleteMicrovmPayload — closes the cross-task payload-read window', () => { - test('deletes the task\'s own object from the payload bucket', async () => { - await deleteMicrovmPayload('TASK001'); - - expect(mockS3Send).toHaveBeenCalledTimes(1); - const call = mockS3Send.mock.calls[0][0]; - expect(call._type).toBe('DeleteObject'); - expect(call.input).toEqual({ - Bucket: PAYLOAD_BUCKET, - Key: microvmPayloadKey('TASK001'), - }); - }); - - test('is best-effort — a failed delete never throws', async () => { - mockS3Send.mockRejectedValueOnce(new Error('AccessDenied')); - - await expect(deleteMicrovmPayload('TASK001')).resolves.toBeUndefined(); - // Not silent: the lifecycle rule is the backstop, but an operator must be - // able to see the delete is failing. - expect(mockLogger.warn).toHaveBeenCalledWith( - 'Failed to delete MicroVM payload object (non-fatal)', - expect.objectContaining({ task_id: 'TASK001', error: 'AccessDenied' }), - ); - }); - - test('deletes ONLY the given task\'s key — never a prefix or the bucket', async () => { - // The delete must not become a cleanup that can reach another task's object. + // Finalize revokes the single-object link and removes its private replay + // record; worker credentials already deny direct task-object reads. + describe('deleteMicrovmPayload', () => { + test('delegates cleanup of payload and private launch record', async () => { await deleteMicrovmPayload('TASK001'); - - const { input } = mockS3Send.mock.calls[0][0]; - expect(input.Key).toBe('TASK001/payload.json'); - expect(input.Key).not.toContain('*'); - expect(input).not.toHaveProperty('Prefix'); + expect(mockDelete).toHaveBeenCalledWith(PAYLOAD_BUCKET, 'TASK001'); }); }); @@ -998,7 +783,7 @@ describe('LambdaMicrovmComputeStrategy', () => { await expect(start).rejects.toThrow('MicroVM RunMicrovm failed: ThrottlingException: Rate exceeded'); }); - test('preserves the original error as `cause` so err.name stays inspectable', async () => { + test('preserves the AWS error name in a sanitized cause', async () => { const err = new Error('quota'); err.name = 'ServiceQuotaExceededException'; mockSend.mockRejectedValueOnce(err); @@ -1006,7 +791,7 @@ describe('LambdaMicrovmComputeStrategy', () => { await new LambdaMicrovmComputeStrategy() .startSession({ taskId: 'TASK001', userId: 'u', payload: {}, blueprintConfig: BLUEPRINT }) .catch((thrown: Error) => { - expect(thrown.cause).toBe(err); + expect(thrown.cause).not.toBe(err); expect((thrown.cause as Error).name).toBe('ServiceQuotaExceededException'); }); expect.assertions(2); @@ -1024,16 +809,16 @@ describe('LambdaMicrovmComputeStrategy', () => { test('marks a payload-upload failure so an S3 fault is attributed to this backend', async () => { const err = new Error('Access Denied'); err.name = 'AccessDenied'; - mockS3Send.mockRejectedValueOnce(err); + mockPrepare.mockRejectedValueOnce(err); const start = new LambdaMicrovmComputeStrategy().startSession({ taskId: 'TASK001', userId: 'cognito-test', - payload: payloadWithEnvelopeBytes(20_000), + payload: { prompt: 'x'.repeat(20_000) }, blueprintConfig: BLUEPRINT, }); - await expect(start).rejects.toThrow('MicroVM payload upload failed: AccessDenied: Access Denied'); + await expect(start).rejects.toThrow('MicroVM payload bootstrap failed: AccessDenied: Access Denied'); // Never reaches RunMicrovm — no half-started MicroVM on an upload fault. expect(mockSend).not.toHaveBeenCalled(); }); @@ -1101,7 +886,7 @@ describe('LambdaMicrovmComputeStrategy without the MicroVM substrate deployed', await expect(start).rejects.toThrow(new RegExp(envVar)); // Fails BEFORE any AWS call — no half-started MicroVM, no orphan S3 object. expect(mockSend).not.toHaveBeenCalled(); - expect(mockS3Send).not.toHaveBeenCalled(); + expect(mockPrepare).not.toHaveBeenCalled(); }); test('MICROVM_IMAGE_VERSION is optional — the field is omitted so the service picks the default', async () => { @@ -1195,7 +980,7 @@ describe('LambdaMicrovmComputeStrategy image-identifier validation', () => { userId: 'cognito-test', // Oversized on purpose: the guard must fire before the payload upload, or a // misconfiguration leaves orphan objects in the payload bucket. - payload: payloadWithEnvelopeBytes(20_000), + payload: { prompt: 'x'.repeat(20_000) }, blueprintConfig: BLUEPRINT, }); @@ -1205,7 +990,7 @@ describe('LambdaMicrovmComputeStrategy image-identifier validation', () => { // ...and the remedy. await expect(start).rejects.toThrow(/--context compute_type=lambda-microvm/); expect(mockSend).not.toHaveBeenCalled(); - expect(mockS3Send).not.toHaveBeenCalled(); + expect(mockPrepare).not.toHaveBeenCalled(); }); test('accepts a full image ARN', async () => { @@ -1259,8 +1044,8 @@ describe('buildMicrovmPlatformConfig — the MicroVM substitute for a deploy-tim expect([...MICROVM_PLATFORM_CONFIG_REQUIRED_KEYS]) .toEqual(sharedConstants.microvm_platform_config.required); - // Order is part of the contract: it is the serialization order, which the 4 KB - // inline/S3 branch decision is computed against. + // Keep the reviewed key inventory explicit. Payload/bootstrap hashing uses + // canonical JSON, so insertion order does not alter retry identity. expect([...MICROVM_PLATFORM_CONFIG_KEYS]).toEqual([ 'task_table_name', 'task_events_table_name', @@ -1474,18 +1259,6 @@ describe('buildMicrovmPlatformConfig — the MicroVM substitute for a deploy-tim const config = buildMicrovmPlatformConfig(); expect(config).toEqual(EXPECTED_PLATFORM_CONFIG); }); - - test('the full thirteen-key block fits the pointer envelope inside the 4 KB cap', () => { - // The one shape with no smaller fallback: if the pointer envelope itself - // exceeded 4 096 bytes there would be nothing left to move to S3. This asserts - // the design has real headroom rather than relying on the guard. - const pointerEnvelope = JSON.stringify({ - agent_payload_s3_uri: `s3://${PAYLOAD_BUCKET}/TASK001/payload.json`, - platform_config: buildMicrovmPlatformConfig(FULL_ENV), - }); - expect(Buffer.byteLength(pointerEnvelope, 'utf8')) - .toBeLessThan(MICROVM_RUN_HOOK_PAYLOAD_LIMIT_BYTES / 2); - }); }); describe('LambdaMicrovmComputeStrategy with the FULL platform_config environment', () => { @@ -1509,21 +1282,9 @@ describe('LambdaMicrovmComputeStrategy with the FULL platform_config environment for (const key of Object.keys(OPTIONAL_ENV)) delete process.env[key]; }); - test('delivers every configured identifier on the wire, in both envelope halves', async () => { - mockS3Send.mockResolvedValueOnce({}); - runMicrovmOk(); - - await new LambdaMicrovmComputeStrategy().startSession({ - taskId: 'TASK001', - userId: 'cognito-test', - payload: { repo_url: 'org/repo', hydrated_context: { blob: 'x'.repeat(10_000) } }, - blueprintConfig: BLUEPRINT, - }); - - const expected = { ...EXPECTED_PLATFORM_CONFIG, ...buildMicrovmPlatformConfig() }; - const envelope = JSON.parse(mockSend.mock.calls[0][0].input.runHookPayload); - expect(envelope.platform_config).toEqual(expected); - expect(Object.keys(envelope.platform_config)).toHaveLength(13); - expect(JSON.parse(mockS3Send.mock.calls[0][0].input.Body).platform_config).toEqual(expected); + test('passes every configured identifier to the authenticated manifest producer', async () => { + mockSend.mockResolvedValueOnce({ microvmId: MICROVM_ID, endpoint: ENDPOINT }); + await new LambdaMicrovmComputeStrategy().startSession({ taskId: 'TASK001', userId: 'u1', payload: {}, blueprintConfig: BLUEPRINT }); + expect(mockPrepare.mock.calls[0][0].platformConfig).toEqual(buildMicrovmPlatformConfig()); }); }); diff --git a/cdk/test/handlers/start-session-composition.test.ts b/cdk/test/handlers/start-session-composition.test.ts index 1d2e816b9..b60912b40 100644 --- a/cdk/test/handlers/start-session-composition.test.ts +++ b/cdk/test/handlers/start-session-composition.test.ts @@ -56,10 +56,17 @@ jest.mock('@aws-sdk/client-lambda-microvms', () => ({ }, })); -jest.mock('@aws-sdk/client-s3', () => ({ - S3Client: jest.fn(() => ({ send: jest.fn().mockResolvedValue({}) })), - PutObjectCommand: jest.fn((input: unknown) => ({ _type: 'PutObject', input })), - DeleteObjectCommand: jest.fn((input: unknown) => ({ _type: 'DeleteObject', input })), +// This suite checks strategy/metadata composition. Real bootstrap replay is +// covered by microvm-start-recovery and orchestrate-task-microvm. +jest.mock('../../src/handlers/shared/payload-bootstrap', () => ({ + ...jest.requireActual('../../src/handlers/shared/payload-bootstrap'), + preparePayloadReference: jest.fn(async ({ taskId }: { taskId: string }) => ({ + version: 2, + task_id: taskId, + bootstrap_s3_uri: 's3://bucket/bootstrap/example.json', + payload_url: 'https://signed.example/task', + expires_at: Date.now() + 900000, + })), })); jest.mock('../../src/handlers/shared/repo-config', () => ({ diff --git a/cdk/test/scripts/check-constants-sync.test.ts b/cdk/test/scripts/check-constants-sync.test.ts index 8e251e1d5..e2e8b82b7 100644 --- a/cdk/test/scripts/check-constants-sync.test.ts +++ b/cdk/test/scripts/check-constants-sync.test.ts @@ -62,6 +62,8 @@ const FIXTURE_FILES = [ 'agent/src/jira_reactions.py', 'agent/src/server.py', 'agent/src/config.py', + 'agent/src/payload_bootstrap.py', + 'cdk/src/handlers/shared/payload-bootstrap.ts', 'cdk/src/constructs/lambda-microvm-compute.ts', ]; @@ -126,6 +128,30 @@ describe('check-constants-sync', () => { // subprocess spawns, so give it room on a cold cache. jest.setTimeout(60_000); + describe('payload bootstrap contract', () => { + test.each([ + ['max_payload_bytes', 0], + ['minimum_url_lifetime_seconds', 901], + ['manifest_prefix', '../'], + ['launch_filename', 'payload.json'], + ])('rejects unsafe %s', (key, value) => { + const result = runInMutatedRepo(root => patchContract(root, json => { + json.payload_bootstrap[key] = value; + })); + expect(result.status).toBe(1); + expect(result.stderr).toContain('payload_bootstrap'); + }); + + test.each([ + ['agent/src/payload_bootstrap.py', 'CONTRACT = {}'], + ['cdk/src/handlers/shared/payload-bootstrap.ts', 'export const PAYLOAD_BOOTSTRAP = {};'], + ])('rejects a consumer with its own copy: %s', (file, source) => { + const result = runInMutatedRepo(root => write(root, file, source)); + expect(result.status).toBe(1); + expect(result.stderr).toContain('consumers must read the shared contract'); + }); + }); + describe('the real repository', () => { test('passes, and says what it actually checked', () => { const result = runInMutatedRepo(() => {}); diff --git a/cdk/test/stacks/agent.test.ts b/cdk/test/stacks/agent.test.ts index 95f1224e8..32bb732c9 100644 --- a/cdk/test/stacks/agent.test.ts +++ b/cdk/test/stacks/agent.test.ts @@ -1372,9 +1372,16 @@ describe('AgentStack with the Lambda MicroVMs substrate gate (--context compute_ const actions = payloadStatements.flatMap(s => Array.isArray(s.Action) ? s.Action : [s.Action]); expect(actions).toContain('s3:PutObject'); - // The bucket's lifecycle rule is the reaper on this backend — unlike the ECS - // path the orchestrator never deletes, so the grant must not exist. - expect(actions).not.toContain('s3:DeleteObject'); + expect(actions).toContain('s3:DeleteObject'); + expect(actions).toContain('s3:GetObject'); + expect(actions).toContain('s3:ListBucket'); + const deletion = payloadStatements.find(s => Array.isArray(s.Action) && s.Action.includes('s3:DeleteObject')); + expect(deletion!.Resource).toEqual(['payload.json', 'launch.json'].map(filename => ({ + 'Fn::Join': ['', [ + { 'Fn::GetAtt': [expect.stringMatching(/^LambdaMicrovmComputePayloadBucket/), 'Arn'] }, + `/*/${filename}`, + ]], + }))); }); test('cancel Lambda may terminate a MicroVM (and only terminate), image-scoped', () => { diff --git a/contracts/constants.json b/contracts/constants.json index 174812d40..c4f4c3a1a 100644 --- a/contracts/constants.json +++ b/contracts/constants.json @@ -65,6 +65,15 @@ ], "account_anchor_key": "agent_session_role_arn" }, + "payload_bootstrap": { + "version": 2, + "manifest_prefix": "bootstrap/", + "launch_filename": "launch.json", + "max_manifest_bytes": 16384, + "max_payload_bytes": 8388608, + "url_ttl_seconds": 900, + "minimum_url_lifetime_seconds": 300 + }, "microvm_hook_budgets": { "ready_hook_timeout_seconds": 300, "warmup_total_budget_seconds": 240, diff --git a/contracts/constants.md b/contracts/constants.md index c9224ce3d..3bf857283 100644 --- a/contracts/constants.md +++ b/contracts/constants.md @@ -21,6 +21,8 @@ the contract. This is the neutral location both runtimes read. |---|---|---| | `agent/src/shared_constants.py` | `/app/contracts/constants.json` | import-time | | `agent/src/policy.py`, `agent/src/jira_reactions.py` | `SHARED_CONSTANTS` | import-time | +| `agent/src/payload_bootstrap.py` | `SHARED_CONSTANTS["payload_bootstrap"]` | import-time | +| `cdk/src/handlers/shared/payload-bootstrap.ts`, `cdk/src/constructs/payload-bootstrap-permissions.ts` | `payload_bootstrap` | import-time | | `agent/src/server.py` | `SHARED_CONSTANTS["microvm_platform_config"]`, `SHARED_CONSTANTS["microvm_hook_budgets"]` | import-time | | `cdk/src/handlers/shared/types.ts`, `jira-app-actor.ts` | `../../../../contracts/constants.json` | synth-time `import` | | `cdk/src/handlers/shared/strategies/lambda-microvm-strategy.ts` | `microvm_platform_config` | synth-time `import`, read per session start | @@ -77,6 +79,15 @@ JSON at TypeScript compile time via `resolveJsonModule`. "jira_oauth_secret_arn", "agent_session_role_arn"], "account_anchor_key": "agent_session_role_arn" }, + "payload_bootstrap": { + "version": 2, + "manifest_prefix": "bootstrap/", + "launch_filename": "launch.json", + "max_manifest_bytes": 16384, + "max_payload_bytes": 8388608, + "url_ttl_seconds": 900, + "minimum_url_lifetime_seconds": 300 + }, "microvm_hook_budgets": { "ready_hook_timeout_seconds": 300, "warmup_total_budget_seconds": 240, @@ -121,7 +132,7 @@ JSON at TypeScript compile time via `resolveJsonModule`. variable the agent installs it as (UPPER_SNAKE). This block is unlike the others — it is a **security allowlist**, not a tuning bound. The MicroVM image is a snapshot whose env is frozen at build time, so the agent's non-secret - platform env arrives in the `/run` hook payload instead; the values land in + platform env arrives through an authenticated v2 manifest and task payload instead; the values land in `os.environ`, which makes an unrecognised key an env-injection attempt. The consumer (`agent/src/server.py`) therefore **rejects** any `platform_config` carrying a key that is not in this map. Values are non-secret identifiers @@ -138,15 +149,15 @@ JSON at TypeScript compile time via `resolveJsonModule`. that disagrees with the anchor below on partition or account, is rejected (HTTP 400 `MICROVM_RUN_PLATFORM_CONFIG_INVALID`). This is **fail-fast plus defence in depth, not an ownership proof** — the account-scoped IAM grants are - what actually deny a foreign read, and an in-account redirect is deliberately - *not* covered (see `MICROVM_PLATFORM_CONFIG_ARN_KEYS` in - `agent/src/server.py` for the full statement of what this does and does not buy). + what actually deny a foreign read, and this ARN check alone does not cover an in-account redirect. The v2 bootstrap + authenticates a deployment manifest with IAM and requires the downloaded config + to match it; that separate check rejects same-account workspace substitutions. - **`microvm_platform_config.account_anchor_key`** — which `arn_keys` entry supplies the expected partition + account. Must be `agent_session_role_arn`-shaped: a payload key rather than `os.environ` or an `sts:GetCallerIdentity`, because the environment is empty by construction on this backend (the snapshot bakes nothing) - and this check runs on the path that must make zero AWS calls beyond the S3 - payload fetch. Two invariants follow and both are enforced: the anchor must be in + and the ARN consistency check itself makes no AWS calls. The v2 bootstrap + manifest read and signed task download precede it. Two invariants follow and both are enforced: the anchor must be in `arn_keys`, **and** it must be in `required` — an optional anchor would let a payload disarm the whole check by simply omitting it. @@ -159,6 +170,18 @@ duplication is deliberate: a malformed entry here would silently **widen** what agent accepts from a network payload, so neither side is trusted to be the only gate. +- **`payload_bootstrap`** — the shared ECS/MicroVM v2 transport. `version` is + required on references, manifests and task documents. `manifest_prefix` and + `launch_filename` define the authenticated settings directory and private retry + record. Byte limits bound manifest and task downloads; URL lifetime is at most + `url_ttl_seconds`, shortened by known signer credential expiry, with initial + creation requiring `minimum_url_lifetime_seconds`. The constants checker + rejects nonpositive/noninteger bounds, unsafe/colliding paths, a minimum above + its maximum, and consumers that stop reading the shared block. Changing the + protocol requires matching coordinator, worker images and policies; old unsigned + transports are rejected. See repository runbook + `docs/verification/645-payload-bootstrap.md` for rollout and live checks. + - **`microvm_hook_budgets.ready_hook_timeout_seconds`** — the `/ready` build-hook budget the CDK construct declares to `CreateMicrovmImage` (`READY_HOOK_TIMEOUT_SECONDS` in `cdk/src/constructs/lambda-microvm-compute.ts`). diff --git a/docs/decisions/ADR-021-lambda-microvms-compute-backend.md b/docs/decisions/ADR-021-lambda-microvms-compute-backend.md index 79b984ffc..b4199e72c 100644 --- a/docs/decisions/ADR-021-lambda-microvms-compute-backend.md +++ b/docs/decisions/ADR-021-lambda-microvms-compute-backend.md @@ -197,25 +197,28 @@ The binary was fine — in the identical image, locally, `claude --version` answ Both halves of the fix are kept, because they answer different questions. `/ready` now **exec's the heavyweight binaries before returning 200** (`claude` required, `git`/`node` best-effort), which is the only mechanism that can make the shipped snapshot warm — and its own budget rises to 300 s, well inside the 3600 s build-hook window, because it now does work whose duration is a cold `exec`. Two structural rules keep that honest, because **per-command timeouts do not compose**: the required command runs FIRST with its own budget so no best-effort warm-up can starve the one that decides whether the snapshot is usable, and the best-effort ones then SHARE the remainder of a total warm-up ceiling that sits inside the hook budget with margin (240 s against 300 s). Without them, three commands at 120 s each would be 360 s — a fix for a runtime failure that produces a build failure instead — and a single hung optional command could hold up a 200 that the required warm-up had already earned. Separately, the version probe's timeout goes from 10 s to 60 s: a probe that exists to print a version string into a log line gains nothing from a tight bound and loses the whole task when it trips. The general rule this generalises to, and the reason it belongs in the ADR rather than only in a comment: **on this backend, a first-touch cost that other substrates pay during container start is deferred to the first task instead**, so anything large and lazily-loaded is a turn-0 hazard unless it is touched in `/ready`. -**Payload delivery** reuses the ECS strategy's S3-pointer pattern, adapted to `runHookPayload` (**≤ 4 KB** — measured, see below): payloads that fit ride inline; the rest are uploaded by the strategy to a platform payload bucket (the ECS payload bucket pattern in `ecs-agent-cluster.ts`: orchestrator write access, compute-role read-only scoped to the bucket, lifecycle expiry on objects) with the S3 URI in `runHookPayload` in place of the payload itself — the MicroVM **execution role** holds the read grant, exactly as the ECS task role does today. Since P2 the hook body also carries `platform_config` in both branches, so `runHookPayload` is never *only* the URI (see the canonical shapes below). +**Payload delivery — v2 amendment (2026-09-13, #817/#700).** The local implementation now shares an authenticated bootstrap protocol between ECS and MicroVM. This replaces the original inline/S3-pointer protocol and broad worker payload-bucket read grant. The historical P1/P2 runs below predate this amendment; AWS authorization, networking, expiry and coordinated deployment validation remain pending. The repository runbook is `docs/verification/645-payload-bootstrap.md`. -The cap is **4 096 bytes**, not the 16 384 the SDK documents. Measured exactly: 4 096 passes, 4 097 is rejected with *"Value at 'runHookPayload' failed to satisfy constraint: Member must have length less than or equal to 4096"*. Two consequences follow. First, the original threshold would have inlined every envelope between 4 097 and 16 384 bytes and had the service reject all of them. Second, and more structurally: **the S3-pointer path is now the dominant one, and inline is the exception.** A hydrated task payload (prompt + issue thread + repo context) essentially always exceeds 4 KB, so "small payloads ride inline" describes tiny repo-less prompts rather than the common case. The payload bucket is therefore not a rarely-exercised overflow valve but a required part of every normal task, which raises its lifecycle rule (`MICROVM_PAYLOAD_TTL_DAYS`) and the execution role's read grant from edge-case plumbing to load-bearing. +Every task uses S3. The coordinator publishes a non-secret deployment manifest at `bootstrap/.json`, conditionally creates `/payload.json`, and sends a short-lived signed URL for that one task object. The worker reads the manifest with its own AWS role, whose policy explicitly denies object reads outside its deployment's `bootstrap/*` and denies payload-bucket listing. The explicit deny also prevents a foreign public bucket from authenticating a forged manifest. The task document must name the reference's task ID and contain the exact manifest configuration before the MicroVM installs any of it. -**Canonical wire shapes.** Three, and the producer (`lambda-microvm-strategy.ts`) emits exactly these: +The `runHookPayload` cap remains **4,096 bytes**, measured against the service despite the SDK's documented 16,384. It now applies to the serialized reference rather than choosing an inline branch. Payloads are capped at 8 MiB and manifests at 16 KiB; the bounds and version are shared in `contracts/constants.json`. -| Where | Exact shape | +| Location | v2 shape | |---|---| -| `runHookPayload`, inline branch | `{"agent_payload": {…}, "platform_config": {…}}` | -| `runHookPayload`, pointer branch | `{"agent_payload_s3_uri": "s3://…", "platform_config": {…}}` | -| the object at that S3 URI | `{…agent_payload fields…, "platform_config": {…}}` — the payload's own fields at the TOP level, with the config merged in beside them | +| `runHookPayload` string / ECS `AGENT_PAYLOAD_REF` | `{version:2, task_id, bootstrap_s3_uri, payload_url, expires_at}` | +| `bootstrap/.json` | `{version:2, backend, platform_config}` | +| `/payload.json` | `{version:2, task_id, agent_payload, platform_config}` | +| Private `/launch.json` | `{fingerprint, reference}`; coordinator-readable only, never on the agent-readable task row | -Two asymmetries are deliberate and must not be "tidied" without changing both sides. First, **the S3 object is not the envelope**: the payload's fields sit at the top level (that is what P1 uploaded, before `platform_config` existed) rather than nested under an `agent_payload` key. Second, **`platform_config` is duplicated** on the pointer path — once beside the pointer, once inside the uploaded object. It costs a few hundred bytes and buys the property that the config is reachable whichever end of the fetch a reader looks at, which matters because it is the agent's only substitute for an env block. +The coordinator saves the exact reference for replay: re-signing would change a Run request with the same client token. Task objects use conditional creation and read-back recovery after a lost committed write. URL lifetime is at most 900 seconds, bounded by known credential expiry, and initial creation requires at least 300 seconds. Expired saved references fail without re-signing. The coordinator needs bucket-scoped `ListBucket` so an absent launch record returns `NoSuchKey` rather than `AccessDenied`. It deletes both task objects at finalization; one-day lifecycle expiry is the backstop. Manifests are refreshed with identical bytes at preparation and may coexist across configuration revisions until lifecycle cleanup. -The agent's reader is deliberately more permissive than this contract: it also accepts an S3 object shaped like the envelope (`agent_payload` nested), and `platform_config` present in only one of the two places (the fetched object wins, the hook body is the fallback). Those are **defensive compatibility** for the independent deploy cadences of a snapshot image and the orchestrator Lambda — a tolerant reader, not an alternative contract. A producer must emit the three shapes above. +The image accepts only v2. The old inline/pointer forms and baked-environment fallback are rejected. A coordinated drain and switch of coordinator, images and application IAM is required; there is no new KMS/SSM resource or bootstrap bundle version. Signed URLs are bearer capabilities and must never appear in task rows, ordinary logs or repository subprocess environments. ECS consumes/removes its reference before importing the task pipeline. The URL consumer restricts requests to the exact task object on regional S3 HTTPS, disables redirects/proxies and bounds response bytes. AWS verifies signatures and actual expiration. -**Platform configuration delivery (P2): payload-sourced, allowlisted, fail-closed.** The other two backends hand the agent its non-secret platform env at launch — AgentCore Runtime env vars, ECS container overrides — and there is no equivalent on this substrate: a MicroVM starts from a **snapshot**, so its process environment is whatever was frozen at *image build* time and is then replayed by every MicroVM launched from that image version. Baking the deployment's identifiers into the snapshot would make them **version-frozen**: a redeploy that renames a table, adds a bucket or rotates the session role would leave every existing image version describing a deployment that no longer exists, and the drift would surface as a task-time `ResourceNotFound` rather than a deploy-time error. So the values travel with the task instead: `platform_config` is a SIBLING of the payload — beside `agent_payload` in the inline branch, beside `agent_payload_s3_uri` in the pointer branch, and merged in beside the payload's own fields inside the S3 object (the canonical shapes above give each one exactly) — whose snake_case keys the agent installs into `os.environ` as their UPPER_SNAKE equivalents. A payload value therefore **wins** over any pre-existing/image value — the orchestrator is describing the live deployment, the snapshot is describing a past one. `platform_config` carries **non-secret identifiers only** (table and bucket names, secret ARNs, the session-role ARN); secrets are still fetched at `/run` time from Secrets Manager using those ARNs, so the snapshot-must-stay-secret-free requirement above is untouched. Per-task fields — `memory_id` and friends — stay inside `agent_payload`: `platform_config` configures the *process*, `agent_payload` describes the *task*. +**Platform configuration delivery (P2, strengthened by v2).** A MicroVM restores a snapshot, including its process environment, so current deployment identifiers must arrive at task launch. The authenticated manifest and downloaded document both contain `platform_config`: non-secret table/bucket names, secret ARNs and session-role ARN. Per-task fields such as `memory_id` remain in `agent_payload`. ECS's manifest config is empty because ECS already receives deployment settings through its task definition and coordinator overrides. -Two rules make it safe. First, **the allowlist fails closed**: the agent installs a fixed set of keys and *rejects the entire run* (HTTP 400, nothing spawned, not one key installed) if the block carries anything else. These values become environment variables of the process that spawns the agent's tool subprocesses, so an unrecognised key is an attempt to set an arbitrary variable in the agent (`AWS_ENDPOINT_URL`, `LD_PRELOAD`, `PATH`, …) — an injection attempt, not a forward-compatibility gap, which is why unknown keys are refused rather than filtered out. Second, **installation happens before any credential or pipeline initialisation** on the hook path: the very next step reads `GITHUB_TOKEN_SECRET_ARN` to resolve the GitHub token and `AGENT_SESSION_ROLE_ARN` to scope the task's credentials, so installing later would silently resolve the whole task against the snapshot's frozen env. The one call that must precede installation is the S3 payload fetch (the config is *inside* the fetched object), which therefore runs on the ambient compute role via the attributed platform client — and it is the ONLY one: the same rule covers **logging**, so every `/run` log line before the install is stdout-only. The CloudWatch writer would otherwise resolve credentials and pin a boto3 default session (region included) off whatever a snapshot happened to bake, which is the build-hook defect one phase later. Nothing is lost — in the intended deployment there is no baked `LOG_GROUP_NAME`, so those lines would have gone to stdout anyway, and the reason for every pre-install rejection also travels in the structured 4xx/5xx body the service surfaces. A **required subset** (task table, task-events table, GitHub token secret ARN, session-role ARN) is rejected as `…_INCOMPLETE` when missing or blank — a distinct wire code from the `…_INVALID` allowlist rejection, because the remedies differ (deployment wiring vs. producer bug). A `/run` envelope with *no* `platform_config` at all is still accepted, loudly warned: the image snapshot and the orchestrator Lambda deploy on independent cadences, and a new image must not require a same-instant orchestrator. The key set is a cross-package contract in `contracts/constants.json` (`microvm_platform_config`), consumed by the agent's `/run` hook and produced by the orchestrator, with shape and required-subset invariants enforced by `scripts/check-constants-sync.ts`. +MicroVM installs only allowlisted keys and rejects unknown keys before installing any. Required identifiers must be nonblank; malformed/control-character values and inconsistent ARN partitions/accounts are rejected. Legitimate cross-region secrets remain allowed when present in the trusted manifest. Account agreement alone cannot authenticate a sibling ARN; v2's manifest/config comparison supplies the provenance check. No-config envelopes are rejected regardless of the image's existing environment. + +Manifest read and signed payload download precede configuration installation. Secrets, task-scoped credential setup, CloudWatch initialization and the pipeline follow installation; pre-install diagnostics use stdout without unsafe exception chains. Build hooks remain AWS-silent. The settings allowlist and bootstrap bounds are cross-language contracts with drift checks. These source guarantees do not establish complete hostile-worker isolation: roles still retain other platform grants and choose session tags, and a stolen signed URL remains usable until expiry or revocation. **No orchestrator→agent HTTP path exists in P1–P3**: payload arrives through the `/run` hook, all agent work is outbound, and therefore **no JWE auth tokens are minted at all** — token minting (and its ≤ 60 min TTL refresh problem) is deferred until a real consumer exists (e.g. operator shell access, [#391](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/391)). The `endpoint` stays in the `SessionHandle` because it is genuinely per-session state that becomes load-bearing the day such a consumer appears. But note the service does not agree by default: omitting `ingressNetworkConnectors` on `RunMicrovm` attaches a **public** `HTTP_INGRESS` connector, so the strategy passes the Lambda-managed `NO_INGRESS` connector explicitly on every launch (see sub-decision 4's security table). @@ -224,12 +227,12 @@ Two rules make it safe. First, **the allowlist fails closed**: the agent install Normative requirements (EARS). **Each requirement's own `(Pn)` tag is authoritative**; there is no blanket phase for the list. The tags are per-requirement because the original list *was* split P1/P2 on the assumption that a hook could be declared in one phase and served in a later one — which the service does not permit (see the phasing table above), so the hook-serving requirements collapsed into P1 while the P2 items below arrived with the P2 hooks and `platform_config`: - (P1) The image build shall not embed secrets, tokens, or per-task identity in the snapshot. -- (P1) If the task payload exceeds the 4 KB `runHookPayload` limit, then the strategy shall upload the payload to the platform payload bucket and pass its S3 URI in `runHookPayload` in place of the payload (from P2, alongside `platform_config`). -- (P1) The MicroVM execution role shall hold read-only access to the payload bucket, scoped to that bucket. +- (P1, amended by v2) Every task shall use the authenticated manifest and single-object signed payload reference; the serialized hook reference shall not exceed 4,096 bytes. +- (P1, amended by v2) The worker role shall read only deployment bootstrap manifests with ambient credentials; other object reads and payload-bucket listing shall be explicitly denied. The coordinator shall own task-object writes, signing, replay and deletion. - (P1) Where no ingress is configured for a deployment, the strategy shall pass the Lambda-managed `NO_INGRESS` network connector on every `RunMicrovm` call (the field shall not be omitted). - (P1) Where the image enables any MicroVM lifecycle hook, the image shall also enable the `/ready` hook and the agent shall serve it. - (P1) When the `/run` hook receives the task payload, the agent shall validate it, start the pipeline asynchronously, and return HTTP 200 within the hook budget. -- (P1) If the `/run` hook payload cannot be resolved to a task payload, then the agent shall reject the hook with a client error and shall not start a pipeline. +- (P1, clarified) Invalid hook references shall return a structured client error; unreadable manifest/payload bytes shall return a structured server error. Neither path shall install configuration or start a pipeline. - (P1) The agent shall not execute the clone→verify→PR pipeline on the hook path. - (P1) The agent shall resolve credentials at `/run` time. - (P1) Where a deployment configures a MicroVM image before smoke parity is verified, the platform shall warn that the backend has no smoke-parity guarantee. @@ -394,8 +397,8 @@ Lambda MicroVMs launched in 5 regions (us-east-1/2, us-west-2, eu-west-1, ap-nor **P1 (start/poll/stop — no suspend):** -- Unit tests for the strategy: start/poll/stop mapping (including `SessionStatus` `'suspended'` reported mechanically, without task-state interpretation), payload-size branching (inline vs S3 pointer, at the exact 4 096/4 097-byte boundary), the image-identifier-must-be-an-ARN guard, the explicit `NO_INGRESS` argument (including the blank-env-var fallback, which must never omit the field), error classification (`ServiceQuotaExceededException`, `ThrottlingException`, `ResourceNotFoundException`, regional-unavailability), the omit-`idlePolicy` invariant, and `maximumDurationInSeconds` fixed at 28 800. -- Agent tests: `/ready` returns 200 once the server is up and starts nothing; `/run` accepts both envelope shapes (inline and S3 pointer), starts the pipeline asynchronously through the same mapper `/invocations` uses, returns before the pipeline finishes, and rejects every unusable envelope with a named code before spawning; `/suspend` and `/resume` are NOT served (`/validate` and `/terminate` joined the served set in P2). +- Unit tests for the strategy: start/poll/stop mapping (including `SessionStatus` `'suspended'` reported mechanically, without task-state interpretation), v2 reference-size bounds (4,096 bytes), immutable signed-reference replay and scoped payload transport, the image-identifier-must-be-an-ARN guard, the explicit `NO_INGRESS` argument (including the blank-env-var fallback, which must never omit the field), error classification (`ServiceQuotaExceededException`, `ThrottlingException`, `ResourceNotFoundException`, regional-unavailability), the omit-`idlePolicy` invariant, and `maximumDurationInSeconds` fixed at 28 800. +- Agent tests: `/ready` returns 200 after required local warm-up succeeds, without starting a task or calling AWS; `/run` accepts authenticated v2 references and rejects old unsigned envelopes, starts the pipeline asynchronously through the same mapper `/invocations` uses, returns before the pipeline finishes, and rejects every unusable envelope with a named code before spawning; `/suspend` and `/resume` are NOT served (`/validate` and `/terminate` joined the served set in P2). - Orchestrator tests: substrate-terminal + non-terminal task status → failed classification; `suspended` + non-`AWAITING_APPROVAL` status → anomaly event, no fail-fast; `compute_metadata` persisted with `microvmId`/`endpoint` after `startSession`. - CDK assertions: MicroVM resources present only when `ComputeTypes` includes the backend; synth failure for unsupported regions (plus the context-flag escape hatch); memory size validated against the accepted list at synth; the connector operator role and its trust; two connectors with the build-only one carrying port 80 and the runtime one not; the `/ready` + `/run` hook declaration and the absence of the others; IAM actions scoped as specified (orchestrator lifecycle set; no `CreateMicrovmAuthToken` anywhere); payload-bucket grants (execution role read-only); backend cost-allocation tags; types-sync check covers the widened `ComputeType`. - CLI tests: onboarding rejection with remedy when the availability probe fails; doctor check present when a blueprint selects the backend. @@ -404,7 +407,7 @@ Lambda MicroVMs launched in 5 regions (us-east-1/2, us-west-2, eu-west-1, ap-nor **P2 (smoke parity):** - Agent tests: `/validate` returns 200 with its individual check results, 503 while initialising, reports a missing hook route / unsupported interpreter, starts nothing, and makes **zero AWS calls even with `LOG_GROUP_NAME` set** (asserted by poisoning the boto3 and CloudWatch-writer seams — the same assertion covers `/ready`); `/terminate` returns 200 with no body at all, with a malformed / non-object / wrong-content-type / whitespace-only body, when the body read itself fails, with a pipeline still running (without joining it), and when its own best-effort step raises — and never calls `task_state.write_terminal`; a structural assertion that the route carries no typed body param keeps the 422 from being reintroduced. -- `platform_config` tests: the allowlist and required subset are read from `contracts/constants.json` (the wire key set is additionally asserted literally, as the agent-side tripwire on a contract edit); an unknown key rejects the whole block with nothing installed; a non-object block and a non-string value are rejected; a blank/`null` optional value is skipped without clobbering an image value while a blank required value is rejected; a payload value beats a pre-existing env value; installation is observed to happen before the GitHub-token resolver runs and before any pipeline thread exists; the config is picked up from the inline envelope, from beside the S3 pointer, and from inside the fetched object (inner wins); an envelope with no `platform_config` is still accepted with a warning. +- `platform_config` tests: the allowlist and required subset are read from `contracts/constants.json` (the wire key set is additionally asserted literally, as the agent-side tripwire on a contract edit); an unknown key rejects the whole block with nothing installed; a non-object block and a non-string value are rejected; a blank/`null` optional value is skipped without clobbering an image value while a blank required value is rejected; a payload value beats a pre-existing env value; installation is observed to happen before the GitHub-token resolver runs and before any pipeline thread exists; the downloaded config must equal the IAM-authenticated manifest, including same-account workspace identifiers; missing config and legacy envelopes are rejected regardless of baked environment values. Transport tests cover signed URLs, exact task identity, bad bytes and rejection before installation. - Snapshot credential hygiene: a subprocess probe asserts that importing `server` and serving `/ready` + `/validate` imports neither `boto3` nor `botocore`, caches no `aws_session` session, and spawns no CloudWatch writer thread — the property that keeps a build-role credential chain and the build-time region out of the snapshot. - `/run` pre-install silence: with a **baked `LOG_GROUP_NAME`** (the hostile case — without it the assertions pass vacuously) every AWS/credential seam (`boto3.client`/`Session`, the `aws_session` factories, `_debug_cw`/`_warn_cw`) is armed to raise until the install succeeds. Asserted on the accepted path, on all three rejection paths (bad envelope, `platform_config` invalid, `platform_config` incomplete) and on the failed-fetch 500 — where the seams stay armed for the whole request, because a rejected run installed nothing and so earns no AWS call. The permitted exception is asserted POSITIVELY: exactly one client is built pre-install, for `s3`, through the attributed factory. - `/ready` warm-up tests (P2-F5): the hook exec's each configured binary exactly once with a generous timeout; `claude` is the only REQUIRED entry; a timeout, a missing binary, a non-zero exit and an unexpected `OSError` each produce **503 with the reason logged to stdout** rather than a 200 or a 500; a best-effort failure still reports ready; the warm-up makes zero AWS calls with `LOG_GROUP_NAME` baked. Plus the backstop half: the `claude --version` probe's bound is asserted to be ≥ 60 s and to be applied to the *exec* rather than to the PATH lookup, and a missing CLI warns instead of raising. diff --git a/docs/design/COMPUTE.md b/docs/design/COMPUTE.md index b74ee18ce..60354a7b7 100644 --- a/docs/design/COMPUTE.md +++ b/docs/design/COMPUTE.md @@ -117,7 +117,7 @@ See [ORCHESTRATOR.md](./ORCHESTRATOR.md) for how the orchestrator handles these Lambda MicroVMs are an opt-in third backend. Include `lambda-microvm` in `compute_types`; repositories inherit the first listed backend or choose a deployed backend through an override. Legacy `compute_type=lambda-microvm` deploys AgentCore and MicroVM, with AgentCore as the default. Image configuration has three states: a managed base-image ARN and version creates the snapshot image in CDK; an external image identifier uses a snapshot built out of band; and supplying neither provisions only the roles, buckets, and connectors needed for the bootstrap deploy. `cdk/scripts/package-microvm-artifact.sh` packages the agent as zip + Dockerfile, uploads it to the artifact bucket, and can create the external image. Lambda MicroVMs are available in five launch regions (us-east-1, us-east-2, us-west-2, eu-west-1, ap-northeast-1) and will expand; the platform enforces regional availability in layers via a synth-time constant, onboarding live probes, and orchestration-time classification. -Because a snapshot freezes its build-time environment, deployment-specific, non-secret identifiers travel in the `/run` hook's `platform_config` block instead. The strategy sends the canonical inline envelope or, when that envelope exceeds the verified 4,096-byte `runHookPayload` limit, an S3-pointer envelope with the configuration also merged into the uploaded payload. The agent accepts only allowlisted keys and installs them before pipeline initialization; [ADR-021 §3](../decisions/ADR-021-lambda-microvms-compute-backend.md#3-packaging-same-agent-image-source-new-build-path) defines the exact wire shapes and validation rules. +Because a snapshot freezes its build-time environment, current deployment identifiers arrive through the v2 payload bootstrap. The coordinator publishes a non-secret deployment manifest and sends a single-object signed download URL for the task. The worker reads only its deployment's `bootstrap/*` with ambient credentials; other object reads and payload-bucket listing are explicitly denied. The downloaded task identity and configuration must match the authenticated manifest before configuration installation. The serialized reference fits the verified 4,096-byte hook limit; all payload sizes use S3. ECS shares this transport through `AGENT_PAYLOAD_REF`. [ADR-021 §3](../decisions/ADR-021-lambda-microvms-compute-backend.md#3-packaging-same-agent-image-source-new-build-path) defines the wire format, compatibility change and pending live gates. Networking separates image build from execution: the build-only connector permits TCP 80 and 443 because the Dockerfile uses `apt-get`, while running MicroVMs retain 443-only egress through the platform VPC. Every launch explicitly passes the Lambda-managed `NO_INGRESS` connector; omission would select the service's public-ingress default. The P2 image declares and serves `/ready` and `/validate` at build time and `/run` and `/terminate` at runtime. `/suspend` and `/resume` remain disabled until their P3 implementation. diff --git a/docs/design/SECURITY.md b/docs/design/SECURITY.md index 3935d020e..59b11b8a5 100644 --- a/docs/design/SECURITY.md +++ b/docs/design/SECURITY.md @@ -46,7 +46,10 @@ Three authentication mechanisms protect the platform, matching its input channel The compute role retains only non-tenant access (Bedrock model invocation — already ARN-scoped; CloudWatch Logs; the GitHub PAT secret, read once before the SessionRole is assumed; AgentCore Memory) plus `sts:AssumeRole`/`sts:TagSession` on the SessionRole. Because the agent runs under credentials that are themselves an assumed role, its `AssumeRole` is *role chaining* — capped at one hour regardless of the role's max session duration — so the agent uses a **refreshable** credential provider that re-assumes before expiry (tasks can run up to the 8-hour `maxLifetime`). The design is backend-agnostic: the same SessionRole and agent code serve all three backends (AgentCore Runtime, ECS Fargate, Lambda MicroVMs). A compromised agent session is therefore confined to its own task's data, enforced at the IAM layer rather than by application-code conventions. The policy structure (the `dynamodb:LeadingKeys` condition on `${aws:PrincipalTag/task_id}`, per-user S3 prefixes, and `Scan` exclusion) is asserted by CDK template tests, and the refreshable-credential and session-tag flow by agent unit tests; the matching-tag → allow / mismatched-or-absent-tag → deny behaviour was additionally confirmed once via the IAM policy simulator during development. -**Lambda MicroVMs compute-role delta** - On this backend the compute role additionally holds prefix-scoped `secretsmanager:GetSecretValue` on the per-workspace channel-OAuth secrets (`bgagent-linear-oauth-*`, `bgagent-jira-oauth-*`), read access to the `/run` payload bucket (the task payload arrives as an S3 object, not as environment), and `ec2:DescribeAvailabilityZones` (`Resource: *`, read-only — EC2 describe actions have no resource-level scoping) for a CDK repo's own synth gate. It is also **the only compute role in the platform whose trust policy carries no confused-deputy condition**: the Lambda MicroVMs service populates no `aws:SourceAccount` or `aws:SourceArn` when it assumes the role, so a trust policy carrying one is unassumable — verified live, not assumed (connector creation failed deterministically, and `RunMicrovm` surfaced the same root cause as a misleading caller-side `iam:PassRole` denial). The compensating controls are that each of the three MicroVM roles can be passed to `lambda.amazonaws.com` only by a named principal — the orchestrator, via an `iam:PassRole` scoped to the execution role's exact ARN, and the CloudFormation deployment role for the build and connector-operator roles — that every other resource they reach is account-scoped by ARN apart from two justified `Resource: *` read/create-time statements, and that none of them holds `iam:*`, cross-account trust, or any `sts:AssumeRole` beyond the execution role's scoped hop to the per-task SessionRole. Full evidence, the two-arm PassRole experiment, and the alternatives considered are in [ADR-021 §4](../decisions/ADR-021-lambda-microvms-compute-backend.md#4-infra-and-iam-conditional-resources-behind-bootstrap-computetypes). +**Lambda MicroVMs compute-role delta** - On this backend the compute role additionally holds prefix-scoped `secretsmanager:GetSecretValue` on the per-workspace channel-OAuth secrets (`bgagent-linear-oauth-*`, `bgagent-jira-oauth-*`), read access only to its payload bucket's `bootstrap/*` manifests (other object reads and payload-bucket listing are explicitly denied), and `ec2:DescribeAvailabilityZones` (`Resource: *`, read-only — EC2 describe actions have no resource-level scoping) for a CDK repo's own synth gate. It is also **the only compute role in the platform whose trust policy carries no confused-deputy condition**: the Lambda MicroVMs service populates no `aws:SourceAccount` or `aws:SourceArn` when it assumes the role, so a trust policy carrying one is unassumable — verified live, not assumed (connector creation failed deterministically, and `RunMicrovm` surfaced the same root cause as a misleading caller-side `iam:PassRole` denial). The compensating controls are that each of the three MicroVM roles can be passed to `lambda.amazonaws.com` only by a named principal — the orchestrator, via an `iam:PassRole` scoped to the execution role's exact ARN, and the CloudFormation deployment role for the build and connector-operator roles — that every other resource they reach is account-scoped by ARN apart from two justified `Resource: *` read/create-time statements, and that none of them holds `iam:*`, cross-account trust, or any `sts:AssumeRole` beyond the execution role's scoped hop to the per-task SessionRole. Full evidence, the two-arm PassRole experiment, and the alternatives considered are in [ADR-021 §4](../decisions/ADR-021-lambda-microvms-compute-backend.md#4-infra-and-iam-conditional-resources-behind-bootstrap-computetypes). + +**ECS/MicroVM task bootstrap (v2)** — The coordinator publishes non-secret deployment manifests and supplies a short-lived signed URL for exactly one task's payload. The worker reads the manifest with its ambient role, whose explicit deny outside its own `bootstrap/*` prevents a foreign public bucket from authorizing fake configuration. It verifies downloaded task identity and exact manifest/config agreement before installing MicroVM settings. The coordinator privately persists the URL outside TaskTable for retry and deletes both task objects at finalization. Worker roles cannot read/list task objects using their ambient credentials. A signed URL is a bearer capability: redact it in errors and keep it out of task rows and repository subprocess environments. Existing session-tag trust and other platform grants remain separate limitations. This protocol is implemented locally; real IAM/network/expiry gates and the coordinated image/coordinator/policy rollout are documented in the repository's `docs/verification/645-payload-bootstrap.md`. + > Out of scope for this control and tracked separately as GitHub issues: replacing the shared GitHub PAT (GitHub App / Token Vault), binding credentials to the MicroVM via attestation, and scoping AgentCore Memory (namespace isolation by `actorId`/`sessionId` remains its boundary). diff --git a/docs/src/content/docs/architecture/Compute.md b/docs/src/content/docs/architecture/Compute.md index d9a6603fa..61a7bfaed 100644 --- a/docs/src/content/docs/architecture/Compute.md +++ b/docs/src/content/docs/architecture/Compute.md @@ -121,7 +121,7 @@ See [ORCHESTRATOR.md](/sample-autonomous-cloud-coding-agents/architecture/orches Lambda MicroVMs are an opt-in third backend. Include `lambda-microvm` in `compute_types`; repositories inherit the first listed backend or choose a deployed backend through an override. Legacy `compute_type=lambda-microvm` deploys AgentCore and MicroVM, with AgentCore as the default. Image configuration has three states: a managed base-image ARN and version creates the snapshot image in CDK; an external image identifier uses a snapshot built out of band; and supplying neither provisions only the roles, buckets, and connectors needed for the bootstrap deploy. `cdk/scripts/package-microvm-artifact.sh` packages the agent as zip + Dockerfile, uploads it to the artifact bucket, and can create the external image. Lambda MicroVMs are available in five launch regions (us-east-1, us-east-2, us-west-2, eu-west-1, ap-northeast-1) and will expand; the platform enforces regional availability in layers via a synth-time constant, onboarding live probes, and orchestration-time classification. -Because a snapshot freezes its build-time environment, deployment-specific, non-secret identifiers travel in the `/run` hook's `platform_config` block instead. The strategy sends the canonical inline envelope or, when that envelope exceeds the verified 4,096-byte `runHookPayload` limit, an S3-pointer envelope with the configuration also merged into the uploaded payload. The agent accepts only allowlisted keys and installs them before pipeline initialization; [ADR-021 §3](/sample-autonomous-cloud-coding-agents/architecture/adr-021-lambda-microvms-compute-backend#3-packaging-same-agent-image-source-new-build-path) defines the exact wire shapes and validation rules. +Because a snapshot freezes its build-time environment, current deployment identifiers arrive through the v2 payload bootstrap. The coordinator publishes a non-secret deployment manifest and sends a single-object signed download URL for the task. The worker reads only its deployment's `bootstrap/*` with ambient credentials; other object reads and payload-bucket listing are explicitly denied. The downloaded task identity and configuration must match the authenticated manifest before configuration installation. The serialized reference fits the verified 4,096-byte hook limit; all payload sizes use S3. ECS shares this transport through `AGENT_PAYLOAD_REF`. [ADR-021 §3](/sample-autonomous-cloud-coding-agents/architecture/adr-021-lambda-microvms-compute-backend#3-packaging-same-agent-image-source-new-build-path) defines the wire format, compatibility change and pending live gates. Networking separates image build from execution: the build-only connector permits TCP 80 and 443 because the Dockerfile uses `apt-get`, while running MicroVMs retain 443-only egress through the platform VPC. Every launch explicitly passes the Lambda-managed `NO_INGRESS` connector; omission would select the service's public-ingress default. The P2 image declares and serves `/ready` and `/validate` at build time and `/run` and `/terminate` at runtime. `/suspend` and `/resume` remain disabled until their P3 implementation. diff --git a/docs/src/content/docs/architecture/Security.md b/docs/src/content/docs/architecture/Security.md index d7a6d04e1..fc525d395 100644 --- a/docs/src/content/docs/architecture/Security.md +++ b/docs/src/content/docs/architecture/Security.md @@ -50,7 +50,10 @@ Three authentication mechanisms protect the platform, matching its input channel The compute role retains only non-tenant access (Bedrock model invocation — already ARN-scoped; CloudWatch Logs; the GitHub PAT secret, read once before the SessionRole is assumed; AgentCore Memory) plus `sts:AssumeRole`/`sts:TagSession` on the SessionRole. Because the agent runs under credentials that are themselves an assumed role, its `AssumeRole` is *role chaining* — capped at one hour regardless of the role's max session duration — so the agent uses a **refreshable** credential provider that re-assumes before expiry (tasks can run up to the 8-hour `maxLifetime`). The design is backend-agnostic: the same SessionRole and agent code serve all three backends (AgentCore Runtime, ECS Fargate, Lambda MicroVMs). A compromised agent session is therefore confined to its own task's data, enforced at the IAM layer rather than by application-code conventions. The policy structure (the `dynamodb:LeadingKeys` condition on `${aws:PrincipalTag/task_id}`, per-user S3 prefixes, and `Scan` exclusion) is asserted by CDK template tests, and the refreshable-credential and session-tag flow by agent unit tests; the matching-tag → allow / mismatched-or-absent-tag → deny behaviour was additionally confirmed once via the IAM policy simulator during development. -**Lambda MicroVMs compute-role delta** - On this backend the compute role additionally holds prefix-scoped `secretsmanager:GetSecretValue` on the per-workspace channel-OAuth secrets (`bgagent-linear-oauth-*`, `bgagent-jira-oauth-*`), read access to the `/run` payload bucket (the task payload arrives as an S3 object, not as environment), and `ec2:DescribeAvailabilityZones` (`Resource: *`, read-only — EC2 describe actions have no resource-level scoping) for a CDK repo's own synth gate. It is also **the only compute role in the platform whose trust policy carries no confused-deputy condition**: the Lambda MicroVMs service populates no `aws:SourceAccount` or `aws:SourceArn` when it assumes the role, so a trust policy carrying one is unassumable — verified live, not assumed (connector creation failed deterministically, and `RunMicrovm` surfaced the same root cause as a misleading caller-side `iam:PassRole` denial). The compensating controls are that each of the three MicroVM roles can be passed to `lambda.amazonaws.com` only by a named principal — the orchestrator, via an `iam:PassRole` scoped to the execution role's exact ARN, and the CloudFormation deployment role for the build and connector-operator roles — that every other resource they reach is account-scoped by ARN apart from two justified `Resource: *` read/create-time statements, and that none of them holds `iam:*`, cross-account trust, or any `sts:AssumeRole` beyond the execution role's scoped hop to the per-task SessionRole. Full evidence, the two-arm PassRole experiment, and the alternatives considered are in [ADR-021 §4](/sample-autonomous-cloud-coding-agents/architecture/adr-021-lambda-microvms-compute-backend#4-infra-and-iam-conditional-resources-behind-bootstrap-computetypes). +**Lambda MicroVMs compute-role delta** - On this backend the compute role additionally holds prefix-scoped `secretsmanager:GetSecretValue` on the per-workspace channel-OAuth secrets (`bgagent-linear-oauth-*`, `bgagent-jira-oauth-*`), read access only to its payload bucket's `bootstrap/*` manifests (other object reads and payload-bucket listing are explicitly denied), and `ec2:DescribeAvailabilityZones` (`Resource: *`, read-only — EC2 describe actions have no resource-level scoping) for a CDK repo's own synth gate. It is also **the only compute role in the platform whose trust policy carries no confused-deputy condition**: the Lambda MicroVMs service populates no `aws:SourceAccount` or `aws:SourceArn` when it assumes the role, so a trust policy carrying one is unassumable — verified live, not assumed (connector creation failed deterministically, and `RunMicrovm` surfaced the same root cause as a misleading caller-side `iam:PassRole` denial). The compensating controls are that each of the three MicroVM roles can be passed to `lambda.amazonaws.com` only by a named principal — the orchestrator, via an `iam:PassRole` scoped to the execution role's exact ARN, and the CloudFormation deployment role for the build and connector-operator roles — that every other resource they reach is account-scoped by ARN apart from two justified `Resource: *` read/create-time statements, and that none of them holds `iam:*`, cross-account trust, or any `sts:AssumeRole` beyond the execution role's scoped hop to the per-task SessionRole. Full evidence, the two-arm PassRole experiment, and the alternatives considered are in [ADR-021 §4](/sample-autonomous-cloud-coding-agents/architecture/adr-021-lambda-microvms-compute-backend#4-infra-and-iam-conditional-resources-behind-bootstrap-computetypes). + +**ECS/MicroVM task bootstrap (v2)** — The coordinator publishes non-secret deployment manifests and supplies a short-lived signed URL for exactly one task's payload. The worker reads the manifest with its ambient role, whose explicit deny outside its own `bootstrap/*` prevents a foreign public bucket from authorizing fake configuration. It verifies downloaded task identity and exact manifest/config agreement before installing MicroVM settings. The coordinator privately persists the URL outside TaskTable for retry and deletes both task objects at finalization. Worker roles cannot read/list task objects using their ambient credentials. A signed URL is a bearer capability: redact it in errors and keep it out of task rows and repository subprocess environments. Existing session-tag trust and other platform grants remain separate limitations. This protocol is implemented locally; real IAM/network/expiry gates and the coordinated image/coordinator/policy rollout are documented in the repository's `docs/verification/645-payload-bootstrap.md`. + > Out of scope for this control and tracked separately as GitHub issues: replacing the shared GitHub PAT (GitHub App / Token Vault), binding credentials to the MicroVM via attestation, and scoping AgentCore Memory (namespace isolation by `actorId`/`sessionId` remains its boundary). diff --git a/docs/src/content/docs/decisions/Adr-021-lambda-microvms-compute-backend.md b/docs/src/content/docs/decisions/Adr-021-lambda-microvms-compute-backend.md index fa42d0108..2fad1dfa7 100644 --- a/docs/src/content/docs/decisions/Adr-021-lambda-microvms-compute-backend.md +++ b/docs/src/content/docs/decisions/Adr-021-lambda-microvms-compute-backend.md @@ -201,25 +201,28 @@ The binary was fine — in the identical image, locally, `claude --version` answ Both halves of the fix are kept, because they answer different questions. `/ready` now **exec's the heavyweight binaries before returning 200** (`claude` required, `git`/`node` best-effort), which is the only mechanism that can make the shipped snapshot warm — and its own budget rises to 300 s, well inside the 3600 s build-hook window, because it now does work whose duration is a cold `exec`. Two structural rules keep that honest, because **per-command timeouts do not compose**: the required command runs FIRST with its own budget so no best-effort warm-up can starve the one that decides whether the snapshot is usable, and the best-effort ones then SHARE the remainder of a total warm-up ceiling that sits inside the hook budget with margin (240 s against 300 s). Without them, three commands at 120 s each would be 360 s — a fix for a runtime failure that produces a build failure instead — and a single hung optional command could hold up a 200 that the required warm-up had already earned. Separately, the version probe's timeout goes from 10 s to 60 s: a probe that exists to print a version string into a log line gains nothing from a tight bound and loses the whole task when it trips. The general rule this generalises to, and the reason it belongs in the ADR rather than only in a comment: **on this backend, a first-touch cost that other substrates pay during container start is deferred to the first task instead**, so anything large and lazily-loaded is a turn-0 hazard unless it is touched in `/ready`. -**Payload delivery** reuses the ECS strategy's S3-pointer pattern, adapted to `runHookPayload` (**≤ 4 KB** — measured, see below): payloads that fit ride inline; the rest are uploaded by the strategy to a platform payload bucket (the ECS payload bucket pattern in `ecs-agent-cluster.ts`: orchestrator write access, compute-role read-only scoped to the bucket, lifecycle expiry on objects) with the S3 URI in `runHookPayload` in place of the payload itself — the MicroVM **execution role** holds the read grant, exactly as the ECS task role does today. Since P2 the hook body also carries `platform_config` in both branches, so `runHookPayload` is never *only* the URI (see the canonical shapes below). +**Payload delivery — v2 amendment (2026-09-13, #817/#700).** The local implementation now shares an authenticated bootstrap protocol between ECS and MicroVM. This replaces the original inline/S3-pointer protocol and broad worker payload-bucket read grant. The historical P1/P2 runs below predate this amendment; AWS authorization, networking, expiry and coordinated deployment validation remain pending. The repository runbook is `docs/verification/645-payload-bootstrap.md`. -The cap is **4 096 bytes**, not the 16 384 the SDK documents. Measured exactly: 4 096 passes, 4 097 is rejected with *"Value at 'runHookPayload' failed to satisfy constraint: Member must have length less than or equal to 4096"*. Two consequences follow. First, the original threshold would have inlined every envelope between 4 097 and 16 384 bytes and had the service reject all of them. Second, and more structurally: **the S3-pointer path is now the dominant one, and inline is the exception.** A hydrated task payload (prompt + issue thread + repo context) essentially always exceeds 4 KB, so "small payloads ride inline" describes tiny repo-less prompts rather than the common case. The payload bucket is therefore not a rarely-exercised overflow valve but a required part of every normal task, which raises its lifecycle rule (`MICROVM_PAYLOAD_TTL_DAYS`) and the execution role's read grant from edge-case plumbing to load-bearing. +Every task uses S3. The coordinator publishes a non-secret deployment manifest at `bootstrap/.json`, conditionally creates `/payload.json`, and sends a short-lived signed URL for that one task object. The worker reads the manifest with its own AWS role, whose policy explicitly denies object reads outside its deployment's `bootstrap/*` and denies payload-bucket listing. The explicit deny also prevents a foreign public bucket from authenticating a forged manifest. The task document must name the reference's task ID and contain the exact manifest configuration before the MicroVM installs any of it. -**Canonical wire shapes.** Three, and the producer (`lambda-microvm-strategy.ts`) emits exactly these: +The `runHookPayload` cap remains **4,096 bytes**, measured against the service despite the SDK's documented 16,384. It now applies to the serialized reference rather than choosing an inline branch. Payloads are capped at 8 MiB and manifests at 16 KiB; the bounds and version are shared in `contracts/constants.json`. -| Where | Exact shape | +| Location | v2 shape | |---|---| -| `runHookPayload`, inline branch | `{"agent_payload": {…}, "platform_config": {…}}` | -| `runHookPayload`, pointer branch | `{"agent_payload_s3_uri": "s3://…", "platform_config": {…}}` | -| the object at that S3 URI | `{…agent_payload fields…, "platform_config": {…}}` — the payload's own fields at the TOP level, with the config merged in beside them | +| `runHookPayload` string / ECS `AGENT_PAYLOAD_REF` | `{version:2, task_id, bootstrap_s3_uri, payload_url, expires_at}` | +| `bootstrap/.json` | `{version:2, backend, platform_config}` | +| `/payload.json` | `{version:2, task_id, agent_payload, platform_config}` | +| Private `/launch.json` | `{fingerprint, reference}`; coordinator-readable only, never on the agent-readable task row | -Two asymmetries are deliberate and must not be "tidied" without changing both sides. First, **the S3 object is not the envelope**: the payload's fields sit at the top level (that is what P1 uploaded, before `platform_config` existed) rather than nested under an `agent_payload` key. Second, **`platform_config` is duplicated** on the pointer path — once beside the pointer, once inside the uploaded object. It costs a few hundred bytes and buys the property that the config is reachable whichever end of the fetch a reader looks at, which matters because it is the agent's only substitute for an env block. +The coordinator saves the exact reference for replay: re-signing would change a Run request with the same client token. Task objects use conditional creation and read-back recovery after a lost committed write. URL lifetime is at most 900 seconds, bounded by known credential expiry, and initial creation requires at least 300 seconds. Expired saved references fail without re-signing. The coordinator needs bucket-scoped `ListBucket` so an absent launch record returns `NoSuchKey` rather than `AccessDenied`. It deletes both task objects at finalization; one-day lifecycle expiry is the backstop. Manifests are refreshed with identical bytes at preparation and may coexist across configuration revisions until lifecycle cleanup. -The agent's reader is deliberately more permissive than this contract: it also accepts an S3 object shaped like the envelope (`agent_payload` nested), and `platform_config` present in only one of the two places (the fetched object wins, the hook body is the fallback). Those are **defensive compatibility** for the independent deploy cadences of a snapshot image and the orchestrator Lambda — a tolerant reader, not an alternative contract. A producer must emit the three shapes above. +The image accepts only v2. The old inline/pointer forms and baked-environment fallback are rejected. A coordinated drain and switch of coordinator, images and application IAM is required; there is no new KMS/SSM resource or bootstrap bundle version. Signed URLs are bearer capabilities and must never appear in task rows, ordinary logs or repository subprocess environments. ECS consumes/removes its reference before importing the task pipeline. The URL consumer restricts requests to the exact task object on regional S3 HTTPS, disables redirects/proxies and bounds response bytes. AWS verifies signatures and actual expiration. -**Platform configuration delivery (P2): payload-sourced, allowlisted, fail-closed.** The other two backends hand the agent its non-secret platform env at launch — AgentCore Runtime env vars, ECS container overrides — and there is no equivalent on this substrate: a MicroVM starts from a **snapshot**, so its process environment is whatever was frozen at *image build* time and is then replayed by every MicroVM launched from that image version. Baking the deployment's identifiers into the snapshot would make them **version-frozen**: a redeploy that renames a table, adds a bucket or rotates the session role would leave every existing image version describing a deployment that no longer exists, and the drift would surface as a task-time `ResourceNotFound` rather than a deploy-time error. So the values travel with the task instead: `platform_config` is a SIBLING of the payload — beside `agent_payload` in the inline branch, beside `agent_payload_s3_uri` in the pointer branch, and merged in beside the payload's own fields inside the S3 object (the canonical shapes above give each one exactly) — whose snake_case keys the agent installs into `os.environ` as their UPPER_SNAKE equivalents. A payload value therefore **wins** over any pre-existing/image value — the orchestrator is describing the live deployment, the snapshot is describing a past one. `platform_config` carries **non-secret identifiers only** (table and bucket names, secret ARNs, the session-role ARN); secrets are still fetched at `/run` time from Secrets Manager using those ARNs, so the snapshot-must-stay-secret-free requirement above is untouched. Per-task fields — `memory_id` and friends — stay inside `agent_payload`: `platform_config` configures the *process*, `agent_payload` describes the *task*. +**Platform configuration delivery (P2, strengthened by v2).** A MicroVM restores a snapshot, including its process environment, so current deployment identifiers must arrive at task launch. The authenticated manifest and downloaded document both contain `platform_config`: non-secret table/bucket names, secret ARNs and session-role ARN. Per-task fields such as `memory_id` remain in `agent_payload`. ECS's manifest config is empty because ECS already receives deployment settings through its task definition and coordinator overrides. -Two rules make it safe. First, **the allowlist fails closed**: the agent installs a fixed set of keys and *rejects the entire run* (HTTP 400, nothing spawned, not one key installed) if the block carries anything else. These values become environment variables of the process that spawns the agent's tool subprocesses, so an unrecognised key is an attempt to set an arbitrary variable in the agent (`AWS_ENDPOINT_URL`, `LD_PRELOAD`, `PATH`, …) — an injection attempt, not a forward-compatibility gap, which is why unknown keys are refused rather than filtered out. Second, **installation happens before any credential or pipeline initialisation** on the hook path: the very next step reads `GITHUB_TOKEN_SECRET_ARN` to resolve the GitHub token and `AGENT_SESSION_ROLE_ARN` to scope the task's credentials, so installing later would silently resolve the whole task against the snapshot's frozen env. The one call that must precede installation is the S3 payload fetch (the config is *inside* the fetched object), which therefore runs on the ambient compute role via the attributed platform client — and it is the ONLY one: the same rule covers **logging**, so every `/run` log line before the install is stdout-only. The CloudWatch writer would otherwise resolve credentials and pin a boto3 default session (region included) off whatever a snapshot happened to bake, which is the build-hook defect one phase later. Nothing is lost — in the intended deployment there is no baked `LOG_GROUP_NAME`, so those lines would have gone to stdout anyway, and the reason for every pre-install rejection also travels in the structured 4xx/5xx body the service surfaces. A **required subset** (task table, task-events table, GitHub token secret ARN, session-role ARN) is rejected as `…_INCOMPLETE` when missing or blank — a distinct wire code from the `…_INVALID` allowlist rejection, because the remedies differ (deployment wiring vs. producer bug). A `/run` envelope with *no* `platform_config` at all is still accepted, loudly warned: the image snapshot and the orchestrator Lambda deploy on independent cadences, and a new image must not require a same-instant orchestrator. The key set is a cross-package contract in `contracts/constants.json` (`microvm_platform_config`), consumed by the agent's `/run` hook and produced by the orchestrator, with shape and required-subset invariants enforced by `scripts/check-constants-sync.ts`. +MicroVM installs only allowlisted keys and rejects unknown keys before installing any. Required identifiers must be nonblank; malformed/control-character values and inconsistent ARN partitions/accounts are rejected. Legitimate cross-region secrets remain allowed when present in the trusted manifest. Account agreement alone cannot authenticate a sibling ARN; v2's manifest/config comparison supplies the provenance check. No-config envelopes are rejected regardless of the image's existing environment. + +Manifest read and signed payload download precede configuration installation. Secrets, task-scoped credential setup, CloudWatch initialization and the pipeline follow installation; pre-install diagnostics use stdout without unsafe exception chains. Build hooks remain AWS-silent. The settings allowlist and bootstrap bounds are cross-language contracts with drift checks. These source guarantees do not establish complete hostile-worker isolation: roles still retain other platform grants and choose session tags, and a stolen signed URL remains usable until expiry or revocation. **No orchestrator→agent HTTP path exists in P1–P3**: payload arrives through the `/run` hook, all agent work is outbound, and therefore **no JWE auth tokens are minted at all** — token minting (and its ≤ 60 min TTL refresh problem) is deferred until a real consumer exists (e.g. operator shell access, [#391](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/391)). The `endpoint` stays in the `SessionHandle` because it is genuinely per-session state that becomes load-bearing the day such a consumer appears. But note the service does not agree by default: omitting `ingressNetworkConnectors` on `RunMicrovm` attaches a **public** `HTTP_INGRESS` connector, so the strategy passes the Lambda-managed `NO_INGRESS` connector explicitly on every launch (see sub-decision 4's security table). @@ -228,12 +231,12 @@ Two rules make it safe. First, **the allowlist fails closed**: the agent install Normative requirements (EARS). **Each requirement's own `(Pn)` tag is authoritative**; there is no blanket phase for the list. The tags are per-requirement because the original list *was* split P1/P2 on the assumption that a hook could be declared in one phase and served in a later one — which the service does not permit (see the phasing table above), so the hook-serving requirements collapsed into P1 while the P2 items below arrived with the P2 hooks and `platform_config`: - (P1) The image build shall not embed secrets, tokens, or per-task identity in the snapshot. -- (P1) If the task payload exceeds the 4 KB `runHookPayload` limit, then the strategy shall upload the payload to the platform payload bucket and pass its S3 URI in `runHookPayload` in place of the payload (from P2, alongside `platform_config`). -- (P1) The MicroVM execution role shall hold read-only access to the payload bucket, scoped to that bucket. +- (P1, amended by v2) Every task shall use the authenticated manifest and single-object signed payload reference; the serialized hook reference shall not exceed 4,096 bytes. +- (P1, amended by v2) The worker role shall read only deployment bootstrap manifests with ambient credentials; other object reads and payload-bucket listing shall be explicitly denied. The coordinator shall own task-object writes, signing, replay and deletion. - (P1) Where no ingress is configured for a deployment, the strategy shall pass the Lambda-managed `NO_INGRESS` network connector on every `RunMicrovm` call (the field shall not be omitted). - (P1) Where the image enables any MicroVM lifecycle hook, the image shall also enable the `/ready` hook and the agent shall serve it. - (P1) When the `/run` hook receives the task payload, the agent shall validate it, start the pipeline asynchronously, and return HTTP 200 within the hook budget. -- (P1) If the `/run` hook payload cannot be resolved to a task payload, then the agent shall reject the hook with a client error and shall not start a pipeline. +- (P1, clarified) Invalid hook references shall return a structured client error; unreadable manifest/payload bytes shall return a structured server error. Neither path shall install configuration or start a pipeline. - (P1) The agent shall not execute the clone→verify→PR pipeline on the hook path. - (P1) The agent shall resolve credentials at `/run` time. - (P1) Where a deployment configures a MicroVM image before smoke parity is verified, the platform shall warn that the backend has no smoke-parity guarantee. @@ -398,8 +401,8 @@ Lambda MicroVMs launched in 5 regions (us-east-1/2, us-west-2, eu-west-1, ap-nor **P1 (start/poll/stop — no suspend):** -- Unit tests for the strategy: start/poll/stop mapping (including `SessionStatus` `'suspended'` reported mechanically, without task-state interpretation), payload-size branching (inline vs S3 pointer, at the exact 4 096/4 097-byte boundary), the image-identifier-must-be-an-ARN guard, the explicit `NO_INGRESS` argument (including the blank-env-var fallback, which must never omit the field), error classification (`ServiceQuotaExceededException`, `ThrottlingException`, `ResourceNotFoundException`, regional-unavailability), the omit-`idlePolicy` invariant, and `maximumDurationInSeconds` fixed at 28 800. -- Agent tests: `/ready` returns 200 once the server is up and starts nothing; `/run` accepts both envelope shapes (inline and S3 pointer), starts the pipeline asynchronously through the same mapper `/invocations` uses, returns before the pipeline finishes, and rejects every unusable envelope with a named code before spawning; `/suspend` and `/resume` are NOT served (`/validate` and `/terminate` joined the served set in P2). +- Unit tests for the strategy: start/poll/stop mapping (including `SessionStatus` `'suspended'` reported mechanically, without task-state interpretation), v2 reference-size bounds (4,096 bytes), immutable signed-reference replay and scoped payload transport, the image-identifier-must-be-an-ARN guard, the explicit `NO_INGRESS` argument (including the blank-env-var fallback, which must never omit the field), error classification (`ServiceQuotaExceededException`, `ThrottlingException`, `ResourceNotFoundException`, regional-unavailability), the omit-`idlePolicy` invariant, and `maximumDurationInSeconds` fixed at 28 800. +- Agent tests: `/ready` returns 200 after required local warm-up succeeds, without starting a task or calling AWS; `/run` accepts authenticated v2 references and rejects old unsigned envelopes, starts the pipeline asynchronously through the same mapper `/invocations` uses, returns before the pipeline finishes, and rejects every unusable envelope with a named code before spawning; `/suspend` and `/resume` are NOT served (`/validate` and `/terminate` joined the served set in P2). - Orchestrator tests: substrate-terminal + non-terminal task status → failed classification; `suspended` + non-`AWAITING_APPROVAL` status → anomaly event, no fail-fast; `compute_metadata` persisted with `microvmId`/`endpoint` after `startSession`. - CDK assertions: MicroVM resources present only when `ComputeTypes` includes the backend; synth failure for unsupported regions (plus the context-flag escape hatch); memory size validated against the accepted list at synth; the connector operator role and its trust; two connectors with the build-only one carrying port 80 and the runtime one not; the `/ready` + `/run` hook declaration and the absence of the others; IAM actions scoped as specified (orchestrator lifecycle set; no `CreateMicrovmAuthToken` anywhere); payload-bucket grants (execution role read-only); backend cost-allocation tags; types-sync check covers the widened `ComputeType`. - CLI tests: onboarding rejection with remedy when the availability probe fails; doctor check present when a blueprint selects the backend. @@ -408,7 +411,7 @@ Lambda MicroVMs launched in 5 regions (us-east-1/2, us-west-2, eu-west-1, ap-nor **P2 (smoke parity):** - Agent tests: `/validate` returns 200 with its individual check results, 503 while initialising, reports a missing hook route / unsupported interpreter, starts nothing, and makes **zero AWS calls even with `LOG_GROUP_NAME` set** (asserted by poisoning the boto3 and CloudWatch-writer seams — the same assertion covers `/ready`); `/terminate` returns 200 with no body at all, with a malformed / non-object / wrong-content-type / whitespace-only body, when the body read itself fails, with a pipeline still running (without joining it), and when its own best-effort step raises — and never calls `task_state.write_terminal`; a structural assertion that the route carries no typed body param keeps the 422 from being reintroduced. -- `platform_config` tests: the allowlist and required subset are read from `contracts/constants.json` (the wire key set is additionally asserted literally, as the agent-side tripwire on a contract edit); an unknown key rejects the whole block with nothing installed; a non-object block and a non-string value are rejected; a blank/`null` optional value is skipped without clobbering an image value while a blank required value is rejected; a payload value beats a pre-existing env value; installation is observed to happen before the GitHub-token resolver runs and before any pipeline thread exists; the config is picked up from the inline envelope, from beside the S3 pointer, and from inside the fetched object (inner wins); an envelope with no `platform_config` is still accepted with a warning. +- `platform_config` tests: the allowlist and required subset are read from `contracts/constants.json` (the wire key set is additionally asserted literally, as the agent-side tripwire on a contract edit); an unknown key rejects the whole block with nothing installed; a non-object block and a non-string value are rejected; a blank/`null` optional value is skipped without clobbering an image value while a blank required value is rejected; a payload value beats a pre-existing env value; installation is observed to happen before the GitHub-token resolver runs and before any pipeline thread exists; the downloaded config must equal the IAM-authenticated manifest, including same-account workspace identifiers; missing config and legacy envelopes are rejected regardless of baked environment values. Transport tests cover signed URLs, exact task identity, bad bytes and rejection before installation. - Snapshot credential hygiene: a subprocess probe asserts that importing `server` and serving `/ready` + `/validate` imports neither `boto3` nor `botocore`, caches no `aws_session` session, and spawns no CloudWatch writer thread — the property that keeps a build-role credential chain and the build-time region out of the snapshot. - `/run` pre-install silence: with a **baked `LOG_GROUP_NAME`** (the hostile case — without it the assertions pass vacuously) every AWS/credential seam (`boto3.client`/`Session`, the `aws_session` factories, `_debug_cw`/`_warn_cw`) is armed to raise until the install succeeds. Asserted on the accepted path, on all three rejection paths (bad envelope, `platform_config` invalid, `platform_config` incomplete) and on the failed-fetch 500 — where the seams stay armed for the whole request, because a rejected run installed nothing and so earns no AWS call. The permitted exception is asserted POSITIVELY: exactly one client is built pre-install, for `s3`, through the attributed factory. - `/ready` warm-up tests (P2-F5): the hook exec's each configured binary exactly once with a generous timeout; `claude` is the only REQUIRED entry; a timeout, a missing binary, a non-zero exit and an unexpected `OSError` each produce **503 with the reason logged to stdout** rather than a 200 or a 500; a best-effort failure still reports ready; the warm-up makes zero AWS calls with `LOG_GROUP_NAME` baked. Plus the backstop half: the `claude --version` probe's bound is asserted to be ≥ 60 s and to be applied to the *exec* rather than to the PATH lookup, and a missing CLI warns instead of raising. diff --git a/docs/verification/645-payload-bootstrap.md b/docs/verification/645-payload-bootstrap.md new file mode 100644 index 000000000..34018e577 --- /dev/null +++ b/docs/verification/645-payload-bootstrap.md @@ -0,0 +1,127 @@ +# #645: trusted task delivery for ECS and MicroVM + +Implementation date: 2026-09-13. Tracks the local prerequisites in #817 and #700. **Implemented locally; AWS authorization, networking, expiry and deployment checks below are still pending.** This does not implement P3 sleep/wake. + +## What changed, in plain language + +Think of S3 as a locked filing cabinet. A **bucket** is one cabinet and an **object** is one file. The **coordinator** is the supervisor that starts tasks. A **worker** is the ECS container or MicroVM that runs the coding agent. + +Previously, each worker's permission badge could read other tasks' instruction files. Also, checking that two AWS addresses named the same account did not prove either address belonged to this deployment. + +The new protocol gives the worker: + +1. A small **manifest**: a list of the deployment's non-secret settings. The worker reads this with its own AWS permission badge. Only this deployment's bootstrap directory is allowed. +2. A **presigned URL**: a temporary download ticket, created by the coordinator, for exactly one task's instruction file. AWS checks its signature. Possessing the ticket permits the read, so the complete URL must be treated like a password. + +The downloaded task must name the expected task ID and contain exactly the settings in the authenticated manifest. Changing a secret's address to another workspace in the same AWS account now fails this comparison. + +This bootstrap means “load the information needed to start a task.” It is distinct from the infrastructure bootstrap that installs deployment permissions. + +## Storage and wire contract + +Both backends use `contracts/constants.json` → `payload_bootstrap`, version 2. All task payloads use this path, including small tasks. + +| Location | Content / owner | +|---|---| +| `bootstrap/.json` | `{version:2, backend, platform_config}`. Coordinator writes; worker reads. The filename contains a SHA-256 digest: a fingerprint of the exact JSON bytes. | +| `/payload.json` | `{version:2, task_id, agent_payload, platform_config}`. Coordinator writes; worker downloads using the signed URL. | +| `/launch.json` | `{fingerprint, reference}`. Private coordinator replay record containing the signed URL. No worker read. | +| MicroVM `runHookPayload` / ECS `AGENT_PAYLOAD_REF` | JSON string containing the reference below. Never log it. | + +```json +{ + "version": 2, + "task_id": "TASK001", + "bootstrap_s3_uri": "s3://deployment-bucket/bootstrap/.json", + "payload_url": "", + "expires_at": 1789312500000 +} +``` + +The example is descriptive; the manifest digest and signed URL must be produced by the coordinator. `expires_at` is milliseconds since the Unix epoch. + +MicroVM manifests contain the allowlisted environment identifiers built from the coordinator's deployment environment. ECS manifests contain `{}` for `platform_config`: its platform settings already arrive through the trusted task definition and coordinator overrides. Task-specific fields remain in `agent_payload`. + +Manifest and payload limits are **16 KiB** and **8 MiB**, respectively. The serialized MicroVM reference must fit **4,096 bytes**. The entire ECS overrides object must fit **8,192 UTF-8 bytes**; the prompt is no longer duplicated in `TASK_DESCRIPTION`. + +The image rejects the old unsigned inline/S3 envelopes. There is no compatibility branch that accepts settings merely because an image already contains the required environment variables. + +## Permission boundary + +| Principal | Allowed | Denied / not granted | +|---|---|---| +| Worker ambient role | Exact `s3:GetObject` on its bucket's `bootstrap/*` | Explicit `Deny s3:GetObject*` outside that prefix, including other/public buckets; explicit `Deny s3:List*` on its payload bucket. No payload write/delete grant. | +| Trusted coordinator | `PutObject` on manifests and `*/payload.json`, `*/launch.json`; `GetObject`/`DeleteObject` on the two task paths; `ListBucket` on its payload bucket | No task-object version deletion or manifest deletion grant added by this helper. | + +The explicit denial outside `bootstrap/*` is essential. An allow-only policy would not authenticate configuration: an attacker-controlled public bucket could grant the worker access to a fake manifest. A successful read with the deployed deny policy establishes its permitted origin; the hash only detects different bytes, not authorship. + +The coordinator needs `ListBucket` because S3 returns **403 AccessDenied**, rather than **404 NoSuchKey**, for a missing object when the caller cannot list the bucket. The first launch probes for its saved record. Workers do not get this permission. + +AWS documents this in [GetObject permissions](https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html). Its [conditional-write guide](https://docs.aws.amazon.com/AmazonS3/latest/userguide/conditional-writes.html) specifies that the first completed conditional write wins and later writes receive 412; a concurrent delete can produce 409. The [presigned-URL guide](https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html) confirms that temporary credential expiry can end a URL's validity before its requested expiry. These documents were checked during this review; deployed behavior remains a separate gate. + +The worker reads the manifest through the attributed `platform_client("s3")` before installing configuration. It then downloads the payload over HTTPS without adding worker credentials. Only the exact bucket/task key on a regional S3 host is accepted; redirects, environment proxies, alternate hosts, credentials in URLs, custom ports, duplicate query parameters and non-HTTPS URLs are rejected. AWS validates the actual signature and expiry; local URL checks are not a cryptographic verifier. + +The runtime still needs HTTPS/443 and DNS access to the selected S3 region. The source checks do not establish that the deployed connector permits it. Build hooks remain AWS-silent; before configuration installation, runtime bootstrap uses manifest-read and payload-download operations, and diagnostics go to stdout. + +## Retry, expiry and cleanup + +- The coordinator serializes JSON consistently and conditionally creates task objects with `IfNoneMatch: '*'`. A second writer cannot overwrite existing instructions. Read-back handles a write that committed but lost its reply. +- The saved launch record returns the **same URL** after a retry or coordinator restart. Generating a new URL would change the MicroVM Run request while reusing its client token. The private record is deliberately outside TaskTable because the agent can read its own task row. +- A URL is requested for at most **900 seconds**. If the SDK exposes an earlier credential expiry, that shortens the requested lifetime. Initial creation refuses a lifetime under **300 seconds**. AWS can still reject credentials earlier; the provider's actual expiration behavior needs live evidence. +- An expired saved reference fails explicitly; it is not silently re-signed. Recover any existing compute handle before deciding what to do. A timeout or expired ticket does not prove no worker started. MicroVM's saved-start receipt still governs its 120-second application replay window. +- The coordinator refreshes identical manifest bytes at each preparation so the bucket's one-day lifecycle does not remove an old manifest just before a new task reads it. Historical authorized manifests can coexist until lifecycle deletion; this is provenance authentication, not a “latest configuration only” policy. +- Finalization best-effort deletes both `payload.json` and `launch.json`. Deleting the current payload revokes its unversioned download link. Lifecycle deletion remains a backstop and is asynchronous, not an exact one-day alarm. +- ECS removes `AGENT_PAYLOAD_REF` from its environment before importing the pipeline or starting repository subprocesses. Errors redact signed URLs; Python exception chains must not reintroduce them. Control-plane request metadata and the coordinator's private record still contain the capability and require trusted access. + +No new KMS key, SSM parameter, table or bootstrap bundle version is needed. Application IAM policies, coordinator code and worker images all change. + +For P3, `/resume` must continue the restored task, not re-run bootstrap or reuse its expired launch ticket. The task context/workspace and durable approval records supply the information needed after sleep; credential refresh remains a separate resume barrier. + +## Local verification + +Tests exercise real producer/consumer code with fake services. The Python tests use real streaming bodies for truncation/closure cases. The MicroVM recovery tests use the shared transport while simulating lost Run replies and coordinator restart. + +Coverage includes immutable/replayed/conflicting writes, competing launch preparation, committed writes with lost responses, expiry/short-lived credentials, wrong task/configuration, same-account workspace substitution, public-bucket denial before download, cross-region secret preservation, malformed/oversized bytes, redirect/host rejection, ECS environment removal and both cleanup keys. + +A regression reproduced a signed-URL leak through a chained Python traceback. Route logging and sanitized exceptions now prevent that leak. Separate tests cover coordinator-side error redaction and oversized ECS/MicroVM references. + +Permission tests inspect synthesized IAM policies, including the `NotResource` explicit deny and the coordinator's missing-object permission. The constants-checker subprocess rejects invalid bounds/paths and consumers that stop importing the contract. + +An offline compatibility probe generated a URL using the actual JavaScript AWS SDK with dummy credentials and passed it through the Python URL parser. That proves the observed SDK URL shape is supported; it makes no AWS authorization claim. + +See the [implementation checklist](./645-p3-implementation-plan.md#implementation-progress) for final suite counts. Mock authorization failures are not proof of effective AWS IAM. Conditional S3 writes and the missing-object behavior must also be checked live. + +## Coordinated deployment and rollback + +1. Record the source commit, existing coordinator version, ECS task definitions, MicroVM image/version and effective application policies. Retain the previous deployable artifacts and inspect the CloudFormation change set. Do not delete/recreate storage as an upgrade mechanism. +2. Pause new admissions and scheduled/queue submissions for both affected backends. Drain existing tasks, approvals and pending/retry launches; reconcile uncertain starts and terminate any live test compute. Do not upgrade beneath a running old coordinator. +3. Build the new ECS image and a MicroVM image from the same source/contract. Validate build hooks without task secrets. Retain the old image definitions for rollback. Building the new image before the switch is safe; starting production tasks against mixed versions is not. +4. With admissions paused, deploy the matching coordinator, image/task-definition references and IAM changes. Wait for all resources and permissions to settle. Old producer + new image and new producer + old image both fail the version contract; old workers with new policies cannot use the former broad S3 fetch. +5. Verify effective policies and image identifiers, then perform the live matrix below in the test deployment. Inspect sanitized logs, cleanup and retry records. Resume admissions only after these gates pass. +6. On failure, keep admissions paused. Drain/terminate new-version workers and reconcile unknown launches. Restore the previous code, images/task definitions and application policies together. Old permissions restore the old security exposure; rollback is an availability recovery, not a security fix. Do not reuse a task ID with a conflicting or expired launch record; inspect it and use a fresh task submission once the old compute is accounted for. + +The normal stack already creates distinct payload buckets for the selected backend. Check each backend in its own representative deployment. This runbook does not authorize or perform a deployment. + +## Required AWS evidence + +For **both ECS and MicroVM**, retain source/image identifiers, relevant policy snippets, sanitized error codes, AWS request IDs and timing. Never retain signed URLs, credentials or downloaded customer prompts in evidence. + +| Check | Expected result | +|---|---| +| New task with no stored launch | Coordinator gets `NoSuchKey`, creates immutable payload/reference, worker starts successfully. | +| Worker reads own deployment manifest | Allowed; hash/backend/config validation passes. | +| Worker lists its payload bucket | Explicitly denied. | +| Worker reads own or another task's payload/launch with ambient credentials | Explicitly denied, including guessed keys. | +| Worker reads a valid-looking manifest in another deployment/public bucket | Explicitly denied before configuration installation or payload download. | +| Worker puts/deletes a manifest, payload or launch record | Denied by effective policies; no alternate grant should permit mutation. | +| Correct signed URL versus modified task path/signature | Own URL succeeds; modified request fails. | +| Expired URL / expired signer credentials | S3 rejects; no configuration or pipeline starts; diagnostic has no bearer URL. | +| Same-account other-workspace secret substitution | Reject; cross-region secret explicitly present in the trusted manifest still works. | +| Two preparations / lost committed S3 reply | Same saved reference or explicit conflict, no overwrite of task instructions. | +| Lost MicroVM Run reply / coordinator restart | Same client token and exact request; existing VM recovered, no replacement. Record actual AWS retention/conflict behavior. | +| Typical/large registry-hydrated task | Manifest and exact S3 download work over runtime DNS/HTTPS; hook/override limits hold. #818 still needs its registry-resolution end-to-end case. | +| Success, failure, cancellation | Expected terminal status; compute terminated; both private task objects deleted or cleanup failure visibly recorded. | +| Attempted public MicroVM ingress | No usable public control path with explicit `NO_INGRESS`. Test while the VM is running. | +| Environment/log inspection | Repository subprocesses do not inherit `AGENT_PAYLOAD_REF`; normal/error logs contain no signed URL. | + +This boundary authenticates the boot path under the deployed policy. It does **not** prove complete isolation from a fully compromised worker: compute roles still select session tags and retain other platform permissions, and a stolen bearer link can be used until it expires or is revoked. See [coordinator metadata verification](./645-coordinator-metadata.md) for the remaining task-reporting and session-tag trust limits. diff --git a/scripts/check-constants-sync.ts b/scripts/check-constants-sync.ts index 536427486..a9615f9a6 100644 --- a/scripts/check-constants-sync.ts +++ b/scripts/check-constants-sync.ts @@ -49,7 +49,9 @@ const POLICY_PY = path.join(REPO_ROOT, 'agent/src/policy.py'); const JIRA_REACTIONS_PY = path.join(REPO_ROOT, 'agent/src/jira_reactions.py'); const SERVER_PY = path.join(REPO_ROOT, 'agent/src/server.py'); const CONFIG_PY = path.join(REPO_ROOT, 'agent/src/config.py'); -const PYTHON_CONSUMERS = [POLICY_PY, JIRA_REACTIONS_PY, SERVER_PY, CONFIG_PY]; +const PAYLOAD_BOOTSTRAP_PY = path.join(REPO_ROOT, 'agent/src/payload_bootstrap.py'); +const PAYLOAD_BOOTSTRAP_TS = path.join(REPO_ROOT, 'cdk/src/handlers/shared/payload-bootstrap.ts'); +const PYTHON_CONSUMERS = [POLICY_PY, JIRA_REACTIONS_PY, SERVER_PY, CONFIG_PY, PAYLOAD_BOOTSTRAP_PY]; const MICROVM_COMPUTE_TS = path.join(REPO_ROOT, 'cdk/src/constructs/lambda-microvm-compute.ts'); const TS_CONSUMERS = [MICROVM_COMPUTE_TS]; @@ -185,6 +187,15 @@ function main(): number { warmup_total_budget_seconds: number; warmup_required_timeout_seconds: number; }; + payload_bootstrap?: { + version: number; + manifest_prefix: string; + launch_filename: string; + max_manifest_bytes: number; + max_payload_bytes: number; + url_ttl_seconds: number; + minimum_url_lifetime_seconds: number; + }; }; try { json = JSON.parse(fs.readFileSync(CONSTANTS_JSON, 'utf-8')); @@ -356,6 +367,27 @@ function main(): number { ); } + const bootstrap = json.payload_bootstrap; + const bootstrapNumbers = [ + 'version', 'max_manifest_bytes', 'max_payload_bytes', + 'url_ttl_seconds', 'minimum_url_lifetime_seconds', + ] as const; + if (!bootstrap || bootstrapNumbers.some(key => !Number.isInteger(bootstrap[key]) || bootstrap[key] <= 0) + || typeof bootstrap.manifest_prefix !== 'string' || !/^[a-z][a-z0-9_-]*\/$/.test(bootstrap.manifest_prefix) + || typeof bootstrap.launch_filename !== 'string' || !/^[a-z][a-z0-9_-]*\.json$/.test(bootstrap.launch_filename) + || bootstrap.launch_filename === 'payload.json') { + invariantErrors.push('payload_bootstrap must define positive integer bounds and distinct safe object paths'); + } else if (bootstrap.minimum_url_lifetime_seconds > bootstrap.url_ttl_seconds + || bootstrap.max_manifest_bytes > bootstrap.max_payload_bytes) { + invariantErrors.push('payload_bootstrap minimum lifetime/manifest size exceeds its corresponding maximum'); + } + // Check that both implementations still read the shared block. Literal copies + // would allow a security cap or protocol version to drift across languages. + if (!/CONTRACT\s*=\s*SHARED_CONSTANTS\["payload_bootstrap"\]/.test(fs.readFileSync(PAYLOAD_BOOTSTRAP_PY, 'utf8')) + || !/PAYLOAD_BOOTSTRAP\s*=\s*constants\.payload_bootstrap/.test(fs.readFileSync(PAYLOAD_BOOTSTRAP_TS, 'utf8'))) { + invariantErrors.push('payload_bootstrap consumers must read the shared contract'); + } + if (invariantErrors.length > 0) { console.error(`Semantic invariant violations in ${CONSTANTS_JSON}:\n`); for (const e of invariantErrors) console.error(` - ${e}`); From e914c7f195ac81b64d46579775426ca1f7e16669 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 5 Nov 2026 15:54:49 +0000 Subject: [PATCH 2/5] fix(contracts): every ARN-shaped platform-config field must be validated (#1002, #817) An ARN-shaped key (`*_arn` / `*_ARN`) in `microvm_platform_config.env_by_key` that is missing from `arn_keys` now fails both the constants-sync check and agent import, so a new ARN field cannot silently skip the partition/account consistency check. The comments now say what the check is: consistency with the payload's own anchor ARN, not proof of deployment identity. --- agent/src/server.py | 5 ++ agent/tests/test_server.py | 60 +++++++++++++++++++ .../lambda-microvm-strategy.test.ts | 9 +++ cdk/test/scripts/check-constants-sync.test.ts | 23 +++++++ scripts/check-constants-sync.ts | 19 ++++-- 5 files changed, 110 insertions(+), 6 deletions(-) diff --git a/agent/src/server.py b/agent/src/server.py index b03809f1c..efb1ec7aa 100644 --- a/agent/src/server.py +++ b/agent/src/server.py @@ -1000,6 +1000,11 @@ def _validate_platform_config_contract() -> None: unknown_arn = sorted(MICROVM_PLATFORM_CONFIG_ARN_KEYS - set(MICROVM_PLATFORM_CONFIG_ENV_BY_KEY)) if unknown_arn: raise ValueError(f"{where}.arn_keys names key(s) absent from env_by_key: {unknown_arn}") + for key, env_name in MICROVM_PLATFORM_CONFIG_ENV_BY_KEY.items(): + if ( + key.endswith("_arn") or env_name.endswith("_ARN") + ) and key not in MICROVM_PLATFORM_CONFIG_ARN_KEYS: + raise ValueError(f"{where}: ARN-shaped key {key!r} is missing from arn_keys") anchor = MICROVM_PLATFORM_CONFIG_ACCOUNT_ANCHOR_KEY if anchor not in MICROVM_PLATFORM_CONFIG_ARN_KEYS: raise ValueError(f"{where}.account_anchor_key {anchor!r} must be one of arn_keys") diff --git a/agent/tests/test_server.py b/agent/tests/test_server.py index c128af8ae..0184799f7 100644 --- a/agent/tests/test_server.py +++ b/agent/tests/test_server.py @@ -1681,8 +1681,68 @@ def test_allowlist_is_sourced_from_the_shared_contract(self): from shared_constants import SHARED_CONSTANTS contract = SHARED_CONSTANTS["microvm_platform_config"] + assert set(contract) == {"env_by_key", "required", "arn_keys", "account_anchor_key"} assert contract["env_by_key"] == server.MICROVM_PLATFORM_CONFIG_ENV_BY_KEY assert frozenset(contract["required"]) == server.MICROVM_PLATFORM_CONFIG_REQUIRED_KEYS + assert frozenset(contract["arn_keys"]) == server.MICROVM_PLATFORM_CONFIG_ARN_KEYS + assert contract["account_anchor_key"] == server.MICROVM_PLATFORM_CONFIG_ACCOUNT_ANCHOR_KEY + + def test_arn_fields_and_account_anchor_are_explicitly_reviewed(self): + assert { + "github_token_secret_arn", + "linear_oauth_secret_arn", + "jira_oauth_secret_arn", + "agent_session_role_arn", + } == server.MICROVM_PLATFORM_CONFIG_ARN_KEYS + assert server.MICROVM_PLATFORM_CONFIG_ACCOUNT_ANCHOR_KEY == "agent_session_role_arn" + + @pytest.mark.parametrize( + "key,env_name", + [("new_resource_arn", "NEW_RESOURCE"), ("new_resource", "NEW_RESOURCE_ARN")], + ) + def test_new_arn_fields_cannot_omit_arn_validation(self, monkeypatch, key, env_name): + monkeypatch.setattr( + server, + "MICROVM_PLATFORM_CONFIG_ENV_BY_KEY", + {**server.MICROVM_PLATFORM_CONFIG_ENV_BY_KEY, key: env_name}, + ) + with pytest.raises(ValueError, match=r"ARN-shaped key.*missing from arn_keys"): + server._validate_platform_config_contract() + + monkeypatch.setattr( + server, + "MICROVM_PLATFORM_CONFIG_ARN_KEYS", + server.MICROVM_PLATFORM_CONFIG_ARN_KEYS | {key}, + ) + server._validate_platform_config_contract() + + @pytest.mark.parametrize( + "constant,value,error", + [ + ("MICROVM_PLATFORM_CONFIG_ARN_KEYS", frozenset(), "arn_keys must not be empty"), + ( + "MICROVM_PLATFORM_CONFIG_ARN_KEYS", + frozenset({"unknown_arn"}), + "arn_keys names key.*absent from env_by_key", + ), + ( + "MICROVM_PLATFORM_CONFIG_ACCOUNT_ANCHOR_KEY", + "task_table_name", + "must be one of arn_keys", + ), + ( + "MICROVM_PLATFORM_CONFIG_ACCOUNT_ANCHOR_KEY", + "linear_oauth_secret_arn", + "must also be listed in .required", + ), + ], + ) + def test_invalid_arn_contract_fails_before_serving_tasks( + self, monkeypatch, constant, value, error + ): + monkeypatch.setattr(server, constant, value) + with pytest.raises(ValueError, match=error): + server._validate_platform_config_contract() def test_wire_contract_is_exactly_the_documented_key_set(self): # Spelled out on purpose: this is the wire contract Stage B's producer is diff --git a/cdk/test/handlers/shared/strategies/lambda-microvm-strategy.test.ts b/cdk/test/handlers/shared/strategies/lambda-microvm-strategy.test.ts index cbda31ea3..df9800e08 100644 --- a/cdk/test/handlers/shared/strategies/lambda-microvm-strategy.test.ts +++ b/cdk/test/handlers/shared/strategies/lambda-microvm-strategy.test.ts @@ -1043,6 +1043,15 @@ describe('buildMicrovmPlatformConfig — the MicroVM substitute for a deploy-tim .toEqual(Object.keys(sharedConstants.microvm_platform_config.env_by_key)); expect([...MICROVM_PLATFORM_CONFIG_REQUIRED_KEYS]) .toEqual(sharedConstants.microvm_platform_config.required); + expect(Object.keys(sharedConstants.microvm_platform_config).sort()) + .toEqual(['account_anchor_key', 'arn_keys', 'env_by_key', 'required']); + expect(sharedConstants.microvm_platform_config.arn_keys).toEqual([ + 'github_token_secret_arn', + 'linear_oauth_secret_arn', + 'jira_oauth_secret_arn', + 'agent_session_role_arn', + ]); + expect(sharedConstants.microvm_platform_config.account_anchor_key).toBe('agent_session_role_arn'); // Keep the reviewed key inventory explicit. Payload/bootstrap hashing uses // canonical JSON, so insertion order does not alter retry identity. diff --git a/cdk/test/scripts/check-constants-sync.test.ts b/cdk/test/scripts/check-constants-sync.test.ts index e2e8b82b7..4f2f88e17 100644 --- a/cdk/test/scripts/check-constants-sync.test.ts +++ b/cdk/test/scripts/check-constants-sync.test.ts @@ -393,6 +393,29 @@ describe('check-constants-sync', () => { }); describe('ARN-pinning contract (review B5)', () => { + test.each([ + ['new_resource_arn', 'NEW_RESOURCE'], + ['new_resource', 'NEW_RESOURCE_ARN'], + ])('rejects an unvalidated ARN field %s → %s', (key, envName) => { + const result = runInMutatedRepo((root) => { + patchContract(root, (json) => { + json.microvm_platform_config.env_by_key[key] = envName; + }); + }); + expect(result.status).toBe(1); + expect(result.stderr).toContain(`ARN-shaped key "${key}" is missing from arn_keys`); + }); + + test('accepts a new ARN field when its validation is also declared', () => { + const result = runInMutatedRepo((root) => { + patchContract(root, (json) => { + json.microvm_platform_config.env_by_key.new_resource_arn = 'NEW_RESOURCE_ARN'; + json.microvm_platform_config.arn_keys.push('new_resource_arn'); + }); + }); + expect(result.status).toBe(0); + }); + test('rejects an arn_keys entry that is not a wire key', () => { const result = runInMutatedRepo((root) => { patchContract(root, (json) => { diff --git a/scripts/check-constants-sync.ts b/scripts/check-constants-sync.ts index a9615f9a6..1fd1f3a3f 100644 --- a/scripts/check-constants-sync.ts +++ b/scripts/check-constants-sync.ts @@ -298,12 +298,11 @@ function main(): number { invariantErrors.push('microvm_platform_config.required contains a duplicate'); } - // ARN pinning (ADR-021 P2, review B5). `arn_keys` names the values the agent - // pins to its own partition/account before installing them into the env that - // resolves credentials and fetches secrets; `account_anchor_key` names the ARN - // that supplies the expected partition/account. Both are validated here as well - // as at agent import time, because a malformed entry would silently WIDEN what - // the agent accepts from a network payload. + // ARN consistency (ADR-021 P2, review B5). `arn_keys` names the values checked + // against the partition/account supplied by `account_anchor_key`. That anchor + // comes from the same payload; agreement does not establish deployment identity. + // Validate both here and at agent import time so a new ARN field cannot + // silently skip the existing consistency check. if (!Array.isArray(mpc.arn_keys) || mpc.arn_keys.length === 0) { invariantErrors.push('microvm_platform_config.arn_keys must be a non-empty array'); } else { @@ -317,6 +316,14 @@ function main(): number { if (new Set(mpc.arn_keys).size !== mpc.arn_keys.length) { invariantErrors.push('microvm_platform_config.arn_keys contains a duplicate'); } + for (const [key, envName] of Object.entries(envByKey)) { + if ((key.endsWith('_arn') || (typeof envName === 'string' && envName.endsWith('_ARN'))) + && !mpc.arn_keys.includes(key)) { + invariantErrors.push( + `microvm_platform_config: ARN-shaped key "${key}" is missing from arn_keys`, + ); + } + } if (!mpc.arn_keys.includes(mpc.account_anchor_key)) { invariantErrors.push( 'microvm_platform_config.account_anchor_key must be one of arn_keys', From b940ebd2ea7fc9fd34b929c8af74c52855e2c4a8 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Mon, 16 Nov 2026 01:46:20 +0000 Subject: [PATCH 3/5] fix(security): pass the new lint, dead-code and typecheck gates - payload_bootstrap: mark the redirect handler's redirect_request as an @override (ARG002), and allowlist its fixed-signature newurl parameter for vulture - drop microvmPayloadKey, unused since the S3 payload path went away (knip) - name the parametrized cases of the substitution test (strict parametrization ids) - type the microvm execution-role statement filter with its Action field (typecheck) --- agent/.vulture_allowlist.py | 7 +++++++ agent/src/payload_bootstrap.py | 3 ++- agent/tests/test_payload_bootstrap.py | 1 + .../shared/strategies/lambda-microvm-strategy.ts | 11 ----------- cdk/test/constructs/lambda-microvm-compute.test.ts | 2 +- 5 files changed, 11 insertions(+), 13 deletions(-) diff --git a/agent/.vulture_allowlist.py b/agent/.vulture_allowlist.py index 8e8eb6bdf..35222a6fd 100644 --- a/agent/.vulture_allowlist.py +++ b/agent/.vulture_allowlist.py @@ -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) diff --git a/agent/src/payload_bootstrap.py b/agent/src/payload_bootstrap.py index b5133731b..9188e7c93 100644 --- a/agent/src/payload_bootstrap.py +++ b/agent/src/payload_bootstrap.py @@ -12,7 +12,7 @@ import json import os import re -from typing import Any +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 @@ -27,6 +27,7 @@ class PayloadFetchError(RuntimeError): class _NoRedirect(HTTPRedirectHandler): + @override def redirect_request(self, req, fp, code, msg, headers, newurl): return None diff --git a/agent/tests/test_payload_bootstrap.py b/agent/tests/test_payload_bootstrap.py index 04af816b0..12c284ff1 100644 --- a/agent/tests/test_payload_bootstrap.py +++ b/agent/tests/test_payload_bootstrap.py @@ -199,6 +199,7 @@ def test_run_hook_never_logs_the_chained_http_error_url(transport, monkeypatch, lambda d: d["agent_payload"].update(task_id="task-2"), lambda d: d.update(platform_config=None), ], + ids=["foreign-secret-arn", "document-task-id", "payload-task-id", "no-platform-config"], ) def test_same_account_workspace_redirect_or_task_substitution_is_rejected(transport, mutate): # Detach the document from the fixture's authenticated manifest values. diff --git a/cdk/src/handlers/shared/strategies/lambda-microvm-strategy.ts b/cdk/src/handlers/shared/strategies/lambda-microvm-strategy.ts index 963b04caf..8250d96c6 100644 --- a/cdk/src/handlers/shared/strategies/lambda-microvm-strategy.ts +++ b/cdk/src/handlers/shared/strategies/lambda-microvm-strategy.ts @@ -368,17 +368,6 @@ function wrapMicrovmError(operation: string, err: unknown): Error { return new Error(`${MICROVM_ERROR_MARKER} ${operation} failed: ${detail}`, { cause: safeCause }); } -/** - * S3 object key for a task's MicroVM ``/run`` payload. Same key shape as the - * ECS payload bucket (``ecsPayloadKey``): one object per task under its own - * task-id prefix, deleted by the orchestrator at finalize (see - * {@link deleteMicrovmPayload}), with the payload bucket's lifecycle-expiry rule - * (ADR-021 sub-decision 3, ``MICROVM_PAYLOAD_TTL_DAYS``) as the backstop. - */ -export function microvmPayloadKey(taskId: string): string { - return `${taskId}/payload.json`; -} - /** Remove task instructions and their saved download capability after finalization. * Best-effort; bucket lifecycle reaps leftovers. Deployment manifests are shared. */ diff --git a/cdk/test/constructs/lambda-microvm-compute.test.ts b/cdk/test/constructs/lambda-microvm-compute.test.ts index 94ad1854d..c30ebe3ed 100644 --- a/cdk/test/constructs/lambda-microvm-compute.test.ts +++ b/cdk/test/constructs/lambda-microvm-compute.test.ts @@ -723,7 +723,7 @@ describe('LambdaMicrovmCompute — image provisioned from a managed base image', const actions: string[] = statements.flatMap((s: { Action: string | string[] }) => Array.isArray(s.Action) ? s.Action : [s.Action]); - const allowed = statements.filter((s: { Effect: string }) => s.Effect === 'Allow' && s.Action === 's3:GetObject'); + const allowed = statements.filter((s: { Effect: string; Action?: string | string[] }) => s.Effect === 'Allow' && s.Action === 's3:GetObject'); expect(allowed).toHaveLength(1); expect(JSON.stringify(allowed[0].Resource)).toContain('/bootstrap/*'); const denied = statements.find((s: { NotResource?: unknown }) => s.NotResource); From aef7c31e2e642f64c231a65603a0e08771c27822 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Mon, 16 Nov 2026 02:18:13 +0000 Subject: [PATCH 4/5] docs(verification): drop links to two pages that were never committed (link check) --- docs/verification/645-payload-bootstrap.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/verification/645-payload-bootstrap.md b/docs/verification/645-payload-bootstrap.md index 34018e577..f3b12f3bb 100644 --- a/docs/verification/645-payload-bootstrap.md +++ b/docs/verification/645-payload-bootstrap.md @@ -89,7 +89,7 @@ Permission tests inspect synthesized IAM policies, including the `NotResource` e An offline compatibility probe generated a URL using the actual JavaScript AWS SDK with dummy credentials and passed it through the Python URL parser. That proves the observed SDK URL shape is supported; it makes no AWS authorization claim. -See the [implementation checklist](./645-p3-implementation-plan.md#implementation-progress) for final suite counts. Mock authorization failures are not proof of effective AWS IAM. Conditional S3 writes and the missing-object behavior must also be checked live. +Mock authorization failures are not proof of effective AWS IAM. Conditional S3 writes and the missing-object behavior must also be checked live. ## Coordinated deployment and rollback @@ -124,4 +124,4 @@ For **both ECS and MicroVM**, retain source/image identifiers, relevant policy s | Attempted public MicroVM ingress | No usable public control path with explicit `NO_INGRESS`. Test while the VM is running. | | Environment/log inspection | Repository subprocesses do not inherit `AGENT_PAYLOAD_REF`; normal/error logs contain no signed URL. | -This boundary authenticates the boot path under the deployed policy. It does **not** prove complete isolation from a fully compromised worker: compute roles still select session tags and retain other platform permissions, and a stolen bearer link can be used until it expires or is revoked. See [coordinator metadata verification](./645-coordinator-metadata.md) for the remaining task-reporting and session-tag trust limits. +This boundary authenticates the boot path under the deployed policy. It does **not** prove complete isolation from a fully compromised worker: compute roles still select session tags and retain other platform permissions, and a stolen bearer link can be used until it expires or is revoked. The remaining task-reporting and session-tag trust limits are outside this document. From 5c90c1489bfeeea04a8b7e1fc5c459dd1ed162c6 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Mon, 16 Nov 2026 15:19:26 +0000 Subject: [PATCH 5/5] docs: regenerate the Starlight mirrors with main's generator --- docs/src/content/docs/architecture/Compute.md | 2 +- docs/src/content/docs/architecture/Security.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/src/content/docs/architecture/Compute.md b/docs/src/content/docs/architecture/Compute.md index 55c550e50..53a517b36 100644 --- a/docs/src/content/docs/architecture/Compute.md +++ b/docs/src/content/docs/architecture/Compute.md @@ -119,7 +119,7 @@ See [ORCHESTRATOR.md](/sample-autonomous-cloud-coding-agents/architecture/orches Lambda MicroVMs are an opt-in third backend. Include `lambda-microvm` in `compute_types`; repositories inherit the first listed backend or choose a deployed backend through an override. Legacy `compute_type=lambda-microvm` deploys AgentCore and MicroVM, with AgentCore as the default. Image configuration has three states: a managed base-image ARN and version creates the snapshot image in CDK; an external image identifier uses a snapshot built out of band; and supplying neither provisions only the roles, buckets, and connectors needed for the bootstrap deploy. `cdk/scripts/package-microvm-artifact.sh` packages the agent as zip + Dockerfile, uploads it to the artifact bucket, and can create the external image. Lambda MicroVMs are available in five launch regions (us-east-1, us-east-2, us-west-2, eu-west-1, ap-northeast-1) and will expand; the platform enforces regional availability in layers via a synth-time constant, onboarding live probes, and orchestration-time classification. -Because a snapshot freezes its build-time environment, current deployment identifiers arrive through the v2 payload bootstrap. The coordinator publishes a non-secret deployment manifest and sends a single-object signed download URL for the task. The worker reads only its deployment's `bootstrap/*` with ambient credentials; other object reads and payload-bucket listing are explicitly denied. The downloaded task identity and configuration must match the authenticated manifest before configuration installation. The serialized reference fits the verified 4,096-byte hook limit; all payload sizes use S3. ECS shares this transport through `AGENT_PAYLOAD_REF`. [ADR-021 §3](/sample-autonomous-cloud-coding-agents/architecture/adr-021-lambda-microvms-compute-backend#3-packaging-same-agent-image-source-new-build-path) defines the wire format, compatibility change and pending live gates. +Because a snapshot freezes its build-time environment, current deployment identifiers arrive through the v2 payload bootstrap. The coordinator publishes a non-secret deployment manifest and sends a single-object signed download URL for the task. The worker reads only its deployment's `bootstrap/*` with ambient credentials; other object reads and payload-bucket listing are explicitly denied. The downloaded task identity and configuration must match the authenticated manifest before configuration installation. The serialized reference fits the verified 4,096-byte hook limit; all payload sizes use S3. ECS shares this transport through `AGENT_PAYLOAD_REF`. [ADR-021 §3](/sample-autonomous-cloud-coding-agents/decisions/adr-021-lambda-microvms-compute-backend#3-packaging-same-agent-image-source-new-build-path) defines the wire format, compatibility change and pending live gates. Networking separates image build from execution: the build-only connector permits TCP 80 and 443 because the Dockerfile uses `apt-get`, while running MicroVMs retain 443-only egress through the platform VPC. Every launch explicitly passes the Lambda-managed `NO_INGRESS` connector; omission would select the service's public-ingress default. The P2 image declares and serves `/ready` and `/validate` at build time and `/run` and `/terminate` at runtime. `/suspend` and `/resume` remain disabled until their P3 implementation. diff --git a/docs/src/content/docs/architecture/Security.md b/docs/src/content/docs/architecture/Security.md index 39379c374..28f703ee8 100644 --- a/docs/src/content/docs/architecture/Security.md +++ b/docs/src/content/docs/architecture/Security.md @@ -48,7 +48,7 @@ Three authentication mechanisms protect the platform, matching its input channel The compute role retains only non-tenant access (Bedrock model invocation — already ARN-scoped; CloudWatch Logs; the GitHub PAT secret, read once before the SessionRole is assumed; AgentCore Memory) plus `sts:AssumeRole`/`sts:TagSession` on the SessionRole. Because the agent runs under credentials that are themselves an assumed role, its `AssumeRole` is *role chaining* — capped at one hour regardless of the role's max session duration — so the agent uses a **refreshable** credential provider that re-assumes before expiry (tasks can run up to the 8-hour `maxLifetime`). The design is backend-agnostic: the same SessionRole and agent code serve all three backends (AgentCore Runtime, ECS Fargate, Lambda MicroVMs). A compromised agent session is therefore confined to its own task's data, enforced at the IAM layer rather than by application-code conventions. The policy structure (the `dynamodb:LeadingKeys` condition on `${aws:PrincipalTag/task_id}`, per-user S3 prefixes, and `Scan` exclusion) is asserted by CDK template tests, and the refreshable-credential and session-tag flow by agent unit tests; the matching-tag → allow / mismatched-or-absent-tag → deny behaviour was additionally confirmed once via the IAM policy simulator during development. -**Lambda MicroVMs compute-role delta** - On this backend the compute role additionally holds prefix-scoped `secretsmanager:GetSecretValue` on the per-workspace channel-OAuth secrets (`bgagent-linear-oauth-*`, `bgagent-jira-oauth-*`), read access only to its payload bucket's `bootstrap/*` manifests (other object reads and payload-bucket listing are explicitly denied), and `ec2:DescribeAvailabilityZones` (`Resource: *`, read-only — EC2 describe actions have no resource-level scoping) for a CDK repo's own synth gate. It is also **the only compute role in the platform whose trust policy carries no confused-deputy condition**: the Lambda MicroVMs service populates no `aws:SourceAccount` or `aws:SourceArn` when it assumes the role, so a trust policy carrying one is unassumable — verified live, not assumed (connector creation failed deterministically, and `RunMicrovm` surfaced the same root cause as a misleading caller-side `iam:PassRole` denial). The compensating controls are that each of the three MicroVM roles can be passed to `lambda.amazonaws.com` only by a named principal — the orchestrator, via an `iam:PassRole` scoped to the execution role's exact ARN, and the CloudFormation deployment role for the build and connector-operator roles — that every other resource they reach is account-scoped by ARN apart from two justified `Resource: *` read/create-time statements, and that none of them holds `iam:*`, cross-account trust, or any `sts:AssumeRole` beyond the execution role's scoped hop to the per-task SessionRole. Full evidence, the two-arm PassRole experiment, and the alternatives considered are in [ADR-021 §4](/sample-autonomous-cloud-coding-agents/architecture/adr-021-lambda-microvms-compute-backend#4-infra-and-iam-conditional-resources-behind-bootstrap-computetypes). +**Lambda MicroVMs compute-role delta** - On this backend the compute role additionally holds prefix-scoped `secretsmanager:GetSecretValue` on the per-workspace channel-OAuth secrets (`bgagent-linear-oauth-*`, `bgagent-jira-oauth-*`), read access only to its payload bucket's `bootstrap/*` manifests (other object reads and payload-bucket listing are explicitly denied), and `ec2:DescribeAvailabilityZones` (`Resource: *`, read-only — EC2 describe actions have no resource-level scoping) for a CDK repo's own synth gate. It is also **the only compute role in the platform whose trust policy carries no confused-deputy condition**: the Lambda MicroVMs service populates no `aws:SourceAccount` or `aws:SourceArn` when it assumes the role, so a trust policy carrying one is unassumable — verified live, not assumed (connector creation failed deterministically, and `RunMicrovm` surfaced the same root cause as a misleading caller-side `iam:PassRole` denial). The compensating controls are that each of the three MicroVM roles can be passed to `lambda.amazonaws.com` only by a named principal — the orchestrator, via an `iam:PassRole` scoped to the execution role's exact ARN, and the CloudFormation deployment role for the build and connector-operator roles — that every other resource they reach is account-scoped by ARN apart from two justified `Resource: *` read/create-time statements, and that none of them holds `iam:*`, cross-account trust, or any `sts:AssumeRole` beyond the execution role's scoped hop to the per-task SessionRole. Full evidence, the two-arm PassRole experiment, and the alternatives considered are in [ADR-021 §4](/sample-autonomous-cloud-coding-agents/decisions/adr-021-lambda-microvms-compute-backend#4-infra-and-iam-conditional-resources-behind-bootstrap-computetypes). **ECS/MicroVM task bootstrap (v2)** — The coordinator publishes non-secret deployment manifests and supplies a short-lived signed URL for exactly one task's payload. The worker reads the manifest with its ambient role, whose explicit deny outside its own `bootstrap/*` prevents a foreign public bucket from authorizing fake configuration. It verifies downloaded task identity and exact manifest/config agreement before installing MicroVM settings. The coordinator privately persists the URL outside TaskTable for retry and deletes both task objects at finalization. Worker roles cannot read/list task objects using their ambient credentials. A signed URL is a bearer capability: redact it in errors and keep it out of task rows and repository subprocess environments. Existing session-tag trust and other platform grants remain separate limitations. This protocol is implemented locally; real IAM/network/expiry gates and the coordinated image/coordinator/policy rollout are documented in the repository's `docs/verification/645-payload-bootstrap.md`.