diff --git a/docs/system-specs/modules/cloud.md b/docs/system-specs/modules/cloud.md index 0a972b20e776..fe211d95c4c2 100644 --- a/docs/system-specs/modules/cloud.md +++ b/docs/system-specs/modules/cloud.md @@ -80,6 +80,19 @@ claim that a hostile in-process agent is fully contained. | `fargate_engine.py` | The `LaunchEngine` for Fargate, not yet reachable through `engine_for`: nothing registers it, and the provisioner id it will need belongs to the change that wires it, because the built-in id gates `size_key` against the EC2 instance ladder and a cpu/memory pair is not on it. Its teardown decides ownership from a task's tags: the `kirocrew:managed` marker is checked as a boolean gate **before** the identifier, so a task whose marker holds anything other than `true` is `UNMARKED` and is never stopped, and identity is then read under the imported `LAUNCH_TAG_KEY`. A running task this launch started but whose launch tag is absent or names another launch is `MISLABELLED`; both it and a running `UNMARKED` task carrying this launch's `startedBy` are REFUSED rather than deleted, and the plan returns `confirmed=False` naming the ARNs, because deleting on a `startedBy` match alone is a guess and reporting `True` would tell the operator their billing stopped when a task may still be running. Neither the marker's key nor its value nor the launch-tag key is spelled here; all three are imported from the modules that own them. | | `ui.py` / `wizard.py` | Terminal UI + the interactive launch flow. `_deploy_with_progress` runs the blocking deploy on a daemon thread and captures the `aws cloudformation deploy` child via a `proc_sink`, so a Ctrl+C on the main (poll) thread terminates it instead of orphaning it (~1800s). An unknown `--size`/`size_key` on the public `launch()` entrypoint yields a clean rc=1 + message, not an uncaught `KeyError`. Resuming a saved stack (`launch` after `stop`) first calls `_ensure_running_and_ssm_ready` — starts a `stopped` instance and waits for SSM `Online` before sign-in/tunnel (which are SSM-only and would otherwise fail); a `terminated` instance fails clean pointing at `--new`. `last_tag` is persisted (`cfg.save()`) **only after** a deploy confirms healthy — a failed first launch leaves no saved pointer, so the next `launch` retries clean instead of resuming a rolled-back/instance-less stack; `_saved_launch_is_usable` additionally ignores a stale saved tag (from an older build) whose stack is in a `_FAILED_STATES` status or has no instance. | | `templates/kirocrew-ec2.yaml` | The CloudFormation stack. | +| `templates/kirocrew-fargate-base.yaml` | The account-and-region Fargate stack: the ECS cluster and an egress-only security group with no ingress. One per account and region, shared by every crew's tasks, so deleting one crew's stack cannot delete the cluster its siblings run on. | +| `templates/kirocrew-fargate-crew.yaml` | The per-crew Fargate stack: the execution role (crew-scoped secret read, log write), a policy-less task role, and the log group. Resource names are the ones `identity.py` derives (`kirocrew-crew--exec`, `-task`, `/kirocrew/crew/`) and `taskdef.py` refuses a document that disagrees with, so a rename on either side becomes a launch refusal rather than a mismatch that runs. The task role is created with no policies at all and must never gain `secretsmanager:GetSecretValue` -- the execution role holds that read, scoped to the one crew's secret namespace. | + +The two Fargate stacks publish the fields the launch engine's refusal at +`fargate_engine.py` lists, so each has exactly one place to be read from. The +base stack outputs `ClusterName`, `ClusterArn`, `SecurityGroupId`, `SubnetIds`, +`CpuArchitecture`, `Region` and `StackTag`; the crew stack outputs `Crew`, +`ExecutionRoleArn`, `TaskRoleArn`, `LogGroupName`, `SecretNamePrefix` and +`SecretArnPattern`. `SecretArnPattern` is asserted character-for-character +against the policy that grants the read, so an output cannot promise reach the +role does not have. The templates are verified statically and offline by +`test/test_fargate_scaffolding_contract.py`, which calls the `identity.py` and +`taskdef.py` derivation functions rather than restating their strings. ## Provisioning shape diff --git a/src/kiro_crew/cloud/templates/kirocrew-fargate-base.yaml b/src/kiro_crew/cloud/templates/kirocrew-fargate-base.yaml new file mode 100644 index 000000000000..7f886d3a9aad --- /dev/null +++ b/src/kiro_crew/cloud/templates/kirocrew-fargate-base.yaml @@ -0,0 +1,116 @@ +AWSTemplateFormatVersion: "2010-09-09" +Description: >- + Shared Fargate scaffolding for Kiro Crew remote crews in the user's own AWS + account: the ECS cluster every crew task runs on and the egress-only security + group they are placed in. One stack per account and region. The per-crew roles + and log group live in kirocrew-fargate-crew.yaml, one stack per crew, so + deleting a crew cannot delete the cluster its siblings run on. + + Its outputs are the configuration home for FargateLaunchSpec.placement: + ClusterName, SecurityGroupId and the subnets the operator passed in, plus the + CPU architecture the crew image was built for. + +# --------------------------------------------------------------------------- +# Parameters. Networking is taken, never invented: a Fargate task needs a route +# to pull its image, and whether that is a NAT gateway or a public subnet is a +# property of the operator's VPC that this stack cannot discover. Passing the +# subnets in keeps the failure at deploy time with a name attached, instead of a +# task that reaches RUNNING and then cannot pull. +# --------------------------------------------------------------------------- +Parameters: + StackTag: + Type: String + Default: kirocrew + # Mirrors the EC2 lane's cap for the same reason: names derived from this tag + # are bounded by AWS resource-name limits, and a value that passes template + # validation but fails opaquely at resource creation is worse than one + # refused here. An ECS cluster name maxes at 255, so 51 is comfortable. + AllowedPattern: "[a-zA-Z0-9-]{1,51}" + Description: Discovery tag value written as kirocrew:fargate. + + VpcId: + Type: AWS::EC2::VPC::Id + Description: VPC the crew tasks are placed in. + + SubnetIds: + Type: List + Description: >- + Subnets for the tasks' awsvpc network interfaces. Each must be able to + reach the container registry, either through a NAT gateway or as a public + subnet with assignPublicIp enabled at RunTask. + + CpuArchitecture: + Type: String + Default: X86_64 + # Exactly taskdef.CPU_ARCHITECTURES, upper-case as the ECS API spells it. + # taskdef._refuse_unknown_architecture rejects anything outside that set, so a + # value this stack accepted but the launcher refuses would deploy cleanly and + # then never start a crew. A test compares these values against that frozenset + # by importing it, so a change on either side reds instead. + AllowedValues: [X86_64, ARM64] + Description: >- + Architecture the crew image was built for. It must match the image: a task + whose runtime platform disagrees with its image fails at start. + +Resources: + # --- The cluster. Named from the stack tag so a launcher can derive it rather + # than discover it, which is what lets Placement.cluster be stated instead + # of searched for. Naming it explicitly also keeps it out of the account's + # implicit `default` cluster, which runtask.py refuses to assume. + Cluster: + Type: AWS::ECS::Cluster + Properties: + ClusterName: !Sub "kirocrew-crew-${StackTag}" + ClusterSettings: + - Name: containerInsights + Value: disabled + Tags: + - { Key: "kirocrew:managed", Value: "true" } + - { Key: "kirocrew:fargate", Value: !Ref StackTag } + + # --- Security group: no ingress at all. The crew's control surface is reached + # outbound-authenticated, so nothing needs to dial in, and an empty ingress + # list is the difference between a crew that is reachable by its owner and + # one that is reachable by the internet. Egress is open so the task can + # pull its image and reach the model endpoint. + TaskSecurityGroup: + Type: AWS::EC2::SecurityGroup + Properties: + GroupDescription: !Sub "Kiro Crew Fargate crews ${StackTag} - egress only, no inbound" + VpcId: !Ref VpcId + SecurityGroupEgress: + - IpProtocol: "-1" + CidrIp: 0.0.0.0/0 + Description: Allow all outbound + Tags: + - { Key: "kirocrew:managed", Value: "true" } + - { Key: "kirocrew:fargate", Value: !Ref StackTag } + +Outputs: + ClusterName: + Description: ECS cluster name for FargateLaunchSpec.placement.cluster. + Value: !Ref Cluster + ClusterArn: + Description: ECS cluster ARN. + Value: !GetAtt Cluster.Arn + SecurityGroupId: + Description: Security group id for FargateLaunchSpec.placement.security_groups. + Value: !Ref TaskSecurityGroup + SubnetIds: + Description: >- + Subnets for FargateLaunchSpec.placement.subnets, echoed back so the launch + spec reads every placement field from stack outputs rather than half from a + stack and half from whatever the operator typed. + Value: !Join [",", !Ref SubnetIds] + CpuArchitecture: + Description: >- + Architecture for FargateLaunchSpec.cpu_architecture, echoed back for the + same reason as SubnetIds: every launch-spec field is read from a stack + output rather than half from a stack and half from the operator's memory. + Value: !Ref CpuArchitecture + Region: + Description: Region the stack was deployed to. + Value: !Ref AWS::Region + StackTag: + Description: The kirocrew:fargate discovery tag value. + Value: !Ref StackTag diff --git a/src/kiro_crew/cloud/templates/kirocrew-fargate-crew.yaml b/src/kiro_crew/cloud/templates/kirocrew-fargate-crew.yaml new file mode 100644 index 000000000000..5c05dcb94fd7 --- /dev/null +++ b/src/kiro_crew/cloud/templates/kirocrew-fargate-crew.yaml @@ -0,0 +1,226 @@ +AWSTemplateFormatVersion: "2010-09-09" +Description: >- + Per-crew Fargate scaffolding for one Kiro Crew remote crew: the two roles a task + carries and the log group it writes to. One stack per crew, alongside the + shared kirocrew-fargate-base.yaml. Deleting this stack removes exactly one + crew's identity and logs and leaves the cluster and its siblings untouched. + + Every name here is DERIVED by src/kiro_crew/cloud/fargate/identity.py, not + chosen: the task definition builds executionRoleArn, taskRoleArn and the log + group from the crew name and then refuses a document whose ARNs disagree. So a + name changed on either side is a launch refusal, not a mismatch that runs. + +# --------------------------------------------------------------------------- +# Parameters +# --------------------------------------------------------------------------- +Parameters: + Crew: + Type: String + # Mirrors _CREW_RE in cloud/fargate/identity.py exactly. The bounds are not + # cosmetic: a trailing hyphen makes the derived role name end in "--exec", + # and a leading one is not a legal start for the resource names built from + # it. Refusing here keeps that at deploy time rather than at first launch. + AllowedPattern: "^[a-z0-9]([a-z0-9-]{0,30}[a-z0-9])?$" + Description: >- + Crew name. 1 to 32 characters, lower-case alphanumeric with inner hyphens, + never leading or trailing. + + LogRetentionDays: + Type: Number + Default: 30 + AllowedValues: [1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365] + Description: Days a crew's task logs are kept before CloudWatch expires them. + + PermissionsBoundaryArn: + Type: String + Default: "" + # Empty is a DECLARED degraded mode, not an oversight. The EC2 lane caps its + # instance role with a shared, pre-created, immutable boundary authored ONCE + # by launcher code (cloud/iam.py ensure_instance_boundary), so a leaked + # launcher credential cannot author a permissive one. No equivalent creator + # exists for the crew boundary yet: cloud/iam.py builds only the EC2 one. + # Rather than reference a policy nothing creates, this parameter accepts the + # exact ARN once that creator lands and otherwise deploys without a ceiling. + # A test asserts the pattern stays exact, so widening it is a visible edit. + # A test compares this against identity._PARTITION_RE behaviourally, so the + # partition alternation cannot drift from the one CrewBinding accepts: a + # pattern that admitted only "aws" would refuse a valid aws-cn or aws-us-gov + # ARN at parameter validation, and the per-crew stack would simply fail to + # deploy in those partitions. + AllowedPattern: "^$|^arn:aws(-[a-z0-9]+)*:iam::[0-9]{12}:policy/kirocrew-crew-boundary$" + Description: >- + ARN of the pre-created shared crew permissions boundary + (arn:aws:iam:::policy/kirocrew-crew-boundary), or empty until the + code that creates it exists. When set, it is the ceiling on what these + roles can ever do regardless of attached policies. + + EcrRepositoryArn: + Type: String + Default: "" + # Empty means the crew image is pulled from a public registry, which needs no + # execution-role permission at all -- the decided delivery for the shared + # crew image (issue #11408) is ECR Public. Set it only for a private + # repository, and the grant is then scoped to that one repository ARN. + # Partition alternation as above, pinned to identity._PARTITION_RE by the same + # test: an ECR repository in aws-cn or aws-us-gov is a valid target. + AllowedPattern: "^$|^arn:aws(-[a-z0-9]+)*:ecr:[a-z0-9-]{1,32}:[0-9]{12}:repository/[a-zA-Z0-9._/-]+$" + Description: >- + ARN of the private ECR repository holding the crew image, or empty when the + image is pulled from a public registry. + +Conditions: + HasBoundary: !Not [!Equals [!Ref PermissionsBoundaryArn, ""]] + HasPrivateRegistry: !Not [!Equals [!Ref EcrRepositoryArn, ""]] + +Resources: + # --- Log group. Named /kirocrew/crew/ because log_group_name() derives + # exactly that, and logConfiguration is one of the four fields RunTask + # CANNOT override, so the name is fixed at registration. + LogGroup: + Type: AWS::Logs::LogGroup + Properties: + LogGroupName: !Sub "/kirocrew/crew/${Crew}" + RetentionInDays: !Ref LogRetentionDays + Tags: + - { Key: "kirocrew:managed", Value: "true" } + - { Key: "kirocrew:crew", Value: !Ref Crew } + + # --- Execution role: what ECS itself assumes BEFORE the container starts, to + # fetch the crew's secrets and open its log stream. The container never + # holds this role, which is why the secret read lives here and not on the + # task role. + # + # Every action is listed individually. No prefix wildcard appears anywhere + # in this template, deliberately: cloud/aws.py's read allowlist documents + # that a prefix admits `secretsmanager get-secret-value` and + # `ssm get-parameter --with-decryption`, so `secretsmanager:Get*` would + # grant the very thing the task role is denied. + ExecutionRole: + Type: AWS::IAM::Role + Properties: + RoleName: !Sub "kirocrew-crew-${Crew}-exec" + PermissionsBoundary: !If [HasBoundary, !Ref PermissionsBoundaryArn, !Ref "AWS::NoValue"] + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Principal: { Service: ecs-tasks.amazonaws.com } + Action: sts:AssumeRole + Condition: + # Without this the role is assumable on behalf of any task in the + # account, including one an unrelated stack registered. + StringEquals: + "aws:SourceAccount": !Ref "AWS::AccountId" + Policies: + - PolicyName: CrewSecretRead + PolicyDocument: + Version: "2012-10-17" + Statement: + # Resource-scoped to THIS crew's secret namespace. The trailing + # wildcard covers the six-character suffix Secrets Manager appends + # and which no caller can derive (see identity.py's + # _SECRET_SUFFIX_RE) -- it does not widen the crew segment, so this + # role cannot read a sibling crew's secret. + - Effect: Allow + Action: + - secretsmanager:GetSecretValue + Resource: + - !Sub "arn:${AWS::Partition}:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:kirocrew/crew/${Crew}/*" + - PolicyName: CrewLogWrite + PolicyDocument: + Version: "2012-10-17" + Statement: + # Scoped to this crew's own log group. CreateLogGroup is absent on + # purpose: the group is created by this stack, so a task that could + # create one could also write outside the namespace it is retained + # and deleted under. + - Effect: Allow + Action: + - logs:CreateLogStream + - logs:PutLogEvents + Resource: + - !Sub "arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:/kirocrew/crew/${Crew}:*" + - !If + - HasPrivateRegistry + - PolicyName: CrewImagePull + PolicyDocument: + Version: "2012-10-17" + Statement: + # GetAuthorizationToken is account-wide by the service's own + # design: it names no repository, so it cannot be scoped to one. + - Effect: Allow + Action: + - ecr:GetAuthorizationToken + Resource: "*" + - Effect: Allow + Action: + - ecr:BatchCheckLayerAvailability + - ecr:BatchGetImage + - ecr:GetDownloadUrlForLayer + Resource: + - !Ref EcrRepositoryArn + - !Ref "AWS::NoValue" + Tags: + - { Key: "kirocrew:managed", Value: "true" } + - { Key: "kirocrew:crew", Value: !Ref Crew } + + # --- Task role: the identity the RUNNING container carries, and therefore the + # blast radius one agent turn reaches. It is created with NO policies at + # all, which is the intended starting state rather than an unfinished one. + # + # It must NEVER be granted secretsmanager:GetSecretValue. identity.py's + # task_role_arn docstring states the reason: the model credential is + # already in the container's environment by the time this role exists, so + # the permission buys the crew nothing it does not have, while a turn that + # could re-read a secret could read every crew's. A test asserts the + # absence, so granting it later is a visible, argued edit. + TaskRole: + Type: AWS::IAM::Role + Properties: + RoleName: !Sub "kirocrew-crew-${Crew}-task" + PermissionsBoundary: !If [HasBoundary, !Ref PermissionsBoundaryArn, !Ref "AWS::NoValue"] + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Principal: { Service: ecs-tasks.amazonaws.com } + Action: sts:AssumeRole + Condition: + StringEquals: + "aws:SourceAccount": !Ref "AWS::AccountId" + Tags: + - { Key: "kirocrew:managed", Value: "true" } + - { Key: "kirocrew:crew", Value: !Ref Crew } + +Outputs: + Crew: + Description: The crew this stack scaffolds. + Value: !Ref Crew + ExecutionRoleArn: + Description: >- + Role ECS assumes to fetch secrets and open the log stream. Must equal + identity.execution_role_arn() for this crew or the task definition is + refused. + Value: !GetAtt ExecutionRole.Arn + TaskRoleArn: + Description: >- + Role the running container carries. Must equal identity.task_role_arn() for + this crew or the task definition is refused. + Value: !GetAtt TaskRole.Arn + LogGroupName: + Description: Log group for the task's awslogs driver. + Value: !Ref LogGroup + SecretNamePrefix: + Description: >- + Namespace a crew secret must be created under for the execution role to + read it. A secret outside it resolves to no value and the task refuses to + start. + Value: !Sub "kirocrew/crew/${Crew}/" + SecretArnPattern: + Description: >- + The one secret ARN pattern the execution role may read, for the launch + spec's secret references. A test asserts this is character-for-character the + Resource on the CrewSecretRead statement, so widening one and not the other + cannot ship: an output that promised more than the policy grants would send + a caller after a secret the task then cannot read. + Value: !Sub "arn:${AWS::Partition}:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:kirocrew/crew/${Crew}/*" diff --git a/test/test_fargate_scaffolding_contract.py b/test/test_fargate_scaffolding_contract.py new file mode 100644 index 000000000000..198365f36a91 --- /dev/null +++ b/test/test_fargate_scaffolding_contract.py @@ -0,0 +1,462 @@ +"""The Fargate scaffolding templates must keep agreeing with ``identity.py``. + +Every name in ``kirocrew-fargate-crew.yaml`` is DERIVED on the code side, not +chosen: ``taskdef.py`` builds ``executionRoleArn``, ``taskRoleArn`` and the log +group from the crew name and then refuses a document whose ARNs disagree. So a +rename on either side does not produce a mismatch that runs -- it produces a +launch refusal, at the first launch after the rename, with nothing failing at +the moment the rename lands. These tests assert the agreement by CALLING the +derivation functions, so a rename on either side reds here instead. + +Two of them guard a security property rather than a name: + +* **The task role gets no secret read.** ``identity.task_role_arn``'s docstring + states the reason -- the model credential is already in the container's + environment by the time that role exists, so the permission buys the crew + nothing it does not have, while a turn that could re-read a secret could read + every crew's. Granting it would be a one-line, plausible-looking edit that + nothing else would catch. +* **No action is a prefix wildcard.** ``cloud/aws.py``'s read allowlist documents + why it enumerates instead of prefixing: a prefix admits + ``secretsmanager get-secret-value`` and ``ssm get-parameter --with-decryption``. + So ``secretsmanager:Get*`` on the execution role would grant, through the + wildcard, exactly what the task role is denied outright. + +Static and offline: these read only the template text, so they cannot flake and +need no AWS account, no credential and no deploy. +""" + +from __future__ import annotations + +import re +from pathlib import Path +from typing import Any + +import pytest +import yaml +from yaml_helpers import load_with + +from kiro_crew.cloud.fargate.identity import _CREW_RE # the contract the template mirrors +from kiro_crew.cloud.fargate.identity import _PARTITION_RE # ditto, for ARN partitions +from kiro_crew.cloud.fargate.identity import ( + SECRET_NAME_PREFIX, + CrewBinding, + execution_role_arn, + log_group_name, + task_role_arn, +) +from kiro_crew.cloud.fargate.taskdef import CPU_ARCHITECTURES + +ROOT = Path(__file__).resolve().parents[1] +TEMPLATES = ROOT / "src" / "kiro_crew" / "cloud" / "templates" +BASE = TEMPLATES / "kirocrew-fargate-base.yaml" +CREW = TEMPLATES / "kirocrew-fargate-crew.yaml" + +#: A crew name for rendering ``${Crew}`` so the rendered value can be compared +#: against what the identity functions derive for the same crew. +SAMPLE_CREW = "demo" +SAMPLE_BINDING = CrewBinding(partition="aws", account="123456789012", crew=SAMPLE_CREW) + + +class _CfnLoader(yaml.SafeLoader): + """SafeLoader that keeps CloudFormation's short-form intrinsics readable. + + ``yaml.safe_load`` raises on ``!Sub`` and friends, so a test that used it + would fail for the wrong reason. Each tag becomes ``{"__tag__": name, + "value": ...}``, which keeps the payload reachable without pretending to + evaluate the intrinsic. + """ + + +def _intrinsic(loader: yaml.Loader, tag_suffix: str, node: yaml.Node) -> dict[str, Any]: + if isinstance(node, yaml.ScalarNode): + value: Any = loader.construct_scalar(node) + elif isinstance(node, yaml.SequenceNode): + value = loader.construct_sequence(node, deep=True) + else: + value = loader.construct_mapping(node, deep=True) + return {"__tag__": tag_suffix.lstrip("!"), "value": value} + + +_CfnLoader.add_multi_constructor("!", _intrinsic) + + +def _load(path: Path) -> dict[str, Any]: + # Through the repo's helper rather than a direct call with an explicit + # loader: the two parse identically, but this keeps the safe base class as + # the only construction path and leaves nothing for a scanner that keys on + # the call name and cannot see that the loader subclasses SafeLoader. + return load_with(_CfnLoader, path.read_text(encoding="utf-8")) + + +def _render(node: Any, crew: str = SAMPLE_CREW) -> str: + """The literal a ``!Sub`` scalar produces once ``${Crew}`` is substituted.""" + if isinstance(node, str): + return node + assert isinstance(node, dict) and node.get("__tag__") == "Sub", node + text = node["value"] + assert isinstance(text, str), text + return text.replace("${Crew}", crew) + + +def _walk(node: Any) -> Any: + """Every mapping in a nested document, so a statement cannot hide in a branch. + + Walking beats reading named fields for the same reason ``identity.py`` walks a + task definition: a policy moved into an ``!If`` branch, or a statement added + under a new logical id, is covered without anyone extending a list here. + """ + if isinstance(node, dict): + yield node + for value in node.values(): + yield from _walk(value) + elif isinstance(node, (list, tuple)): + for value in node: + yield from _walk(value) + + +def _statement_actions(mapping: dict[str, Any]) -> list[str]: + """The actions one statement grants, as a list whether written as one or many.""" + action = mapping["Action"] + return [action] if isinstance(action, str) else list(action) + + +def _actions(document: dict[str, Any]) -> list[str]: + """Every IAM action string anywhere in the document.""" + found: list[str] = [] + for mapping in _walk(document): + if "Action" not in mapping or "Effect" not in mapping: + continue # a mapping with Action but no Effect is not a statement + found.extend(_statement_actions(mapping)) + return found + + +def _role(document: dict[str, Any], logical_id: str) -> dict[str, Any]: + resource = document["Resources"][logical_id] + assert resource["Type"] == "AWS::IAM::Role", resource["Type"] + return resource["Properties"] + + +def _pattern(document: dict[str, Any], parameter: str) -> str: + return document["Parameters"][parameter]["AllowedPattern"] + + +# -------------------------------------------------------------------------- +# The templates must be loadable at all. Every other test depends on it, so it +# is asserted once rather than being the incidental cause of seven failures. +# -------------------------------------------------------------------------- + + +@pytest.mark.parametrize("path", [BASE, CREW], ids=["base", "crew"]) +def test_template_parses_and_declares_resources(path: Path) -> None: + document = _load(path) + assert document["AWSTemplateFormatVersion"] == "2010-09-09" + assert document["Resources"], f"{path.name} declares no resources" + + +# -------------------------------------------------------------------------- +# Names: derived on the code side, mirrored here. +# -------------------------------------------------------------------------- + + +def test_role_names_are_exactly_what_identity_derives() -> None: + document = _load(CREW) + expected_exec = execution_role_arn(SAMPLE_BINDING).rsplit("/", 1)[1] + expected_task = task_role_arn(SAMPLE_BINDING).rsplit("/", 1)[1] + + assert _render(_role(document, "ExecutionRole")["RoleName"]) == expected_exec + assert _render(_role(document, "TaskRole")["RoleName"]) == expected_task + + +def test_log_group_name_is_exactly_what_identity_derives() -> None: + document = _load(CREW) + log_group = document["Resources"]["LogGroup"]["Properties"]["LogGroupName"] + assert _render(log_group) == log_group_name(SAMPLE_BINDING) + + +def test_the_crew_parameter_admits_exactly_the_crew_names_identity_admits() -> None: + """A behavioural comparison, not a string compare of two regexes. + + Two patterns can be spelled differently and mean the same thing, and can be + spelled almost identically and differ on the case that matters -- a trailing + hyphen, which would derive the role name ``kirocrew-crew-demo--exec``. + """ + template_pattern = re.compile(f"^(?:{_pattern(_load(CREW), 'Crew')})$".replace("^^", "^")) + candidates = [ + "demo", + "a", + "0", + "crew-with-inner-hyphens", + "trailing-", + "-leading", + "UPPER", + "under_score", + "", + "a" * 32, + "a" * 33, + "a--b", + ] + for candidate in candidates: + mine = bool(template_pattern.fullmatch(candidate)) + theirs = bool(_CREW_RE.fullmatch(candidate)) + assert ( + mine == theirs + ), f"{candidate!r}: template says {mine}, identity._CREW_RE says {theirs}" + + +# -------------------------------------------------------------------------- +# Security properties. +# -------------------------------------------------------------------------- + + +def test_the_task_role_can_read_no_secret() -> None: + properties = _role(_load(CREW), "TaskRole") + assert "Policies" not in properties, "the task role is meant to carry no policy at all" + assert "ManagedPolicyArns" not in properties + # Case-INSENSITIVE on purpose. The managed policy that would grant this is + # spelled ``SecretsManagerReadWrite``, so a lower-case substring check reads + # straight past the most likely way someone grants it. + rendered = yaml.dump(properties).lower() + assert "secretsmanager" not in rendered, ( + "the task role must never reach Secrets Manager: the credential is already in the " + "container's environment, and a turn that could re-read it could read every crew's" + ) + + +@pytest.mark.parametrize("logical_id", ["ExecutionRole", "TaskRole"], ids=["exec", "task"]) +def test_each_role_is_assumable_only_on_behalf_of_this_account(logical_id: str) -> None: + """Both roles trust ``ecs-tasks`` narrowed by ``aws:SourceAccount``. + + Without the condition the trust policy names a SERVICE, not a caller, so the + role is assumable on behalf of any task in any account that ECS will act + for -- the confused-deputy shape. The template says this in a comment, and a + comment asserting what the adjacent document does not do is this line's + recurring defect, so it is asserted here instead. + """ + statements = _role(_load(CREW), logical_id)["AssumeRolePolicyDocument"]["Statement"] + assert len(statements) == 1, f"expected one trust statement, found {len(statements)}" + statement = statements[0] + + principal = statement["Principal"] + assert principal == {"Service": "ecs-tasks.amazonaws.com"}, principal + + condition = statement.get("Condition") + assert condition, f"{logical_id} trusts the service with no condition at all" + source_account = condition["StringEquals"]["aws:SourceAccount"] + assert ( + isinstance(source_account, dict) and source_account.get("__tag__") == "Ref" + ), f"{logical_id} pins aws:SourceAccount to {source_account!r} rather than this account" + assert source_account["value"] == "AWS::AccountId", source_account["value"] + + +def test_no_action_anywhere_is_a_prefix_wildcard() -> None: + for path in (BASE, CREW): + for action in _actions(_load(path)): + assert "*" not in action, ( + f"{path.name} grants {action!r}; a prefix admits the very calls the " + "enumeration exists to exclude" + ) + + +@pytest.mark.parametrize("path", [BASE, CREW], ids=["base", "crew"]) +def test_no_statement_inverts_the_enumeration(path: Path) -> None: + """No ``NotAction`` or ``NotResource`` anywhere. + + Either one turns an allow-list into a deny-list, so an ``Allow`` naming three + excluded actions grants every other call in the service -- the same reach as + the prefix wildcard the test above forbids, spelled in a way that check reads + straight past because it collects only ``Action``. + """ + for mapping in _walk(_load(path)): + if "Effect" not in mapping: + continue + for inverted in ("NotAction", "NotResource"): + assert inverted not in mapping, ( + f"{path.name} has a statement using {inverted}, which grants everything " + "it does not name" + ) + + +def test_the_execution_roles_secret_read_is_scoped_to_one_crew() -> None: + document = _load(CREW) + reads = [ + mapping + for mapping in _walk(_role(document, "ExecutionRole")) + if "Action" in mapping and "secretsmanager:GetSecretValue" in _statement_actions(mapping) + ] + assert len(reads) == 1, f"expected exactly one secret-read statement, found {len(reads)}" + + resources = reads[0]["Resource"] + resources = [resources] if not isinstance(resources, list) else resources + assert resources, "the secret read names no resource" + for resource in resources: + rendered = _render(resource) + assert f"secret:{SECRET_NAME_PREFIX}{SAMPLE_CREW}/" in rendered, ( + f"{rendered!r} is not scoped to this crew's secret namespace, so the role " + "could read a sibling crew's secret" + ) + + +def test_the_boundary_parameter_admits_only_empty_or_the_one_boundary() -> None: + """Empty is the declared degraded mode; anything else must be the one policy. + + A widened pattern is how a boundary stops being a ceiling: an operator could + pass a policy they authored, and the role's effective permissions would be + capped by nothing meaningful. + """ + pattern = re.compile(_pattern(_load(CREW), "PermissionsBoundaryArn")) + account = "123456789012" + assert pattern.fullmatch("") + assert pattern.fullmatch(f"arn:aws:iam::{account}:policy/kirocrew-crew-boundary") + for rejected in ( + f"arn:aws:iam::{account}:policy/anything-else", + f"arn:aws:iam::{account}:policy/kirocrew-crew-boundary-2", + f"arn:aws:iam::{account}:policy/AdministratorAccess", + "arn:aws:iam::123:policy/kirocrew-crew-boundary", + ): + assert not pattern.fullmatch(rejected), f"{rejected!r} should not be accepted" + + +def test_both_arn_patterns_accept_exactly_the_partitions_identity_accepts() -> None: + """Both ARN parameters must admit every partition ``CrewBinding`` admits. + + Compared against ``identity._PARTITION_RE`` candidate by candidate rather than + by restating its alternation here: a second copy of another module's table + drifts silently, and this drift would only surface when somebody in that + partition tried to deploy. A pattern admitting ``aws`` alone rejects a valid + ``aws-cn`` or ``aws-us-gov`` ARN at CloudFormation parameter validation, so the + per-crew stack cannot deploy in those partitions at all -- while the resources + inside the template are already partition-correct, because they build every ARN + from ``${AWS::Partition}``. + """ + document = _load(CREW) + boundary = re.compile(_pattern(document, "PermissionsBoundaryArn")) + ecr = re.compile(_pattern(document, "EcrRepositoryArn")) + account = "123456789012" + + for partition in ( + "aws", + "aws-cn", + "aws-us-gov", + "aws-iso", + "aws-iso-b", + "AWS", + "aws_cn", + "aws-", + "gcp", + "", + ): + identity_accepts = bool(_PARTITION_RE.fullmatch(partition)) + boundary_arn = f"arn:{partition}:iam::{account}:policy/kirocrew-crew-boundary" + ecr_arn = f"arn:{partition}:ecr:us-east-1:{account}:repository/kirocrew-crew" + assert bool(boundary.fullmatch(boundary_arn)) == identity_accepts, ( + f"PermissionsBoundaryArn and identity._PARTITION_RE disagree on partition " + f"{partition!r} (identity accepts it: {identity_accepts})" + ) + assert bool(ecr.fullmatch(ecr_arn)) == identity_accepts, ( + f"EcrRepositoryArn and identity._PARTITION_RE disagree on partition " + f"{partition!r} (identity accepts it: {identity_accepts})" + ) + + +def test_the_shared_security_group_has_no_ingress() -> None: + """No inbound at all: a crew is reached outbound-authenticated. + + An ingress rule added here is the difference between a crew reachable by its + owner and one reachable by the internet, and it would not fail any functional + check. + """ + properties = _load(BASE)["Resources"]["TaskSecurityGroup"]["Properties"] + assert "SecurityGroupIngress" not in properties + assert properties["SecurityGroupEgress"], "the task must still be able to pull its image" + + +# -------------------------------------------------------------------------- +# The outputs are the launch spec's configuration home, so their KEYS are the +# contract a later change reads. A renamed or dropped output is a stack that +# deploys and a launcher that finds nothing. +# -------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("path", "expected"), + [ + ( + BASE, + { + "ClusterName", + "ClusterArn", + "SecurityGroupId", + "SubnetIds", + "CpuArchitecture", + "Region", + "StackTag", + }, + ), + ( + CREW, + { + "Crew", + "ExecutionRoleArn", + "TaskRoleArn", + "LogGroupName", + "SecretNamePrefix", + "SecretArnPattern", + }, + ), + ], + ids=["base", "crew"], +) +def test_every_output_the_launch_spec_reads_is_present(path: Path, expected: set[str]) -> None: + """Equality, not containment, in both directions. + + A subset check would pass a dropped output, and asserting only presence would + let an output be quietly added without anyone naming what reads it. Every + output here is one the launch spec or an operator consumes. + """ + declared = set(_load(path)["Outputs"]) + assert declared == expected, ( + f"{path.name} outputs {sorted(declared)}; " + f"missing {sorted(expected - declared)}, unexpected {sorted(declared - expected)}" + ) + for key in sorted(declared): + assert _load(path)["Outputs"][key].get("Value") is not None, f"{key} declares no Value" + + +def test_the_architecture_parameter_admits_exactly_what_taskdef_admits() -> None: + """The template's AllowedValues and ``CPU_ARCHITECTURES`` are one set. + + Compared by importing that frozenset rather than by restating its members, so + adding an architecture on the code side without offering it here -- or offering + one here that ``_refuse_unknown_architecture`` rejects -- reds. The second + direction is the one that would otherwise ship: the stack would deploy and the + crew would never start. + """ + allowed = _load(BASE)["Parameters"]["CpuArchitecture"]["AllowedValues"] + assert set(allowed) == set( + CPU_ARCHITECTURES + ), f"template offers {sorted(allowed)}, taskdef accepts {sorted(CPU_ARCHITECTURES)}" + + +def test_the_secret_arn_output_is_exactly_the_execution_roles_grant() -> None: + """The advertised ARN pattern and the granted one must be the same string. + + Two places state this pattern, so they can disagree: widening the policy + without the output hides the reach, and widening the output without the policy + sends a caller after a secret the execution role cannot fetch. Rendered with + the same crew on both sides, so only a real divergence reds. + """ + document = _load(CREW) + advertised = _render(document["Outputs"]["SecretArnPattern"]["Value"]) + + granted = [ + mapping["Resource"] + for mapping in _walk(_role(document, "ExecutionRole")) + if "Action" in mapping and "secretsmanager:GetSecretValue" in _statement_actions(mapping) + ] + assert len(granted) == 1, f"expected one secret-read statement, found {len(granted)}" + resources = granted[0] if isinstance(granted[0], list) else [granted[0]] + assert [_render(resource) for resource in resources] == [advertised], ( + f"output advertises {advertised!r}, policy grants " + f"{[_render(resource) for resource in resources]!r}" + )