Przeglądaj źródła

fix: harden the cost gate, the Portainer pin, the SearXNG bind, workload tests, the Spaces outputs and the onion lab audit (#449) (#452)

The cost gate now refuses provisioner blocks and external data sources. The Portainer image is pinned by tag and digest. The SearXNG compose file checks its bind address before core starts. The workload stack tests read every file of the stack. The Spaces module no longer outputs secret keys. The onion lab audit reads probe responses and counts 3xx answers.

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
ChiefGyk3D 1 miesiąc temu
rodzic
commit
7d24523c2f

+ 8 - 8
docs/settings.json

@@ -1313,12 +1313,12 @@
       {
         "name": "portainer_version",
         "type": "string",
-        "description": "Exact Portainer CE image tag, an LTS release from Portainer's releases page (read 2026-10-31). Bumped in a reviewed change, which replaces the droplet.",
+        "description": "Portainer CE image reference after portainer/portainer-ce:, pinned by exact tag and by digest (2.45.3, an LTS release from Portainer's releases page read 2026-10-31; the multi-arch index digest read from Docker Hub on 2026-11-02). Bumped in a reviewed change, which replaces the droplet.",
         "required": false,
-        "default": "2.45.3",
-        "validation": "an exact version such as 2.45.3; never latest, a range or a variant",
+        "default": "2.45.3@sha256:3609c307943bca8e5c492f69ddd6965df177208b50678a4cff28391c8dd4e96e",
+        "validation": "<exact version>@sha256:<64 hex digits>, such as 2.45.3@sha256:...; never latest, a range, a variant or a tag without its digest",
         "set_where": "tfvars (local plans) or Spacelift stack environment (TF_VAR_*)",
-        "example": "2.45.3",
+        "example": "2.45.3@sha256:3609c307943bca8e5c492f69ddd6965df177208b50678a4cff28391c8dd4e96e",
         "sensitivity": "public",
         "sensitive_in_code": false,
         "status": "exists"
@@ -2358,12 +2358,12 @@
       {
         "name": "portainer_version",
         "type": "string",
-        "description": "Exact Portainer CE image tag (an LTS release, read 2026-10-31). Never latest or a range. Bumping it replaces the droplet.",
+        "description": "Portainer CE image reference after portainer/portainer-ce:, pinned by exact tag and by digest (2.45.3, an LTS release read 2026-10-31; the multi-arch index digest read from Docker Hub on 2026-11-02). Never latest or a range. Bumping it replaces the droplet.",
         "required": false,
-        "default": "2.45.3",
-        "validation": "an exact version such as 2.45.3; never latest, a range or a variant",
+        "default": "2.45.3@sha256:3609c307943bca8e5c492f69ddd6965df177208b50678a4cff28391c8dd4e96e",
+        "validation": "<exact version>@sha256:<64 hex digits>, such as 2.45.3@sha256:...; never latest, a range, a variant or a tag without its digest",
         "set_where": "set by the calling stack (not a user setting)",
-        "example": "2.45.3",
+        "example": "2.45.3@sha256:3609c307943bca8e5c492f69ddd6965df177208b50678a4cff28391c8dd4e96e",
         "sensitivity": "public",
         "sensitive_in_code": false,
         "status": "exists"

+ 1 - 1
docs/stages/03-workloads.md

@@ -37,7 +37,7 @@ The order is the one every stage guide states: update, baseline, harden, then ap
 - **Baseline.** User `cah-admin`, one public key, no password, root locked. sshd: no root login, no password login, `AllowUsers cah-admin`.
 - **Harden.** `sshd -t && systemctl restart ssh` runs before anything is installed.
 - **Docker Engine** from Docker's apt repository. The key file must hold exactly one key and its fingerprint must equal the pin (`docker_apt_key_fingerprint`) before the repository is trusted. `daemon.json`: `live-restore`, capped `json-file` logs, default bind address `127.0.0.1`, and **no `hosts` key**, so the Docker API is the local socket and nothing else.
-- **Portainer CE**, pinned to an exact tag (`portainer_version`), from a compose file owned by cloud-init. Its one published port is `${PORTAINER_BIND:?}:9443:9443`, where the address is the droplet's private VPC address read from the metadata endpoint. If there is no private address nothing starts: there is no wildcard fallback. Memory limit and `no-new-privileges` are set.
+- **Portainer CE**, pinned to an exact tag and image digest (`portainer_version`), from a compose file owned by cloud-init. Its one published port is `${PORTAINER_BIND:?}:9443:9443`, where the address is the droplet's private VPC address read from the metadata endpoint. If there is no private address nothing starts: there is no wildcard fallback. Memory limit and `no-new-privileges` are set.
 - **No credential in user-data.** User-data is readable from the metadata endpoint and ends up in state. The daemons' credentials stay in Doppler (design section 6).
 
 ## 4. Before the switch can be turned on

+ 2 - 1
docs/wiki/Lab-Publish-a-Web-Server-as-a-Tor-Onion-Service-and-an-I2P-Site-Time-Boxed-and-Defensive.md

@@ -285,6 +285,7 @@ Here is what it prints against the two small servers this page's tests start on
 ```
 check_origin: 127.0.0.1:8080
 [REVIEW] something listens on every interface: 0.0.0.0:22 (is it supposed to?)
+[REVIEW] header Server names the software: nginx (no version, so not a failure; hide it if your server can)
 0 problems
 ```
 
@@ -303,7 +304,7 @@ check_origin: 127.0.0.1:8080
 6 problems
 ```
 
-The `[REVIEW]` lines are not failures: SSH on port 22 is a listener you may well want, and the script cannot know. A clean run proves only that these four checks found nothing. It does not prove the service is safe.
+The `[REVIEW]` lines are not failures: SSH on port 22 is a listener you may well want, and the script cannot know; a `Server` header that says only `nginx` names the software without a version, which a stock nginx still sends with `server_tokens off`, so it is listed for you to judge. The script reads the headers of every response it gets, including the probe paths, and counts a status of 2xx or 3xx on a probe path as an answer, because a redirect also tells a visitor the path exists. A clean run proves only that these four checks found nothing. It does not prove the service is safe.
 
 ### Step 6: tear it down
 

+ 2 - 2
docs/wiki/Settings-Reference.md

@@ -158,7 +158,7 @@ Stack variables are the settings you set per site. Module variables are filled i
 | `admin_ssh_key_name`<br>Name of an SSH key already registered on the DigitalOcean account. | `string` | required | non-empty | Doppler (config prd), exported as TF_VAR_* by the Spacelift hook (ADMIN_SSH_KEY_NAME) | `example-admin-key` | private (not a credential, but identifies the owner) | exists |
 | `reboot_time`<br>HH:MM (in timezone) when unattended-upgrades may reboot the droplet. At least 30 minutes from the connectors' reboots (04:00 and 05:00) and weekly updates (04:30 and 05:30); the default is outside the edge slots too. | `string` | `"03:30"` | HH:MM in 24-hour time; at least 30 minutes (around the clock) from 04:00, 04:30, 05:00 and 05:30 | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `03:30` | public | exists |
 | `timezone`<br>IANA time zone name of the machine, also the zone reboot_time is read in. Default America/New_York, the zone the connectors' windows are written in. Changing it replaces the droplet. | `string` | `"America/New_York"` | UTC, or Area/Location with letters, digits and _ + - only (no spaces or line breaks) | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `America/New_York` | public | exists |
-| `portainer_version`<br>Exact Portainer CE image tag, an LTS release from Portainer's releases page (read 2026-10-31). Bumped in a reviewed change, which replaces the droplet. | `string` | `"2.45.3"` | an exact version such as 2.45.3; never latest, a range or a variant | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `2.45.3` | public | exists |
+| `portainer_version`<br>Portainer CE image reference after portainer/portainer-ce:, pinned by exact tag and by digest (2.45.3, an LTS release from Portainer's releases page read 2026-10-31; the multi-arch index digest read from Docker Hub on 2026-11-02). Bumped in a reviewed change, which replaces the droplet. | `string` | `"2.45.3@sha256:3609c307943bca8e5c492f69ddd6965df177208b50678a4cff28391c8dd4e96e"` | &lt;exact version&gt;@sha256:&lt;64 hex digits&gt;, such as 2.45.3@sha256:...; never latest, a range, a variant or a tag without its digest | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `2.45.3@sha256:3609c307943bca8e5c492f69ddd6965df177208b50678a4cff28391c8dd4e96e` | public | exists |
 | `onion_service_enabled`<br>Optional, default off (issue #391). true, together with workload_enabled, adds a loopback-only static origin and a Tor onion service to the workload host's cloud-init. The flag adds no resource, opens no port and changes no firewall rule. The service key is made on the host and never appears in the plan or the state. | `bool` | `false` | none beyond bool (nullable = false); has no effect while workload_enabled is false | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `false` | public | exists |
 | `workload_web_ports`<br>Optional, default empty (issue #437). Web ports of workloads on the host, for example [8080] for SearXNG. Each port gets one TCP-only Twingate resource on the host's private address (admins group) and one inbound allowance from the connector tag. Empty creates nothing, and so does workload_enabled = false. Nothing is applied. | `list(number)` | `[]` | whole numbers from 1024 to 65535, no duplicates, at most 8, never 22 or 9443 (nullable = false) | tfvars (local plans) or Spacelift stack environment (TF_VAR_*) | `[8080]` | public | exists |
 
@@ -274,7 +274,7 @@ Stack variables are the settings you set per site. Module variables are filled i
 | `reboot_time`<br>HH:MM (in timezone) when unattended-upgrades may reboot this droplet. | `string` | required | HH:MM in 24-hour time | set by the calling stack (not a user setting) | `03:30` | public | exists |
 | `timezone`<br>IANA time zone name of the machine, also the zone reboot_time is read in. Changing it replaces the droplet. | `string` | `"America/New_York"` | UTC, or Area/Location with letters, digits and _ + - only (no spaces or line breaks) | set by the calling stack (not a user setting) | `America/New_York` | public | exists |
 | `docker_apt_key_fingerprint`<br>Primary fingerprint of Docker's apt signing key. The cloud-init refuses a key file that does not hold exactly this one key before it trusts the repository. Changing it replaces the droplet. | `string` | `"9DC858229FC7DD38854AE2D88D81803C0EBFCD88"` | a full 40-character fingerprint in uppercase hexadecimal, no spaces | set by the calling stack (not a user setting); the default is Docker's published key | `9DC858229FC7DD38854AE2D88D81803C0EBFCD88` | public | exists |
-| `portainer_version`<br>Exact Portainer CE image tag (an LTS release, read 2026-10-31). Never latest or a range. Bumping it replaces the droplet. | `string` | `"2.45.3"` | an exact version such as 2.45.3; never latest, a range or a variant | set by the calling stack (not a user setting) | `2.45.3` | public | exists |
+| `portainer_version`<br>Portainer CE image reference after portainer/portainer-ce:, pinned by exact tag and by digest (2.45.3, an LTS release read 2026-10-31; the multi-arch index digest read from Docker Hub on 2026-11-02). Never latest or a range. Bumping it replaces the droplet. | `string` | `"2.45.3@sha256:3609c307943bca8e5c492f69ddd6965df177208b50678a4cff28391c8dd4e96e"` | &lt;exact version&gt;@sha256:&lt;64 hex digits&gt;, such as 2.45.3@sha256:...; never latest, a range, a variant or a tag without its digest | set by the calling stack (not a user setting) | `2.45.3@sha256:3609c307943bca8e5c492f69ddd6965df177208b50678a4cff28391c8dd4e96e` | public | exists |
 | `portainer_port`<br>Host port Portainer's HTTPS UI is published on, bound to the private address only. | `number` | `9443` | a whole port from 1024 to 65535, never 22; non-nullable | set by the calling stack (not a user setting) | `9443` | public | exists |
 | `onion_service_enabled`<br>Optional, default off (issue #391). true adds a loopback-only static nginx origin and a Tor onion service to the cloud-init. It opens no port to the internet, changes no firewall rule and keeps the service key on the host, out of the plan and the state. Changing it replaces the droplet. | `bool` | `false` | none beyond bool (nullable = false) | set by the calling stack (not a user setting) | `false` | public | exists |
 | `onion_origin_image`<br>Static origin image for the onion service, the official Docker Hub library image pinned by tag and by digest (nginx 1.30.6-alpine, digest read from Docker Hub 2026-11-01). Used only when onion_service_enabled is true. Bumping it replaces the droplet. | `string` | `"nginx:1.30.6-alpine@sha256:0e52bd054126cdc040b1276c0af347aeb02a41b9cfe305d6094767ac30e97949"` | nginx:&lt;exact version&gt;-alpine@sha256:&lt;64 hex digits&gt;; never latest, never a tag alone | set by the calling stack (not a user setting) | `nginx:1.30.6-alpine@sha256:0e52bd054126cdc040b1276c0af347aeb02a41b9cfe305d6094767ac30e97949` | public | exists |

+ 27 - 6
labs/onion-lab/check_origin.py

@@ -4,9 +4,10 @@
 It answers the questions the lesson lists, for an origin on THIS machine only:
 
   1. Does the origin listen on anything but loopback?
-  2. Do the response headers name the software, a version, a proxy or an address?
+  2. Do the response headers (the front page, a missing page and every probe path) carry a version, an operating system,
+     a proxy hint or an address? A Server header that names only the software is listed for review, not failed.
   3. Does the page load or embed anything from another host, or write an address into its text?
-  4. Do the usual status and debug paths answer?
+  4. Do the usual status and debug paths answer with a 2xx or 3xx status?
 
 It sends plain GET requests to a loopback address and reads `ss -ltn`. It refuses any other target, never touches Tor or I2P,
 and changes nothing. A clean run proves only that these four checks found nothing; it does not prove the service is safe.
@@ -105,6 +106,20 @@ def header_problems(headers):
     return problems
 
 
+def server_review(headers):
+    """Review lines for a Server header that names the software without a version.
+
+    A bare name such as `nginx` is what a stock server sends even with its version hidden, so it is listed for the
+    reader to judge and is not a failure. A version or an operating system is already a failure in header_problems,
+    so it is left out here."""
+    lines = []
+    for name, value in headers:
+        value = value.strip()
+        if name.lower() == "server" and value and not (VERSIONED.search(value) or "(" in value):
+            lines.append(f"header Server names the software: {value}")
+    return lines
+
+
 class Scan(html.parser.HTMLParser):
     def __init__(self):
         super().__init__(convert_charrefs=True)
@@ -158,7 +173,8 @@ def outbound_links(body):
 
 
 def exposed_paths(results):
-    return sorted(path for path, status in results.items() if status == 200 and path != "/")
+    """Paths whose status is 2xx or 3xx: the page answers, or redirects somewhere (a redirect still tells a visitor the path exists)."""
+    return sorted(path for path, status in results.items() if 200 <= status < 400 and path != "/")
 
 
 def fetch(host, port, path):
@@ -207,14 +223,19 @@ def main(argv=None):
         for link in outbound_links(body):
             print(f"[REVIEW] the page links out to {link} (a click sends a referrer and ends the session's cover)")
         _, miss_headers, _ = fetch(args.host, args.port, "/no-such-page")
-        problems += [p for p in header_problems(miss_headers) if p not in problems]
-        results = {path: fetch(args.host, args.port, path)[0] for path in PROBE_PATHS}
+        probes = {path: fetch(args.host, args.port, path) for path in PROBE_PATHS}
     except OSError as err:
         print(f"check_origin: could not reach the origin: {err}")
         return 2
-    problems += [f"the path {p} answers 200" for p in exposed_paths(results)]
+    responses = [headers, miss_headers] + [probe[1] for probe in probes.values()]
+    problems += [p for p in dict.fromkeys(q for h in responses[1:] for q in header_problems(h)) if p not in problems]
+    reviews = list(dict.fromkeys(line for h in responses for line in server_review(h)))
+    results = {path: probe[0] for path, probe in probes.items()}
+    problems += [f"the path {p} answers {results[p]}" for p in exposed_paths(results)]
     if status != 200:
         problems.append(f"the front page answered {status}, not 200")
+    for line in reviews:
+        print(f"[REVIEW] {line} (no version, so not a failure; hide it if your server can)")
     for p in problems:
         print(f"[FAIL] {p}")
     print(f"{len(problems)} problems")

+ 1 - 1
modules/docker-host/cloud-init.yaml.tftpl

@@ -153,7 +153,7 @@ write_files:
           "max-file": "3"
         }
       }
-  # Portainer CE, pinned to an exact tag. The only published port is bound to
+  # Portainer CE, pinned to an exact tag and an image digest. The only published port is bound to
   # the droplet's private VPC address, which cah-portainer-up writes to .env;
   # ":?" makes compose refuse to start when it is unset, so there is no wildcard
   # fallback. Port 8000 (the Edge agent tunnel) and 9000 (plain HTTP) are not

+ 35 - 3
modules/docker-host/tests/docker-host.tftest.hcl

@@ -144,8 +144,8 @@ run "the_docker_daemon_has_no_network_socket_and_binds_loopback_by_default" {
 run "portainer_is_pinned_bound_to_the_private_address_and_limited" {
   command = plan
   assert {
-    condition     = strcontains(digitalocean_droplet.workload.user_data, "image: portainer/portainer-ce:2.45.3")
-    error_message = "Portainer CE must be pinned to an exact version tag."
+    condition     = strcontains(digitalocean_droplet.workload.user_data, "image: portainer/portainer-ce:2.45.3@sha256:3609c307943bca8e5c492f69ddd6965df177208b50678a4cff28391c8dd4e96e")
+    error_message = "Portainer CE must be pinned to an exact version tag and to its image digest."
   }
   assert {
     condition     = strcontains(digitalocean_droplet.workload.user_data, "- \"$${PORTAINER_BIND:?}:9443:9443\"")
@@ -207,7 +207,39 @@ run "latest_is_not_a_portainer_version" {
 run "a_range_is_not_a_portainer_version" {
   command = plan
   variables {
-    portainer_version = "2.45"
+    portainer_version = "2.45@sha256:3609c307943bca8e5c492f69ddd6965df177208b50678a4cff28391c8dd4e96e"
+  }
+  expect_failures = [var.portainer_version]
+}
+
+run "a_tag_without_a_digest_is_not_a_portainer_version" {
+  command = plan
+  variables {
+    portainer_version = "2.45.3"
+  }
+  expect_failures = [var.portainer_version]
+}
+
+run "a_short_or_uppercase_digest_is_not_a_portainer_version" {
+  command = plan
+  variables {
+    portainer_version = "2.45.3@sha256:3609c307943bca8e5c492f69ddd6965df177208b50678a4cff28391c8dd4e96"
+  }
+  expect_failures = [var.portainer_version]
+}
+
+run "a_digest_alone_is_not_a_portainer_version" {
+  command = plan
+  variables {
+    portainer_version = "@sha256:3609c307943bca8e5c492f69ddd6965df177208b50678a4cff28391c8dd4e96e"
+  }
+  expect_failures = [var.portainer_version]
+}
+
+run "a_second_image_reference_is_not_a_portainer_version" {
+  command = plan
+  variables {
+    portainer_version = "2.45.3@sha256:3609c307943bca8e5c492f69ddd6965df177208b50678a4cff28391c8dd4e96e\n  other: image"
   }
   expect_failures = [var.portainer_version]
 }

+ 4 - 4
modules/docker-host/variables.tf

@@ -94,12 +94,12 @@ variable "docker_apt_key_fingerprint" {
 
 variable "portainer_version" {
   type        = string
-  default     = "2.45.3"
-  description = "Exact Portainer CE image tag (an LTS release from Portainer's releases page, read 2026-10-31). Never latest or a range: Portainer updates only when this is bumped in a reviewed change, which replaces the droplet."
+  default     = "2.45.3@sha256:3609c307943bca8e5c492f69ddd6965df177208b50678a4cff28391c8dd4e96e"
+  description = "Portainer CE image reference after portainer/portainer-ce:, pinned by exact tag and by digest (2.45.3, an LTS release from Portainer's releases page read 2026-10-31; the multi-arch index digest read from Docker Hub on 2026-11-02). Never latest or a range: Portainer updates only when this is bumped in a reviewed change, which replaces the droplet."
 
   validation {
-    condition     = can(regex("^[0-9]+\\.[0-9]+\\.[0-9]+$", var.portainer_version))
-    error_message = "portainer_version must be an exact version such as 2.45.3, never latest, a range or a variant."
+    condition     = can(regex("^[0-9]+\\.[0-9]+\\.[0-9]+@sha256:[0-9a-f]{64}$", var.portainer_version))
+    error_message = "portainer_version must be <exact version>@sha256:<64 hex digits> such as 2.45.3@sha256:..., pinned by tag and by digest, never latest, a range or a variant."
   }
 }
 

+ 2 - 2
modules/spaces-bucket/README.md

@@ -42,8 +42,8 @@ bucket. The prefix per daemon is a convention, not a boundary.
 ## Outputs
 
 `bucket_name`, `region`, `endpoint`, `bucket_domain_name` and `urn` are plain
-strings (the module has no off state: switch it with `count` on the call). `access_keys` and `secret_keys` are maps by key name
-and are marked sensitive. Do not print them; put them in Doppler.
+strings (the module has no off state: switch it with `count` on the call). `access_keys` is a map of key ids by key name
+and is marked sensitive. The module has no output for a secret key.
 
 ## Restore
 

+ 0 - 6
modules/spaces-bucket/outputs.tf

@@ -28,9 +28,3 @@ output "access_keys" {
   sensitive   = true
   description = "Access key ids by key name. Sensitive: an id identifies a credential."
 }
-
-output "secret_keys" {
-  value       = { for k, v in digitalocean_spaces_key.this : k => v.secret_key }
-  sensitive   = true
-  description = "Secret keys by key name. Sensitive. They are also in OpenTofu state; store them in Doppler and do not print them."
-}

+ 5 - 5
modules/spaces-bucket/tests/spaces-bucket.tftest.hcl

@@ -176,20 +176,20 @@ run "keys_cannot_be_fullaccess_or_empty_grant" {
   }
 }
 
-run "secret_outputs_are_sensitive" {
+run "key_ids_are_sensitive_and_no_output_carries_a_secret_key" {
   command = plan
   variables {
     create_access_keys = true
     access_key_names   = ["penguin-overlord"]
   }
-  assert {
-    condition     = issensitive(output.secret_keys)
-    error_message = "secret_keys must be marked sensitive."
-  }
   assert {
     condition     = issensitive(output.access_keys)
     error_message = "access_keys must be marked sensitive."
   }
+  assert {
+    condition     = length(regexall("secret_key", file("${path.module}/outputs.tf"))) == 0
+    error_message = "The module must not output a secret key: outputs.tf names no secret_key."
+  }
 }
 
 run "rejects_duplicate_key_names" {

+ 51 - 2
scripts/cost_check.py

@@ -1640,17 +1640,66 @@ def droplet_backup_problems(rel, block):
     return found
 
 
+HCL_WORD_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_-]*")
+# A provisioner block header after the word: an optional label, then the brace.
+# HCL needs no whitespace between a keyword and a quoted label, between two quoted
+# labels, or before the brace; whitespace is required only before a bare label.
+_WS = r"[ \t\r]*"
+_WS1 = r"[ \t\r]+"
+_QUOTED = r'"[^"\n]*"'
+_BARE = r"[A-Za-z_][A-Za-z0-9_-]*"
+PROVISIONER_TAIL_RE = re.compile(rf"(?:{_WS}{_QUOTED}|{_WS1}{_BARE})?{_WS}\{{")
+# `data "external" "name" {` after the word `data`, in any legal spacing. The first
+# label may be quoted (a backslash in it could spell "external" as an escape, so any
+# escaped first label is treated as external) or bare.
+_EXTERNAL_LABEL = rf'(?:{_WS}"(?:external|[^"\n]*\\[^"\n]*)"|{_WS1}external(?![A-Za-z0-9_-]))'
+# The second label is optional here: a malformed header is refused too (fail closed).
+EXTERNAL_DATA_TAIL_RE = re.compile(rf"{_EXTERNAL_LABEL}(?:{_WS}{_QUOTED}|{_WS}{_BARE})?{_WS}\{{")
+
+
+def run_hook_problems(rel, text):
+    """Provisioner blocks (local-exec, remote-exec, file) and external data
+    sources, wherever they sit. They run commands at apply or plan time, which
+    the gate can neither read nor cost, so each one fails the gate. Quoted
+    strings are skipped and comments and heredocs are already stripped, so the
+    words only count where the configuration is code."""
+    found, i, n = [], 0, len(text)
+    while i < n:
+        if text[i] == '"':
+            i = skip_string(text, i)
+            continue
+        word = HCL_WORD_RE.match(text, i)
+        if not word:
+            i += 1
+            continue
+        line = text.count("\n", 0, i) + 1
+        if word.group(0) == "provisioner" and PROVISIONER_TAIL_RE.match(text, word.end()):
+            found.append(
+                f"{rel}:{line}: a provisioner block runs commands at apply time and is "
+                "refused; the gate cannot read or cost what it does"
+            )
+        elif word.group(0) == "data" and EXTERNAL_DATA_TAIL_RE.match(text, word.end()):
+            found.append(
+                f"{rel}:{line}: an external data source runs a program at plan time and "
+                "is refused; the gate cannot read or cost what it does"
+            )
+        i = word.end()
+    return found
+
+
 def block_problems(root):
     """Everything wrong with how the files themselves read: unreadable HCL,
-    escapes in labels, headers the scanner does not understand, and count or
+    escapes in labels, headers the scanner does not understand, count or
     for_each on a costed resource (the manifest cannot be reconciled with it
-    without a plan)."""
+    without a plan), and provisioners or external data sources anywhere."""
     problems = []
     costed = set().union(*COSTED_TYPES.values())
     for rel, text, error in hcl_files(root):
         if error:
             problems.append(f"{rel}: unreadable HCL, refused: {error}")
             continue
+        if not lab_file(root, rel):
+            problems += run_hook_problems(rel, text)
         try:
             blocks = find_blocks(text)
         except HclError as err:

+ 19 - 3
stacks/30-workloads/tests/workloads.tftest.hcl

@@ -201,8 +201,16 @@ run "twingate_gets_one_resource_per_port_and_nothing_else" {
     error_message = "Both resources live in the given remote network."
   }
   assert {
-    condition     = length(regexall("\"twingate_resource\"", file("${path.module}/main.tf"))) == 2
-    error_message = "Exactly two Twingate resources: no Docker API resource, ever."
+    condition     = length(regexall("\"twingate_resource\"", file("${path.module}/main.tf"))) + length(regexall("\"twingate_resource\"", file("${path.module}/workload_web.tf"))) + length(regexall("\"twingate_resource\"", file("${path.module}/outputs.tf"))) + length(regexall("\"twingate_resource\"", file("${path.module}/variables.tf"))) == 3
+    error_message = "Exactly three Twingate resource blocks across the stack's files (ssh and Portainer in main.tf, the for_each web resource in workload_web.tf): no Docker API resource, ever."
+  }
+  assert {
+    condition     = length(setintersection(twingate_resource.ssh[0].protocols.tcp.ports, toset(["2375", "2376"]))) == 0 && length(setintersection(twingate_resource.portainer[0].protocols.tcp.ports, toset(["2375", "2376"]))) == 0
+    error_message = "No planned Twingate resource may allow the Docker API ports 2375 or 2376."
+  }
+  assert {
+    condition     = length(regexall("(?i)2375|2376|ALLOW_ALL|[01]\\s*-\\s*65535", file("${path.module}/main.tf"))) + length(regexall("(?i)2375|2376|ALLOW_ALL|[01]\\s*-\\s*65535", file("${path.module}/workload_web.tf"))) == 0
+    error_message = "No rule in the stack may allow the Docker API ports or every port."
   }
 }
 
@@ -288,6 +296,14 @@ run "a_floating_portainer_version_is_refused" {
   expect_failures = [var.portainer_version]
 }
 
+run "a_portainer_tag_without_a_digest_is_refused" {
+  command = plan
+  variables {
+    portainer_version = "2.45.3"
+  }
+  expect_failures = [var.portainer_version]
+}
+
 # --- the optional onion service flag (issue #391; default off, nothing applied) --
 
 run "the_onion_flag_defaults_to_off_and_the_effective_output_is_false" {
@@ -341,7 +357,7 @@ run "the_onion_flag_with_the_master_switch_changes_no_firewall_rule" {
     error_message = "The onion flag must not add, remove or widen any firewall rule."
   }
   assert {
-    condition     = length(regexall("\"twingate_resource\"", file("${path.module}/main.tf"))) == 2
+    condition     = length(regexall("\"twingate_resource\"", file("${path.module}/main.tf"))) + length(regexall("\"twingate_resource\"", file("${path.module}/workload_web.tf"))) == 3
     error_message = "The onion flag adds no Twingate resource."
   }
 }

+ 4 - 4
stacks/30-workloads/variables.tf

@@ -132,12 +132,12 @@ variable "timezone" {
 
 variable "portainer_version" {
   type        = string
-  default     = "2.45.3"
-  description = "Exact Portainer CE image tag, an LTS release from Portainer's releases page (read 2026-10-31). Bumped in a reviewed change, which replaces the droplet."
+  default     = "2.45.3@sha256:3609c307943bca8e5c492f69ddd6965df177208b50678a4cff28391c8dd4e96e"
+  description = "Portainer CE image reference after portainer/portainer-ce:, pinned by exact tag and by digest (2.45.3, an LTS release from Portainer's releases page read 2026-10-31; the multi-arch index digest read from Docker Hub on 2026-11-02). Bumped in a reviewed change, which replaces the droplet."
 
   validation {
-    condition     = can(regex("^[0-9]+\\.[0-9]+\\.[0-9]+$", var.portainer_version))
-    error_message = "portainer_version must be an exact version such as 2.45.3, never latest, a range or a variant."
+    condition     = can(regex("^[0-9]+\\.[0-9]+\\.[0-9]+@sha256:[0-9a-f]{64}$", var.portainer_version))
+    error_message = "portainer_version must be <exact version>@sha256:<64 hex digits> such as 2.45.3@sha256:..., pinned by tag and by digest, never latest, a range or a variant."
   }
 }
 

+ 28 - 0
tests/onion_lab_fixtures.py

@@ -49,6 +49,34 @@ class Clean(http.server.BaseHTTPRequestHandler):
         pass
 
 
+class Redirecting(http.server.BaseHTTPRequestHandler):
+    """A clean front page, a redirect with an absolute Location on one probe path and a 200 on another."""
+
+    server_version = "nginx"
+    sys_version = ""
+
+    def do_GET(self):
+        headers = []
+        if self.path == "/":
+            body, code = b"<p>plain</p>", 200
+        elif self.path == "/.env":
+            body, code = b"", 301
+            headers.append(("Location", "http://example.test:8080/.env/"))
+        elif self.path == "/status":
+            body, code = b"ok", 200
+        else:
+            body, code = b"Not found.", 404
+        self.send_response(code)
+        for name, value in headers:
+            self.send_header(name, value)
+        self.send_header("Content-Length", str(len(body)))
+        self.end_headers()
+        self.wfile.write(body)
+
+    def log_message(self, *args):
+        pass
+
+
 @contextlib.contextmanager
 def serving(handler):
     """Yield the port of a loopback server running `handler`; shut it down on exit."""

+ 183 - 0
tests/test_cost_check_provisioners.py

@@ -0,0 +1,183 @@
+# SPDX-License-Identifier: Apache-2.0
+"""The cost gate refuses provisioner blocks and external data sources.
+
+A provisioner (local-exec, remote-exec, file) runs commands at apply time and
+an external data source runs a program at plan time. The gate cannot cost or
+read either, so the source scan fails on them whatever resource type holds them.
+"""
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
+import cost_check
+from test_cost_check import droplet, make_repo
+
+OK_DROPLET = {"modules/ok/main.tf": 'resource "digitalocean_droplet" "a" {}\n'}
+
+
+def problems_for(tmp_path, files):
+    root = make_repo(tmp_path, [droplet()], tf_files={**OK_DROPLET, **files})
+    approved = json.loads((root / "docs/stages/approved.json").read_text())
+    problems, _ = cost_check.gate_problems(root, approved)
+    return problems
+
+
+def provisioner_problems(problems):
+    return [p for p in problems if "provisioner" in p or "external data" in p]
+
+
+NULL_LOCAL_EXEC = (
+    'resource "null_resource" "x" {\n'
+    '  provisioner "local-exec" {\n    command = "true"\n  }\n}\n'
+)
+
+
+def test_a_null_resource_with_a_local_exec_provisioner_is_refused(tmp_path):
+    problems = problems_for(tmp_path, {"stacks/10-access/x.tf": NULL_LOCAL_EXEC})
+    found = provisioner_problems(problems)
+    assert found and "stacks/10-access/x.tf:2" in found[0]
+
+
+def test_the_same_file_without_the_provisioner_is_clean(tmp_path):
+    clean = 'resource "null_resource" "x" {\n  triggers = {}\n}\n'
+    assert problems_for(tmp_path, {"stacks/10-access/x.tf": clean}) == []
+
+
+@pytest.mark.parametrize(
+    "text",
+    [
+        'resource "null_resource" "x" {\n  provisioner "remote-exec" {\n    inline = []\n  }\n}\n',
+        'resource "terraform_data" "x" {\n  provisioner "file" {\n    source = "a"\n  }\n}\n',
+        'resource "null_resource" "x" { provisioner "local-exec" { command = "true" } }\n',
+        'resource "null_resource" "x" {\n  provisioner local-exec {\n  }\n}\n',
+        'resource "digitalocean_tag" "x" {\n  provisioner "local-exec" {\n  }\n}\n',
+        'resource "null_resource" "x" {\n  provisioner "local-exec" {\n  when = destroy\n  }\n}\n',
+    ],
+)
+def test_every_provisioner_form_is_refused(tmp_path, text):
+    problems = problems_for(tmp_path, {"stacks/10-access/x.tf": text})
+    assert provisioner_problems(problems)
+
+
+def test_a_provisioner_in_a_module_directory_is_refused(tmp_path):
+    problems = problems_for(tmp_path, {"modules/other/main.tf": NULL_LOCAL_EXEC})
+    assert provisioner_problems(problems)
+
+
+def test_a_provisioner_in_a_tofu_file_is_refused(tmp_path):
+    problems = problems_for(tmp_path, {"stacks/10-access/x.tofu": NULL_LOCAL_EXEC})
+    assert provisioner_problems(problems)
+
+
+@pytest.mark.parametrize(
+    "text",
+    [
+        'data "external" "x" {\n  program = ["true"]\n}\n',
+        'data external x {\n  program = ["true"]\n}\n',
+        'data "external" "x" { program = ["true"] }\n',
+    ],
+)
+def test_an_external_data_source_is_refused(tmp_path, text):
+    problems = problems_for(tmp_path, {"stacks/10-access/x.tf": text})
+    found = provisioner_problems(problems)
+    assert found and "external data source" in found[0]
+
+
+def test_other_data_sources_are_not_flagged(tmp_path):
+    text = 'data "digitalocean_image" "x" {\n  slug = "a"\n}\n'
+    assert provisioner_problems(problems_for(tmp_path, {"stacks/10-access/x.tf": text})) == []
+
+
+@pytest.mark.parametrize(
+    "text",
+    [
+        '# provisioner "local-exec" {\n',
+        '/* provisioner "local-exec" {\n} */\n',
+        'locals {\n  note = "provisioner \\"local-exec\\" { }"\n}\n',
+        'locals {\n  note = "data external x {"\n}\n',
+        'locals {\n  provisioner = "x"\n  data = "external"\n}\n',
+        'locals {\n  doc = <<EOT\nprovisioner "local-exec" {\nEOT\n}\n',
+    ],
+)
+def test_the_words_in_comments_strings_and_attributes_are_not_flagged(tmp_path, text):
+    assert provisioner_problems(problems_for(tmp_path, {"stacks/10-access/x.tf": text})) == []
+
+
+@pytest.mark.parametrize(
+    "text",
+    [
+        'resource "null_resource" "x" {\n  provisioner"local-exec"{\n  }\n}\n',
+        'resource "null_resource" "x" {\n  provisioner"local-exec" {\n  }\n}\n',
+        'resource "null_resource" "x" {\n  provisioner "local-exec"{\n  }\n}\n',
+        'resource "null_resource" "x" {\n  provisioner\t"local-exec"\t{\n  }\n}\n',
+        'resource "null_resource" "x" {\n  provisioner  \t "local-exec"   {\n  }\n}\n',
+        'resource "null_resource" "x" {\n  provisioner{\n  }\n}\n',
+        'resource "null_resource" "x" {provisioner"file"{}}\n',
+        'resource "null_resource" "x" {\r\n  provisioner "local-exec" {\r\n  }\r\n}\r\n',
+        'resource "null_resource" "x" {\n  /* c */ provisioner "local-exec" {\n  }\n}\n',
+        'resource "null_resource" "x" {\n  provisioner "local-exec" { # c\n  }\n}\n',
+        'resource "null_resource" "x" {\n  provisioner /* c */ "local-exec" {\n  }\n}\n',
+    ],
+)
+def test_odd_spacing_does_not_hide_a_provisioner(tmp_path, text):
+    assert provisioner_problems(problems_for(tmp_path, {"stacks/10-access/x.tf": text}))
+
+
+@pytest.mark.parametrize(
+    "text",
+    [
+        'data"external""x"{\n}\n',
+        'data"external" "x"{\n}\n',
+        'data "external""x" {\n}\n',
+        'data\t"external"\t"x"\t{\n}\n',
+        'data "external"{\n}\n',
+        'data external{\n}\n',
+        'data external"x"{\n}\n',
+        'data"external"x{\n}\n',
+        'data "ext\\u0065rnal" "x" {\n}\n',
+        'data /* c */ "external" "x" {\n}\n',
+    ],
+)
+def test_odd_spacing_does_not_hide_an_external_data_source(tmp_path, text):
+    found = provisioner_problems(problems_for(tmp_path, {"stacks/10-access/x.tf": text}))
+    assert found and "external data source" in found[0]
+
+
+@pytest.mark.parametrize(
+    "name", ["stacks/10-access/x.tf.json", "stacks/10-access/x.tofu.json", "modules/other/x.tf.json", "labs/vm/x.tf.json"]
+)
+def test_json_configuration_files_are_refused_outright(tmp_path, name):
+    body = '{"resource": {"null_resource": {"x": {"provisioner": [{"local-exec": {"command": "true"}}]}}}}'
+    problems = problems_for(tmp_path, {name: body})
+    assert any(name in p and "is refused" in p for p in problems), problems
+
+
+def test_a_provisioner_in_a_tofu_override_file_is_refused(tmp_path):
+    problems = problems_for(tmp_path, {"stacks/10-access/x_override.tofu": NULL_LOCAL_EXEC})
+    assert provisioner_problems(problems)
+
+
+@pytest.mark.parametrize(
+    "text",
+    [
+        'locals {\n  doc = <<-EOT\n    provisioner"local-exec"{\n    data"external""x"{\n  EOT\n}\n',
+        '// provisioner"local-exec"{\n',
+        '# data"external""x"{\n',
+        'locals {\n  s = "provisioner\\"local-exec\\"{"\n}\n',
+        'locals {\n  s = "${provisioner}"\n}\n',
+        'locals {\n  provisioner = {}\n  external = 1\n}\n',
+        'data "digitalocean_image" "external" {\n  slug = "a"\n}\n',
+        'data "http" "external" {\n}\n',
+    ],
+)
+def test_odd_spacing_in_strings_comments_heredocs_and_other_words_is_not_flagged(tmp_path, text):
+    assert provisioner_problems(problems_for(tmp_path, {"stacks/10-access/x.tf": text})) == []
+
+
+def test_labs_are_exempt_like_the_other_cost_rules(tmp_path):
+    problems = problems_for(tmp_path, {"labs/vm/main.tf": NULL_LOCAL_EXEC})
+    assert provisioner_problems(problems) == []

+ 40 - 2
tests/test_onion_lab_files.py

@@ -17,7 +17,7 @@ import re
 import sys
 from pathlib import Path
 
-from onion_lab_fixtures import Clean, Leaky, serving
+from onion_lab_fixtures import Clean, Leaky, Redirecting, serving
 
 ROOT = Path(__file__).resolve().parent.parent
 LAB = ROOT / "labs" / "onion-lab"
@@ -332,13 +332,51 @@ def test_the_body_check_flags_clearnet_resources_and_names_links_for_review():
     assert c.outbound_links('<a href="https://example.test/">out</a><a href="/in">in</a>') == ["https://example.test/"]
 
 
-def test_the_status_page_check_flags_a_200_and_nothing_else():
+def test_a_bare_server_name_is_listed_for_review_and_a_version_is_a_failure():
+    c = load_checker()
+    assert c.server_review([("Server", "nginx"), ("Content-Type", "text/html")]) == ["header Server names the software: nginx"]
+    assert c.server_review([("server", " Caddy ")]) == ["header Server names the software: Caddy"]
+    assert c.server_review([("Content-Type", "text/html"), ("Server", "")]) == []
+    assert c.server_review([("Content-Type", "text/html")]) == []
+    # A version or an operating system is already a failure in header_problems, so it is not listed twice.
+    assert c.server_review([("Server", "nginx/1.30.6")]) == []
+    assert c.server_review([("Server", "Apache (Ubuntu)")]) == []
+    assert c.header_problems([("Server", "nginx/1.30.6")])
+
+
+def test_the_status_page_check_flags_a_2xx_or_3xx_and_nothing_else():
     c = load_checker()
     assert c.exposed_paths({"/server-status": 404, "/.git/HEAD": 404, "/": 200}) == []
     assert c.exposed_paths({"/server-status": 200, "/.env": 200, "/nginx_status": 403}) == ["/.env", "/server-status"]
+    assert c.exposed_paths({"/.env": 301, "/status": 302, "/stub_status": 204, "/phpinfo.php": 500, "/server-info": 401}) == ["/.env", "/status", "/stub_status"]
+    assert c.exposed_paths({"/.env": 399, "/status": 400, "/server-info": 199}) == ["/.env"]
     assert "/server-status" in c.PROBE_PATHS and "/stub_status" in c.PROBE_PATHS and "/.git/HEAD" in c.PROBE_PATHS
 
 
+def test_the_audit_lists_the_server_name_for_review_without_failing(tmp_path, capsys):
+    c = load_checker()
+    ss = tmp_path / "ss.txt"
+    with serving(Clean) as port:
+        ss.write_text(LOOPBACK_ONLY.format(port=port))
+        assert c.main(["--port", str(port), "--ss-file", str(ss)]) == 0
+    out = capsys.readouterr().out
+    assert out.count("[REVIEW] header Server names the software: nginx") == 1, "once, not once per request"
+    assert "0 problems" in out
+
+
+def test_the_audit_inspects_the_headers_and_status_of_the_probe_responses(tmp_path, capsys):
+    c = load_checker()
+    ss = tmp_path / "ss.txt"
+    with serving(Redirecting) as port:
+        ss.write_text(LOOPBACK_ONLY.format(port=port))
+        assert c.main(["--port", str(port), "--ss-file", str(ss)]) == 1
+    out = capsys.readouterr().out
+    assert "[FAIL] the path /.env answers 301" in out
+    assert "[FAIL] header Location is an absolute address" in out and "/.env/" in out
+    assert "[FAIL] the path /status answers 200" in out
+    assert "2 problems" not in out and "3 problems" in out
+
+
 LOOPBACK_ONLY = "LISTEN 0 511 127.0.0.1:{port} 0.0.0.0:*\n"
 
 

+ 89 - 3
tests/test_searxng_workload.py

@@ -7,6 +7,7 @@ public instance flag would each make a private search proxy into something else,
 """
 
 import re
+import subprocess
 import tomllib
 from pathlib import Path
 
@@ -139,18 +140,103 @@ def test_the_workload_files_exist():
         assert p.is_file(), p
 
 
-def test_the_compose_file_parses_and_has_the_two_services():
+def test_the_compose_file_parses_and_has_the_services():
     compose = load()
-    assert set(compose["services"]) == {"core", "valkey"}
+    assert set(compose["services"]) == {"core", "valkey", "bind-check"}
     assert compose["networks"]["backend"]["internal"] is True
 
 
 def test_every_image_is_pinned_by_tag_and_digest():
     refs = images(load())
-    assert len(refs) == 2, "the guard collected too little"
+    assert len(refs) == 3, "the guard collected too little"
     assert not unpinned(load()), unpinned(load())
 
 
+# ---- the bind check: a pre-start step that refuses an address that is not private ------------------------------
+
+
+def bind_check_script(compose: dict) -> str:
+    """The shell text the bind-check service runs, as the shell sees it ($$ is compose's escape for $)."""
+    entry = compose["services"]["bind-check"]["entrypoint"]
+    assert entry[:2] == ["/bin/sh", "-c"] and len(entry) == 3, entry
+    return entry[2].replace("$$", "$")
+
+
+def run_bind_check(script: str, value: str) -> int:
+    done = subprocess.run(["/bin/sh", "-c", script], check=False, env={"SEARXNG_BIND": value, "PATH": "/usr/bin:/bin"}, capture_output=True, text=True, timeout=10)
+    return done.returncode
+
+
+def bind_check_wiring_problems(compose: dict) -> list[str]:
+    bad = []
+    svc = compose["services"].get("bind-check")
+    if svc is None:
+        return ["no bind-check service"]
+    if "restart" not in svc or str(svc["restart"]).strip('"') != "no":
+        bad.append("bind-check restarts")
+    if not REQUIRED_VAR.match(str(svc.get("environment", {}).get("SEARXNG_BIND", ""))):
+        bad.append("bind-check does not require SEARXNG_BIND")
+    if svc.get("ports"):
+        bad.append("bind-check publishes ports")
+    deps = compose["services"]["core"].get("depends_on", {})
+    if not isinstance(deps, dict) or deps.get("bind-check", {}).get("condition") != "service_completed_successfully":
+        bad.append("core does not wait for bind-check to complete successfully")
+    return bad
+
+
+PRIVATE_BINDS = ("10.116.0.5", "10.0.0.1", "192.168.1.20", "172.16.0.2", "172.31.255.1", "127.0.0.1")
+REFUSED_BINDS = (
+    "0.0.0.0",
+    "::",
+    "[::]",
+    "",
+    "8.8.8.8",
+    "172.15.0.1",
+    "172.32.0.1",
+    "192.169.0.1",
+    "100.64.0.1",
+    "10.0.0.1:9999",
+    "10.0.0.1 ",
+    "10.0.0.1,0.0.0.0",
+    "10.example.com",
+    "localhost",
+)
+
+
+def test_the_bind_check_accepts_private_addresses_and_refuses_the_rest():
+    script = bind_check_script(load())
+    for value in PRIVATE_BINDS:
+        assert run_bind_check(script, value) == 0, value
+    for value in REFUSED_BINDS:
+        assert run_bind_check(script, value) != 0, repr(value)
+
+
+def test_the_bind_check_blocks_core_and_publishes_nothing():
+    assert bind_check_wiring_problems(load()) == []
+
+
+def test_the_bind_check_guard_bites():
+    compose = load()
+    script = bind_check_script(compose)
+    # A check that accepts everything, or one that lets a wildcard through, fails the refused list.
+    assert run_bind_check("exit 0", "0.0.0.0") == 0
+    loose = script.replace("10.*", "*", 1)
+    assert loose != script and run_bind_check(loose, "0.0.0.0") == 0
+    # The wiring guard sees each way of letting core start without the check.
+    for mutate in (
+        lambda c: c["services"]["core"].update(depends_on={"valkey": {"condition": "service_started"}}),
+        lambda c: c["services"]["core"].update(depends_on=["valkey", "bind-check"]),
+        lambda c: c["services"]["core"]["depends_on"]["bind-check"].update(condition="service_started"),
+        lambda c: c["services"]["bind-check"].update(restart="unless-stopped"),
+        lambda c: c["services"]["bind-check"]["environment"].update(SEARXNG_BIND="10.0.0.1"),
+        lambda c: c["services"]["bind-check"].update(ports=["10.0.0.1:1:1"]),
+        lambda c: c["services"].pop("bind-check"),
+    ):
+        bad = yaml.safe_load(yaml.safe_dump(compose))
+        mutate(bad)
+        assert bind_check_wiring_problems(bad), mutate
+
+
 def test_the_pins_guard_bites():
     good = {"services": {"a": {"image": "docker.io/x/y:1.2.3@sha256:" + "a" * 64}}}
     assert not unpinned(good)

+ 90 - 11
tests/test_workloads_stack.py

@@ -167,17 +167,66 @@ def test_the_firewall_check_bites():
         assert firewall_problems(bad), "a widened firewall was not noticed"
 
 
-def test_exactly_two_twingate_resources_and_never_a_docker_api_one():
-    main = strip_comments(read(STACK / "main.tf"))
-    found = blocks(main, "resource")
-    twingate = [labels for labels, _ in found if labels[0] == "twingate_resource"]
-    assert sorted(twingate) == [["twingate_resource", "portainer"], ["twingate_resource", "ssh"]]
-    assert "2375" not in main and "2376" not in main
-    for labels, body in found:
-        if labels[0] == "twingate_resource":
-            assert re.search(r'policy\s*=\s*"RESTRICTED"', body)
-            assert re.search(r'udp\s*=\s*\{\s*policy\s*=\s*"DENY_ALL"', body)
-            assert re.search(r"allow_icmp\s*=\s*false", body)
+EXPECTED_TWINGATE = [
+    ["twingate_resource", "portainer"],
+    ["twingate_resource", "ssh"],
+    ["twingate_resource", "workload_web"],
+]
+# A rule that opens the Docker API ports or every port.
+OPEN_PORT_RE = re.compile(r'2375|2376|ALLOW_ALL|\b[01]\s*-\s*65535|"all"|"\*"', re.IGNORECASE)
+
+
+def stack_texts():
+    """{file name: comment-free text} of every .tf file in the stack directory."""
+    return {
+        path.name: strip_comments(read(path))
+        for path in sorted(STACK.glob("*.tf"))
+        if ".terraform" not in path.parts
+    }
+
+
+def twingate_problems(texts):
+    """Every Twingate resource of every file: the set must be the expected one,
+    each narrow (TCP restricted, UDP denied, no ICMP), and no file may name the
+    Docker API ports or an all-ports rule."""
+    problems = []
+    found = []
+    for name, text in texts.items():
+        for labels, body in blocks(text, "resource"):
+            if labels[0] == "twingate_resource":
+                found.append(labels)
+                for needle in (r'policy\s*=\s*"RESTRICTED"', r'udp\s*=\s*\{\s*policy\s*=\s*"DENY_ALL"', r"allow_icmp\s*=\s*false"):
+                    if not re.search(needle, body):
+                        problems.append(f"{name}: {labels[1]} lacks {needle}")
+        if OPEN_PORT_RE.search(text):
+            problems.append(f"{name}: names a Docker API port or an all-ports rule")
+    if sorted(found) != EXPECTED_TWINGATE:
+        problems.append(f"Twingate resources are {sorted(found)}, expected {EXPECTED_TWINGATE}")
+    return problems
+
+
+def test_the_twingate_resources_of_every_file_are_the_expected_narrow_three():
+    texts = stack_texts()
+    assert {"main.tf", "workload_web.tf", "variables.tf", "outputs.tf"} <= set(texts), "the scan lost its files"
+    assert twingate_problems(texts) == []
+
+
+def test_the_twingate_check_sees_a_resource_in_any_file_and_open_ports():
+    texts = stack_texts()
+    extra = 'resource "twingate_resource" "extra" {\n  protocols = {}\n}\n'
+    assert twingate_problems({**texts, "another.tf": extra})
+    assert twingate_problems({**texts, "main.tf": texts["main.tf"] + extra})
+    web = texts["workload_web.tf"]
+    for bad in (
+        web.replace('policy = "RESTRICTED"', 'policy = "ALLOW_ALL"', 1),
+        web.replace("ports  = [each.key]", 'ports  = ["2375"]', 1),
+        web.replace("ports  = [each.key]", 'ports  = ["2376"]', 1),
+        web.replace("ports  = [each.key]", 'ports  = ["1-65535"]', 1),
+        web.replace("ports  = [each.key]", 'ports  = ["0-65535"]', 1),
+        web.replace("allow_icmp = false", "allow_icmp = true", 1),
+    ):
+        assert twingate_problems({**texts, "workload_web.tf": bad}), bad[-200:]
+    assert twingate_problems({k: v for k, v in texts.items() if k != "workload_web.tf"})
 
 
 def test_the_stack_has_no_wildcard_anywhere():
@@ -212,6 +261,36 @@ def test_the_module_pins_portainer_and_never_pipes_an_installer():
     assert "cah-apt-key-check /root/docker.gpg.key" in template
 
 
+PINNED_PORTAINER_RE = re.compile(r"^[0-9]+\.[0-9]+\.[0-9]+@sha256:[0-9a-f]{64}$")
+
+
+def portainer_pin_problems(variables):
+    """The portainer_version default and validation must both demand tag plus digest."""
+    found = [b for b in blocks(strip_comments(variables), "variable") if b[0] == ["portainer_version"]]
+    if len(found) != 1:
+        return ["portainer_version variable missing"]
+    body = found[0][1]
+    problems = []
+    default = re.search(r'(?m)^\s*default\s*=\s*"([^"]*)"\s*$', body)
+    if not default or not PINNED_PORTAINER_RE.match(default.group(1)):
+        problems.append("the default is not <version>@sha256:<64 hex>")
+    if "@sha256:[0-9a-f]{64}$" not in body:
+        problems.append("the validation does not demand a digest")
+    return problems
+
+
+def test_portainer_is_pinned_by_tag_and_digest_in_the_module_and_the_stack():
+    for path in (MODULE / "variables.tf", STACK / "variables.tf"):
+        assert portainer_pin_problems(read(path)) == [], path.as_posix()
+
+
+def test_the_portainer_pin_check_bites():
+    good = read(MODULE / "variables.tf")
+    tag_only = good.replace("@sha256:3609c307943bca8e5c492f69ddd6965df177208b50678a4cff28391c8dd4e96e", "", 1)
+    assert portainer_pin_problems(tag_only)
+    assert portainer_pin_problems(good.replace("@sha256:[0-9a-f]{64}$", "$", 1))
+
+
 def test_the_module_droplet_leaves_backups_off_and_has_no_public_v6():
     main = strip_comments(read(MODULE / "main.tf"))
     ((_, body),) = blocks(main, "resource")

+ 3 - 3
workloads/searxng/README.md

@@ -8,7 +8,7 @@ SearXNG is a metasearch engine: it sends your query to many search engines and r
 
 | File | What it is |
 |---|---|
-| `docker-compose.yml` | Two services: `core` (SearXNG) and `valkey` (the cache the limiter needs) |
+| `docker-compose.yml` | Three services: `core` (SearXNG), `valkey` (the cache the limiter needs) and `bind-check` (runs once before `core` and exits with an error unless `SEARXNG_BIND` is a private IPv4 address, so `core` does not start) |
 | `settings.yml` | SearXNG settings: limiter on, not a public instance, HTML output only, secret key a placeholder |
 | `limiter.toml` | Bot detection settings that differ from the defaults |
 | `env.example` | The names of the stack variables, no values |
@@ -57,6 +57,6 @@ There is almost nothing to back up. The configuration is in git. The secret is i
 
 Read on 2026-11-01: SearXNG's container installation page, its server, valkey and outgoing settings pages, the limiter page, the bot detection page, the architecture page, the "Why use a private instance?" page, the upstream compose template, `.env.example`, `settings.yml` and `limiter.toml`; Docker's port publishing and packet filtering pages; the registry digests above.
 
-Checked offline by `tests/test_searxng_workload.py`: the compose file parses; both images are pinned by tag and digest; the one published port is bound by a required variable and no wildcard bind appears; the cache publishes nothing and sits on an internal network; no secret value is in any file; the limiter is on and the instance is not public in the file and in the environment; the Tor option is off.
+Checked offline by `tests/test_searxng_workload.py`: the compose file parses; both images are pinned by tag and digest; the one published port is bound by a required variable and no wildcard bind appears; the `bind-check` script, run in a local shell, accepts private addresses and refuses a wildcard or public one, and `core` waits for it to finish successfully; the cache publishes nothing and sits on an internal network; no secret value is in any file; the limiter is on and the instance is not public in the file and in the environment; the Tor option is off.
 
-**Not verified:** that Portainer accepts the file or that a container engine starts it (no Docker Engine was run; the checks were a YAML parse and `docker-compose config` 2.26.1, which rendered the file with the variables set and stopped with an error naming `SEARXNG_BIND` when it was unset, a syntax and interpolation check only); that the images start with these settings; that SearXNG honors `use_default_settings` with this file and the environment overrides as the docs describe; that the container starts with `no-new-privileges` and a read-write config mount; that the limiter works when every user reaches the instance from the Twingate connector's address (the limiter counts requests per client address, so all users may look like one client, est.); what memory it uses; that the Twingate and firewall path exists; that the Valkey instance needs no password on an internal network (it is unreachable from outside the compose network by construction, not tested).
+**Not verified:** that the `bind-check` container runs as written (its script was tested in a local shell only, and the cache image's shell was not run); that Portainer accepts the file or that a container engine starts it (no Docker Engine was run; the checks were a YAML parse and `docker-compose config` 2.26.1, which rendered the file with the variables set and stopped with an error naming `SEARXNG_BIND` when it was unset, a syntax and interpolation check only); that the images start with these settings; that SearXNG honors `use_default_settings` with this file and the environment overrides as the docs describe; that the container starts with `no-new-privileges` and a read-write config mount; that the limiter works when every user reaches the instance from the Twingate connector's address (the limiter counts requests per client address, so all users may look like one client, est.); what memory it uses; that the Twingate and firewall path exists; that the Valkey instance needs no password on an internal network (it is unreachable from outside the compose network by construction, not tested).

+ 26 - 1
workloads/searxng/docker-compose.yml

@@ -19,7 +19,10 @@ services:
     image: docker.io/searxng/searxng:2026.11.1-8b35dcd2e@sha256:4b106e61eeb9e216ac96c85591338c1e9ceb5a84c26f72cd18b8ba8f0f52093c
     restart: unless-stopped
     depends_on:
-      - valkey
+      valkey:
+        condition: service_started
+      bind-check:
+        condition: service_completed_successfully
     ports:
       - "${SEARXNG_BIND:?set SEARXNG_BIND to the host private address}:8080:8080"
     environment:
@@ -39,6 +42,28 @@ services:
       - frontend
       - backend
 
+  # Runs once before core and exits. It refuses a SEARXNG_BIND that is not a private IPv4 address (10/8, 172.16/12,
+  # 192.168/16, or 127/8 for a laptop), so core, which waits for it, never publishes its port on a wildcard or a public
+  # address. It uses the cache image, which already has a shell, and it publishes nothing.
+  bind-check:
+    container_name: searxng-bind-check
+    image: docker.io/valkey/valkey:9.1.3-alpine@sha256:bf09d58e96d6b4524a15396b65b242bbe18beebbcc15a04d8ee75ddac62fae0b
+    entrypoint:
+      - /bin/sh
+      - -c
+      - 'case "$$SEARXNG_BIND" in *[!0-9.]*|"") echo "SEARXNG_BIND must be a private IPv4 address" >&2; exit 1;; 10.*|127.*|192.168.*|172.1[6-9].*|172.2[0-9].*|172.3[01].*) exit 0;; *) echo "SEARXNG_BIND must be a private IPv4 address" >&2; exit 1;; esac'
+    environment:
+      SEARXNG_BIND: ${SEARXNG_BIND:?set SEARXNG_BIND to the host private address}
+    restart: "no"
+    mem_limit: 16m
+    read_only: true
+    security_opt:
+      - no-new-privileges:true
+    cap_drop:
+      - ALL
+    networks:
+      - backend
+
   valkey:
     container_name: searxng-valkey
     image: docker.io/valkey/valkey:9.1.3-alpine@sha256:bf09d58e96d6b4524a15396b65b242bbe18beebbcc15a04d8ee75ddac62fae0b