carlos / platform Public

Add isolated region ingress and fixed-resource plan gate

Add the P3a ingress child and literal fixed-target fixture without changing
fixed hosts. Guard saved plans against fixed-resource drift, capacity loss,
and protected-address removal; require exact reviewed exceptions.

Add mock and Python fixture tests, plus the census proposal for the new
infra files. Independent census and task review remain with the controller.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev fc89adf690529a8aec8960f6204a7b07ec70a485 parent f7ca1a4
20 files changed, +1,505 −0
  • docs/superpowers/notes/census-proposal-region-ha-p3a.md +24 −0
  • docs/superpowers/notes/census-region-ha-p3a-claims.tsv +10 −0
  • infra/modules/region-host/ingress/main.tf +127 −0
  • infra/modules/region-host/ingress/outputs.tf +19 −0
  • infra/modules/region-host/ingress/tests/fixed-targets/main.tf +32 −0
  • infra/modules/region-host/ingress/tests/fixed-targets/tests/targets.tftest.hcl +61 −0
  • infra/modules/region-host/ingress/tests/fixed-targets/variables.tf +56 −0
  • infra/modules/region-host/ingress/tests/fixed-targets/versions.tf +9 −0
  • infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl +217 −0
  • infra/modules/region-host/ingress/variables.tf +46 −0
  • infra/modules/region-host/ingress/versions.tf +9 −0
  • infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl +97 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-region-ha-p3a.tsv +28 −0
  • scripts/check-region-group-plan.py +395 −0
  • scripts/check_region_group_plan_test.py +256 −0
  • scripts/testdata/region-group-plan/fixed-eip-reassociation.json +25 −0
  • scripts/testdata/region-group-plan/new-ingress.json +26 −0
  • scripts/testdata/region-group-plan/targeted-fixed-user-data.json +41 −0
  • scripts/testdata/region-group-plan/unchanged-move.json +26 −0

Intent

Human

<cross-session-message from="uds:/run/user/1001/cc-socks/3781367.sock" from-name="platform-72" from-mode="bypass"> Release heads-up from platform-72: Paul asked for a roll. I'm cutting v0.33.5 from main ceee7a67 (CI green): dev first, then flagship. Since v0.33.4 it carries b40f3bc8 (activity labels), b7802fd8 (probe-burst limit #491), 79d9d6a2 + 06bc3d73 (console styling and mobile nav), 65420a4d (#500), 21738194 + ceee7a67 (team-service design and prototype). If one of these is yours and it needs holding, a flagship step, or a specific check, reply within about 15 minutes. If it's not yours, no reply needed. </cross-session-message>

Human

Do you need approval to merge?

Human

go ahead.

Human

<paseo-system version="1" kind="agent-message" source-agent-id="0f39318c-0ba2-460c-9717-b97d0d681e91" message-id="7a2a3c6d-c01f-4e42-93ef-ca426ecaec2f"> From platform-6e: DEV ROLL DONE (v0.33.9 on all dev boxes and the dev console since 01:43:21Z; flagship finished 01:53Z). sophie and leo are yours. Heads-up: in the next hour I&apos;ll change the dev CONSOLE&apos;s settings for domain buying (a console.service drop-in, then one console restart of about 3 s on the console box). I won&apos;t touch any edge or box agent. </paseo-system>

Human

<task-notification> <task-id>br1zvsoq6</task-id> <tool-use-id>toolu_01CkcKrbMXDuMduxV5NhpXQm</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/a649f7fd-c78e-486b-b681-6b115cf45536/tasks/br1zvsoq6.output</output-file> <status>completed</status> <summary>Background command "Coordinate console restart timing with platform-6e" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>b2mleehtg</task-id> <tool-use-id>toolu_01UacdEMvszdLrmH73hpk3dS</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/6cb8c43c-d494-478a-8f04-1067486903df/tasks/b2mleehtg.output</output-file> <status>completed</status> <summary>Background command "W=/home/paulca/amadan.net/carlos/platform/.claude/worktrees/region-ha-p3/.superpowers/sdd/2026-11-03-region-ha-p3a; until [ -s $W/copy-luna-final2.md ]; do sleep 20; done; cat $W/copy-luna-final2.md" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 11.1 g CO₂e (1,284,325 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on region-ha-p3-group, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/docs/superpowers/notes/census-proposal-region-ha-p3a.md b/docs/superpowers/notes/census-proposal-region-ha-p3a.md
new file mode 100644
index 000000000..05789fe39
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-region-ha-p3a.md
@@ -0,0 +1,24 @@
+# Census approval: region-ha-p3a
+
+Ruling `census-ruling-region-ha-p3a`. The independent reviewer approves or rejects every change below, 10 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+Envelopes re-pinned: `infra/modules/region-host/ingress`, `infra/modules/region-host/ingress/tests`, `infra/modules/region-host/ingress/tests/fixed-targets`, `infra/modules/region-host/ingress/tests/fixed-targets/tests`, `infra/modules/region-host/tests`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `infra/modules/region-host/ingress/main.tf:external`: reads +file:external; written legacy, accepted-legacy, frozen
+- new `infra/modules/region-host/ingress/outputs.tf:external`: reads +file:external; written legacy, accepted-legacy, frozen
+- new `infra/modules/region-host/ingress/tests/fixed-targets/main.tf:external`: reads +file:external; written legacy, accepted-legacy, frozen
+- new `infra/modules/region-host/ingress/tests/fixed-targets/tests/targets.tftest.hcl:external`: reads +file:external; written legacy, accepted-legacy, frozen
+- new `infra/modules/region-host/ingress/tests/fixed-targets/variables.tf:external`: reads +file:external; written legacy, accepted-legacy, frozen
+- new `infra/modules/region-host/ingress/tests/fixed-targets/versions.tf:external`: reads +file:external; written legacy, accepted-legacy, frozen
+- new `infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl:external`: reads +file:external; written legacy, accepted-legacy, frozen
+- new `infra/modules/region-host/ingress/variables.tf:external`: reads +file:external; written legacy, accepted-legacy, frozen
+- new `infra/modules/region-host/ingress/versions.tf:external`: reads +file:external; written legacy, accepted-legacy, frozen
+- new `infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl:external`: reads +file:external; written legacy, accepted-legacy, frozen
+
+Seal: `c68e2453bfc8afaf3794eb4c08850428982fa6954269b6b99bddfda4e6242929` → `f2d9c89885a0019f5a30651f8019bb6f0c55bf84b412e045e59e30b66b4bf32e`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-region-ha-p3a.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/notes/census-region-ha-p3a-claims.tsv b/docs/superpowers/notes/census-region-ha-p3a-claims.tsv
new file mode 100644
index 000000000..b0abac5f4
--- /dev/null
+++ b/docs/superpowers/notes/census-region-ha-p3a-claims.tsv
@@ -0,0 +1,10 @@
+infra/modules/region-host/ingress/main.tf:external Add isolated IPv4 NLB, VPC/zone lookups, validated CIDR egress, protected new EIPs and TCP health-checked target groups; no fixed-resource edits or root runtime reads.
+infra/modules/region-host/ingress/outputs.tf:external Expose per-zone addresses and NLB/TG identities for root attachments and Task 4 alarms; no root runtime reads.
+infra/modules/region-host/ingress/tests/fixed-targets/main.tf:external Add dev-root fixture attaching literal instance IDs to both target groups with read-only AZ lookups and target-zone precondition; no fixed-module references or root runtime reads.
+infra/modules/region-host/ingress/tests/fixed-targets/tests/targets.tftest.hcl:external Add plan-only mock witnesses for target attachments and out-of-zone refusal; no live API calls or root runtime reads.
+infra/modules/region-host/ingress/tests/fixed-targets/variables.tf:external Define explicit ingress and literal target inputs for the dev-root fixture; no root runtime reads.
+infra/modules/region-host/ingress/tests/fixed-targets/versions.tf:external Declare OpenTofu/AWS provider requirements for the dev-root fixture; no root runtime reads.
+infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl:external Add plan-only mock tests for NLB protocol, health, zone/VPC boundary, protected allocations and restricted SG traffic; no live API calls or root runtime reads.
+infra/modules/region-host/ingress/variables.tf:external Add ingress-only inputs and topology/CIDR validation; no root runtime reads.
+infra/modules/region-host/ingress/versions.tf:external Declare OpenTofu and AWS provider requirements for the isolated ingress child; no root runtime reads.
+infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl:external Add mock regression for the unchanged fixed instance/profile/SG/root-volume wiring and legacy outputs; no root runtime reads.
diff --git a/infra/modules/region-host/ingress/main.tf b/infra/modules/region-host/ingress/main.tf
new file mode 100644
index 000000000..bcbcb620d
--- /dev/null
+++ b/infra/modules/region-host/ingress/main.tf
@@ -0,0 +1,127 @@
+data "aws_vpc" "target" {
+ id = var.vpc_id
+}
+
+data "aws_subnets" "zone" {
+ for_each = var.zones
+ filter {
+ name = "subnet-id"
+ values = [each.value.subnet_id]
+ }
+ filter {
+ name = "vpc-id"
+ values = [var.vpc_id]
+ }
+ filter {
+ name = "availability-zone"
+ values = [each.key]
+ }
+}
+
+data "aws_eip" "existing" {
+ for_each = { for az, zone in var.zones : az => zone if zone.allocation_id != null }
+ id = each.value.allocation_id
+}
+
+resource "aws_eip" "public" {
+ for_each = { for az, zone in var.zones : az => zone if zone.allocation_id == null }
+ domain = "vpc"
+ tags = { Name = "${var.name}-${each.key}" }
+ lifecycle {
+ prevent_destroy = true
+ }
+}
+
+resource "aws_security_group" "nlb" {
+ name = "${var.name}-nlb"
+ vpc_id = var.vpc_id
+ dynamic "ingress" {
+ for_each = toset([80, 443])
+ content {
+ ipv6_cidr_blocks = []
+ prefix_list_ids = []
+ security_groups = []
+ self = false
+ protocol = "tcp"
+ from_port = ingress.value
+ to_port = ingress.value
+ cidr_blocks = ["0.0.0.0/0"]
+ }
+ }
+ dynamic "egress" {
+ for_each = toset([80, 443])
+ content {
+ ipv6_cidr_blocks = []
+ prefix_list_ids = []
+ security_groups = []
+ self = false
+ protocol = "tcp"
+ from_port = egress.value
+ to_port = egress.value
+ cidr_blocks = var.target_vpc_cidrs
+ }
+ }
+ lifecycle {
+ precondition {
+ condition = var.target_vpc_cidrs == toset(concat(
+ [data.aws_vpc.target.cidr_block],
+ [for association in data.aws_vpc.target.cidr_block_associations : association.cidr_block]
+ ))
+ error_message = "target_vpc_cidrs must match the target VPC"
+ }
+ }
+}
+
+resource "aws_lb" "nlb" {
+ name = var.name
+ internal = false
+ load_balancer_type = "network"
+ ip_address_type = "ipv4"
+ enable_cross_zone_load_balancing = true
+ security_groups = [aws_security_group.nlb.id]
+ dynamic "subnet_mapping" {
+ for_each = var.zones
+ content {
+ subnet_id = subnet_mapping.value.subnet_id
+ allocation_id = subnet_mapping.value.allocation_id != null ? subnet_mapping.value.allocation_id : aws_eip.public[subnet_mapping.key].id
+ }
+ }
+ lifecycle {
+ precondition {
+ condition = alltrue([for az, zone in var.zones : contains(data.aws_subnets.zone[az].ids, zone.subnet_id)])
+ error_message = "each subnet must belong to its named availability zone and the target VPC"
+ }
+ }
+}
+
+resource "aws_lb_target_group" "target" {
+ for_each = toset(["80", "443"])
+ name = "${var.name}-${each.key}"
+ port = tonumber(each.key)
+ protocol = "TCP"
+ target_type = "instance"
+ vpc_id = var.vpc_id
+ preserve_client_ip = true
+ deregistration_delay = 30
+ health_check {
+ enabled = true
+ protocol = "HTTP"
+ port = "80"
+ path = "/.carlos/lb-health"
+ interval = 10
+ healthy_threshold = 2
+ unhealthy_threshold = 2
+ matcher = "200"
+ }
+}
+
+resource "aws_lb_listener" "tcp" {
+ for_each = aws_lb_target_group.target
+ load_balancer_arn = aws_lb.nlb.arn
+ port = tonumber(each.key)
+ protocol = "TCP"
+ default_action {
+ type = "forward"
+ target_group_arn = each.value.arn
+ }
+}
diff --git a/infra/modules/region-host/ingress/outputs.tf b/infra/modules/region-host/ingress/outputs.tf
new file mode 100644
index 000000000..75a78a521
--- /dev/null
+++ b/infra/modules/region-host/ingress/outputs.tf
@@ -0,0 +1,19 @@
+output "public_ips" {
+ description = "Public IPv4 addresses for the load balancer, one address per availability zone."
+ value = { for az, zone in var.zones : az => zone.allocation_id != null ? data.aws_eip.existing[az].public_ip : aws_eip.public[az].public_ip }
+}
+output "allocation_ids" {
+ value = { for az, zone in var.zones : az => zone.allocation_id != null ? zone.allocation_id : aws_eip.public[az].id }
+}
+output "target_group_arns" {
+ value = { for port, group in aws_lb_target_group.target : port => group.arn }
+}
+output "nlb_security_group_id" {
+ value = aws_security_group.nlb.id
+}
+output "nlb_arn_suffix" {
+ value = aws_lb.nlb.arn_suffix
+}
+output "target_group_arn_suffixes" {
+ value = { for port, group in aws_lb_target_group.target : port => group.arn_suffix }
+}
diff --git a/infra/modules/region-host/ingress/tests/fixed-targets/main.tf b/infra/modules/region-host/ingress/tests/fixed-targets/main.tf
new file mode 100644
index 000000000..9b5885369
--- /dev/null
+++ b/infra/modules/region-host/ingress/tests/fixed-targets/main.tf
@@ -0,0 +1,32 @@
+module "ingress" {
+ source = "../.."
+ name = var.name
+ vpc_id = var.vpc_id
+ zones = var.zones
+ target_vpc_cidrs = var.target_vpc_cidrs
+}
+
+data "aws_instance" "target" {
+ for_each = var.target_ids
+ instance_id = each.value
+}
+
+locals {
+ attachments = { for pair in setproduct(toset(["80", "443"]), var.target_ids) : "${pair[0]}/${pair[1]}" => {
+ port = pair[0]
+ id = pair[1]
+ } }
+}
+
+resource "aws_lb_target_group_attachment" "fixed" {
+ for_each = local.attachments
+ target_group_arn = module.ingress.target_group_arns[each.value.port]
+ target_id = each.value.id
+ port = tonumber(each.value.port)
+ lifecycle {
+ precondition {
+ condition = length(setsubtract(toset([for instance in data.aws_instance.target : instance.availability_zone]), toset(keys(var.zones)))) == 0
+ error_message = "target instance availability zone is not covered by the load balancer"
+ }
+ }
+}
diff --git a/infra/modules/region-host/ingress/tests/fixed-targets/tests/targets.tftest.hcl b/infra/modules/region-host/ingress/tests/fixed-targets/tests/targets.tftest.hcl
new file mode 100644
index 000000000..47e48fc3b
--- /dev/null
+++ b/infra/modules/region-host/ingress/tests/fixed-targets/tests/targets.tftest.hcl
@@ -0,0 +1,61 @@
+mock_provider "aws" {
+ mock_resource "aws_lb" {
+ defaults = {
+ arn = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/net/shop-probe/0123456789abcdef"
+ arn_suffix = "net/shop-probe/0123456789abcdef"
+ }
+ }
+ mock_resource "aws_lb_target_group" {
+ defaults = {
+ arn = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/shop-probe/0123456789abcdef"
+ arn_suffix = "targetgroup/shop-probe/0123456789abcdef"
+ }
+ }
+ mock_resource "aws_security_group" {
+ defaults = { id = "sg-0123456789abcdef0" }
+ }
+ mock_data "aws_vpc" {
+ defaults = {
+ cidr_block = "10.0.0.0/16"
+ cidr_block_associations = [{ cidr_block = "10.0.0.0/16", association_id = "vpc-cidr-assoc-0123456789abcdef0", state = "associated" }]
+ }
+ }
+ mock_data "aws_subnets" {
+ defaults = { ids = ["subnet-0123456789abcdef0", "subnet-0123456789abcdef1"] }
+ }
+ mock_data "aws_instance" {
+ defaults = { availability_zone = "eu-west-1a" }
+ }
+}
+variables {
+ name = "shop-probe"
+ vpc_id = "vpc-0123456789abcdef0"
+ target_vpc_cidrs = ["10.0.0.0/16"]
+ zones = {
+ eu-west-1a = { subnet_id = "subnet-0123456789abcdef0", allocation_id = null }
+ eu-west-1b = { subnet_id = "subnet-0123456789abcdef1", allocation_id = null }
+ }
+ target_ids = ["i-0123456789abcdef0", "i-0123456789abcdef1"]
+}
+run "literal_targets" {
+ command = plan
+ assert {
+ condition = length(aws_lb_target_group_attachment.fixed) == 4 && alltrue([
+ for attachment in aws_lb_target_group_attachment.fixed :
+ contains(var.target_ids, attachment.target_id) && contains([80, 443], attachment.port)
+ ])
+ error_message = "both fixed targets must be attached to both target groups"
+ }
+ assert {
+ condition = toset([for instance in data.aws_instance.target : instance.instance_id]) == toset(var.target_ids)
+ error_message = "instance lookups must use literal target IDs"
+ }
+}
+run "out_of_zone_target_refused" {
+ command = plan
+ override_data {
+ target = data.aws_instance.target
+ values = { availability_zone = "eu-west-1c" }
+ }
+ expect_failures = [aws_lb_target_group_attachment.fixed]
+}
diff --git a/infra/modules/region-host/ingress/tests/fixed-targets/variables.tf b/infra/modules/region-host/ingress/tests/fixed-targets/variables.tf
new file mode 100644
index 000000000..3478c2213
--- /dev/null
+++ b/infra/modules/region-host/ingress/tests/fixed-targets/variables.tf
@@ -0,0 +1,56 @@
+variable "vpc_id" {
+ type = string
+ nullable = false
+ description = "VPC containing every load balancer subnet and target."
+}
+
+variable "zones" {
+ type = map(object({
+ subnet_id = string
+ allocation_id = string
+ }))
+ nullable = false
+ description = "Availability zones for the load balancer. Each entry supplies a subnet_id and an allocation_id. A null allocation_id creates a protected public address. Provide at least two zones in one VPC."
+ validation {
+ condition = length(var.zones) >= 2
+ error_message = "zones must include at least two distinct availability zones"
+ }
+ validation {
+ condition = length(distinct(compact([for zone in var.zones : zone.allocation_id]))) == length([for zone in var.zones : zone if zone.allocation_id != null])
+ error_message = "allocation_id must be used by only one availability zone"
+ }
+ validation {
+ condition = length(distinct([for zone in var.zones : zone.subnet_id])) == length(var.zones) && alltrue([for zone in var.zones : zone.subnet_id != null])
+ error_message = "each availability zone must name a different subnet"
+ }
+}
+
+variable "name" {
+ type = string
+ nullable = false
+ description = "Name prefix for the load balancer and its related resources."
+ validation {
+ condition = can(regex("^[a-zA-Z][a-zA-Z0-9-]{0,22}$", var.name)) && !startswith(var.name, "internal-")
+ error_message = "name must start with a letter, contain only letters, digits or hyphens, be at most 23 characters, and not start with internal-"
+ }
+}
+
+variable "target_vpc_cidrs" {
+ type = set(string)
+ nullable = false
+ description = "VPC CIDR blocks that the load balancer may use for target and health-check traffic."
+ validation {
+ condition = length(var.target_vpc_cidrs) > 0 && alltrue([for cidr in var.target_vpc_cidrs : can(cidrnetmask(cidr))])
+ error_message = "target_vpc_cidrs must match the target VPC"
+ }
+}
+
+variable "target_ids" {
+ type = set(string)
+ nullable = false
+ description = "Literal instance IDs of the existing fixed targets."
+ validation {
+ condition = length(var.target_ids) > 0 && alltrue([for id in var.target_ids : can(regex("^i-[0-9a-f]{17}$", id))])
+ error_message = "target_ids must contain literal EC2 instance IDs"
+ }
+}
diff --git a/infra/modules/region-host/ingress/tests/fixed-targets/versions.tf b/infra/modules/region-host/ingress/tests/fixed-targets/versions.tf
new file mode 100644
index 000000000..c028066c2
--- /dev/null
+++ b/infra/modules/region-host/ingress/tests/fixed-targets/versions.tf
@@ -0,0 +1,9 @@
+terraform {
+ required_version = ">= 1.10"
+ required_providers {
+ aws = {
+ source = "hashicorp/aws"
+ version = ">= 6.0"
+ }
+ }
+}
diff --git a/infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl b/infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl
new file mode 100644
index 000000000..5c90e6ee2
--- /dev/null
+++ b/infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl
@@ -0,0 +1,217 @@
+mock_provider "aws" {
+ mock_data "aws_subnets" {
+ defaults = { ids = ["subnet-0123456789abcdef0", "subnet-0123456789abcdef1"] }
+ }
+ mock_resource "aws_lb" {
+ defaults = {
+ arn = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:loadbalancer/net/shop-probe/0123456789abcdef"
+ arn_suffix = "net/shop-probe/0123456789abcdef"
+ }
+ }
+ mock_resource "aws_lb_target_group" {
+ defaults = {
+ arn = "arn:aws:elasticloadbalancing:eu-west-1:123456789012:targetgroup/shop-probe/0123456789abcdef"
+ arn_suffix = "targetgroup/shop-probe/0123456789abcdef"
+ }
+ }
+ mock_resource "aws_security_group" {
+ defaults = { id = "sg-0123456789abcdef0" }
+ }
+ mock_data "aws_vpc" {
+ defaults = {
+ cidr_block = "10.0.0.0/16"
+ cidr_block_associations = [{ cidr_block = "10.0.0.0/16", association_id = "vpc-cidr-assoc-0123456789abcdef0", state = "associated" }]
+ }
+ }
+ mock_data "aws_eip" {
+ defaults = { public_ip = "192.0.2.10" }
+ }
+}
+
+variables {
+ name = "shop-probe"
+ vpc_id = "vpc-0123456789abcdef0"
+ target_vpc_cidrs = ["10.0.0.0/16"]
+ zones = {
+ eu-west-1a = { subnet_id = "subnet-0123456789abcdef0", allocation_id = null }
+ eu-west-1b = { subnet_id = "subnet-0123456789abcdef1", allocation_id = null }
+ }
+}
+
+run "nlb_contract" {
+ command = plan
+ assert {
+ condition = alltrue([for az, subnet in data.aws_subnets.zone :
+ { for filter in subnet.filter : filter.name => toset(filter.values) } == {
+ subnet-id = toset([var.zones[az].subnet_id])
+ vpc-id = toset([var.vpc_id])
+ availability-zone = toset([az])
+ }
+ ])
+ error_message = "subnet lookups must filter by exact ID, VPC and zone"
+ }
+ assert {
+ condition = (
+ aws_lb.nlb.security_groups == toset([aws_security_group.nlb.id]) &&
+ output.nlb_security_group_id == aws_security_group.nlb.id &&
+ output.nlb_arn_suffix == aws_lb.nlb.arn_suffix &&
+ alltrue([for port, group in aws_lb_target_group.target :
+ output.target_group_arns[port] == group.arn && output.target_group_arn_suffixes[port] == group.arn_suffix &&
+ aws_lb_listener.tcp[port].default_action[0].target_group_arn == group.arn &&
+ aws_lb_listener.tcp[port].load_balancer_arn == aws_lb.nlb.arn
+ ])
+ )
+ error_message = "NLB, target groups, listeners and outputs must stay connected"
+ }
+ assert {
+ condition = (
+ aws_lb.nlb.load_balancer_type == "network" && !aws_lb.nlb.internal &&
+ aws_lb.nlb.ip_address_type == "ipv4" && aws_lb.nlb.enable_cross_zone_load_balancing &&
+ length(aws_lb.nlb.subnet_mapping) == 2 && length(aws_lb.nlb.security_groups) == 1
+ )
+ error_message = "NLB topology changed"
+ }
+ assert {
+ condition = alltrue([for key, tg in aws_lb_target_group.target :
+ tg.protocol == "TCP" && tg.port == tonumber(key) && tg.target_type == "instance" &&
+ tg.preserve_client_ip == "true" && tg.deregistration_delay == "30" &&
+ tg.health_check[0].protocol == "HTTP" && tg.health_check[0].port == "80" &&
+ tg.health_check[0].path == "/.carlos/lb-health" && tg.health_check[0].interval == 10 &&
+ tg.health_check[0].healthy_threshold == 2 && tg.health_check[0].unhealthy_threshold == 2 &&
+ tg.health_check[0].matcher == "200"
+ ]) && toset(keys(aws_lb_target_group.target)) == toset(["80", "443"])
+ error_message = "target and health-check contract changed"
+ }
+ assert {
+ condition = alltrue([for key, listener in aws_lb_listener.tcp :
+ listener.protocol == "TCP" && listener.port == tonumber(key) &&
+ listener.default_action[0].type == "forward"
+ ]) && toset(keys(aws_lb_listener.tcp)) == toset(["80", "443"])
+ error_message = "TCP passthrough listeners changed"
+ }
+ assert {
+ condition = (
+ toset(keys(output.public_ips)) == toset(keys(var.zones)) &&
+ toset(keys(output.allocation_ids)) == toset(keys(var.zones)) &&
+ toset(keys(output.target_group_arns)) == toset(["80", "443"]) &&
+ toset(keys(output.target_group_arn_suffixes)) == toset(["80", "443"])
+ )
+ error_message = "ingress output keys changed"
+ }
+}
+
+run "target_security" {
+ command = plan
+ assert {
+ condition = length(aws_security_group.nlb.ingress) == 2 && alltrue([
+ for rule in aws_security_group.nlb.ingress :
+ rule.protocol == "tcp" && contains([80, 443], rule.from_port) &&
+ rule.to_port == rule.from_port && rule.cidr_blocks == tolist(["0.0.0.0/0"]) &&
+ length(rule.prefix_list_ids) == 0 && length(rule.ipv6_cidr_blocks) == 0 && length(rule.security_groups) == 0 && !rule.self
+ ])
+ error_message = "NLB ingress must allow only public IPv4 TCP 80 and 443"
+ }
+ assert {
+ condition = length(aws_security_group.nlb.egress) == 2 && alltrue([
+ for rule in aws_security_group.nlb.egress :
+ rule.protocol == "tcp" && contains([80, 443], rule.from_port) &&
+ rule.to_port == rule.from_port && toset(rule.cidr_blocks) == toset(var.target_vpc_cidrs) &&
+ length(rule.prefix_list_ids) == 0 && length(rule.ipv6_cidr_blocks) == 0 && length(rule.security_groups) == 0 && !rule.self
+ ])
+ error_message = "NLB egress must allow only target and health ports within the VPC"
+ }
+}
+
+run "one_zone_refused" {
+ command = plan
+ variables {
+ zones = { eu-west-1a = { subnet_id = "subnet-0123456789abcdef0", allocation_id = null } }
+ }
+ expect_failures = [var.zones]
+}
+run "duplicate_allocation_refused" {
+ command = plan
+ variables {
+ zones = {
+ eu-west-1a = { subnet_id = "subnet-0123456789abcdef0", allocation_id = "eipalloc-0123456789abcdef0" }
+ eu-west-1b = { subnet_id = "subnet-0123456789abcdef1", allocation_id = "eipalloc-0123456789abcdef0" }
+ }
+ }
+ expect_failures = [var.zones]
+}
+run "wrong_vpc_refused" {
+ command = plan
+ override_data {
+ target = data.aws_subnets.zone
+ values = { ids = [] }
+ }
+ expect_failures = [aws_lb.nlb]
+}
+run "wrong_zone_refused" {
+ command = plan
+ override_data {
+ target = data.aws_subnets.zone
+ values = { ids = [] }
+ }
+ expect_failures = [aws_lb.nlb]
+}
+run "wrong_cidr_refused" {
+ command = plan
+ variables { target_vpc_cidrs = ["0.0.0.0/0"] }
+ expect_failures = [aws_security_group.nlb]
+}
+run "ipv6_cidr_refused" {
+ command = plan
+ variables { target_vpc_cidrs = ["::/0"] }
+ expect_failures = [var.target_vpc_cidrs]
+}
+run "supplied_allocation_has_one_owner" {
+ command = plan
+ variables {
+ zones = {
+ eu-west-1a = { subnet_id = "subnet-0123456789abcdef0", allocation_id = "eipalloc-0123456789abcdef0" }
+ eu-west-1b = { subnet_id = "subnet-0123456789abcdef1", allocation_id = null }
+ }
+ }
+ assert {
+ condition = (
+ keys(aws_eip.public) == ["eu-west-1b"] &&
+ keys(data.aws_eip.existing) == ["eu-west-1a"] &&
+ output.allocation_ids["eu-west-1a"] == "eipalloc-0123456789abcdef0" &&
+ output.public_ips["eu-west-1a"] == "192.0.2.10"
+ )
+ error_message = "supplied allocations must remain externally owned"
+ }
+}
+run "protected_addresses" {
+ command = plan
+ assert {
+ condition = strcontains(file("${path.module}/main.tf"), "prevent_destroy = true")
+ error_message = "Ingress addresses are protected from deletion. Remove this protection only in a reviewed disposable experiment copy."
+ }
+}
+
+run "duplicate_subnet_refused" {
+ command = plan
+ variables {
+ zones = {
+ eu-west-1a = { subnet_id = "subnet-0123456789abcdef0", allocation_id = null }
+ eu-west-1b = { subnet_id = "subnet-0123456789abcdef0", allocation_id = null }
+ }
+ }
+ expect_failures = [var.zones]
+}
+run "secondary_cidr_missing_refused" {
+ command = plan
+ override_data {
+ target = data.aws_vpc.target
+ values = {
+ cidr_block = "10.0.0.0/16"
+ cidr_block_associations = [
+ { cidr_block = "10.0.0.0/16", association_id = "primary", state = "associated" },
+ { cidr_block = "10.1.0.0/16", association_id = "secondary", state = "associated" }
+ ]
+ }
+ }
+ expect_failures = [aws_security_group.nlb]
+}
diff --git a/infra/modules/region-host/ingress/variables.tf b/infra/modules/region-host/ingress/variables.tf
new file mode 100644
index 000000000..60535de29
--- /dev/null
+++ b/infra/modules/region-host/ingress/variables.tf
@@ -0,0 +1,46 @@
+variable "vpc_id" {
+ type = string
+ nullable = false
+ description = "VPC containing every load balancer subnet and target."
+}
+
+variable "zones" {
+ type = map(object({
+ subnet_id = string
+ allocation_id = string
+ }))
+ nullable = false
+ description = "Availability zones for the load balancer. Each entry supplies a subnet_id and an allocation_id. A null allocation_id creates a protected public address. Provide at least two zones in one VPC."
+ validation {
+ condition = length(var.zones) >= 2
+ error_message = "zones must include at least two distinct availability zones"
+ }
+ validation {
+ condition = length(distinct(compact([for zone in var.zones : zone.allocation_id]))) == length([for zone in var.zones : zone if zone.allocation_id != null])
+ error_message = "allocation_id must be used by only one availability zone"
+ }
+ validation {
+ condition = length(distinct([for zone in var.zones : zone.subnet_id])) == length(var.zones) && alltrue([for zone in var.zones : zone.subnet_id != null])
+ error_message = "each availability zone must name a different subnet"
+ }
+}
+
+variable "name" {
+ type = string
+ nullable = false
+ description = "Name prefix for the load balancer and its related resources."
+ validation {
+ condition = can(regex("^[a-zA-Z][a-zA-Z0-9-]{0,22}$", var.name)) && !startswith(var.name, "internal-")
+ error_message = "name must start with a letter, contain only letters, digits or hyphens, be at most 23 characters, and not start with internal-"
+ }
+}
+
+variable "target_vpc_cidrs" {
+ type = set(string)
+ nullable = false
+ description = "VPC CIDR blocks that the load balancer may use for target and health-check traffic."
+ validation {
+ condition = length(var.target_vpc_cidrs) > 0 && alltrue([for cidr in var.target_vpc_cidrs : can(cidrnetmask(cidr))])
+ error_message = "target_vpc_cidrs must match the target VPC"
+ }
+}
diff --git a/infra/modules/region-host/ingress/versions.tf b/infra/modules/region-host/ingress/versions.tf
new file mode 100644
index 000000000..c028066c2
--- /dev/null
+++ b/infra/modules/region-host/ingress/versions.tf
@@ -0,0 +1,9 @@
+terraform {
+ required_version = ">= 1.10"
+ required_providers {
+ aws = {
+ source = "hashicorp/aws"
+ version = ">= 6.0"
+ }
+ }
+}
diff --git a/infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl b/infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl
new file mode 100644
index 000000000..ca68ecb17
--- /dev/null
+++ b/infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl
@@ -0,0 +1,97 @@
+# Plan-time tests for the host instance's metadata service settings.
+# mock_provider means no AWS account and no credentials.
+mock_provider "aws" {}
+
+override_data {
+ target = data.aws_vpcs.default
+ values = { ids = ["vpc-0aaaaaaaaaaaaaaaa"] }
+}
+
+override_data {
+ target = data.aws_caller_identity.current
+ values = { account_id = "123456789012" }
+}
+
+# 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" }
+}
+
+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/*"
+}
+
+
+override_data {
+ target = data.aws_ami.debian_arm64
+ values = { id = "ami-0123456789abcdef0" }
+}
+override_data {
+ target = data.aws_vpc.host
+ values = { cidr_block = "10.0.0.0/16" }
+}
+override_resource {
+ target = aws_instance.host
+ values = { id = "i-0123456789abcdef0" }
+}
+override_resource {
+ target = aws_security_group.host
+ values = { id = "sg-0123456789abcdef0" }
+}
+override_resource {
+ target = aws_iam_role.host
+ values = { arn = "arn:aws:iam::123456789012:role/carlos-test-host" }
+}
+override_resource {
+ target = aws_eip.host
+ values = { public_ip = "192.0.2.10" }
+}
+run "fixed_state_unchanged" {
+ command = plan
+ assert {
+ condition = (
+ aws_instance.host.instance_type == "t4g.small" &&
+ aws_instance.host.iam_instance_profile == "carlos-test-host" &&
+ aws_instance.host.vpc_security_group_ids == toset(["sg-0123456789abcdef0"]) &&
+ aws_instance.host.user_data == "#!/bin/sh\n" &&
+ !aws_instance.host.user_data_replace_on_change &&
+ aws_instance.host.root_block_device[0].volume_size == 20 &&
+ aws_instance.host.root_block_device[0].volume_type == "gp3" &&
+ aws_instance.host.root_block_device[0].encrypted &&
+ aws_instance.host.root_block_device[0].delete_on_termination &&
+ aws_eip.host.instance == "i-0123456789abcdef0" &&
+ aws_iam_instance_profile.host.role == "carlos-test-host"
+ )
+ error_message = "fixed instance, profile, security group and volume contract changed"
+ }
+ assert {
+ condition = (
+ output.instance_id == "i-0123456789abcdef0" &&
+ output.eip_public_ip == "192.0.2.10" &&
+ output.security_group_id == "sg-0123456789abcdef0" &&
+ output.role_name == "carlos-test-host" &&
+ output.role_arn == "arn:aws:iam::123456789012:role/carlos-test-host" &&
+ output.ami_id == "ami-0123456789abcdef0" &&
+ output.vpc_cidr == "10.0.0.0/16" && output.store_user_boundary_arn == null
+ )
+ error_message = "legacy fixed outputs changed"
+ }
+ assert {
+ condition = length(aws_security_group.host.ingress) == 2 && alltrue([
+ for rule in aws_security_group.host.ingress :
+ rule.protocol == "tcp" && contains([80, 443], rule.from_port) &&
+ rule.to_port == rule.from_port && rule.cidr_blocks == tolist(["0.0.0.0/0"])
+ ])
+ error_message = "fixed public ingress changed"
+ }
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 75956ce81..b05325a0a 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -75,3 +75,4 @@ plan14-root-reads-domains-check-country.tsv b0fc198c53bb0dacba33a54c3d8bf8fe5ac0
plan14-root-reads-static-stream-extract.tsv 7fb932b118e67e23b33a374c6a4020b38976667c7ec4cfb855c0f8b598b1756b
plan14-root-reads-ls284.tsv 744b16d970f22476b79982e57c326157ca5137fa96ccaee4a7ae10c25248d124
plan14-root-reads-region-ha-p1b3b-t.tsv c68e2453bfc8afaf3794eb4c08850428982fa6954269b6b99bddfda4e6242929
+plan14-root-reads-region-ha-p3a.tsv f2d9c89885a0019f5a30651f8019bb6f0c55bf84b412e045e59e30b66b4bf32e
diff --git a/internal/provision/testdata/plan14-root-reads-region-ha-p3a.tsv b/internal/provision/testdata/plan14-root-reads-region-ha-p3a.tsv
new file mode 100644
index 000000000..7e019ff1b
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-region-ha-p3a.tsv
@@ -0,0 +1,28 @@
+# Census overlay region-ha-p3a, written by census-propose (#369). census-ruling-region-ha-p3a, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-region-ha-p3a.md.
+# 0 body, 0 sites, 5 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 10 new dispositions: 0 reads re-frozen at their disposition with the claim, 10 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy 377eb01304b9a5473fcef2354ef85dd2ba95785c48ff2ba1a0782778499989ef infra/modules/region-host/ingress/main.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add isolated IPv4 NLB, VPC/zone lookups, validated CIDR egress, protected new EIPs and TCP health-checked target groups; no fixed-resource edits or root runtime reads. file:external@0 103369ef62af3311ee0e01e751e23a03ca3634015841f0a9437ee7e682353d37
+@legacy c1636b10d14fd359d718264048fe782d0405dde3102b72a1a8eac270c37b14f6 infra/modules/region-host/ingress/outputs.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Expose per-zone addresses and NLB/TG identities for root attachments and Task 4 alarms; no root runtime reads. file:external@0 83d036fd1e80e375df647bfbb84eb9307faa97ad5511672c938a164919f246a9
+@legacy 7a49227972307af74b52e450dc5ea86547395d41192f24792c71ca21db3b474d infra/modules/region-host/ingress/tests/fixed-targets/main.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add dev-root fixture attaching literal instance IDs to both target groups with read-only AZ lookups and target-zone precondition; no fixed-module references or root runtime reads. file:external@0 98e19cac1a98259ba7f3c1e9ab95471e25afa2ae77c54bd4c575a2e094fac62e
+@legacy b113d1b975dae34ecf57a2b5c98e94c8d6f89fd7476e321202c25886b866cb08 infra/modules/region-host/ingress/tests/fixed-targets/tests/targets.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add plan-only mock witnesses for target attachments and out-of-zone refusal; no live API calls or root runtime reads. file:external@0 9fc255e828aaff0d55d156caa417e40fcf3afb8d9ef29b025f4178ca669799fb
+@legacy 5d72b4a4f0a34f5cc4ef70092940738197fb5c1aa4ec382127cabdd9c82702bc infra/modules/region-host/ingress/tests/fixed-targets/variables.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Define explicit ingress and literal target inputs for the dev-root fixture; no root runtime reads. file:external@0 644a067756d767c5668463eca9c1e4a45af902aacf140ef9cca437f3a24efde4
+@legacy 5f2c8be4b3fe6775f9542426e5c729a4b16115dafa420b0e63040f71bd80f685 infra/modules/region-host/ingress/tests/fixed-targets/versions.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Declare OpenTofu/AWS provider requirements for the dev-root fixture; no root runtime reads. file:external@0 bb3be812da255c0f031b2bfdfee462e4687de3681c742b529b55693a8875136b
+@legacy aa756aff32e21027c70a4766381edfbb2acfc2bacf921909a5dfe735816f4a0c infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add plan-only mock tests for NLB protocol, health, zone/VPC boundary, protected allocations and restricted SG traffic; no live API calls or root runtime reads. file:external@0 ab86b091ae5ef1bfcd20d99b0643d85d8eb888a003e47bf06e28922c5adbdc40
+@legacy 0c7e79156fc210a3460e9cbce1a7e26edbf22f0c799710f3e82e1a09a483d994 infra/modules/region-host/ingress/variables.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add ingress-only inputs and topology/CIDR validation; no root runtime reads. file:external@0 a1599da50d212d5e64f527719ee781e5a0a494185d144f0a958433741f4c9d36
+@legacy 134888d1b095e8268cdd1cd04df27087407ae3fee1c4742f0df5a431520783ef infra/modules/region-host/ingress/versions.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Declare OpenTofu and AWS provider requirements for the isolated ingress child; no root runtime reads. file:external@0 bb3be812da255c0f031b2bfdfee462e4687de3681c742b529b55693a8875136b
+@legacy 73e967bb630a74f28c53f50b63c997d086154b025cf7b59074d5b0fe2fc3bea7 infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add mock regression for the unchanged fixed instance/profile/SG/root-volume wiring and legacy outputs; no root runtime reads. file:external@0 cab0fdd9e01c4497f06a617db6c41aa9887da80bd0518c76fe8eba935be42c85
+infra/modules/region-host/ingress/main.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add isolated IPv4 NLB, VPC/zone lookups, validated CIDR egress, protected new EIPs and TCP health-checked target groups; no fixed-resource edits or root runtime reads. file:external@0 103369ef62af3311ee0e01e751e23a03ca3634015841f0a9437ee7e682353d37
+infra/modules/region-host/ingress/outputs.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Expose per-zone addresses and NLB/TG identities for root attachments and Task 4 alarms; no root runtime reads. file:external@0 83d036fd1e80e375df647bfbb84eb9307faa97ad5511672c938a164919f246a9
+infra/modules/region-host/ingress/tests/fixed-targets/main.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add dev-root fixture attaching literal instance IDs to both target groups with read-only AZ lookups and target-zone precondition; no fixed-module references or root runtime reads. file:external@0 98e19cac1a98259ba7f3c1e9ab95471e25afa2ae77c54bd4c575a2e094fac62e
+infra/modules/region-host/ingress/tests/fixed-targets/tests/targets.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add plan-only mock witnesses for target attachments and out-of-zone refusal; no live API calls or root runtime reads. file:external@0 9fc255e828aaff0d55d156caa417e40fcf3afb8d9ef29b025f4178ca669799fb
+infra/modules/region-host/ingress/tests/fixed-targets/variables.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Define explicit ingress and literal target inputs for the dev-root fixture; no root runtime reads. file:external@0 644a067756d767c5668463eca9c1e4a45af902aacf140ef9cca437f3a24efde4
+infra/modules/region-host/ingress/tests/fixed-targets/versions.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Declare OpenTofu/AWS provider requirements for the dev-root fixture; no root runtime reads. file:external@0 bb3be812da255c0f031b2bfdfee462e4687de3681c742b529b55693a8875136b
+infra/modules/region-host/ingress/tests/group_ingress.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add plan-only mock tests for NLB protocol, health, zone/VPC boundary, protected allocations and restricted SG traffic; no live API calls or root runtime reads. file:external@0 ab86b091ae5ef1bfcd20d99b0643d85d8eb888a003e47bf06e28922c5adbdc40
+infra/modules/region-host/ingress/variables.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add ingress-only inputs and topology/CIDR validation; no root runtime reads. file:external@0 a1599da50d212d5e64f527719ee781e5a0a494185d144f0a958433741f4c9d36
+infra/modules/region-host/ingress/versions.tf external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Declare OpenTofu and AWS provider requirements for the isolated ingress child; no root runtime reads. file:external@0 bb3be812da255c0f031b2bfdfee462e4687de3681c742b529b55693a8875136b
+infra/modules/region-host/tests/fixed_state_unchanged.tftest.hcl external legacy accepted-legacy accepted-legacy;rev3=census-ruling-region-ha-p3a;basis=Add mock regression for the unchanged fixed instance/profile/SG/root-volume wiring and legacy outputs; no root runtime reads. file:external@0 cab0fdd9e01c4497f06a617db6c41aa9887da80bd0518c76fe8eba935be42c85
+@coverage infra/modules/region-host/ingress 009777ca5464e8e6e0bfda45c00229b8924e0dc55f39d7d3036bca2b2d4f871e
+@coverage infra/modules/region-host/ingress/tests 2d7e20b48fd461253375a250c0fd01a19160a42873136e33777b588770a0b3d5
+@coverage infra/modules/region-host/ingress/tests/fixed-targets f99d9d22e9ad6820b3fcc4e5210dad538a62274005c6fdd7c4a3af292aef91cc
+@coverage infra/modules/region-host/ingress/tests/fixed-targets/tests 567e4b97ac15cea31cb88aba77dccf739e58382158dba13d6b03e22935995b52
+@coverage infra/modules/region-host/tests 18abb8044924e7422d67f4266905e6da7d024426cd7846868fca55932adbb9ae
diff --git a/scripts/check-region-group-plan.py b/scripts/check-region-group-plan.py
new file mode 100755
index 000000000..dccf197aa
--- /dev/null
+++ b/scripts/check-region-group-plan.py
@@ -0,0 +1,395 @@
+#!/usr/bin/env python3
+import argparse
+import json
+import re
+import sys
+
+DECREASE = 'plan refused. the minimum, maximum or desired size of %s would decrease'
+FIXED = 'plan refused. %s would %s, but fixed box resources cannot be changed'
+UNKNOWN = 'plan refused. the guarded resource %s has values or a change shape this gate cannot safely read'
+PROTECTED = 'plan refused. protected ingress address %s would be deleted or replaced'
+ALLOW = 'plan refused. an allow-list entry must name one address and one attribute, include before and after values, a purpose and an approval. wildcards and whole-resource entries are not allowed'
+MANIFEST = 'plan refused. the cleanup manifest names a fixed box or a pre-existing regional address'
+OK = 'plan approved. checked %d resources'
+PARSE = 'could not read the plan or review file: %s'
+
+IDENT = r'[A-Za-z_][A-Za-z_0-9-]*'
+INDEX = r'\[(?:[0-9]+|"(?:[^"\\]|\\.)*")\]'
+ADDRESS = re.compile(rf'(?:module\.{IDENT}(?:{INDEX})?\.)*(?P<data>data\.)?'
+ rf'(?P<type>{IDENT})\.(?P<name>{IDENT})(?:{INDEX})?')
+RULES = {'aws_security_group_rule', 'aws_vpc_security_group_ingress_rule',
+ 'aws_vpc_security_group_egress_rule'}
+HOST_IAM = {'aws_iam_role', 'aws_iam_instance_profile', 'aws_iam_role_policy',
+ 'aws_iam_role_policy_attachment', 'aws_iam_policy', 'aws_iam_policy_attachment'}
+CHANGE_FIELDS = {'actions', 'before', 'after', 'after_unknown', 'before_sensitive',
+ 'after_sensitive', 'replace_paths', 'importing', 'generated_config'}
+ACTIONS = [['no-op'], ['create'], ['read'], ['update'], ['delete'],
+ ['delete', 'create'], ['create', 'delete']]
+DISPOSABLE = {('aws_eip', 'public'), ('aws_lb', 'nlb'), ('aws_security_group', 'nlb'),
+ ('aws_lb_target_group', 'target'), ('aws_lb_listener', 'tcp'),
+ ('aws_lb_target_group_attachment', 'fixed'),
+ ('aws_autoscaling_group', 'group'), ('aws_launch_template', 'group')}
+MISSING = object()
+
+
+class Refused(Exception):
+ pass
+
+
+def same(left, right):
+ # JSON booleans and numbers compare equal in Python unless types are preserved.
+ return json.dumps(left, sort_keys=True) == json.dumps(right, sort_keys=True)
+
+
+def address_parts(address):
+ if not isinstance(address, str):
+ return None
+ return ADDRESS.fullmatch(address)
+
+
+def fixed(kind, name):
+ return (kind == 'aws_instance' or kind in RULES or
+ kind in {'aws_security_group', 'aws_eip'} and name == 'host' or
+ kind in HOST_IAM and (name == 'host' or name.startswith('host_') or
+ name == 'store_user_boundary'))
+
+
+def unknown(value):
+ if value is False:
+ return False
+ if isinstance(value, dict):
+ return any(unknown(v) for v in value.values())
+ if isinstance(value, list):
+ return any(unknown(v) for v in value)
+ return True
+
+
+def changes(document):
+ if (not isinstance(document, dict) or
+ not re.fullmatch(r'1\.[0-9]+', str(document.get('format_version', ''))) or
+ not isinstance(document.get('resource_changes'), list)):
+ raise ValueError('invalid plan structure or format_version')
+ if document.get('errored') is True:
+ raise Refused(UNKNOWN % '<plan>')
+ rows = document['resource_changes']
+ drift = document.get('resource_drift', [])
+ if not isinstance(drift, list):
+ raise ValueError('invalid resource_drift')
+ return rows + drift
+
+
+def parse_resource(row):
+ if not isinstance(row, dict):
+ raise Refused(UNKNOWN % '<resource>')
+ address = row.get('address')
+ parts = address_parts(address)
+ if (parts is None or row.get('type') != parts['type'] or row.get('name') != parts['name'] or
+ row.get('mode') != ('data' if parts['data'] else 'managed')):
+ raise Refused(UNKNOWN % address)
+ change = row.get('change')
+ if (not isinstance(change, dict) or
+ not {'actions', 'before', 'after', 'after_unknown'} <= change.keys() or
+ not change.keys() <= CHANGE_FIELDS or
+ not isinstance(change['after_unknown'], (dict, bool)) or
+ change['actions'] not in ACTIONS or
+ any(value is not None and not isinstance(value, dict)
+ for value in (change['before'], change['after'])) or
+ change.get('importing') is not None or change.get('generated_config') is not None):
+ raise Refused(UNKNOWN % address)
+ actions, before, after = change['actions'], change['before'], change['after']
+ if (actions == ['create'] and (before is not None or after is None) or
+ actions == ['delete'] and (before is None or after is not None) or
+ actions in [['no-op'], ['update'], ['delete', 'create'], ['create', 'delete']]
+ and (before is None or after is None)):
+ raise Refused(UNKNOWN % address)
+ if actions == ['no-op'] and not same(before, after):
+ raise Refused(UNKNOWN % address)
+ previous = row.get('previous_address')
+ if previous is not None:
+ old = address_parts(previous)
+ if (old is None or old['type'] != parts['type'] or old['data'] != parts['data'] or
+ actions != ['no-op'] or not same(before, after) or unknown(change['after_unknown'])):
+ raise Refused(UNKNOWN % address)
+ return address, parts['type'], parts['name'], change
+
+
+def pointer_tokens(pointer):
+ if (not isinstance(pointer, str) or not pointer.startswith('/') or pointer == '/' or
+ '*' in pointer or '?' in pointer or re.search(r'~(?![01])', pointer)):
+ raise Refused(ALLOW)
+ return [s.replace('~1', '/').replace('~0', '~') for s in pointer[1:].split('/')]
+
+
+def lookup(value, tokens):
+ for token in tokens:
+ if isinstance(value, dict):
+ value = value.get(token, MISSING)
+ elif isinstance(value, list) and re.fullmatch(r'0|[1-9][0-9]*', token):
+ index = int(token)
+ value = value[index] if index < len(value) else MISSING
+ else:
+ return MISSING
+ return value
+
+
+def differences(before, after, path=()):
+ if same(before, after):
+ return []
+ if isinstance(before, dict) and isinstance(after, dict):
+ out = []
+ for key in before.keys() | after.keys():
+ if key not in before or key not in after:
+ out.append(path + (key,))
+ else:
+ out.extend(differences(before[key], after[key], path + (key,)))
+ return out
+ if isinstance(before, list) and isinstance(after, list) and len(before) == len(after):
+ return [diff for index, (old, new) in enumerate(zip(before, after))
+ for diff in differences(old, new, path + (str(index),))]
+ return [path]
+
+
+def allow_entries(entries):
+ if not isinstance(entries, list):
+ raise Refused(ALLOW)
+ seen = set()
+ for entry in entries:
+ if (not isinstance(entry, dict) or
+ set(entry) != {'address', 'attribute', 'before', 'after', 'purpose', 'approval'} or
+ address_parts(entry['address']) is None or
+ any(c in entry['address'] for c in '*?') or
+ any(not isinstance(entry[k], str) or not entry[k].strip() for k in ['purpose', 'approval'])):
+ raise Refused(ALLOW)
+ pointer_tokens(entry['attribute'])
+ key = (entry['address'], entry['attribute'])
+ if key in seen:
+ raise Refused(ALLOW)
+ seen.add(key)
+ return entries
+
+
+def allowed(address, change, entries):
+ if change['actions'] != ['update']:
+ return False
+ paths = []
+ for entry in entries:
+ if entry['address'] != address:
+ continue
+ tokens = pointer_tokens(entry['attribute'])
+ before, after = (lookup(change[k], tokens) for k in ['before', 'after'])
+ if (before is MISSING or after is MISSING or same(before, after) or
+ not same(before, entry['before']) or not same(after, entry['after'])):
+ raise Refused(ALLOW)
+ paths.append(tuple(tokens))
+ diffs = differences(change['before'], change['after'])
+ return bool(paths) and bool(diffs) and all(
+ any(diff[:len(path)] == path for path in paths) for diff in diffs)
+
+
+def state_resources(document):
+ def walk(module):
+ if not isinstance(module, dict):
+ raise ValueError('invalid prior_state module')
+ resources = module.get('resources', [])
+ children = module.get('child_modules', [])
+ if not isinstance(resources, list) or not isinstance(children, list):
+ raise ValueError('invalid prior_state resources')
+ for row in resources:
+ if not isinstance(row, dict) or not isinstance(row.get('values'), dict):
+ raise ValueError('invalid prior_state resource')
+ yield row
+ for child in children:
+ yield from walk(child)
+ prior = document.get('prior_state', {})
+ if not isinstance(prior, dict):
+ raise ValueError('invalid prior_state')
+ values = prior.get('values', {})
+ if not isinstance(values, dict):
+ raise ValueError('invalid prior_state values')
+ return list(walk(values.get('root_module', {})))
+
+
+def cleanup_entries(manifest, rows):
+ if manifest is None:
+ return set()
+ if (not isinstance(manifest, dict) or
+ set(manifest) != {'purpose', 'approval', 'resources', 'creation_plan'} or
+ any(not isinstance(manifest[k], str) or not manifest[k].strip() for k in ['purpose', 'approval']) or
+ not isinstance(manifest['resources'], list) or not manifest['resources']):
+ raise Refused(MANIFEST)
+ # The reviewed creation plan proves these addresses were new. The allocation
+ # IDs, filled in after that apply, bind cleanup to those exact allocations.
+ creation = manifest['creation_plan']
+ try:
+ created = {row['address']: row for row in changes(creation)}
+ prior_eips = {row['values'].get('id') for row in state_resources(creation)
+ if row.get('type') == 'aws_eip'}
+ prior_addresses = {row['address'] for row in state_resources(creation)}
+ for row in changes(creation):
+ if row.get('type') == 'aws_eip':
+ if row['change'].get('before'):
+ prior_eips.add(row['change']['before'].get('id'))
+ if row.get('mode') == 'data' and row['change'].get('after'):
+ prior_eips.add(row['change']['after'].get('id'))
+ except (KeyError, TypeError, ValueError):
+ raise Refused(MANIFEST) from None
+ current = {row['address']: row for row in rows}
+ disposable, allocations = set(), set()
+ for entry in manifest['resources']:
+ if not isinstance(entry, dict) or not isinstance(entry.get('address'), str):
+ raise Refused(MANIFEST)
+ address = entry['address']
+ if address in disposable or address in prior_addresses or address not in current or address not in created:
+ raise Refused(MANIFEST)
+ _, kind, name, change = parse_resource(current[address])
+ if (fixed(kind, name) or (kind, name) not in DISPOSABLE or
+ current[address]['mode'] != 'managed' or change['actions'] != ['delete'] or
+ unknown(change['after_unknown'])):
+ raise Refused(MANIFEST)
+ birth = created[address]
+ _, _, _, first = parse_resource(birth)
+ if (birth['mode'] != 'managed' or first['actions'] != ['create'] or
+ 'previous_address' in birth):
+ raise Refused(MANIFEST)
+ if kind == 'aws_eip':
+ allocation = entry.get('allocation_id')
+ if (set(entry) != {'address', 'allocation_id'} or not isinstance(allocation, str) or
+ not allocation.startswith('eipalloc-') or allocation in prior_eips or allocation in allocations or
+ allocation != change['before'].get('id')):
+ raise Refused(MANIFEST)
+ allocations.add(allocation)
+ elif set(entry) != {'address'}:
+ raise Refused(MANIFEST)
+ disposable.add(address)
+ return disposable
+
+
+def check(document, entries, manifest):
+ rows = changes(document)
+ parsed = [parse_resource(row) for row in rows]
+ entries = allow_entries(entries)
+ disposable = cleanup_entries(manifest, rows)
+ existing = [(address, kind, name, change['before'])
+ for row, (address, kind, name, change) in zip(rows, parsed)
+ if row['mode'] == 'managed' and change['before'] is not None]
+ existing += [(row['address'], row.get('type'), row.get('name'), row['values'])
+ for row in state_resources(document) if row.get('mode') == 'managed']
+ fixed_modules, roles, allocations, instances, public_ips = set(), set(), set(), set(), set()
+ for address, kind, name, values in existing:
+ parts = address_parts(address)
+ if parts is None or not isinstance(name, str):
+ raise Refused(UNKNOWN % address)
+ if fixed(kind, name) and kind not in RULES:
+ fixed_modules.add(address[:parts.start('type')])
+ if kind == 'aws_iam_role' and name == 'host':
+ roles.update(v for k in ['name', 'id', 'arn'] if isinstance(v := values.get(k), str))
+ if kind == 'aws_eip':
+ allocations.update(v for k in ['id', 'allocation_id'] if isinstance(v := values.get(k), str))
+ if isinstance(values.get('public_ip'), str):
+ public_ips.add(values['public_ip'])
+ if kind == 'aws_instance' and isinstance(values.get('id'), str):
+ instances.add(values['id'])
+ host_sgs = {c['before'].get('id') for _, kind, name, c in parsed
+ if kind == 'aws_security_group' and name == 'host' and c['before']}
+ host_sgs.update(row['values'].get('id') for row in state_resources(document)
+ if row.get('type') == 'aws_security_group' and row.get('name') == 'host')
+ host_sgs.discard(None)
+ for row, (address, kind, name, change) in zip(rows, parsed):
+ if row['mode'] == 'data':
+ continue
+ before, after, actions = change['before'], change['after'], change['actions']
+ # Adding a standalone rule also changes a fixed SG. Unknown destinations
+ # are refused; this module uses inline rules for its new NLB SG.
+ if kind in RULES and actions == ['create']:
+ sg = after.get('security_group_id')
+ if not sg or sg in host_sgs or unknown(change['after_unknown']):
+ raise Refused(FIXED % (address, 'create'))
+ parts = address_parts(address)
+ same_module = address[:parts.start('type')] in fixed_modules
+ related = False
+ if kind in HOST_IAM:
+ for values in [before, after]:
+ if values is not None:
+ related = related or values.get('role') in roles or bool(set(values.get('roles') or []) & roles)
+ if same_module and unknown(change['after_unknown']):
+ related = True
+ if kind == 'aws_eip_association':
+ for values in [before, after]:
+ if values is not None:
+ related = (related or values.get('allocation_id') in allocations or
+ values.get('instance_id') in instances or values.get('public_ip') in public_ips)
+ related = related or unknown(change['after_unknown'])
+ is_fixed = fixed(kind, name) or related
+ if before is None:
+ if actions == ['create'] and (related or is_fixed and same_module):
+ raise Refused(FIXED % (address, 'create'))
+ continue
+ guarded = is_fixed or kind in {'aws_eip', 'aws_autoscaling_group'}
+ if guarded and (unknown(change['after_unknown']) or actions == ['read']):
+ raise Refused(UNKNOWN % address)
+ if address in disposable:
+ continue
+ if is_fixed:
+ if actions == ['no-op'] and same(before, after):
+ continue
+ if not allowed(address, change, entries):
+ raise Refused(FIXED % (address, '/'.join(actions)))
+ elif kind == 'aws_eip':
+ if 'delete' in actions:
+ raise Refused(PROTECTED % address)
+ if actions == ['no-op'] and not same(before, after):
+ raise Refused(UNKNOWN % address)
+ elif kind == 'aws_autoscaling_group':
+ if 'delete' in actions:
+ raise Refused(DECREASE % address)
+ for key in ['min_size', 'max_size', 'desired_capacity']:
+ old, new = before.get(key), after.get(key)
+ if (type(old) is not int or type(new) is not int or old < 0 or new < 0):
+ raise Refused(UNKNOWN % address)
+ if new < old:
+ raise Refused(DECREASE % address)
+ # Stale exceptions do not silently carry into a different plan.
+ for entry in entries:
+ matches = [change for address, _, _, change in parsed if address == entry['address']]
+ if len(matches) != 1 or not allowed(entry['address'], matches[0], [entry]):
+ # Multiple exact attributes on one resource are checked together above.
+ if len(matches) != 1 or not allowed(entry['address'], matches[0], entries):
+ raise Refused(ALLOW)
+ return len(rows)
+
+
+def read_json(path):
+ def pairs(items):
+ result = {}
+ for key, value in items:
+ if key in result:
+ raise ValueError('duplicate JSON key')
+ result[key] = value
+ return result
+ def invalid_constant(value):
+ raise ValueError('invalid JSON constant')
+ with open(path, encoding='utf-8') as source:
+ return json.load(source, object_pairs_hook=pairs, parse_constant=invalid_constant)
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('plan')
+ parser.add_argument('--allow-list')
+ parser.add_argument('--cleanup-manifest')
+ args = parser.parse_args()
+ try:
+ count = check(read_json(args.plan), read_json(args.allow_list) if args.allow_list else [],
+ read_json(args.cleanup_manifest) if args.cleanup_manifest else None)
+ except Refused as error:
+ print(error, file=sys.stderr)
+ return 1
+ except (OSError, ValueError, TypeError, KeyError, RecursionError) as error:
+ print(PARSE % error, file=sys.stderr)
+ return 2
+ print(OK % count)
+ return 0
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/scripts/check_region_group_plan_test.py b/scripts/check_region_group_plan_test.py
new file mode 100644
index 000000000..0116f78df
--- /dev/null
+++ b/scripts/check_region_group_plan_test.py
@@ -0,0 +1,256 @@
+import copy
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+import tempfile
+import unittest
+
+GATE = Path(__file__).with_name('check-region-group-plan.py')
+FIXED = 'module.deployment["dev"].module.ie.aws_instance.host'
+EIP = 'module.probe.aws_eip.public["eu-west-1a"]'
+
+
+def resource(address=FIXED, kind='aws_instance', name='host', before=None,
+ after=None, actions=None, unknown=None, **extra):
+ return dict(address=address, mode='managed', type=kind, name=name,
+ change=dict(actions=actions or ['update'], before=before,
+ after=after, after_unknown=unknown or {}), **extra)
+
+
+def plan(*resources):
+ return dict(format_version='1.2', resource_changes=list(resources))
+
+
+class GateTests(unittest.TestCase):
+ def gate(self, document, expected, allow=None, cleanup=None):
+ with tempfile.TemporaryDirectory(dir=os.environ.get('TMPDIR')) as tmp:
+ root = Path(tmp)
+ path = root / 'plan.json'
+ path.write_text(json.dumps(document))
+ args = [sys.executable, str(GATE), str(path)]
+ for flag, value in [('--allow-list', allow), ('--cleanup-manifest', cleanup)]:
+ if value is not None:
+ path = root / (flag[2:] + '.json')
+ path.write_text(json.dumps(value))
+ args.extend([flag, str(path)])
+ result = subprocess.run(args, text=True, capture_output=True)
+ self.assertEqual(expected, result.returncode, result.stdout + result.stderr)
+ return result
+
+ def test_saved_plan_fixtures(self):
+ for name, expected in [('new-ingress.json', 0), ('targeted-fixed-user-data.json', 1),
+ ('unchanged-move.json', 0), ('fixed-eip-reassociation.json', 1)]:
+ with self.subTest(name=name):
+ document = json.loads((GATE.parent / 'testdata/region-group-plan' / name).read_text())
+ self.gate(document, expected)
+
+ def test_fixed_updates_and_targeted_closure(self):
+ for attr in ['user_data', 'instance_type', 'iam_instance_profile', 'root_block_device']:
+ with self.subTest(attr=attr):
+ self.gate(plan(resource(before={attr: 'old'}, after={attr: 'new'})), 1)
+ self.gate(plan(resource(before={'user_data': 'old'}, after={'user_data': 'new'}),
+ resource('module.probe.aws_lb.nlb', 'aws_lb', 'nlb',
+ after={}, actions=['create'], unknown={'arn': True})), 1)
+
+ def test_all_fixed_resource_names_at_any_module_path(self):
+ names = {'aws_instance': ['host', 'another_fixed_box'],
+ 'aws_security_group': ['host'],
+ 'aws_iam_role': ['host'], 'aws_iam_instance_profile': ['host'],
+ 'aws_iam_role_policy': ['host_buckets', 'host_route53', 'host_steering',
+ 'host_costexplorer', 'host_metrics', 'host_ssm_parameter_scope',
+ 'host_release_key_deny', 'host_store', 'host_console_mail',
+ 'host_store_scan', 'host_terminations'],
+ 'aws_iam_role_policy_attachment': ['host_ssm'],
+ 'aws_iam_policy': ['store_user_boundary'], 'aws_eip': ['host'],
+ 'aws_security_group_rule': ['host_extra'],
+ 'aws_vpc_security_group_ingress_rule': ['extra'],
+ 'aws_vpc_security_group_egress_rule': ['extra']}
+ for kind, units in names.items():
+ for name in units:
+ with self.subTest(kind=kind, name=name):
+ self.gate(plan(resource(f'module.any[0].{kind}.{name}', kind, name,
+ {'id': 'old'}, {'id': 'new'})), 1)
+
+ def test_fixed_actions_unknowns_and_moves(self):
+ for actions in [['delete'], ['delete', 'create'], ['create', 'delete'], ['forget'], ['read']]:
+ self.gate(plan(resource(before={'id': 'i-fixed'}, after=None, actions=actions)), 1)
+ for unknown in [{'user_data': True}, {'root_block_device': [True]}, True, {'x': 'unknown'}]:
+ self.gate(plan(resource(before={'id': 'i-fixed'}, after={'id': 'i-fixed'},
+ actions=['no-op'], unknown=unknown)), 1)
+ moved = resource(before={'id': 'i-fixed'}, after={'id': 'i-fixed'},
+ actions=['no-op'], previous_address='aws_instance.host')
+ self.gate(plan(moved), 0)
+ moved['change']['after']['x'] = 'drift'
+ self.gate(plan(moved), 1)
+ self.gate(plan(resource('aws_iam_role.renamed', 'aws_iam_role', 'renamed',
+ {'name': 'old'}, {'name': 'new'},
+ previous_address='aws_iam_role.host')), 1)
+
+ def test_create_unknowns_are_allowed(self):
+ self.gate(plan(resource('module.probe.aws_lb.nlb', 'aws_lb', 'nlb',
+ after={'internal': False}, actions=['create'], unknown={'arn': True}),
+ resource(EIP, 'aws_eip', 'public', after={'domain': 'vpc'},
+ actions=['create'], unknown={'id': True, 'public_ip': True}),
+ resource('module.new.aws_autoscaling_group.group', 'aws_autoscaling_group',
+ 'group', after={'min_size': 2, 'max_size': 2, 'desired_capacity': 2},
+ actions=['create'], unknown={'arn': True})), 0)
+
+ def test_asg_decrease_unknown_delete(self):
+ baseline = dict(min_size=2, max_size=2, desired_capacity=2)
+ for attr in baseline:
+ updated = dict(baseline, **{attr: 1})
+ self.gate(plan(resource('aws_autoscaling_group.group', 'aws_autoscaling_group',
+ 'group', baseline, updated)), 1)
+ self.gate(plan(resource('aws_autoscaling_group.group', 'aws_autoscaling_group',
+ 'group', baseline, baseline, unknown={'min_size': True})), 1)
+ self.gate(plan(resource('aws_autoscaling_group.group', 'aws_autoscaling_group',
+ 'group', baseline, None, actions=['delete'])), 1)
+ self.gate(plan(resource('aws_autoscaling_group.group', 'aws_autoscaling_group',
+ 'group', baseline, dict(min_size=3, max_size=3, desired_capacity=3))), 0)
+
+ def test_fixed_eip_reassociation_and_ingress_protection(self):
+ self.gate(plan(resource('aws_eip.host', 'aws_eip', 'host',
+ {'instance': 'i-old'}, {'instance': 'i-new'})), 1)
+ for actions in [['delete'], ['delete', 'create'], ['create', 'delete']]:
+ self.gate(plan(resource(EIP, 'aws_eip', 'public', {'id': 'eipalloc-new'},
+ None if actions == ['delete'] else {'id': 'eipalloc-other'},
+ actions=actions)), 1)
+ self.gate(plan(resource(EIP, 'aws_eip', 'public', {'id': 'eipalloc-new'},
+ {'id': 'eipalloc-new'}, unknown={'public_ip': True})), 1)
+
+ def test_exact_attribute_allow_list(self):
+ change = resource(before={'instance_type': 't4g.small', 'user_data': 'old'},
+ after={'instance_type': 't4g.medium', 'user_data': 'old'})
+ entry = dict(address=FIXED, attribute='/instance_type', before='t4g.small',
+ after='t4g.medium', purpose='Reviewed resize', approval='review-123')
+ self.gate(plan(change), 0, allow=[entry])
+ for field, value in [('address', '*'), ('attribute', ''), ('attribute', '/*'),
+ ('before', 'wrong'), ('approval', '')]:
+ bad = dict(entry, **{field: value})
+ self.gate(plan(change), 1, allow=[bad])
+ change['change']['after']['user_data'] = 'new'
+ self.gate(plan(change), 1, allow=[entry])
+ change['change']['actions'] = ['delete', 'create']
+ self.gate(plan(change), 1, allow=[entry])
+
+ def test_allow_list_nested_attribute(self):
+ change = resource(before={'root_block_device': [{'volume_size': 20, 'encrypted': True}]},
+ after={'root_block_device': [{'volume_size': 30, 'encrypted': True}]})
+ entry = dict(address=FIXED, attribute='/root_block_device/0/volume_size', before=20, after=30,
+ purpose='Reviewed volume growth', approval='review-123')
+ self.gate(plan(change), 0, allow=[entry])
+ change['change']['after']['root_block_device'][0]['encrypted'] = False
+ self.gate(plan(change), 1, allow=[entry])
+
+ def test_allow_list_cannot_hide_unknown_or_moved_drift(self):
+ entry = dict(address=FIXED, attribute='/user_data', before='old', after='new',
+ purpose='Reviewed change', approval='review-123')
+ change = resource(before={'user_data': 'old'}, after={'user_data': 'new'},
+ unknown={'user_data': True})
+ self.gate(plan(change), 1, allow=[entry])
+ change['change']['after_unknown'] = {}
+ change['previous_address'] = 'aws_instance.host'
+ self.gate(plan(change), 1, allow=[entry])
+
+ def test_cleanup_manifest_requires_creation_evidence(self):
+ cleanup_plan = plan(resource(EIP, 'aws_eip', 'public', {'id': 'eipalloc-probe'},
+ None, actions=['delete']))
+ manifest = dict(purpose='End the disposable dev probe', approval='review-123',
+ resources=[dict(address=EIP, allocation_id='eipalloc-probe')],
+ creation_plan=plan(resource(EIP, 'aws_eip', 'public', None,
+ {'domain': 'vpc'}, actions=['create'],
+ unknown={'id': True})))
+ self.gate(cleanup_plan, 0, cleanup=manifest)
+ for mutation in ['fixed', 'preexisting', 'wrong-id', 'missing-evidence', 'imported']:
+ bad = copy.deepcopy(manifest)
+ if mutation == 'fixed':
+ bad['resources'][0]['address'] = FIXED
+ elif mutation == 'preexisting':
+ bad['creation_plan']['resource_changes'][0]['change']['before'] = {'id': 'eipalloc-probe'}
+ elif mutation == 'wrong-id':
+ bad['resources'][0]['allocation_id'] = 'eipalloc-other'
+ elif mutation == 'missing-evidence':
+ del bad['creation_plan']
+ else:
+ bad['creation_plan']['resource_changes'][0]['change']['importing'] = {'id': 'eipalloc-probe'}
+ with self.subTest(mutation=mutation):
+ self.gate(cleanup_plan, 1, cleanup=bad)
+ # A pre-existing allocation cannot be relabelled as disposable.
+ bad = copy.deepcopy(manifest)
+ bad['creation_plan']['prior_state'] = {'values': {'root_module': {'resources': [
+ dict(address='aws_eip.regional', mode='managed', type='aws_eip',
+ name='regional', values={'id': 'eipalloc-probe'})]}}}
+ self.gate(cleanup_plan, 1, cleanup=bad)
+
+ def test_rule_creation_cannot_modify_fixed_sg(self):
+ sg = resource('module.ie.aws_security_group.host', 'aws_security_group', 'host',
+ {'id': 'sg-fixed'}, {'id': 'sg-fixed'}, actions=['no-op'])
+ rule = resource('aws_vpc_security_group_ingress_rule.added',
+ 'aws_vpc_security_group_ingress_rule', 'added', None,
+ {'security_group_id': 'sg-fixed'}, actions=['create'])
+ self.gate(plan(sg, rule), 1)
+ rule['change']['after'] = {}
+ rule['change']['after_unknown'] = {'security_group_id': True}
+ self.gate(plan(sg, rule), 1)
+ rule['change']['after'] = {'security_group_id': 'sg-new'}
+ rule['change']['after_unknown'] = {}
+ self.gate(plan(sg, rule), 0)
+
+ def test_new_policy_or_association_cannot_change_fixed_host(self):
+ role = resource('module.ie.aws_iam_role.host', 'aws_iam_role', 'host',
+ {'name': 'fixed-role'}, {'name': 'fixed-role'}, actions=['no-op'])
+ for kind, name, after in [
+ ('aws_iam_role_policy', 'host_route53', {'role': 'fixed-role', 'policy': '{}'}),
+ ('aws_iam_role_policy_attachment', 'renamed', {'role': 'fixed-role', 'policy_arn': 'arn:policy'}),
+ ('aws_eip_association', 'rebind', {'allocation_id': 'eipalloc-fixed', 'instance_id': 'i-other'})
+ ]:
+ with self.subTest(kind=kind):
+ eip = resource('module.ie.aws_eip.host', 'aws_eip', 'host',
+ {'id': 'eipalloc-fixed'}, {'id': 'eipalloc-fixed'}, actions=['no-op'])
+ self.gate(plan(role, eip, resource(f'module.ie.{kind}.{name}', kind, name,
+ None, after, actions=['create'])), 1)
+ self.gate(plan(resource('module.new.aws_iam_role.host', 'aws_iam_role', 'host',
+ None, {'name': 'new-role'}, actions=['create'], unknown={'arn': True})), 0)
+
+ def test_cleanup_rejects_borrowed_address_from_read(self):
+ birth = resource(EIP, 'aws_eip', 'public', None, {}, actions=['create'], unknown={'id': True})
+ borrowed = resource('data.aws_eip.regional', 'aws_eip', 'regional', None,
+ {'id': 'eipalloc-borrowed'}, actions=['read'])
+ borrowed['mode'] = 'data'
+ manifest = dict(purpose='End the disposable probe', approval='review-123',
+ resources=[dict(address=EIP, allocation_id='eipalloc-borrowed')],
+ creation_plan=plan(birth, borrowed))
+ self.gate(plan(resource(EIP, 'aws_eip', 'public', {'id': 'eipalloc-borrowed'},
+ None, actions=['delete'])), 1, cleanup=manifest)
+
+ def test_noop_and_type_sensitive_values(self):
+ self.gate(plan(resource(before={'id': 'i-fixed'}, after={'id': 'i-fixed'},
+ actions=['no-op'])), 0)
+ self.gate(plan(resource(before={'x': False}, after={'x': 0})), 1)
+ self.gate(plan(resource(before={'id': 'i-fixed'}, after={'id': 'i-fixed'})), 1)
+ self.gate(plan(resource('aws_autoscaling_group.group', 'aws_autoscaling_group', 'group',
+ dict(min_size=2, max_size=2, desired_capacity=2),
+ dict(min_size=3, max_size=3, desired_capacity=3), actions=['no-op'])), 1)
+
+ def test_malformed_input_and_guarded_shapes(self):
+ for document in [[], {}, {'format_version': '99.0', 'resource_changes': []},
+ {'format_version': '1.2', 'resource_changes': {}}]:
+ self.gate(document, 2)
+ for mutate in [lambda r: r['change'].pop('after'),
+ lambda r: r['change'].update(actions=['invented']),
+ lambda r: r['change'].update(after=[]),
+ lambda r: r['change'].update(after_unknown=[]),
+ lambda r: r['change'].update(unrecognized_action=True),
+ lambda r: r.update(type='aws_lb'),
+ lambda r: r['change'].update(importing={'id': 'i-fixed'})]:
+ r = resource(before={'id': 'i-fixed'}, after={'id': 'i-fixed'}, actions=['no-op'])
+ mutate(r)
+ self.gate(plan(r), 1)
+ result = subprocess.run([sys.executable, str(GATE), '--override'], capture_output=True)
+ self.assertEqual(2, result.returncode)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/scripts/testdata/region-group-plan/fixed-eip-reassociation.json b/scripts/testdata/region-group-plan/fixed-eip-reassociation.json
new file mode 100644
index 000000000..1dcc68ad8
--- /dev/null
+++ b/scripts/testdata/region-group-plan/fixed-eip-reassociation.json
@@ -0,0 +1,25 @@
+{
+ "format_version": "1.2",
+ "resource_changes": [
+ {
+ "address": "module.ie.aws_eip.host",
+ "mode": "managed",
+ "type": "aws_eip",
+ "name": "host",
+ "change": {
+ "actions": [
+ "update"
+ ],
+ "before": {
+ "id": "eipalloc-0123456789abcdef0",
+ "instance": "i-0123456789abcdef0"
+ },
+ "after": {
+ "id": "eipalloc-0123456789abcdef0",
+ "instance": "i-0123456789abcdef1"
+ },
+ "after_unknown": {}
+ }
+ }
+ ]
+}
diff --git a/scripts/testdata/region-group-plan/new-ingress.json b/scripts/testdata/region-group-plan/new-ingress.json
new file mode 100644
index 000000000..76de3d93d
--- /dev/null
+++ b/scripts/testdata/region-group-plan/new-ingress.json
@@ -0,0 +1,26 @@
+{
+ "format_version": "1.2",
+ "resource_changes": [
+ {
+ "address": "module.probe.aws_lb.nlb",
+ "mode": "managed",
+ "type": "aws_lb",
+ "name": "nlb",
+ "change": {
+ "actions": [
+ "create"
+ ],
+ "before": null,
+ "after": {
+ "internal": false,
+ "load_balancer_type": "network"
+ },
+ "after_unknown": {
+ "arn": true,
+ "dns_name": true,
+ "id": true
+ }
+ }
+ }
+ ]
+}
diff --git a/scripts/testdata/region-group-plan/targeted-fixed-user-data.json b/scripts/testdata/region-group-plan/targeted-fixed-user-data.json
new file mode 100644
index 000000000..6bf18f067
--- /dev/null
+++ b/scripts/testdata/region-group-plan/targeted-fixed-user-data.json
@@ -0,0 +1,41 @@
+{
+ "format_version": "1.2",
+ "resource_changes": [
+ {
+ "address": "module.deployment[\"dev\"].module.ie.aws_instance.host",
+ "mode": "managed",
+ "type": "aws_instance",
+ "name": "host",
+ "change": {
+ "actions": [
+ "update"
+ ],
+ "before": {
+ "id": "i-0123456789abcdef0",
+ "user_data": "old"
+ },
+ "after": {
+ "id": "i-0123456789abcdef0",
+ "user_data": "new"
+ },
+ "after_unknown": {}
+ }
+ },
+ {
+ "address": "module.probe.aws_lb.nlb",
+ "mode": "managed",
+ "type": "aws_lb",
+ "name": "nlb",
+ "change": {
+ "actions": [
+ "create"
+ ],
+ "before": null,
+ "after": {},
+ "after_unknown": {
+ "arn": true
+ }
+ }
+ }
+ ]
+}
diff --git a/scripts/testdata/region-group-plan/unchanged-move.json b/scripts/testdata/region-group-plan/unchanged-move.json
new file mode 100644
index 000000000..63df6d7a7
--- /dev/null
+++ b/scripts/testdata/region-group-plan/unchanged-move.json
@@ -0,0 +1,26 @@
+{
+ "format_version": "1.2",
+ "resource_changes": [
+ {
+ "address": "module.deployment[\"dev\"].module.ie.aws_instance.host",
+ "mode": "managed",
+ "type": "aws_instance",
+ "name": "host",
+ "change": {
+ "actions": [
+ "no-op"
+ ],
+ "before": {
+ "id": "i-0123456789abcdef0",
+ "instance_type": "t4g.small"
+ },
+ "after": {
+ "id": "i-0123456789abcdef0",
+ "instance_type": "t4g.small"
+ },
+ "after_unknown": {}
+ },
+ "previous_address": "module.ie.aws_instance.host"
+ }
+ ]
+}