feat: scope opt-in console IAM for managed fleets
Managed fleets 2b-1 Task 5. Off by default; nothing is applied. - region-host: managed_fleets_enabled (default false) adds one inline policy, host_managed_fleets, to the existing host role. EC2 launch is split by resource type: approved images, subnets and groups; ENIs in approved subnets; volumes and per-region instances requiring the four identity tags, IMDSv2, hop limit 1 and no instance profile. CreateTags only at RunInstances. Terminate and console output need the exact deployment tag and all four identity tags, so region hosts are out. - S3 create/configure/readback on the fleet prefix only, with an explicit Deny of those writes on the deployment and data buckets (no Get or DeleteObject deny). IAM user grants on the fleet path only; CreateUser and PutUserPolicy need the exact boundary. - The store boundary is shared: created for either feature, statements concatenated, app-only rendering byte-identical. Fleet statements are the fleet-data policy over the prefix. - Validation refuses empty or wildcard identity and network, bad regions, cross-region IDs, root or overlapping user paths, and prefixes that are long, wildcard, cover own buckets or overlap the store prefix. A precondition refuses a role over IAM's 10,240-character inline total. - Exact fixtures in internal/awsmanaged/testdata, compared by the tofu test and pinned structurally by TestManagedFleetRenderedPolicyIsolation.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+2,053
−13
infra/modules/region-host/main.tf+27 −13infra/modules/region-host/managed_fleets.tf+311 −0infra/modules/region-host/outputs.tf+15 −0infra/modules/region-host/tests/managed_fleets.tftest.hcl+638 −0infra/modules/region-host/variables.tf+114 −0internal/awsmanaged/infra_policy_test.go+657 −0internal/awsmanaged/testdata/managed-boundary-policy.json+62 −0internal/awsmanaged/testdata/managed-console-policy.json+229 −0
diff --git a/infra/modules/region-host/main.tf b/infra/modules/region-host/main.tf| index b4184ede6..535ebb02c 100644 |
| --- a/infra/modules/region-host/main.tf |
| +++ b/infra/modules/region-host/main.tf |
| @@ -691,24 +691,38 @@ data "aws_caller_identity" "current" {} |
| # that may CreateUser and PutUserPolicy can mint a principal wider than |
| # itself, and scoping those calls to an IAM path does not help, because a path |
| # says which user is made and nothing about what it may do. |
| +# |
| +# Managed fleet users (managed_fleets.tf) are made under this same boundary, |
| +# so it exists when either feature is on. Its statements are concatenated: |
| +# the object-storage pair only with a store prefix, the fleet statements only |
| +# with managed fleets, so an object-storage-only deployment renders it byte |
| +# for byte as before. Name and description stay fixed: changing either |
| +# replaces a policy every existing store user is bound to. |
| +locals { |
| + store_boundary_statements = [ |
| + { |
| + Effect = "Allow" |
| + Action = ["s3:ListBucket", "s3:GetBucketLocation"] |
| + Resource = "arn:aws:s3:::${var.store_bucket_prefix}*" |
| + }, |
| + { |
| + Effect = "Allow" |
| + Action = ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"] |
| + Resource = "arn:aws:s3:::${var.store_bucket_prefix}*/*" |
| + }, |
| + ] |
| +} |
| + |
| resource "aws_iam_policy" "store_user_boundary" { |
| - count = var.store_bucket_prefix == "" ? 0 : 1 |
| + count = var.store_bucket_prefix != "" || var.managed_fleets_enabled ? 1 : 0 |
| name = "${var.iam_name}-store-boundary" |
| description = "Permissions ceiling for CARLOS object-store users. Intersected with each user's inline policy, which narrows it to that user's one bucket." |
| policy = jsonencode({ |
| Version = "2012-10-17" |
| - Statement = [ |
| - { |
| - Effect = "Allow" |
| - Action = ["s3:ListBucket", "s3:GetBucketLocation"] |
| - Resource = "arn:aws:s3:::${var.store_bucket_prefix}*" |
| - }, |
| - { |
| - Effect = "Allow" |
| - Action = ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"] |
| - Resource = "arn:aws:s3:::${var.store_bucket_prefix}*/*" |
| - }, |
| - ] |
| + Statement = concat( |
| + [for st in local.store_boundary_statements : st if var.store_bucket_prefix != ""], |
| + [for st in local.managed_boundary_statements : st if var.managed_fleets_enabled], |
| + ) |
| }) |
| } |
diff --git a/infra/modules/region-host/managed_fleets.tf b/infra/modules/region-host/managed_fleets.tf| new file mode 100644 |
| index 000000000..53da2f65c |
| --- /dev/null |
| +++ b/infra/modules/region-host/managed_fleets.tf |
| @@ -0,0 +1,311 @@ |
| +# ---- managed fleets: the console's AWS authority (issue #457 phase 2b-1) ---- |
| +# |
| +# Everything here exists only when managed_fleets_enabled is true, and only on |
| +# the console host's existing role: no new role, instance profile, pass-role, |
| +# security group, subnet or SSM path. The calls it covers are exactly the ones |
| +# internal/awsmanaged makes: |
| +# |
| +# compute.go RunInstances (launch-time tags), DescribeInstances, |
| +# DescribeImages, TerminateInstances, GetConsoleOutput |
| +# (Latest=true is a parameter of the same action) |
| +# storage.go CreateBucket with tags, then location, tags, versioning, |
| +# encryption, public access block and lifecycle, each read |
| +# and, on a proven bucket, written |
| +# credentials.go the fleet user's lifecycle under managed_fleet_user_path |
| +# |
| +# A fleet user is made under the shared boundary (aws_iam_policy. |
| +# store_user_boundary, main.tf), whose fleet statements below are its |
| +# fleet-data policy (internal/awsmanaged/policy.go) over the bucket prefix. |
| +# The user's own inline policy narrows that to one bucket and denies the rest. |
| +# |
| +# The rendered documents are pinned in internal/awsmanaged/testdata |
| +# (managed-console-policy.json, managed-boundary-policy.json) by |
| +# tests/managed_fleets.tftest.hcl, and their shape by |
| +# TestManagedFleetRenderedPolicyIsolation. Neither is a live IAM verdict. |
| +# |
| +# Read scope, stated plainly: host_buckets already allows ec2:DescribeInstances |
| +# on "*" in every region for the infrastructure inventory. The region-bound |
| +# Describe statement here does not narrow that; it adds DescribeImages and |
| +# says which regions this grant is for. |
| + |
| +locals { |
| + managed_account = data.aws_caller_identity.current.account_id |
| + managed_regions = sort(keys(var.managed_fleets_regions)) |
| + managed_identity_tags = ["carlos:deployment", "carlos:fleet", "carlos:label", "carlos:operation"] |
| + managed_bucket_arn = "arn:aws:s3:::${var.managed_fleet_bucket_prefix}*" |
| + managed_user_arn = "arn:aws:iam::${local.managed_account}:user${var.managed_fleet_user_path}*" |
| + |
| + managed_subnet_arns = flatten([ |
| + for r in local.managed_regions : [ |
| + for s in sort(tolist(var.managed_fleets_regions[r].subnets)) : "arn:aws:ec2:${r}:${local.managed_account}:subnet/${s}" |
| + ] |
| + ]) |
| + managed_group_arns = flatten([ |
| + for r in local.managed_regions : [ |
| + for g in sort(tolist(var.managed_fleets_regions[r].security_groups)) : "arn:aws:ec2:${r}:${local.managed_account}:security-group/${g}" |
| + ] |
| + ]) |
| + managed_instance_arns = [for r in local.managed_regions : "arn:aws:ec2:${r}:${local.managed_account}:instance/*"] |
| + |
| + # Tags a launch must put on what it creates: the exact deployment, nonempty |
| + # fleet, label and operation, and no other key. RunInstances evaluates |
| + # these on the instance and volume it creates; the network interface is not |
| + # tagged, so they are never placed on it. |
| + managed_launch_tag_like = { |
| + "aws:RequestTag/carlos:fleet" = "?*" |
| + "aws:RequestTag/carlos:label" = "?*" |
| + "aws:RequestTag/carlos:operation" = "?*" |
| + } |
| + managed_launch_tag_keys = { "aws:TagKeys" = local.managed_identity_tags } |
| + |
| + managed_console_statements = concat( |
| + [ |
| + { |
| + Sid = "ReadManagedRegions" |
| + Effect = "Allow" |
| + Action = ["ec2:DescribeImages", "ec2:DescribeInstances"] |
| + Resource = "*" |
| + Condition = { StringEquals = { "aws:RequestedRegion" = local.managed_regions } } |
| + }, |
| + # Image ARNs carry no account: an approved public AMI is named as an |
| + # image in its region, never as an account-owned resource. |
| + { |
| + Sid = "LaunchApprovedImages" |
| + Effect = "Allow" |
| + Action = ["ec2:RunInstances"] |
| + Resource = [for r in local.managed_regions : "arn:aws:ec2:${r}::image/${var.managed_fleets_regions[r].image}"] |
| + }, |
| + { |
| + Sid = "LaunchApprovedNetwork" |
| + Effect = "Allow" |
| + Action = ["ec2:RunInstances"] |
| + Resource = concat(local.managed_subnet_arns, local.managed_group_arns) |
| + }, |
| + # The box's one network interface is created in an approved subnet; the |
| + # condition also keeps an existing interface elsewhere out of reach. |
| + { |
| + Sid = "LaunchNetworkInterfaces" |
| + Effect = "Allow" |
| + Action = ["ec2:RunInstances"] |
| + Resource = [for r in local.managed_regions : "arn:aws:ec2:${r}:${local.managed_account}:network-interface/*"] |
| + Condition = { ArnEquals = { "ec2:Subnet" = local.managed_subnet_arns } } |
| + }, |
| + { |
| + Sid = "LaunchTaggedVolumes" |
| + Effect = "Allow" |
| + Action = ["ec2:RunInstances"] |
| + Resource = [for r in local.managed_regions : "arn:aws:ec2:${r}:${local.managed_account}:volume/*"] |
| + Condition = { |
| + StringEquals = { "aws:RequestTag/carlos:deployment" = var.managed_fleets_deployment } |
| + StringLike = local.managed_launch_tag_like |
| + "ForAllValues:StringEquals" = local.managed_launch_tag_keys |
| + } |
| + }, |
| + ], |
| + # One instance statement per region, because instance types are approved |
| + # per region. Type, IMDSv2, hop limit and the absent instance profile are |
| + # instance keys, so they sit here and nowhere else. |
| + [for r in local.managed_regions : { |
| + Sid = "LaunchInstances${join("", [for part in split("-", r) : title(part)])}" |
| + Effect = "Allow" |
| + Action = ["ec2:RunInstances"] |
| + Resource = ["arn:aws:ec2:${r}:${local.managed_account}:instance/*"] |
| + Condition = { |
| + StringEquals = { |
| + "aws:RequestTag/carlos:deployment" = var.managed_fleets_deployment |
| + "ec2:InstanceType" = sort(tolist(var.managed_fleets_regions[r].instance_types)) |
| + "ec2:MetadataHttpTokens" = "required" |
| + } |
| + NumericEquals = { "ec2:MetadataHttpPutResponseHopLimit" = "1" } |
| + StringLike = local.managed_launch_tag_like |
| + "ForAllValues:StringEquals" = local.managed_launch_tag_keys |
| + Null = { "ec2:InstanceProfile" = "true" } |
| + } |
| + }], |
| + [ |
| + # Tags only as part of RunInstances. No DeleteTags and no retagging of a |
| + # running box: its identity is fixed at launch. Which tags is not |
| + # repeated here: the same request's instance and volume statements |
| + # above already require exactly the four identity tags, and repeating |
| + # them costs inline policy space this role is short of. |
| + { |
| + Sid = "TagAtLaunchOnly" |
| + Effect = "Allow" |
| + Action = ["ec2:CreateTags"] |
| + Resource = flatten([for r in local.managed_regions : ["arn:aws:ec2:${r}:${local.managed_account}:instance/*", "arn:aws:ec2:${r}:${local.managed_account}:volume/*"]]) |
| + Condition = { StringEquals = { "ec2:CreateAction" = "RunInstances" } } |
| + }, |
| + # Only boxes carrying this deployment AND all four identity tags. A |
| + # region host (group.tf group_tags: deployment and region) lacks fleet, |
| + # label and operation, so this grant can neither stop it nor read it. |
| + { |
| + Sid = "ManagedBoxesOnly" |
| + Effect = "Allow" |
| + Action = ["ec2:GetConsoleOutput", "ec2:TerminateInstances"] |
| + Resource = local.managed_instance_arns |
| + Condition = { |
| + StringEquals = { "aws:ResourceTag/carlos:deployment" = var.managed_fleets_deployment } |
| + Null = { for k in local.managed_identity_tags : "aws:ResourceTag/${k}" => "false" } |
| + } |
| + }, |
| + # Bucket creation and setup, prefix-scoped. s3:TagResource is what |
| + # CreateBucket's tags need; there is no PutBucketTagging. No bucket |
| + # policy, no DeleteBucket and no object access: the console provisions |
| + # fleet buckets and never reads fleet data. |
| + { |
| + Sid = "FleetBuckets" |
| + Effect = "Allow" |
| + Action = [ |
| + "s3:CreateBucket", |
| + "s3:TagResource", |
| + "s3:GetBucketLocation", |
| + "s3:GetBucketTagging", |
| + "s3:GetBucketVersioning", |
| + "s3:PutBucketVersioning", |
| + "s3:GetEncryptionConfiguration", |
| + "s3:PutEncryptionConfiguration", |
| + "s3:GetBucketPublicAccessBlock", |
| + "s3:PutBucketPublicAccessBlock", |
| + "s3:GetLifecycleConfiguration", |
| + "s3:PutLifecycleConfiguration", |
| + ] |
| + Resource = [local.managed_bucket_arn] |
| + }, |
| + # The deployment's own buckets are never created, tagged or |
| + # reconfigured through this grant, whatever prefix is chosen (the |
| + # variable refuses an overlapping one too). Writes only: every Get here |
| + # is one the inventory and host_buckets rely on, and s3:DeleteObject |
| + # must never be denied on these buckets (lease release, main.tf |
| + # host_store). |
| + { |
| + Sid = "NeverConfigureDeploymentBuckets" |
| + Effect = "Deny" |
| + Action = [ |
| + "s3:CreateBucket", |
| + "s3:TagResource", |
| + "s3:PutBucketVersioning", |
| + "s3:PutEncryptionConfiguration", |
| + "s3:PutBucketPublicAccessBlock", |
| + "s3:PutLifecycleConfiguration", |
| + ] |
| + Resource = concat([var.deployment_bucket_arn, var.data_bucket_arn], var.sibling_staging_arns) |
| + }, |
| + # The two calls that could mint a principal wider than this role, each |
| + # refused unless the user carries the boundary. Same rule as host_store. |
| + { |
| + Sid = "CreateBoundedFleetUsers" |
| + Effect = "Allow" |
| + Action = ["iam:CreateUser", "iam:PutUserPolicy"] |
| + Resource = [local.managed_user_arn] |
| + Condition = { StringEquals = { "iam:PermissionsBoundary" = one(aws_iam_policy.store_user_boundary[*].arn) } } |
| + }, |
| + # The drift reads, the key lifecycle and DeleteUser (kept for the later |
| + # approved cleanup; no runtime caller in 2b-1), all on the fleet path. |
| + # Deliberately absent: DeleteUserPolicy (2d), AttachUserPolicy, group |
| + # changes, login profiles, and any boundary or policy-version edit. |
| + { |
| + Sid = "ManageFleetUsers" |
| + Effect = "Allow" |
| + Action = [ |
| + "iam:GetUser", |
| + "iam:GetUserPolicy", |
| + "iam:ListUserPolicies", |
| + "iam:ListAttachedUserPolicies", |
| + "iam:ListGroupsForUser", |
| + "iam:ListAccessKeys", |
| + "iam:CreateAccessKey", |
| + "iam:DeleteAccessKey", |
| + "iam:DeleteUser", |
| + ] |
| + Resource = [local.managed_user_arn] |
| + }, |
| + ], |
| + ) |
| + |
| + # The fleet statements of the shared boundary: internal/awsmanaged's |
| + # fleet-data policy with its one bucket widened to the prefix. Nothing |
| + # more, so no fleet user can exceed what that policy would give it. |
| + managed_data_prefixes = ["instances/*", "moves/*", "move-snapshots/*"] |
| + managed_probe_prefix = "_carlos/probes/*" |
| + managed_secrets_object = "system/fleet-secrets-key.json" |
| + managed_boundary_statements = [ |
| + { |
| + Sid = "FleetBucket" |
| + Effect = "Allow" |
| + Action = ["s3:GetBucketLocation", "s3:ListBucket"] |
| + Resource = [local.managed_bucket_arn] |
| + }, |
| + { |
| + Sid = "FleetVersions" |
| + Effect = "Allow" |
| + Action = ["s3:ListBucketVersions"] |
| + Resource = [local.managed_bucket_arn] |
| + Condition = { StringLike = { "s3:prefix" = concat(local.managed_data_prefixes, [local.managed_probe_prefix, local.managed_secrets_object]) } } |
| + }, |
| + { |
| + Sid = "FleetData" |
| + Effect = "Allow" |
| + Action = [ |
| + "s3:GetObject", |
| + "s3:PutObject", |
| + "s3:DeleteObject", |
| + "s3:GetObjectVersion", |
| + "s3:AbortMultipartUpload", |
| + "s3:ListMultipartUploadParts", |
| + ] |
| + Resource = [for p in local.managed_data_prefixes : "${local.managed_bucket_arn}/${p}"] |
| + }, |
| + { |
| + Sid = "FleetProbes" |
| + Effect = "Allow" |
| + Action = ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"] |
| + Resource = ["${local.managed_bucket_arn}/${local.managed_probe_prefix}"] |
| + }, |
| + { |
| + Sid = "FleetKeyRead" |
| + Effect = "Allow" |
| + Action = ["s3:GetObject"] |
| + Resource = ["${local.managed_bucket_arn}/${local.managed_secrets_object}"] |
| + }, |
| + { |
| + Sid = "FleetKeyCreate" |
| + Effect = "Allow" |
| + Action = ["s3:PutObject"] |
| + Resource = ["${local.managed_bucket_arn}/${local.managed_secrets_object}"] |
| + Condition = { StringEquals = { "s3:if-none-match" = ["*"] } } |
| + }, |
| + ] |
| +} |
| + |
| +locals { |
| + managed_console_policy = jsonencode({ |
| + Version = "2012-10-17" |
| + Statement = local.managed_console_statements |
| + }) |
| + # Every other inline policy this role can carry in fixed mode. IAM caps |
| + # their total at 10,240 characters without whitespace (jsonencode writes |
| + # none), and the console host already carries most of them. |
| + host_inline_policies = concat( |
| + [aws_iam_role_policy.host_buckets.policy, aws_iam_role_policy.host_metrics.policy, aws_iam_role_policy.host_terminations.policy], |
| + aws_iam_role_policy.host_route53[*].policy, aws_iam_role_policy.host_steering[*].policy, |
| + aws_iam_role_policy.host_costexplorer[*].policy, aws_iam_role_policy.host_ssm_parameter_scope[*].policy, |
| + aws_iam_role_policy.host_release_key_deny[*].policy, aws_iam_role_policy.host_store[*].policy, |
| + aws_iam_role_policy.host_console_mail[*].policy, aws_iam_role_policy.host_store_scan[*].policy, |
| + aws_iam_role_policy.alert_publish[*].policy, |
| + ) |
| +} |
| + |
| +resource "aws_iam_role_policy" "host_managed_fleets" { |
| + count = var.managed_fleets_enabled ? 1 : 0 |
| + name = "${var.iam_name}-managed-fleets" |
| + role = aws_iam_role.host.id |
| + policy = local.managed_console_policy |
| + lifecycle { |
| + # Fail the plan, not the middle of an apply. Unknown lengths (a policy |
| + # naming a resource this apply creates) are checked at apply instead. |
| + precondition { |
| + condition = sum(concat([length(local.managed_console_policy)], [for p in local.host_inline_policies : length(p)])) <= 10240 |
| + error_message = "With the managed fleet grant this host role's inline policies exceed IAM's 10,240-character total. Name fewer managed fleet regions, subnets or security groups, or turn off a grant this host does not need." |
| + } |
| + } |
| +} |
diff --git a/infra/modules/region-host/outputs.tf b/infra/modules/region-host/outputs.tf| index d7d6e36b2..66e9b4f19 100644 |
| --- a/infra/modules/region-host/outputs.tf |
| +++ b/infra/modules/region-host/outputs.tf |
| @@ -77,3 +77,18 @@ output "group_boot_parameters" { |
| termination_queue_url = aws_ssm_parameter.group_queue[0].name |
| } : null |
| } |
| + |
| +output "managed_fleet_user_boundary_arn" { |
| + description = "ARN of the permissions boundary managed fleet users are created under: the same policy as store_user_boundary_arn, which holds the fleet statements while managed_fleets_enabled is true. Give it to the console as its fleet user boundary. Null when managed fleets are off." |
| + value = var.managed_fleets_enabled ? aws_iam_policy.store_user_boundary[0].arn : null |
| +} |
| + |
| +output "managed_fleet_user_path" { |
| + description = "IAM path managed fleet users are created under, for the console's fleet user path setting. Null when managed fleets are off." |
| + value = var.managed_fleets_enabled ? var.managed_fleet_user_path : null |
| +} |
| + |
| +output "managed_fleet_bucket_prefix" { |
| + description = "Bucket-name prefix managed fleet buckets are created under, for the console's fleet bucket prefix setting. Null when managed fleets are off." |
| + value = var.managed_fleets_enabled ? var.managed_fleet_bucket_prefix : null |
| +} |
diff --git a/infra/modules/region-host/tests/managed_fleets.tftest.hcl b/infra/modules/region-host/tests/managed_fleets.tftest.hcl| new file mode 100644 |
| index 000000000..18d8774e5 |
| --- /dev/null |
| +++ b/infra/modules/region-host/tests/managed_fleets.tftest.hcl |
| @@ -0,0 +1,638 @@ |
| +# Plan-time tests for the opt-in managed fleet grant on the console host role |
| +# (managed fleets phase 2b-1, issue #457). mock_provider means no AWS |
| +# account, no credentials and no live data source: every run is a plan, and |
| +# the rendered policies are compared with the checked-in fixtures that |
| +# internal/awsmanaged's TestManagedFleetRenderedPolicyIsolation also reads. |
| +# These are evidence of intent, not an AWS verdict on live authorization. |
| +mock_provider "aws" { |
| + mock_data "aws_region" { defaults = { region = "eu-west-1" } } |
| +} |
| + |
| +override_data { |
| + target = data.aws_vpcs.default |
| + values = { ids = ["vpc-0aaaaaaaaaaaaaaaa"] } |
| +} |
| + |
| +override_data { |
| + target = data.aws_caller_identity.current |
| + values = { account_id = "123456789012" } |
| +} |
| + |
| +override_data { |
| + target = data.aws_ami.debian_arm64 |
| + values = { id = "ami-0aaaaaaaaaaaaaaaa" } |
| +} |
| + |
| +override_data { |
| + target = data.aws_vpc.host |
| + values = { cidr_block = "10.0.0.0/16" } |
| +} |
| + |
| +# The termination queue's ARN feeds an EventBridge target, which the provider |
| +# validates as an ARN; the mock's random string is not one. |
| +override_resource { |
| + target = aws_sqs_queue.terminations |
| + values = { arn = "arn:aws:sqs:eu-west-1:123456789012:carlos-test-host-terminations" } |
| +} |
| + |
| +override_resource { |
| + target = aws_sns_topic.alerts |
| + values = { arn = "arn:aws:sns:eu-west-1:123456789012:carlos-test-ie-alerts" } |
| +} |
| + |
| +override_resource { |
| + target = aws_iam_policy.store_user_boundary |
| + values = { arn = "arn:aws:iam::123456789012:policy/carlos-test-host-store-boundary" } |
| +} |
| + |
| +variables { |
| + name = "carlos-test-ie" |
| + sg_description = "carlos test host" |
| + iam_name = "carlos-test-host" |
| + instance_type = "t4g.small" |
| + root_volume_size = 20 |
| + user_data = "#!/bin/sh\n" |
| + deployment_bucket_arn = "arn:aws:s3:::carlos-test-platform" |
| + data_bucket_arn = "arn:aws:s3:::carlos-test-ie" |
| + ssm_parameter_arn = "arn:aws:ssm:eu-west-1:123456789012:parameter/carlos/*" |
| + |
| + # The fixture inputs. Present but switched off, so the first run proves the |
| + # switch alone keeps everything out. |
| + managed_fleets_deployment = "production" |
| + managed_fleets_regions = { |
| + "eu-west-1" = { |
| + image = "ami-0123456789abcdef0" |
| + subnets = ["subnet-0123456789abcdef1", "subnet-0123456789abcdef0"] |
| + security_groups = ["sg-0123456789abcdef0"] |
| + instance_types = ["t4g.small", "t4g.medium"] |
| + } |
| + "us-east-1" = { |
| + image = "ami-0fedcba9876543210" |
| + subnets = ["subnet-0fedcba9876543210"] |
| + security_groups = ["sg-0fedcba9876543210"] |
| + instance_types = ["m7g.large"] |
| + } |
| + } |
| + managed_fleet_bucket_prefix = "carlos-fleet-" |
| +} |
| + |
| +run "off_by_default" { |
| + command = plan |
| + assert { |
| + condition = length(aws_iam_role_policy.host_managed_fleets) == 0 |
| + error_message = "managed_fleets_enabled defaults to false and must create no grant" |
| + } |
| + assert { |
| + condition = length(aws_iam_policy.store_user_boundary) == 0 |
| + error_message = "with object storage and managed fleets both off there is no boundary" |
| + } |
| + assert { |
| + condition = ( |
| + output.managed_fleet_user_boundary_arn == null && |
| + output.managed_fleet_user_path == null && |
| + output.managed_fleet_bucket_prefix == null && |
| + output.store_user_boundary_arn == null |
| + ) |
| + error_message = "every managed fleet output is null while the feature is off" |
| + } |
| +} |
| + |
| +run "off_with_module_defaults" { |
| + command = plan |
| + variables { |
| + managed_fleets_deployment = "" |
| + managed_fleets_regions = {} |
| + managed_fleet_bucket_prefix = "" |
| + } |
| + assert { |
| + condition = length(aws_iam_role_policy.host_managed_fleets) == 0 && length(aws_iam_policy.store_user_boundary) == 0 |
| + error_message = "the module defaults create no managed fleet grant and no boundary" |
| + } |
| +} |
| + |
| +# Object storage on, managed fleets off: the store boundary and the store |
| +# grant render byte for byte as they did before this change. |
| +run "store_only_unchanged" { |
| + command = plan |
| + variables { |
| + store_bucket_prefix = "carlos-store-test-" |
| + } |
| + assert { |
| + condition = length(aws_iam_role_policy.host_managed_fleets) == 0 |
| + error_message = "object storage alone must not create the managed fleet grant" |
| + } |
| + assert { |
| + condition = aws_iam_policy.store_user_boundary[0].policy == "{\"Statement\":[{\"Action\":[\"s3:ListBucket\",\"s3:GetBucketLocation\"],\"Effect\":\"Allow\",\"Resource\":\"arn:aws:s3:::carlos-store-test-*\"},{\"Action\":[\"s3:GetObject\",\"s3:PutObject\",\"s3:DeleteObject\"],\"Effect\":\"Allow\",\"Resource\":\"arn:aws:s3:::carlos-store-test-*/*\"}],\"Version\":\"2012-10-17\"}" |
| + error_message = "the object storage boundary changed" |
| + } |
| + assert { |
| + condition = aws_iam_policy.store_user_boundary[0].name == "carlos-test-host-store-boundary" && aws_iam_policy.store_user_boundary[0].description == "Permissions ceiling for CARLOS object-store users. Intersected with each user's inline policy, which narrows it to that user's one bucket." |
| + error_message = "the boundary's name or description changed, which would replace a policy every store user is bound to" |
| + } |
| + assert { |
| + condition = aws_iam_role_policy.host_store[0].policy == "{\"Statement\":[{\"Action\":[\"s3:CreateBucket\",\"s3:DeleteBucket\",\"s3:ListBucket\",\"s3:GetBucketLocation\"],\"Effect\":\"Allow\",\"Resource\":\"arn:aws:s3:::carlos-store-test-*\"},{\"Action\":[\"s3:DeleteObject\"],\"Effect\":\"Allow\",\"Resource\":\"arn:aws:s3:::carlos-store-test-*/*\"},{\"Action\":[\"s3:DeleteBucket\",\"s3:CreateBucket\"],\"Effect\":\"Deny\",\"Resource\":[\"arn:aws:s3:::carlos-test-platform\",\"arn:aws:s3:::carlos-test-platform/*\",\"arn:aws:s3:::carlos-test-ie\",\"arn:aws:s3:::carlos-test-ie/*\"]},{\"Action\":[\"iam:CreateUser\",\"iam:PutUserPolicy\"],\"Condition\":{\"StringEquals\":{\"iam:PermissionsBoundary\":\"arn:aws:iam::123456789012:policy/carlos-test-host-store-boundary\"}},\"Effect\":\"Allow\",\"Resource\":\"arn:aws:iam::123456789012:user/carlos-store/*\"},{\"Action\":[\"iam:GetUser\",\"iam:DeleteUser\",\"iam:DeleteUserPolicy\",\"iam:CreateAccessKey\",\"iam:DeleteAccessKey\",\"iam:ListAccessKeys\"],\"Effect\":\"Allow\",\"Resource\":\"arn:aws:iam::123456789012:user/carlos-store/*\"}],\"Version\":\"2012-10-17\"}" |
| + error_message = "the object storage grant changed" |
| + } |
| + assert { |
| + condition = output.store_user_boundary_arn == "arn:aws:iam::123456789012:policy/carlos-test-host-store-boundary" && output.managed_fleet_user_boundary_arn == null |
| + error_message = "object storage alone publishes the store boundary and no managed fleet boundary" |
| + } |
| +} |
| + |
| +# Managed fleets on, object storage off: the boundary is created for fleet |
| +# users and holds only fleet statements, and the console grant is exactly the |
| +# fixture. |
| +run "managed_only" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + } |
| + assert { |
| + condition = length(aws_iam_role_policy.host_managed_fleets) == 1 && aws_iam_role_policy.host_managed_fleets[0].name == "carlos-test-host-managed-fleets" |
| + error_message = "one grant, named <iam_name>-managed-fleets" |
| + } |
| + assert { |
| + condition = jsondecode(aws_iam_role_policy.host_managed_fleets[0].policy) == jsondecode(file("../../../internal/awsmanaged/testdata/managed-console-policy.json")) |
| + error_message = "the console grant differs from internal/awsmanaged/testdata/managed-console-policy.json" |
| + } |
| + assert { |
| + condition = length(aws_iam_policy.store_user_boundary) == 1 && jsondecode(aws_iam_policy.store_user_boundary[0].policy) == jsondecode(file("../../../internal/awsmanaged/testdata/managed-boundary-policy.json")) |
| + error_message = "the boundary differs from internal/awsmanaged/testdata/managed-boundary-policy.json" |
| + } |
| + assert { |
| + condition = alltrue([ |
| + for st in jsondecode(aws_iam_policy.store_user_boundary[0].policy).Statement : |
| + startswith(st.Sid, "Fleet") && alltrue([for r in flatten([st.Resource]) : startswith(r, "arn:aws:s3:::carlos-fleet-")]) |
| + ]) |
| + error_message = "with object storage off the boundary holds fleet statements only" |
| + } |
| + assert { |
| + condition = alltrue([ |
| + for doc in [aws_iam_role_policy.host_managed_fleets[0].policy, aws_iam_policy.store_user_boundary[0].policy] : |
| + alltrue([for st in jsondecode(doc).Statement : alltrue([ |
| + for r in flatten([st.Resource]) : !contains(["arn:aws:s3:::*", "arn:aws:s3:::*/*"], r) |
| + ])]) |
| + ]) |
| + error_message = "no statement may name every bucket" |
| + } |
| + assert { |
| + condition = alltrue([ |
| + for st in jsondecode(aws_iam_role_policy.host_managed_fleets[0].policy).Statement : |
| + st.Sid == "ReadManagedRegions" if contains(flatten([st.Resource]), "*") |
| + ]) |
| + error_message = "only the region-bound Describe statement may name Resource *" |
| + } |
| + assert { |
| + condition = ( |
| + output.managed_fleet_user_boundary_arn == "arn:aws:iam::123456789012:policy/carlos-test-host-store-boundary" && |
| + output.managed_fleet_user_path == "/carlos-managed-fleet/" && |
| + output.managed_fleet_bucket_prefix == "carlos-fleet-" && |
| + output.store_user_boundary_arn == null |
| + ) |
| + error_message = "managed fleet outputs name the shared boundary, the user path and the prefix; the store output stays null" |
| + } |
| +} |
| + |
| +run "enabled_shape" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + } |
| + # Instances and volumes made by RunInstances carry the exact deployment and |
| + # nonempty fleet, label and operation tags, and no other tag key. |
| + assert { |
| + condition = alltrue([ |
| + for st in jsondecode(aws_iam_role_policy.host_managed_fleets[0].policy).Statement : |
| + st.Condition.StringEquals["aws:RequestTag/carlos:deployment"] == "production" && |
| + st.Condition.StringLike == { |
| + "aws:RequestTag/carlos:fleet" = "?*" |
| + "aws:RequestTag/carlos:label" = "?*" |
| + "aws:RequestTag/carlos:operation" = "?*" |
| + } && |
| + st.Condition["ForAllValues:StringEquals"]["aws:TagKeys"] == ["carlos:deployment", "carlos:fleet", "carlos:label", "carlos:operation"] |
| + if contains(st.Action, "ec2:RunInstances") && anytrue([for r in st.Resource : can(regex(":(instance|volume)/", r))]) |
| + ]) |
| + error_message = "RunInstances must require the four identity tags on instances and volumes" |
| + } |
| + # Tags only at launch: CreateTags is conditioned on RunInstances and only |
| + # on the two resource types the launch tags. |
| + assert { |
| + condition = alltrue([ |
| + for st in jsondecode(aws_iam_role_policy.host_managed_fleets[0].policy).Statement : |
| + st.Condition.StringEquals["ec2:CreateAction"] == "RunInstances" && |
| + alltrue([for r in st.Resource : can(regex("^arn:aws:ec2:[a-z0-9-]+:123456789012:(instance|volume)/\\*$", r))]) |
| + if contains(st.Action, "ec2:CreateTags") |
| + ]) |
| + error_message = "CreateTags is allowed only inside RunInstances, on instances and volumes" |
| + } |
| + # Terminate and console output need the exact deployment and all four |
| + # identity tags present. |
| + assert { |
| + condition = alltrue([ |
| + for st in jsondecode(aws_iam_role_policy.host_managed_fleets[0].policy).Statement : |
| + st.Condition.StringEquals == { "aws:ResourceTag/carlos:deployment" = "production" } && |
| + st.Condition.Null == { |
| + "aws:ResourceTag/carlos:deployment" = "false" |
| + "aws:ResourceTag/carlos:fleet" = "false" |
| + "aws:ResourceTag/carlos:label" = "false" |
| + "aws:ResourceTag/carlos:operation" = "false" |
| + } |
| + if contains(st.Action, "ec2:TerminateInstances") || contains(st.Action, "ec2:GetConsoleOutput") |
| + ]) |
| + error_message = "TerminateInstances and GetConsoleOutput need the exact deployment and all four identity tags" |
| + } |
| + # A region host carries carlos:deployment and carlos:region only |
| + # (group.tf group_tags). It must lack a tag both actions require. |
| + assert { |
| + condition = alltrue([ |
| + for st in jsondecode(aws_iam_role_policy.host_managed_fleets[0].policy).Statement : |
| + !alltrue([for k, v in st.Condition.Null : contains(["carlos:deployment", "carlos:region"], trimprefix(k, "aws:ResourceTag/"))]) |
| + if contains(st.Action, "ec2:TerminateInstances") |
| + ]) |
| + error_message = "a deployment+region region host would satisfy the terminate grant" |
| + } |
| + # Launch constraints sit on the instance resource, the only one of the |
| + # RunInstances resource types that supports them. |
| + assert { |
| + condition = alltrue([ |
| + for st in jsondecode(aws_iam_role_policy.host_managed_fleets[0].policy).Statement : |
| + st.Condition.StringEquals["ec2:MetadataHttpTokens"] == "required" && |
| + st.Condition.NumericEquals["ec2:MetadataHttpPutResponseHopLimit"] == "1" && |
| + st.Condition.Null["ec2:InstanceProfile"] == "true" && |
| + length(st.Condition.StringEquals["ec2:InstanceType"]) > 0 |
| + if contains(st.Action, "ec2:RunInstances") && anytrue([for r in st.Resource : can(regex(":instance/", r))]) |
| + ]) |
| + error_message = "instance launches need IMDSv2, hop limit 1, no instance profile and an approved type" |
| + } |
| + assert { |
| + condition = alltrue([ |
| + for st in jsondecode(aws_iam_role_policy.host_managed_fleets[0].policy).Statement : |
| + !anytrue([for k in keys(try(st.Condition, {})) : true]) |
| + if contains(st.Action, "ec2:RunInstances") && anytrue([for r in st.Resource : can(regex(":(image|subnet|security-group)/", r))]) |
| + ]) |
| + error_message = "image, subnet and security group statements carry no condition (none of the instance or tag keys applies to them)" |
| + } |
| + assert { |
| + condition = alltrue(flatten([ |
| + for st in jsondecode(aws_iam_role_policy.host_managed_fleets[0].policy).Statement : [ |
| + for a in st.Action : |
| + !can(regex("^(iam:(CreateRole|PassRole|AttachUserPolicy|AttachRolePolicy|PutRolePolicy|PutUserPermissionsBoundary|DeleteUserPermissionsBoundary|UpdateUser|DeleteUserPolicy|CreatePolicyVersion|SetDefaultPolicyVersion|AddUserToGroup|CreateLoginProfile|UpdateLoginProfile|CreateInstanceProfile|AddRoleToInstanceProfile)|ssm:.*|ssmmessages:.*|ec2messages:.*|ec2:(DeleteTags|AssociateIamInstanceProfile|ReplaceIamInstanceProfileAssociation|ModifyInstanceAttribute|CreateSecurityGroup|AuthorizeSecurityGroupIngress|CreateSubnet|CreateVpc|CreateKeyPair|ImportKeyPair)|s3:(DeleteBucket|PutBucketPolicy|PutBucketTagging|DeleteObjectVersion|ListBucketMultipartUploads))$", a)) && !strcontains(a, "*") |
| + ] |
| + ])) |
| + error_message = "the grant holds no role, pass-role, profile, SSM, boundary edit, retagging or wildcard action" |
| + } |
| + assert { |
| + condition = anytrue([ |
| + for st in jsondecode(aws_iam_role_policy.host_managed_fleets[0].policy).Statement : |
| + st.Effect == "Allow" && contains(st.Action, "s3:CreateBucket") && contains(st.Action, "s3:TagResource") && st.Resource == ["arn:aws:s3:::carlos-fleet-*"] |
| + ]) |
| + error_message = "creating a tagged bucket needs s3:TagResource beside s3:CreateBucket, on the managed prefix" |
| + } |
| + # Explicit Deny on every bucket write action for the deployment and data |
| + # buckets, whatever prefix an operator picks. No read and no object |
| + # delete: the inventory reads and lease release depend on those. |
| + assert { |
| + condition = anytrue([ |
| + for st in jsondecode(aws_iam_role_policy.host_managed_fleets[0].policy).Statement : |
| + st.Effect == "Deny" && |
| + toset(st.Action) == toset(["s3:CreateBucket", "s3:TagResource", "s3:PutBucketVersioning", "s3:PutEncryptionConfiguration", "s3:PutBucketPublicAccessBlock", "s3:PutLifecycleConfiguration"]) && |
| + toset(st.Resource) == toset(["arn:aws:s3:::carlos-test-platform", "arn:aws:s3:::carlos-test-ie"]) |
| + ]) |
| + error_message = "the deployment and data buckets must be denied every fleet bucket write" |
| + } |
| + assert { |
| + condition = alltrue([ |
| + for st in jsondecode(aws_iam_role_policy.host_managed_fleets[0].policy).Statement : |
| + !anytrue([for a in st.Action : startswith(a, "s3:Get") || startswith(a, "s3:List") || startswith(a, "s3:DeleteObject")]) |
| + if st.Effect == "Deny" |
| + ]) |
| + error_message = "the Deny must spare reads and object deletes" |
| + } |
| +} |
| + |
| +run "existing_user_boundary" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + } |
| + assert { |
| + condition = alltrue([ |
| + for st in jsondecode(aws_iam_role_policy.host_managed_fleets[0].policy).Statement : |
| + st.Condition == { StringEquals = { "iam:PermissionsBoundary" = "arn:aws:iam::123456789012:policy/carlos-test-host-store-boundary" } } && |
| + st.Resource == ["arn:aws:iam::123456789012:user/carlos-managed-fleet/*"] |
| + if contains(st.Action, "iam:CreateUser") || contains(st.Action, "iam:PutUserPolicy") |
| + ]) |
| + error_message = "CreateUser and PutUserPolicy require the exact boundary, on the managed path in this account" |
| + } |
| + assert { |
| + condition = alltrue([ |
| + for st in jsondecode(aws_iam_role_policy.host_managed_fleets[0].policy).Statement : |
| + st.Resource == ["arn:aws:iam::123456789012:user/carlos-managed-fleet/*"] |
| + if anytrue([for a in st.Action : startswith(a, "iam:")]) |
| + ]) |
| + error_message = "every IAM action is held to the managed fleet user path" |
| + } |
| +} |
| + |
| +# Both features on, with every other console grant this role can carry: app |
| +# statements first, exactly as before, then the fleet statements. The full |
| +# host-role union is checked here. One managed region keeps the role inside |
| +# IAM's inline total (role_inline_limit below shows the refusal). |
| +run "policy_union" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + managed_fleets_regions = { |
| + "eu-west-1" = { |
| + image = "ami-0123456789abcdef0" |
| + subnets = ["subnet-0123456789abcdef0", "subnet-0123456789abcdef1"] |
| + security_groups = ["sg-0123456789abcdef0"] |
| + instance_types = ["t4g.small", "t4g.medium"] |
| + } |
| + } |
| + store_bucket_prefix = "carlos-store-test-" |
| + store_scanning = true |
| + enable_cost_explorer = true |
| + console_mail_from = "noreply@example.com" |
| + console_mail_region = "eu-west-1" |
| + route53_zone_ids = ["Z0123456789ABCDEFGHIJ"] |
| + steering_zone_ids = ["Z0123456789ABCDEFGHIJ"] |
| + steering_record_names = ["*.example.com"] |
| + alerts_email = "ops@example.com" |
| + } |
| + assert { |
| + condition = jsondecode(aws_iam_policy.store_user_boundary[0].policy).Statement == concat( |
| + [ |
| + { Effect = "Allow", Action = ["s3:ListBucket", "s3:GetBucketLocation"], Resource = "arn:aws:s3:::carlos-store-test-*" }, |
| + { Effect = "Allow", Action = ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"], Resource = "arn:aws:s3:::carlos-store-test-*/*" }, |
| + ], |
| + jsondecode(file("../../../internal/awsmanaged/testdata/managed-boundary-policy.json")).Statement, |
| + ) |
| + error_message = "with both features on the boundary is the unchanged app statements followed by the fleet fixture" |
| + } |
| + # No older grant on this role already allows a new fleet mutation, and the |
| + # ones they share with object storage stay on the disjoint store prefix and |
| + # path. |
| + assert { |
| + condition = alltrue(flatten([ |
| + for doc in [ |
| + aws_iam_role_policy.host_buckets.policy, aws_iam_role_policy.host_route53[0].policy, |
| + aws_iam_role_policy.host_steering[0].policy, aws_iam_role_policy.host_costexplorer[0].policy, |
| + aws_iam_role_policy.host_metrics.policy, aws_iam_role_policy.host_ssm_parameter_scope[0].policy, |
| + aws_iam_role_policy.host_release_key_deny[0].policy, aws_iam_role_policy.host_store[0].policy, |
| + aws_iam_role_policy.host_console_mail[0].policy, aws_iam_role_policy.host_store_scan[0].policy, |
| + aws_iam_role_policy.host_terminations.policy, aws_iam_role_policy.alert_publish[0].policy, |
| + ] : [ |
| + for st in jsondecode(doc).Statement : [ |
| + for a in flatten([st.Action]) : |
| + !contains(["*", "ec2:*", "s3:*", "iam:*"], a) && (st.Effect == "Deny" || ( |
| + !contains([ |
| + "ec2:RunInstances", "ec2:TerminateInstances", "ec2:CreateTags", "ec2:GetConsoleOutput", "ec2:DescribeImages", |
| + "s3:TagResource", "s3:GetBucketTagging", "s3:PutBucketVersioning", "s3:PutEncryptionConfiguration", |
| + "s3:PutBucketPublicAccessBlock", "s3:GetLifecycleConfiguration", "s3:PutLifecycleConfiguration", |
| + "iam:GetUserPolicy", "iam:ListUserPolicies", "iam:ListAttachedUserPolicies", "iam:ListGroupsForUser", |
| + ], a) && |
| + (!contains(["s3:CreateBucket", "iam:CreateUser", "iam:PutUserPolicy", "iam:GetUser", "iam:DeleteUser", "iam:CreateAccessKey", "iam:DeleteAccessKey", "iam:ListAccessKeys"], a) || |
| + alltrue([for r in flatten([st.Resource]) : contains(["arn:aws:s3:::carlos-store-test-*", "arn:aws:iam::123456789012:user/carlos-store/*"], r)])) |
| + )) |
| + ] |
| + ] |
| + ])) |
| + error_message = "an older grant on the host role reaches a new managed fleet mutation" |
| + } |
| + # Inventory reads that already exist stay broad. Named here so the union is |
| + # stated, not implied: the new grant does not narrow them. |
| + assert { |
| + condition = anytrue([ |
| + for st in jsondecode(aws_iam_role_policy.host_buckets.policy).Statement : |
| + contains(flatten([st.Action]), "ec2:DescribeInstances") && st.Resource == "*" && !can(st.Condition) |
| + ]) |
| + error_message = "the pre-existing inventory DescribeInstances on * is expected to remain; update the union story if it changed" |
| + } |
| + # IAM caps one role's inline policies at 10,240 characters in total. |
| + assert { |
| + condition = sum([ |
| + for doc in [ |
| + aws_iam_role_policy.host_buckets.policy, aws_iam_role_policy.host_route53[0].policy, |
| + aws_iam_role_policy.host_steering[0].policy, aws_iam_role_policy.host_costexplorer[0].policy, |
| + aws_iam_role_policy.host_metrics.policy, aws_iam_role_policy.host_ssm_parameter_scope[0].policy, |
| + aws_iam_role_policy.host_release_key_deny[0].policy, aws_iam_role_policy.host_store[0].policy, |
| + aws_iam_role_policy.host_console_mail[0].policy, aws_iam_role_policy.host_store_scan[0].policy, |
| + aws_iam_role_policy.host_terminations.policy, aws_iam_role_policy.alert_publish[0].policy, |
| + aws_iam_role_policy.host_managed_fleets[0].policy, |
| + ] : length(doc) |
| + ]) <= 10240 |
| + error_message = "the host role's inline policies together exceed IAM's 10,240-character limit" |
| + } |
| +} |
| + |
| +# The same console with four managed regions is over IAM's inline total: the |
| +# plan refuses rather than an apply failing half-way. |
| +run "role_inline_limit" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + managed_fleets_regions = { |
| + for i, r in ["eu-west-1", "eu-central-1", "us-east-1", "us-west-2"] : r => { |
| + image = "ami-0123456789abcdef${i}" |
| + subnets = ["subnet-0123456789abcde${i}0", "subnet-0123456789abcde${i}1"] |
| + security_groups = ["sg-0123456789abcde${i}0"] |
| + instance_types = ["t4g.small", "t4g.medium"] |
| + } |
| + } |
| + store_bucket_prefix = "carlos-store-test-" |
| + store_scanning = true |
| + enable_cost_explorer = true |
| + console_mail_from = "noreply@example.com" |
| + console_mail_region = "eu-west-1" |
| + route53_zone_ids = ["Z0123456789ABCDEFGHIJ"] |
| + steering_zone_ids = ["Z0123456789ABCDEFGHIJ"] |
| + steering_record_names = ["*.example.com"] |
| + alerts_email = "ops@example.com" |
| + } |
| + expect_failures = [aws_iam_role_policy.host_managed_fleets] |
| +} |
| + |
| +# ---- refused configurations: each fails the plan before any resource ---- |
| + |
| +run "bad_empty_deployment" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + managed_fleets_deployment = "" |
| + } |
| + expect_failures = [var.managed_fleets_deployment] |
| +} |
| + |
| +run "bad_wildcard_deployment" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + managed_fleets_deployment = "prod*" |
| + } |
| + expect_failures = [var.managed_fleets_deployment] |
| +} |
| + |
| +run "bad_no_regions" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + managed_fleets_regions = {} |
| + } |
| + expect_failures = [var.managed_fleets_regions] |
| +} |
| + |
| +run "bad_wildcard_region" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + managed_fleets_regions = { |
| + "*" = { image = "ami-0123456789abcdef0", subnets = ["subnet-0123456789abcdef0"], security_groups = ["sg-0123456789abcdef0"], instance_types = ["t4g.small"] } |
| + } |
| + } |
| + expect_failures = [var.managed_fleets_regions] |
| +} |
| + |
| +run "bad_wildcard_image" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + managed_fleets_regions = { |
| + "eu-west-1" = { image = "ami-*", subnets = ["subnet-0123456789abcdef0"], security_groups = ["sg-0123456789abcdef0"], instance_types = ["t4g.small"] } |
| + } |
| + } |
| + expect_failures = [var.managed_fleets_regions] |
| +} |
| + |
| +run "bad_empty_network" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + managed_fleets_regions = { |
| + "eu-west-1" = { image = "ami-0123456789abcdef0", subnets = [], security_groups = ["sg-0123456789abcdef0"], instance_types = ["t4g.small"] } |
| + } |
| + } |
| + expect_failures = [var.managed_fleets_regions] |
| +} |
| + |
| +run "bad_wildcard_security_group" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + managed_fleets_regions = { |
| + "eu-west-1" = { image = "ami-0123456789abcdef0", subnets = ["subnet-0123456789abcdef0"], security_groups = ["sg-*"], instance_types = ["t4g.small"] } |
| + } |
| + } |
| + expect_failures = [var.managed_fleets_regions] |
| +} |
| + |
| +run "bad_instance_type" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + managed_fleets_regions = { |
| + "eu-west-1" = { image = "ami-0123456789abcdef0", subnets = ["subnet-0123456789abcdef0"], security_groups = ["sg-0123456789abcdef0"], instance_types = ["t3.small"] } |
| + } |
| + } |
| + expect_failures = [var.managed_fleets_regions] |
| +} |
| + |
| +# A subnet or security group belongs to exactly one region, so the same ID |
| +# under two regions is wrong for one of them. |
| +run "bad_region_mismatch" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + managed_fleets_regions = { |
| + "eu-west-1" = { image = "ami-0123456789abcdef0", subnets = ["subnet-0123456789abcdef0"], security_groups = ["sg-0123456789abcdef0"], instance_types = ["t4g.small"] } |
| + "us-east-1" = { image = "ami-0fedcba9876543210", subnets = ["subnet-0123456789abcdef0"], security_groups = ["sg-0fedcba9876543210"], instance_types = ["t4g.small"] } |
| + } |
| + } |
| + expect_failures = [var.managed_fleets_regions] |
| +} |
| + |
| +run "bad_root_user_path" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + managed_fleet_user_path = "/" |
| + } |
| + expect_failures = [var.managed_fleet_user_path] |
| +} |
| + |
| +run "bad_wildcard_user_path" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + managed_fleet_user_path = "/carlos-*/" |
| + } |
| + expect_failures = [var.managed_fleet_user_path] |
| +} |
| + |
| +run "bad_overlapping_user_path" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + store_bucket_prefix = "carlos-store-test-" |
| + managed_fleet_user_path = "/carlos-store/fleets/" |
| + } |
| + expect_failures = [var.managed_fleet_user_path] |
| +} |
| + |
| +run "bad_empty_prefix" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + managed_fleet_bucket_prefix = "" |
| + } |
| + expect_failures = [var.managed_fleet_bucket_prefix] |
| +} |
| + |
| +run "bad_wildcard_prefix" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + managed_fleet_bucket_prefix = "carlos-*" |
| + } |
| + expect_failures = [var.managed_fleet_bucket_prefix] |
| +} |
| + |
| +# 25 characters: one over the cap that keeps a fleet user's inline policy |
| +# inside IAM's 2,048-character limit (internal/awsmanaged bucketPrefixRE). |
| +run "bad_long_prefix" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + managed_fleet_bucket_prefix = "carlos-fleet-abcdefghijkl" |
| + } |
| + expect_failures = [var.managed_fleet_bucket_prefix] |
| +} |
| + |
| +run "bad_prefix_covers_deployment_bucket" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + managed_fleet_bucket_prefix = "carlos-test-" |
| + } |
| + expect_failures = [var.managed_fleet_bucket_prefix] |
| +} |
| + |
| +run "bad_prefix_overlaps_store_prefix" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + store_bucket_prefix = "carlos-store-test-" |
| + managed_fleet_bucket_prefix = "carlos-store-" |
| + } |
| + expect_failures = [var.managed_fleet_bucket_prefix] |
| +} |
| + |
| +run "bad_prefix_inside_store_prefix" { |
| + command = plan |
| + variables { |
| + managed_fleets_enabled = true |
| + store_bucket_prefix = "carlos-" |
| + managed_fleet_bucket_prefix = "carlos-fleet-" |
| + } |
| + expect_failures = [var.managed_fleet_bucket_prefix] |
| +} |
diff --git a/infra/modules/region-host/variables.tf b/infra/modules/region-host/variables.tf| index 4bbbd82db..259a094e3 100644 |
| --- a/infra/modules/region-host/variables.tf |
| +++ b/infra/modules/region-host/variables.tf |
| @@ -398,3 +398,117 @@ variable "group_transaction_open" { |
| error_message = "finish the open group maintenance transaction before planning or applying infrastructure" |
| } |
| } |
| + |
| +# ---- managed fleets (issue #457 phase 2b-1) --------------------------------- |
| +# |
| +# Off by default. Switching it on is a live IAM change on the console host |
| +# and needs its own approved plan; see managed_fleets.tf for the grant. |
| + |
| +variable "managed_fleets_enabled" { |
| + description = "Let this host's role launch and terminate managed fleet boxes and make each fleet's bucket and bounded IAM user (managed_fleets.tf). Off by default: without it the role gets no managed fleet grant at all. Set it only on the box that runs the console, in fixed mode, and only for a scoped, approved rollout." |
| + type = bool |
| + default = false |
| + nullable = false |
| + validation { |
| + condition = !var.managed_fleets_enabled || var.mode == "fixed" |
| + error_message = "managed_fleets_enabled is for the console host in fixed mode. A region group's boxes never launch managed fleet boxes." |
| + } |
| +} |
| + |
| +variable "managed_fleets_deployment" { |
| + description = "Deployment name managed fleet boxes are tagged with (carlos:deployment), the same value the console runs as. The grant only launches boxes carrying it and only terminates or reads boxes that already carry it. Required when managed_fleets_enabled is true." |
| + type = string |
| + default = "" |
| + nullable = false |
| + validation { |
| + condition = !var.managed_fleets_enabled || can(regex("^[a-z][a-z0-9-]{0,31}$", var.managed_fleets_deployment)) |
| + error_message = "managed_fleets_deployment must be this deployment's name: lowercase letters, digits and hyphens, starting with a letter, at most 32 characters, with no wildcards." |
| + } |
| +} |
| + |
| +variable "managed_fleets_regions" { |
| + description = "Regions managed fleet boxes may launch in, keyed by AWS region name. Each names the one approved arm64 image, the subnets and dedicated security groups a box may use, and the instance types allowed there. The grant names exactly these and nothing else. Required when managed_fleets_enabled is true." |
| + type = map(object({ |
| + image = string |
| + subnets = set(string) |
| + security_groups = set(string) |
| + instance_types = set(string) |
| + })) |
| + default = {} |
| + nullable = false |
| + validation { |
| + condition = !var.managed_fleets_enabled || length(var.managed_fleets_regions) > 0 |
| + error_message = "managed_fleets_regions must name at least one region when managed_fleets_enabled is true." |
| + } |
| + validation { |
| + condition = !var.managed_fleets_enabled || alltrue([ |
| + for region, cfg in var.managed_fleets_regions : |
| + can(regex("^[a-z]{2}(-[a-z]+)+-[0-9]{1,2}$", region)) && |
| + can(regex("^ami-([0-9a-f]{8}|[0-9a-f]{17})$", cfg.image)) && |
| + length(cfg.subnets) > 0 && alltrue([for s in cfg.subnets : can(regex("^subnet-([0-9a-f]{8}|[0-9a-f]{17})$", s))]) && |
| + length(cfg.security_groups) > 0 && length(cfg.security_groups) <= 16 && |
| + alltrue([for g in cfg.security_groups : can(regex("^sg-([0-9a-f]{8}|[0-9a-f]{17})$", g))]) && |
| + length(cfg.instance_types) > 0 && |
| + alltrue([for t in cfg.instance_types : can(regex("^([a-z]+[0-9]+(g|gd|gn|gen))\\.(nano|micro|small|medium|large|xlarge|(2|4|8|12|16|24|32|48|64|96|112)xlarge|metal)$", t))]) |
| + ]) |
| + error_message = "Each managed_fleets_regions entry needs an AWS region name as its key, one image ID (ami-...), at least one subnet ID (subnet-...), one to 16 security group IDs (sg-...) and at least one arm64 Graviton instance type. Wildcards are refused." |
| + } |
| + validation { |
| + condition = !var.managed_fleets_enabled || ( |
| + length(flatten([for cfg in values(var.managed_fleets_regions) : tolist(cfg.subnets)])) == length(distinct(flatten([for cfg in values(var.managed_fleets_regions) : tolist(cfg.subnets)]))) && |
| + length(flatten([for cfg in values(var.managed_fleets_regions) : tolist(cfg.security_groups)])) == length(distinct(flatten([for cfg in values(var.managed_fleets_regions) : tolist(cfg.security_groups)]))) |
| + ) |
| + error_message = "A subnet or security group belongs to one region, so the same ID cannot appear under two regions in managed_fleets_regions." |
| + } |
| +} |
| + |
| +variable "managed_fleet_bucket_prefix" { |
| + description = "Bucket-name prefix reserved for managed fleet buckets (each bucket is this prefix plus 24 hex characters), the console's fleet bucket prefix setting. The grant creates and configures buckets under it only. It must not cover the deployment or data buckets and must not overlap store_bucket_prefix. Required when managed_fleets_enabled is true." |
| + type = string |
| + default = "" |
| + nullable = false |
| + validation { |
| + condition = !var.managed_fleets_enabled || ( |
| + can(regex("^[a-z0-9][a-z0-9-]{0,23}$", var.managed_fleet_bucket_prefix)) && |
| + !startswith(var.managed_fleet_bucket_prefix, "xn--") && |
| + !startswith(var.managed_fleet_bucket_prefix, "sthree-") && |
| + !startswith(var.managed_fleet_bucket_prefix, "amzn-s3-demo-") |
| + ) |
| + error_message = "managed_fleet_bucket_prefix must be 1 to 24 lowercase letters, digits or hyphens, starting with a letter or digit, with no wildcards and no reserved S3 prefix. The cap keeps each fleet user's inline policy inside IAM's 2,048-character limit." |
| + } |
| + validation { |
| + condition = !var.managed_fleets_enabled || var.managed_fleet_bucket_prefix == "" || !anytrue([ |
| + for arn in concat([var.deployment_bucket_arn, var.data_bucket_arn], var.sibling_staging_arns) : |
| + startswith(trimprefix(arn, "arn:aws:s3:::"), var.managed_fleet_bucket_prefix) |
| + ]) |
| + error_message = "managed_fleet_bucket_prefix covers this deployment's own deployment, data or staging bucket. Choose a prefix none of them starts with." |
| + } |
| + validation { |
| + condition = !var.managed_fleets_enabled || var.store_bucket_prefix == "" || var.managed_fleet_bucket_prefix == "" || !( |
| + startswith(var.store_bucket_prefix, var.managed_fleet_bucket_prefix) || |
| + startswith(var.managed_fleet_bucket_prefix, var.store_bucket_prefix) |
| + ) |
| + error_message = "managed_fleet_bucket_prefix and store_bucket_prefix overlap. Neither may start with the other, so fleet buckets and object stores never share a name space." |
| + } |
| +} |
| + |
| +variable "managed_fleet_user_path" { |
| + description = "IAM path every managed fleet user lives under, the console's fleet user path setting. It scopes the role's user grant to fleet users only. It must differ from store_user_path and sit outside it." |
| + type = string |
| + default = "/carlos-managed-fleet/" |
| + nullable = false |
| + validation { |
| + condition = !var.managed_fleets_enabled || ( |
| + length(var.managed_fleet_user_path) <= 512 && |
| + can(regex("^/([A-Za-z0-9+=,.@_-]+/)+$", var.managed_fleet_user_path)) |
| + ) |
| + error_message = "managed_fleet_user_path must be an IAM path below the root, such as /carlos-managed-fleet/, with no wildcards." |
| + } |
| + validation { |
| + condition = !var.managed_fleets_enabled || !( |
| + startswith(var.managed_fleet_user_path, var.store_user_path) || |
| + startswith(var.store_user_path, var.managed_fleet_user_path) |
| + ) |
| + error_message = "managed_fleet_user_path overlaps store_user_path. Neither may contain the other, so object storage users and fleet users never share a grant." |
| + } |
| +} |
diff --git a/internal/awsmanaged/infra_policy_test.go b/internal/awsmanaged/infra_policy_test.go| new file mode 100644 |
| index 000000000..e3dde878c |
| --- /dev/null |
| +++ b/internal/awsmanaged/infra_policy_test.go |
| @@ -0,0 +1,657 @@ |
| +package awsmanaged |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "os" |
| + "path/filepath" |
| + "regexp" |
| + "slices" |
| + "sort" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/objstore" |
| +) |
| + |
| +// The rendered region-host IAM for managed fleets (infra/modules/region-host |
| +// managed_fleets.tf). The module's tofu test compares its actual plan output |
| +// with these same fixtures (ledger ruling P4); this test pins their shape. |
| +// It is structural: exact sets, ARN classes, required conditions and the |
| +// boundary as a prefix substitution of the fleet-data policy. It does not |
| +// evaluate IAM and says nothing about live authorization. |
| + |
| +const ( |
| + infraAccount = "123456789012" |
| + infraDeployment = "production" |
| + infraPrefix = "carlos-fleet-" |
| + infraUserPath = "/carlos-managed-fleet/" |
| + infraBoundaryARN = "arn:aws:iam::123456789012:policy/carlos-test-host-store-boundary" |
| + infraFleetBucket = "arn:aws:s3:::carlos-fleet-*" |
| + infraFleetUsers = "arn:aws:iam::123456789012:user/carlos-managed-fleet/*" |
| +) |
| + |
| +type infraRegion struct { |
| + image string |
| + subnets, groups, iTypes []string |
| +} |
| + |
| +// The tofu test's managed_fleets_regions, sorted as the module renders them. |
| +var infraRegions = map[string]infraRegion{ |
| + "eu-west-1": {image: "ami-0123456789abcdef0", subnets: []string{"subnet-0123456789abcdef0", "subnet-0123456789abcdef1"}, |
| + groups: []string{"sg-0123456789abcdef0"}, iTypes: []string{"t4g.medium", "t4g.small"}}, |
| + "us-east-1": {image: "ami-0fedcba9876543210", subnets: []string{"subnet-0fedcba9876543210"}, |
| + groups: []string{"sg-0fedcba9876543210"}, iTypes: []string{"m7g.large"}}, |
| +} |
| + |
| +// The deployment and data buckets of the tofu test. |
| +var infraProtected = []string{"arn:aws:s3:::carlos-test-platform", "arn:aws:s3:::carlos-test-ie"} |
| + |
| +// A region host carries deployment and region only (group.tf group_tags); |
| +// TestAWSComputeManagedTags shows ListDeployment drops it. |
| +var infraRegionHostTags = map[string]string{"carlos:deployment": infraDeployment, "carlos:region": "ie"} |
| + |
| +var infraIdentityTags = []string{tagDeployment, tagFleet, tagLabel, tagOperation} |
| + |
| +type infraValues []string |
| + |
| +func (v *infraValues) UnmarshalJSON(b []byte) error { |
| + var one string |
| + if err := json.Unmarshal(b, &one); err == nil { |
| + *v = infraValues{one} |
| + return nil |
| + } |
| + var many []string |
| + if err := json.Unmarshal(b, &many); err != nil { |
| + return err |
| + } |
| + *v = many |
| + return nil |
| +} |
| + |
| +type infraStatement struct { |
| + Sid string `json:"Sid"` |
| + Effect string `json:"Effect"` |
| + Action infraValues `json:"Action"` |
| + Resource infraValues `json:"Resource"` |
| + Condition map[string]map[string]infraValues `json:"Condition"` |
| +} |
| + |
| +type infraDoc struct { |
| + Version string `json:"Version"` |
| + Statement []infraStatement `json:"Statement"` |
| +} |
| + |
| +// loadInfraDoc decodes a fixture strictly: NotAction, NotResource or |
| +// Principal in a host or boundary document is a shape this test refuses. |
| +func loadInfraDoc(t *testing.T, name string) infraDoc { |
| + t.Helper() |
| + raw, err := os.ReadFile(filepath.Join("testdata", name)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + dec := json.NewDecoder(bytes.NewReader(raw)) |
| + dec.DisallowUnknownFields() |
| + var d infraDoc |
| + if err := dec.Decode(&d); err != nil { |
| + t.Fatalf("%s: %v", name, err) |
| + } |
| + if d.Version != "2012-10-17" || len(d.Statement) == 0 { |
| + t.Fatalf("%s: version %q, %d statements", name, d.Version, len(d.Statement)) |
| + } |
| + seen := map[string]bool{} |
| + for _, st := range d.Statement { |
| + if !regexp.MustCompile(`^[A-Za-z0-9]+$`).MatchString(st.Sid) || seen[st.Sid] { |
| + t.Fatalf("%s: Sid %q missing, invalid or repeated", name, st.Sid) |
| + } |
| + seen[st.Sid] = true |
| + if st.Effect != "Allow" && st.Effect != "Deny" || len(st.Action) == 0 || len(st.Resource) == 0 { |
| + t.Fatalf("%s: statement %s is incomplete", name, st.Sid) |
| + } |
| + } |
| + return d |
| +} |
| + |
| +func sortedCopy(v []string) []string { |
| + out := slices.Clone(v) |
| + sort.Strings(out) |
| + return out |
| +} |
| + |
| +func sameValues(a, b []string) bool { return slices.Equal(sortedCopy(a), sortedCopy(b)) } |
| + |
| +func infraRegionNames() []string { |
| + var out []string |
| + for r := range infraRegions { |
| + out = append(out, r) |
| + } |
| + sort.Strings(out) |
| + return out |
| +} |
| + |
| +// conditionKeys lists a statement's condition keys, reducing tag keys to |
| +// their family (aws:RequestTag/carlos:fleet -> aws:RequestTag/). |
| +func conditionKeys(st infraStatement) []string { |
| + var out []string |
| + for _, keys := range st.Condition { |
| + for k := range keys { |
| + for _, fam := range []string{"aws:RequestTag/", "aws:ResourceTag/"} { |
| + if strings.HasPrefix(k, fam) { |
| + k = fam |
| + } |
| + } |
| + out = append(out, k) |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// The condition keys the EC2 service authorization reference lists for each |
| +// resource type of the three actions, narrowed to the keys this grant could |
| +// use. A key on a statement whose resource type lacks it is a fixture error: |
| +// IAM would find it absent and refuse the launch, or ignore the bound. |
| +var ec2ConditionKeys = map[string]map[string][]string{ |
| + "ec2:RunInstances": { |
| + "image": {"aws:ResourceTag/", "ec2:ImageID", "ec2:Owner", "ec2:Public", "ec2:Region"}, |
| + "subnet": {"aws:ResourceTag/", "ec2:SubnetID", "ec2:Vpc", "ec2:Region", "ec2:AvailabilityZone"}, |
| + "security-group": {"aws:ResourceTag/", "ec2:SecurityGroupID", "ec2:Vpc", "ec2:Region"}, |
| + "network-interface": {"aws:RequestTag/", "aws:TagKeys", "ec2:Subnet", "ec2:Vpc", "ec2:AssociatePublicIpAddress", "ec2:Region"}, |
| + "volume": {"aws:RequestTag/", "aws:TagKeys", "ec2:Encrypted", "ec2:VolumeType", "ec2:VolumeSize", "ec2:Region"}, |
| + "instance": {"aws:RequestTag/", "aws:TagKeys", "ec2:InstanceType", "ec2:InstanceProfile", "ec2:MetadataHttpTokens", |
| + "ec2:MetadataHttpPutResponseHopLimit", "ec2:MetadataHttpEndpoint", "ec2:Region"}, |
| + }, |
| + "ec2:CreateTags": { |
| + "instance": {"aws:RequestTag/", "aws:ResourceTag/", "aws:TagKeys", "ec2:CreateAction", "ec2:Region"}, |
| + "volume": {"aws:RequestTag/", "aws:ResourceTag/", "aws:TagKeys", "ec2:CreateAction", "ec2:Region"}, |
| + }, |
| + "ec2:TerminateInstances": {"instance": {"aws:ResourceTag/", "ec2:Region"}}, |
| + "ec2:GetConsoleOutput": {"instance": {"aws:ResourceTag/", "ec2:Region"}}, |
| +} |
| + |
| +var ( |
| + ec2ImageARN = regexp.MustCompile(`^arn:aws:ec2:([a-z0-9-]+)::image/(.+)$`) |
| + ec2AccountARN = regexp.MustCompile(`^arn:aws:ec2:([a-z0-9-]+):([0-9]{12}):(instance|volume|network-interface|subnet|security-group)/(.+)$`) |
| +) |
| + |
| +// ec2Resource classifies an EC2 resource ARN and checks it against the |
| +// configured regions, images, subnets and groups. Created resources must be |
| +// a whole type in a configured region of this account; used resources must |
| +// be exactly a configured one. An image ARN has no account field. |
| +func ec2Resource(t *testing.T, sid, arn string) (kind, region string) { |
| + t.Helper() |
| + if m := ec2ImageARN.FindStringSubmatch(arn); m != nil { |
| + cfg, ok := infraRegions[m[1]] |
| + if !ok || m[2] != cfg.image { |
| + t.Errorf("%s: image %s is not the approved image of a configured region", sid, arn) |
| + } |
| + return "image", m[1] |
| + } |
| + m := ec2AccountARN.FindStringSubmatch(arn) |
| + if m == nil { |
| + t.Errorf("%s: %s is not a recognised EC2 resource ARN", sid, arn) |
| + return "", "" |
| + } |
| + cfg, ok := infraRegions[m[1]] |
| + if !ok || m[2] != infraAccount { |
| + t.Errorf("%s: %s is outside the configured regions or this account", sid, arn) |
| + } |
| + switch m[3] { |
| + case "subnet": |
| + if !slices.Contains(cfg.subnets, m[4]) { |
| + t.Errorf("%s: subnet %s is not approved in %s", sid, m[4], m[1]) |
| + } |
| + case "security-group": |
| + if !slices.Contains(cfg.groups, m[4]) { |
| + t.Errorf("%s: security group %s is not approved in %s", sid, m[4], m[1]) |
| + } |
| + default: |
| + if m[4] != "*" { |
| + t.Errorf("%s: created %s resources are named by type, got %s", sid, m[3], arn) |
| + } |
| + } |
| + return m[3], m[1] |
| +} |
| + |
| +func checkLaunchTags(t *testing.T, st infraStatement, keyFamily string) { |
| + t.Helper() |
| + if got := st.Condition["StringEquals"][keyFamily+tagDeployment]; !slices.Equal(got, []string{infraDeployment}) { |
| + t.Errorf("%s: %s%s is %v", st.Sid, keyFamily, tagDeployment, got) |
| + } |
| + for _, k := range infraIdentityTags[1:] { |
| + if got := st.Condition["StringLike"][keyFamily+k]; !slices.Equal(got, []string{"?*"}) { |
| + t.Errorf("%s: %s%s must be nonempty, got %v", st.Sid, keyFamily, k, got) |
| + } |
| + } |
| + if got := st.Condition["ForAllValues:StringEquals"]["aws:TagKeys"]; !sameValues(got, infraIdentityTags) { |
| + t.Errorf("%s: tag keys %v, want exactly the four identity keys", st.Sid, got) |
| + } |
| +} |
| + |
| +func TestManagedFleetRenderedPolicyIsolation(t *testing.T) { |
| + ctx := context.Background() |
| + |
| + // The fixture's inputs are a configuration the Task 4 adapter accepts, |
| + // and a fleet user and bucket it would make fall inside the grant. |
| + scfg := StorageConfig{Deployment: infraDeployment, AccountID: infraAccount, IAMRegion: "us-east-1", |
| + BucketPrefix: infraPrefix, UserPath: infraUserPath, BoundaryARN: infraBoundaryARN, Regions: infraRegionNames()} |
| + if err := validateStorageConfig(scfg); err != nil { |
| + t.Fatalf("fixture inputs are not a valid adapter configuration: %v", err) |
| + } |
| + if err := validateConfig(ComputeConfig{Deployment: infraDeployment, AccountID: infraAccount, Regions: infraRegionNames()}); err != nil { |
| + t.Fatalf("fixture inputs are not a valid compute configuration: %v", err) |
| + } |
| + bucketA, userA, err := fleetResourceNames(scfg, "shop") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + bucketB, _, err := fleetResourceNames(scfg, "shop-two") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if !strings.HasPrefix("arn:aws:s3:::"+bucketA, strings.TrimSuffix(infraFleetBucket, "*")) || |
| + !strings.HasPrefix("arn:aws:iam::"+infraAccount+":user"+infraUserPath+userA, strings.TrimSuffix(infraFleetUsers, "*")) { |
| + t.Fatalf("fleet bucket %s or user %s falls outside the grant", bucketA, userA) |
| + } |
| + for _, p := range infraProtected { |
| + if strings.HasPrefix(p, strings.TrimSuffix(infraFleetBucket, "*")) { |
| + t.Fatalf("protected bucket %s matches the fleet prefix", p) |
| + } |
| + } |
| + |
| + t.Run("console grant", func(t *testing.T) { |
| + doc := loadInfraDoc(t, "managed-console-policy.json") |
| + wantAllow := []string{ |
| + "ec2:DescribeImages", "ec2:DescribeInstances", "ec2:RunInstances", "ec2:CreateTags", |
| + "ec2:TerminateInstances", "ec2:GetConsoleOutput", |
| + "s3:CreateBucket", "s3:TagResource", "s3:GetBucketLocation", "s3:GetBucketTagging", |
| + "s3:GetBucketVersioning", "s3:PutBucketVersioning", "s3:GetEncryptionConfiguration", |
| + "s3:PutEncryptionConfiguration", "s3:GetBucketPublicAccessBlock", "s3:PutBucketPublicAccessBlock", |
| + "s3:GetLifecycleConfiguration", "s3:PutLifecycleConfiguration", |
| + "iam:CreateUser", "iam:PutUserPolicy", "iam:GetUser", "iam:GetUserPolicy", "iam:ListUserPolicies", |
| + "iam:ListAttachedUserPolicies", "iam:ListGroupsForUser", "iam:ListAccessKeys", "iam:CreateAccessKey", |
| + "iam:DeleteAccessKey", "iam:DeleteUser", |
| + } |
| + allow := map[string]bool{} |
| + covered := map[string]map[string]bool{} // region -> RunInstances resource kinds |
| + var denies []infraStatement |
| + for _, st := range doc.Statement { |
| + if st.Effect == "Deny" { |
| + denies = append(denies, st) |
| + continue |
| + } |
| + for _, a := range st.Action { |
| + if strings.ContainsAny(a, "*?") { |
| + t.Errorf("%s: wildcard action %s", st.Sid, a) |
| + } |
| + allow[a] = true |
| + } |
| + service := strings.SplitN(st.Action[0], ":", 2)[0] |
| + for _, a := range st.Action { |
| + if !strings.HasPrefix(a, service+":") { |
| + t.Errorf("%s mixes services", st.Sid) |
| + } |
| + } |
| + switch service { |
| + case "ec2": |
| + checkEC2Statement(t, st, covered) |
| + case "s3": |
| + if !slices.Equal(st.Resource, []string{infraFleetBucket}) || st.Condition != nil { |
| + t.Errorf("%s: S3 bucket actions must name exactly %s, got %v", st.Sid, infraFleetBucket, st.Resource) |
| + } |
| + case "iam": |
| + if !slices.Equal(st.Resource, []string{infraFleetUsers}) { |
| + t.Errorf("%s: IAM actions must name exactly %s, got %v", st.Sid, infraFleetUsers, st.Resource) |
| + } |
| + escalates := slices.Contains(st.Action, "iam:CreateUser") || slices.Contains(st.Action, "iam:PutUserPolicy") |
| + bounded := len(st.Condition) == 1 && len(st.Condition["StringEquals"]) == 1 && |
| + slices.Equal(st.Condition["StringEquals"]["iam:PermissionsBoundary"], []string{infraBoundaryARN}) |
| + if escalates != bounded || !escalates && st.Condition != nil { |
| + t.Errorf("%s: CreateUser and PutUserPolicy, and only they, need the exact boundary: %v", st.Sid, st.Condition) |
| + } |
| + if escalates && !sameValues(st.Action, []string{"iam:CreateUser", "iam:PutUserPolicy"}) { |
| + t.Errorf("%s: the boundary statement carries %v", st.Sid, st.Action) |
| + } |
| + default: |
| + t.Errorf("%s: service %s has no place in this grant", st.Sid, service) |
| + } |
| + } |
| + var got []string |
| + for a := range allow { |
| + got = append(got, a) |
| + } |
| + if !sameValues(got, wantAllow) { |
| + t.Errorf("allowed actions\n got %v\nwant %v", sortedCopy(got), sortedCopy(wantAllow)) |
| + } |
| + for _, region := range infraRegionNames() { |
| + for _, kind := range []string{"image", "subnet", "security-group", "network-interface", "volume", "instance"} { |
| + if !covered[region][kind] { |
| + t.Errorf("RunInstances in %s has no grant for %s", region, kind) |
| + } |
| + } |
| + } |
| + |
| + // Explicit Deny: every bucket write the grant allows, on the |
| + // deployment and data buckets, and nothing a read or a lease release |
| + // needs. |
| + var writes []string |
| + for a := range allow { |
| + if strings.HasPrefix(a, "s3:") && !strings.HasPrefix(a, "s3:Get") { |
| + writes = append(writes, a) |
| + } |
| + } |
| + if len(denies) != 1 { |
| + t.Fatalf("want one Deny, got %d", len(denies)) |
| + } |
| + d := denies[0] |
| + if !sameValues(d.Action, writes) || !sameValues(d.Resource, infraProtected) || d.Condition != nil { |
| + t.Errorf("protected-bucket Deny is %+v, want %v on %v", d, sortedCopy(writes), infraProtected) |
| + } |
| + }) |
| + |
| + t.Run("boundary covers exactly the fleet-data policy", func(t *testing.T) { |
| + boundary := loadInfraDoc(t, "managed-boundary-policy.json") |
| + inlineJSON, err := fleetDataPolicy("arn:aws:s3:::" + bucketA) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + inline, err := canonicalPolicy(inlineJSON) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + // Every Allow of the fleet user's inline policy, with its bucket |
| + // replaced by the prefix pattern, is a boundary statement, and the |
| + // boundary has nothing else. |
| + bucket := "arn:aws:s3:::" + bucketA |
| + var want []infraStatement |
| + for _, st := range inline.Statement { |
| + if st.Effect != "Allow" { |
| + continue |
| + } |
| + sub := infraStatement{Sid: "Fleet" + st.Sid, Effect: "Allow", Action: infraValues(sortedCopy(st.Action))} |
| + if st.Sid == "Bucket" { |
| + sub.Sid = "FleetBucket" |
| + } |
| + for _, r := range st.Resource { |
| + sub.Resource = append(sub.Resource, strings.Replace(r, bucket, infraFleetBucket, 1)) |
| + } |
| + sub.Resource = infraValues(sortedCopy(sub.Resource)) |
| + if st.Condition != nil { |
| + sub.Condition = map[string]map[string]infraValues{} |
| + for op, keys := range st.Condition { |
| + sub.Condition[op] = map[string]infraValues{} |
| + for k, v := range keys { |
| + sub.Condition[op][k] = infraValues(sortedCopy(v)) |
| + } |
| + } |
| + } |
| + want = append(want, sub) |
| + } |
| + var have []infraStatement |
| + for _, st := range boundary.Statement { |
| + st.Action, st.Resource = sortedCopy(st.Action), sortedCopy(st.Resource) |
| + for _, keys := range st.Condition { |
| + for k, v := range keys { |
| + keys[k] = sortedCopy(v) |
| + } |
| + } |
| + have = append(have, st) |
| + } |
| + sort.Slice(want, func(i, j int) bool { return want[i].Sid < want[j].Sid }) |
| + sort.Slice(have, func(i, j int) bool { return have[i].Sid < have[j].Sid }) |
| + wb, _ := json.Marshal(want) |
| + hb, _ := json.Marshal(have) |
| + if !bytes.Equal(wb, hb) { |
| + t.Errorf("boundary fleet statements are not the inline policy over the prefix\n got %s\nwant %s", hb, wb) |
| + } |
| + for _, st := range boundary.Statement { |
| + if st.Effect != "Allow" { |
| + t.Errorf("%s: the boundary is a ceiling; it holds no Deny", st.Sid) |
| + } |
| + for _, a := range st.Action { |
| + if strings.ContainsAny(a, "*?") || a == "s3:ListBucketMultipartUploads" || a == "s3:DeleteObjectVersion" { |
| + t.Errorf("%s: boundary allows %s", st.Sid, a) |
| + } |
| + } |
| + for _, r := range st.Resource { |
| + if !strings.HasPrefix(r, infraFleetBucket) || r == "arn:aws:s3:::*" || r == "arn:aws:s3:::*/*" { |
| + t.Errorf("%s: boundary resource %s is not under the fleet prefix", st.Sid, r) |
| + } |
| + } |
| + } |
| + }) |
| + |
| + t.Run("fleet data stays in its own bucket", func(t *testing.T) { |
| + raw, err := os.ReadFile(filepath.Join("testdata", "fleet-data-policy.json")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + fixture, err := fleetDataPolicy(fixtureBucketARN) |
| + if err != nil || !samePolicy(fixture, string(raw)) { |
| + t.Fatalf("fleet-data-policy.json no longer matches the renderer: %v", err) |
| + } |
| + a, b := "arn:aws:s3:::"+bucketA, "arn:aws:s3:::"+bucketB |
| + if a == b || strings.HasPrefix(b, a) || strings.HasPrefix(a, b) { |
| + t.Fatalf("two fleets share a bucket name space: %s %s", a, b) |
| + } |
| + docJSON, err := fleetDataPolicy(a) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + doc, err := canonicalPolicy(docJSON) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + bucketLevel := map[string]bool{"s3:GetBucketLocation": true, "s3:ListBucket": true, "s3:ListBucketVersions": true} |
| + var denied int |
| + for _, st := range doc.Statement { |
| + if st.Effect == "Deny" { |
| + denied++ |
| + // The exemption is exactly this bucket and its objects, and the |
| + // other fleet's name does not extend this one, so the Deny |
| + // covers it. |
| + if !sameValues(st.Action, []string{"s3:*"}) || !sameValues(st.NotResource, []string{a, a + "/*"}) || len(st.Resource) != 0 { |
| + t.Errorf("cross-bucket Deny is %+v", st) |
| + } |
| + continue |
| + } |
| + for _, act := range st.Action { |
| + for _, r := range st.Resource { |
| + switch { |
| + case bucketLevel[act] && r != a: |
| + t.Errorf("%s: bucket action %s on %s", st.Sid, act, r) |
| + case !bucketLevel[act] && !strings.HasPrefix(r, a+"/"): |
| + t.Errorf("%s: object action %s on %s", st.Sid, act, r) |
| + } |
| + if strings.HasPrefix(r, b) { |
| + t.Errorf("%s: names the other fleet's bucket", st.Sid) |
| + } |
| + // Copy sources are reads, copy destinations are puts: both |
| + // classes stay inside this bucket. |
| + if (act == "s3:GetObject" || act == "s3:GetObjectVersion" || act == "s3:PutObject") && !strings.HasPrefix(r, a+"/") { |
| + t.Errorf("%s: copy source or destination %s on %s", st.Sid, act, r) |
| + } |
| + } |
| + } |
| + } |
| + if denied != 1 { |
| + t.Errorf("want one cross-bucket Deny, got %d", denied) |
| + } |
| + }) |
| + |
| + t.Run("app store inline policy carries no fleet power", func(t *testing.T) { |
| + p := objstore.NewMemProvisioner("eu-west-1") |
| + const appBucket = "arn:aws:s3:::carlos-store-test-0123" |
| + for i, v := range []struct { |
| + deny *objstore.DenyTag |
| + denyWrites bool |
| + }{{nil, false}, {&objstore.DenyTag{Key: objstore.TagVerdict, Value: "infected"}, false}, {nil, true}} { |
| + user := "store-user-" + string(rune('a'+i)) |
| + if _, err := p.EnsureUser(ctx, user, "/carlos-store/", appBucket, v.deny, v.denyWrites); err != nil { |
| + t.Fatal(err) |
| + } |
| + var doc struct { |
| + Statement []struct { |
| + Effect string |
| + Action infraValues |
| + Resource infraValues |
| + } |
| + } |
| + if err := json.Unmarshal([]byte(p.PolicyFor(user)), &doc); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, st := range doc.Statement { |
| + for _, r := range st.Resource { |
| + if r != appBucket && r != appBucket+"/*" || strings.Contains(r, infraPrefix) { |
| + t.Errorf("app policy names %s", r) |
| + } |
| + } |
| + if st.Effect != "Allow" { |
| + continue |
| + } |
| + for _, act := range st.Action { |
| + if strings.Contains(act, "Version") || strings.Contains(act, "Multipart") || strings.ContainsAny(act, "*?") { |
| + t.Errorf("app policy allows %s", act) |
| + } |
| + } |
| + } |
| + } |
| + }) |
| +} |
| + |
| +// checkEC2Statement pins one EC2 Allow: every resource is configured, every |
| +// condition key is one the resource types in the statement support, and the |
| +// required bounds for that action and type are present. |
| +func checkEC2Statement(t *testing.T, st infraStatement, covered map[string]map[string]bool) { |
| + t.Helper() |
| + if slices.Contains(st.Resource, "*") { |
| + if !sameValues(st.Action, []string{"ec2:DescribeImages", "ec2:DescribeInstances"}) || len(st.Resource) != 1 || |
| + len(st.Condition) != 1 || len(st.Condition["StringEquals"]) != 1 || |
| + !sameValues(st.Condition["StringEquals"]["aws:RequestedRegion"], infraRegionNames()) { |
| + t.Errorf("%s: Resource * is only for the two Describe calls, bound to the configured regions: %+v", st.Sid, st) |
| + } |
| + return |
| + } |
| + kinds := map[string]bool{} |
| + regions := map[string]bool{} |
| + for _, r := range st.Resource { |
| + kind, region := ec2Resource(t, st.Sid, r) |
| + kinds[kind] = true |
| + regions[region] = true |
| + } |
| + for _, act := range st.Action { |
| + table, ok := ec2ConditionKeys[act] |
| + if !ok { |
| + t.Errorf("%s: %s is not an EC2 action this grant expects", st.Sid, act) |
| + continue |
| + } |
| + for kind := range kinds { |
| + supported, ok := table[kind] |
| + if !ok { |
| + t.Errorf("%s: %s on a %s resource", st.Sid, act, kind) |
| + continue |
| + } |
| + for _, k := range conditionKeys(st) { |
| + if !slices.Contains(supported, k) { |
| + t.Errorf("%s: condition key %s is not supported for %s on %s", st.Sid, k, act, kind) |
| + } |
| + } |
| + } |
| + } |
| + switch { |
| + case slices.Equal(st.Action, []string{"ec2:RunInstances"}): |
| + if len(kinds) != 1 && !(len(kinds) == 2 && kinds["subnet"] && kinds["security-group"]) { |
| + t.Errorf("%s: one RunInstances statement per resource type (subnets with groups), got %v", st.Sid, kinds) |
| + } |
| + for region := range regions { |
| + if covered[region] == nil { |
| + covered[region] = map[string]bool{} |
| + } |
| + for kind := range kinds { |
| + covered[region][kind] = true |
| + } |
| + } |
| + switch { |
| + case kinds["instance"]: |
| + if len(regions) != 1 { |
| + t.Fatalf("%s: instance types are per region; one region per statement", st.Sid) |
| + } |
| + var region string |
| + for r := range regions { |
| + region = r |
| + } |
| + checkLaunchTags(t, st, "aws:RequestTag/") |
| + types := st.Condition["StringEquals"]["ec2:InstanceType"] |
| + if !sameValues(types, infraRegions[region].iTypes) { |
| + t.Errorf("%s: instance types %v, want %v", st.Sid, types, infraRegions[region].iTypes) |
| + } |
| + for _, it := range types { |
| + if !armTypeRE.MatchString(it) { |
| + t.Errorf("%s: %s is not an approved ARM type", st.Sid, it) |
| + } |
| + } |
| + if !slices.Equal(st.Condition["StringEquals"]["ec2:MetadataHttpTokens"], []string{"required"}) || |
| + !slices.Equal(st.Condition["NumericEquals"]["ec2:MetadataHttpPutResponseHopLimit"], []string{"1"}) || |
| + !slices.Equal(st.Condition["Null"]["ec2:InstanceProfile"], []string{"true"}) { |
| + t.Errorf("%s: launch needs IMDSv2, hop limit 1 and no instance profile: %v", st.Sid, st.Condition) |
| + } |
| + case kinds["volume"]: |
| + checkLaunchTags(t, st, "aws:RequestTag/") |
| + case kinds["network-interface"]: |
| + var want []string |
| + for _, r := range infraRegionNames() { |
| + for _, s := range infraRegions[r].subnets { |
| + want = append(want, "arn:aws:ec2:"+r+":"+infraAccount+":subnet/"+s) |
| + } |
| + } |
| + if len(st.Condition) != 1 || !sameValues(st.Condition["ArnEquals"]["ec2:Subnet"], want) { |
| + t.Errorf("%s: network interfaces must stay in approved subnets: %v", st.Sid, st.Condition) |
| + } |
| + default: |
| + if st.Condition != nil { |
| + t.Errorf("%s: image, subnet and group statements carry no condition", st.Sid) |
| + } |
| + } |
| + case slices.Equal(st.Action, []string{"ec2:CreateTags"}): |
| + // Which tags is the RunInstances instance and volume statements' |
| + // job (same request); this one only pins tagging to the launch. |
| + if len(st.Condition) != 1 || len(st.Condition["StringEquals"]) != 1 || |
| + !slices.Equal(st.Condition["StringEquals"]["ec2:CreateAction"], []string{"RunInstances"}) || |
| + kinds["image"] || kinds["subnet"] || kinds["security-group"] || kinds["network-interface"] { |
| + t.Errorf("%s: tags only at RunInstances, on instances and volumes: %+v", st.Sid, st) |
| + } |
| + if len(regions) != len(infraRegions) { |
| + t.Errorf("%s: launch tagging is needed in every configured region", st.Sid) |
| + } |
| + case sameValues(st.Action, []string{"ec2:GetConsoleOutput", "ec2:TerminateInstances"}): |
| + if len(kinds) != 1 || !kinds["instance"] || len(regions) != len(infraRegions) { |
| + t.Errorf("%s: terminate and console output name instances in every configured region", st.Sid) |
| + } |
| + if len(st.Condition) != 2 || len(st.Condition["StringEquals"]) != 1 || |
| + !slices.Equal(st.Condition["StringEquals"]["aws:ResourceTag/"+tagDeployment], []string{infraDeployment}) { |
| + t.Errorf("%s: exact deployment tag required: %v", st.Sid, st.Condition) |
| + } |
| + null := st.Condition["Null"] |
| + var required []string |
| + for k, v := range null { |
| + if !slices.Equal(v, []string{"false"}) { |
| + t.Errorf("%s: Null %s = %v", st.Sid, k, v) |
| + } |
| + required = append(required, strings.TrimPrefix(k, "aws:ResourceTag/")) |
| + } |
| + if !sameValues(required, infraIdentityTags) { |
| + t.Errorf("%s: all four identity tags must be present, got %v", st.Sid, required) |
| + } |
| + missing := false |
| + for _, k := range required { |
| + if _, ok := infraRegionHostTags[k]; !ok { |
| + missing = true |
| + } |
| + } |
| + if !missing { |
| + t.Errorf("%s: a deployment+region region host carries every required tag", st.Sid) |
| + } |
| + default: |
| + t.Errorf("%s: unexpected EC2 action set %v", st.Sid, st.Action) |
| + } |
| +} |
diff --git a/internal/awsmanaged/testdata/managed-boundary-policy.json b/internal/awsmanaged/testdata/managed-boundary-policy.json| new file mode 100644 |
| index 000000000..6662c178a |
| --- /dev/null |
| +++ b/internal/awsmanaged/testdata/managed-boundary-policy.json |
| @@ -0,0 +1,62 @@ |
| +{ |
| + "Version": "2012-10-17", |
| + "Statement": [ |
| + { |
| + "Sid": "FleetBucket", |
| + "Effect": "Allow", |
| + "Action": ["s3:GetBucketLocation", "s3:ListBucket"], |
| + "Resource": ["arn:aws:s3:::carlos-fleet-*"] |
| + }, |
| + { |
| + "Sid": "FleetVersions", |
| + "Effect": "Allow", |
| + "Action": ["s3:ListBucketVersions"], |
| + "Resource": ["arn:aws:s3:::carlos-fleet-*"], |
| + "Condition": { |
| + "StringLike": { |
| + "s3:prefix": ["instances/*", "moves/*", "move-snapshots/*", "_carlos/probes/*", "system/fleet-secrets-key.json"] |
| + } |
| + } |
| + }, |
| + { |
| + "Sid": "FleetData", |
| + "Effect": "Allow", |
| + "Action": [ |
| + "s3:GetObject", |
| + "s3:PutObject", |
| + "s3:DeleteObject", |
| + "s3:GetObjectVersion", |
| + "s3:AbortMultipartUpload", |
| + "s3:ListMultipartUploadParts" |
| + ], |
| + "Resource": [ |
| + "arn:aws:s3:::carlos-fleet-*/instances/*", |
| + "arn:aws:s3:::carlos-fleet-*/moves/*", |
| + "arn:aws:s3:::carlos-fleet-*/move-snapshots/*" |
| + ] |
| + }, |
| + { |
| + "Sid": "FleetProbes", |
| + "Effect": "Allow", |
| + "Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"], |
| + "Resource": ["arn:aws:s3:::carlos-fleet-*/_carlos/probes/*"] |
| + }, |
| + { |
| + "Sid": "FleetKeyRead", |
| + "Effect": "Allow", |
| + "Action": ["s3:GetObject"], |
| + "Resource": ["arn:aws:s3:::carlos-fleet-*/system/fleet-secrets-key.json"] |
| + }, |
| + { |
| + "Sid": "FleetKeyCreate", |
| + "Effect": "Allow", |
| + "Action": ["s3:PutObject"], |
| + "Resource": ["arn:aws:s3:::carlos-fleet-*/system/fleet-secrets-key.json"], |
| + "Condition": { |
| + "StringEquals": { |
| + "s3:if-none-match": ["*"] |
| + } |
| + } |
| + } |
| + ] |
| +} |
diff --git a/internal/awsmanaged/testdata/managed-console-policy.json b/internal/awsmanaged/testdata/managed-console-policy.json| new file mode 100644 |
| index 000000000..b1fb95f30 |
| --- /dev/null |
| +++ b/internal/awsmanaged/testdata/managed-console-policy.json |
| @@ -0,0 +1,229 @@ |
| +{ |
| + "Version": "2012-10-17", |
| + "Statement": [ |
| + { |
| + "Sid": "ReadManagedRegions", |
| + "Effect": "Allow", |
| + "Action": ["ec2:DescribeImages", "ec2:DescribeInstances"], |
| + "Resource": "*", |
| + "Condition": { |
| + "StringEquals": { |
| + "aws:RequestedRegion": ["eu-west-1", "us-east-1"] |
| + } |
| + } |
| + }, |
| + { |
| + "Sid": "LaunchApprovedImages", |
| + "Effect": "Allow", |
| + "Action": ["ec2:RunInstances"], |
| + "Resource": [ |
| + "arn:aws:ec2:eu-west-1::image/ami-0123456789abcdef0", |
| + "arn:aws:ec2:us-east-1::image/ami-0fedcba9876543210" |
| + ] |
| + }, |
| + { |
| + "Sid": "LaunchApprovedNetwork", |
| + "Effect": "Allow", |
| + "Action": ["ec2:RunInstances"], |
| + "Resource": [ |
| + "arn:aws:ec2:eu-west-1:123456789012:subnet/subnet-0123456789abcdef0", |
| + "arn:aws:ec2:eu-west-1:123456789012:subnet/subnet-0123456789abcdef1", |
| + "arn:aws:ec2:us-east-1:123456789012:subnet/subnet-0fedcba9876543210", |
| + "arn:aws:ec2:eu-west-1:123456789012:security-group/sg-0123456789abcdef0", |
| + "arn:aws:ec2:us-east-1:123456789012:security-group/sg-0fedcba9876543210" |
| + ] |
| + }, |
| + { |
| + "Sid": "LaunchNetworkInterfaces", |
| + "Effect": "Allow", |
| + "Action": ["ec2:RunInstances"], |
| + "Resource": [ |
| + "arn:aws:ec2:eu-west-1:123456789012:network-interface/*", |
| + "arn:aws:ec2:us-east-1:123456789012:network-interface/*" |
| + ], |
| + "Condition": { |
| + "ArnEquals": { |
| + "ec2:Subnet": [ |
| + "arn:aws:ec2:eu-west-1:123456789012:subnet/subnet-0123456789abcdef0", |
| + "arn:aws:ec2:eu-west-1:123456789012:subnet/subnet-0123456789abcdef1", |
| + "arn:aws:ec2:us-east-1:123456789012:subnet/subnet-0fedcba9876543210" |
| + ] |
| + } |
| + } |
| + }, |
| + { |
| + "Sid": "LaunchTaggedVolumes", |
| + "Effect": "Allow", |
| + "Action": ["ec2:RunInstances"], |
| + "Resource": [ |
| + "arn:aws:ec2:eu-west-1:123456789012:volume/*", |
| + "arn:aws:ec2:us-east-1:123456789012:volume/*" |
| + ], |
| + "Condition": { |
| + "StringEquals": { |
| + "aws:RequestTag/carlos:deployment": "production" |
| + }, |
| + "StringLike": { |
| + "aws:RequestTag/carlos:fleet": "?*", |
| + "aws:RequestTag/carlos:label": "?*", |
| + "aws:RequestTag/carlos:operation": "?*" |
| + }, |
| + "ForAllValues:StringEquals": { |
| + "aws:TagKeys": ["carlos:deployment", "carlos:fleet", "carlos:label", "carlos:operation"] |
| + } |
| + } |
| + }, |
| + { |
| + "Sid": "LaunchInstancesEuWest1", |
| + "Effect": "Allow", |
| + "Action": ["ec2:RunInstances"], |
| + "Resource": ["arn:aws:ec2:eu-west-1:123456789012:instance/*"], |
| + "Condition": { |
| + "StringEquals": { |
| + "aws:RequestTag/carlos:deployment": "production", |
| + "ec2:InstanceType": ["t4g.medium", "t4g.small"], |
| + "ec2:MetadataHttpTokens": "required" |
| + }, |
| + "NumericEquals": { |
| + "ec2:MetadataHttpPutResponseHopLimit": "1" |
| + }, |
| + "StringLike": { |
| + "aws:RequestTag/carlos:fleet": "?*", |
| + "aws:RequestTag/carlos:label": "?*", |
| + "aws:RequestTag/carlos:operation": "?*" |
| + }, |
| + "ForAllValues:StringEquals": { |
| + "aws:TagKeys": ["carlos:deployment", "carlos:fleet", "carlos:label", "carlos:operation"] |
| + }, |
| + "Null": { |
| + "ec2:InstanceProfile": "true" |
| + } |
| + } |
| + }, |
| + { |
| + "Sid": "LaunchInstancesUsEast1", |
| + "Effect": "Allow", |
| + "Action": ["ec2:RunInstances"], |
| + "Resource": ["arn:aws:ec2:us-east-1:123456789012:instance/*"], |
| + "Condition": { |
| + "StringEquals": { |
| + "aws:RequestTag/carlos:deployment": "production", |
| + "ec2:InstanceType": ["m7g.large"], |
| + "ec2:MetadataHttpTokens": "required" |
| + }, |
| + "NumericEquals": { |
| + "ec2:MetadataHttpPutResponseHopLimit": "1" |
| + }, |
| + "StringLike": { |
| + "aws:RequestTag/carlos:fleet": "?*", |
| + "aws:RequestTag/carlos:label": "?*", |
| + "aws:RequestTag/carlos:operation": "?*" |
| + }, |
| + "ForAllValues:StringEquals": { |
| + "aws:TagKeys": ["carlos:deployment", "carlos:fleet", "carlos:label", "carlos:operation"] |
| + }, |
| + "Null": { |
| + "ec2:InstanceProfile": "true" |
| + } |
| + } |
| + }, |
| + { |
| + "Sid": "TagAtLaunchOnly", |
| + "Effect": "Allow", |
| + "Action": ["ec2:CreateTags"], |
| + "Resource": [ |
| + "arn:aws:ec2:eu-west-1:123456789012:instance/*", |
| + "arn:aws:ec2:eu-west-1:123456789012:volume/*", |
| + "arn:aws:ec2:us-east-1:123456789012:instance/*", |
| + "arn:aws:ec2:us-east-1:123456789012:volume/*" |
| + ], |
| + "Condition": { |
| + "StringEquals": { |
| + "ec2:CreateAction": "RunInstances" |
| + } |
| + } |
| + }, |
| + { |
| + "Sid": "ManagedBoxesOnly", |
| + "Effect": "Allow", |
| + "Action": ["ec2:GetConsoleOutput", "ec2:TerminateInstances"], |
| + "Resource": [ |
| + "arn:aws:ec2:eu-west-1:123456789012:instance/*", |
| + "arn:aws:ec2:us-east-1:123456789012:instance/*" |
| + ], |
| + "Condition": { |
| + "StringEquals": { |
| + "aws:ResourceTag/carlos:deployment": "production" |
| + }, |
| + "Null": { |
| + "aws:ResourceTag/carlos:deployment": "false", |
| + "aws:ResourceTag/carlos:fleet": "false", |
| + "aws:ResourceTag/carlos:label": "false", |
| + "aws:ResourceTag/carlos:operation": "false" |
| + } |
| + } |
| + }, |
| + { |
| + "Sid": "FleetBuckets", |
| + "Effect": "Allow", |
| + "Action": [ |
| + "s3:CreateBucket", |
| + "s3:TagResource", |
| + "s3:GetBucketLocation", |
| + "s3:GetBucketTagging", |
| + "s3:GetBucketVersioning", |
| + "s3:PutBucketVersioning", |
| + "s3:GetEncryptionConfiguration", |
| + "s3:PutEncryptionConfiguration", |
| + "s3:GetBucketPublicAccessBlock", |
| + "s3:PutBucketPublicAccessBlock", |
| + "s3:GetLifecycleConfiguration", |
| + "s3:PutLifecycleConfiguration" |
| + ], |
| + "Resource": ["arn:aws:s3:::carlos-fleet-*"] |
| + }, |
| + { |
| + "Sid": "NeverConfigureDeploymentBuckets", |
| + "Effect": "Deny", |
| + "Action": [ |
| + "s3:CreateBucket", |
| + "s3:TagResource", |
| + "s3:PutBucketVersioning", |
| + "s3:PutEncryptionConfiguration", |
| + "s3:PutBucketPublicAccessBlock", |
| + "s3:PutLifecycleConfiguration" |
| + ], |
| + "Resource": [ |
| + "arn:aws:s3:::carlos-test-platform", |
| + "arn:aws:s3:::carlos-test-ie" |
| + ] |
| + }, |
| + { |
| + "Sid": "CreateBoundedFleetUsers", |
| + "Effect": "Allow", |
| + "Action": ["iam:CreateUser", "iam:PutUserPolicy"], |
| + "Resource": ["arn:aws:iam::123456789012:user/carlos-managed-fleet/*"], |
| + "Condition": { |
| + "StringEquals": { |
| + "iam:PermissionsBoundary": "arn:aws:iam::123456789012:policy/carlos-test-host-store-boundary" |
| + } |
| + } |
| + }, |
| + { |
| + "Sid": "ManageFleetUsers", |
| + "Effect": "Allow", |
| + "Action": [ |
| + "iam:GetUser", |
| + "iam:GetUserPolicy", |
| + "iam:ListUserPolicies", |
| + "iam:ListAttachedUserPolicies", |
| + "iam:ListGroupsForUser", |
| + "iam:ListAccessKeys", |
| + "iam:CreateAccessKey", |
| + "iam:DeleteAccessKey", |
| + "iam:DeleteUser" |
| + ], |
| + "Resource": ["arn:aws:iam::123456789012:user/carlos-managed-fleet/*"] |
| + } |
| + ] |
| +} |