ソースを参照

feat: plan policy denies world-open outbound firewall rules unless allowlisted (#253) (#283)

* feat: plan policy denies world-open outbound firewall rules unless allowlisted (#253)

Adds an outbound check next to the inbound one: a digitalocean_firewall
outbound rule with 0.0.0.0/0 or ::/0 among its destination addresses is
denied unless outbound_allowlist, keyed by stack id and resource address,
has an entry with direction, protocol, ports and destinations.

icmp rules and rules with no port range (or "all") are never
allowlistable; a literal range is judged as written. The two shipped
entries cover the rules the firewall module renders today for
cah-00-foundation and cah-10-access.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* Plan policy: judge the whole internet by prefix length, deny unknown rule values (#253)

Review of PR #283. A world-open destination or source is now any address with
a prefix length of 0 or 1 (IPv4 and IPv6, any spelling, split halves), and
anything unparseable fails closed. A firewall whose inbound_rule, outbound_rule
or rule address lists are unknown until apply (change.after_unknown) is denied.
Docs state both rules, the per-instance allowlist keys and the udp 1-65535
versus all rationale. A Python test checks the shipped allowlist matches what
the firewall module renders.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
ChiefGyk3D 1 ヶ月 前
親
コミット
15e8bc7314

+ 213 - 4
.spacelift/policies/plan.rego

@@ -20,15 +20,28 @@
 #     or one other group's tag), so a source address, droplet id, load
 #     balancer or Kubernetes source is a change the module cannot produce, and
 #     0.0.0.0/0 or ::/0 is the whole internet.
+#   - a digitalocean_firewall with an outbound rule whose destination is the
+#     whole internet (0.0.0.0/0 or ::/0), unless outbound_allowlist has an
+#     entry for that stack and address (issue #253). Outbound rules to a tag,
+#     or to named addresses, are not judged. icmp rules and rules with no
+#     port range (or "all") are never allowlistable: see outbound_allowlist.
+#     "The whole internet" is judged by prefix length (0 or 1, IPv4 and IPv6),
+#     not by exact spelling; see wide_address.
+#   - a digitalocean_firewall whose inbound_rule or outbound_rule, or a rule's
+#     source or destination addresses, are unknown until apply. They could
+#     resolve to the whole internet, so they are denied; see unknown_in_rules.
 #   - an AWS security group rule that admits a CIDR range (IPv4 or IPv6). The
-#     AWS firewall module admits only a reference to the group itself.
+#     AWS firewall module admits only a reference to the group itself. AWS
+#     egress rules are not judged here.
 #   - a droplet with ipv6 turned on, or an AWS VPC, subnet or instance that
 #     takes an IPv6 range or address. IPv6 stays closed in this repository.
 #
 # Pure deletes and no-ops are ignored: removing a rule never opens anything.
 #
 # The escape hatch is this file. A deliberate inbound rule is allowed only by
-# an entry in inbound_allowlist below, in a pull request that gets reviewed.
+# an entry in inbound_allowlist below, and a deliberate world-open outbound
+# rule only by an entry in outbound_allowlist, in a pull request that gets
+# reviewed.
 # Nothing a plan can set itself (a stack label, an environment variable, a
 # field in the plan) is read, so a branch cannot grant its own exception. The
 # IPv6 checks have no escape hatch.
@@ -93,6 +106,53 @@ import rego.v1
 # stack approval. Remove the entry when the rule goes away.
 inbound_allowlist := {}
 
+# World-open outbound exceptions (issue #253), same shape as inbound_allowlist:
+# keyed by stack id, then by a resource address or a group name from
+# address_groups. An entry allows one kind of outbound rule and nothing else:
+#
+#   {
+#     "direction": "outbound",          # required, exactly "outbound"
+#     "protocol": "tcp",                # required, exact match
+#     "ports": ["443", "80"],           # required, exact port_range strings
+#     "destinations": ["0.0.0.0/0", "::/0"],  # required, every destination
+#                                       # address the rule has must be listed
+#   }
+#
+# Only a rule with 0.0.0.0/0 or ::/0 among its destination_addresses is
+# judged; a rule to a tag, or to named addresses only, needs no entry. Rules
+# are judged one by one, so one entry covers one protocol and a firewall with
+# tcp and udp rules needs an entry for each. An entry naming only one of the
+# two world ranges does not cover a rule that uses both.
+#
+# Decision on icmp and all-port rules: they are NEVER allowlistable, even if an
+# entry tries to name them. An icmp rule has no port, and a tcp or udp rule
+# whose port_range is missing, empty or "all" has no limit; with a world-open
+# destination, nothing narrows either of them, so the way to get them is to
+# name destinations instead of the world. A literal range such as "1-65535"
+# is judged as written: an entry must name that exact string, which puts the
+# widest range in the reviewed pull request with its reason. Empty entries,
+# missing fields and unknown stacks allow nothing.
+#
+# Every entry below exists because the firewall module renders it today: the
+# five default outbound rules (tcp 443, 80, 53; udp 53, 123) on any address,
+# plus the extra rules the connector firewall in cah-10-access adds. Remove an
+# entry when its rule goes away.
+outbound_allowlist := {
+	# stacks/00-foundation: the baseline firewall. Defaults only: package
+	# mirrors, DNS and NTP have no fixed addresses to pin.
+	"cah-00-foundation": {"module.baseline_firewall.digitalocean_firewall.this": [
+		{"direction": "outbound", "protocol": "tcp", "ports": ["443", "80", "53"], "destinations": ["0.0.0.0/0", "::/0"]},
+		{"direction": "outbound", "protocol": "udp", "ports": ["53", "123"], "destinations": ["0.0.0.0/0", "::/0"]},
+	]},
+	# stacks/10-access: the connector firewall. The defaults, plus Twingate's
+	# documented outbound needs: tcp 30000-31000 and udp to any port for
+	# peer-to-peer connections (see the comment above the module call).
+	"cah-10-access": {"module.connector_firewall.digitalocean_firewall.this": [
+		{"direction": "outbound", "protocol": "tcp", "ports": ["443", "80", "53", "30000-31000"], "destinations": ["0.0.0.0/0", "::/0"]},
+		{"direction": "outbound", "protocol": "udp", "ports": ["53", "123", "1-65535"], "destinations": ["0.0.0.0/0", "::/0"]},
+	]},
+}
+
 # Named groups of resource addresses, per stack id, so one entry can cover
 # several resources in that stack: {"stack-id": {"group-name": ["address"]}}.
 # A group of one stack means nothing in another.
@@ -147,6 +207,35 @@ deny contains msg if {
 	)
 }
 
+deny contains msg if {
+	some rc in changed_resources("digitalocean_firewall")
+	some rule in values(rc.change.after, "outbound_rule")
+	world_open_outbound(rule)
+	not outbound_rule_allowed(rc, rule)
+	msg := sprintf(
+		"%s: outbound rule %s reaches the whole internet (%s). Outbound world-open rules need an outbound_allowlist entry for this stack and address, naming the direction, protocol, port and destinations. icmp and all-port rules are never allowed: name destinations instead.",
+		[rc.address, rule_label(rule), destination_summary(rule)],
+	)
+}
+
+deny contains msg if {
+	some rc in changed_resources("digitalocean_firewall")
+	some where in unknown_in_rules(rc, "inbound_rule", non_tag_sources)
+	msg := sprintf(
+		"%s: %s is not known until apply, so the plan cannot show whether the rule is tag-scoped. Inbound sources must be known at plan time; make the value static. No allowlist entry covers an unknown value.",
+		[rc.address, where],
+	)
+}
+
+deny contains msg if {
+	some rc in changed_resources("digitalocean_firewall")
+	some where in unknown_in_rules(rc, "outbound_rule", {"destination_addresses"})
+	msg := sprintf(
+		"%s: %s is not known until apply, so the plan cannot show whether the rule reaches the whole internet. Outbound destinations must be known at plan time; make the value static. No allowlist entry covers an unknown value.",
+		[rc.address, where],
+	)
+}
+
 deny contains msg if {
 	some entry in aws_ingress_cidrs
 	not aws_allowed(entry)
@@ -214,6 +303,14 @@ entries_for(address) := [entry |
 	some entry in entries
 ]
 
+# The same for outbound rules, from outbound_allowlist.
+outbound_entries_for(address) := [entry |
+	stack_id != ""
+	some key, entries in object.get(outbound_allowlist, stack_id, {})
+	key_covers(key, address)
+	some entry in entries
+]
+
 # One entry admits one rule when every part matches exactly. Anything missing
 # from the entry, or from the rule, admits nothing.
 admits(entry, protocol, port, addresses) if {
@@ -228,6 +325,39 @@ admits(entry, protocol, port, addresses) if {
 	}
 }
 
+# An outbound entry admits a world-open rule when the direction is outbound,
+# the protocol and port_range match exactly, and every destination address of
+# the rule is listed. icmp, a missing or empty port_range and "all" are never
+# admitted (see outbound_allowlist).
+outbound_admits(entry, rule) if {
+	object.get(entry, "direction", "") == "outbound"
+	protocol := object.get(rule, "protocol", "")
+	protocol in {"tcp", "udp"}
+	protocol == object.get(entry, "protocol", "")
+	port := object.get(rule, "port_range", "")
+	is_string(port)
+	not port in {"", "all"}
+	port in object.get(entry, "ports", [])
+	addresses := values(rule, "destination_addresses")
+	count(addresses) > 0
+	every address in addresses {
+		address in object.get(entry, "destinations", [])
+	}
+}
+
+# A world-open outbound rule is allowed only when it names no other kind of
+# destination and an entry admits it.
+outbound_rule_allowed(rc, rule) if {
+	not has_other_destination(rule)
+	some entry in outbound_entries_for(rc.address)
+	outbound_admits(entry, rule)
+}
+
+has_other_destination(rule) if {
+	some key in {"destination_tags", "destination_droplet_ids", "destination_load_balancer_uids", "destination_kubernetes_ids"}
+	filled(rule, key)
+}
+
 # A DigitalOcean inbound rule is allowed only when it carries source
 # addresses, no other non-tag source kind, and an entry admits it.
 rule_allowed(rc, rule) if {
@@ -369,11 +499,88 @@ filled_string(obj, key) if {
 	v != ""
 }
 
-world_addresses := {"0.0.0.0/0", "::/0"}
+# "The whole internet" is judged by prefix length, not by spelling: 0.0.0.0/0,
+# ::/0, 0::/0, ::0/0, 0.0.0.0/00 and the two halves 0.0.0.0/1 + 128.0.0.0/1 (or
+# ::/1 + 8000::/1) all count. An address with a prefix length of 0 or 1 is
+# world-open. Anything that does not parse as an address or a CIDR range, or
+# that is not text, fails closed and counts as world-open too. A rule listing
+# such an address can then never match an allowlist entry, which names exact
+# strings. Narrower splits (four /2 ranges and so on) are not detected: the
+# firewall module never renders them, and the allowlist is exact.
+wide_address(address) if not is_string(address)
+
+wide_address(address) if {
+	is_string(address)
+	not valid_address(address)
+}
+
+wide_address(address) if {
+	is_string(address)
+	net.cidr_is_valid(address)
+	to_number(split(address, "/")[1]) <= 1
+}
+
+# A CIDR range, or a bare address (a single host).
+valid_address(address) if net.cidr_is_valid(address)
+
+valid_address(address) if {
+	not contains(address, "/")
+	not contains(address, ":")
+	net.cidr_is_valid(concat("/", [address, "32"]))
+}
+
+valid_address(address) if {
+	not contains(address, "/")
+	contains(address, ":")
+	net.cidr_is_valid(concat("/", [address, "128"]))
+}
 
 world_open(rule) if {
 	some address in values(rule, "source_addresses")
-	address in world_addresses
+	wide_address(address)
+}
+
+world_open_outbound(rule) if {
+	some address in values(rule, "destination_addresses")
+	wide_address(address)
+}
+
+# Values that are not known until apply. A plan lists them in
+# change.after_unknown, which mirrors change.after: true for a value, or for a
+# whole list, and a list of objects (one per element) where only some fields
+# are unknown. An unknown rule list or address list may resolve to the whole
+# internet at apply time, so the policy cannot judge it: it is denied, and no
+# allowlist entry covers it.
+unknown_flag(v) if v == true
+
+unknown_flag(v) if {
+	is_array(v)
+	some x in v
+	x == true
+}
+
+after_unknown_of(rc) := u if {
+	u := object.get(object.get(rc, "change", {}), "after_unknown", {})
+	is_object(u)
+} else := {}
+
+# What is unknown in one rule list of a firewall: the whole list, a whole rule,
+# or one of the named address fields of a rule.
+unknown_in_rules(rc, list_key, address_keys) := (whole_list | whole_rules) | fields if {
+	unknown_rules := object.get(after_unknown_of(rc), list_key, false)
+	whole_list := {list_key | unknown_rules == true}
+	whole_rules := {sprintf("%s[%d]", [list_key, i]) |
+		is_array(unknown_rules)
+		some i, el in unknown_rules
+		el == true
+	}
+	fields := {sprintf("%s[%d].%s", [list_key, i, key]) |
+		is_array(unknown_rules)
+		some i, el in unknown_rules
+		is_object(el)
+		some key in address_keys
+		unknown_flag(object.get(el, key, false))
+	}
 }
 
 # The only sources the firewall module emits are tags. Any other kind of
@@ -413,6 +620,8 @@ source_summary(rule) := concat(", ", sort(parts)) if {
 	count(parts) > 0
 } else := "no source tag"
 
+destination_summary(rule) := concat(", ", sort([sprintf("address %s", [a]) | some a in values(rule, "destination_addresses")]))
+
 # AWS ingress from an address. A reference to a security group (or to the group
 # itself) carries no CIDR and is the one admitted kind.
 # One finding per rule (or inline block), holding every CIDR range it admits,

+ 443 - 2
.spacelift/policies/plan_test.rego

@@ -61,8 +61,11 @@ denied_on(id, changes) := reasons if {
 
 # Clean plans.
 
+# The fixture also has the world-open outbound 443 rule the module renders, so
+# it passes only where an outbound entry covers it (issue #253).
 test_connector_firewall_with_zero_inbound_passes if {
-	count(denied([connector_firewall])) == 0
+	allow := allow_for("svc-a", fw, [out_entry({})])
+	count(reasons_with_outbound("svc-a", [connector_firewall], allow)) == 0
 }
 
 test_tag_scoped_inbound_rule_passes if {
@@ -332,6 +335,7 @@ test_groups_of_another_stack_do_not_apply if {
 
 test_allowlists_are_empty_by_default if {
 	count(spacelift.inbound_allowlist) == 0
+	count(object.keys(spacelift.outbound_allowlist)) == 2
 	count(spacelift.address_groups) == 0
 	count(spacelift.destroy_allowlist) == 0
 	count(spacelift.whole_service_teardown_stacks) == 0
@@ -344,7 +348,8 @@ current_stacks := ["cah-00-foundation", "cah-10-access", "cah-20-telemetry", "ca
 
 test_current_stacks_keep_their_verdicts if {
 	every id in current_stacks {
-		count(denied_on(id, [connector_firewall, firewall_with([tag_rule])])) == 0
+		count(denied_on(id, [firewall_with([tag_rule])])) == 0
+		count(denied_on(id, [connector_firewall])) == 1
 		count(denied_on(id, [firewall_with([bad_rule])])) == 1
 		count(denied_on(id, [firewall_with([with_source({"source_tags": [], "source_addresses": ["0.0.0.0/0"]})])])) == 1
 		count(denied_on(id, [sg_cidr])) == 1
@@ -817,3 +822,439 @@ test_aws_inline_block_with_two_ranges_needs_one_entry if {
 	]}}
 	count(reasons_with("aws-a", [sg], split)) == 1
 }
+
+# World-open outbound rules (issue #253).
+
+out_world := ["0.0.0.0/0", "::/0"]
+
+out_rule(protocol, port, destinations) := {
+	"protocol": protocol,
+	"port_range": port,
+	"destination_addresses": destinations,
+	"destination_tags": [],
+	"destination_droplet_ids": [],
+	"destination_load_balancer_uids": [],
+	"destination_kubernetes_ids": [],
+}
+
+firewall_out(rules) := create(fw, "digitalocean_firewall", {"inbound_rule": [], "outbound_rule": rules})
+
+out_entry(overrides) := object.union(
+	{
+		"direction": "outbound",
+		"protocol": "tcp",
+		"ports": ["443"],
+		"destinations": out_world,
+	},
+	overrides,
+)
+
+reasons_with_outbound(id, changes, allowlist) := reasons if {
+	reasons := spacelift.deny with input as on_stack(id, changes) with data.spacelift.outbound_allowlist as allowlist
+}
+
+test_world_open_outbound_is_denied_by_default if {
+	reasons := denied_on("svc-a", [firewall_out([out_rule("tcp", "443", out_world)])])
+	count(reasons) == 1
+	some reason in reasons
+	contains(reason, "outbound rule tcp/443 reaches the whole internet")
+}
+
+test_world_open_ipv4_only_outbound_is_denied if {
+	count(denied_on("svc-a", [firewall_out([out_rule("tcp", "443", ["0.0.0.0/0"])])])) == 1
+}
+
+test_world_open_ipv6_only_outbound_is_denied if {
+	count(denied_on("svc-a", [firewall_out([out_rule("tcp", "443", ["::/0"])])])) == 1
+}
+
+test_world_mixed_with_named_destination_is_denied if {
+	count(denied_on("svc-a", [firewall_out([out_rule("tcp", "443", ["203.0.113.0/24", "0.0.0.0/0"])])])) == 1
+}
+
+# Narrowed or tag-scoped outbound rules are not world-open.
+test_outbound_to_named_addresses_passes if {
+	rule := out_rule("tcp", "443", ["203.0.113.0/24", "198.51.100.7/32", "2001:db8::/32"])
+	count(denied_on("svc-a", [firewall_out([rule])])) == 0
+}
+
+test_outbound_to_tag_passes if {
+	rule := object.union(out_rule("tcp", "22", []), {"destination_tags": ["cah-access"]})
+	count(denied_on("svc-a", [firewall_out([rule])])) == 0
+}
+
+test_outbound_with_null_destinations_does_not_crash if {
+	rule := {"protocol": "tcp", "port_range": "22", "destination_addresses": null}
+	count(denied_on("svc-a", [firewall_out([rule])])) == 0
+	count(denied_on("svc-a", [create(fw, "digitalocean_firewall", {"inbound_rule": []})])) == 0
+}
+
+test_outbound_allowlisted_entry_passes_in_its_stack if {
+	allow := allow_for("svc-a", fw, [out_entry({})])
+	count(reasons_with_outbound("svc-a", [firewall_out([out_rule("tcp", "443", out_world)])], allow)) == 0
+}
+
+test_outbound_entry_is_keyed_by_stack if {
+	allow := allow_for("svc-a", fw, [out_entry({})])
+	count(reasons_with_outbound("svc-b", [firewall_out([out_rule("tcp", "443", out_world)])], allow)) == 1
+}
+
+test_outbound_entry_is_keyed_by_address if {
+	allow := allow_for("svc-a", fw, [out_entry({})])
+	other := create("module.other.digitalocean_firewall.this", "digitalocean_firewall", {"outbound_rule": [out_rule("tcp", "443", out_world)]})
+	count(reasons_with_outbound("svc-a", [other], allow)) == 1
+}
+
+test_outbound_plan_with_no_stack_id_gets_no_exception if {
+	allow := allow_for("svc-a", fw, [out_entry({})])
+	reasons := spacelift.deny with input as plan([firewall_out([out_rule("tcp", "443", out_world)])]) with data.spacelift.outbound_allowlist as allow
+	count(reasons) == 1
+}
+
+test_outbound_group_covers_its_members_in_its_stack_only if {
+	allow := allow_for("svc-a", "web", [out_entry({})])
+	changes := [firewall_out([out_rule("tcp", "443", out_world)])]
+	groups := {"svc-a": {"web": [fw]}}
+	covered := spacelift.deny with input as on_stack("svc-a", changes) with data.spacelift.outbound_allowlist as allow with data.spacelift.address_groups as groups
+	count(covered) == 0
+	elsewhere := spacelift.deny with input as on_stack("svc-b", changes) with data.spacelift.outbound_allowlist as allow with data.spacelift.address_groups as groups
+	count(elsewhere) == 1
+}
+
+# Each field narrows the entry.
+
+test_outbound_entry_for_another_port_denies if {
+	allow := allow_for("svc-a", fw, [out_entry({"ports": ["80"]})])
+	count(reasons_with_outbound("svc-a", [firewall_out([out_rule("tcp", "443", out_world)])], allow)) == 1
+}
+
+test_outbound_entry_for_another_protocol_denies if {
+	allow := allow_for("svc-a", fw, [out_entry({"protocol": "udp"})])
+	count(reasons_with_outbound("svc-a", [firewall_out([out_rule("tcp", "443", out_world)])], allow)) == 1
+}
+
+test_outbound_entry_for_another_destination_denies if {
+	allow := allow_for("svc-a", fw, [out_entry({"destinations": ["203.0.113.0/24"]})])
+	count(reasons_with_outbound("svc-a", [firewall_out([out_rule("tcp", "443", ["203.0.113.0/24", "0.0.0.0/0"])])], allow)) == 1
+}
+
+test_outbound_world_entry_must_list_both_ranges if {
+	rule := out_rule("tcp", "443", out_world)
+	only4 := allow_for("svc-a", fw, [out_entry({"destinations": ["0.0.0.0/0"]})])
+	count(reasons_with_outbound("svc-a", [firewall_out([rule])], only4)) == 1
+	only_v4_rule := out_rule("tcp", "443", ["0.0.0.0/0"])
+	both := allow_for("svc-a", fw, [out_entry({})])
+	count(reasons_with_outbound("svc-a", [firewall_out([only_v4_rule])], both)) == 0
+}
+
+test_outbound_entry_with_wrong_direction_denies if {
+	rule := out_rule("tcp", "443", out_world)
+	inbound := allow_for("svc-a", fw, [out_entry({"direction": "inbound"})])
+	count(reasons_with_outbound("svc-a", [firewall_out([rule])], inbound)) == 1
+	missing := allow_for("svc-a", fw, [object.remove(out_entry({}), ["direction"])])
+	count(reasons_with_outbound("svc-a", [firewall_out([rule])], missing)) == 1
+}
+
+test_outbound_entry_missing_a_field_denies if {
+	rule := out_rule("tcp", "443", out_world)
+	every field in ["protocol", "ports", "destinations"] {
+		allow := allow_for("svc-a", fw, [object.remove(out_entry({}), [field])])
+		count(reasons_with_outbound("svc-a", [firewall_out([rule])], allow)) == 1
+	}
+}
+
+test_outbound_entry_with_empty_lists_denies if {
+	rule := out_rule("tcp", "443", out_world)
+	count(reasons_with_outbound("svc-a", [firewall_out([rule])], allow_for("svc-a", fw, [out_entry({"ports": []})]))) == 1
+	count(reasons_with_outbound("svc-a", [firewall_out([rule])], allow_for("svc-a", fw, [out_entry({"destinations": []})]))) == 1
+}
+
+# An outbound entry never admits an inbound rule, and an inbound entry never
+# admits an outbound one.
+test_outbound_entry_does_not_cover_inbound_rules if {
+	allow := allow_for("svc-a", fw, [out_entry({"ports": ["8080"], "destinations": ["198.51.100.0/24"]})])
+	reasons := spacelift.deny with input as on_stack("svc-a", [firewall_with([bad_rule])]) with data.spacelift.outbound_allowlist as allow
+	count(reasons) == 1
+}
+
+test_inbound_entry_does_not_cover_outbound_rules if {
+	allow := allow_for("svc-a", fw, [entry({"ports": ["443"], "sources": out_world})])
+	reasons := spacelift.deny with input as on_stack("svc-a", [firewall_out([out_rule("tcp", "443", out_world)])]) with data.spacelift.inbound_allowlist as allow
+	count(reasons) == 1
+}
+
+test_outbound_rule_with_another_destination_kind_is_never_covered if {
+	allow := allow_for("svc-a", fw, [out_entry({})])
+	rule := object.union(out_rule("tcp", "443", out_world), {"destination_tags": ["cah-access"]})
+	count(reasons_with_outbound("svc-a", [firewall_out([rule])], allow)) == 1
+}
+
+test_outbound_rules_are_judged_one_by_one if {
+	allow := allow_for("svc-a", fw, [out_entry({})])
+	rules := [out_rule("tcp", "443", out_world), out_rule("tcp", "8443", out_world), out_rule("tcp", "22", ["203.0.113.7/32"])]
+	reasons := reasons_with_outbound("svc-a", [firewall_out(rules)], allow)
+	count(reasons) == 1
+	some reason in reasons
+	contains(reason, "tcp/8443")
+}
+
+# Decision: icmp and all-port rules are never allowlistable (issue #253).
+
+test_world_open_icmp_is_denied if {
+	count(denied_on("svc-a", [firewall_out([out_rule("icmp", "", out_world)])])) == 1
+	count(denied_on("svc-a", [firewall_out([{"protocol": "icmp", "destination_addresses": out_world}])])) == 1
+}
+
+test_icmp_is_never_covered_by_an_entry if {
+	allow := allow_for("svc-a", fw, [out_entry({"protocol": "icmp", "ports": ["", "all", "0"]})])
+	count(reasons_with_outbound("svc-a", [firewall_out([out_rule("icmp", "", out_world)])], allow)) == 1
+	count(reasons_with_outbound("svc-a", [firewall_out([out_rule("icmp", "0", out_world)])], allow)) == 1
+}
+
+test_all_port_rule_is_never_covered_by_an_entry if {
+	allow := allow_for("svc-a", fw, [out_entry({"ports": ["", "all", "443"]})])
+	count(reasons_with_outbound("svc-a", [firewall_out([out_rule("tcp", "all", out_world)])], allow)) == 1
+	count(reasons_with_outbound("svc-a", [firewall_out([out_rule("tcp", "", out_world)])], allow)) == 1
+	count(reasons_with_outbound("svc-a", [firewall_out([{"protocol": "tcp", "destination_addresses": out_world}])], allow)) == 1
+	udp_allow := allow_for("svc-a", fw, [out_entry({"protocol": "udp", "ports": ["", "all"]})])
+	count(reasons_with_outbound("svc-a", [firewall_out([out_rule("udp", null, out_world)])], udp_allow)) == 1
+}
+
+# A literal range is judged as written: the entry must name the exact string.
+test_explicit_full_range_needs_its_own_entry if {
+	rule := out_rule("udp", "1-65535", out_world)
+	count(reasons_with_outbound("svc-a", [firewall_out([rule])], allow_for("svc-a", fw, [out_entry({"protocol": "udp"})]))) == 1
+	count(reasons_with_outbound("svc-a", [firewall_out([rule])], allow_for("svc-a", fw, [out_entry({"protocol": "udp", "ports": ["1-65535"]})]))) == 0
+}
+
+# Outbound handling reads firewall create and update, like inbound.
+test_outbound_delete_and_noop_are_ignored if {
+	after := {"outbound_rule": [out_rule("tcp", "443", out_world)]}
+	count(denied_on("svc-a", [change(fw, "digitalocean_firewall", ["no-op"], after)])) == 0
+	count(denied_on("svc-a", [change(fw, "digitalocean_firewall", ["update"], after)])) == 1
+}
+
+# Today's stacks: the rules the firewall module renders for them pass with the
+# shipped entries, at their real addresses, and nothing wider does.
+
+default_outbound := [
+	out_rule("tcp", "443", out_world),
+	out_rule("tcp", "80", out_world),
+	out_rule("tcp", "53", out_world),
+	out_rule("udp", "53", out_world),
+	out_rule("udp", "123", out_world),
+]
+
+baseline_addr := "module.baseline_firewall.digitalocean_firewall.this"
+
+connector_addr := "module.connector_firewall.digitalocean_firewall.this"
+
+baseline_fw := create(baseline_addr, "digitalocean_firewall", {"inbound_rule": [], "outbound_rule": default_outbound})
+
+connector_extra := [out_rule("tcp", "30000-31000", out_world), out_rule("udp", "1-65535", out_world)]
+
+connector_fw := create(connector_addr, "digitalocean_firewall", {"inbound_rule": [], "outbound_rule": array.concat(default_outbound, connector_extra)})
+
+test_shipped_baseline_firewall_passes_in_foundation if {
+	count(denied_on("cah-00-foundation", [baseline_fw])) == 0
+}
+
+test_shipped_connector_firewall_passes_in_access if {
+	count(denied_on("cah-10-access", [connector_fw])) == 0
+}
+
+test_shipped_entries_do_not_cross_stacks_or_addresses if {
+	count(denied_on("cah-10-access", [baseline_fw])) == 5
+	count(denied_on("cah-00-foundation", [connector_fw])) == 7
+	count(denied_on("cah-20-telemetry", [baseline_fw])) == 5
+	count(denied_on("cah-20-telemetry", [connector_fw])) == 7
+}
+
+test_shipped_entries_do_not_allow_more_than_they_name if {
+	wider := [
+		out_rule("tcp", "8443", out_world),
+		out_rule("tcp", "1-65535", out_world),
+		out_rule("tcp", "all", out_world),
+		out_rule("udp", "30000-31000", out_world),
+		out_rule("icmp", "", out_world),
+	]
+	extra := create(connector_addr, "digitalocean_firewall", {"outbound_rule": wider})
+	count(denied_on("cah-10-access", [extra])) == 5
+	foundation_extra := create(baseline_addr, "digitalocean_firewall", {"outbound_rule": connector_extra})
+	count(denied_on("cah-00-foundation", [foundation_extra])) == 2
+}
+
+# Review of PR #283: the whole internet is judged by prefix length, not by
+# exact spelling, and an unknown value never passes.
+
+# Spellings of "everything", split halves, and values that cannot be parsed.
+# Unparseable text fails closed: it is treated as the whole internet.
+world_spellings := [
+	["0.0.0.0/1", "128.0.0.0/1"],
+	["::/1", "8000::/1"],
+	["0::/0"],
+	["0:0:0:0:0:0:0:0/0"],
+	["::0/0"],
+	["::/00"],
+	["0.0.0.0/00"],
+	["0.0.0.0/01"],
+	["128.0.0.0/1"],
+	["203.0.113.0/24", "0.0.0.0/00"],
+	["banana"],
+	["0.0.0.0/"],
+	["0.0.0.0/33"],
+	["10.0.0.0/-1"],
+	[" 0.0.0.0/0"],
+	[""],
+]
+
+test_outbound_world_spellings_are_denied if {
+	every destinations in world_spellings {
+		reasons := denied_on("svc-a", [firewall_out([out_rule("tcp", "443", destinations)])])
+		count(reasons) == 1
+		some reason in reasons
+		contains(reason, "reaches the whole internet")
+	}
+}
+
+test_outbound_world_spelling_is_not_covered_by_an_exact_entry if {
+	allow := allow_for("svc-a", fw, [out_entry({})])
+	every destinations in world_spellings {
+		count(reasons_with_outbound("svc-a", [firewall_out([out_rule("tcp", "443", destinations)])], allow)) == 1
+	}
+
+	# ::/0 spelled differently next to the listed range is still not listed.
+	count(reasons_with_outbound("svc-a", [firewall_out([out_rule("tcp", "443", ["0.0.0.0/0", "0::/0"])])], allow)) == 1
+}
+
+test_outbound_narrow_destinations_are_not_world_open if {
+	every destinations in [
+		["64.0.0.0/2"],
+		["10.0.0.0/8"],
+		["203.0.113.0/24"],
+		["203.0.113.7"],
+		["203.0.113.7/32"],
+		["2001:db8::/32"],
+		["2001:db8::1"],
+		["2001:db8::1/128"],
+	] {
+		count(denied_on("svc-a", [firewall_out([out_rule("tcp", "443", destinations)])])) == 0
+	}
+}
+
+test_inbound_world_spellings_are_called_out_as_the_whole_internet if {
+	every sources in world_spellings {
+		reasons := denied([firewall_with([with_source({"source_tags": [], "source_addresses": sources})])])
+		count(reasons) == 1
+		some reason in reasons
+		contains(reason, "opens the port to the whole internet")
+	}
+}
+
+test_inbound_narrow_sources_are_not_called_the_whole_internet if {
+	reasons := denied([firewall_with([with_source({"source_tags": [], "source_addresses": ["198.51.100.0/24"]})])])
+	count(reasons) == 1
+	some reason in reasons
+	contains(reason, "is not tag-scoped")
+}
+
+test_inbound_world_spelling_is_not_covered_by_an_exact_entry if {
+	allow := allow_for("svc-a", fw, [entry({"sources": ["0.0.0.0/0", "::/0"]})])
+	rule := with_source({"source_tags": [], "source_addresses": ["0::/0"]})
+	count(reasons_with("svc-a", [firewall_with([rule])], allow)) == 1
+}
+
+# Unknown values. A real plan lists them in change.after_unknown, which mirrors
+# change.after: true for a value, or a list whose elements are objects.
+
+firewall_unknown(after, unknown) := {
+	"address": fw,
+	"type": "digitalocean_firewall",
+	"change": {"actions": ["create"], "after": after, "after_unknown": unknown},
+}
+
+test_unknown_outbound_rule_list_is_denied if {
+	reasons := denied([firewall_unknown({"inbound_rule": []}, {"outbound_rule": true})])
+	count(reasons) == 1
+	some reason in reasons
+	contains(reason, "outbound_rule")
+	contains(reason, "not known")
+}
+
+test_unknown_destination_addresses_in_one_rule_is_denied if {
+	after := {"inbound_rule": [], "outbound_rule": [out_rule("tcp", "443", ["203.0.113.0/24"]), out_rule("udp", "53", [])]}
+	reasons := denied([firewall_unknown(after, {"outbound_rule": [{}, {"destination_addresses": true}]})])
+	count(reasons) == 1
+	some reason in reasons
+	contains(reason, "outbound_rule")
+	contains(reason, "destination_addresses")
+}
+
+test_unknown_element_of_destination_addresses_is_denied if {
+	after := {"inbound_rule": [], "outbound_rule": [out_rule("tcp", "443", ["203.0.113.0/24"])]}
+	reasons := denied([firewall_unknown(after, {"outbound_rule": [{"destination_addresses": [false, true]}]})])
+	count(reasons) == 1
+}
+
+test_unknown_whole_outbound_rule_element_is_denied if {
+	after := {"inbound_rule": [], "outbound_rule": [out_rule("tcp", "443", ["203.0.113.0/24"])]}
+	count(denied([firewall_unknown(after, {"outbound_rule": [true]})])) == 1
+}
+
+test_unknown_outbound_is_not_allowlistable if {
+	allow := allow_for("svc-a", fw, [out_entry({})])
+	after := {"inbound_rule": [], "outbound_rule": [out_rule("tcp", "443", out_world)]}
+	changes := [firewall_unknown(after, {"outbound_rule": [{"destination_addresses": [true, false]}]})]
+	count(reasons_with_outbound("svc-a", changes, allow)) == 1
+}
+
+test_unknown_inbound_rule_list_is_denied if {
+	reasons := denied([firewall_unknown({"outbound_rule": []}, {"inbound_rule": true})])
+	count(reasons) == 1
+	some reason in reasons
+	contains(reason, "inbound_rule")
+	contains(reason, "not known")
+}
+
+test_unknown_inbound_sources_are_denied if {
+	after := {"outbound_rule": [], "inbound_rule": [tag_rule, tag_rule]}
+	every key in ["source_addresses", "source_droplet_ids", "source_load_balancer_uids", "source_kubernetes_ids"] {
+		reasons := denied([firewall_unknown(after, {"inbound_rule": [{}, {key: true}]})])
+		count(reasons) == 1
+		some reason in reasons
+		contains(reason, key)
+	}
+}
+
+test_unknown_on_update_is_denied_too if {
+	update := {
+		"address": fw,
+		"type": "digitalocean_firewall",
+		"change": {"actions": ["update"], "after": {"inbound_rule": []}, "after_unknown": {"outbound_rule": true}},
+	}
+	count(denied([update])) == 1
+}
+
+# Unknown values elsewhere are not this policy's business, and the empty and
+# absent shapes of after_unknown do not crash it.
+test_unrelated_and_empty_unknowns_pass if {
+	after := {"inbound_rule": [tag_rule], "outbound_rule": [out_rule("tcp", "443", ["203.0.113.0/24"])]}
+	count(denied([firewall_unknown(after, {"id": true, "droplet_ids": true, "outbound_rule": [{"protocol": false}], "inbound_rule": [{"source_tags": true}]})])) == 0
+	count(denied([firewall_unknown(after, {})])) == 0
+	count(denied([firewall_unknown(after, null)])) == 0
+	count(denied([firewall_unknown(after, {"outbound_rule": false, "inbound_rule": false})])) == 0
+}
+
+test_unknown_on_a_delete_is_ignored if {
+	gone := {
+		"address": fw,
+		"type": "digitalocean_firewall",
+		"change": {"actions": ["delete"], "before": {"inbound_rule": []}, "after": null, "after_unknown": {"outbound_rule": true}},
+	}
+	not any_not_known(denied([gone]))
+}
+
+any_not_known(reasons) if {
+	some reason in reasons
+	contains(reason, "not known")
+}

+ 30 - 1
docs/spacelift-secrets.md

@@ -280,6 +280,12 @@ It denies a created or updated resource that is:
 | Resource | Denied when |
 |---|---|
 | `digitalocean_firewall` | An inbound rule has any source other than a tag: a source address (and `0.0.0.0/0` or `::/0` is called out as the whole internet), a droplet id, a load balancer or a Kubernetes cluster. The firewall module only ever emits `source_tags`, so a tag-scoped rule passes. |
+| `digitalocean_firewall` (outbound) | An outbound rule has a world-open address among its destination addresses (see below) and no `outbound_allowlist` entry covers it (issue #253). A rule to a tag, or to named addresses only, is not judged. A world-open `icmp` rule, or one with no port range (or `all`), is always denied. |
+| `digitalocean_firewall` (unknown values) | The plan marks `inbound_rule` or `outbound_rule` as unknown until apply, or marks a rule's source or destination addresses as unknown. The policy cannot tell what they resolve to, so it denies; no allowlist entry covers it. |
+
+**What counts as the whole internet.** The policy reads prefix lengths, not spellings. An inbound source or outbound destination with a prefix length of 0 or 1 is world-open, for IPv4 and IPv6: `0.0.0.0/0`, `::/0`, `0::/0`, `::0/0`, `0:0:0:0:0:0:0:0/0`, `0.0.0.0/00`, and the two halves `0.0.0.0/1` with `128.0.0.0/1` (or `::/1` with `8000::/1`). Anything that is not text, or does not parse as an address or a CIDR range, fails closed and counts as world-open. Such a value never matches an allowlist entry, because entries name exact strings. Narrower splits (for example four `/2` ranges) are not detected; the firewall module never renders them and an entry is exact, so they would be an unreviewed change the policy does not call out by name.
+
+**Unknown values.** A plan lists values it cannot know yet in `change.after_unknown`, which mirrors `change.after`: `true` for a whole list or value, or a list of objects for the rules. A firewall create or update where `outbound_rule` or `inbound_rule` is unknown, where one whole rule is unknown, or where a rule's `destination_addresses` (outbound) or any non-tag source (inbound: addresses, droplet ids, load balancers, Kubernetes clusters) is unknown, is denied with a message that names the field. Make the value static (a literal, or an input known at plan time) and the plan can be judged. This closes the case where a value resolves to `0.0.0.0/0` only at apply.
 | `aws_vpc_security_group_ingress_rule`, `aws_security_group_rule` (ingress), `aws_security_group` (inline ingress) | The source is a CIDR range, IPv4 or IPv6. A reference to a security group passes. |
 | `digitalocean_droplet` | `ipv6 = true`. |
 | `aws_vpc`, `aws_subnet`, `aws_instance` | The plan turns on an IPv6 range or address. |
@@ -319,7 +325,30 @@ inbound_allowlist := {"example-stack-id": {"module.service_host.digitalocean_fir
 
 The rule must match every field: direction (only `inbound` is read today), protocol, port range (exact strings such as `5201` or `8000-8100`) and every source address the rule has. An entry for a rule open to the world names both `0.0.0.0/0` and `::/0`; an entry naming only one does not cover a rule that uses both, while a rule that uses only one of them is within an entry that names both. A rule that adds a droplet, load balancer or Kubernetes source is never covered. A firewall with two rules needs an entry for each rule that is not tag-scoped. AWS ingress rules are judged by the same entries (the sources are CIDR ranges); one rule with several ranges needs one entry that lists them all. `address_groups` names a set of addresses per stack so one entry can cover several resources there. A missing or unknown stack id, address, group or field allows nothing: the policy fails closed.
 
-Add an entry only when that service's stack is approved, in the same pull request, with a threat-model note (`docs/wiki/Threat-Model.md`) naming the stack, the port, the source and the reason, and a review. After the merge, paste the new body into Spacelift. There is no stack label, environment variable or plan field that grants an exception, on purpose: a branch must not be able to grant its own. All the lists are empty today. The IPv6 checks have no exception.
+Add an entry only when that service's stack is approved, in the same pull request, with a threat-model note (`docs/wiki/Threat-Model.md`) naming the stack, the port, the source and the reason, and a review. After the merge, paste the new body into Spacelift. There is no stack label, environment variable or plan field that grants an exception, on purpose: a branch must not be able to grant its own. The inbound and destroy lists are empty today and `outbound_allowlist` holds only the entries below. The IPv6 checks have no exception.
+
+### A deliberate outbound exception
+
+The firewall module renders five outbound rules on every firewall (tcp 443, 80, 53 and udp 53, 123) to any address, because package mirrors, DNS and NTP servers have no fixed addresses, and a stack can add more through `extra_outbound_rules`. The plan policy treats any outbound rule whose destinations include `0.0.0.0/0` or `::/0` the way it treats a world-open inbound rule: denied unless `outbound_allowlist` has an entry for it. The map has the same shape as `inbound_allowlist` (stack id, then address or group name), and an entry says its direction, protocol, ports and destinations:
+
+```rego
+outbound_allowlist := {"example-stack-id": {"module.service_host.digitalocean_firewall.this": [{
+	"direction": "outbound",
+	"protocol": "tcp",
+	"ports": ["443", "80"],
+	"destinations": ["0.0.0.0/0", "::/0"],
+}]}}
+```
+
+Matching is exact, as for inbound: the direction must be `outbound`, the protocol and each port string must match, and every destination address of the rule must be in the entry. One entry covers one protocol, so a firewall with tcp and udp rules needs two. An entry naming only one world range does not cover a rule that uses both. Another stack, another address, or a plan with no stack id gets nothing. A rule that adds a destination tag, droplet, load balancer or Kubernetes cluster next to the world range is never covered. AWS egress rules are not judged by this check.
+
+**Decision on icmp and all-port rules: they are never allowlistable.** An `icmp` rule has no port, and a tcp or udp rule with no `port_range` (missing, empty or `all`) has no limit. Combined with a world-open destination, nothing narrows either one, so an entry that tries to name them (`"ports": ["all"]`, `"protocol": "icmp"`) admits nothing. If one is genuinely needed, give the rule destinations instead of the whole internet. A literal range such as `1-65535` is judged as written: the entry must name that exact string, which puts the widest range in the reviewed pull request with its reason. The connector firewall's `udp 1-65535` is exactly that case.
+
+Why `udp 1-65535` is allowlisted and `all` is not, stated plainly: they are the same in effect, every port, and the policy does not pretend otherwise. The policy judges text. `all` (or no range) states no limit, so there is nothing for a reviewer to read; `1-65535` is a number the author chose to write down, and it takes an exact entry naming it. That entry exists because Twingate's documented outbound needs ask for udp to any port for peer-to-peer connections, and it is limited to the `cah-10-access` connector firewall. This is a judgment about visibility, not a claim that `1-65535` is narrower.
+
+**Instance stacks need their own entry.** Allowlists are keyed by the exact stack id. An instance of a stack gets its own id (for example `cah-10-access-tor2`, from `stacks/sites/tor2/10-access`), so the `cah-10-access` entry does not cover it: a world-open outbound rule there is denied until a reviewed pull request adds an entry under `cah-10-access-tor2` for its own firewall address. That is on purpose and fails closed: one site's exception never covers another's. Adding an instance therefore includes adding its entry, with the reason. `tests/test_outbound_allowlist_matches_module.py` checks that the shipped entries match what the module and the access stack render today.
+
+The shipped `outbound_allowlist` has two stack entries, each for a rule the module renders today and each with its reason in the file: `cah-00-foundation` for `module.baseline_firewall.digitalocean_firewall.this` (the five defaults), and `cah-10-access` for `module.connector_firewall.digitalocean_firewall.this` (the defaults, `tcp 30000-31000` and `udp 1-65535`, which Twingate's documented outbound needs ask for). The telemetry and AWS stacks have no entry, so a world-open outbound rule there is denied. Remove an entry when its rule goes away, and add one only in a pull request that names the stack, the protocol, the ports and the reason.
 
 A deliberate destroy works the same way. `destroy_allowlist` maps a stack id to a list of addresses or group names: add the protected resource under its stack, in a pull request that names the stack, the address and the reason, and paste the new body into Spacelift after the merge. The denial message says the same. Remove the entry once the change has applied, so the next plan is guarded again. Other addresses, and the same address in another stack, stay denied.
 

+ 1 - 1
docs/wiki/Spacelift.md

@@ -106,7 +106,7 @@ This is the one place this wiki states the caveat in full; other pages link here
 
 ### The plan policy: no open ports in a plan
 
-A second policy, `.spacelift/policies/plan.rego`, reads the plan before an apply and denies it if it would open a port on a core machine: a firewall inbound rule with a source address or `0.0.0.0/0`, an AWS ingress rule from a CIDR range, or IPv6 turned on for a droplet or an AWS network. A rule that admits only a tag (the only kind the firewall module emits) passes. The firewall module's tests catch the same mistakes in CI; this catches them in the plan that is about to be applied.
+A second policy, `.spacelift/policies/plan.rego`, reads the plan before an apply and denies it if it would open a port on a core machine: a firewall inbound rule with a source address or `0.0.0.0/0`, an AWS ingress rule from a CIDR range, or IPv6 turned on for a droplet or an AWS network. A rule that admits only a tag (the only kind the firewall module emits) passes. It also reads outbound rules: one that reaches the whole internet (judged by prefix length, so `0::/0`, `0.0.0.0/00` and the halves `0.0.0.0/1` plus `128.0.0.0/1` count too) is denied unless a reviewed `outbound_allowlist` entry names its stack, address, protocol, ports and destinations, and an icmp or all-port rule to the whole internet is never allowed. A firewall rule list or address list that is unknown until apply is denied too, since it could resolve to the whole internet. The firewall module's tests catch the same mistakes in CI; this catches them in the plan that is about to be applied.
 
 A deliberate exception is a reviewed code change: an entry in an allowlist inside the policy file, with a threat-model note. A stack label or a plan field cannot grant one. How the allowlists work is in [the allowlist model](#the-plan-policy-the-allowlist-model) below. It is written and tested but **not yet attached**, and it is a policy in Spacelift like the push policy, so the same paid-plan caveat applies; whether the plan policy type is available on the maintainer's plan is unconfirmed. The steps are in [section 9a of the secrets runbook](https://github.com/ChiefGyk3D/Clouds-Against-Humanity/blob/main/docs/spacelift-secrets.md#9a-the-plan-policy).
 

+ 86 - 0
tests/test_outbound_allowlist_matches_module.py

@@ -0,0 +1,86 @@
+"""The shipped outbound_allowlist matches what the firewall module renders.
+
+The plan policy (.spacelift/policies/plan.rego) allows a world-open outbound
+rule only through an exact entry. Each shipped entry exists because the module
+renders that rule today (issue #253), so a change to the module defaults or to
+a stack's extra_outbound_rules that is not mirrored in the policy would either
+be denied at apply time or leave a stale exception behind. This reads the
+sources and compares them in both directions. Each check also runs on a broken
+fixture, so a check that stops biting fails here.
+"""
+
+import re
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+POLICY = ROOT / ".spacelift/policies/plan.rego"
+MODULE = ROOT / "modules/firewall/main.tf"
+ACCESS = ROOT / "stacks/10-access/main.tf"
+
+RULE = re.compile(r'protocol\s*=\s*"(\w+)"\s*,\s*port_range\s*=\s*"([^"]+)"')
+
+
+def strip_comments(text: str) -> str:
+    return re.sub(r"(?m)(#|//).*$", "", text)
+
+
+def tf_rules(text: str, header: str) -> set[tuple[str, str]]:
+    """(protocol, port_range) pairs in the bracketed list after `header`."""
+    start = text.index(header)
+    open_at = text.index("[", start)
+    depth = 0
+    for i in range(open_at, len(text)):
+        depth += {"[": 1, "]": -1}.get(text[i], 0)
+        if depth == 0:
+            return set(RULE.findall(text[open_at : i + 1]))
+    raise AssertionError(f"unbalanced list after {header!r}")
+
+
+def policy_entries(text: str) -> dict[str, set[tuple[str, str]]]:
+    """Stack id -> (protocol, port) pairs from outbound_allowlist entries."""
+    body = strip_comments(text)
+    start = body.index("outbound_allowlist := {")
+    end = body.index("address_groups :=", start)
+    section = body[start:end]
+    result: dict[str, set[tuple[str, str]]] = {}
+    for stack in re.finditer(r'"(cah-[\w-]+)":\s*\{', section):
+        rest = section[stack.end() :]
+        nxt = re.search(r'\n\t"cah-[\w-]+":\s*\{', rest)
+        chunk = rest[: nxt.start()] if nxt else rest
+        pairs: set[tuple[str, str]] = set()
+        for entry in re.finditer(r'"protocol":\s*"(\w+)",\s*"ports":\s*\[([^\]]*)\]', chunk):
+            for port in re.findall(r'"([^"]+)"', entry.group(2)):
+                pairs.add((entry.group(1), port))
+        result[stack.group(1)] = pairs
+    return result
+
+
+def expected(module: str, access: str) -> dict[str, set[tuple[str, str]]]:
+    defaults = tf_rules(strip_comments(module), "default_outbound = [")
+    extra = tf_rules(strip_comments(access), "extra_outbound_rules = [")
+    return {"cah-00-foundation": defaults, "cah-10-access": defaults | extra}
+
+
+def test_shipped_entries_match_what_the_module_renders():
+    got = policy_entries(POLICY.read_text())
+    want = expected(MODULE.read_text(), ACCESS.read_text())
+    assert want["cah-00-foundation"], "found no default outbound rules"
+    assert want["cah-10-access"] > want["cah-00-foundation"], "found no extra rules"
+    assert got == want
+
+
+def test_check_notices_a_rule_missing_from_the_policy():
+    module = MODULE.read_text().replace('{ protocol = "udp", port_range = "123" },', "")
+    assert policy_entries(POLICY.read_text()) != expected(module, ACCESS.read_text())
+
+
+def test_check_notices_a_stale_policy_entry():
+    stale = POLICY.read_text().replace('"ports": ["53", "123"]', '"ports": ["53", "123", "8443"]', 1)
+    assert policy_entries(stale) != expected(MODULE.read_text(), ACCESS.read_text())
+
+
+def test_check_notices_a_new_extra_rule_in_the_stack():
+    access = ACCESS.read_text().replace(
+        'port_range = "30000-31000" },', 'port_range = "30000-31000" },\n    { protocol = "tcp", port_range = "8443" },', 1
+    )
+    assert policy_entries(POLICY.read_text()) != expected(MODULE.read_text(), access)