From 6cc40152a0d2e325af5652bf5650baa84132c2ab Mon Sep 17 00:00:00 2001 From: bgagent Date: Sun, 15 Nov 2026 13:35:42 -0600 Subject: [PATCH 01/25] test(tooling): add the AWS Emulator integration tier (ADR-013 Tier 2a) ADR-013 marks Tier 2a (container integration tests between the unit build and remote CI) as "does not exist". This adds it in one narrow shape: ABCA's real handler, CLI and agent code runs in jest and pytest as usual, and only its AWS SDK calls go to a pinned AWS Emulator (https://github.com/aws/aws-emulator) on loopback. It needs Docker and no AWS account. It does not replace the real-AWS integ smoke: IAM, deployment and the AgentCore runtime are outside what an emulator can show. What is added: - scripts/aws-emulator/: a Dockerfile that pins the emulator version and verifies the package signature, a wrapper (up, down, run) that replaces the AWS environment with the emulator's, a jest configuration builder and global setup that refuse any other environment, and a Node preload that refuses connections leaving the machine. - cdk/test/emulator: the task API handlers, the concurrency reconciler and the orchestrator's admission and finalize functions on tables created from the CDK constructs. Four tests are test.failing witnesses of defects on main (#51 twice, #1003, and the reconciler's status list that PR #1009 rewrites). - cli/test/emulator: configure, login, token refresh and password change against a Cognito pool created through emulated CloudFormation. - agent/tests_emulator: progress events, trace upload, secrets, CloudWatch Logs, the tenant-scoped session, the approval transactions, and the trace round trip of #61 (agent upload, get-trace-url handler, bgagent trace download). - mise tasks emulator:up, emulator:down, emulator:run and test:integration. None is reachable from `mise run build`. The unit runs cannot pick these tests up, by naming and location: the jest files are *.emulator.ts, which the unit testMatch does not match, and the agent suite sits beside tests/, the only directory the unit run collects. knip.json names the tier's entry files (the two emulator jest configurations, the suites, the trace shim, the global setup and the Node preload), which the dead-code check cannot reach from the unit entry points. Verified at this commit as first made, on main c8fcdb08: - `mise run test:integration` from the repository root, in a login shell that exports a real AWS profile: 11 cdk, 5 cli and 42 agent tests pass in 29 s, emulator start and stop included. - `uvx ruff check tests_emulator` and `uvx ruff format --check tests_emulator` pass in agent/. - scripts/aws-emulator/emulator.sh is committed with mode 100755. After the rebase onto 8697c821 (main with #1035) the tier was run again at the head of the series, not at this commit. Refs #1041 --- .dockerignore | 4 + agent/pyproject.toml | 1 + agent/tests_emulator/__init__.py | 0 agent/tests_emulator/conftest.py | 309 ++++++++++++++++++ .../test_approval_transactions.py | 119 +++++++ agent/tests_emulator/test_cloudwatch_logs.py | 111 +++++++ agent/tests_emulator/test_progress_events.py | 128 ++++++++ agent/tests_emulator/test_scoped_session.py | 231 +++++++++++++ agent/tests_emulator/test_secrets.py | 118 +++++++ agent/tests_emulator/test_trace_round_trip.py | 208 ++++++++++++ agent/tests_emulator/test_trace_upload.py | 134 ++++++++ cdk/jest.emulator.config.js | 2 + .../emulator/concurrency-seats.emulator.ts | 188 +++++++++++ cdk/test/emulator/harness.ts | 125 +++++++ cdk/test/emulator/task-api.emulator.ts | 197 +++++++++++ cdk/test/emulator/trace-api-shim.ts | 71 ++++ cli/jest.emulator.config.js | 2 + cli/test/emulator/cognito-sign-in.emulator.ts | 242 ++++++++++++++ knip.json | 8 +- mise.toml | 38 +++ scripts/aws-emulator/Dockerfile | 62 ++++ scripts/aws-emulator/emulator.sh | 133 ++++++++ scripts/aws-emulator/jest-config.js | 45 +++ scripts/aws-emulator/jest-global-setup.js | 54 +++ scripts/aws-emulator/loopback-only.cjs | 47 +++ 25 files changed, 2575 insertions(+), 2 deletions(-) create mode 100644 agent/tests_emulator/__init__.py create mode 100644 agent/tests_emulator/conftest.py create mode 100644 agent/tests_emulator/test_approval_transactions.py create mode 100644 agent/tests_emulator/test_cloudwatch_logs.py create mode 100644 agent/tests_emulator/test_progress_events.py create mode 100644 agent/tests_emulator/test_scoped_session.py create mode 100644 agent/tests_emulator/test_secrets.py create mode 100644 agent/tests_emulator/test_trace_round_trip.py create mode 100644 agent/tests_emulator/test_trace_upload.py create mode 100644 cdk/jest.emulator.config.js create mode 100644 cdk/test/emulator/concurrency-seats.emulator.ts create mode 100644 cdk/test/emulator/harness.ts create mode 100644 cdk/test/emulator/task-api.emulator.ts create mode 100644 cdk/test/emulator/trace-api-shim.ts create mode 100644 cli/jest.emulator.config.js create mode 100644 cli/test/emulator/cognito-sign-in.emulator.ts create mode 100644 scripts/aws-emulator/Dockerfile create mode 100755 scripts/aws-emulator/emulator.sh create mode 100644 scripts/aws-emulator/jest-config.js create mode 100644 scripts/aws-emulator/jest-global-setup.js create mode 100644 scripts/aws-emulator/loopback-only.cjs diff --git a/.dockerignore b/.dockerignore index 5e535dbb7..563244a02 100644 --- a/.dockerignore +++ b/.dockerignore @@ -32,6 +32,10 @@ agent/**/*.pyc # Deployment profile (ADR-024): infrastructure selection only; editing it must not rebuild the image abca.deployment*.json +# Emulator test tooling: never part of the agent image, and bumping its pinned +# version must not change the image hash +scripts/aws-emulator/ + # Git and tooling .git/ .prek/ diff --git a/agent/pyproject.toml b/agent/pyproject.toml index beed12af7..2d2619461 100644 --- a/agent/pyproject.toml +++ b/agent/pyproject.toml @@ -166,6 +166,7 @@ ignore = [ max-complexity = 15 [tool.ruff.lint.per-file-ignores] +"tests_emulator/**" = ["S101", "S106", "S108", "PLR2004", "ARG", "TID251"] # emulator-backed tests (mise run test:integration): assert; test tokens; /tmp paths; literal assertions; fixtures taken for their effect; their own boto3 session "src/entrypoint.py" = ["E402"] # re-export shim: importlib.reload() call must precede re-export from-imports # aws_session.py is the one module that builds boto3 clients, resources and sessions: # it attaches the solution User-Agent (#319). TID251 is one rule for the whole diff --git a/agent/tests_emulator/__init__.py b/agent/tests_emulator/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/agent/tests_emulator/conftest.py b/agent/tests_emulator/conftest.py new file mode 100644 index 000000000..df9bb80c1 --- /dev/null +++ b/agent/tests_emulator/conftest.py @@ -0,0 +1,309 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 + +"""Fixtures for tests that run agent code against a local AWS Emulator (ADR-013 Tier 2a). + +Everything under ``tests_emulator/`` makes real AWS SDK calls. They go to an AWS +Emulator (https://github.com/aws/aws-emulator) on this machine, selected by the +environment ``scripts/aws-emulator/emulator.sh run`` builds:: + + AWS_ENDPOINT_URL=https://127.0.0.1: + AWS_SHARED_CREDENTIALS_FILE, AWS_CONFIG_FILE, AWS_CA_BUNDLE (written by the emulator) + NODE_EXTRA_CA_CERTS= (cross-language test only) + +This directory sits beside ``tests/``, not inside it: the unit run collects +``tests/`` only (``testpaths``), and the unit suite's conftest never applies +here. ``mise run test:integration`` runs it; for one file:: + + cd agent && ../scripts/aws-emulator/emulator.sh run uv run pytest --no-cov tests_emulator/ + +There is no skip path. Unless the AWS environment is exactly the emulator's, +every test fails before anything is created: with no endpoint these calls would +go to AWS with whatever credentials the shell holds. The session also refuses to +start unless STS, resolved the way agent code resolves it, reports the +emulator's fixed account id. And nothing in this process may connect anywhere +but loopback (``_refuse_non_loopback``): the environment only says where AWS SDK +calls go, and agent code also calls GitHub, Linear and Jira. + +The emulator keeps state in memory and has no reset call, so isolation comes from +names: one set of tables/bucket/log group per pytest session (unique run id), and +a fresh task id and user id per test. +""" + +from __future__ import annotations + +import os +import re +import socket +import sys +import uuid +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any + +import pytest + +if TYPE_CHECKING: + from task_state import ApprovalRow + +EMULATOR_ACCOUNT_ID = "000000000000" +# An IP address, not ``localhost``: with a host name the JavaScript SDK addresses +# S3 buckets as ``.localhost``, which the emulator's certificate does not cover. +_LOOPBACK_EMULATOR = re.compile(r"https://127\.0\.0\.1:\d+") +# What emulator.sh sets. Anything else in the AWS_* namespace (a profile, keys, a +# per-service endpoint, AWS_IGNORE_CONFIGURED_ENDPOINT_URLS) could send a call +# somewhere other than the emulator, or sign it with real credentials. +_EXPECTED_AWS_ENV = frozenset( + { + "AWS_ENDPOINT_URL", + "AWS_SHARED_CREDENTIALS_FILE", + "AWS_CONFIG_FILE", + "AWS_CA_BUNDLE", + "AWS_EC2_METADATA_DISABLED", + "AWS_DISABLE_HOST_PREFIX_INJECTION", + "AWS_REGION", + "AWS_DEFAULT_REGION", + } +) +_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "localhost", "::1"}) + +_REGION = os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION") or "us-east-1" + + +def _refuse_non_loopback(event: str, args: tuple[Any, ...]) -> None: + """Audit hook: refuse a connection, datagram or name lookup that would leave this machine. + + It covers this process only; a child process does not inherit an audit hook. + The refusal reaches the caller as an ordinary network error, so a test of + code that swallows network errors has to assert that no request was attempted. + When a test fails here, stub the call that tried to connect. Do not add hosts. + """ + if event in ("socket.connect", "socket.sendto", "socket.sendmsg"): + address = args[1] + host = address[0] if isinstance(address, tuple) else None # a str is a Unix socket path + elif event in ("socket.getaddrinfo", "socket.gethostbyname", "socket.gethostbyname_ex"): + host = args[0] + else: + return + if isinstance(host, bytes): + host = host.decode("ascii", "replace") + if host is not None and host not in _LOOPBACK_HOSTS: + raise PermissionError( + f"emulator tests must not open a connection that leaves this machine, " + f"and this one tried to reach {host!r}" + ) + + +# An audit hook cannot be removed again. That is fine here: this conftest is only +# loaded by a pytest process that was asked for tests_emulator. +sys.addaudithook(_refuse_non_loopback) + + +def _why_not_an_emulator() -> str | None: + """Reason the AWS environment could reach something other than a local emulator.""" + endpoint = os.environ.get("AWS_ENDPOINT_URL", "") + if not _LOOPBACK_EMULATOR.fullmatch(endpoint): + return ( + f"AWS_ENDPOINT_URL must be https://127.0.0.1: (it is {endpoint!r}); " + "run these tests with `mise run test:integration`" + ) + strays = sorted( + name for name in os.environ if name.startswith("AWS_") and name not in _EXPECTED_AWS_ENV + ) + if strays: + return f"unexpected AWS configuration in the environment: {', '.join(strays)}" + return None + + +@dataclass(frozen=True) +class Emulator: + """A verified emulator plus the resources this pytest session created in it.""" + + endpoint: str + region: str + ca_bundle: str + # Signed with the emulator's own key, which the emulator never denies: the + # tests use it to seed and to read back, independently of the code under test. + session: Any + task_table: str + task_events_table: str + task_approvals_table: str + trace_bucket: str + log_group: str + + def client(self, service_name: str, **kwargs: Any) -> Any: + return self.session.client(service_name, endpoint_url=self.endpoint, **kwargs) + + def table(self, name: str) -> Any: + return self.session.resource("dynamodb", endpoint_url=self.endpoint).Table(name) + + +# Key schemas of the tables these tests exercise. They mirror task-table.ts, +# task-events-table.ts and task-approvals-table.ts under cdk/src/constructs/; the +# agent uses none of their GSIs. +_TABLE_KEYS = { + "task_table": [("task_id", "HASH")], + "task_events_table": [("task_id", "HASH"), ("event_id", "RANGE")], + "task_approvals_table": [("task_id", "HASH"), ("request_id", "RANGE")], +} + + +def _create_tables(ddb: Any, names: dict[str, str]) -> None: + for field, name in names.items(): + keys = _TABLE_KEYS[field] + ddb.create_table( + TableName=name, + BillingMode="PAY_PER_REQUEST", + AttributeDefinitions=[{"AttributeName": k, "AttributeType": "S"} for k, _ in keys], + KeySchema=[{"AttributeName": k, "KeyType": kind} for k, kind in keys], + ) + # The emulator keeps a new table CREATING for three seconds, like AWS does for + # longer. Create them all first so the waits overlap. boto3's default is to + # poll every 20 seconds. + for name in names.values(): + ddb.get_waiter("table_exists").wait( + TableName=name, WaiterConfig={"Delay": 1, "MaxAttempts": 30} + ) + + +@pytest.fixture(scope="session") +def emulator() -> Any: + # Every test depends on this fixture (through ``_isolated_agent_state``), so + # failing here stops the whole run before anything below can reach AWS itself. + reason = _why_not_an_emulator() + if reason: + pytest.fail(reason, pytrace=False) + # The audit hook has to be in force before anything below runs. With it, the + # lookup is refused before a query is sent. + try: + socket.getaddrinfo("loopback-guard-check.invalid", 443) + except OSError as exc: + refused = isinstance(exc, PermissionError) + else: + refused = False + if not refused: + pytest.fail("the loopback-only audit hook did not refuse a name lookup", pytrace=False) + + import boto3 + from botocore.config import Config + from botocore.exceptions import BotoCoreError, ClientError + + endpoint = os.environ["AWS_ENDPOINT_URL"] + run_id = uuid.uuid4().hex[:8] + tables = { + "task_table": f"abca-emu-{run_id}-TaskTable", + "task_events_table": f"abca-emu-{run_id}-TaskEventsTable", + "task_approvals_table": f"abca-emu-{run_id}-TaskApprovalsTable", + } + emu = Emulator( + endpoint=endpoint, + region=_REGION, + ca_bundle=os.environ.get("AWS_CA_BUNDLE", ""), + session=boto3.Session(region_name=_REGION), + trace_bucket=f"abca-emu-{run_id}-traces", + log_group=f"/abca-emu/{run_id}/application", + **tables, + ) + + fail_fast = Config(connect_timeout=3, read_timeout=10, retries={"total_max_attempts": 1}) + # Built with no endpoint argument, the way agent code builds its clients: a + # setting in the shared config file can turn AWS_ENDPOINT_URL off, and this is + # where that shows. + sts = emu.session.client("sts", config=fail_fast) + problem = None + if sts.meta.endpoint_url != endpoint: + problem = f"SDK clients resolve to {sts.meta.endpoint_url}, not to {endpoint}" + else: + try: + account = sts.get_caller_identity()["Account"] + except (BotoCoreError, ClientError) as exc: + problem = f"AWS_ENDPOINT_URL={endpoint} is set but did not answer STS: {exc}" + else: + if account != EMULATOR_ACCOUNT_ID: + problem = ( + f"{endpoint} answered as account {account}, not the emulator's " + f"{EMULATOR_ACCOUNT_ID}; refusing to create test resources there" + ) + if problem: + pytest.fail(problem, pytrace=False) + + ddb, s3, logs = emu.client("dynamodb"), emu.client("s3"), emu.client("logs") + _create_tables(ddb, tables) + s3.create_bucket(Bucket=emu.trace_bucket) + logs.create_log_group(logGroupName=emu.log_group) + + yield emu + + for name in tables.values(): + ddb.delete_table(TableName=name) + for obj in s3.list_objects_v2(Bucket=emu.trace_bucket).get("Contents", []): + s3.delete_object(Bucket=emu.trace_bucket, Key=obj["Key"]) + s3.delete_bucket(Bucket=emu.trace_bucket) + logs.delete_log_group(logGroupName=emu.log_group) + + +def _reset_agent_module_state() -> None: + """Drop what agent modules cache at module level between calls. + + A client or table handle cached by one test would otherwise be reused by the + next one, with the previous test's table names and session. + """ + import aws_session + import progress_writer + import task_state + + aws_session.reset_session_cache() + progress_writer._reset_circuit_breakers() + task_state._table = None + + +@pytest.fixture(autouse=True) +def _isolated_agent_state(emulator: Emulator) -> Any: + """Give each test clean agent module state, and leave none behind.""" + _reset_agent_module_state() + yield + _reset_agent_module_state() + + +@pytest.fixture +def agent_env(emulator: Emulator, monkeypatch: pytest.MonkeyPatch) -> Emulator: + """The environment the stack gives the agent runtime (cdk/src/stacks/agent.ts).""" + monkeypatch.setenv("AWS_REGION", emulator.region) + monkeypatch.setenv("TASK_TABLE_NAME", emulator.task_table) + monkeypatch.setenv("TASK_EVENTS_TABLE_NAME", emulator.task_events_table) + monkeypatch.setenv("TASK_APPROVALS_TABLE_NAME", emulator.task_approvals_table) + monkeypatch.setenv("TRACE_ARTIFACTS_BUCKET_NAME", emulator.trace_bucket) + return emulator + + +def approval_row(task_id: str, request_id: str) -> ApprovalRow: + """A pending approval as the PreToolUse hook records it (design §10.1).""" + return { + "task_id": task_id, + "request_id": request_id, + "tool_name": "Bash", + "tool_input_preview": "git push --force", + "tool_input_sha256": "a" * 64, + "reason": "Soft-deny: force_push_any", + "severity": "high", + "matching_rule_ids": ["force_push_any"], + "status": "PENDING", + "created_at": "2026-05-07T00:00:00Z", + "timeout_s": 300, + "ttl": 1_800_000_000, + "user_id": "u-alice", + "repo": "owner/repo", + } + + +@pytest.fixture +def task_id() -> str: + """A task id shaped like production ones (ULID), unique per test.""" + from progress_writer import _generate_ulid + + return _generate_ulid() + + +@pytest.fixture +def user_id() -> str: + """A platform user id shaped like a Cognito ``sub``, unique per test.""" + return str(uuid.uuid4()) diff --git a/agent/tests_emulator/test_approval_transactions.py b/agent/tests_emulator/test_approval_transactions.py new file mode 100644 index 000000000..d6a0a122f --- /dev/null +++ b/agent/tests_emulator/test_approval_transactions.py @@ -0,0 +1,119 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 + +"""The approval-gate writes in ``task_state.py`` against real DynamoDB semantics. + +``tests/test_task_state.py`` hands these functions a MagicMock client, because (as +``_get_ddb_client`` notes) moto did not fully emulate ``TransactWriteItems`` with +conditions across two tables. Here the transactions run: the conditions are +evaluated by the service, a cancelled transaction really leaves nothing behind, +and the cancellation reasons are the ones the SDK reports. +""" + +from __future__ import annotations + +import pytest + +import task_state +from progress_writer import _generate_ulid + +from .conftest import approval_row + + +def _task(task_id: str) -> dict: + record = task_state.get_task(task_id) + assert record is not None + return record + + +@pytest.fixture +def running_task(agent_env, task_id) -> str: + """A task the orchestrator created and the agent already marked RUNNING.""" + agent_env.table(agent_env.task_table).put_item(Item={"task_id": task_id, "status": "RUNNING"}) + return task_id + + +@pytest.fixture +def pending_request(running_task) -> str: + """An approval the agent is waiting on for ``running_task``.""" + request_id = _generate_ulid() + task_state.transact_write_approval_request( + running_task, request_id, approval_row(running_task, request_id) + ) + return request_id + + +class TestApprovalRequest: + def test_pending_row_and_awaiting_status_are_written_together(self, running_task): + request_id = _generate_ulid() + row = approval_row(running_task, request_id) + + task_state.transact_write_approval_request(running_task, request_id, row) + + assert task_state.get_approval_row(running_task, request_id) == row + task = _task(running_task) + assert task["status"] == "AWAITING_APPROVAL" + assert task["awaiting_approval_request_id"] == request_id + + def test_cancelled_task_gets_no_approval_row(self, agent_env, running_task): + agent_env.table(agent_env.task_table).put_item( + Item={"task_id": running_task, "status": "CANCELLED"} + ) + request_id = _generate_ulid() + + with pytest.raises(task_state.ApprovalWriteError) as raised: + task_state.transact_write_approval_request( + running_task, request_id, approval_row(running_task, request_id) + ) + + # The Put passed its own condition and was still undone with the Update. + codes = [reason["Code"] for reason in raised.value.cancellation_reasons] + assert codes == ["None", "ConditionalCheckFailed"] + assert task_state.get_approval_row(running_task, request_id) is None + assert _task(running_task)["status"] == "CANCELLED" + + def test_same_request_cannot_be_recorded_twice(self, running_task, pending_request): + with pytest.raises(task_state.ApprovalWriteError) as raised: + task_state.transact_write_approval_request( + running_task, pending_request, approval_row(running_task, pending_request) + ) + + codes = [reason["Code"] for reason in raised.value.cancellation_reasons] + assert codes == ["ConditionalCheckFailed", "ConditionalCheckFailed"] + + +class TestResumeAndTimeout: + def test_resume_returns_the_task_to_running(self, running_task, pending_request): + task_state.transact_resume_from_approval(running_task, pending_request) + + task = _task(running_task) + assert task["status"] == "RUNNING" + assert "awaiting_approval_request_id" not in task + + def test_resume_for_a_different_request_is_refused(self, running_task, pending_request): + with pytest.raises(task_state.ApprovalResumeError): + task_state.transact_resume_from_approval(running_task, _generate_ulid()) + + assert _task(running_task)["status"] == "AWAITING_APPROVAL" + + def test_timeout_only_wins_while_the_request_is_still_pending( + self, running_task, pending_request + ): + 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" + ) + + assert (timed_out, late_denial) == (True, False) + row = task_state.get_approval_row(running_task, pending_request) + assert row is not None + assert row["status"] == "TIMED_OUT" + assert "deny_reason" not in row + + def test_gate_counter_is_created_then_incremented(self, running_task): + assert task_state.increment_approval_gate_count_in_ddb(running_task) is True + assert task_state.increment_approval_gate_count_in_ddb(running_task) is True + + assert _task(running_task)["approval_gate_count"] == 2 diff --git a/agent/tests_emulator/test_cloudwatch_logs.py b/agent/tests_emulator/test_cloudwatch_logs.py new file mode 100644 index 000000000..0ae037aff --- /dev/null +++ b/agent/tests_emulator/test_cloudwatch_logs.py @@ -0,0 +1,111 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 + +"""The agent's direct CloudWatch Logs writers against a real Logs API. + +Three writers put events into the application log group, each on its own stream +per task: the trajectory (``trajectory/``), the metrics report +(``metrics/``) and fatal errors (``agent_error/``). +""" + +from __future__ import annotations + +import json +import threading + +import pytest + +from shell import log_error_cw +from telemetry import _TrajectoryWriter, print_metrics + + +@pytest.fixture +def log_group(agent_env, monkeypatch) -> str: + monkeypatch.setenv("LOG_GROUP_NAME", agent_env.log_group) + return agent_env.log_group + + +def _messages(emulator, stream: str) -> list[str]: + events = emulator.client("logs").get_log_events( + logGroupName=emulator.log_group, logStreamName=stream, startFromHead=True + )["events"] + return [event["message"] for event in events] + + +class TestTrajectoryStream: + def test_turns_and_decisions_are_written_in_order(self, emulator, log_group, task_id): + writer = _TrajectoryWriter(task_id) + + writer.write_turn( + turn=1, model="claude", thinking="", text="hi", tool_calls=[], tool_results=[] + ) + writer.write_policy_decision("Bash", allowed=False, reason="hard deny", duration_ms=0.4) + + turn, decision = (json.loads(m) for m in _messages(emulator, f"trajectory/{task_id}")) + assert (turn["event"], turn["task_id"], turn["turn"]) == ("TRAJECTORY_TURN", task_id, 1) + assert decision == { + "event": "POLICY_DECISION", + "task_id": task_id, + "tool_name": "Bash", + "allowed": False, + "reason": "hard deny", + "duration_ms": 0.4, + } + + def test_second_writer_for_a_task_appends_to_the_existing_stream( + self, emulator, log_group, task_id + ): + _TrajectoryWriter(task_id).write_policy_decision("Read", True, "permit", 0.1) + second = _TrajectoryWriter(task_id) + + # The stream already exists: CreateLogStream answers + # ResourceAlreadyExistsException, which the writer must swallow. + second.write_policy_decision("Edit", True, "permit", 0.1) + + assert second._failure_count == 0 + tools = [json.loads(m)["tool_name"] for m in _messages(emulator, f"trajectory/{task_id}")] + assert tools == ["Read", "Edit"] + + def test_missing_log_group_disables_cloudwatch_but_not_the_trace_accumulator( + self, agent_env, task_id, monkeypatch, capsys + ): + monkeypatch.setenv("LOG_GROUP_NAME", f"{agent_env.log_group}-absent") + writer = _TrajectoryWriter(task_id, accumulate=True) + + for _ in range(4): + writer.write_policy_decision("Bash", True, "permit", 0.1) + + assert writer._disabled is True + assert writer._failure_count == writer._MAX_FAILURES + assert "ResourceNotFoundException" in capsys.readouterr().out + assert len(writer._events) == 4 + + +class TestMetricsAndErrorStreams: + def test_metrics_report_is_written_with_native_types(self, emulator, log_group, task_id): + print_metrics( + {"task_id": task_id, "status": "success", "turns": 3, "cost_usd": 0.25, "error": None} + ) + + (report,) = _messages(emulator, f"metrics/{task_id}") + assert json.loads(report) == { + "event": "METRICS_REPORT", + "task_id": task_id, + "status": "success", + "turns": 3, + "cost_usd": 0.25, + "error": None, + } + + def test_fatal_error_is_mirrored_to_the_application_log_group( + self, emulator, log_group, task_id + ): + log_error_cw("Agent failed: missing built-in hard-deny policies", task_id=task_id) + # The mirror runs on a daemon thread so it cannot block the failing path. + for thread in threading.enumerate(): + if thread.name == "agent-error-cw-write": + thread.join(timeout=30) + + assert _messages(emulator, f"agent_error/{task_id}") == [ + "[agent/error] Agent failed: missing built-in hard-deny policies" + ] diff --git a/agent/tests_emulator/test_progress_events.py b/agent/tests_emulator/test_progress_events.py new file mode 100644 index 000000000..aa29143d8 --- /dev/null +++ b/agent/tests_emulator/test_progress_events.py @@ -0,0 +1,128 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 + +"""``_ProgressWriter`` against a real DynamoDB API (the emulator's). + +``tests/test_progress_writer.py`` drives the writer with a MagicMock table and +hand-built ``ClientError``s. Here the same code talks to DynamoDB semantics: the +item has to survive the SDK's type marshalling and the service's validation, and +the errors the circuit breaker classifies are the ones the service really sends. +""" + +from __future__ import annotations + +import time +from decimal import Decimal + +from boto3.dynamodb.conditions import Key + +from progress_writer import _TTL_SECONDS, _ProgressWriter + + +def _events(emulator, task_id: str) -> list[dict]: + """All events for a task, oldest first. + + Ordered by the microsecond ``timestamp`` rather than by the table's sort key: + ``event_id`` only orders events to the millisecond, so two written within one + millisecond can come back from DynamoDB in either order. + """ + response = emulator.table(emulator.task_events_table).query( + KeyConditionExpression=Key("task_id").eq(task_id), ConsistentRead=True + ) + return sorted(response["Items"], key=lambda event: event["timestamp"]) + + +class TestProgressEventsReachDynamoDB: + def test_typed_events_round_trip_with_the_documented_item_shape(self, agent_env, task_id): + writer = _ProgressWriter(task_id, user_id="user-1", repo="owner/repo") + + writer.write_agent_milestone("clone_complete", "Repository cloned") + writer.write_agent_turn( + turn=1, model="claude", thinking="", text="Reading files", tool_calls_count=2 + ) + writer.write_agent_cost_update(cost_usd=0.1234, input_tokens=10, output_tokens=20, turn=1) + writer.write_approval_pre_approvals_loaded(count=2, scopes=["tool_type:Bash", "rule:r1"]) + + events = _events(agent_env, task_id) + assert [e["event_type"] for e in events] == [ + "agent_milestone", + "agent_turn", + "agent_cost_update", + "agent_milestone", + ] + milestone, turn, cost, approvals = events + assert milestone["metadata"] == { + "milestone": "clone_complete", + "details": "Repository cloned", + } + # Empty strings and nested lists are stored as given; numbers come back as + # DynamoDB numbers (the writer converts floats to Decimal for the SDK). + assert turn["metadata"]["thinking_preview"] == "" + assert turn["metadata"]["tool_calls_count"] == 2 + assert cost["metadata"]["cost_usd"] == Decimal("0.1234") + assert approvals["metadata"]["scopes"] == ["tool_type:Bash", "rule:r1"] + for event in events: + assert event["task_id"] == task_id + assert event["user_id"] == "user-1" + assert event["repo"] == "owner/repo" + assert len(event["event_id"]) == 26 + assert abs(int(event["ttl"]) - (time.time() + _TTL_SECONDS)) < 60 + # The sort key's time prefix follows emission order, which is what lets + # `bgagent watch` page through the table by event_id. + time_prefixes = [event["event_id"][:10] for event in events] + assert time_prefixes == sorted(time_prefixes) + + def test_unknown_cost_is_stored_as_null(self, agent_env, task_id): + _ProgressWriter(task_id).write_agent_cost_update( + cost_usd=None, input_tokens=1, output_tokens=2, turn=1 + ) + + (event,) = _events(agent_env, task_id) + assert event["metadata"]["cost_usd"] is None + assert "user_id" not in event + assert "repo" not in event + + def test_runner_and_pipeline_writers_share_one_stream(self, agent_env, task_id): + runner_writer = _ProgressWriter(task_id) + pipeline_writer = _ProgressWriter(task_id, trace=True) + + runner_writer.write_agent_tool_call("Bash", "ls", turn=1) + pipeline_writer.write_agent_milestone("pr_created", "x" * 5000) + + tool_call, milestone = _events(agent_env, task_id) + assert tool_call["metadata"]["tool_name"] == "Bash" + # trace=True raises the preview cap from 200 chars to 4 KB. + assert milestone["metadata"]["details"] == "x" * 4096 + "..." + + +class TestProgressWriterOnRealServiceErrors: + def test_item_over_400kb_is_dropped_without_tripping_the_breaker( + self, agent_env, task_id, capsys + ): + writer = _ProgressWriter(task_id) + + writer.write_approval_pre_approvals_loaded(count=500, scopes=["s" * 1000] * 500) + writer.write_agent_milestone("after_oversized", "still alive") + + assert "dropped event due to permanent DDB error" in capsys.readouterr().out + assert writer._disabled is False + assert writer._failure_count == 0 + assert [e["metadata"]["milestone"] for e in _events(agent_env, task_id)] == [ + "after_oversized" + ] + + def test_missing_table_opens_the_breaker_on_the_first_write( + self, agent_env, task_id, monkeypatch, capsys + ): + monkeypatch.setenv("TASK_EVENTS_TABLE_NAME", f"{agent_env.task_events_table}-absent") + writer = _ProgressWriter(task_id) + + writer.write_agent_milestone("first", "") + writer.write_agent_milestone("second", "") + + # One line for the first write; the second never reaches DynamoDB. + out = capsys.readouterr().out + assert out.count("disabling progress writer") == 1 + assert "ResourceNotFoundException" in out + assert writer._disabled is True + assert _ProgressWriter(task_id)._disabled is True diff --git a/agent/tests_emulator/test_scoped_session.py b/agent/tests_emulator/test_scoped_session.py new file mode 100644 index 000000000..9f7996bb0 --- /dev/null +++ b/agent/tests_emulator/test_scoped_session.py @@ -0,0 +1,231 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 + +"""The per-task scoped session (``aws_session.py``) against real STS and IAM APIs. + +``tests/test_aws_session.py`` checks the arguments handed to a mocked +``assume_role``. Here the agent really assumes a SessionRole with its +``{user_id, repo, task_id}`` session tags and uses the credentials it gets back. + +What the emulator lets these tests establish, and what it does not: + +* STS validates the request (role exists, trust policy allows ``sts:AssumeRole`` + and ``sts:TagSession``, tag shape) and returns credentials that DynamoDB and S3 + accept. That part behaves like AWS. +* For a role created in the emulator, DynamoDB and S3 also evaluate the role's + identity policy, including ``dynamodb:LeadingKeys`` and + ``${aws:PrincipalTag/...}`` — so a cross-tenant call is denied here. AWS states + that this evaluation is not the same as the real one. The denial tests below + are therefore a tripwire for the agent's wiring (tags reach STS, tenant data + goes through the scoped session), never evidence that the policy is safe. +* The role policy below is a hand-written mirror of + ``cdk/src/constructs/agent-session-role.ts``, not the deployed policy. +""" + +from __future__ import annotations + +import json +import uuid + +import pytest +from boto3.dynamodb.conditions import Key +from botocore.exceptions import ClientError + +import task_state +from aws_session import configure_session, is_scoped, tenant_client +from progress_writer import _generate_ulid, _ProgressWriter +from telemetry import upload_trace_to_s3 + +from .conftest import EMULATOR_ACCOUNT_ID, approval_row + +_ASSUMABLE_BY_ACCOUNT = {"AWS": f"arn:aws:iam::{EMULATOR_ACCOUNT_ID}:root"} + +# AgentSessionRole.DDB_ITEM_ACTIONS (Scan is deliberately absent). +_DDB_ITEM_ACTIONS = [ + "dynamodb:GetItem", + "dynamodb:BatchGetItem", + "dynamodb:Query", + "dynamodb:PutItem", + "dynamodb:UpdateItem", + "dynamodb:DeleteItem", + "dynamodb:BatchWriteItem", + "dynamodb:ConditionCheckItem", +] + + +def _trust_policy(actions: list[str]) -> str: + statement = {"Effect": "Allow", "Principal": _ASSUMABLE_BY_ACCOUNT, "Action": actions} + return json.dumps({"Version": "2012-10-17", "Statement": [statement]}) + + +def _session_role_policy(emulator) -> str: + table_arn = f"arn:aws:dynamodb:{emulator.region}:{EMULATOR_ACCOUNT_ID}:table" + bucket_arn = f"arn:aws:s3:::{emulator.trace_bucket}" + statements = [ + { + "Effect": "Allow", + "Action": _DDB_ITEM_ACTIONS, + "Resource": f"{table_arn}/{table}", + "Condition": { + "ForAllValues:StringEquals": { + "dynamodb:LeadingKeys": ["${aws:PrincipalTag/task_id}"] + } + }, + } + for table in ( + emulator.task_table, + emulator.task_events_table, + emulator.task_approvals_table, + ) + ] + statements += [ + { + "Effect": "Allow", + "Action": "s3:PutObject", + "Resource": f"{bucket_arn}/{prefix}/${{aws:PrincipalTag/{tag}}}/*", + } + for prefix, tag in (("traces", "user_id"), ("artifacts", "task_id")) + ] + return json.dumps({"Version": "2012-10-17", "Statement": statements}) + + +@pytest.fixture(scope="module") +def roles(emulator): + """A SessionRole like the deployed one, and one whose trust omits TagSession.""" + iam = emulator.client("iam") + suffix = uuid.uuid4().hex[:8] + session_role = f"abca-emu-{suffix}-SessionRole" + untaggable_role = f"abca-emu-{suffix}-NoTagSession" + + arns = { + "session": iam.create_role( + RoleName=session_role, + AssumeRolePolicyDocument=_trust_policy(["sts:AssumeRole", "sts:TagSession"]), + )["Role"]["Arn"], + "untaggable": iam.create_role( + RoleName=untaggable_role, + AssumeRolePolicyDocument=_trust_policy(["sts:AssumeRole"]), + )["Role"]["Arn"], + "absent": f"arn:aws:iam::{EMULATOR_ACCOUNT_ID}:role/abca-emu-{suffix}-Absent", + } + iam.put_role_policy( + RoleName=session_role, PolicyName="tenant", PolicyDocument=_session_role_policy(emulator) + ) + + yield arns + + iam.delete_role_policy(RoleName=session_role, PolicyName="tenant") + iam.delete_role(RoleName=session_role) + iam.delete_role(RoleName=untaggable_role) + + +@pytest.fixture +def scoped(agent_env, roles, monkeypatch, task_id, user_id): + """The agent as the pipeline leaves it: SessionRole set, session tags configured.""" + monkeypatch.setenv("AGENT_SESSION_ROLE_ARN", roles["session"]) + configure_session(user_id=user_id, repo="owner/repo", task_id=task_id) + return agent_env + + +def _events(emulator, task_id: str) -> list[dict]: + return emulator.table(emulator.task_events_table).query( + KeyConditionExpression=Key("task_id").eq(task_id), ConsistentRead=True + )["Items"] + + +class TestScopedCredentials: + def test_tenant_clients_act_as_the_session_role_named_for_the_task( + self, scoped, roles, task_id + ): + identity = tenant_client("sts").get_caller_identity() + + assert is_scoped() is True + role_name = roles["session"].rsplit("/", 1)[1] + assert identity["Arn"] == ( + f"arn:aws:sts::{EMULATOR_ACCOUNT_ID}:assumed-role/{role_name}/abca-{task_id}" + ) + + def test_agent_writes_its_own_events_trace_and_task_record(self, scoped, task_id, user_id): + scoped.table(scoped.task_table).put_item( + Item={"task_id": task_id, "user_id": user_id, "status": "RUNNING"} + ) + + _ProgressWriter(task_id, user_id=user_id).write_agent_milestone("clone_complete", "") + uri = upload_trace_to_s3(task_id=task_id, user_id=user_id, body=b"\x1f\x8b trace") + task_state.write_terminal(task_id, "COMPLETED", {"trace_s3_uri": uri}) + + assert [e["metadata"]["milestone"] for e in _events(scoped, task_id)] == ["clone_complete"] + assert uri == f"s3://{scoped.trace_bucket}/traces/{user_id}/{task_id}.jsonl.gz" + record = task_state.get_task(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): + 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) + + assert task_state.get_approval_row(task_id, request_id) == row + record = task_state.get_task(task_id) + assert record is not None + assert record["status"] == "RUNNING" + + +class TestOtherTenantsDataIsOutOfReach: + """Tripwire only — see the module docstring for what a denial here means.""" + + def test_event_for_another_task_is_denied_and_stops_the_writer(self, scoped, capsys): + other_task = _generate_ulid() + writer = _ProgressWriter(other_task) + + writer.write_agent_milestone("clone_complete", "") + + assert "AccessDeniedException" in capsys.readouterr().out + assert writer._disabled is True + assert _events(scoped, other_task) == [] + + def test_trace_under_another_users_prefix_is_denied(self, scoped, task_id, capsys): + other_user = str(uuid.uuid4()) + + uri = upload_trace_to_s3(task_id=task_id, user_id=other_user, body=b"\x1f\x8b trace") + + assert uri is None + assert "AccessDenied" in capsys.readouterr().out + listing = scoped.client("s3").list_objects_v2( + Bucket=scoped.trace_bucket, Prefix=f"traces/{other_user}/" + ) + assert listing["KeyCount"] == 0 + + def test_another_tasks_record_cannot_be_read(self, scoped): + other_task = _generate_ulid() + scoped.table(scoped.task_table).put_item(Item={"task_id": other_task, "status": "RUNNING"}) + + with pytest.raises(task_state.TaskFetchError, match="AccessDeniedException"): + task_state.get_task(other_task) + + +@pytest.mark.parametrize("role", ["absent", "untaggable"]) +class TestSessionRoleThatCannotBeAssumed: + @pytest.fixture + def unassumable(self, agent_env, roles, role, monkeypatch, task_id, user_id): + monkeypatch.setenv("AGENT_SESSION_ROLE_ARN", roles[role]) + configure_session(user_id=user_id, repo="owner/repo", task_id=task_id) + return agent_env + + def test_tenant_data_calls_fail_instead_of_using_ambient_credentials( + self, unassumable, task_id, user_id + ): + with pytest.raises(ClientError) as raised: + tenant_client("sts").get_caller_identity() + uri = upload_trace_to_s3(task_id=task_id, user_id=user_id, body=b"\x1f\x8b trace") + + assert raised.value.operation_name == "AssumeRole" + assert raised.value.response["Error"]["Code"] == "AccessDenied" + assert uri is None + listing = unassumable.client("s3").list_objects_v2( + Bucket=unassumable.trace_bucket, Prefix=f"traces/{user_id}/" + ) + assert listing["KeyCount"] == 0 diff --git a/agent/tests_emulator/test_secrets.py b/agent/tests_emulator/test_secrets.py new file mode 100644 index 000000000..a6877e6ee --- /dev/null +++ b/agent/tests_emulator/test_secrets.py @@ -0,0 +1,118 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 + +"""Credential lookups in ``config.py`` against a real Secrets Manager API.""" + +from __future__ import annotations + +import json +import os +import uuid +from datetime import UTC, datetime, timedelta + +import pytest +from botocore.exceptions import ClientError + +from config import resolve_github_token, resolve_linear_api_token + + +@pytest.fixture +def create_secret(emulator): + """Create secrets in the emulator; delete them when the test ends.""" + client = emulator.client("secretsmanager") + arns: list[str] = [] + + def _create(value: str) -> str: + arn = client.create_secret(Name=f"abca-emu/{uuid.uuid4().hex}", SecretString=value)["ARN"] + arns.append(arn) + return arn + + yield _create + + for arn in arns: + client.delete_secret(SecretId=arn, ForceDeleteWithoutRecovery=True) + + +@pytest.fixture +def token_env(agent_env, monkeypatch): + """Both resolvers cache the token in ``os.environ``; undo that after the test. + + They assign ``os.environ[...]`` directly, which pytest only reverts for + variables ``monkeypatch`` already owns — so claim them here, set to empty + (which the resolvers treat as "not cached"). + """ + monkeypatch.setenv("GITHUB_TOKEN", "") + monkeypatch.setenv("LINEAR_API_TOKEN", "") + monkeypatch.delenv("LINEAR_VAULT_ENABLED", raising=False) + monkeypatch.delenv("LINEAR_OAUTH_SECRET_ARN", raising=False) + + +class TestGithubTokenFromSecretsManager: + def test_token_is_read_by_arn_and_cached_for_git(self, token_env, create_secret, monkeypatch): + monkeypatch.setenv("GITHUB_TOKEN_SECRET_ARN", create_secret("emulator-github-token")) + + assert resolve_github_token() == "emulator-github-token" + assert os.environ["GITHUB_TOKEN"] == "emulator-github-token" # noqa: S105 + + def test_cached_token_is_returned_without_another_lookup( + self, token_env, create_secret, monkeypatch, emulator + ): + arn = create_secret("first-value") + monkeypatch.setenv("GITHUB_TOKEN_SECRET_ARN", arn) + resolve_github_token() + emulator.client("secretsmanager").put_secret_value(SecretId=arn, SecretString="rotated") + + assert resolve_github_token() == "first-value" + + def test_missing_secret_raises_the_service_error(self, token_env, monkeypatch): + monkeypatch.setenv( + "GITHUB_TOKEN_SECRET_ARN", + f"arn:aws:secretsmanager:us-east-1:000000000000:secret:absent-{uuid.uuid4().hex}", + ) + + with pytest.raises(ClientError) as raised: + resolve_github_token() + + assert raised.value.response["Error"]["Code"] == "ResourceNotFoundException" + + +class TestLinearTokenFromSecretsManager: + @staticmethod + def _oauth_secret(**overrides) -> str: + # expires_at is far enough ahead that the resolver never attempts a + # refresh, which would call Linear's real OAuth endpoint. + expires_at = (datetime.now(UTC) + timedelta(days=1)).isoformat().replace("+00:00", "Z") + return json.dumps( + { + "access_token": "emulator-linear-access", + "refresh_token": "emulator-linear-refresh", + "expires_at": expires_at, + "scope": "read,write", + **overrides, + } + ) + + def test_unexpired_token_is_returned_from_the_workspace_secret(self, token_env, create_secret): + arn = create_secret(self._oauth_secret()) + + resolved = resolve_linear_api_token({"linear_oauth_secret_arn": arn}) + + assert resolved == "emulator-linear-access" + assert os.environ["LINEAR_API_TOKEN"] == "emulator-linear-access" # noqa: S105 + + # ``shell.log`` writes to fd 1 directly, so these two read it with ``capfd``. + def test_secret_that_is_not_json_yields_no_token(self, token_env, create_secret, capfd): + arn = create_secret("not json") + + assert resolve_linear_api_token({"linear_oauth_secret_arn": arn}) == "" + assert "is not valid JSON" in capfd.readouterr().out + + def test_missing_secret_is_logged_as_an_error_and_yields_no_token(self, token_env, capfd): + arn = f"arn:aws:secretsmanager:us-east-1:000000000000:secret:absent-{uuid.uuid4().hex}" + + assert resolve_linear_api_token({"linear_oauth_secret_arn": arn}) == "" + # The resolver escalates to ERROR only for the two "will not self-heal" + # codes, matching on the code string the service returns. + assert "ERROR resolve_linear_api_token failed: ResourceNotFoundException" in ( + capfd.readouterr().out + ) diff --git a/agent/tests_emulator/test_trace_round_trip.py b/agent/tests_emulator/test_trace_round_trip.py new file mode 100644 index 000000000..909c66be8 --- /dev/null +++ b/agent/tests_emulator/test_trace_round_trip.py @@ -0,0 +1,208 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 + +"""The ``--trace`` round trip across all three languages' halves (issue #61). + + agent (Python) writes the gzipped JSONL trace to S3 and records its + URI on the task telemetry / pipeline / task_state + API handler (TS) checks ownership, HEADs the object, presigns a GET + cdk/src/handlers/get-trace-url.ts + CLI (TS) asks the API, downloads through the URL, gunzips + cli/src/commands/trace.ts + +``test_trace_key_contract.py`` pins the key shape by reading the TypeScript as +text. Here the three halves run for real against one emulator: the Python side in +this process, the TypeScript sides in Node from source (``tsx``, a dev dependency +of ``@abca/cdk``). The only stand-ins are for what sits between them in a +deployment: ``cdk/test/emulator/trace-api-shim.ts`` for API Gateway and its +Cognito authorizer (so the CLI runs in API-key mode and its login path is not +exercised), and a ``put_item`` for the task record the orchestrator would have +created. +""" + +from __future__ import annotations + +import gzip +import json +import os +import subprocess +import threading +from pathlib import Path + +import pytest +import requests + +import task_state +from models import TaskConfig +from pipeline import _maybe_upload_trace +from progress_writer import _ProgressWriter +from telemetry import _TrajectoryWriter + +_REPO_ROOT = Path(__file__).resolve().parents[2] +_TSX = _REPO_ROOT / "node_modules" / ".bin" / "tsx" +_API_SHIM = _REPO_ROOT / "cdk" / "test" / "emulator" / "trace-api-shim.ts" +_CLI = _REPO_ROOT / "cli" / "src" / "bin" / "bgagent.ts" + + +@pytest.fixture(scope="module") +def trace_api(emulator): + """Base URL of the real get-trace-url handler, served over HTTP for this module.""" + if not _TSX.exists(): + pytest.fail("Node dependencies are not installed (run `mise run install`)", pytrace=False) + env = { + **os.environ, + "AWS_REGION": emulator.region, + "NODE_EXTRA_CA_CERTS": emulator.ca_bundle, + "TASK_TABLE_NAME": emulator.task_table, + "TRACE_ARTIFACTS_BUCKET_NAME": emulator.trace_bucket, + } + shim = subprocess.Popen([_TSX, _API_SHIM], env=env, stdout=subprocess.PIPE, text=True) + assert shim.stdout is not None + first_line = shim.stdout.readline() + try: + port = json.loads(first_line)["port"] + except (ValueError, KeyError, TypeError): + shim.kill() + shim.wait(timeout=30) + shim.stdout.close() + pytest.fail(f"trace API shim did not start: {first_line!r}") + # The handler logs to stdout; keep reading so a full pipe can never stall it. + drain = threading.Thread(target=shim.stdout.read, daemon=True) + drain.start() + + yield f"http://127.0.0.1:{port}" + + shim.terminate() + shim.wait(timeout=30) + drain.join(timeout=30) + shim.stdout.close() + + +@pytest.fixture +def bgagent(trace_api, emulator, tmp_path): + """Run the real CLI as ``user`` against the handler; returns the finished process.""" + config_dir = tmp_path / "bgagent-config" + config_dir.mkdir() + (config_dir / "config.json").write_text(json.dumps({"api_url": trace_api})) + + def _run(user: str, *args: str) -> subprocess.CompletedProcess[bytes]: + env = { + **os.environ, + "BGAGENT_CONFIG_DIR": str(config_dir), + # API-key mode skips the Cognito login; the shim reads it as the caller. + "BGAGENT_API_KEY": user, + "NODE_EXTRA_CA_CERTS": emulator.ca_bundle, + } + return subprocess.run( + [_TSX, _CLI, *args], env=env, capture_output=True, timeout=90, check=False + ) + + return _run + + +@pytest.fixture +def traced_task(agent_env, task_id, user_id) -> bytes: + """A finished ``--trace`` task, written by the agent's own code. Returns the artifact.""" + agent_env.table(agent_env.task_table).put_item( + Item={"task_id": task_id, "user_id": user_id, "status": "RUNNING"} + ) + trajectory = _TrajectoryWriter(task_id, accumulate=True) + trajectory.write_turn( + turn=1, + model="claude", + thinking="plan", + text="Reading the repo — ünïcödé", + tool_calls=[{"name": "Bash", "input": {"command": "ls"}}], + tool_results=[{"tool_use_id": "t1", "content": "README.md\n" * 200, "is_error": False}], + ) + trajectory.write_policy_decision("Bash", allowed=True, reason="permit", duration_ms=1.5) + artifact = trajectory.dump_gzipped_jsonl() + assert artifact is not None + + config = TaskConfig( + repo_url="owner/repo", + aws_region=agent_env.region, + task_id=task_id, + task_description="Do a thing", + user_id=user_id, + trace=True, + ) + uri = _maybe_upload_trace(config, trajectory, _ProgressWriter(task_id, trace=True)) + task_state.write_terminal(task_id, "COMPLETED", {"trace_s3_uri": uri}) + return artifact + + +def _trace_url(api: str, task_id: str, caller: str) -> requests.Response: + return requests.get(f"{api}/tasks/{task_id}/trace", headers={"X-API-Key": caller}, timeout=30) + + +class TestTraceRoundTrip: + def test_cli_prints_the_jsonl_the_agent_wrote(self, traced_task, bgagent, task_id, user_id): + result = bgagent(user_id, "trace", "download", task_id) + + assert result.returncode == 0, result.stderr.decode() + assert result.stdout == gzip.decompress(traced_task) + header, *events = [json.loads(line) for line in result.stdout.splitlines()] + assert header["event"] == "TRAJECTORY_ARTIFACT_HEADER" + assert [e["event"] for e in events] == ["TRAJECTORY_TURN", "POLICY_DECISION"] + + def test_cli_output_file_is_the_stored_artifact_byte_for_byte( + self, traced_task, bgagent, task_id, user_id, tmp_path + ): + target = tmp_path / "trace.jsonl.gz" + + result = bgagent(user_id, "trace", "download", task_id, "-o", str(target)) + + assert result.returncode == 0, result.stderr.decode() + assert target.read_bytes() == traced_task + + def test_presigned_url_works_for_any_https_client_that_trusts_the_emulator( + self, traced_task, trace_api, emulator, task_id, user_id + ): + issued = _trace_url(trace_api, task_id, user_id) + assert issued.status_code == 200, issued.text + + download = requests.get(issued.json()["data"]["url"], verify=emulator.ca_bundle, timeout=30) + + assert download.status_code == 200 + assert download.content == traced_task + assert download.headers["Content-Type"] == "application/gzip" + assert "Content-Encoding" not in download.headers + + +class TestTraceUrlIsRefused: + def test_for_a_caller_who_does_not_own_the_task(self, traced_task, trace_api, task_id): + response = _trace_url(trace_api, task_id, "someone-else") + + assert response.status_code == 403 + assert response.json()["error"]["code"] == "FORBIDDEN" + # The key-prefix guard further down answers with the same status and code; + # the message is what shows that the record-ownership check refused this. + assert response.json()["error"]["message"] == "You do not have access to this task." + + def test_until_the_agent_has_recorded_a_trace( + self, agent_env, bgagent, trace_api, task_id, user_id + ): + agent_env.table(agent_env.task_table).put_item( + Item={"task_id": task_id, "user_id": user_id, "status": "RUNNING"} + ) + + response = _trace_url(trace_api, task_id, user_id) + result = bgagent(user_id, "trace", "download", task_id) + + assert response.status_code == 404 + assert response.json()["error"]["code"] == "TRACE_NOT_AVAILABLE" + assert result.returncode != 0 + assert f"No trace artifact for task {task_id}" in result.stderr.decode() + + def test_when_the_recorded_object_is_gone_from_s3( + self, traced_task, trace_api, emulator, task_id, user_id + ): + emulator.client("s3").delete_object( + Bucket=emulator.trace_bucket, Key=f"traces/{user_id}/{task_id}.jsonl.gz" + ) + + response = _trace_url(trace_api, task_id, user_id) + + assert response.status_code == 404 + assert response.json()["error"]["code"] == "TRACE_NOT_AVAILABLE" diff --git a/agent/tests_emulator/test_trace_upload.py b/agent/tests_emulator/test_trace_upload.py new file mode 100644 index 000000000..b46cfd2f0 --- /dev/null +++ b/agent/tests_emulator/test_trace_upload.py @@ -0,0 +1,134 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# SPDX-License-Identifier: MIT-0 + +"""The ``--trace`` upload half (design §10.1) against a real S3 API. + +``tests/test_trace_upload.py`` asserts the ``put_object`` arguments on a mock. +Here the object is written to the emulator's S3 and read back, so the stored +bytes, key and content headers are what a downloader would actually receive. +""" + +from __future__ import annotations + +import gzip +import json + +from boto3.dynamodb.conditions import Key + +from models import TaskConfig +from pipeline import _maybe_upload_trace +from progress_writer import _ProgressWriter +from telemetry import _TrajectoryWriter, upload_trace_to_s3 + + +def _task_config(task_id: str, user_id: str, *, trace: bool) -> TaskConfig: + return TaskConfig( + repo_url="owner/repo", + aws_region="us-east-1", + task_id=task_id, + task_description="Do a thing", + user_id=user_id, + trace=trace, + ) + + +def _recorded_trajectory(task_id: str) -> _TrajectoryWriter: + """A trajectory with the events a short traced task accumulates.""" + trajectory = _TrajectoryWriter(task_id, accumulate=True) + trajectory.write_turn( + turn=1, + model="claude", + thinking="plan", + text="Reading the repo — ünïcödé", + tool_calls=[{"name": "Bash", "input": {"command": "ls"}}], + tool_results=[{"tool_use_id": "t1", "content": "README.md", "is_error": False}], + ) + trajectory.write_policy_decision("Bash", allowed=True, reason="permit", duration_ms=1.5) + trajectory.write_result( + subtype="success", + num_turns=1, + cost_usd=0.01, + duration_ms=1200, + duration_api_ms=900, + session_id="session-1", + usage=None, + ) + return trajectory + + +def _artifact(trajectory: _TrajectoryWriter) -> bytes: + artifact = trajectory.dump_gzipped_jsonl() + assert artifact is not None + return artifact + + +def _stored_trace(emulator, user_id: str, task_id: str) -> dict: + return emulator.client("s3").get_object( + Bucket=emulator.trace_bucket, Key=f"traces/{user_id}/{task_id}.jsonl.gz" + ) + + +class TestTraceUploadReachesS3: + def test_artifact_is_stored_byte_for_byte_under_the_callers_prefix( + self, agent_env, task_id, user_id + ): + artifact = _artifact(_recorded_trajectory(task_id)) + + uri = upload_trace_to_s3(task_id=task_id, user_id=user_id, body=artifact) + + assert uri == f"s3://{agent_env.trace_bucket}/traces/{user_id}/{task_id}.jsonl.gz" + stored = _stored_trace(agent_env, user_id, task_id) + assert stored["Body"].read() == artifact + # Described as gzip *content*, not as a gzip *encoding*: a client that saw + # Content-Encoding: gzip would decompress it behind the CLI's back. + assert stored["ContentType"] == "application/gzip" + assert "ContentEncoding" not in stored + + def test_stored_artifact_is_header_plus_events_as_jsonl(self, agent_env, task_id, user_id): + artifact = _artifact(_recorded_trajectory(task_id)) + upload_trace_to_s3(task_id=task_id, user_id=user_id, body=artifact) + + body = _stored_trace(agent_env, user_id, task_id)["Body"].read() + header, *events = [json.loads(line) for line in gzip.decompress(body).splitlines()] + assert header["event"] == "TRAJECTORY_ARTIFACT_HEADER" + assert header["task_id"] == task_id + assert header["accumulated_events"] == 3 + assert [e["event"] for e in events] == [ + "TRAJECTORY_TURN", + "POLICY_DECISION", + "TRAJECTORY_RESULT", + ] + assert events[0]["text"] == "Reading the repo — ünïcödé" + + def test_missing_bucket_fails_open(self, agent_env, task_id, user_id, monkeypatch, capsys): + monkeypatch.setenv("TRACE_ARTIFACTS_BUCKET_NAME", f"{agent_env.trace_bucket}-absent") + + uri = upload_trace_to_s3(task_id=task_id, user_id=user_id, body=b"\x1f\x8b") + + assert uri is None + assert "S3 put_object failed: NoSuchBucket" in capsys.readouterr().out + + +class TestPipelineTraceUpload: + def test_upload_announces_the_artifact_on_the_event_stream(self, agent_env, task_id, user_id): + config = _task_config(task_id, user_id, trace=True) + progress = _ProgressWriter(task_id, trace=True, user_id=user_id, repo=config.repo_url) + + uri = _maybe_upload_trace(config, _recorded_trajectory(task_id), progress) + + assert uri == f"s3://{agent_env.trace_bucket}/traces/{user_id}/{task_id}.jsonl.gz" + (event,) = agent_env.table(agent_env.task_events_table).query( + KeyConditionExpression=Key("task_id").eq(task_id), ConsistentRead=True + )["Items"] + assert event["metadata"] == {"milestone": "trajectory_uploaded", "details": uri} + + def test_task_without_trace_uploads_nothing(self, agent_env, task_id, user_id): + config = _task_config(task_id, user_id, trace=False) + + uri = _maybe_upload_trace(config, _recorded_trajectory(task_id), _ProgressWriter(task_id)) + + assert uri is None + listing = agent_env.client("s3").list_objects_v2( + Bucket=agent_env.trace_bucket, Prefix=f"traces/{user_id}/" + ) + assert listing["KeyCount"] == 0 diff --git a/cdk/jest.emulator.config.js b/cdk/jest.emulator.config.js new file mode 100644 index 000000000..fd9254d2b --- /dev/null +++ b/cdk/jest.emulator.config.js @@ -0,0 +1,2 @@ +// Emulator-backed handler tests (test/emulator/*.emulator.ts). Run with `mise run test:integration`. +module.exports = require('../scripts/aws-emulator/jest-config')(require('./package.json').jest); diff --git a/cdk/test/emulator/concurrency-seats.emulator.ts b/cdk/test/emulator/concurrency-seats.emulator.ts new file mode 100644 index 000000000..79ac624e4 --- /dev/null +++ b/cdk/test/emulator/concurrency-seats.emulator.ts @@ -0,0 +1,188 @@ +/** + * 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. + */ + +/** + * Per-user concurrency seats against the AWS Emulator (ADR-013 Tier 2a). + * + * A seat is one unit of `active_count` in UserConcurrencyTable: admission takes + * it with a conditional increment and finalization gives it back. The durable + * `orchestrate-task` entry point needs the Lambda durable-execution service, so + * these tests call the functions its steps call (`shared/orchestrator.ts`), plus + * the real `create-task`, `get-task` and `reconcile-concurrency` handlers. + * + * Runs only through `jest.emulator.config.js` (see ./harness). + */ + +import { randomUUID } from 'node:crypto'; +import { GetCommand, UpdateCommand } from '@aws-sdk/lib-dynamodb'; +import { apiEvent, emulatorTables } from './harness'; +import { TaskEventsTable } from '../../src/constructs/task-events-table'; +import { TaskStatus } from '../../src/constructs/task-status'; +import { TaskTable } from '../../src/constructs/task-table'; +import { UserConcurrencyTable } from '../../src/constructs/user-concurrency-table'; + +const MAX_SEATS = 3; + +// Handlers read their configuration at module load, so the environment is set +// before any handler is imported. Names are unique to this file's run. +const run = randomUUID().slice(0, 8); +process.env.TASK_TABLE_NAME = `emu-${run}-tasks`; +process.env.TASK_EVENTS_TABLE_NAME = `emu-${run}-events`; +process.env.USER_CONCURRENCY_TABLE_NAME = `emu-${run}-seats`; +process.env.MAX_CONCURRENT_TASKS_PER_USER = String(MAX_SEATS); + +import { handler as createTask } from '../../src/handlers/create-task'; +import { handler as getTask } from '../../src/handlers/get-task'; +import { handler as reconcileConcurrency } from '../../src/handlers/reconcile-concurrency'; +import { admissionControl, finalizeTask, loadTask, queueTask, transitionTask } from '../../src/handlers/shared/orchestrator'; +import type { TaskRecord } from '../../src/handlers/shared/types'; +import { makeDocClient } from '../../src/handlers/shared/ua'; + +const ddb = makeDocClient(); + +/** A user no other test has written for, so tests need no cleanup between them. */ +const newUser = (): string => `user-${randomUUID()}`; + +/** Submit a repo-less task through the real create-task handler and load its record. */ +async function submitted(userId: string): Promise { + const result = await createTask(apiEvent(userId, { httpMethod: 'POST', body: JSON.stringify({ task_description: 'Summarize the open issues' }) })); + expect(result.statusCode).toBe(201); + return loadTask(JSON.parse(result.body).data.task_id); +} + +/** Take a submitted task as far as RUNNING the way the orchestrator's steps do: admit, hydrate, start. */ +async function running(userId: string): Promise { + const task = await submitted(userId); + expect(await admissionControl(task)).toBe(true); + await transitionTask(task.task_id, TaskStatus.SUBMITTED, TaskStatus.HYDRATING); + await transitionTask(task.task_id, TaskStatus.HYDRATING, TaskStatus.RUNNING); + return task.task_id; +} + +/** The agent's terminal write: RUNNING to COMPLETED. */ +async function complete(taskId: string): Promise { + await transitionTask(taskId, TaskStatus.RUNNING, TaskStatus.FINALIZING); + await transitionTask(taskId, TaskStatus.FINALIZING, TaskStatus.COMPLETED); +} + +/** Seats the user holds according to UserConcurrencyTable. */ +async function seats(userId: string): Promise { + const { Item } = await ddb.send(new GetCommand({ + TableName: process.env.USER_CONCURRENCY_TABLE_NAME, + Key: { user_id: userId }, + ConsistentRead: true, + })); + return Item?.active_count ?? 0; +} + +describe('concurrency seats against the AWS Emulator', () => { + emulatorTables((stack) => { + new TaskTable(stack, 'Tasks', { tableName: process.env.TASK_TABLE_NAME }); + new TaskEventsTable(stack, 'Events', { tableName: process.env.TASK_EVENTS_TABLE_NAME }); + new UserConcurrencyTable(stack, 'Seats', { tableName: process.env.USER_CONCURRENCY_TABLE_NAME }); + }); + + test('racing admissions never exceed the cap, and the losers queue in FIFO order', async () => { + const user = newUser(); + const tasks: TaskRecord[] = []; + for (let i = 0; i < MAX_SEATS + 2; i++) tasks.push(await submitted(user)); + + // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism -- fixed-size fixture, not input-derived + const admitted = await Promise.all(tasks.map((task) => admissionControl(task))); + + expect(admitted.filter(Boolean)).toHaveLength(MAX_SEATS); + expect(await seats(user)).toBe(MAX_SEATS); + + // The orchestrator parks a task that lost admission; GET then ranks it among the user's queued tasks. + const losers = tasks.filter((_, i) => !admitted[i]); + for (const task of losers) expect(await queueTask(task)).toBe(true); + const positions: number[] = []; + for (const task of losers) { + const result = await getTask(apiEvent(user, { pathParameters: { task_id: task.task_id } })); + positions.push(JSON.parse(result.body).data.queue_position); + } + const fifo = losers.map((task) => `${task.created_at}#${task.task_id}`); + expect(positions).toEqual(fifo.map((key) => [...fifo].sort().indexOf(key) + 1)); + expect(await seats(user)).toBe(MAX_SEATS); + }); + + test('finalizing a completed task gives back exactly its own seat', async () => { + const user = newUser(); + const done = await running(user); + await running(user); + expect(await seats(user)).toBe(2); + + await complete(done); + await finalizeTask(done, { attempts: 1 }, user); + + expect(await seats(user)).toBe(1); + }); + + test('the concurrency reconciler repairs a leaked seat from the real index', async () => { + const user = newUser(); + await running(user); + // A seat with no live task behind it, as a finalize step that never ran leaves. + expect(await admissionControl({ user_id: user } as TaskRecord)).toBe(true); + expect(await seats(user)).toBe(2); + + await reconcileConcurrency(); + + expect(await seats(user)).toBe(1); + }); + + // KNOWN FAILURES: executable witnesses for two seat defects on main, reproduced + // here with real conditional writes rather than mocked `send` calls. Kept as + // `test.failing` so the suite stays green and flags the day the fix lands (open + // PR #1009 addresses both). Each was run once as a plain `test` to confirm it + // fails on its last assertion and not on setup; the passing tests above cover + // the same setup. + test.failing('#1003: a replayed finalize step does not release a second seat', async () => { + const user = newUser(); + const done = await running(user); + await running(user); + await complete(done); + + // Durable execution re-runs a step whose result it did not record. + await finalizeTask(done, { attempts: 1 }, user); + await finalizeTask(done, { attempts: 1 }, user); + + expect(await seats(user)).toBe(1); + }); + + // No issue reports this one: reconcile-concurrency counts four hard-coded + // statuses, while the design and ACTIVE_STATUSES say a task awaiting approval + // holds its seat. + test.failing('the concurrency reconciler keeps the seat of a task awaiting approval', async () => { + const user = newUser(); + const paused = await running(user); + // The Python agent is the only writer of this status. It sets `status` and + // leaves `status_created_at` alone, so this does the same. + await ddb.send(new UpdateCommand({ + TableName: process.env.TASK_TABLE_NAME, + Key: { task_id: paused }, + UpdateExpression: 'SET #status = :awaiting', + ExpressionAttributeNames: { '#status': 'status' }, + ExpressionAttributeValues: { ':awaiting': TaskStatus.AWAITING_APPROVAL }, + })); + + await reconcileConcurrency(); + + expect(await seats(user)).toBe(1); + }); +}); diff --git a/cdk/test/emulator/harness.ts b/cdk/test/emulator/harness.ts new file mode 100644 index 000000000..e54c3895a --- /dev/null +++ b/cdk/test/emulator/harness.ts @@ -0,0 +1,125 @@ +/** + * 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. + */ + +/** + * Shared setup for the emulator-backed handler tests (ADR-013 Tier 2a). + * + * These suites run real handler code in-process and let its AWS calls go over + * the wire to an AWS Emulator (https://github.com/aws/aws-emulator). Nothing + * here configures an endpoint: the SDK clients the handlers already build pick + * up AWS_ENDPOINT_URL, AWS_REGION and the emulator's credentials file from the + * environment, and Node trusts its certificate through NODE_EXTRA_CA_CERTS. + * + * The files are named `*.emulator.ts`, which the unit configuration does not + * match. They run only through `jest.emulator.config.js` + * (`mise run test:integration`), which refuses to start unless that + * environment is the emulator's and the emulator answers. + * + * The emulator keeps state in memory and has no reset route. Each test file + * therefore names its tables uniquely (so files can share one instance, run in + * parallel and be re-run without a restart), and each test writes under a user + * id of its own (so tests need no cleanup between them). + */ + +import { CreateTableCommand, DeleteTableCommand, DynamoDBClient, waitUntilTableExists } from '@aws-sdk/client-dynamodb'; +import { App, Stack } from 'aws-cdk-lib'; +import { Template } from 'aws-cdk-lib/assertions'; +import type { APIGatewayProxyEvent } from 'aws-lambda'; + +/** Timeout for table setup (ms). The emulator alone holds a new table in CREATING for 3 s; Jest's default is 5 s. */ +const SETUP_TIMEOUT_MS = 30_000; + +/** How long to wait for a new table to become ACTIVE (seconds). Shorter than the hook, so its own error is the one shown. */ +const TABLE_WAIT_SECONDS = 20; + +/** + * Give the enclosing `describe` the DynamoDB tables that `declare` adds to a + * stack: created on the emulator before its tests and deleted after them. + * + * The CreateTable inputs are read from the synthesized template, so key schema + * and indexes are the constructs' own. A handler that queries an index its + * construct no longer declares fails here instead of after a deploy. + * + * Streams and point-in-time recovery are not carried over. Neither is TTL, on + * purpose: the emulator deletes an expired item within a second where AWS takes + * up to days, so with TTL on, code that forgets to compare `ttl` with the clock + * looks correct here. + * @param declare - instantiates the table constructs under test, each with an explicit `tableName`. + * @param seed - writes the rows every test in the file needs, once the tables are ACTIVE. + */ +export function emulatorTables(declare: (stack: Stack) => void, seed?: () => Promise): void { + let ddb: DynamoDBClient | undefined; + const created: string[] = []; + + beforeAll(async () => { + const stack = new Stack(new App(), 'EmulatorTables'); + declare(stack); + ddb = new DynamoDBClient({}); + for (const [logicalId, { Properties: table }] of Object.entries(Template.fromStack(stack).findResources('AWS::DynamoDB::Table'))) { + if (typeof table.TableName !== 'string') { + throw new Error(`Table ${logicalId} has no literal tableName; pass one to its construct so the handler environment can name it.`); + } + await ddb.send(new CreateTableCommand({ + TableName: table.TableName, + AttributeDefinitions: table.AttributeDefinitions, + KeySchema: table.KeySchema, + GlobalSecondaryIndexes: table.GlobalSecondaryIndexes, + BillingMode: table.BillingMode, + })); + created.push(table.TableName); + } + // Create them all before waiting: the CREATING window then costs one wait, not one per table. + for (const TableName of created) { + await waitUntilTableExists({ client: ddb, maxWaitTime: TABLE_WAIT_SECONDS, minDelay: 1 }, { TableName }); + } + await seed?.(); + }, SETUP_TIMEOUT_MS); + + afterAll(async () => { + for (const TableName of created) await ddb?.send(new DeleteTableCommand({ TableName })); + ddb?.destroy(); + }); +} + +/** + * An API Gateway proxy event as the Cognito authorizer would deliver it. + * @param userId - the authenticated caller (`claims.sub`). + * @param overrides - request parts the call under test needs (body, headers, path or query parameters). + * @returns the event. + */ +export function apiEvent(userId: string, overrides: Partial = {}): APIGatewayProxyEvent { + return { + body: null, + headers: {}, + multiValueHeaders: {}, + httpMethod: 'GET', + isBase64Encoded: false, + path: '/v1/tasks', + pathParameters: null, + queryStringParameters: null, + multiValueQueryStringParameters: null, + stageVariables: null, + resource: '/tasks', + requestContext: { + authorizer: { claims: { sub: userId } }, + identity: { sourceIp: '127.0.0.1', userAgent: 'jest' }, + } as unknown as APIGatewayProxyEvent['requestContext'], + ...overrides, + }; +} diff --git a/cdk/test/emulator/task-api.emulator.ts b/cdk/test/emulator/task-api.emulator.ts new file mode 100644 index 000000000..24c0d4ae4 --- /dev/null +++ b/cdk/test/emulator/task-api.emulator.ts @@ -0,0 +1,197 @@ +/** + * 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. + */ + +/** + * Task API lifecycle against the AWS Emulator (ADR-013 Tier 2a). + * + * The real handler entry points run in-process; only their AWS calls leave the + * process, to an emulator whose tables are created from the CDK constructs. + * Nothing is mocked, so these tests see what `jest.mock('@aws-sdk/...')` tests + * cannot: index key order, `Limit` before `FilterExpression`, and the state a + * sequence of real conditional writes leaves behind. + * + * Runs only through `jest.emulator.config.js` (see ./harness). + */ + +import { randomUUID } from 'node:crypto'; +import { PutCommand } from '@aws-sdk/lib-dynamodb'; +import type { APIGatewayProxyResult } from 'aws-lambda'; +import { apiEvent, emulatorTables } from './harness'; +import { RepoTable } from '../../src/constructs/repo-table'; +import { TaskEventsTable } from '../../src/constructs/task-events-table'; +import { TaskTable } from '../../src/constructs/task-table'; + +// Handlers read their table names at module load, so the environment is set +// before any handler is imported. Names are unique to this file's run. +const run = randomUUID().slice(0, 8); +process.env.TASK_TABLE_NAME = `emu-${run}-tasks`; +process.env.TASK_EVENTS_TABLE_NAME = `emu-${run}-events`; +process.env.REPO_TABLE_NAME = `emu-${run}-repos`; + +import { handler as cancelTask } from '../../src/handlers/cancel-task'; +import { handler as createTask } from '../../src/handlers/create-task'; +import { handler as getTask } from '../../src/handlers/get-task'; +import { handler as getTaskEvents } from '../../src/handlers/get-task-events'; +import { handler as listTasks } from '../../src/handlers/list-tasks'; +import { makeDocClient } from '../../src/handlers/shared/ua'; + +const REPO = 'acme/widgets'; +const CONCURRENT_CANCELS = 8; + +/** A user no other test has written for, so tests need no cleanup between them. */ +const newUser = (): string => `user-${randomUUID()}`; +const data = (result: APIGatewayProxyResult) => JSON.parse(result.body).data; +const byId = (taskId: string) => ({ pathParameters: { task_id: taskId } }); +const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + +/** POST /v1/tasks through the real handler. Returns the HTTP result. */ +function submit(userId: string, idempotencyKey?: string): Promise { + return createTask(apiEvent(userId, { + httpMethod: 'POST', + headers: idempotencyKey ? { 'Idempotency-Key': idempotencyKey } : {}, + body: JSON.stringify({ repo: REPO, workflow_ref: 'coding/new-task-v1', task_description: 'Add a health check endpoint' }), + })); +} + +/** GET /v1/tasks through the real handler. Returns the parsed body. */ +async function list(userId: string, query?: Record) { + const result = await listTasks(apiEvent(userId, { queryStringParameters: query ?? null })); + expect(result.statusCode).toBe(200); + return JSON.parse(result.body) as { data: { task_id: string; status: string }[]; pagination: { next_token: string | null; has_more: boolean } }; +} + +describe('task API against the AWS Emulator', () => { + emulatorTables((stack) => { + new TaskTable(stack, 'Tasks', { tableName: process.env.TASK_TABLE_NAME }); + new TaskEventsTable(stack, 'Events', { tableName: process.env.TASK_EVENTS_TABLE_NAME }); + new RepoTable(stack, 'Repos', { tableName: process.env.REPO_TABLE_NAME }); + }, () => { + // The row a Blueprint writes at deploy time; create-task gates on it. + const now = new Date().toISOString(); + return makeDocClient().send(new PutCommand({ + TableName: process.env.REPO_TABLE_NAME, + Item: { repo: REPO, status: 'active', onboarded_at: now, updated_at: now }, + })); + }); + + test('create, get, list, cancel: one task through every handler', async () => { + const user = newUser(); + + const created = await submit(user); + expect(created.statusCode).toBe(201); + const taskId: string = data(created).task_id; + expect(data(created)).toMatchObject({ status: 'SUBMITTED', repo: REPO }); + + expect(data(await getTask(apiEvent(user, byId(taskId))))).toMatchObject({ task_id: taskId, status: 'SUBMITTED' }); + expect((await getTask(apiEvent(newUser(), byId(taskId)))).statusCode).toBe(403); + expect((await list(user)).data.map((t) => t.task_id)).toEqual([taskId]); + + const cancelled = await cancelTask(apiEvent(user, byId(taskId))); + expect(cancelled.statusCode).toBe(200); + expect((await cancelTask(apiEvent(user, byId(taskId)))).statusCode).toBe(409); + + // The cancel rewrote the index sort key, so the task has moved between status filters. + expect(data(await getTask(apiEvent(user, byId(taskId)))).status).toBe('CANCELLED'); + expect((await list(user, { status: 'CANCELLED' })).data.map((t) => t.task_id)).toEqual([taskId]); + expect((await list(user, { status: 'SUBMITTED' })).data).toEqual([]); + + const events = data(await getTaskEvents(apiEvent(user, byId(taskId)))); + expect(events.map((e: { event_type: string }) => e.event_type)).toEqual(['task_created', 'task_cancelled']); + }); + + test('replaying an Idempotency-Key returns the original task and creates nothing', async () => { + const user = newUser(); + const key = `key-${randomUUID()}`; + + const first = await submit(user, key); + const replay = await submit(user, key); + + expect(first.statusCode).toBe(201); + expect(replay.statusCode).toBe(200); + expect(replay.headers).toMatchObject({ 'Idempotent-Replay': 'true' }); + expect(data(replay).task_id).toBe(data(first).task_id); + expect((await list(user)).data).toHaveLength(1); + + // The key is global, not per user: someone else reusing it is refused, not handed the task. + expect((await submit(newUser(), key)).statusCode).toBe(409); + }); + + // An outcome test: a loser is refused either by cancel-task's read of the task or + // by its conditional write, depending on timing, and this cannot tell which. The + // test that fails when a condition is missing is 'racing admissions' in + // concurrency-seats.emulator.ts. + test('concurrent cancels: one succeeds, the rest are refused, one event is recorded', async () => { + const user = newUser(); + const taskId: string = data(await submit(user)).task_id; + + // eslint-disable-next-line @cdklabs/promiseall-no-unbounded-parallelism -- fixed-size fixture, not input-derived + const results = await Promise.all(Array.from({ length: CONCURRENT_CANCELS }, () => cancelTask(apiEvent(user, byId(taskId))))); + + expect(results.map((r) => r.statusCode).sort()).toEqual([200, ...Array(CONCURRENT_CANCELS - 1).fill(409)]); + const events = data(await getTaskEvents(apiEvent(user, byId(taskId)))); + expect(events.filter((e: { event_type: string }) => e.event_type === 'task_cancelled')).toHaveLength(1); + }); + + test('list pages through the index without losing or repeating a task', async () => { + const user = newUser(); + const submitted: string[] = []; + for (let i = 0; i < 5; i++) submitted.push(data(await submit(user)).task_id); + + const seen: string[] = []; + let nextToken: string | null = null; + let pages = 0; + do { + const page = await list(user, { limit: '2', ...(nextToken && { next_token: nextToken }) }); + seen.push(...page.data.map((t) => t.task_id)); + nextToken = page.pagination.next_token; + pages++; + } while (nextToken); + + expect(pages).toBe(3); + expect([...seen].sort()).toEqual([...submitted].sort()); + }); + + // KNOWN FAILURES: executable witnesses for #51, which was found by hand on a + // deployed stack. `list-tasks` queries UserStatusIndex, whose sort key is + // `{status}#{timestamp}`, so results come back grouped by status rather than + // newest first, and a status filter is applied after `Limit` has already cut + // the page (the short page does carry a next_token, which `bgagent list` does + // not follow). Kept as `test.failing` so the suite stays green and flags the + // day the handler is fixed. Each was run once as a plain `test` to confirm it + // fails on its last assertion and not on setup. + test.failing('#51: list returns the newest task first (API_CONTRACT.md: "ordered by created_at descending")', async () => { + const user = newUser(); + const older: string = data(await submit(user)).task_id; + await pause(5); + const newer: string = data(await submit(user)).task_id; + await cancelTask(apiEvent(user, byId(newer))); + + expect((await list(user)).data.map((t) => t.task_id)).toEqual([newer, older]); + }); + + test.failing('#51: a status filter returns the matching task when it fits the page', async () => { + const user = newUser(); + const first: string = data(await submit(user)).task_id; + await submit(user); + await submit(user); + await cancelTask(apiEvent(user, byId(first))); + + expect((await list(user, { status: 'CANCELLED', limit: '2' })).data.map((t) => t.task_id)).toEqual([first]); + }); +}); diff --git a/cdk/test/emulator/trace-api-shim.ts b/cdk/test/emulator/trace-api-shim.ts new file mode 100644 index 000000000..23dd36ae4 --- /dev/null +++ b/cdk/test/emulator/trace-api-shim.ts @@ -0,0 +1,71 @@ +/** + * 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. + */ + +/** + * Stand-in for API Gateway in front of the real `get-trace-url` Lambda handler. + * + * Started by `agent/tests_emulator/test_trace_round_trip.py` (through `tsx`) so + * that pytest and the real `bgagent` CLI can reach the handler over HTTP. It + * only translates an HTTP request into the proxy event API Gateway would build + * and writes the handler's result back; every decision is the handler's own. + * + * API Gateway's Cognito authorizer would put the verified caller in + * `requestContext.authorizer.claims.sub`. Here the caller is whoever the + * `X-API-Key` header names — the header the CLI sends for `BGAGENT_API_KEY`. + * + * Prints `{"port": }` on stdout once it is listening. + */ + +import { createServer } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { handler } from '../../src/handlers/get-trace-url'; + +// The handler makes real SDK calls and trusts whatever caller the header names, +// so this serves it only when those calls are bound for an emulator on loopback. +if (!/^https:\/\/127\.0\.0\.1:\d+$/.test(process.env.AWS_ENDPOINT_URL ?? '')) { + throw new Error('trace-api-shim serves only against an AWS Emulator (AWS_ENDPOINT_URL=https://127.0.0.1:).'); +} + +const TRACE_ROUTE = /^\/tasks\/([^/]+)\/trace$/; + +const server = createServer((req, res) => { + const match = TRACE_ROUTE.exec(new URL(req.url ?? '/', 'http://shim').pathname); + if (req.method !== 'GET' || !match) { + res.writeHead(404).end(); + return; + } + const caller = req.headers['x-api-key']; + const event = { + httpMethod: 'GET', + path: req.url, + headers: req.headers, + pathParameters: { task_id: decodeURIComponent(match[1]) }, + requestContext: { + authorizer: typeof caller === 'string' ? { claims: { sub: caller } } : undefined, + }, + }; + handler(event as never).then( + (result) => res.writeHead(result.statusCode, result.headers as Record).end(result.body), + (err: unknown) => res.writeHead(500).end(String(err)), + ); +}); + +server.listen(0, '127.0.0.1', () => { + process.stdout.write(`${JSON.stringify({ port: (server.address() as AddressInfo).port })}\n`); +}); diff --git a/cli/jest.emulator.config.js b/cli/jest.emulator.config.js new file mode 100644 index 000000000..4bc710f1d --- /dev/null +++ b/cli/jest.emulator.config.js @@ -0,0 +1,2 @@ +// Emulator-backed CLI tests (test/emulator/*.emulator.ts). Run with `mise run test:integration`. +module.exports = require('../scripts/aws-emulator/jest-config')(require('./package.json').jest); diff --git a/cli/test/emulator/cognito-sign-in.emulator.ts b/cli/test/emulator/cognito-sign-in.emulator.ts new file mode 100644 index 000000000..f4d107bff --- /dev/null +++ b/cli/test/emulator/cognito-sign-in.emulator.ts @@ -0,0 +1,242 @@ +/** + * 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. + */ + +/** + * The CLI's real sign-in path against an AWS Emulator + * (https://github.com/aws/aws-emulator) instead of a mocked SDK (ADR-013 + * Tier 2a). + * + * Nothing here is mocked. `bgagent configure --stack-name` reads a real + * CloudFormation stack's outputs, and `login` / `getAuthToken` / + * `changePassword` talk to the Cognito user pool that stack created, so the + * assertions are about what the service answers (JWT claims, error names, the + * pool's password policy) rather than about what a mock was told to return. + * + * Named `*.emulator.ts`, which the unit configuration does not match. It runs + * only through `jest.emulator.config.js` (`mise run test:integration`), which + * refuses to start unless the AWS environment is the emulator's and the + * emulator answers. + */ + +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { + CloudFormationClient, + CreateStackCommand, + DeleteStackCommand, + DescribeStacksCommand, + type Stack, +} from '@aws-sdk/client-cloudformation'; +import { changePassword, getAuthToken, login } from '../../src/auth'; +import { adminInviteUser, adminResetPassword, resolveCognitoAdminContext } from '../../src/cognito-admin'; +import { makeConfigureCommand } from '../../src/commands/configure'; +import { loadConfig, loadCredentials, saveCredentials } from '../../src/config'; +import { makeClient } from '../../src/ua'; + +const REGION = process.env.AWS_REGION ?? 'us-east-1'; +const SETUP_TIMEOUT_MS = 30_000; +/** Shorter than the hook, so a stack that never settles reports itself instead of a bare hook timeout. */ +const STACK_WAIT_MS = 20_000; +const POLL_INTERVAL_MS = 50; + +const TEMP_PASSWORD = 'T3mp$trongPass!'; +const PASSWORD = 'N3w$trongPass!'; +const NEXT_PASSWORD = 'An0ther$trongPass!'; + +/** + * The two resources the sign-in path needs, shaped like the ones + * `cdk/src/constructs/task-api.ts` synthesizes (email as the username, the + * 12-character policy, password + refresh auth flows, no client secret), with + * the outputs `bgagent configure --stack-name` reads. + */ +const STACK_TEMPLATE = { + AWSTemplateFormatVersion: '2010-09-09', + Resources: { + UserPool: { + Type: 'AWS::Cognito::UserPool', + Properties: { + UsernameAttributes: ['email'], + AutoVerifiedAttributes: ['email'], + AdminCreateUserConfig: { AllowAdminCreateUserOnly: true }, + Policies: { + PasswordPolicy: { + MinimumLength: 12, + RequireLowercase: true, + RequireUppercase: true, + RequireNumbers: true, + RequireSymbols: true, + }, + }, + }, + }, + AppClient: { + Type: 'AWS::Cognito::UserPoolClient', + Properties: { + UserPoolId: { Ref: 'UserPool' }, + ExplicitAuthFlows: ['ALLOW_USER_PASSWORD_AUTH', 'ALLOW_USER_SRP_AUTH', 'ALLOW_REFRESH_TOKEN_AUTH'], + GenerateSecret: false, + }, + }, + }, + Outputs: { + ApiUrl: { Value: 'https://api.invalid/v1/' }, + UserPoolId: { Value: { Ref: 'UserPool' } }, + AppClientId: { Value: { Ref: 'AppClient' } }, + }, +}; + +/** Claims of an ID token; the signature is not checked (the CLI never checks it either). */ +function idTokenClaims(idToken: string): Record { + const [, payload] = idToken.split('.'); + return JSON.parse(Buffer.from(payload, 'base64url').toString('utf-8')) as Record; +} + +async function settledStack(cloudFormation: CloudFormationClient, stackName: string): Promise { + const deadline = Date.now() + STACK_WAIT_MS; + while (Date.now() < deadline) { + const stack = (await cloudFormation.send(new DescribeStacksCommand({ StackName: stackName }))).Stacks?.[0]; + if (stack?.StackStatus && !stack.StackStatus.endsWith('_IN_PROGRESS')) return stack; + await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS)); + } + throw new Error(`Fixture stack ${stackName} was still in progress after ${STACK_WAIT_MS} ms`); +} + +describe('bgagent sign-in against an AWS Emulator', () => { + const stackName = `bgagent-cli-emulator-${Date.now().toString(36)}`; + let cloudFormation: CloudFormationClient; + let stackOutputs: Map; + let configDir: string; + let userCount = 0; + + /** A fresh user in FORCE_CHANGE_PASSWORD, as `bgagent admin invite-user` leaves it. */ + async function invitedUser(): Promise { + userCount += 1; + const email = `user-${userCount}@example.com`; + await adminInviteUser(await resolveCognitoAdminContext({ region: REGION, stackName }), email, TEMP_PASSWORD); + return email; + } + + /** A fresh user with a permanent password, as `bgagent admin reset-password` leaves it. */ + async function confirmedUser(): Promise { + const email = await invitedUser(); + await adminResetPassword(await resolveCognitoAdminContext({ region: REGION, stackName }), email, PASSWORD); + return email; + } + + beforeAll(async () => { + // First, before any CLI code runs: the CLI keeps its config and tokens under + // ~/.bgagent, and this suite must never read or replace the developer's own. + configDir = fs.mkdtempSync(path.join(os.tmpdir(), 'bgagent-emulator-')); + process.env.BGAGENT_CONFIG_DIR = configDir; + + cloudFormation = makeClient(CloudFormationClient, { region: REGION }); + await cloudFormation.send(new CreateStackCommand({ StackName: stackName, TemplateBody: JSON.stringify(STACK_TEMPLATE) })); + const stack = await settledStack(cloudFormation, stackName); + if (stack.StackStatus !== 'CREATE_COMPLETE') { + throw new Error(`Fixture stack ${stackName} ended in ${stack.StackStatus}: ${stack.StackStatusReason ?? 'no reason given'}`); + } + stackOutputs = new Map((stack.Outputs ?? []).map((output) => [output.OutputKey, output.OutputValue])); + + const log = jest.spyOn(console, 'log').mockImplementation(() => undefined); + try { + await makeConfigureCommand().parseAsync(['node', 'configure', '--stack-name', stackName, '--region', REGION]); + } finally { + log.mockRestore(); + } + }, SETUP_TIMEOUT_MS); + + afterAll(async () => { + if (configDir) fs.rmSync(configDir, { recursive: true, force: true }); + await cloudFormation?.send(new DeleteStackCommand({ StackName: stackName })); + }, SETUP_TIMEOUT_MS); + + /** Token cache inside the suite's own directory (never derived from the CLI's default). */ + const credentialsFile = (): string => path.join(configDir, 'credentials.json'); + + beforeEach(() => { + fs.rmSync(credentialsFile(), { force: true }); + }); + + test('configure --stack-name stores the pool and client the stack created', () => { + expect(stackOutputs.get('UserPoolId')).toMatch(new RegExp(`^${REGION}_`)); + expect(loadConfig()).toEqual({ + api_url: 'https://api.invalid/v1/', + region: REGION, + user_pool_id: stackOutputs.get('UserPoolId'), + client_id: stackOutputs.get('AppClientId'), + stack_name: stackName, + }); + }); + + test('an invited user is challenged for a new password and nothing is cached', async () => { + const email = await invitedUser(); + + await expect(login(email, TEMP_PASSWORD)).rejects.toThrow(/requires a new password on first login/); + + expect(loadCredentials()).toBeNull(); + }); + + // Emulator 1.0.385 answers 501 NotImplemented for RespondToAuthChallenge with + // NEW_PASSWORD_REQUIRED, so the rotation itself cannot run yet (upstream: + // aws/aws-emulator issues/things-that-do-not-work/ + // 20261029T182116Z-cognito-idp-mfa-challenge-state-machine-mfa-setup.md). The + // body is the test we want; when an emulator release makes it pass, jest + // reports this case as failed and `.failing` can simply be dropped. + test.failing('first sign-in rotates the temporary password (blocked by an emulator gap)', async () => { + const email = await invitedUser(); + + await login(email, TEMP_PASSWORD, () => Promise.resolve(PASSWORD)); + + expect(loadCredentials()).not.toBeNull(); + }); + + test('login caches an ID token for the user, and an expired cache is refreshed', async () => { + const email = await confirmedUser(); + + await login(email, PASSWORD); + + const cached = loadCredentials(); + expect(fs.statSync(credentialsFile()).mode % 0o1000).toBe(0o600); + const claims = idTokenClaims(cached!.id_token); + expect(claims).toMatchObject({ email, token_use: 'id', aud: loadConfig().client_id }); + expect(claims.iss).toBe(`https://cognito-idp.${REGION}.amazonaws.com/${loadConfig().user_pool_id}`); + await expect(getAuthToken()).resolves.toBe(cached!.id_token); + + saveCredentials({ ...cached!, token_expiry: new Date(0).toISOString() }); + const refreshed = idTokenClaims(await getAuthToken()); + + expect(refreshed).toMatchObject({ email, sub: claims.sub }); + expect(loadCredentials()!.refresh_token).toBe(cached!.refresh_token); + expect(Date.parse(loadCredentials()!.token_expiry)).toBeGreaterThan(Date.now()); + }); + + test('change-password verifies the current password, applies the pool policy, then rotates', async () => { + const email = await confirmedUser(); + await login(email, PASSWORD); + + await expect(changePassword('Wr0ng$trongPass!', NEXT_PASSWORD)).rejects.toThrow('Current password is incorrect.'); + // The CLI's own prefix; what follows is the service's wording, which is not asserted. + await expect(changePassword(PASSWORD, 'weak')).rejects.toThrow(/^New password rejected: /); + await changePassword(PASSWORD, NEXT_PASSWORD); + + await expect(login(email, PASSWORD)).rejects.toThrow(/incorrect password/); + await expect(login(email, NEXT_PASSWORD)).resolves.toBeUndefined(); + }); +}); diff --git a/knip.json b/knip.json index b4293f900..313e9ab9f 100644 --- a/knip.json +++ b/knip.json @@ -13,14 +13,18 @@ }, "workspaces": { ".": { - "entry": ["scripts/*.{js,mjs,ts}"] + "entry": ["scripts/*.{js,mjs,ts}", "scripts/aws-emulator/jest-global-setup.js", "scripts/aws-emulator/loopback-only.cjs"] }, "cdk": { - "entry": ["src/main.ts!", "src/handlers/*.ts!", "scripts/*.ts", "test/integ/integ.*.ts"], + "entry": [ + "src/main.ts!", "src/handlers/*.ts!", "scripts/*.ts", "test/integ/integ.*.ts", + "jest.emulator.config.js", "test/emulator/*.emulator.ts", "test/emulator/trace-api-shim.ts" + ], "project": ["src/**/*.ts!", "scripts/**/*.ts", "test/**/*.ts"], "ignoreDependencies": ["tsx", "@aws-cdk/integ-runner"] }, "cli": { + "entry": ["jest.emulator.config.js", "test/emulator/*.emulator.ts"], "project": ["src/**/*.ts!", "test/**/*.ts"] }, "docs": { diff --git a/mise.toml b/mise.toml index fd101a42f..5b18d33c4 100644 --- a/mise.toml +++ b/mise.toml @@ -205,6 +205,44 @@ run = [ description = "Fast tier without a test run: the `lint` and `drift-prevention` tasks. Not check-only: drift-prevention fixes trailing whitespace and missing final newlines (and then fails) and regenerates the command stubs" depends = [":lint", ":drift-prevention"] +################## +#### EMULATOR #### +################## + +# Emulator-backed integration tests (ADR-013 Tier 2a): ABCA's real handler, CLI and agent code +# against a local AWS Emulator (https://github.com/aws/aws-emulator). Needs Docker and no AWS +# account. Nothing here is reachable from `mise run build`. The emulator version is pinned once, +# in scripts/aws-emulator/Dockerfile. See docs/research/aws-emulator-local-tests.md. + +[tasks."emulator:up"] +description = "Start a fresh AWS Emulator on 127.0.0.1 (builds the pinned, signature-verified image on first use)" +run = "scripts/aws-emulator/emulator.sh up" + +[tasks."emulator:down"] +description = "Stop the AWS Emulator (emulated state is in memory and is discarded)" +run = "scripts/aws-emulator/emulator.sh down" + +# Arguments after `--` are the command, for one file while iterating. Run from the repository +# root (these are root tasks); the parentheses keep the shell there: +# mise run emulator:run -- yarn --cwd cdk jest --config jest.emulator.config.js task-api +# (cd agent && ../scripts/aws-emulator/emulator.sh run uv run pytest --no-cov tests_emulator/test_secrets.py) +# For programs that use an AWS SDK. Not for AWS CLI v1, which ignores the endpoint for some services. +[tasks."emulator:run"] +description = "Run a command against the running emulator with the AWS environment replaced by the emulator's (pass it after --)" +run = "scripts/aws-emulator/emulator.sh run" + +# On failure the list stops and the emulator stays up for inspection (`docker logs`); the next +# `emulator:up` replaces it, and it is started with an idle timeout of one hour. +[tasks."test:integration"] +description = "Tier 2a: emulator-backed integration tests (cdk, cli, agent) against a fresh AWS Emulator" +run = [ + { task = "emulator:up" }, + "scripts/aws-emulator/emulator.sh run yarn --cwd cdk jest --config jest.emulator.config.js", + "scripts/aws-emulator/emulator.sh run yarn --cwd cli jest --config jest.emulator.config.js", + "cd agent && ../scripts/aws-emulator/emulator.sh run uv run pytest --no-cov tests_emulator", + { task = "emulator:down" }, +] + ################## #### SECURITY #### ################## diff --git a/scripts/aws-emulator/Dockerfile b/scripts/aws-emulator/Dockerfile new file mode 100644 index 000000000..16847bb47 --- /dev/null +++ b/scripts/aws-emulator/Dockerfile @@ -0,0 +1,62 @@ +# AWS Emulator (https://github.com/aws/aws-emulator) for the local/CI integration tier (ADR-013 Tier 2a). +# Test tooling only: never part of a deployed stack or of the agent image. +# +# AWS publishes no prebuilt image, so this installs the signed Linux package. It differs from the +# user guide's five-line Dockerfile in three ways: +# - the version is pinned (the guide installs `latest`), +# - the package is verified against its detached signature and the AWS publishing key, pinned by +# fingerprint, before it is installed (the guide's `rpm -i` verifies nothing), +# - telemetry is off in the image itself, so no caller can forget to disable it. +# +# AWS_EMULATOR_VERSION is the ONE pin for the repository: scripts/aws-emulator/emulator.sh reads it +# from this line, and CI builds this same file. Bump it here and nowhere else. +# Use the three-part version from https://github.com/aws/aws-emulator/releases (versions.json lists +# a fourth component, e.g. 1.0.385.1, that the package file names do not carry). +ARG AWS_EMULATOR_VERSION=1.0.385 + +# Pinned by digest like every other external image in this repository (see agent/Dockerfile). +# The digest is a multi-platform index (linux/amd64 + linux/arm64). To bump: +# docker buildx imagetools inspect public.ecr.aws/amazonlinux/amazonlinux:2023-minimal +FROM public.ecr.aws/amazonlinux/amazonlinux:2023-minimal@sha256:158a9044f9dc0777f098b76c8b54346f6ed4560b9a6a416dec7a5ba3bc483af4 AS base + +FROM base AS verified +ARG AWS_EMULATOR_VERSION +ARG TARGETARCH +# Signature check, fail-closed. +# +# This base image ships gnupg2-minimal (no gpg-agent, no gpgv), so `gpg --import` as written in the +# user guide fails here. Dearmor the key into a keyring file and verify against that instead. +# +# VALIDSIG's last field is the primary-key fingerprint of the key that made the signature, so the +# grep asserts both "the signature is good" and "it was made by the key we pinned", whatever else +# current.asc may contain after a key rotation. A rotation therefore fails the build until the +# fingerprint is updated from the user guide ("To verify the package before you install it"). +RUN set -eu; \ + case "$TARGETARCH" in \ + amd64) arch=x86_64 ;; \ + arm64) arch=aarch64 ;; \ + *) echo "unsupported architecture: $TARGETARCH" >&2; exit 1 ;; \ + esac; \ + url="https://downloads.aws.com/aws-emulator/packages/aws-emulator/LTS/aws-emulator-${AWS_EMULATOR_VERSION}-1-${arch}.rpm"; \ + curl -fsSL --retry 3 -o /tmp/aws-emulator.rpm "$url"; \ + curl -fsSL --retry 3 -o /tmp/aws-emulator.rpm.sig "$url.sig"; \ + curl -fsSL --retry 3 -o /tmp/aws-publishing.asc https://downloads.aws.com/keys/gpg/current.asc; \ + export GNUPGHOME=/tmp/gnupg; mkdir -m 700 "$GNUPGHOME"; \ + gpg --batch --no-autostart --dearmor < /tmp/aws-publishing.asc > /tmp/aws-publishing.gpg; \ + gpg --batch --no-autostart --no-default-keyring --keyring /tmp/aws-publishing.gpg \ + --status-fd 1 --verify /tmp/aws-emulator.rpm.sig /tmp/aws-emulator.rpm \ + > /tmp/verify.status 2> /tmp/verify.log \ + || { cat /tmp/verify.log /tmp/verify.status >&2; exit 1; }; \ + grep -Eq '^\[GNUPG:\] VALIDSIG .* 98BCF336A3BE53B734E967C52E5BF49BD940F624$' /tmp/verify.status \ + || { echo "package is not signed by the pinned AWS publishing key" >&2; cat /tmp/verify.status >&2; exit 1; } + +FROM base +# Bind-mount the verified package instead of ADD/COPY so the ~160 MB archive is not kept as a layer. +RUN --mount=type=bind,from=verified,source=/tmp/aws-emulator.rpm,target=/tmp/aws-emulator.rpm \ + rpm -i /tmp/aws-emulator.rpm && mkdir -p /home/emulator && chown 1000 /home/emulator +USER 1000 +ENV HOME=/home/emulator \ + EMULATOR_TELEMETRY=off +EXPOSE 9297 +# -b 0.0.0.0 so Docker can forward the port; emulator.sh publishes it on 127.0.0.1 only. +ENTRYPOINT ["aws-emulator", "-b", "0.0.0.0", "--telemetry", "off"] diff --git a/scripts/aws-emulator/emulator.sh b/scripts/aws-emulator/emulator.sh new file mode 100755 index 000000000..240dcba55 --- /dev/null +++ b/scripts/aws-emulator/emulator.sh @@ -0,0 +1,133 @@ +#!/usr/bin/env bash +# AWS Emulator lifecycle and guarded command runner for the local/CI integration tier +# (ADR-013 Tier 2a). Driven by the mise tasks emulator:up, emulator:down, emulator:run and +# test:integration; nothing here is reachable from `mise run build`. +# +# emulator.sh up build the pinned image if missing, start a FRESH emulator, wait for health +# emulator.sh down stop it (all emulated state is in memory, so this is also "reset") +# emulator.sh run run with the AWS environment replaced by the emulator's +# +# `run` is for programs that use an AWS SDK. Do not use it with AWS CLI v1: that CLI forces a real +# AWS endpoint for sqs, rds, docdb, neptune and health whatever AWS_ENDPOINT_URL says. +# +# Environment: +# ABCA_EMULATOR_PORT port on 127.0.0.1. Default: derived from the checkout path, so two worktrees +# can run the tier at the same time without stopping each other's emulator. +# ABCA_EMULATOR_HOME where the emulator keeps its per-run credentials and certificate. Default is +# under the user cache directory. It is deliberately OUTSIDE the repository: the +# agent image asset fingerprints the repository root, and these files change on +# every start. +# ABCA_EMULATOR_VERSION try another emulator release for this invocation only (default: the pin). +# CDK_DOCKER container engine (default docker), same convention as cdk/mise.toml. +set -euo pipefail + +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +ROOT=$(cd "$HERE/../.." && pwd) +ENGINE=${CDK_DOCKER:-docker} + +# The single version pin lives in the Dockerfile (ARG AWS_EMULATOR_VERSION=...). +# ABCA_EMULATOR_VERSION overrides it for one invocation, which is how a newer upstream release is +# tried before the pin is moved: ABCA_EMULATOR_VERSION= mise run test:integration +VERSION=${ABCA_EMULATOR_VERSION:-$(sed -n 's/^ARG AWS_EMULATOR_VERSION=//p' "$HERE/Dockerfile")} +[[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo "emulator: bad or missing emulator version '$VERSION' (pin: $HERE/Dockerfile)" >&2; exit 1; } + +derive_port() { echo $((20000 + $(printf '%s' "$ROOT" | cksum | cut -d' ' -f1) % 10000)); } +PORT=${ABCA_EMULATOR_PORT:-$(derive_port)} +[[ "$PORT" =~ ^[0-9]+$ ]] || { echo "emulator: ABCA_EMULATOR_PORT must be a number (got '$PORT')" >&2; exit 1; } + +STATE=${ABCA_EMULATOR_HOME:-${XDG_CACHE_HOME:-$HOME/.cache}/abca-aws-emulator} +FILES=$STATE/.aws/emulator/$PORT +# The tag carries the Dockerfile's checksum as well as the version, so a change to the Dockerfile +# that keeps the version (a base-image bump, the key fingerprint) is built, not silently skipped. +IMAGE=abca-aws-emulator:$VERSION-$(cksum < "$HERE/Dockerfile" | cut -d' ' -f1) +NAME=abca-aws-emulator-$PORT +ENDPOINT=https://127.0.0.1:$PORT + +# --noproxy: a proxy configured in the shell must not be asked for a loopback address. +healthy() { curl -sf --max-time 2 --noproxy '*' --cacert "$FILES/ca.pem" "$ENDPOINT/__admin/health" >/dev/null 2>&1; } + +up() { + # Listed, not inspected: while Docker Desktop's engine sleeps (Resource Saver) it answers + # `image inspect` with "No such image", which would re-run the build after every pause. + if [ -z "$("$ENGINE" images -q "$IMAGE" 2>/dev/null)" ]; then + echo "emulator: building $IMAGE (once per version; downloads and verifies the signed package)" + # Dockerfile on stdin: no build context is sent. + "$ENGINE" build --build-arg AWS_EMULATOR_VERSION="$VERSION" -t "$IMAGE" - < "$HERE/Dockerfile" + fi + # Pre-create the shared directory; otherwise Docker on Linux creates it root-owned and the SDK cannot read it. + mkdir -p "$STATE/.aws/emulator" + "$ENGINE" rm -f "$NAME" >/dev/null 2>&1 || true + # On Linux the files must belong to the caller; Docker Desktop (macOS) maps ownership itself. + local user=() + if [ "$(uname -s)" = Linux ]; then user=(--user "$(id -u):$(id -g)"); fi + # -e HOME makes the emulator write the same paths inside the container as on the host. + # 127.0.0.1 on the publish side keeps the emulator off the host's network interfaces (it binds + # 0.0.0.0 in the container). Other containers on the same engine can still reach it. + # ${user[@]+...}: an empty array is "unbound" under `set -u` on the bash 3.2 that macOS ships. + "$ENGINE" run -d --name "$NAME" ${user[@]+"${user[@]}"} --memory=2g --memory-swap=2g \ + -p "127.0.0.1:$PORT:$PORT" -e HOME="$STATE" \ + -v "$STATE/.aws/emulator:$STATE/.aws/emulator" \ + "$IMAGE" -p "$PORT" --idle-timeout 3600 >/dev/null + for _ in $(seq 120); do + if healthy; then echo "emulator: $VERSION ready on $ENDPOINT"; return 0; fi + sleep 0.25 + done + echo "emulator: did not become healthy on $ENDPOINT" >&2 + "$ENGINE" logs "$NAME" 2>&1 | tail -20 >&2 + exit 1 +} + +down() { + # SIGTERM first so the emulator deletes its credentials and certificate; then remove the container. + "$ENGINE" stop -t 5 "$NAME" >/dev/null 2>&1 || true + "$ENGINE" rm -f "$NAME" >/dev/null 2>&1 || true + echo "emulator: stopped ($NAME)" +} + +# Replace the AWS environment of this shell with the emulator's. EVERY AWS_* variable goes, not a +# hand-picked list: that also covers AWS_ENDPOINT_URL_, AWS_IGNORE_CONFIGURED_ENDPOINT_URLS, +# AWS_ROLE_ARN / AWS_WEB_IDENTITY_TOKEN_FILE and the container-credential variables an agent runtime +# sets. Everything outside that namespace is inherited, apart from the tokens removed below. +emulator_env() { + local name + while IFS= read -r name; do unset "$name"; done < <(compgen -e | grep -E '^AWS_' || true) + # Real credentials for other services have no business in a run that only talks to loopback. + unset GITHUB_TOKEN GH_TOKEN BGAGENT_API_KEY + export AWS_ENDPOINT_URL=$ENDPOINT + export AWS_SHARED_CREDENTIALS_FILE=$FILES/emulator_credentials + export AWS_CONFIG_FILE=$FILES/config + export AWS_CA_BUNDLE=$FILES/ca.pem + export NODE_EXTRA_CA_CERTS=$FILES/ca.pem + export AWS_EC2_METADATA_DISABLED=true + export AWS_DISABLE_HOST_PREFIX_INJECTION=true + export AWS_REGION=us-east-1 AWS_DEFAULT_REGION=us-east-1 + # A proxy configured in the shell must not be asked for a loopback address. + export NO_PROXY="127.0.0.1,localhost${NO_PROXY:+,$NO_PROXY}" + export no_proxy="127.0.0.1,localhost${no_proxy:+,$no_proxy}" + # Not an AWS variable, but the same hazard: without this the CLI reads ~/.bgagent, which holds + # the API URL and tokens of the developer's REAL deployment. + export BGAGENT_CONFIG_DIR=$STATE/bgagent + # The variables above only say where AWS SDK calls go. This makes every Node process started + # from here refuse any connection that would leave the machine (see loopback-only.cjs); the + # Python suite installs the same rule itself (agent/tests_emulator/conftest.py). + export NODE_OPTIONS="--require \"$HERE/loopback-only.cjs\"${NODE_OPTIONS:+ $NODE_OPTIONS}" +} + +# Refuse to run anything unless an emulator started by `up` is answering on this port. +guard() { + { [ -r "$AWS_SHARED_CREDENTIALS_FILE" ] && healthy; } \ + || { echo "emulator: refusing to run: no healthy emulator on $ENDPOINT (run: mise run emulator:up)" >&2; exit 1; } +} + +case "${1:-}" in + up) up ;; + down) down ;; + run) + shift + [ $# -gt 0 ] || { echo "usage: emulator.sh run " >&2; exit 2; } + emulator_env + guard + exec "$@" + ;; + *) echo "usage: emulator.sh up | down | run " >&2; exit 2 ;; +esac diff --git a/scripts/aws-emulator/jest-config.js b/scripts/aws-emulator/jest-config.js new file mode 100644 index 000000000..2c84f3f23 --- /dev/null +++ b/scripts/aws-emulator/jest-config.js @@ -0,0 +1,45 @@ +// Builds the jest configuration for a package's emulator-backed tests (ADR-013 Tier 2a) from that +// package's own unit-test configuration. Used by cdk/jest.emulator.config.js and +// cli/jest.emulator.config.js; run through `mise run test:integration`. +// +// The tests are named *.emulator.ts, which the unit configurations' testMatch does not match, so +// a unit run cannot pick them up. They make real AWS SDK calls: with no endpoint set they would +// call AWS with whatever credentials the shell holds. So this refuses to produce a configuration +// unless the AWS environment is the one scripts/aws-emulator/emulator.sh builds, and the +// configuration it produces confirms, before any test file loads, that the loopback-only preload +// is in force and that the endpoint is that emulator (jest-global-setup.js). + +const path = require('node:path'); + +const LOOPBACK_EMULATOR = /^https:\/\/127\.0\.0\.1:\d+$/; +// What emulator.sh sets. Anything else in the AWS_* namespace (a profile, keys, a per-service +// endpoint, AWS_IGNORE_CONFIGURED_ENDPOINT_URLS) could send a call somewhere other than the +// emulator, or sign it with real credentials. +const EXPECTED = new Set([ + 'AWS_ENDPOINT_URL', 'AWS_SHARED_CREDENTIALS_FILE', 'AWS_CONFIG_FILE', 'AWS_CA_BUNDLE', + 'AWS_EC2_METADATA_DISABLED', 'AWS_DISABLE_HOST_PREFIX_INJECTION', 'AWS_REGION', 'AWS_DEFAULT_REGION', +]); + +module.exports = function emulatorConfig(unitConfig) { + const endpoint = process.env.AWS_ENDPOINT_URL ?? ''; + const strays = Object.keys(process.env).filter((name) => name.startsWith('AWS_') && !EXPECTED.has(name)); + if (!LOOPBACK_EMULATOR.test(endpoint) || strays.length > 0) { + throw new Error( + `Emulator tests need AWS_ENDPOINT_URL=https://127.0.0.1: and no other AWS configuration ` + + `(AWS_ENDPOINT_URL='${endpoint}'${strays.length > 0 ? `; unexpected: ${strays.join(', ')}` : ''}). ` + + 'Run them with: mise run test:integration', + ); + } + // A unit configuration may carry a globalSetup that strips the AWS environment so that unit + // tests cannot reach AWS (the CLI's does, from #1035 on). That environment is what these tests + // run on, so it is replaced; everything else is inherited. + return { + ...unitConfig, + testMatch: ['/test/emulator/**/*.emulator.ts'], + globalSetup: path.join(__dirname, 'jest-global-setup.js'), + // Coverage thresholds are a property of the unit suite; a handful of files cannot meet them. + collectCoverage: false, + // The unit run's JUnit report lives in the same directory; do not overwrite it. + reporters: ['default'], + }; +}; diff --git a/scripts/aws-emulator/jest-global-setup.js b/scripts/aws-emulator/jest-global-setup.js new file mode 100644 index 000000000..2e8eaf61d --- /dev/null +++ b/scripts/aws-emulator/jest-global-setup.js @@ -0,0 +1,54 @@ +// Jest globalSetup for the emulator-backed tests: runs once, before any test file is loaded, and +// stops the run unless two things hold. +// +// 1. loopback-only.cjs is preloaded and refuses a connection that leaves this machine. The +// environment only says where AWS SDK calls go; that preload is what keeps everything else +// (and an SDK client a profile setting has pointed back at AWS) on this machine. +// 2. The endpoint really is the AWS Emulator this environment belongs to. Only an emulator answers +// `ok` on /__admin/health, and only the one that wrote the certificate named by +// NODE_EXTRA_CA_CERTS passes the TLS handshake. A loopback address that is some other local +// service fails here instead of receiving a suite's CreateTable calls. +// +// Deliberately free of dependencies: this file belongs to no package. + +const https = require('node:https'); +const net = require('node:net'); + +/** True when the preload is in force. Sends nothing either way: with the preload, connect throws before the name is resolved. */ +function loopbackOnly() { + if (net.Socket.prototype.connect.name !== 'loopbackOnlyConnect') return false; + const probe = new net.Socket(); + try { + probe.connect(443, 'loopback-guard-check.invalid'); + return false; + } catch { + return true; + } finally { + probe.destroy(); + } +} + +module.exports = function requireEmulator() { + if (!loopbackOnly()) { + throw new Error( + 'Emulator tests need the loopback-only preload (scripts/aws-emulator/loopback-only.cjs), and it is not in force. ' + + 'Run them with: mise run test:integration', + ); + } + const endpoint = process.env.AWS_ENDPOINT_URL; + const refuse = (why) => new Error(`No AWS Emulator at ${endpoint} (${why}). Start one with: mise run emulator:up`); + return new Promise((resolve, reject) => { + const request = https.get(`${endpoint}/__admin/health`, { timeout: 3000 }, (response) => { + let body = ''; + response.setEncoding('utf8'); + response.on('data', (chunk) => { body += chunk; }); + response.on('end', () => { + if (response.statusCode === 200 && body.trim() === 'ok') resolve(); + else reject(refuse(`its health route answered ${response.statusCode}`)); + }); + }); + // An endpoint that accepts and never answers fails in seconds, not at a test's timeout. + request.on('timeout', () => request.destroy(new Error('no answer within 3 s'))); + request.on('error', (error) => reject(refuse(error.message))); + }); +}; diff --git a/scripts/aws-emulator/loopback-only.cjs b/scripts/aws-emulator/loopback-only.cjs new file mode 100644 index 000000000..1bd5886e6 --- /dev/null +++ b/scripts/aws-emulator/loopback-only.cjs @@ -0,0 +1,47 @@ +// Preloaded into every Node process that emulator.sh starts (NODE_OPTIONS=--require): jest and +// its workers, tsx, the bgagent CLI. A child process gets it through the inherited NODE_OPTIONS, +// so one started with an environment of its own does not. +// +// The emulator tests make real network calls, and the only place they may go is this machine. +// The environment points the AWS SDK at the emulator; it does not govern anything else. Product +// code also calls GitHub, Slack, Linear and Jira, fetches a token-verification key set from the +// real Cognito host, and opens a hand-signed WebSocket, none of which follow AWS_ENDPOINT_URL. +// Every TCP connection out of a Node process (http, https, http2, fetch, WebSocket, the AWS SDK) +// goes through net.Socket.connect, so that is where one that would leave the machine is refused, +// before a name is resolved or a packet is sent. Pipes are untouched. UDP (node:dgram) does not +// pass through here and is not covered; no ABCA code uses it. +// +// The refusal reaches the caller as an ordinary network error. A test of code that swallows +// network errors therefore has to assert that no request was attempted. +// +// When a test fails here, stub the call that tried to connect. Do not add hosts to the list. +// jest-global-setup.js checks, by this function's name and by a refused probe, that this is loaded. +'use strict'; + +const net = require('node:net'); + +const LOOPBACK = new Set(['localhost', '127.0.0.1', '::1', '::ffff:127.0.0.1']); + +/** The TCP host a connect call targets, or undefined for a pipe. */ +function tcpHost(args) { + // net.connect() hands over one normalized [options, listener] array, socket.connect() the caller's arguments. + const [first, second] = Array.isArray(args[0]) ? args[0] : args; + if (typeof first === 'object' && first !== null) { + // http's agent passes `path: null` for TCP; like node, only a non-empty path means a pipe. + return first.path ? undefined : first.host || 'localhost'; + } + if (typeof first === 'string' && Number.isNaN(Number(first))) return undefined; + return typeof second === 'string' && second ? second : 'localhost'; +} + +const connect = net.Socket.prototype.connect; +net.Socket.prototype.connect = function loopbackOnlyConnect(...args) { + const host = tcpHost(args); + if (host !== undefined && !LOOPBACK.has(host)) { + throw new Error( + `Emulator tests must not open a connection that leaves this machine, and this one tried to reach ${host}. ` + + 'Stub the call that sends the request (see scripts/aws-emulator/loopback-only.cjs).', + ); + } + return connect.apply(this, args); +}; From 15fb17b061fc6581bf06c5701abecd1cd1dbfdd9 Mon Sep 17 00:00:00 2001 From: bgagent Date: Mon, 16 Nov 2026 00:28:24 -0600 Subject: [PATCH 02/25] test(tooling): test the emulator guard's refusals The emulator tier keeps itself away from real AWS with a layered guard: the jest configuration and the pytest session refuse any AWS environment that is not the wrapper's, both confirm the endpoint before a test runs, and a Node preload and a Python audit hook refuse a connection that leaves the machine. None of these refusals had a test; they had only been tried by hand. The tier is an advisory check, so a guard that stops refusing has to fail the required build instead. Two unit suites now run the real guard files, each case in a child process whose environment is built from nothing: - cdk/test/scripts/aws-emulator-guard.test.ts (16 cases): the jest configuration, the global setup and the loopback-only preload. - agent/tests/test_emulator_guard.py (4 cases): the environment check, the audit hook and the session fixture of agent/tests_emulator/conftest.py. Every input is harmless if the guard under test is broken: loopback ports, 127.0.0.2, .invalid names answered by a stub resolver inside the child, no credentials. Each file's header lists the refusals it does not make happen. With them, three small corrections to the guard's own files, and the comments in mise.toml and emulator.sh that describe the tier: - emulator.sh says so when curl is missing (up and run). Without curl the health check failed silently and a running emulator was reported as unhealthy. - The audit hook's event list named socket.gethostbyname_ex, an event CPython does not raise (gethostbyname_ex raises socket.gethostbyname). The name is removed; the call is still refused. - Comments now say what the guard does not cover: a name that Node code resolves itself (node:dns), and a reverse lookup of an address in Python. Both can only produce a DNS question. Verified: - Both suites pass on macOS (jest 16, pytest 4), through a scrubbed environment and from a shell that exports a made-up AWS profile and access key. - Against copies of the guard files with one weakening each, the suites fail: 24 JavaScript and 22 Python weakenings each failed the expected cases before the last three cases were added, and the weakening behind each of those three fails it. - On Linux (arm64): before the last three cases were added, both suites passed in an Ubuntu 24.04 container as an unprivileged user, as root and with no network interface but loopback. The final pytest file passes in a Python 3.13 container without network, as root and as an unprivileged user. The jest cases added last have run under jest on macOS only. - `mise run build` runs both files; `mise run test:integration` does not. Refs #1041 --- agent/tests/test_emulator_guard.py | 206 ++++++++++++++++++ agent/tests_emulator/conftest.py | 3 +- cdk/test/scripts/aws-emulator-guard.test.ts | 225 ++++++++++++++++++++ mise.toml | 6 +- scripts/aws-emulator/emulator.sh | 15 +- scripts/aws-emulator/loopback-only.cjs | 4 +- 6 files changed, 452 insertions(+), 7 deletions(-) create mode 100644 agent/tests/test_emulator_guard.py create mode 100644 cdk/test/scripts/aws-emulator-guard.test.ts diff --git a/agent/tests/test_emulator_guard.py b/agent/tests/test_emulator_guard.py new file mode 100644 index 000000000..e235580bb --- /dev/null +++ b/agent/tests/test_emulator_guard.py @@ -0,0 +1,206 @@ +"""Regression guards for the refusals of the emulator suite (``tests_emulator/conftest.py``). + +The emulator tests make real AWS SDK calls. Three things in their conftest stand +between them and a real account: ``_why_not_an_emulator`` (the environment), the +audit hook ``_refuse_non_loopback`` (anything that would leave the machine) and the +``emulator`` fixture, which every test depends on and which fails the test before +anything is created. A guard that stops refusing lets every emulator test pass, so +the refusals are made to happen here. Two of the fixture's are not: SDK clients that +resolve to another endpoint, and an STS answer from another account. Both need more +than a loopback port that nothing listens on. + +That conftest installs its audit hook when it is imported, and an audit hook cannot +be removed again, so it is never imported into this process: every case runs in a +fresh interpreter. Its whole environment is an empty home directory and what the +case names: the shell that started pytest may export a real profile. Nothing here +can leave the machine even if the guard under test is broken: there are no +credentials, the endpoint is a loopback port that nothing listens on, the one other +address is 127.0.0.2, and no resolver is asked about a name (``_NUMERIC_ONLY``). + +No emulator is needed, which is why this is part of the unit suite. The accepting +path is exercised by every ``mise run test:integration``. +""" + +import json +import re +import subprocess +import sys +from pathlib import Path + +AGENT_DIR = Path(__file__).resolve().parent.parent +# What scripts/aws-emulator/emulator.sh sets, and the only AWS variables the guard accepts. +# Nothing listens on port 1. +WRAPPER_ENVIRONMENT = { + "AWS_ENDPOINT_URL": "https://127.0.0.1:1", + "AWS_SHARED_CREDENTIALS_FILE": "/nonexistent/emulator_credentials", + "AWS_CONFIG_FILE": "/nonexistent/config", + "AWS_CA_BUNDLE": "/nonexistent/ca.pem", + "AWS_EC2_METADATA_DISABLED": "true", + "AWS_DISABLE_HOST_PREFIX_INJECTION": "true", + "AWS_REGION": "us-east-1", + "AWS_DEFAULT_REGION": "us-east-1", +} +REFUSED_ENDPOINTS = [ + "http://127.0.0.1:1", # not TLS + "https://localhost:1", # a name, not the address + "https://127.0.0.2:1", # another address + "https://127.0.0.1:1@outside.invalid", # only begins like the emulator's + "https://outside.invalid/https://127.0.0.1:1", # only ends like it +] +REFUSED_STRAYS = [ + "AWS_PROFILE", # a source of credentials + "AWS_ENDPOINT_URL_DYNAMODB", # begins like an accepted name, and sends one service elsewhere + "AWS_SDK_UA_APP_ID", # harmless in itself: whatever the wrapper does not set is refused +] + +# How every child starts: names are resolved numerically only. The audit event the hook +# listens for is raised all the same, but no resolver is asked, whatever the hook does. +_NUMERIC_ONLY = """ +import socket, sys + +_getaddrinfo = socket.getaddrinfo + + +def _numeric_only(host, port, family=0, type=0, proto=0, flags=0): + return _getaddrinfo(host, port, family, type, proto, flags | socket.AI_NUMERICHOST) + + +socket.getaddrinfo = _numeric_only +""" + +_PROBE = """ +import json, os + +import tests_emulator.conftest as guard # the import under test: it installs the audit hook + + +def reason(variables): + for name in [name for name in os.environ if name.startswith("AWS_")]: + del os.environ[name] + os.environ.update(variables) + return guard._why_not_an_emulator() + + +def outcome(attempt): + try: + attempt() + except PermissionError as exc: + return f"refused: {exc}" + except OSError as exc: + return f"not refused ({type(exc).__name__})" + return "not refused" + + +def connect(address): + with socket.socket() as tcp: + tcp.settimeout(1) + tcp.connect(address) + + +OTHER = ("127.0.0.2", 9) +with socket.socket() as listener, socket.socket(type=socket.SOCK_DGRAM) as udp: + listener.bind(("127.0.0.1", 0)) + listener.listen(1) + print(json.dumps({ + "reasons": [reason(variables) for variables in json.loads(sys.argv[1])], + "getaddrinfo": outcome(lambda: socket.getaddrinfo("outside.invalid", 443)), + "gethostbyname": outcome(lambda: socket.gethostbyname(OTHER[0])), + "connect": outcome(lambda: connect(OTHER)), + "sendto": outcome(lambda: udp.sendto(b"x", OTHER)), + "sendmsg": outcome(lambda: udp.sendmsg([b"x"], [], 0, OTHER)), + "loopback": outcome(lambda: connect(listener.getsockname())), + })) +""" + +_PYTEST = """ +import pytest + +sys.exit(pytest.main(sys.argv[1:])) +""" + +# In a child that starts with this, the conftest's call installs no audit hook. +_NO_AUDIT_HOOK = """ +sys.addaudithook = lambda hook: None +""" + + +def _run( + code: str, args: list[str], home: Path, variables: dict[str, str] +) -> subprocess.CompletedProcess[str]: + """Run ``code`` in a fresh interpreter in ``agent/``, with ``home`` and ``variables`` only.""" + return subprocess.run( + [sys.executable, "-c", _NUMERIC_ONLY + code, *args], + cwd=str(AGENT_DIR), + env={"HOME": str(home), **variables}, + capture_output=True, + text=True, + timeout=100, + check=False, + ) + + +def test_the_environment_check_and_the_audit_hook_refuse(tmp_path): + refused = [ + ({}, "(it is '')"), + *(({"AWS_ENDPOINT_URL": url}, f"(it is {url!r})") for url in REFUSED_ENDPOINTS), + *(({**WRAPPER_ENVIRONMENT, name: "x"}, f"environment: {name}") for name in REFUSED_STRAYS), + ] + environments = [WRAPPER_ENVIRONMENT, *(variables for variables, _ in refused)] + + proc = _run(_PROBE, [json.dumps(environments)], tmp_path, {}) + + assert proc.returncode == 0, proc.stderr + seen = json.loads(proc.stdout.splitlines()[-1]) + accepted, *reasons = seen["reasons"] + assert accepted is None, "the wrapper's own environment must be accepted" + for reason, (variables, expected) in zip(reasons, refused, strict=True): + assert expected in (reason or ""), f"must refuse {variables}" + leaves = "must not open a connection that leaves this machine, and this one tried to reach" + assert f"{leaves} 'outside.invalid'" in seen["getaddrinfo"] + for attempt in ("gethostbyname", "connect", "sendto", "sendmsg"): + assert f"{leaves} '127.0.0.2'" in seen[attempt], attempt + # Loopback stays open: that is where the emulator is. + assert seen["loopback"] == "not refused" + + +def test_no_emulator_test_runs_in_a_shell_without_the_emulator_environment(tmp_path): + # As `mise run test:integration` runs the suite; no cache, so that this run leaves no trace. + args = ["--no-cov", "-p", "no:cacheprovider", "-q", "tests_emulator"] + + proc = _run(_PYTEST, args, tmp_path, {}) + + assert proc.returncode == 1, proc.stdout + proc.stderr + assert "must be https://127.0.0.1: (it is '')" in proc.stdout, proc.stdout + # Errors only: no skip path, and no test that gets as far as its body. + summary = proc.stdout.splitlines()[-1] + assert not re.search(r" (passed|skipped|failed)", summary), summary + + +def _run_a_test_that_asks_for_no_fixture(home: Path, code: str) -> subprocess.CompletedProcess[str]: + """Run ``code``, which ends in ``_PYTEST``, on one test that asks for no fixture.""" + (home / "test_asks_for_nothing.py").write_text("def test_asks_for_nothing():\n pass\n") + # That file is outside tests_emulator/, so the conftest is loaded as a plugin, with the + # suite's own settings. --noconftest keeps out a conftest.py that happens to sit above + # the temporary directory. + args = ["-c", "pyproject.toml", "-p", "tests_emulator.conftest", "-p", "no:cacheprovider", "-q"] + # What a stopped emulator leaves behind: its variables, but no files and no listener. + return _run(code, [*args, "--noconftest", str(home)], home, WRAPPER_ENVIRONMENT) + + +def test_a_test_that_asks_for_no_fixture_is_stopped_when_the_emulator_does_not_answer(tmp_path): + proc = _run_a_test_that_asks_for_no_fixture(tmp_path, _PYTEST) + + assert proc.returncode == 1, proc.stdout + proc.stderr + # With the endpoint the conftest filled in: its own source, which pytest prints with an + # error the fixture did not expect, must not pass for the refusal. + assert "https://127.0.0.1:1 is set but did not answer STS" in proc.stdout, proc.stdout + + +def test_a_test_that_asks_for_no_fixture_is_stopped_when_the_audit_hook_is_not_in_force(tmp_path): + proc = _run_a_test_that_asks_for_no_fixture(tmp_path, _NO_AUDIT_HOOK + _PYTEST) + + assert proc.returncode == 1, proc.stdout + proc.stderr + # As a line of its own, which is how pytest reports the refusal: the conftest's source, + # which it prints with an error the fixture did not expect, has the same words. + refusal = "the loopback-only audit hook did not refuse a name lookup" + assert f"\n{refusal}\n" in proc.stdout, proc.stdout diff --git a/agent/tests_emulator/conftest.py b/agent/tests_emulator/conftest.py index df9bb80c1..8b0aa0042 100644 --- a/agent/tests_emulator/conftest.py +++ b/agent/tests_emulator/conftest.py @@ -73,6 +73,7 @@ def _refuse_non_loopback(event: str, args: tuple[Any, ...]) -> None: """Audit hook: refuse a connection, datagram or name lookup that would leave this machine. It covers this process only; a child process does not inherit an audit hook. + A reverse lookup of an address (gethostbyaddr, getnameinfo) is not covered. The refusal reaches the caller as an ordinary network error, so a test of code that swallows network errors has to assert that no request was attempted. When a test fails here, stub the call that tried to connect. Do not add hosts. @@ -80,7 +81,7 @@ def _refuse_non_loopback(event: str, args: tuple[Any, ...]) -> None: if event in ("socket.connect", "socket.sendto", "socket.sendmsg"): address = args[1] host = address[0] if isinstance(address, tuple) else None # a str is a Unix socket path - elif event in ("socket.getaddrinfo", "socket.gethostbyname", "socket.gethostbyname_ex"): + elif event in ("socket.getaddrinfo", "socket.gethostbyname"): host = args[0] else: return diff --git a/cdk/test/scripts/aws-emulator-guard.test.ts b/cdk/test/scripts/aws-emulator-guard.test.ts new file mode 100644 index 000000000..2d303f41c --- /dev/null +++ b/cdk/test/scripts/aws-emulator-guard.test.ts @@ -0,0 +1,225 @@ +/** + * 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. + */ + +/** + * Tests for the guard of the emulator-backed tests (`scripts/aws-emulator/`). + * + * Those tests make real AWS SDK calls, so three files stand between them and a real + * account: `jest-config.js` refuses an AWS environment that is not the emulator's, + * `jest-global-setup.js` refuses a preload that is missing or refuses nothing and an + * endpoint that is not an emulator, and `loopback-only.cjs` refuses a connection that + * leaves the machine. A guard that stops refusing lets every emulator test pass, so the + * refusals are made to happen here. Three of `jest-global-setup.js` are not: a certificate + * it does not trust and a wrong answer on the health route, which need a TLS listener, and + * an endpoint that never answers, which takes three seconds. + * + * Every case runs the real file in a child `node` whose whole environment is what the + * case names: the shell that starts jest may export a real AWS profile. No case can + * send anything off the machine even when the guard under test is broken: there are no + * credentials, the endpoints are loopback ports, and the hosts are 127.0.0.2 or + * `.invalid` names that no resolver is asked about. + * + * Neither an emulator nor Docker is needed, so this runs with the unit suite (same + * placement rationale as `check-constants-sync.test.ts`). The accepting path, a real + * emulator answering its health route, is exercised by every `mise run test:integration`. + */ + +import { spawnSync } from 'node:child_process'; +import * as path from 'node:path'; + +const REPO_ROOT = path.resolve(__dirname, '../../..'); +const GUARD = path.join(REPO_ROOT, 'scripts/aws-emulator'); +const JEST_CONFIG = path.join(GUARD, 'jest-config.js'); +const GLOBAL_SETUP = path.join(GUARD, 'jest-global-setup.js'); +const PRELOAD = path.join(GUARD, 'loopback-only.cjs'); + +/** The AWS variables `emulator.sh run` sets, and the only ones the guard accepts. Nothing listens on port 1. */ +const WRAPPER_ENVIRONMENT = { + AWS_ENDPOINT_URL: 'https://127.0.0.1:1', + AWS_SHARED_CREDENTIALS_FILE: '/nonexistent/emulator_credentials', + AWS_CONFIG_FILE: '/nonexistent/config', + AWS_CA_BUNDLE: '/nonexistent/ca.pem', + AWS_EC2_METADATA_DISABLED: 'true', + AWS_DISABLE_HOST_PREFIX_INJECTION: 'true', + AWS_REGION: 'us-east-1', + AWS_DEFAULT_REGION: 'us-east-1', +}; + +/** Run `node` with `args`. `env` is its whole environment: nothing is inherited. */ +function node(args: string[], env: Record = {}) { + return spawnSync(process.execPath, args, { env, encoding: 'utf-8', timeout: 30_000 }); +} + +describe('emulator test guard', () => { + // One `node` start per test, about 50 ms each. + jest.setTimeout(60_000); + + describe('jest-config.js', () => { + /** The global setup of the emulator configuration, built from a unit configuration that has one of its own. */ + const BUILD = `require(${JSON.stringify(JEST_CONFIG)})({ globalSetup: 'unit-setup' }).globalSetup`; + + test('accepts what the wrapper sets, and puts its own global setup in place of the unit one', () => { + const result = node(['-p', BUILD], WRAPPER_ENVIRONMENT); + + expect(result).toMatchObject({ status: 0, stdout: `${GLOBAL_SETUP}\n`, stderr: '' }); + }); + + test.each([ + 'http://127.0.0.1:1', // not TLS + 'https://localhost:1', // a name, not the address + 'https://127.0.0.2:1', // another address + 'https://127.0.0.1:1@outside.invalid', // only begins like the emulator's: the host is outside.invalid + 'https://outside.invalid/https://127.0.0.1:1', // only ends like it + ])('refuses the endpoint %s', (endpoint) => { + const result = node(['-p', BUILD], { ...WRAPPER_ENVIRONMENT, AWS_ENDPOINT_URL: endpoint }); + + expect(result.status).toBe(1); + expect(result.stderr).toContain(`(AWS_ENDPOINT_URL='${endpoint}')`); + }); + + test.each([ + 'AWS_PROFILE', // a source of credentials + 'AWS_ENDPOINT_URL_DYNAMODB', // begins like an accepted name, and sends one service elsewhere + 'AWS_SDK_UA_APP_ID', // harmless in itself: whatever the wrapper does not set is refused + ])('refuses %s beside what the wrapper sets', (stray) => { + const result = node(['-p', BUILD], { ...WRAPPER_ENVIRONMENT, [stray]: 'anything' }); + + expect(result.status).toBe(1); + expect(result.stderr).toContain(`unexpected: ${stray})`); + }); + + test.each(['cdk', 'cli'])('%s/jest.emulator.config.js refuses a shell without the emulator environment', (workspace) => { + const result = node([path.join(REPO_ROOT, workspace, 'jest.emulator.config.js')]); + + expect(result.status).toBe(1); + expect(result.stderr).toContain("(AWS_ENDPOINT_URL=''). Run them with: mise run test:integration"); + }); + }); + + describe('jest-global-setup.js refuses to start a run', () => { + /** + * Runs the setup, as jest does, against a listener that answers the health route with the + * emulator's own body and is not the emulator: it does not speak TLS, let alone with the + * certificate of this run. The system resolver is taken out first, so that it is not asked + * even if the preload under test lets the setup's own probe through. + */ + const START = ` + const impostor = require('node:http').createServer((_request, response) => response.end('ok')).unref(); + impostor.listen(0, '127.0.0.1', async () => { + require('node:dns').lookup = (_host, _options, callback) => callback(new Error('no name resolution here')); + process.env.AWS_ENDPOINT_URL = 'https://127.0.0.1:' + impostor.address().port; + await require(${JSON.stringify(GLOBAL_SETUP)})(); + console.log('accepted'); + });`; + + test('without the loopback-only preload', () => { + const result = node(['-e', START], WRAPPER_ENVIRONMENT); + + expect(result.status).toBe(1); + expect(result.stderr).toContain('Error: Emulator tests need the loopback-only preload'); + }); + + test('with a preload that refuses nothing', () => { + // The name the setup looks for, on a connect that lets everything through. + const nameOnly = ` + const net = require('node:net'); + const connect = net.Socket.prototype.connect; + net.Socket.prototype.connect = function loopbackOnlyConnect(...args) { return connect.apply(this, args); };`; + + const result = node(['-e', nameOnly + START], WRAPPER_ENVIRONMENT); + + expect(result.status).toBe(1); + expect(result.stderr).toContain('Error: Emulator tests need the loopback-only preload'); + }); + + test('with a guard that is not the preload', () => { + // Refuses the probe, under another name. + const otherName = ` + const net = require('node:net'); + const connect = net.Socket.prototype.connect; + net.Socket.prototype.connect = function someOtherGuard(...args) { + if (typeof args[1] === 'string' && args[1] !== '127.0.0.1') throw new Error('refused by another guard'); + return connect.apply(this, args); + };`; + + const result = node(['-e', otherName + START], WRAPPER_ENVIRONMENT); + + expect(result.status).toBe(1); + expect(result.stderr).toContain('Error: Emulator tests need the loopback-only preload'); + }); + + test('on an endpoint that is some other local service', () => { + const result = node(['--require', PRELOAD, '-e', START], WRAPPER_ENVIRONMENT); + + expect(result.status).toBe(1); + expect(result.stderr).toMatch(/Error: No AWS Emulator at https:\/\/127\.0\.0\.1:\d+ \(/); + }); + }); + + describe('loopback-only.cjs', () => { + /** + * Tries each way out and reports how it ended. A refusal throws before the name is resolved, + * so the resolver, which is replaced first by one that only counts, is never asked. Without + * the guard an attempt ends in that resolver's error or at 127.0.0.2, and is abandoned at once. + */ + const ATTEMPTS = ` + const net = require('node:net'); + const http = require('node:http'); + const tls = require('node:tls'); + const server = http.createServer((_request, response) => response.end('ok')); + server.listen(0, '127.0.0.1', async () => { + const report = { lookups: 0 }; + require('node:dns').lookup = (_host, _options, callback) => { report.lookups += 1; callback(new Error('no name resolution here')); }; + const attempt = (name, open) => { + try { + open().on('error', () => undefined).destroy(); + report[name] = 'not refused'; + } catch (error) { + report[name] = error.message; + } + }; + attempt('net.connect', () => net.connect({ host: 'outside.invalid', port: 443 })); + attempt('http.get', () => http.get({ host: 'outside.invalid' })); + attempt('tls.connect', () => tls.connect({ host: 'outside.invalid', port: 443 })); + attempt('socket.connect', () => new net.Socket().connect(80, '127.0.0.2')); + report.fetch = await fetch('http://outside.invalid/').then(() => 'not refused', (error) => String(error.cause?.message)); + report.loopback = await (await fetch('http://127.0.0.1:' + server.address().port)).text(); + server.close(); + console.log(JSON.stringify(report)); + });`; + + test('refuses every host but loopback, before the name is resolved', () => { + const refused = (host: string) => expect.stringContaining(`and this one tried to reach ${host}.`); + + const result = node(['--require', PRELOAD, '-e', ATTEMPTS]); + + expect(result).toMatchObject({ status: 0, stderr: '' }); + expect(JSON.parse(result.stdout)).toEqual({ + 'net.connect': refused('outside.invalid'), + 'http.get': refused('outside.invalid'), + 'tls.connect': refused('outside.invalid'), + 'socket.connect': refused('127.0.0.2'), + 'fetch': refused('outside.invalid'), + 'lookups': 0, + // Loopback stays open: that is where the emulator is. + 'loopback': 'ok', + }); + }); + }); +}); diff --git a/mise.toml b/mise.toml index 5b18d33c4..57535b8f3 100644 --- a/mise.toml +++ b/mise.toml @@ -211,8 +211,10 @@ depends = [":lint", ":drift-prevention"] # Emulator-backed integration tests (ADR-013 Tier 2a): ABCA's real handler, CLI and agent code # against a local AWS Emulator (https://github.com/aws/aws-emulator). Needs Docker and no AWS -# account. Nothing here is reachable from `mise run build`. The emulator version is pinned once, -# in scripts/aws-emulator/Dockerfile. See docs/research/aws-emulator-local-tests.md. +# account. `mise run build` runs none of these tasks, only the unit tests of the guard's refusals. +# The emulator version is pinned once, in scripts/aws-emulator/Dockerfile. See +# scripts/aws-emulator/README.md for the rules and the known differences from AWS, and +# docs/research/aws-emulator-local-tests.md for the investigation behind the tier. [tasks."emulator:up"] description = "Start a fresh AWS Emulator on 127.0.0.1 (builds the pinned, signature-verified image on first use)" diff --git a/scripts/aws-emulator/emulator.sh b/scripts/aws-emulator/emulator.sh index 240dcba55..ed921c5c5 100755 --- a/scripts/aws-emulator/emulator.sh +++ b/scripts/aws-emulator/emulator.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # AWS Emulator lifecycle and guarded command runner for the local/CI integration tier # (ADR-013 Tier 2a). Driven by the mise tasks emulator:up, emulator:down, emulator:run and -# test:integration; nothing here is reachable from `mise run build`. +# test:integration. `mise run build` never runs this script, only the unit tests of the other guard files. # # emulator.sh up build the pinned image if missing, start a FRESH emulator, wait for health # emulator.sh down stop it (all emulated state is in memory, so this is also "reset") @@ -10,6 +10,8 @@ # `run` is for programs that use an AWS SDK. Do not use it with AWS CLI v1: that CLI forces a real # AWS endpoint for sqs, rds, docdb, neptune and health whatever AWS_ENDPOINT_URL says. # +# Needs a container engine (see CDK_DOCKER below) and curl, which the health check uses. +# # Environment: # ABCA_EMULATOR_PORT port on 127.0.0.1. Default: derived from the checkout path, so two worktrees # can run the tier at the same time without stopping each other's emulator. @@ -54,7 +56,8 @@ up() { # Dockerfile on stdin: no build context is sent. "$ENGINE" build --build-arg AWS_EMULATOR_VERSION="$VERSION" -t "$IMAGE" - < "$HERE/Dockerfile" fi - # Pre-create the shared directory; otherwise Docker on Linux creates it root-owned and the SDK cannot read it. + # Pre-create the shared directory; otherwise Docker on Linux creates it root-owned and the emulator, + # which runs as the caller, cannot write its files there. mkdir -p "$STATE/.aws/emulator" "$ENGINE" rm -f "$NAME" >/dev/null 2>&1 || true # On Linux the files must belong to the caller; Docker Desktop (macOS) maps ownership itself. @@ -119,12 +122,18 @@ guard() { || { echo "emulator: refusing to run: no healthy emulator on $ENDPOINT (run: mise run emulator:up)" >&2; exit 1; } } +# Without curl the health check fails silently and a running emulator is reported as unhealthy. +need_curl() { + command -v curl >/dev/null || { echo "emulator: curl is required (the health check uses it)" >&2; exit 1; } +} + case "${1:-}" in - up) up ;; + up) need_curl; up ;; down) down ;; run) shift [ $# -gt 0 ] || { echo "usage: emulator.sh run " >&2; exit 2; } + need_curl emulator_env guard exec "$@" diff --git a/scripts/aws-emulator/loopback-only.cjs b/scripts/aws-emulator/loopback-only.cjs index 1bd5886e6..b3f7dc48f 100644 --- a/scripts/aws-emulator/loopback-only.cjs +++ b/scripts/aws-emulator/loopback-only.cjs @@ -9,7 +9,9 @@ // Every TCP connection out of a Node process (http, https, http2, fetch, WebSocket, the AWS SDK) // goes through net.Socket.connect, so that is where one that would leave the machine is refused, // before a name is resolved or a packet is sent. Pipes are untouched. UDP (node:dgram) does not -// pass through here and is not covered; no ABCA code uses it. +// pass through here and is not covered; no ABCA code uses it. Nor does a name that code resolves +// itself (node:dns): the URL and Linear attachment downloads do that before they connect, so a +// test that reaches them has to stub the lookup. // // The refusal reaches the caller as an ordinary network error. A test of code that swallows // network errors therefore has to assert that no request was attempted. From 0d243bd55af1f3f97d62114d528125497f07e5a9 Mon Sep 17 00:00:00 2001 From: bgagent Date: Mon, 16 Nov 2026 00:28:25 -0600 Subject: [PATCH 03/25] fix(cdk): add an index for a user's tasks by creation time (#51) The only index on the task table that is keyed by user sorts on status_created_at, which is `#