From 9a2596c56830017552de8b81628cb8454111ffaf Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 5 Nov 2026 15:08:20 +0000 Subject: [PATCH 1/8] feat(security): trusted approval writer so workers cannot write approval records (#1000) Workers wrote PENDING approval rows directly with task-scoped session credentials that live alongside the repository's code, so malicious or prompt-injected repo code could write any approval record for its task. - ApprovalRequestService (nested stack): IAM-authenticated API Gateway + request-approval Lambda. POST /tasks/{task_id} accepts only "create" (PENDING request + RUNNING -> AWAITING_APPROVAL, one transaction) and "timeout" (PENDING -> TIMED_OUT, conditioned on the task still awaiting that request). It validates a fixed field set, ownership and deadline_epoch, and sets the row TTL itself. - The session role may invoke only /tasks/${aws:PrincipalTag/task_id}; the approvals table moves to a task-scoped read-only grant (listing it as read/write as well fails synth). - Every backend gets APPROVAL_REQUESTS_API_URL: AgentCore runtime env, ECS task env (reserved key), MicroVM platform config (new required contract key approval_requests_api_url). - Agent: approval_requests.py signs requests (SigV4, no redirects, endpoint validated) and never sends retention; task_state routes create/timeout through it and refuses human statuses; hooks carry deadline_epoch. - ADR-025 records the decision. --- agent/src/approval_requests.py | 120 ++++++++++ agent/src/hooks.py | 13 +- agent/src/task_state.py | 40 +++- agent/tests/test_approval_requests.py | 140 ++++++++++++ agent/tests/test_server.py | 4 +- agent/tests/test_task_state.py | 4 +- cdk/src/constructs/agent-session-role.ts | 21 ++ .../constructs/approval-request-service.ts | 103 +++++++++ cdk/src/constructs/ecs-agent-cluster.ts | 9 + cdk/src/constructs/task-orchestrator.ts | 6 + cdk/src/handlers/request-approval.ts | 209 ++++++++++++++++++ cdk/src/handlers/shared/response.ts | 2 + cdk/src/stacks/agent.ts | 19 +- .../constructs/agent-session-role.test.ts | 40 +++- .../approval-request-service.test.ts | 84 +++++++ .../handlers/orchestrate-task-microvm.test.ts | 1 + .../handlers/request-approval-local.test.ts | 171 ++++++++++++++ cdk/test/handlers/request-approval.test.ts | 145 ++++++++++++ .../lambda-microvm-strategy.test.ts | 17 +- .../start-session-composition.test.ts | 1 + contracts/constants.json | 2 + .../ADR-025-trusted-approval-writer.md | 36 +++ .../Adr-025-trusted-approval-writer.md | 40 ++++ 23 files changed, 1214 insertions(+), 13 deletions(-) create mode 100644 agent/src/approval_requests.py create mode 100644 agent/tests/test_approval_requests.py create mode 100644 cdk/src/constructs/approval-request-service.ts create mode 100644 cdk/src/handlers/request-approval.ts create mode 100644 cdk/test/constructs/approval-request-service.test.ts create mode 100644 cdk/test/handlers/request-approval-local.test.ts create mode 100644 cdk/test/handlers/request-approval.test.ts create mode 100644 docs/decisions/ADR-025-trusted-approval-writer.md create mode 100644 docs/src/content/docs/decisions/Adr-025-trusted-approval-writer.md diff --git a/agent/src/approval_requests.py b/agent/src/approval_requests.py new file mode 100644 index 000000000..41f67b14b --- /dev/null +++ b/agent/src/approval_requests.py @@ -0,0 +1,120 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 + +"""IAM-signed requests to the control-plane approval writer.""" + +import json +import os +import re +from http import HTTPStatus +from urllib.parse import urlsplit + +import requests +from botocore.auth import SigV4Auth +from botocore.awsrequest import AWSRequest +from botocore.exceptions import ClientError + +from aws_session import get_session +from ua import sanitize_ua_value, static_user_agent_extra + +API_ENV = "APPROVAL_REQUESTS_API_URL" + + +def configured() -> bool: + available = bool(os.environ.get(API_ENV)) + if not available and os.environ.get("AGENT_SESSION_ROLE_ARN"): + raise RuntimeError( + "APPROVAL_REQUESTS_API_URL is required for cloud approval requests; " + "deploy matching CDK and worker images" + ) + return available + + +def record_request( + operation: str, + task_id: str, + request_id: str, + *, + approval: dict | None = None, + reason: str | None = None, +) -> None: + """Sign the task path with scoped credentials; never follow redirects.""" + endpoint = os.environ.get(API_ENV, "").rstrip("/") + parsed = urlsplit(endpoint) + match = re.fullmatch( + r"[a-z0-9]+\.execute-api\.([a-z0-9-]+)\.amazonaws\.com(?:\.cn)?", parsed.hostname or "" + ) + if ( + parsed.scheme != "https" + or not match + or parsed.username + or parsed.password + or parsed.port not in (None, 443) + or parsed.query + or parsed.fragment + or not re.fullmatch(r"/[A-Za-z0-9_-]+", parsed.path) + or not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", task_id) + or operation not in {"create", "timeout"} + ): + raise ValueError("Invalid approval request endpoint, task id or operation") + payload = {"operation": operation, "task_id": task_id, "request_id": request_id} + if approval is not None: + # Retention is set by the trusted writer, never by the worker. + payload["approval"] = {key: value for key, value in approval.items() if key != "ttl"} + if reason is not None: + payload["reason"] = reason + body = json.dumps(payload, separators=(",", ":")).encode() + user_agent = static_user_agent_extra() + app_id = os.environ.get("AWS_SDK_UA_APP_ID") + if app_id: + user_agent += f" app/{sanitize_ua_value(app_id)}" + url = f"{endpoint}/tasks/{task_id}" + request = AWSRequest( + method="POST", + url=url, + data=body, + headers={"Content-Type": "application/json", "User-Agent": user_agent}, + ) + credentials = get_session().get_credentials() + if credentials is None: + raise RuntimeError("Approval request credentials unavailable") + SigV4Auth(credentials.get_frozen_credentials(), "execute-api", match.group(1)).add_auth(request) + response = requests.post( + url, + data=body, + headers=dict(request.headers), + timeout=(5, 20), + allow_redirects=False, + ) + try: + result = response.json() + except ValueError as exc: + raise RuntimeError( + f"Approval service returned invalid JSON (HTTP {response.status_code})" + ) from exc + data = result.get("data") if isinstance(result, dict) else None + if response.status_code == HTTPStatus.OK and isinstance(data, dict) and data.get("ok") is True: + return + error = result.get("error") if isinstance(result, dict) else None + code = ( + error.get("code", "ApprovalServiceUnavailable") + if isinstance(error, dict) + else "ApprovalServiceUnavailable" + ) + details = error.get("details") if isinstance(error, dict) else None + reasons = details.get("cancellation_reasons", []) if isinstance(details, dict) else [] + message = "Control plane did not acknowledge the approval write" + raise ClientError( + { + "Error": { + "Code": code, + "Message": message, + }, + "CancellationReasons": reasons, + "ResponseMetadata": { + "HTTPStatusCode": response.status_code, + "RequestId": error.get("request_id") if isinstance(error, dict) else None, + }, + }, + "RecordApprovalRequest", + ) diff --git a/agent/src/hooks.py b/agent/src/hooks.py index 99a1252cd..e0a0b42fd 100644 --- a/agent/src/hooks.py +++ b/agent/src/hooks.py @@ -24,7 +24,7 @@ import re import time from collections.abc import Callable -from datetime import UTC +from datetime import UTC, datetime from typing import TYPE_CHECKING, Any import nudge_reader @@ -627,6 +627,17 @@ async def _handle_require_approval( "user_id": user_id or "", "repo": engine.repo, } + # The trusted approval writer cross-checks the deadline against + # created_at + timeout_s, so the row carries it explicitly. + if effective_timeout > 0: + row["deadline_epoch"] = ( + int( + datetime.strptime(row["created_at"], "%Y-%m-%dT%H:%M:%SZ") + .replace(tzinfo=UTC) + .timestamp() + ) + + effective_timeout + ) # Step 6 — bump counters BEFORE the write so cap/rate checks on # subsequent gates reflect the attempt even if the DDB write itself diff --git a/agent/src/task_state.py b/agent/src/task_state.py index bf40d712f..93c78d6d0 100644 --- a/agent/src/task_state.py +++ b/agent/src/task_state.py @@ -7,7 +7,7 @@ import os import time -from typing import TypedDict +from typing import NotRequired, TypedDict from shell import log, log_error_cw @@ -35,6 +35,7 @@ class ApprovalRow(TypedDict): created_at: str timeout_s: int ttl: int + deadline_epoch: NotRequired[int] user_id: str repo: str @@ -664,6 +665,9 @@ def transact_write_approval_request( ) -> None: """Atomically record a pending approval + transition the task to AWAITING_APPROVAL. + The trusted approval service performs the transaction when configured. Direct + DynamoDB is retained only for unscoped local/legacy deployments. + Two items: 1. Put on ``TaskApprovalsTable`` with ``ConditionExpression: attribute_not_exists(request_id)`` — guards against ULID collisions @@ -680,6 +684,23 @@ def transact_write_approval_request( DDB-layer exceptions propagate so the hook's outer try/except can fail-closed with a specific reason. """ + import approval_requests + + if approval_requests.configured(): + try: + approval_requests.record_request( + "create", task_id, request_id, approval=dict(approval_row) + ) + return + except Exception as exc: + if _extract_error_code(exc) == "TransactionCanceledException": + reasons = _extract_cancellation_reasons(exc) + raise ApprovalWriteError( + f"approval write cancelled: reasons={reasons}", cancellation_reasons=reasons + ) from exc + raise + # Compatibility with unscoped legacy/local deployments. configured() rejects + # a missing service URL for cloud workers that use the session role. task_table, approvals_table = _require_tables() ddb = _get_ddb_client(client=client) @@ -804,6 +825,23 @@ def best_effort_update_approval_status( Returns ``True`` on successful write, ``False`` on ``ConditionalCheckFailedException``. All other errors propagate. """ + import approval_requests + + if new_status != "TIMED_OUT": + raise ValueError("Workers may record only non-human timeouts") + if approval_requests.configured(): + try: + approval_requests.record_request("timeout", task_id, request_id, reason=reason) + return True + except Exception as exc: + reasons = _extract_cancellation_reasons(exc) + if _extract_error_code(exc) == "TransactionCanceledException" and ( + reasons + and reasons[0].get("Code") == "ConditionalCheckFailed" + and all(reason.get("Code") == "None" for reason in reasons[1:]) + ): + return False + raise _, approvals_table = _require_tables() ddb = _get_ddb_client(client=client) diff --git a/agent/tests/test_approval_requests.py b/agent/tests/test_approval_requests.py new file mode 100644 index 000000000..9b7e453bb --- /dev/null +++ b/agent/tests/test_approval_requests.py @@ -0,0 +1,140 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 + +import json +from types import SimpleNamespace +from unittest.mock import MagicMock + +import pytest +from botocore.credentials import Credentials +from botocore.exceptions import ClientError + +import approval_requests as broker +import task_state + + +def pending_request() -> task_state.ApprovalRow: + return { + "task_id": "task", + "request_id": "request", + "tool_name": "Bash", + "tool_input_preview": '{"command":"git push"}', + "tool_input_sha256": "a" * 64, + "reason": "Protected operation", + "severity": "high", + "matching_rule_ids": ["protected"], + "status": "PENDING", + "created_at": "2026-09-18T00:00:00Z", + "timeout_s": 0, + "ttl": 1_800_000_000, + "user_id": "owner", + "repo": "owner/repo", + } + + +@pytest.fixture +def transport(monkeypatch): + monkeypatch.setenv(broker.API_ENV, "https://fixture.execute-api.us-east-1.amazonaws.com/v1/") + session = MagicMock() + session.get_credentials.return_value = Credentials( + "testing", "testing-secret", "testing-session" + ) + monkeypatch.setattr(broker, "get_session", lambda: session) + post = MagicMock( + return_value=SimpleNamespace(status_code=200, json=lambda: {"data": {"ok": True}}) + ) + monkeypatch.setattr(broker.requests, "post", post) + return post + + +def test_scoped_signature_binds_the_task_path_and_does_not_redirect(transport): + broker.record_request("create", "task", "request", approval={"status": "PENDING"}) + args, kwargs = transport.call_args + assert args == ("https://fixture.execute-api.us-east-1.amazonaws.com/v1/tasks/task",) + assert "execute-api/aws4_request" in kwargs["headers"]["Authorization"] + assert kwargs["headers"]["X-Amz-Security-Token"] == "testing-session" + assert "md/uksb-wt64nei4u6#agent" in kwargs["headers"]["User-Agent"] + assert kwargs["allow_redirects"] is False + assert json.loads(kwargs["data"])["task_id"] == "task" + + +@pytest.mark.parametrize( + "url", + [ + "http://fixture.execute-api.us-east-1.amazonaws.com/v1", + "https://attacker.example/v1", + "https://fixture.execute-api.us-east-1.amazonaws.com/v1?redirect=elsewhere", + ], +) +def test_rejects_untrusted_endpoints_before_signing(transport, monkeypatch, url): + monkeypatch.setenv(broker.API_ENV, url) + with pytest.raises(ValueError): + broker.record_request("create", "task", "request") + transport.assert_not_called() + + +def test_new_writers_use_service_instead_of_direct_dynamodb(transport, monkeypatch): + direct = MagicMock() + monkeypatch.setattr(task_state, "_get_ddb_client", direct) + task_state.transact_write_approval_request("task", "request", pending_request()) + assert task_state.best_effort_update_approval_status("task", "request", "TIMED_OUT") + assert transport.call_count == 2 + direct.assert_not_called() + + +@pytest.mark.parametrize("operation", ["create", "timeout"]) +def test_cloud_worker_missing_endpoint_reports_configuration_error(monkeypatch, operation): + monkeypatch.delenv(broker.API_ENV, raising=False) + monkeypatch.setenv("AGENT_SESSION_ROLE_ARN", "arn:aws:iam::123456789012:role/session") + direct = MagicMock() + monkeypatch.setattr(task_state, "_get_ddb_client", direct) + with pytest.raises(RuntimeError, match=r"APPROVAL_REQUESTS_API_URL.*matching CDK"): + if operation == "create": + task_state.transact_write_approval_request("task", "request", pending_request()) + else: + task_state.best_effort_update_approval_status("task", "request", "TIMED_OUT") + direct.assert_not_called() + + +@pytest.mark.parametrize("status", ["APPROVED", "DENIED", "PENDING", "CANCELLED"]) +def test_worker_api_cannot_record_a_human_decision(transport, status): + with pytest.raises(ValueError, match="non-human timeouts"): + task_state.best_effort_update_approval_status("task", "request", status) + transport.assert_not_called() + + +def test_uncertain_service_write_does_not_fall_back_to_direct_dynamodb(transport, monkeypatch): + direct = MagicMock() + monkeypatch.setattr(task_state, "_get_ddb_client", direct) + transport.side_effect = TimeoutError("reply lost") + with pytest.raises(TimeoutError): + task_state.transact_write_approval_request("task", "request", pending_request()) + direct.assert_not_called() + + +def test_timeout_race_preserves_human_winner_but_task_check_failure_is_not_benign(transport): + # Item 0 is the approval row (still PENDING?), item 1 the task check. + reasons = [{"Code": "ConditionalCheckFailed"}, {"Code": "None"}] + transport.return_value = SimpleNamespace( + status_code=409, + json=lambda: { + "error": { + "code": "TransactionCanceledException", + "details": {"cancellation_reasons": reasons}, + }, + }, + ) + # A human decision already replaced PENDING: the caller re-reads and honors it. + assert not task_state.best_effort_update_approval_status("task", "request", "TIMED_OUT") + # The task left AWAITING_APPROVAL: never silently treated as "human won". + reasons[:] = [{"Code": "None"}, {"Code": "ConditionalCheckFailed"}] + with pytest.raises(ClientError, match="did not acknowledge") as failure: + task_state.best_effort_update_approval_status("task", "request", "TIMED_OUT") + assert failure.value.response["Error"]["Code"] == "TransactionCanceledException" + + +def test_worker_never_sends_retention(transport): + broker.record_request("create", "task", "request", approval=dict(pending_request())) + sent = json.loads(transport.call_args.kwargs["data"])["approval"] + assert "ttl" not in sent + assert sent["status"] == "PENDING" diff --git a/agent/tests/test_server.py b/agent/tests/test_server.py index 0ac6990ea..e99dc7354 100644 --- a/agent/tests/test_server.py +++ b/agent/tests/test_server.py @@ -1807,6 +1807,7 @@ def test_wire_contract_is_exactly_the_documented_key_set(self): "task_table_name": "TASK_TABLE_NAME", "task_events_table_name": "TASK_EVENTS_TABLE_NAME", "task_approvals_table_name": "TASK_APPROVALS_TABLE_NAME", + "approval_requests_api_url": "APPROVAL_REQUESTS_API_URL", "nudges_table_name": "NUDGES_TABLE_NAME", "log_group_name": "LOG_GROUP_NAME", "artifacts_bucket_name": "ARTIFACTS_BUCKET_NAME", @@ -1829,12 +1830,13 @@ def test_wire_contract_is_exactly_the_documented_key_set(self): "linear_workload_identity_name": "LINEAR_WORKLOAD_IDENTITY_NAME", } - def test_required_subset_is_exactly_the_four_run_blocking_keys(self): + def test_required_subset_is_exactly_the_run_blocking_keys(self): assert ( frozenset( { "task_table_name", "task_events_table_name", + "approval_requests_api_url", "github_token_secret_arn", "agent_session_role_arn", } diff --git a/agent/tests/test_task_state.py b/agent/tests/test_task_state.py index b0eef03d9..55c132e0c 100644 --- a/agent/tests/test_task_state.py +++ b/agent/tests/test_task_state.py @@ -884,12 +884,12 @@ def test_reason_optional_attached(self, approval_tables_env): client.update_item.return_value = {} task_state.best_effort_update_approval_status( - "01KTASK", "01KREQ", "DENIED", reason="no prod pushes", client=client + "01KTASK", "01KREQ", "TIMED_OUT", reason="polling failed", client=client ) call = client.update_item.call_args assert "deny_reason = :reason" in call.kwargs["UpdateExpression"] - assert call.kwargs["ExpressionAttributeValues"][":reason"] == {"S": "no prod pushes"} + assert call.kwargs["ExpressionAttributeValues"][":reason"] == {"S": "polling failed"} def test_conditional_check_failed_returns_false(self, approval_tables_env): """IMPL-24 — this is the VM-throttle race signal the hook re-reads on.""" diff --git a/cdk/src/constructs/agent-session-role.ts b/cdk/src/constructs/agent-session-role.ts index 94ed12a0a..741e7be81 100644 --- a/cdk/src/constructs/agent-session-role.ts +++ b/cdk/src/constructs/agent-session-role.ts @@ -54,6 +54,14 @@ export interface AgentSessionRoleProps { */ readonly taskScopedTables: dynamodb.ITable[]; + /** + * Approvals table: READ-ONLY for the session (its own task's rows). Workers + * observe human decisions and use the rows in transaction condition checks, + * but write requests only through the trusted approval writer + * (`ApprovalRequestService`). Must not also appear in `taskScopedTables`. + */ + readonly approvalsTable?: dynamodb.ITable; + /** * Trace-artifacts bucket. The agent writes `traces//...`; * `s3:PutObject` is scoped to the `traces/${aws:PrincipalTag/user_id}/` @@ -170,6 +178,19 @@ export class AgentSessionRole extends Construct { // One statement per table keeps the resource ARNs explicit. The condition // requires the request's partition key (task_id) to equal the session's // task_id tag. ForAllValues is required by DynamoDB for LeadingKeys. + if (props.approvalsTable + && props.taskScopedTables.some((table) => table.tableArn === props.approvalsTable!.tableArn)) { + throw new Error('approvalsTable must not appear in taskScopedTables: workers may only read approval records'); + } + if (props.approvalsTable) { + this.role.addToPolicy(new iam.PolicyStatement({ + actions: ['dynamodb:GetItem', 'dynamodb:BatchGetItem', 'dynamodb:Query', 'dynamodb:ConditionCheckItem'], + resources: [props.approvalsTable.tableArn], + conditions: { + 'ForAllValues:StringEquals': { 'dynamodb:LeadingKeys': ['${aws:PrincipalTag/task_id}'] }, + }, + })); + } for (const table of props.taskScopedTables) { this.role.addToPolicy( new iam.PolicyStatement({ diff --git a/cdk/src/constructs/approval-request-service.ts b/cdk/src/constructs/approval-request-service.ts new file mode 100644 index 000000000..c5179e5f4 --- /dev/null +++ b/cdk/src/constructs/approval-request-service.ts @@ -0,0 +1,103 @@ +/** + * 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 path from 'node:path'; +import { Duration, NestedStack } from 'aws-cdk-lib'; +import * as apigw from 'aws-cdk-lib/aws-apigateway'; +import type * as dynamodb from 'aws-cdk-lib/aws-dynamodb'; +import * as iam from 'aws-cdk-lib/aws-iam'; +import { Architecture, Runtime } from 'aws-cdk-lib/aws-lambda'; +import { NodejsFunction } from 'aws-cdk-lib/aws-lambda-nodejs'; +import * as logs from 'aws-cdk-lib/aws-logs'; +import { NagSuppressions } from 'cdk-nag'; +import type { Construct } from 'constructs'; + +const REQUEST_TIMEOUT_SECONDS = 15; +/** + * Trusted approval writer. A separate API keeps routes inside this child stack. + * IAM binds a signed POST path to the session's task tag; direct Lambda invoke + * would lose that binding because Lambda does not expose caller session tags. + */ +export class ApprovalRequestService extends NestedStack { + public readonly api: apigw.RestApi; + public readonly fn: NodejsFunction; + + constructor(scope: Construct, id: string, props: { + taskTable: dynamodb.ITable; + approvalsTable: dynamodb.ITable; + }) { + super(scope, id); + this.fn = new NodejsFunction(this, 'RequestFn', { + entry: path.join(__dirname, '..', 'handlers', 'request-approval.ts'), + handler: 'handler', + runtime: Runtime.NODEJS_24_X, + architecture: Architecture.ARM_64, + timeout: Duration.seconds(REQUEST_TIMEOUT_SECONDS), + memorySize: 256, + environment: { + ABCA_COMPONENT: 'approval', + TASK_TABLE_NAME: props.taskTable.tableName, + TASK_APPROVALS_TABLE_NAME: props.approvalsTable.tableName, + }, + }); + this.fn.addToRolePolicy(new iam.PolicyStatement({ + actions: ['dynamodb:GetItem', 'dynamodb:UpdateItem', 'dynamodb:ConditionCheckItem'], + resources: [props.taskTable.tableArn], + })); + this.fn.addToRolePolicy(new iam.PolicyStatement({ + actions: ['dynamodb:PutItem', 'dynamodb:UpdateItem'], + resources: [props.approvalsTable.tableArn], + })); + const accessLogs = new logs.LogGroup(this, 'AccessLogs', { retention: logs.RetentionDays.ONE_MONTH }); + this.api = new apigw.RestApi(this, 'Api', { + description: 'IAM-authenticated worker approval requests; no human decision endpoint.', + // The parent TaskApi configures the regional API Gateway logging role. + cloudWatchRole: false, + deployOptions: { + stageName: 'v1', + accessLogDestination: new apigw.LogGroupLogDestination(accessLogs), + accessLogFormat: apigw.AccessLogFormat.jsonWithStandardFields(), + loggingLevel: apigw.MethodLoggingLevel.INFO, + throttlingRateLimit: 60, + throttlingBurstLimit: 100, + }, + }); + this.api.root.addResource('tasks').addResource('{task_id}').addMethod( + 'POST', new apigw.LambdaIntegration(this.fn, { allowTestInvoke: false }), + { authorizationType: apigw.AuthorizationType.IAM }, + ); + NagSuppressions.addResourceSuppressions(this.fn, [{ + id: 'AwsSolutions-IAM4', reason: 'AWSLambdaBasicExecutionRole provides Lambda runtime logging.', + }], true); + NagSuppressions.addResourceSuppressions(this.api, [ + { id: 'AwsSolutions-APIG2', reason: 'The handler validates request shape and allowed fields. Action descriptions and policy metadata remain worker assertions, not independently verified policy results.' }, + { id: 'AwsSolutions-APIG3', reason: 'Machine-only IAM-signed API; session policy restricts POST to its tagged task path, with stage throttling.' }, + { id: 'AwsSolutions-COG4', reason: 'Workers authenticate with task-scoped AWS credentials, not human Cognito credentials.' }, + ], true); + } + + /** No wildcard task path on production session credentials. */ + public grantRequests(grantee: iam.IGrantable): void { + grantee.grantPrincipal.addToPrincipalPolicy(new iam.PolicyStatement({ + actions: ['execute-api:Invoke'], + resources: [this.api.arnForExecuteApi('POST', '/tasks/${aws:PrincipalTag/task_id}', 'v1')], + conditions: { Null: { 'aws:PrincipalTag/task_id': 'false' } }, + })); + } +} diff --git a/cdk/src/constructs/ecs-agent-cluster.ts b/cdk/src/constructs/ecs-agent-cluster.ts index 8a0ba3799..0d86c95a6 100644 --- a/cdk/src/constructs/ecs-agent-cluster.ts +++ b/cdk/src/constructs/ecs-agent-cluster.ts @@ -99,6 +99,13 @@ export interface EcsAgentClusterProps { */ readonly agentSessionRole?: AgentSessionRole; + /** + * Trusted approval writer base URL (ADR-025). The agent writes approval + * requests through it with its session credentials; required with + * `agentSessionRole`, which no longer writes the approvals table directly. + */ + readonly approvalRequestsApiUrl?: string; + /** * AgentCore Memory for cross-task learning. When provided, the ECS task role * is granted read+write on it so the agent's memory writes (write_task_episode @@ -254,6 +261,7 @@ const RESERVED_BUILD_ENV_KEYS = new Set([ 'ECS_PAYLOAD_BUCKET', 'ARTIFACTS_BUCKET_NAME', 'AGENT_SESSION_ROLE_ARN', + 'APPROVAL_REQUESTS_API_URL', 'CLAUDE_CODE_USE_BEDROCK', 'AWS_REGION', ]); @@ -422,6 +430,7 @@ export class EcsAgentCluster extends Construct { ...(props.agentSessionRole && { AGENT_SESSION_ROLE_ARN: props.agentSessionRole.role.roleArn, }), + ...(props.approvalRequestsApiUrl && { APPROVAL_REQUESTS_API_URL: props.approvalRequestsApiUrl }), // #319 outbound SDK solution attribution — set on the shared base so both // task defs emit `app/uksb-wt64nei4u6#{stack}`. ...(sdkUaAppId ? { AWS_SDK_UA_APP_ID: sdkUaAppId } : {}), diff --git a/cdk/src/constructs/task-orchestrator.ts b/cdk/src/constructs/task-orchestrator.ts index ddd429ce2..e05c76cee 100644 --- a/cdk/src/constructs/task-orchestrator.ts +++ b/cdk/src/constructs/task-orchestrator.ts @@ -242,6 +242,11 @@ export interface TaskOrchestratorProps { * fails closed with `approval_write_failed`. */ readonly taskApprovalsTableName: string; + /** + * Trusted approval writer base URL (`APPROVAL_REQUESTS_API_URL`, ADR-025). + * Workers create PENDING requests and record timeouts through it. + */ + readonly approvalRequestsApiUrl: string; /** Nudges table (`NUDGES_TABLE_NAME`) the agent polls for mid-task nudges. */ readonly nudgesTableName: string; /** Application log group (`LOG_GROUP_NAME`) the agent writes progress logs to. */ @@ -522,6 +527,7 @@ export class TaskOrchestrator extends Construct { // backends. NO IAM grant accompanies any of these (see the prop docs). ...(props.agentPlatformConfig && { TASK_APPROVALS_TABLE_NAME: props.agentPlatformConfig.taskApprovalsTableName, + APPROVAL_REQUESTS_API_URL: props.agentPlatformConfig.approvalRequestsApiUrl, NUDGES_TABLE_NAME: props.agentPlatformConfig.nudgesTableName, LOG_GROUP_NAME: props.agentPlatformConfig.logGroupName, ARTIFACTS_BUCKET_NAME: props.agentPlatformConfig.artifactsBucketName, diff --git a/cdk/src/handlers/request-approval.ts b/cdk/src/handlers/request-approval.ts new file mode 100644 index 000000000..2395f711a --- /dev/null +++ b/cdk/src/handlers/request-approval.ts @@ -0,0 +1,209 @@ +/** + * 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 { GetCommand, TransactWriteCommand } from '@aws-sdk/lib-dynamodb'; +import type { APIGatewayProxyEvent, APIGatewayProxyResult } from 'aws-lambda'; +import { logger } from './shared/logger'; +import { errorResponse, successResponse } from './shared/response'; +import { makeDocClient } from './shared/ua'; +import { computeTtlEpoch } from './shared/validation'; +import constants from '../../../contracts/constants.json'; +import { TaskStatus } from '../constructs/task-status'; + +const ddb = makeDocClient(); +const TASKS = process.env.TASK_TABLE_NAME!; +const APPROVALS = process.env.TASK_APPROVALS_TABLE_NAME!; +const MAX_ID_LENGTH = 128; +const MAX_TEXT_LENGTH = 8192; +/** Matches the agent's CLEANUP_MARGIN_120S past an approval deadline. */ +const APPROVAL_CLEANUP_MARGIN_S = 120; +const DEFAULT_RETENTION_DAYS = 90; +const REQUEST_FIELDS = new Set([ + 'task_id', 'request_id', 'tool_name', 'tool_input_preview', 'tool_input_sha256', + 'reason', 'severity', 'matching_rule_ids', 'status', 'created_at', 'timeout_s', + 'deadline_epoch', 'user_id', 'repo', +]); + +interface RequestInput { + readonly operation: 'create' | 'timeout'; + readonly task_id: string; + readonly request_id: string; + readonly approval?: Record; + readonly reason?: string; +} + +function validShortText(value: unknown): value is string { + return typeof value === 'string' && value.length > 0 && value.length <= MAX_ID_LENGTH; +} + +function validId(value: unknown): value is string { + return validShortText(value) && /^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(value); +} + +/** Never copy decision, notification, retention or arbitrary caller fields. */ +function validateRequest(input: RequestInput, task: Record): Record { + const row = input.approval; + if (!row || Object.keys(row).some(key => !REQUEST_FIELDS.has(key)) + || row.task_id !== input.task_id || row.request_id !== input.request_id + || row.user_id !== task.user_id || row.repo !== (task.repo ?? '') + || row.status !== 'PENDING' + || !validShortText(row.tool_name) || typeof row.tool_input_preview !== 'string' || row.tool_input_preview.length > MAX_TEXT_LENGTH + || typeof row.tool_input_sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(row.tool_input_sha256) + || typeof row.reason !== 'string' || row.reason.length > MAX_TEXT_LENGTH + || !['low', 'medium', 'high'].includes(row.severity as string) + || !Array.isArray(row.matching_rule_ids) || row.matching_rule_ids.length > 500 + || !row.matching_rule_ids.every(validShortText) + || typeof row.created_at !== 'string' || !Number.isFinite(Date.parse(row.created_at)) + || typeof row.timeout_s !== 'number' || !Number.isInteger(row.timeout_s) + || row.timeout_s < 0 || row.timeout_s > constants.approval_timeout_s.max + || (row.timeout_s === 0 ? row.deadline_epoch !== undefined + : row.deadline_epoch !== Math.floor(Date.parse(row.created_at) / 1000) + row.timeout_s)) { + throw new Error('APPROVAL_REQUEST_INVALID'); + } + return { ...row, ttl: approvalRowTtl(row.created_at as string, row.timeout_s as number) }; +} + +/** + * Retention is set here, never by the worker: the gate deadline plus the agent's + * cleanup margin (as the agent computed it before this writer existed), or the + * task retention period for a request without an automatic deadline. + */ +export function approvalRowTtl(createdAt: string, timeoutS: number): number { + const created = Math.floor(Date.parse(createdAt) / 1000); + return timeoutS > 0 + ? created + timeoutS + APPROVAL_CLEANUP_MARGIN_S + : computeTtlEpoch(Number(process.env.TASK_RETENTION_DAYS ?? DEFAULT_RETENTION_DAYS)); +} + +/** + * Worker-callable writer: creates pending requests or records a non-human timeout. + * Human decisions remain exclusively in approve/deny handlers. Workers have no + * direct approvals-table write permission, including whole-row replacement. + */ +export async function recordWorkerRequest(input: RequestInput): Promise> { + if (!input || !validId(input.task_id) || !validId(input.request_id) + || !['create', 'timeout'].includes(input.operation)) { + return { ok: false, code: 'APPROVAL_REQUEST_INVALID' }; + } + try { + const task = (await ddb.send(new GetCommand({ + TableName: TASKS, Key: { task_id: input.task_id }, ConsistentRead: true, + }))).Item; + if (!task || typeof task.user_id !== 'string') return { ok: false, code: 'APPROVAL_TASK_MISSING' }; + if (input.operation === 'create') { + const row = validateRequest(input, task); + await ddb.send(new TransactWriteCommand({ + TransactItems: [{ + Put: { + TableName: APPROVALS, + Item: row, + ConditionExpression: 'attribute_not_exists(request_id)', + }, + }, { + Update: { + TableName: TASKS, + Key: { task_id: input.task_id }, + UpdateExpression: 'SET #status = :awaiting, awaiting_approval_request_id = :request', + ConditionExpression: '#status = :running AND user_id = :user', + ExpressionAttributeNames: { '#status': 'status' }, + ExpressionAttributeValues: { + ':awaiting': TaskStatus.AWAITING_APPROVAL, + ':running': TaskStatus.RUNNING, + ':request': input.request_id, + ':user': task.user_id, + }, + }, + }], + })); + } else { + // A worker may fail closed after a deadline or polling failure; it cannot + // turn either into human DENIED/APPROVED or replace an existing decision. + if (input.approval !== undefined || (input.reason !== undefined + && (typeof input.reason !== 'string' || input.reason.length > MAX_TEXT_LENGTH))) { + return { ok: false, code: 'APPROVAL_REQUEST_INVALID' }; + } + await ddb.send(new TransactWriteCommand({ + TransactItems: [{ + Update: { + TableName: APPROVALS, + Key: { task_id: input.task_id, request_id: input.request_id }, + UpdateExpression: 'SET #status = :timeout, decided_at = :now' + + (input.reason !== undefined ? ', deny_reason = :reason' : ''), + ConditionExpression: '#status = :pending AND user_id = :user', + ExpressionAttributeNames: { '#status': 'status' }, + ExpressionAttributeValues: { + ':timeout': 'TIMED_OUT', + ':pending': 'PENDING', + ':user': task.user_id, + ':now': new Date().toISOString(), + ...(input.reason !== undefined ? { ':reason': input.reason } : {}), + }, + }, + }, { + ConditionCheck: { + TableName: TASKS, + Key: { task_id: input.task_id }, + ConditionExpression: '#status = :awaiting AND awaiting_approval_request_id = :request AND user_id = :user', + ExpressionAttributeNames: { '#status': 'status' }, + ExpressionAttributeValues: { ':awaiting': TaskStatus.AWAITING_APPROVAL, ':request': input.request_id, ':user': task.user_id }, + }, + }], + })); + } + return { ok: true }; + } catch (error) { + const failure = error as { name?: string; message?: string; CancellationReasons?: { Code?: string }[] }; + if (failure.message === 'APPROVAL_REQUEST_INVALID') return { ok: false, code: failure.message }; + const reasons = failure.CancellationReasons?.map(reason => ({ Code: reason.Code })); + logger.warn('Worker approval request was not recorded', { + task_id: input.task_id, + request_id: input.request_id, + operation: input.operation, + error_type: failure.name, + cancellation_reasons: reasons, + }); + return { ok: false, code: failure.name ?? 'APPROVAL_WRITE_FAILED', cancellation_reasons: reasons }; + } +} + +/** IAM authorizes the signed task path before invoking this Lambda. */ +export async function handler(event: APIGatewayProxyEvent): Promise { + const requestId = event.requestContext?.requestId ?? 'unknown'; + if (!event.requestContext?.identity?.userArn || !validId(event.pathParameters?.task_id)) { + return errorResponse(403, 'APPROVAL_CALLER_UNAUTHENTICATED', 'IAM authentication required', requestId); + } + let input: RequestInput; + try { + input = JSON.parse(event.isBase64Encoded + ? Buffer.from(event.body ?? '', 'base64').toString('utf8') : event.body ?? ''); + } catch { + return errorResponse(400, 'APPROVAL_REQUEST_INVALID', 'Invalid JSON request', requestId); + } + if (!input || input.task_id !== event.pathParameters!.task_id) { + return errorResponse(400, 'APPROVAL_TASK_MISMATCH', 'Task must match the signed path', requestId); + } + const result = await recordWorkerRequest(input); + if (result.ok) return successResponse(200, result, requestId); + const code = String(result.code); + const statusCode = code === 'TransactionCanceledException' ? 409 + : code === 'APPROVAL_TASK_MISSING' ? 404 : code === 'APPROVAL_REQUEST_INVALID' ? 400 : 503; + return errorResponse(statusCode, code, 'Approval write was not acknowledged', requestId, { + cancellation_reasons: result.cancellation_reasons ?? [], + }); +} diff --git a/cdk/src/handlers/shared/response.ts b/cdk/src/handlers/shared/response.ts index bab4d5b4c..b91f584a4 100644 --- a/cdk/src/handlers/shared/response.ts +++ b/cdk/src/handlers/shared/response.ts @@ -131,6 +131,7 @@ export function errorResponse( code: string, message: string, requestId: string, + details?: Record, ): APIGatewayProxyResult { return { statusCode, @@ -140,6 +141,7 @@ export function errorResponse( code, message, request_id: requestId, + ...(details ? { details } : {}), }, }), }; diff --git a/cdk/src/stacks/agent.ts b/cdk/src/stacks/agent.ts index 01e7b3d6b..5bb28c20f 100644 --- a/cdk/src/stacks/agent.ts +++ b/cdk/src/stacks/agent.ts @@ -36,6 +36,7 @@ import { AgentSessionRole } from '../constructs/agent-session-role'; import { AgentNetwork, AgentVpc } from '../constructs/agent-vpc'; import { ApiKeyTable } from '../constructs/api-key-table'; import { ApprovalMetricsPublisherConsumer } from '../constructs/approval-metrics-publisher-consumer'; +import { ApprovalRequestService } from '../constructs/approval-request-service'; import { AttachmentsBucket } from '../constructs/attachments-bucket'; import { PLATFORM_DEFAULT_AUX_MODEL_ID, @@ -499,6 +500,17 @@ export class AgentStack extends Stack { ...(microvmImageConfigured && { lambdaMicrovmImageArn: lazyMicrovmImageArn }), }); + // Trusted approval writer (ADR-025): workers create PENDING requests and + // record timeouts through this IAM-authenticated API instead of writing + // the approvals table directly. Its own nested stack keeps the API out of + // the root stack's resource budget. + const approvalRequests = new ApprovalRequestService(this, 'ApprovalRequests', { + taskTable: taskTable.table, approvalsTable: taskApprovalsTable.table, + }); + // Reuse the parent's regional API Gateway logging configuration. + const apiLoggingAccount = taskApi.api.node.tryFindChild('Account'); + if (apiLoggingAccount) approvalRequests.node.addDependency(apiLoggingAccount); + // Agent asset registry API (#246) in its own NestedStack + RestApi so its // ~35 resources don't count against this root stack's 500-resource limit. // It authorizes against the SHARED Cognito user pool, so a caller's JWT works @@ -590,6 +602,7 @@ export class AgentStack extends Stack { // AWAITING_APPROVAL; absent → hook fails closed with // ``approval_write_failed`` (the `ApprovalTablesUnavailable` path). TASK_APPROVALS_TABLE_NAME: taskApprovalsTable.table.tableName, + APPROVAL_REQUESTS_API_URL: approvalRequests.api.url, // Hint for the hook's remaining-maxLifetime calculation (§6.5 // pseudocode line 793). Kept in sync with the AgentCore // lifecycle configuration below so drift is visible. 8 hours. @@ -815,9 +828,10 @@ export class AgentStack extends Stack { taskScopedTables: [ taskTable.table, taskEventsTable.table, - taskApprovalsTable.table, taskNudgesTable.table, ], + // Read-only: requests are written through the trusted approval writer. + approvalsTable: taskApprovalsTable.table, traceArtifactsBucket: traceArtifactsBucket.bucket, attachmentsBucket: attachmentsBucket.bucket, // Session-tagged Bedrock grant for cost attribution — the same @@ -826,6 +840,7 @@ export class AgentStack extends Stack { invokableModels: invokableBedrockModels, }); sessionRoleArnHolder = agentSessionRole.role.roleArn; + approvalRequests.grantRequests(agentSessionRole.role); // X-Ray tracing disabled — requires account-level UpdateTraceSegmentDestination // which needs CloudWatch Logs resource policy propagation. Re-enable via @@ -1098,6 +1113,7 @@ export class AgentStack extends Stack { // construct admits the task role to the trust and injects // AGENT_SESSION_ROLE_ARN into the container. agentSessionRole, + approvalRequestsApiUrl: approvalRequests.api.url, // ADR-019 P1: parity — grants the task role InvokeGateway + injects // ABCA_TOOL_GATEWAY_URL. Undefined unless --context enableToolGateway=true. toolGateway, @@ -1255,6 +1271,7 @@ export class AgentStack extends Stack { // of the resources they identify. agentPlatformConfig: { taskApprovalsTableName: taskApprovalsTable.table.tableName, + approvalRequestsApiUrl: approvalRequests.api.url, nudgesTableName: taskNudgesTable.table.tableName, logGroupName: agentLogGroup.logGroupName, // INTENTIONAL, not a wiring bug: both keys resolve to the SAME bucket diff --git a/cdk/test/constructs/agent-session-role.test.ts b/cdk/test/constructs/agent-session-role.test.ts index c4022350d..12c5d041d 100644 --- a/cdk/test/constructs/agent-session-role.test.ts +++ b/cdk/test/constructs/agent-session-role.test.ts @@ -55,14 +55,14 @@ function createStack() { taskScopedTables: [ taskTable, taskEventsTable, - taskApprovalsTable, taskNudgesTable, ], + approvalsTable: taskApprovalsTable, traceArtifactsBucket, attachmentsBucket, }); - return { stack, template: Template.fromStack(stack), computeRole, sessionRole }; + return { stack, template: Template.fromStack(stack), computeRole, sessionRole, taskApprovalsTable }; } function findComputeRolePolicy(template: Template) { @@ -108,7 +108,7 @@ describe('AgentSessionRole construct', () => { const actions = Array.isArray(s.Action) ? s.Action : [s.Action]; return actions.some((a: string) => a.startsWith('dynamodb:')); }); - // Four task-scoped tables → four conditioned statements. + // Three read/write task-scoped tables + the read-only approvals table. expect(ddbStatements).toHaveLength(4); for (const s of ddbStatements) { expect(s.Condition).toEqual({ @@ -390,3 +390,37 @@ describe.each([false, true])('session-role IAM audit with concrete environment % } }); }); + +describe('AgentSessionRole approvals table (trusted approval writer, ADR-025)', () => { + test('workers may only read their own approval rows', () => { + const { template, taskApprovalsTable, stack } = createStack(); + const statements = Object.entries(template.findResources('AWS::IAM::Policy')) + .filter(([id]) => id.includes('AgentSessionRole')) + .flatMap(([, policy]) => policy.Properties.PolicyDocument.Statement); + const approvalsArn = stack.resolve(taskApprovalsTable.tableArn); + const onApprovals = statements.filter((s: { Resource: unknown }) => + JSON.stringify(s.Resource) === JSON.stringify(approvalsArn)); + expect(onApprovals).toHaveLength(1); + expect([onApprovals[0].Action].flat().sort()).toEqual([ + 'dynamodb:BatchGetItem', 'dynamodb:ConditionCheckItem', 'dynamodb:GetItem', 'dynamodb:Query', + ]); + expect(onApprovals[0].Condition).toEqual({ + 'ForAllValues:StringEquals': { 'dynamodb:LeadingKeys': ['${aws:PrincipalTag/task_id}'] }, + }); + }); + + test('putting the approvals table back in taskScopedTables fails synth', () => { + const stack = new Stack(new App(), 'GuardStack'); + const table = new dynamodb.Table(stack, 'Approvals', { + partitionKey: { name: 'task_id', type: dynamodb.AttributeType.STRING }, + }); + expect(() => new AgentSessionRole(stack, 'SR', { + assumingRoles: [new iam.Role(stack, 'C', { assumedBy: new iam.ServicePrincipal('ecs-tasks.amazonaws.com') })], + taskScopedTables: [table], + approvalsTable: table, + traceArtifactsBucket: new s3.Bucket(stack, 'T'), + attachmentsBucket: new s3.Bucket(stack, 'A'), + })).toThrow('approvalsTable must not appear in taskScopedTables'); + }); +}); + diff --git a/cdk/test/constructs/approval-request-service.test.ts b/cdk/test/constructs/approval-request-service.test.ts new file mode 100644 index 000000000..82dadc1f5 --- /dev/null +++ b/cdk/test/constructs/approval-request-service.test.ts @@ -0,0 +1,84 @@ +/** + * 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 dynamodb from 'aws-cdk-lib/aws-dynamodb'; +import * as iam from 'aws-cdk-lib/aws-iam'; +import { ApprovalRequestService } from '../../src/constructs/approval-request-service'; + +let root: Template; +let child: Template; +beforeAll(() => { + const stack = new Stack(new App(), 'ApprovalFixture', { + env: { account: '123456789012', region: 'us-east-1' }, + }); + const table = (id: string) => new dynamodb.Table(stack, id, { + partitionKey: { name: 'task_id', type: dynamodb.AttributeType.STRING }, + }); + const service = new ApprovalRequestService(stack, 'ApprovalRequests', { + taskTable: table('Tasks'), approvalsTable: table('Approvals'), + }); + const worker = new iam.Role(stack, 'WorkerSession', { + assumedBy: new iam.ServicePrincipal('ecs-tasks.amazonaws.com'), + }); + service.grantRequests(worker); + root = Template.fromStack(stack); + child = Template.fromStack(service); +}); + +test('requires IAM authentication on the only writable endpoint', () => { + child.resourceCountIs('AWS::ApiGateway::Method', 1); + child.hasResourceProperties('AWS::ApiGateway::Method', { + HttpMethod: 'POST', AuthorizationType: 'AWS_IAM', + }); +}); + +test('binds invocation to the session task tag and grants no direct Lambda invocation', () => { + const statements = Object.values(root.findResources('AWS::IAM::Policy')) + .flatMap(policy => policy.Properties.PolicyDocument.Statement); + expect(statements).toHaveLength(1); + expect(statements[0].Action).toBe('execute-api:Invoke'); + expect(JSON.stringify(statements[0].Resource)).toContain('/v1/POST/tasks/${aws:PrincipalTag/task_id}'); + expect(statements[0].Condition).toEqual({ Null: { 'aws:PrincipalTag/task_id': 'false' } }); +}); + +test('keeps the trusted writer and API infrastructure out of the parent resource budget', () => { + root.resourceCountIs('AWS::Lambda::Function', 0); + child.resourceCountIs('AWS::Lambda::Function', 1); + child.resourceCountIs('AWS::DynamoDB::Table', 0); +}); + +test('denies the writer delete, scan and whole-table reach, and exposes no unauthenticated route', () => { + const statements = Object.values(child.findResources('AWS::IAM::Policy')) + .flatMap(policy => policy.Properties.PolicyDocument.Statement); + const actions = statements.flatMap(statement => [statement.Action].flat()); + expect(actions.length).toBeGreaterThan(0); + for (const forbidden of ['dynamodb:DeleteItem', 'dynamodb:BatchWriteItem', 'dynamodb:Scan', 'dynamodb:Query', 'dynamodb:*']) { + expect(actions).not.toContain(forbidden); + } + // Table ARNs only: no index, stream or wildcard resource. + for (const statement of statements) { + expect(JSON.stringify(statement.Resource)).not.toMatch(/\*|\/index\/|\/stream\//); + } + for (const method of Object.values(child.findResources('AWS::ApiGateway::Method'))) { + expect(method.Properties.AuthorizationType).toBe('AWS_IAM'); + expect(method.Properties.ApiKeyRequired).not.toBe(true); + } +}); diff --git a/cdk/test/handlers/orchestrate-task-microvm.test.ts b/cdk/test/handlers/orchestrate-task-microvm.test.ts index 1023238fd..3a8861ab9 100644 --- a/cdk/test/handlers/orchestrate-task-microvm.test.ts +++ b/cdk/test/handlers/orchestrate-task-microvm.test.ts @@ -111,6 +111,7 @@ process.env.MICROVM_EGRESS_CONNECTOR_ARNS = 'arn:aws:lambda:us-east-1:1234567890 process.env.MICROVM_PAYLOAD_BUCKET = 'test-microvm-payload-bucket'; process.env.TASK_TABLE_NAME = 'Tasks'; process.env.TASK_EVENTS_TABLE_NAME = 'TaskEvents'; +process.env.APPROVAL_REQUESTS_API_URL = 'https://fixture.execute-api.us-east-1.amazonaws.com/v1/'; process.env.USER_CONCURRENCY_TABLE_NAME = 'UserConcurrency'; process.env.TASK_RETENTION_DAYS = '90'; diff --git a/cdk/test/handlers/request-approval-local.test.ts b/cdk/test/handlers/request-approval-local.test.ts new file mode 100644 index 000000000..da9e016c6 --- /dev/null +++ b/cdk/test/handlers/request-approval-local.test.ts @@ -0,0 +1,171 @@ +/** + * 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. + */ + +/** Real transaction conditions; loopback endpoint and dummy credentials only. */ +import { randomUUID } from 'node:crypto'; +import { CreateTableCommand, DeleteTableCommand, DynamoDBClient } from '@aws-sdk/client-dynamodb'; +import { DynamoDBDocumentClient, GetCommand, PutCommand, TransactWriteCommand, UpdateCommand } from '@aws-sdk/lib-dynamodb'; + +const endpoint = process.env.ABCA_DDB_LOCAL_ENDPOINT; +if (process.env.CI === 'true' && !endpoint) throw new Error('CI requires ABCA_DDB_LOCAL_ENDPOINT'); +if (endpoint && (new URL(endpoint).hostname !== '127.0.0.1' || new URL(endpoint).protocol !== 'http:')) { + throw new Error('Approval integration tests require an http://127.0.0.1 endpoint'); +} +const mockBeforeTransaction = jest.fn(); +let mockClient: DynamoDBDocumentClient; +jest.mock('../../src/handlers/shared/ua', () => ({ + makeDocClient: () => ({ + send: async (command: unknown) => { + if (command instanceof TransactWriteCommand) await mockBeforeTransaction(); + return mockClient.send(command as GetCommand); + }, + }), +})); +const suffix = randomUUID(); +const tasks = `approval-tasks-${suffix}`; +const approvals = `approval-requests-${suffix}`; +Object.assign(process.env, { TASK_TABLE_NAME: tasks, TASK_APPROVALS_TABLE_NAME: approvals }); +import { recordWorkerRequest } from '../../src/handlers/request-approval'; + +const raw = new DynamoDBClient({ + endpoint: endpoint ?? 'http://127.0.0.1:1', + region: 'us-east-1', + credentials: { accessKeyId: 'local', secretAccessKey: 'local' }, +}); +mockClient = DynamoDBDocumentClient.from(raw); +const local = endpoint ? describe : describe.skip; +jest.setTimeout(30_000); + +local('Trusted approval writer against DynamoDB Local', () => { + let taskId: string; + const gate = 'gate'; + const row = () => ({ + task_id: taskId, + request_id: gate, + user_id: 'owner', + repo: 'owner/repo', + tool_name: 'Bash', + tool_input_preview: '{"command":"git push"}', + tool_input_sha256: 'a'.repeat(64), + reason: 'Protected operation', + severity: 'high', + matching_rule_ids: ['protected'], + status: 'PENDING', + created_at: new Date().toISOString(), + timeout_s: 0, + }); + const create = () => recordWorkerRequest({ + operation: 'create', task_id: taskId, request_id: gate, approval: row(), + }); + const timeout = () => recordWorkerRequest({ + operation: 'timeout', task_id: taskId, request_id: gate, + }); + const read = async (table: string) => (await mockClient.send(new GetCommand({ + TableName: table, + Key: { task_id: taskId, ...(table === approvals ? { request_id: gate } : {}) }, + ConsistentRead: true, + }))).Item; + const change = async (table: string, field: string, value: string) => + mockClient.send(new UpdateCommand({ + TableName: table, + Key: { task_id: taskId, ...(table === approvals ? { request_id: gate } : {}) }, + UpdateExpression: 'SET #field = :value', + ExpressionAttributeNames: { '#field': field }, + ExpressionAttributeValues: { ':value': value }, + })); + beforeAll(async () => { + for (const table of [tasks, approvals]) { + await raw.send(new CreateTableCommand({ + TableName: table, + BillingMode: 'PAY_PER_REQUEST', + AttributeDefinitions: [{ AttributeName: 'task_id', AttributeType: 'S' }, + ...(table === approvals ? [{ AttributeName: 'request_id', AttributeType: 'S' as const }] : [])], + KeySchema: [{ AttributeName: 'task_id', KeyType: 'HASH' }, + ...(table === approvals ? [{ AttributeName: 'request_id', KeyType: 'RANGE' as const }] : [])], + })); + } + }); + afterAll(async () => { + try { for (const table of [tasks, approvals]) await raw.send(new DeleteTableCommand({ TableName: table })); } finally { raw.destroy(); } + }); + beforeEach(async () => { + taskId = randomUUID(); + mockBeforeTransaction.mockReset(); + await mockClient.send(new PutCommand({ + TableName: tasks, + Item: { + task_id: taskId, status: 'RUNNING', user_id: 'owner', repo: 'owner/repo', compute_type: 'lambda-microvm', + }, + })); + }); + + test('creates a durable pending request and its task pointer atomically', async () => { + expect(await create()).toEqual({ ok: true }); + expect(await read(approvals)).toMatchObject({ status: 'PENDING', timeout_s: 0 }); + // Retention comes from the writer, never the worker (no deadline: task retention). + expect((await read(approvals))?.ttl).toBeGreaterThan(Math.floor(Date.now() / 1000) + 80 * 86400); + expect(await read(tasks)).toMatchObject({ status: 'AWAITING_APPROVAL', awaiting_approval_request_id: gate }); + }); + test.each(['APPROVED', 'DENIED', 'CANCELLED'])('timeout preserves an existing %s decision', async status => { + await create(); + await change(approvals, 'status', status); + const before = await read(approvals); + expect(await timeout()).toMatchObject({ + ok: false, + code: 'TransactionCanceledException', + cancellation_reasons: [{ Code: 'ConditionalCheckFailed' }, { Code: 'None' }], + }); + expect(await read(approvals)).toEqual(before); + }); + test('only pending requests can transition to a non-human timeout', async () => { + await create(); + expect(await timeout()).toEqual({ ok: true }); + expect(await read(approvals)).toMatchObject({ status: 'TIMED_OUT' }); + expect(await read(approvals)).not.toHaveProperty('decision_source'); + }); + test('cancellation between read and write prevents both request and task changes', async () => { + mockBeforeTransaction.mockImplementationOnce(() => change(tasks, 'status', 'CANCELLED')); + expect(await create()).toMatchObject({ ok: false, code: 'TransactionCanceledException' }); + expect(await read(approvals)).toBeUndefined(); + expect(await read(tasks)).toMatchObject({ status: 'CANCELLED' }); + }); + test('timeout after the task left AWAITING_APPROVAL changes nothing', async () => { + await create(); + const before = await read(approvals); + mockBeforeTransaction.mockImplementationOnce(() => change(tasks, 'status', 'CANCELLED')); + const result = await timeout(); + expect(result).toMatchObject({ ok: false, code: 'TransactionCanceledException' }); + expect(result.cancellation_reasons).toEqual([{ Code: 'None' }, { Code: 'ConditionalCheckFailed' }]); + expect(await read(approvals)).toEqual(before); + }); + test('a second request cannot replace the first while the task waits', async () => { + await create(); + const result = await recordWorkerRequest({ + operation: 'create', + task_id: taskId, + request_id: 'replacement', + approval: { ...row(), request_id: 'replacement' }, + }); + expect(result).toMatchObject({ ok: false, code: 'TransactionCanceledException' }); + expect(await read(tasks)).toMatchObject({ awaiting_approval_request_id: gate }); + expect((await mockClient.send(new GetCommand({ + TableName: approvals, Key: { task_id: taskId, request_id: 'replacement' }, + }))).Item).toBeUndefined(); + }); +}); diff --git a/cdk/test/handlers/request-approval.test.ts b/cdk/test/handlers/request-approval.test.ts new file mode 100644 index 000000000..8a6b9d755 --- /dev/null +++ b/cdk/test/handlers/request-approval.test.ts @@ -0,0 +1,145 @@ +/** + * 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 type { APIGatewayProxyEvent } from 'aws-lambda'; + +const send = jest.fn(); +jest.mock('../../src/handlers/shared/ua', () => ({ makeDocClient: () => ({ send }) })); +import { approvalRowTtl, handler, recordWorkerRequest } from '../../src/handlers/request-approval'; + +const approval = { + task_id: 'task', + request_id: 'gate', + user_id: 'owner', + repo: 'owner/repo', + tool_name: 'Bash', + tool_input_preview: '{"command":"git push"}', + tool_input_sha256: 'a'.repeat(64), + reason: 'Protected operation', + severity: 'high', + matching_rule_ids: ['protected'], + status: 'PENDING', + created_at: '2026-09-18T00:00:00Z', + timeout_s: 0, +}; +const input = { operation: 'create' as const, task_id: 'task', request_id: 'gate', approval }; +let task: Record; +beforeEach(() => { + task = { user_id: 'owner', repo: 'owner/repo', compute_type: 'ecs', status: 'RUNNING' }; + send.mockReset().mockImplementation(async command => + command.constructor.name === 'GetCommand' ? { Item: task } : {}); +}); + +test.each([ + { status: 'APPROVED' }, { status: 'DENIED' }, + { notified_linear_approval_requested: true }, { decision_source: 'forged' }, + { decided_at: 'now' }, { scope: 'all' }, { ttl: 1 }, { user_id: 'other' }, { repo: 'other/repo' }, +])('rejects forged decision/notification fields and ownership: %j', async changes => { + expect(await recordWorkerRequest({ ...input, approval: { ...approval, ...changes } })) + .toMatchObject({ ok: false, code: 'APPROVAL_REQUEST_INVALID' }); + expect(send).toHaveBeenCalledTimes(1); +}); + +test('records only the pending request, guarded by current task ownership and status', async () => { + expect(await recordWorkerRequest(input)).toEqual({ ok: true }); + const items = send.mock.calls[1][0].input.TransactItems; + expect(items[0].Put.Item).toEqual({ ...approval, ttl: approvalRowTtl(approval.created_at, approval.timeout_s) }); + expect(items[0].Put.ConditionExpression).toBe('attribute_not_exists(request_id)'); + expect(items[1].Update.ConditionExpression).toBe('#status = :running AND user_id = :user'); + expect(items[1].Update.ExpressionAttributeValues[':user']).toBe('owner'); +}); + +test('every backend uses the same two-item transaction (no worker lease on this branch)', async () => { + for (const computeType of ['agentcore', 'ecs', 'lambda-microvm']) { + send.mockClear(); + task.compute_type = computeType; + await recordWorkerRequest(input); + expect(send.mock.calls[1][0].input.TransactItems).toHaveLength(2); + } +}); + +test('retention is set by the writer from the validated deadline, never by the worker', () => { + const created = Date.parse('2026-09-18T00:00:00Z') / 1000; + expect(approvalRowTtl('2026-09-18T00:00:00Z', 300)).toBe(created + 300 + 120); + // No automatic deadline: the task retention period instead. + const noDeadline = approvalRowTtl('2026-09-18T00:00:00Z', 0); + expect(noDeadline).toBeGreaterThan(Math.floor(Date.now() / 1000) + 80 * 86400); +}); + +test('timeout cannot overwrite a human decision or resume the task', async () => { + await recordWorkerRequest({ operation: 'timeout', task_id: 'task', request_id: 'gate' }); + const items = send.mock.calls[1][0].input.TransactItems; + expect(items[0].Update.ExpressionAttributeValues[':timeout']).toBe('TIMED_OUT'); + expect(items[0].Update.ConditionExpression).toBe('#status = :pending AND user_id = :user'); + expect(items[1].ConditionCheck.ConditionExpression).toContain('awaiting_approval_request_id = :request'); + expect(items[1].Update).toBeUndefined(); +}); + +test('preserves cancellation reasons without returning request contents', async () => { + send.mockRejectedValueOnce({ + name: 'TransactionCanceledException', + CancellationReasons: [ + { Code: 'ConditionalCheckFailed', Item: { secret: 'must not return' } }, + ], + }); + expect(await recordWorkerRequest(input)).toEqual({ + ok: false, code: 'TransactionCanceledException', cancellation_reasons: [{ Code: 'ConditionalCheckFailed' }], + }); +}); + +test('requires IAM caller identity and refuses body/path task substitution', async () => { + const event = { + body: JSON.stringify(input), + pathParameters: { task_id: 'other-task' }, + requestContext: { identity: { userArn: 'arn:aws:sts::123456789012:assumed-role/Session/task' } }, + } as unknown as APIGatewayProxyEvent; + expect((await handler(event)).statusCode).toBe(400); + expect(send).not.toHaveBeenCalled(); + expect((await handler({ ...event, requestContext: {} } as APIGatewayProxyEvent)).statusCode).toBe(403); +}); + +test('accepts the signed path for the matching request', async () => { + const result = await handler({ + body: JSON.stringify(input), + pathParameters: { task_id: 'task' }, + requestContext: { identity: { userArn: 'arn:aws:sts::123456789012:assumed-role/Session/task' } }, + } as unknown as APIGatewayProxyEvent); + expect(result.statusCode).toBe(200); + expect(JSON.parse(result.body)).toEqual({ data: { ok: true } }); +}); + +test('reports service failures as unavailable with a request ID, not invalid input', async () => { + send.mockRejectedValueOnce({ name: 'ProvisionedThroughputExceededException' }); + const result = await handler({ + body: JSON.stringify(input), + pathParameters: { task_id: 'task' }, + requestContext: { requestId: 'api-request', identity: { userArn: 'worker' } }, + } as unknown as APIGatewayProxyEvent); + expect(result.statusCode).toBe(503); + expect(JSON.parse(result.body)).toMatchObject({ + error: { code: 'ProvisionedThroughputExceededException', request_id: 'api-request' }, + }); +}); + +test.each(['*', 'task/*', '../task', 'task?x', 'task#lease', 'task\n'])('rejects unsafe task/request/worker identifiers %j before database access', async id => { + for (const key of ['task_id', 'request_id']) { + expect(await recordWorkerRequest({ ...input, [key]: id })).toEqual({ ok: false, code: 'APPROVAL_REQUEST_INVALID' }); + } + expect(send).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..68bfe165a 100644 --- a/cdk/test/handlers/shared/strategies/lambda-microvm-strategy.test.ts +++ b/cdk/test/handlers/shared/strategies/lambda-microvm-strategy.test.ts @@ -60,6 +60,7 @@ delete process.env.MICROVM_INGRESS_CONNECTOR_ARNS; process.env.TASK_TABLE_NAME = TASK_TABLE_NAME; process.env.TASK_EVENTS_TABLE_NAME = TASK_EVENTS_TABLE_NAME; +process.env.APPROVAL_REQUESTS_API_URL = 'https://fixture.execute-api.us-east-1.amazonaws.com/v1/'; process.env.GITHUB_TOKEN_SECRET_ARN = GITHUB_TOKEN_SECRET_ARN; process.env.AGENT_SESSION_ROLE_ARN = AGENT_SESSION_ROLE_ARN; for (const optional of [ @@ -138,6 +139,7 @@ const BLUEPRINT: BlueprintConfig = { compute_type: 'lambda-microvm', runtime_arn const EXPECTED_PLATFORM_CONFIG = { task_table_name: TASK_TABLE_NAME, task_events_table_name: TASK_EVENTS_TABLE_NAME, + approval_requests_api_url: 'https://fixture.execute-api.us-east-1.amazonaws.com/v1/', github_token_secret_arn: GITHUB_TOKEN_SECRET_ARN, agent_session_role_arn: AGENT_SESSION_ROLE_ARN, }; @@ -1229,6 +1231,7 @@ describe('buildMicrovmPlatformConfig — the MicroVM substitute for a deploy-tim TASK_TABLE_NAME: 'tasks', TASK_EVENTS_TABLE_NAME: 'events', TASK_APPROVALS_TABLE_NAME: 'approvals', + APPROVAL_REQUESTS_API_URL: 'https://fixture.execute-api.us-east-1.amazonaws.com/v1/', NUDGES_TABLE_NAME: 'nudges', LOG_GROUP_NAME: '/aws/abca/application', ARTIFACTS_BUCKET_NAME: 'artifacts-bucket', @@ -1265,6 +1268,7 @@ describe('buildMicrovmPlatformConfig — the MicroVM substitute for a deploy-tim 'task_table_name', 'task_events_table_name', 'task_approvals_table_name', + 'approval_requests_api_url', 'nudges_table_name', 'log_group_name', 'artifacts_bucket_name', @@ -1286,17 +1290,18 @@ describe('buildMicrovmPlatformConfig — the MicroVM substitute for a deploy-tim 'linear_vault_enabled', 'linear_workload_identity_name', ]); - expect(MICROVM_PLATFORM_CONFIG_KEYS).toHaveLength(17); + expect(MICROVM_PLATFORM_CONFIG_KEYS).toHaveLength(18); // snake_case on the wire, matching every other key in the /run envelope. for (const key of MICROVM_PLATFORM_CONFIG_KEYS) { expect(key).toMatch(/^[a-z][a-z0-9_]*$/); } }); - test('pins the REQUIRED subset — these four are what a task cannot start without', () => { + test('pins the REQUIRED subset — what a task cannot start without', () => { expect([...MICROVM_PLATFORM_CONFIG_REQUIRED_KEYS]).toEqual([ 'task_table_name', 'task_events_table_name', + 'approval_requests_api_url', 'github_token_secret_arn', 'agent_session_role_arn', ]); @@ -1328,6 +1333,7 @@ describe('buildMicrovmPlatformConfig — the MicroVM substitute for a deploy-tim const config = buildMicrovmPlatformConfig({ TASK_TABLE_NAME: 'tasks', TASK_EVENTS_TABLE_NAME: 'events', + APPROVAL_REQUESTS_API_URL: 'https://fixture.execute-api.us-east-1.amazonaws.com/v1/', GITHUB_TOKEN_SECRET_ARN: 'arn:aws:secretsmanager:us-east-1:123456789012:secret:gh-AbCdEf', AGENT_SESSION_ROLE_ARN: 'arn:aws:iam::123456789012:role/SessionRole', }); @@ -1337,6 +1343,7 @@ describe('buildMicrovmPlatformConfig — the MicroVM substitute for a deploy-tim expect(Object.keys(config)).toEqual([ 'task_table_name', 'task_events_table_name', + 'approval_requests_api_url', 'github_token_secret_arn', 'agent_session_role_arn', ]); @@ -1373,6 +1380,7 @@ describe('buildMicrovmPlatformConfig — the MicroVM substitute for a deploy-tim test.each([ ['TASK_TABLE_NAME', 'task_table_name'], ['TASK_EVENTS_TABLE_NAME', 'task_events_table_name'], + ['APPROVAL_REQUESTS_API_URL', 'approval_requests_api_url'], ['GITHUB_TOKEN_SECRET_ARN', 'github_token_secret_arn'], ['AGENT_SESSION_ROLE_ARN', 'agent_session_role_arn'], ])('throws naming %s when it is missing', (envVar, wireKey) => { @@ -1390,7 +1398,7 @@ describe('buildMicrovmPlatformConfig — the MicroVM substitute for a deploy-tim // One redeploy should fix all of them; reporting one per attempt turns a // misconfiguration into four round-trips. expect(() => buildMicrovmPlatformConfig({})).toThrow( - /task_table_name.*task_events_table_name.*github_token_secret_arn.*agent_session_role_arn/s, + /task_table_name.*task_events_table_name.*approval_requests_api_url.*github_token_secret_arn.*agent_session_role_arn/s, ); }); @@ -1491,6 +1499,7 @@ describe('buildMicrovmPlatformConfig — the MicroVM substitute for a deploy-tim describe('LambdaMicrovmComputeStrategy with the FULL platform_config environment', () => { const OPTIONAL_ENV: Record = { TASK_APPROVALS_TABLE_NAME: 'approvals', + APPROVAL_REQUESTS_API_URL: 'https://fixture.execute-api.us-east-1.amazonaws.com/v1/', NUDGES_TABLE_NAME: 'nudges', LOG_GROUP_NAME: '/aws/abca/application', ARTIFACTS_BUCKET_NAME: 'artifacts-bucket', @@ -1523,7 +1532,7 @@ describe('LambdaMicrovmComputeStrategy with the FULL platform_config environment 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(Object.keys(envelope.platform_config)).toHaveLength(14); expect(JSON.parse(mockS3Send.mock.calls[0][0].input.Body).platform_config).toEqual(expected); }); }); diff --git a/cdk/test/handlers/start-session-composition.test.ts b/cdk/test/handlers/start-session-composition.test.ts index 1d2e816b9..973a2b507 100644 --- a/cdk/test/handlers/start-session-composition.test.ts +++ b/cdk/test/handlers/start-session-composition.test.ts @@ -84,6 +84,7 @@ jest.mock('ulid', () => ({ ulid: jest.fn(() => `ULID${ulidCounter++}`) })); process.env.TASK_TABLE_NAME = 'Tasks'; process.env.TASK_EVENTS_TABLE_NAME = 'TaskEvents'; +process.env.APPROVAL_REQUESTS_API_URL = 'https://fixture.execute-api.us-east-1.amazonaws.com/v1/'; process.env.USER_CONCURRENCY_TABLE_NAME = 'UserConcurrency'; process.env.RUNTIME_ARN = 'arn:aws:bedrock-agentcore:us-east-1:123456789012:runtime/test'; process.env.MAX_CONCURRENT_TASKS_PER_USER = '3'; diff --git a/contracts/constants.json b/contracts/constants.json index 174812d40..59e2aeeb0 100644 --- a/contracts/constants.json +++ b/contracts/constants.json @@ -36,6 +36,7 @@ "task_table_name": "TASK_TABLE_NAME", "task_events_table_name": "TASK_EVENTS_TABLE_NAME", "task_approvals_table_name": "TASK_APPROVALS_TABLE_NAME", + "approval_requests_api_url": "APPROVAL_REQUESTS_API_URL", "nudges_table_name": "NUDGES_TABLE_NAME", "log_group_name": "LOG_GROUP_NAME", "artifacts_bucket_name": "ARTIFACTS_BUCKET_NAME", @@ -54,6 +55,7 @@ "required": [ "task_table_name", "task_events_table_name", + "approval_requests_api_url", "github_token_secret_arn", "agent_session_role_arn" ], diff --git a/docs/decisions/ADR-025-trusted-approval-writer.md b/docs/decisions/ADR-025-trusted-approval-writer.md new file mode 100644 index 000000000..e86953da6 --- /dev/null +++ b/docs/decisions/ADR-025-trusted-approval-writer.md @@ -0,0 +1,36 @@ +# ADR-025: Trusted approval writer + +**Status:** proposed +**Date:** 2026-11-05 + +## Context + +When a Cedar soft-deny gate fires, the agent records a `PENDING` approval row and moves its task to `AWAITING_APPROVAL`. Until now it wrote that row **directly** to the approvals DynamoDB table, using its task-scoped session credentials. The session role granted item-level read **and write** on the table, limited only by a `dynamodb:LeadingKeys` condition on the task's own ID. + +Those credentials live in the same container that runs the repository's code: builds, tests, scripts. Malicious or prompt-injected repository code can therefore use them to write any approval record for its own task. That includes replacing a pending request with an approved one. The defect affects every backend: AgentCore, ECS and Lambda MicroVMs. + +## Decision + +Use a small IAM-authenticated API and Lambda as the **only** worker-facing approval writer. + +- **Interface.** `POST /tasks/{task_id}` accepts exactly two operations: `create` (a `PENDING` request) and `timeout` (close a still-`PENDING` request as `TIMED_OUT`). It cannot record a human approval or denial, a decision source, notification markers, scope, or retention. +- **Binding.** The session role may invoke only `POST /tasks/${aws:PrincipalTag/task_id}`, so a worker can reach only its own task's path. Direct Lambda invocation is not granted, because Lambda does not expose caller session tags. +- **Validation.** The handler accepts only a fixed field set. It requires the row's owner and repository to match the task, and checks that `deadline_epoch` equals `created_at + timeout_s`. The writer itself sets the row's TTL from the validated deadline (plus the agent's 120 s cleanup margin), or from the task retention period when there is no automatic deadline. Workers no longer choose retention. +- **Atomicity.** `create` writes the request and transitions the task `RUNNING → AWAITING_APPROVAL` in one transaction, conditioned on the task's owner and state, and on no existing row with that ID. `timeout` updates only a `PENDING` row owned by the task's user, conditioned on the task still awaiting that request. A human decision that won the race leaves the transaction cancelled, and the worker re-reads and honors it. +- **Session role.** The approvals table leaves the session role's read/write task-scoped tables. The role keeps task-scoped **read-only** access (`GetItem`, `BatchGetItem`, `Query`, `ConditionCheckItem`), which is enough to poll decisions. Listing the table in both places fails synth. +- **Human decisions** remain exclusive to the owner-authenticated approve/deny handlers. +- **Wiring.** Every backend receives the API URL: the AgentCore runtime env, the ECS task env, and the Lambda MicroVM platform config (a required `approval_requests_api_url` contract key). The service is a nested stack, so it does not consume root-stack resource budget. + +## Consequences + +- **Upgrade order.** Images built before this change still write the table directly, and the new IAM policy denies that. Deploy matching infrastructure and images together, with in-flight tasks drained. A worker with a session role but no API URL fails closed at its first gate (`APPROVAL_REQUESTS_API_URL is required`). It does not fall back to direct writes. +- **Availability.** The service adds one signed request per creation and per closure, and becomes an availability dependency. A failure denies permission to proceed; it never becomes consent. +- **Limits of validation.** The service validates record shape and ownership, not the truth of worker-supplied policy descriptions. A preview can be truncated and is not proof of the full tool input. `TIMED_OUT` also covers a worker polling failure, so it is not proof that a human deadline elapsed. +- **Residual trust.** The compute role still chooses session tags when assuming the session role. This API protects the decision-writing boundary. It does not isolate a compromised worker from its ambient compute credentials. +- **Local and legacy paths.** Unscoped local runs with no session role keep the direct-table path for development. + +## References + +- [Issue #1000](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/1000) +- [Approval trust boundaries](../design/CEDAR_HITL_GATES.md) +- [ADR-021: Lambda MicroVM compute backend](./ADR-021-lambda-microvms-compute-backend.md) diff --git a/docs/src/content/docs/decisions/Adr-025-trusted-approval-writer.md b/docs/src/content/docs/decisions/Adr-025-trusted-approval-writer.md new file mode 100644 index 000000000..ea16b99c3 --- /dev/null +++ b/docs/src/content/docs/decisions/Adr-025-trusted-approval-writer.md @@ -0,0 +1,40 @@ +--- +title: Adr 025 trusted approval writer +--- + +# ADR-025: Trusted approval writer + +**Status:** proposed +**Date:** 2026-11-05 + +## Context + +When a Cedar soft-deny gate fires, the agent records a `PENDING` approval row and moves its task to `AWAITING_APPROVAL`. Until now it wrote that row **directly** to the approvals DynamoDB table, using its task-scoped session credentials. The session role granted item-level read **and write** on the table, limited only by a `dynamodb:LeadingKeys` condition on the task's own ID. + +Those credentials live in the same container that runs the repository's code: builds, tests, scripts. Malicious or prompt-injected repository code can therefore use them to write any approval record for its own task. That includes replacing a pending request with an approved one. The defect affects every backend: AgentCore, ECS and Lambda MicroVMs. + +## Decision + +Use a small IAM-authenticated API and Lambda as the **only** worker-facing approval writer. + +- **Interface.** `POST /tasks/{task_id}` accepts exactly two operations: `create` (a `PENDING` request) and `timeout` (close a still-`PENDING` request as `TIMED_OUT`). It cannot record a human approval or denial, a decision source, notification markers, scope, or retention. +- **Binding.** The session role may invoke only `POST /tasks/${aws:PrincipalTag/task_id}`, so a worker can reach only its own task's path. Direct Lambda invocation is not granted, because Lambda does not expose caller session tags. +- **Validation.** The handler accepts only a fixed field set. It requires the row's owner and repository to match the task, and checks that `deadline_epoch` equals `created_at + timeout_s`. The writer itself sets the row's TTL from the validated deadline (plus the agent's 120 s cleanup margin), or from the task retention period when there is no automatic deadline. Workers no longer choose retention. +- **Atomicity.** `create` writes the request and transitions the task `RUNNING → AWAITING_APPROVAL` in one transaction, conditioned on the task's owner and state, and on no existing row with that ID. `timeout` updates only a `PENDING` row owned by the task's user, conditioned on the task still awaiting that request. A human decision that won the race leaves the transaction cancelled, and the worker re-reads and honors it. +- **Session role.** The approvals table leaves the session role's read/write task-scoped tables. The role keeps task-scoped **read-only** access (`GetItem`, `BatchGetItem`, `Query`, `ConditionCheckItem`), which is enough to poll decisions. Listing the table in both places fails synth. +- **Human decisions** remain exclusive to the owner-authenticated approve/deny handlers. +- **Wiring.** Every backend receives the API URL: the AgentCore runtime env, the ECS task env, and the Lambda MicroVM platform config (a required `approval_requests_api_url` contract key). The service is a nested stack, so it does not consume root-stack resource budget. + +## Consequences + +- **Upgrade order.** Images built before this change still write the table directly, and the new IAM policy denies that. Deploy matching infrastructure and images together, with in-flight tasks drained. A worker with a session role but no API URL fails closed at its first gate (`APPROVAL_REQUESTS_API_URL is required`). It does not fall back to direct writes. +- **Availability.** The service adds one signed request per creation and per closure, and becomes an availability dependency. A failure denies permission to proceed; it never becomes consent. +- **Limits of validation.** The service validates record shape and ownership, not the truth of worker-supplied policy descriptions. A preview can be truncated and is not proof of the full tool input. `TIMED_OUT` also covers a worker polling failure, so it is not proof that a human deadline elapsed. +- **Residual trust.** The compute role still chooses session tags when assuming the session role. This API protects the decision-writing boundary. It does not isolate a compromised worker from its ambient compute credentials. +- **Local and legacy paths.** Unscoped local runs with no session role keep the direct-table path for development. + +## References + +- [Issue #1000](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/1000) +- [Approval trust boundaries](/sample-autonomous-cloud-coding-agents/architecture/cedar-hitl-gates) +- [ADR-021: Lambda MicroVM compute backend](/sample-autonomous-cloud-coding-agents/architecture/adr-021-lambda-microvms-compute-backend) From c6cdbad4691e95cab2b40c0f779522ecdf6a7628 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 5 Nov 2026 15:24:24 +0000 Subject: [PATCH 2/8] test(cdk): leave the vault out of the MicroVM network-extraction fixture (#1000) The vault adds no network resources. The MicroVM profile with every other option on sits at the 490-resource root budget on main (#852), so the trusted approval writer's nested stack (+1) pushed the inline baseline over it. --- cdk/test/stacks/network.test.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/cdk/test/stacks/network.test.ts b/cdk/test/stacks/network.test.ts index 7e2397ad4..1c2ad68b1 100644 --- a/cdk/test/stacks/network.test.ts +++ b/cdk/test/stacks/network.test.ts @@ -123,7 +123,11 @@ describe.each(['agentcore', 'ecs', 'lambda-microvm'] as const)('%s network extra 'bedrockGeoRegion': 'global', 'enableToolGateway': true, 'enableAgentRegistry': true, - 'enableLinearIdentityVault': true, + // The vault adds no network resources. The MicroVM profile with every + // other option on sits at the 490-resource root budget on main (#852), + // so the trusted approval writer's nested stack (+1) would push the + // inline baseline over it. Leave the vault out there only. + 'enableLinearIdentityVault': compute !== 'lambda-microvm', 'github:sha': 'fixture-revision', ...(zones ? { [AGENTCORE_AZS_CONTEXT_KEY]: zones } : {}), ...(compute === 'lambda-microvm' ? { From 126b67e7b0007ce24fbf9b8f97bd7d3be104e18f Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Thu, 5 Nov 2026 18:50:05 +0000 Subject: [PATCH 3/8] test(cdk): make the DynamoDB Local approval suite opt-in (#1000) CI has no DynamoDB Local service, so the suite now skips without ABCA_DDB_LOCAL_ENDPOINT instead of failing; the mocked handler suite still runs everywhere. --- cdk/test/handlers/request-approval-local.test.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/cdk/test/handlers/request-approval-local.test.ts b/cdk/test/handlers/request-approval-local.test.ts index da9e016c6..16c44abd1 100644 --- a/cdk/test/handlers/request-approval-local.test.ts +++ b/cdk/test/handlers/request-approval-local.test.ts @@ -17,13 +17,16 @@ * SOFTWARE. */ -/** Real transaction conditions; loopback endpoint and dummy credentials only. */ +/** + * Real transaction conditions; loopback endpoint and dummy credentials only. + * Opt-in: start DynamoDB Local and set ABCA_DDB_LOCAL_ENDPOINT=http://127.0.0.1:8000 to run. + * Without it the suite is skipped; request-approval.test.ts covers the handler with mocks. + */ import { randomUUID } from 'node:crypto'; import { CreateTableCommand, DeleteTableCommand, DynamoDBClient } from '@aws-sdk/client-dynamodb'; import { DynamoDBDocumentClient, GetCommand, PutCommand, TransactWriteCommand, UpdateCommand } from '@aws-sdk/lib-dynamodb'; const endpoint = process.env.ABCA_DDB_LOCAL_ENDPOINT; -if (process.env.CI === 'true' && !endpoint) throw new Error('CI requires ABCA_DDB_LOCAL_ENDPOINT'); if (endpoint && (new URL(endpoint).hostname !== '127.0.0.1' || new URL(endpoint).protocol !== 'http:')) { throw new Error('Approval integration tests require an http://127.0.0.1 endpoint'); } From 91357c08ac26591708dd1c4c88bc06344267cbd8 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Mon, 16 Nov 2026 01:41:31 +0000 Subject: [PATCH 4/8] test(cdk): give the orchestrator fixtures the required approvalRequestsApiUrl (typecheck) --- cdk/test/constructs/agent-session-role.test.ts | 1 - cdk/test/constructs/task-orchestrator.test.ts | 2 ++ 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/cdk/test/constructs/agent-session-role.test.ts b/cdk/test/constructs/agent-session-role.test.ts index 12c5d041d..566f10340 100644 --- a/cdk/test/constructs/agent-session-role.test.ts +++ b/cdk/test/constructs/agent-session-role.test.ts @@ -423,4 +423,3 @@ describe('AgentSessionRole approvals table (trusted approval writer, ADR-025)', })).toThrow('approvalsTable must not appear in taskScopedTables'); }); }); - diff --git a/cdk/test/constructs/task-orchestrator.test.ts b/cdk/test/constructs/task-orchestrator.test.ts index 0ee14deba..0607d7d50 100644 --- a/cdk/test/constructs/task-orchestrator.test.ts +++ b/cdk/test/constructs/task-orchestrator.test.ts @@ -849,6 +849,7 @@ describe('TaskOrchestrator agentPlatformConfig (ADR-021 P2 platform_config trans ...(withConfig && { agentPlatformConfig: { taskApprovalsTableName: approvalsTable.tableName, + approvalRequestsApiUrl: 'https://api.example.com/v1/approval-requests', nudgesTableName: nudgesTable.tableName, logGroupName: '/aws/abca/application', artifactsBucketName: traceBucket.bucketName, @@ -909,6 +910,7 @@ describe('TaskOrchestrator agentPlatformConfig (ADR-021 P2 platform_config trans githubTokenSecretArn: 'arn:aws:secretsmanager:us-east-1:123456789012:secret:github-token-abc123', agentPlatformConfig: { taskApprovalsTableName: 'approvals', + approvalRequestsApiUrl: 'https://api.example.com/v1/approval-requests', nudgesTableName: 'nudges', logGroupName: '/aws/abca/application', artifactsBucketName: 'artifacts', From af72743c0fd2be3ed35c8d047b1b5523feae5b43 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Mon, 16 Nov 2026 15:19:11 +0000 Subject: [PATCH 5/8] test(cdk): record the approval-requests stack's state-bearing resources main pins the logical IDs of every state-bearing resource so a refactor cannot silently replace one. This branch adds two on purpose: the ApprovalRequests nested stack and its access-log group. --- cdk/test/synthesis/legacy-state-ids.json | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/cdk/test/synthesis/legacy-state-ids.json b/cdk/test/synthesis/legacy-state-ids.json index 333160f0f..b3323989f 100644 --- a/cdk/test/synthesis/legacy-state-ids.json +++ b/cdk/test/synthesis/legacy-state-ids.json @@ -29,6 +29,11 @@ "logicalId": "ApprovalMetricsPublisherConsumerApprovalMetricsPublisherLogsCD5D42B2", "type": "AWS::Logs::LogGroup" }, + { + "template": "backgroundagent-dev.template.json", + "logicalId": "ApprovalRequestsNestedStackApprovalRequestsNestedStackResource7951430F", + "type": "AWS::CloudFormation::Stack" + }, { "template": "backgroundagent-dev.template.json", "logicalId": "AttachmentsBucket28B3CCF2", @@ -229,6 +234,11 @@ "logicalId": "WebhookTable610F8307", "type": "AWS::DynamoDB::Table" }, + { + "template": "backgroundagentdevApprovalRequestsCA2748DA.nested.template.json", + "logicalId": "AccessLogs8B620ECA", + "type": "AWS::Logs::LogGroup" + }, { "template": "backgroundagentdevRegistryApiF3ADADE2.nested.template.json", "logicalId": "ApiAccessLogsE9DF007D", From c79d8865601d0cc50dae938cb994a8499c100dec Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Mon, 16 Nov 2026 15:19:43 +0000 Subject: [PATCH 6/8] docs: regenerate the Starlight mirrors with main's generator --- .../docs/decisions/Adr-025-trusted-approval-writer.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/docs/src/content/docs/decisions/Adr-025-trusted-approval-writer.md b/docs/src/content/docs/decisions/Adr-025-trusted-approval-writer.md index ea16b99c3..690119234 100644 --- a/docs/src/content/docs/decisions/Adr-025-trusted-approval-writer.md +++ b/docs/src/content/docs/decisions/Adr-025-trusted-approval-writer.md @@ -1,9 +1,7 @@ --- -title: Adr 025 trusted approval writer +title: "ADR-025: Trusted approval writer" --- -# ADR-025: Trusted approval writer - **Status:** proposed **Date:** 2026-11-05 @@ -37,4 +35,4 @@ Use a small IAM-authenticated API and Lambda as the **only** worker-facing appro - [Issue #1000](https://github.com/aws-samples/sample-autonomous-cloud-coding-agents/issues/1000) - [Approval trust boundaries](/sample-autonomous-cloud-coding-agents/architecture/cedar-hitl-gates) -- [ADR-021: Lambda MicroVM compute backend](/sample-autonomous-cloud-coding-agents/architecture/adr-021-lambda-microvms-compute-backend) +- [ADR-021: Lambda MicroVM compute backend](/sample-autonomous-cloud-coding-agents/decisions/adr-021-lambda-microvms-compute-backend) From 747258f20e28394adc1b9bcfc27460cc6a5ba93a Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Tue, 17 Nov 2026 03:11:28 +0000 Subject: [PATCH 7/8] fix(security): keep status_created_at on the trusted writer's AWAITING_APPROVAL transition Since #1048 every approval transition maintains status_created_at, which the stranded-approval sweep and `ops stuck-tasks` measure from. The writer's RUNNING -> AWAITING_APPROVAL update now sets it too. --- cdk/src/handlers/request-approval.ts | 5 ++++- cdk/test/handlers/request-approval.test.ts | 3 +++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/cdk/src/handlers/request-approval.ts b/cdk/src/handlers/request-approval.ts index 2395f711a..4a2ea4dc0 100644 --- a/cdk/src/handlers/request-approval.ts +++ b/cdk/src/handlers/request-approval.ts @@ -119,7 +119,9 @@ export async function recordWorkerRequest(input: RequestInput): Promise { From d7e3a5db88716170893ea58da486ca89dc852856 Mon Sep 17 00:00:00 2001 From: Sphia Sadek Date: Wed, 18 Nov 2026 17:54:28 +0000 Subject: [PATCH 8/8] test(agent): emulator tier follows the trusted approval writer (#1000) Main's emulator tier (#1048) still had workers write approval rows. Under the trusted writer they may not: the scoped-session gate test now checks that a cloud worker without the writer's endpoint fails closed and writes nothing, and that its session can read but not write its approval rows; the policy mirror gives the approvals table the deployed read-only grant. The timeout test checks that a worker timeout wins once and that a worker-recorded denial is refused. --- .../test_approval_transactions.py | 11 +++- agent/tests_emulator/test_scoped_session.py | 56 +++++++++++++++---- 2 files changed, 54 insertions(+), 13 deletions(-) diff --git a/agent/tests_emulator/test_approval_transactions.py b/agent/tests_emulator/test_approval_transactions.py index e2c75b6e8..13276452a 100644 --- a/agent/tests_emulator/test_approval_transactions.py +++ b/agent/tests_emulator/test_approval_transactions.py @@ -105,11 +105,16 @@ def test_timeout_only_wins_while_the_request_is_still_pending( timed_out = task_state.best_effort_update_approval_status( running_task, pending_request, "TIMED_OUT" ) - late_denial = task_state.best_effort_update_approval_status( - running_task, pending_request, "DENIED", reason="too late" + second_timeout = task_state.best_effort_update_approval_status( + running_task, pending_request, "TIMED_OUT" ) + # A human decision is never the worker's to record (#1000). + with pytest.raises(ValueError, match="only non-human timeouts"): + task_state.best_effort_update_approval_status( + running_task, pending_request, "DENIED", reason="too late" + ) - assert (timed_out, late_denial) == (True, False) + assert (timed_out, second_timeout) == (True, False) row = task_state.get_approval_row(running_task, pending_request) assert row is not None assert row["status"] == "TIMED_OUT" diff --git a/agent/tests_emulator/test_scoped_session.py b/agent/tests_emulator/test_scoped_session.py index 5e7c8ca9d..806136f09 100644 --- a/agent/tests_emulator/test_scoped_session.py +++ b/agent/tests_emulator/test_scoped_session.py @@ -41,6 +41,12 @@ _ASSUMABLE_BY_ACCOUNT = {"AWS": f"arn:aws:iam::{EMULATOR_ACCOUNT_ID}:root"} # AgentSessionRole.DDB_ITEM_ACTIONS (Scan is deliberately absent). +_APPROVALS_READ_ACTIONS = [ + "dynamodb:GetItem", + "dynamodb:BatchGetItem", + "dynamodb:Query", + "dynamodb:ConditionCheckItem", +] _DDB_ITEM_ACTIONS = [ "dynamodb:GetItem", "dynamodb:BatchGetItem", @@ -72,12 +78,22 @@ def _session_role_policy(emulator) -> str: } }, } - for table in ( - emulator.task_table, - emulator.task_events_table, - emulator.task_approvals_table, - ) + for table in (emulator.task_table, emulator.task_events_table) ] + # Approvals are read-only for the session (#1000): workers observe decisions and + # use the rows in condition checks; requests go through the trusted writer. + statements.append( + { + "Effect": "Allow", + "Action": _APPROVALS_READ_ACTIONS, + "Resource": f"{table_arn}/{emulator.task_approvals_table}", + "Condition": { + "ForAllValues:StringEquals": { + "dynamodb:LeadingKeys": ["${aws:PrincipalTag/task_id}"] + } + }, + } + ) statements += [ { "Effect": "Allow", @@ -160,19 +176,39 @@ def test_agent_writes_its_own_events_trace_and_task_record(self, scoped, task_id assert record is not None assert (record["status"], record["trace_s3_uri"]) == ("COMPLETED", uri) - def test_approval_gate_transaction_spans_both_of_the_tasks_tables(self, scoped, task_id): + def test_a_scoped_worker_cannot_open_a_gate_without_the_trusted_writer(self, scoped, task_id): + # Cloud workers request approvals through the trusted writer (#1000). Without + # its endpoint the request fails closed instead of writing the row itself. scoped.table(scoped.task_table).put_item(Item={"task_id": task_id, "status": "RUNNING"}) request_id = _generate_ulid() - row = approval_row(task_id, request_id) - task_state.transact_write_approval_request(task_id, request_id, row) - task_state.transact_resume_from_approval(task_id, request_id) + with pytest.raises(RuntimeError, match="APPROVAL_REQUESTS_API_URL is required"): + task_state.transact_write_approval_request( + task_id, request_id, approval_row(task_id, request_id) + ) - assert task_state.get_approval_row(task_id, request_id) == row + assert task_state.get_approval_row(task_id, request_id) is None record = task_state.get_task(task_id) assert record is not None assert record["status"] == "RUNNING" + def test_the_session_can_read_but_not_write_its_own_approval_rows(self, scoped, task_id): + request_id = _generate_ulid() + scoped.table(scoped.task_approvals_table).put_item(Item=approval_row(task_id, request_id)) + approvals = tenant_client("dynamodb") + key = {"task_id": {"S": task_id}, "request_id": {"S": request_id}} + + assert approvals.get_item(TableName=scoped.task_approvals_table, Key=key)["Item"] + with pytest.raises(ClientError) as denied: + approvals.update_item( + TableName=scoped.task_approvals_table, + Key=key, + UpdateExpression="SET #s = :s", + ExpressionAttributeNames={"#s": "status"}, + ExpressionAttributeValues={":s": {"S": "APPROVED"}}, + ) + assert denied.value.response["Error"]["Code"] == "AccessDeniedException" + class TestOtherTenantsDataIsOutOfReach: """Tripwire only — see the module docstring for what a denial here means."""