From c4d0283300f4f672a59faf0e3a684c4674ce1fdc Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 28 Oct 2026 20:56:40 +0100 Subject: [PATCH 01/31] feat(mail): publish a DMARC aggregate report address (rua) Both mail providers published "v=DMARC1; p=reject; ruf=...; adkim=s; aspf=s" without a rua tag, so the domain owner received no aggregate reports and could not see who sends in the domain's name or whether legitimate mail fails alignment. services..dmarc.rua_user in web-app-stalwart and web-app-mailu now names the users-catalogue key whose mailbox receives the aggregate reports. It is set to administrator, the one user every deployment provisions with a mailbox (user-administrator), and an inventory may name another key. The address is built as @, which is the exact account or alias the provider creates, so the record never points at an address the server does not serve. An assert in the DNS task fails the deploy before any record is written when the user carries no mailbox account (Stalwart), or neither a mailbox account nor a forward alias (Mailu), so reports cannot bounce. Mailu's DMARC_RUA env, which only feeds the record its admin UI suggests, now carries the same local part instead of the unprovisioned "admin". production_facts.py takes a required --dmarc-rua. check_dmarc parses the record's tags and fails unless rua names that mailbox (size suffixes and several URIs are accepted). The policy check now reads the p tag instead of matching the substring "p=", which "sp=" also matched. Closes #1125 Co-Authored-By: Claude Opus 5.5 --- roles/web-app-mailu/README.md | 1 + roles/web-app-mailu/meta/services.yml | 2 + roles/web-app-mailu/tasks/08_dns-records.yml | 15 ++- roles/web-app-mailu/templates/env.j2 | 2 +- roles/web-app-mailu/vars/main.yml | 3 + roles/web-app-stalwart/README.md | 7 +- .../files/python/production_facts.py | 40 ++++++- roles/web-app-stalwart/meta/services.yml | 2 + .../web-app-stalwart/tasks/09_dns-records.yml | 12 +- .../tasks/13_production_facts.yml | 1 + roles/web-app-stalwart/vars/main.yml | 2 + .../files/test_production_facts.py | 104 ++++++++++-------- 12 files changed, 138 insertions(+), 53 deletions(-) diff --git a/roles/web-app-mailu/README.md b/roles/web-app-mailu/README.md index f803334cb0..dfb558d05d 100644 --- a/roles/web-app-mailu/README.md +++ b/roles/web-app-mailu/README.md @@ -87,6 +87,7 @@ Solid `1:1` edges are fixed relationships; dashed `0..1` edges are conditional ( - **Customizable Webmail and Administration:** Provides a modern web interface for managing emails and administrative tasks with ease. - **Flexible Deployment:** Easily scale and customize using Docker Compose, with configurable settings for networking, storage, and external services. - **OIDC Support:** Optionally integrate with OpenID Connect for centralized authentication across your services. +- **DMARC Reports:** The published `_dmarc` record sends aggregate reports (`rua`) to `@` of the user key in `services.mailu.dmarc.rua_user` (`administrator` unless the inventory names another one). That user MUST carry a `mailbox` account or a `forward`, otherwise the deploy fails before any record is written. ## Quick Setup diff --git a/roles/web-app-mailu/meta/services.yml b/roles/web-app-mailu/meta/services.yml index 828b626233..a9bc21bbeb 100644 --- a/roles/web-app-mailu/meta/services.yml +++ b/roles/web-app-mailu/meta/services.yml @@ -46,6 +46,8 @@ mailu: project_hard_restart: true min_storage: 20GB domain: "{{ lookup('email').domain }}" + dmarc: + rua_user: administrator ports: local: http: 8007 diff --git a/roles/web-app-mailu/tasks/08_dns-records.yml b/roles/web-app-mailu/tasks/08_dns-records.yml index 9fa9c1bf66..30c5001cd8 100644 --- a/roles/web-app-mailu/tasks/08_dns-records.yml +++ b/roles/web-app-mailu/tasks/08_dns-records.yml @@ -1,4 +1,17 @@ --- +- name: "✅ Assert the DMARC aggregate report address reaches a Mailu mailbox or alias" + ansible.builtin.assert: + that: + - >- + 'mailbox' in lookup('users', MAILU_DMARC_RUA_USER).accounts + or lookup('users', MAILU_DMARC_RUA_USER).forward | length > 0 + fail_msg: >- + services.mailu.dmarc.rua_user '{{ MAILU_DMARC_RUA_USER }}' carries + neither a mailbox account nor a forward, so Mailu provisions no + recipient for {{ MAILU_DMARC_RUA }} and every DMARC aggregate report + bounces. + quiet: true + - name: "🌐 DNS (Cloudflare) for Mailu" include_role: name: sys-dns-cloudflare-records @@ -26,7 +39,7 @@ zone: "{{ MAILU_DOMAIN_DNS_ZONE }}" name: "_dmarc.{{ MAILU_DOMAIN_DNS_ZONE }}" solo: true - value: '"v=DMARC1; p=reject; ruf=mailto:{{ MAILU_DMARC_RUF }}; adkim=s; aspf=s"' + value: '"v=DMARC1; p=reject; rua=mailto:{{ MAILU_DMARC_RUA }}; ruf=mailto:{{ MAILU_DMARC_RUF }}; adkim=s; aspf=s"' - type: TXT zone: "{{ MAILU_DOMAIN_DNS_ZONE }}" name: "dkim._domainkey.{{ MAILU_DOMAIN_DNS_ZONE }}" diff --git a/roles/web-app-mailu/templates/env.j2 b/roles/web-app-mailu/templates/env.j2 index 469b70fa0d..d073323611 100644 --- a/roles/web-app-mailu/templates/env.j2 +++ b/roles/web-app-mailu/templates/env.j2 @@ -20,7 +20,7 @@ RELAYNETS= RELAYHOST= FETCHMAIL_DELAY=600 RECIPIENT_DELIMITER=+ -DMARC_RUA=admin +DMARC_RUA={{ MAILU_DMARC_RUA_LOCALPART }} DMARC_RUF=admin WELCOME=false WELCOME_SUBJECT=Welcome to your new email account diff --git a/roles/web-app-mailu/vars/main.yml b/roles/web-app-mailu/vars/main.yml index 67132cbd2e..cbacf1545c 100644 --- a/roles/web-app-mailu/vars/main.yml +++ b/roles/web-app-mailu/vars/main.yml @@ -48,6 +48,9 @@ MAILU_EXTRA_HOSTS: "{{ query('mailu_extra_hosts') }}" MAILU_USERS: "{{ lookup('mailu_users') }}" MAILU_DOCKER_FLAVOR: "{{ 'ghcr.io/heviat' if MAILU_OIDC_ENABLED | bool else 'ghcr.io/mailu' }}" MAILU_DMARC_RUF: "{{ lookup('config', application_id, 'users.administrator.email') }}" +MAILU_DMARC_RUA_USER: "{{ lookup('config', application_id, 'services.mailu.dmarc.rua_user') }}" +MAILU_DMARC_RUA_LOCALPART: "{{ lookup('users', MAILU_DMARC_RUA_USER).username }}" +MAILU_DMARC_RUA: "{{ MAILU_DMARC_RUA_LOCALPART }}@{{ MAILU_DOMAIN }}" MAILU_DKIM_KEY_FILE: "{{ MAILU_DOMAIN }}.dkim.key" MAILU_DKIM_KEY_PATH: "/dkim/{{ MAILU_DKIM_KEY_FILE }}" MAILU_NGINX_HOST_DIR: "{{ [ MAILU_OVERRIDES_DIR, 'nginx' ] | path_join }}" diff --git a/roles/web-app-stalwart/README.md b/roles/web-app-stalwart/README.md index 8e3469b14c..72272de799 100644 --- a/roles/web-app-stalwart/README.md +++ b/roles/web-app-stalwart/README.md @@ -221,6 +221,11 @@ account (or the Keycloak SSO token when SSO is enabled). per-volume stop/start cycles. - **ClamAV runs fail-open with short milter timeouts** so mail keeps flowing while clamd warms its signature database instead of blocking the DATA stage. +- **DMARC aggregate reports go to the mailbox of + `services.stalwart.dmarc.rua_user`** (the `administrator` user unless the + inventory names another user key). The `_dmarc` record publishes + `rua=mailto:@`, and a deploy whose report user carries + no `mailbox` account fails before any record is written. - **`config.json` is bootstrap-only** (data store selection); all other configuration lives in the database and is provisioned over JMAP (`templates/jmap/*.json.j2`). @@ -368,7 +373,7 @@ Set `INFINITO_MAIL_PRODUCTION_HOST` to the server's public FQDN (in CI, a GitHub | A / AAAA | the mail host resolves | | MX | the zone's only MX is the mail host (the role publishes it `solo`) | | SPF | exactly one `v=spf1` record, authorising `mx` or `a:` | -| DMARC | `_dmarc` publishes a `v=DMARC1` record with a policy | +| DMARC | `_dmarc` publishes a `v=DMARC1` record with a policy whose `rua` names the deployed aggregate report mailbox | | DKIM | the selector this deploy read back publishes a non-empty `v=DKIM1` key | | SRV | `_submissions`/465, `_imaps`/993, `_pop3s`/995 point at the mail host | | PTR | rDNS does not contradict the mail host (absent → warning; rDNS is provisioned for Hetzner only) | diff --git a/roles/web-app-stalwart/files/python/production_facts.py b/roles/web-app-stalwart/files/python/production_facts.py index dab5f17ab6..6729a944f9 100755 --- a/roles/web-app-stalwart/files/python/production_facts.py +++ b/roles/web-app-stalwart/files/python/production_facts.py @@ -313,17 +313,48 @@ def check_spf(args, resolvers, report: Report) -> None: report.ok(f"SPF of {args.mail_domain}: {value}") +def dmarc_tags(record: str) -> dict[str, str]: + """Split a DMARC record into its ``tag=value`` pairs, tags lowercased.""" + tags: dict[str, str] = {} + for field in record.split(";"): + tag, separator, value = field.partition("=") + if separator: + tags[tag.strip().lower()] = value.strip() + return tags + + +def dmarc_report_addresses(uris: str) -> list[str]: + """The lowercased ``mailto:`` addresses of a ``rua``/``ruf`` value. + + A URI may end in a ``!`` report size limit (RFC 7489 6.2), which is + not part of the address. + """ + addresses: list[str] = [] + for uri in uris.split(","): + target = uri.strip().split("!", 1)[0].lower() + if target.startswith("mailto:"): + addresses.append(target[len("mailto:") :]) + return addresses + + def check_dmarc(args, resolvers, report: Report) -> None: - """_dmarc TXT exists, is a DMARC1 record and declares a policy.""" + """_dmarc TXT is a DMARC1 record with a policy and the deployed rua address.""" name = f"_dmarc.{args.mail_domain}" records = [str(r) for r in query(name, TYPE_TXT, resolvers, args.timeout)] dmarc = [r for r in records if r.lower().startswith("v=dmarc1")] if not dmarc: report.fail(f"{name} has no v=DMARC1 TXT record") return - if "p=" not in dmarc[0].lower(): + tags = dmarc_tags(dmarc[0]) + if not tags.get("p"): report.fail(f"{name} declares no policy (p=): {dmarc[0]}") return + expected = args.dmarc_rua.strip().lower() + if expected not in dmarc_report_addresses(tags.get("rua", "")): + report.fail( + f"{name} sends no aggregate reports to {expected} (rua=): {dmarc[0]}" + ) + return report.ok(f"DMARC of {args.mail_domain}: {dmarc[0]}") @@ -489,6 +520,11 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace: parser.add_argument( "--mail-domain", required=True, help="Zone carrying MX/SPF/DMARC" ) + parser.add_argument( + "--dmarc-rua", + required=True, + help="Mailbox the DMARC record must name as aggregate report address (rua)", + ) parser.add_argument( "--dkim-selector", default="", help="Selector published by the server" ) diff --git a/roles/web-app-stalwart/meta/services.yml b/roles/web-app-stalwart/meta/services.yml index 71c17584bf..78ed5aaf42 100644 --- a/roles/web-app-stalwart/meta/services.yml +++ b/roles/web-app-stalwart/meta/services.yml @@ -58,6 +58,8 @@ stalwart: # nocheck: min-storage-headroom Reason: the mail store (maildir blobs, FTS index, queue) lives in this service's volumes and dwarfs the image transfer size min_storage: 20GB domain: "{{ lookup('email').domain }}" + dmarc: + rua_user: administrator ports: local: http: 8095 diff --git a/roles/web-app-stalwart/tasks/09_dns-records.yml b/roles/web-app-stalwart/tasks/09_dns-records.yml index b461e9c02a..36a9ea4775 100644 --- a/roles/web-app-stalwart/tasks/09_dns-records.yml +++ b/roles/web-app-stalwart/tasks/09_dns-records.yml @@ -1,4 +1,14 @@ --- +- name: "✅ Assert the DMARC aggregate report address reaches a Stalwart mailbox" + ansible.builtin.assert: + that: + - "'mailbox' in lookup('users', STALWART_DMARC_RUA_USER).accounts" + fail_msg: >- + services.stalwart.dmarc.rua_user '{{ STALWART_DMARC_RUA_USER }}' carries + no mailbox account, so Stalwart provisions no recipient for + {{ STALWART_DMARC_RUA }} and every DMARC aggregate report bounces. + quiet: true + - name: "🔧 DNS (Cloudflare) for Stalwart" include_role: name: sys-dns-cloudflare-records @@ -35,7 +45,7 @@ zone: "{{ STALWART_DOMAIN_DNS_ZONE }}" name: "_dmarc.{{ STALWART_DOMAIN_DNS_ZONE }}" solo: true - value: '"v=DMARC1; p=reject; ruf=mailto:{{ STALWART_DMARC_RUF }}; adkim=s; aspf=s"' + value: '"v=DMARC1; p=reject; rua=mailto:{{ STALWART_DMARC_RUA }}; ruf=mailto:{{ STALWART_DMARC_RUF }}; adkim=s; aspf=s"' - type: TXT zone: "{{ STALWART_DOMAIN_DNS_ZONE }}" name: "{{ stalwart_dkim_selector }}._domainkey.{{ STALWART_DOMAIN_DNS_ZONE }}" diff --git a/roles/web-app-stalwart/tasks/13_production_facts.yml b/roles/web-app-stalwart/tasks/13_production_facts.yml index e57495248c..c9ba028b97 100644 --- a/roles/web-app-stalwart/tasks/13_production_facts.yml +++ b/roles/web-app-stalwart/tasks/13_production_facts.yml @@ -9,6 +9,7 @@ {{ [ role_path, 'files/python/production_facts.py' ] | path_join }} --mail-host {{ STALWART_PRODUCTION_HOST | quote }} --mail-domain {{ STALWART_DOMAIN | quote }} + --dmarc-rua {{ STALWART_DMARC_RUA | quote }} {{ ('--dkim-selector ' ~ (stalwart_dkim_selector | quote)) if stalwart_dkim_selector is defined else '' }} {{ ('--resolver ' ~ (STALWART_PRODUCTION_RESOLVER | quote)) diff --git a/roles/web-app-stalwart/vars/main.yml b/roles/web-app-stalwart/vars/main.yml index d7a841b0e5..4057e736d7 100644 --- a/roles/web-app-stalwart/vars/main.yml +++ b/roles/web-app-stalwart/vars/main.yml @@ -84,6 +84,8 @@ STALWART_ADMIN_PASSWORD: "{{ lookup('users', 'stalwartadmin').password }}" STALWART_USERS: "{{ lookup('stalwart_users') }}" STALWART_DMARC_RUF: "{{ lookup('config', application_id, 'users.administrator.email') }}" +STALWART_DMARC_RUA_USER: "{{ lookup('config', application_id, 'services.stalwart.dmarc.rua_user') }}" +STALWART_DMARC_RUA: "{{ lookup('users', STALWART_DMARC_RUA_USER).username }}@{{ STALWART_DOMAIN }}" STALWART_BOT_APP_PASSWORD_DESCRIPTION: "Infinito.Nexus submission" STALWART_BOT_APP_PASSWORD_RETIRED_DESCRIPTION: "Infinito.Nexus submission, retired" diff --git a/tests/unit/python/roles/web-app-stalwart/files/test_production_facts.py b/tests/unit/python/roles/web-app-stalwart/files/test_production_facts.py index 1ef49c2119..2c56608ab1 100644 --- a/tests/unit/python/roles/web-app-stalwart/files/test_production_facts.py +++ b/tests/unit/python/roles/web-app-stalwart/files/test_production_facts.py @@ -23,6 +23,15 @@ def _load_module(): _M = _load_module() +_ARGV = [ + "--mail-host", + "mail.example.org", + "--mail-domain", + "example.org", + "--dmarc-rua", + "administrator@example.org", +] + def _txt_rdata(*chunks: str) -> bytes: out = b"" @@ -188,6 +197,7 @@ def _args(**overrides): base = { "mail_host": "mail.example.org", "mail_domain": "example.org", + "dmarc_rua": "administrator@example.org", "dkim_selector": "sel1", "smtp_port": 25, "timeout": 1.0, @@ -269,18 +279,44 @@ class TestChecks(unittest.TestCase): _M.check_spf(_args(), [], self.report) self.assertEqual(self.report.failures, 1) - def test_dmarc_requires_a_policy(self): - with self._patch_query( - {("_dmarc.example.org", _M.TYPE_TXT): ["v=DMARC1; p=reject"]} - ): + def _check_dmarc_record(self, record): + with self._patch_query({("_dmarc.example.org", _M.TYPE_TXT): [record]}): _M.check_dmarc(_args(), [], self.report) + + def test_dmarc_requires_a_policy_and_the_rua_address(self): + self._check_dmarc_record( + "v=DMARC1; p=reject; rua=mailto:administrator@example.org; " + "ruf=mailto:administrator@example.org; adkim=s; aspf=s" + ) self.assertEqual(self.report.failures, 0) def test_dmarc_without_policy_fails(self): - with self._patch_query({("_dmarc.example.org", _M.TYPE_TXT): ["v=DMARC1;"]}): - _M.check_dmarc(_args(), [], self.report) + self._check_dmarc_record("v=DMARC1; rua=mailto:administrator@example.org") self.assertEqual(self.report.failures, 1) + def test_dmarc_subdomain_policy_is_not_a_policy(self): + self._check_dmarc_record( + "v=DMARC1; sp=reject; rua=mailto:administrator@example.org" + ) + self.assertEqual(self.report.failures, 1) + + def test_dmarc_without_rua_fails(self): + self._check_dmarc_record( + "v=DMARC1; p=reject; ruf=mailto:administrator@example.org" + ) + self.assertEqual(self.report.failures, 1) + + def test_dmarc_rua_to_another_mailbox_fails(self): + self._check_dmarc_record("v=DMARC1; p=reject; rua=mailto:admin@example.org") + self.assertEqual(self.report.failures, 1) + + def test_dmarc_rua_matches_among_several_uris_with_size_limits(self): + self._check_dmarc_record( + "v=DMARC1; p=reject; " + "RUA=mailto:reports@elsewhere.net!10m, mailto:Administrator@Example.org!5m" + ) + self.assertEqual(self.report.failures, 0) + def test_dkim_key_must_be_present(self): record = "v=DKIM1; k=rsa; p=MIIBIjANBg" with self._patch_query( @@ -387,20 +423,25 @@ class TestSmtpBanner(unittest.TestCase): class TestMain(unittest.TestCase): def test_no_resolver_configured_fails_fast(self): with mock.patch.object(_M, "system_resolvers", return_value=[]): - rc = _M.main( - ["--mail-host", "mail.example.org", "--mail-domain", "example.org"] - ) + rc = _M.main(_ARGV) self.assertEqual(rc, 1) + def test_missing_dmarc_rua_is_a_usage_error(self): + with ( + mock.patch.object(_M, "system_resolvers", return_value=["192.0.2.53"]), + mock.patch.object(_M.sys, "stderr"), + self.assertRaises(SystemExit) as raised, + ): + _M.main(_ARGV[:4]) + self.assertEqual(raised.exception.code, 2) + def test_success_path_returns_zero(self): clean = _M.Report() with ( mock.patch.object(_M, "system_resolvers", return_value=["192.0.2.53"]), mock.patch.object(_M, "run_checks", return_value=clean), ): - rc = _M.main( - ["--mail-host", "mail.example.org", "--mail-domain", "example.org"] - ) + rc = _M.main(_ARGV) self.assertEqual(rc, 0) def test_unreachable_resolver_is_a_finding_not_a_traceback(self): @@ -409,16 +450,7 @@ class TestMain(unittest.TestCase): mock.patch.object(_M, "run_checks", side_effect=_M.DnsError("unreachable")), mock.patch.object(_M.time, "sleep"), ): - rc = _M.main( - [ - "--mail-host", - "mail.example.org", - "--mail-domain", - "example.org", - "--retries", - "2", - ] - ) + rc = _M.main([*_ARGV, "--retries", "2"]) self.assertEqual(rc, 1) def test_failures_retry_then_report(self): @@ -429,16 +461,7 @@ class TestMain(unittest.TestCase): mock.patch.object(_M, "run_checks", return_value=broken) as runner, mock.patch.object(_M.time, "sleep"), ): - rc = _M.main( - [ - "--mail-host", - "mail.example.org", - "--mail-domain", - "example.org", - "--retries", - "3", - ] - ) + rc = _M.main([*_ARGV, "--retries", "3"]) self.assertEqual(rc, 1) self.assertEqual(runner.call_count, 3) @@ -498,18 +521,7 @@ class TestMetricsFile(unittest.TestCase): mock.patch.object(_M, "run_checks", return_value=broken), mock.patch.object(_M.time, "sleep"), ): - rc = _M.main( - [ - "--mail-host", - "mail.example.org", - "--mail-domain", - "example.org", - "--retries", - "1", - "--metrics-file", - str(target), - ] - ) + rc = _M.main([*_ARGV, "--retries", "1", "--metrics-file", str(target)]) self.assertEqual(rc, 1) self.assertIn( "stalwart_mail_facts_failures", @@ -525,9 +537,7 @@ class TestMetricsFile(unittest.TestCase): mock.patch.object(_M, "system_resolvers", return_value=["192.0.2.53"]), mock.patch.object(_M, "run_checks", return_value=clean), ): - rc = _M.main( - ["--mail-host", "mail.example.org", "--mail-domain", "example.org"] - ) + rc = _M.main(_ARGV) self.assertEqual(rc, 0) self.assertEqual(list(Path(tmp).iterdir()), []) From 1f8fc336e645d8c52a214b892c83be5a59a6426c Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 28 Oct 2026 21:38:38 +0100 Subject: [PATCH 02/31] feat(proxy): per-app nosniff, Referrer-Policy, Permissions-Policy and HSTS directives #1115 raised HSTS to one year but set no X-Content-Type-Options, Referrer-Policy, Permissions-Policy or HSTS includeSubDomains/preload, because none of them is safe globally: nosniff lets ORB block no-cors responses typed text/html, includeSubDomains on the apex covers hosts the platform does not serve, and a server-level add_header is dropped in every location that sets its own. WEBSERVER_SECURITY_HEADERS (group_vars/all/04_webserver.yml) now holds the platform values, all opt-in: nosniff false, no Referrer-Policy, no Permissions-Policy, HSTS max-age one year without includeSubDomains or preload. A role overrides any key under security_headers in its meta/server.yml, an inventory under applications..server.security_headers. The new security_headers filter merges both, rejects unknown keys, wrong types, unknown Referrer-Policy tokens, non-printable header values and preload without includeSubDomains or below a one-year max-age, and composes the HSTS value. - nosniff, Referrer-Policy and Permissions-Policy are set in the Lua header filter of content_security_policy.conf.j2, next to CSP, so a location's own add_header cannot drop them. Referrer-Policy is only set when the upstream sends none; Permissions-Policy only on HTML documents. - HSTS stays the single server-level add_header in nginx_ssl_header.j2, now with the per-app value. A second emitter in Lua would duplicate the header. It stays inside the TLS branch, which onion vhosts never enter, so an onion vhost gets no HSTS even when its app opts in. No role opts in yet, so rendered vhosts are unchanged. Closes #1123 Co-Authored-By: Claude Opus 5.5 --- group_vars/all/04_webserver.yml | 10 ++ plugins/filter/security_headers.py | 10 ++ .../templates/nginx_ssl_header.j2 | 2 +- roles/sys-svc-proxy/README.md | 26 ++- .../headers/content_security_policy.conf.j2 | 2 + .../templates/headers/security_headers.lua.j2 | 14 ++ .../plugins/filter/test_security_headers.py | 153 ++++++++++++++++ .../python/roles/sys-front-tls/__init__.py | 3 + .../roles/sys-front-tls/templates/__init__.py | 5 + .../templates/test_nginx_ssl_header.py | 103 +++++++++++ .../templates/test_security_headers_lua.py | 117 ++++++++++++ utils/roles/applications/security_headers.py | 168 ++++++++++++++++++ 12 files changed, 611 insertions(+), 2 deletions(-) create mode 100644 plugins/filter/security_headers.py create mode 100644 roles/sys-svc-proxy/templates/headers/security_headers.lua.j2 create mode 100644 tests/unit/python/plugins/filter/test_security_headers.py create mode 100644 tests/unit/python/roles/sys-front-tls/__init__.py create mode 100644 tests/unit/python/roles/sys-front-tls/templates/__init__.py create mode 100644 tests/unit/python/roles/sys-front-tls/templates/test_nginx_ssl_header.py create mode 100644 tests/unit/python/roles/sys-svc-proxy/templates/test_security_headers_lua.py create mode 100644 utils/roles/applications/security_headers.py diff --git a/group_vars/all/04_webserver.yml b/group_vars/all/04_webserver.yml index b0af51f9eb..5168689cb9 100644 --- a/group_vars/all/04_webserver.yml +++ b/group_vars/all/04_webserver.yml @@ -24,3 +24,13 @@ WEBSERVER_WORKER_CONNECTIONS: >- (lookup('applications') | resource_filter(application_id, 'pids_limit', service_name | default(''), RESOURCE_PIDS_LIMIT)) | int ] | min }} + +# Response security headers of every vhost; an app overrides any key under `security_headers` in its meta/server.yml. +WEBSERVER_SECURITY_HEADERS: + nosniff: false # X-Content-Type-Options: nosniff + referrer_policy: "" # Referrer-Policy, sent only when the upstream sends none; "" sends none + permissions_policy: "" # Permissions-Policy on HTML documents; "" sends none + hsts: + max_age: 31536000 # Strict-Transport-Security max-age in seconds + include_subdomains: false # adds includeSubDomains, which covers every subdomain of the vhost + preload: false # adds preload; requires include_subdomains and a max_age of one year diff --git a/plugins/filter/security_headers.py b/plugins/filter/security_headers.py new file mode 100644 index 0000000000..78af696964 --- /dev/null +++ b/plugins/filter/security_headers.py @@ -0,0 +1,10 @@ +"""Expose the response security headers of one application to templates.""" + +from __future__ import annotations + +from utils.roles.applications.security_headers import security_headers + + +class FilterModule: + def filters(self): + return {"security_headers": security_headers} diff --git a/roles/sys-front-tls/templates/nginx_ssl_header.j2 b/roles/sys-front-tls/templates/nginx_ssl_header.j2 index 6fc4b4f1a7..00526b0318 100644 --- a/roles/sys-front-tls/templates/nginx_ssl_header.j2 +++ b/roles/sys-front-tls/templates/nginx_ssl_header.j2 @@ -11,7 +11,7 @@ ssl_session_timeout 1d; ssl_session_cache shared:SSL:50m; ssl_session_tickets on; -add_header Strict-Transport-Security max-age=31536000 always; +add_header Strict-Transport-Security "{{ (lookup('applications') | security_headers(application_id, WEBSERVER_SECURITY_HEADERS)).hsts }}" always; ssl_stapling on; ssl_stapling_verify on; diff --git a/roles/sys-svc-proxy/README.md b/roles/sys-svc-proxy/README.md index 65120388ba..d284cf5588 100644 --- a/roles/sys-svc-proxy/README.md +++ b/roles/sys-svc-proxy/README.md @@ -31,11 +31,35 @@ The goal of this role is to deliver a **hassle-free, production-ready reverse pr - **Automatic TLS & HSTS**: integrates with the *sys-svc-webserver-https* role for certificate management. - **Flexible vHost templates**: *basic* and *ws_generic* flavours cover standard HTTP and WebSocket applications. -- **Security headers**: sensible defaults plus optional X-Frame-Options / CSP based on application settings. +- **Security headers**: CSP from each role's `meta/csp.yml`, plus the per-role headers described in [Security Headers](#security-headers). - **WebSocket & HTTP/2 aware**: upgrades, keep-alive tuning, and gzip already configured. - **OAuth2 gating**: drop-in support when *web-app-keycloak's SSO-proxy sidecar* is present. - **Modular includes**: headers, locations, and global snippets are factored for easy extension. +## Security Headers + +`WEBSERVER_SECURITY_HEADERS` in [04_webserver.yml](../../group_vars/all/04_webserver.yml) holds the platform values. A role overrides any key under `security_headers` in its `meta/server.yml`; an inventory overrides it at `applications..server.security_headers`. + +```yaml +# roles//meta/server.yml +security_headers: + nosniff: true + referrer_policy: strict-origin-when-cross-origin + permissions_policy: 'camera=(self "https://meet.example.org"), microphone=(self)' + hsts: + include_subdomains: true + preload: true +``` + +| Key | Header | Where it is rendered | +|---|---|---| +| `nosniff` | `X-Content-Type-Options: nosniff` | every response of a location that includes [content_security_policy.conf.j2](templates/headers/content_security_policy.conf.j2) | +| `referrer_policy` | `Referrer-Policy` | the same locations, only when the upstream sends none | +| `permissions_policy` | `Permissions-Policy` | HTML documents of the same locations | +| `hsts.*` | `Strict-Transport-Security` | the server block of every TLS vhost, via [nginx_ssl_header.j2](../sys-front-tls/templates/nginx_ssl_header.j2); an onion vhost has no TLS and gets none | + +The `security_headers` filter rejects unknown keys, wrong types, unknown `Referrer-Policy` tokens, and `preload` without `include_subdomains` or below a one-year `max_age`. + ## Credits Implemented by **[Kevin Veen-Birkenbach](https://www.veen.world)**. diff --git a/roles/sys-svc-proxy/templates/headers/content_security_policy.conf.j2 b/roles/sys-svc-proxy/templates/headers/content_security_policy.conf.j2 index 80d3b05a73..e1aeca87e3 100644 --- a/roles/sys-svc-proxy/templates/headers/content_security_policy.conf.j2 +++ b/roles/sys-svc-proxy/templates/headers/content_security_policy.conf.j2 @@ -19,6 +19,8 @@ header_filter_by_lua_block { ngx.header["Content-Security-Policy-Report-Only"] = nil end +{% include 'roles/sys-svc-proxy/templates/headers/security_headers.lua.j2' %} + -- If you'll modify the body later, drop Content-Length on HTML if is_html then ngx.ctx.is_html = true diff --git a/roles/sys-svc-proxy/templates/headers/security_headers.lua.j2 b/roles/sys-svc-proxy/templates/headers/security_headers.lua.j2 new file mode 100644 index 0000000000..58dd96ed17 --- /dev/null +++ b/roles/sys-svc-proxy/templates/headers/security_headers.lua.j2 @@ -0,0 +1,14 @@ +{% set _security_headers = lookup('applications') | security_headers(application_id, WEBSERVER_SECURITY_HEADERS) %} +{% if _security_headers.nosniff %} + ngx.header["X-Content-Type-Options"] = "nosniff" +{% endif %} +{% if _security_headers.referrer_policy %} + if not ngx.header["Referrer-Policy"] then + ngx.header["Referrer-Policy"] = {{ _security_headers.referrer_policy | to_json }} + end +{% endif %} +{% if _security_headers.permissions_policy %} + if is_html then + ngx.header["Permissions-Policy"] = {{ _security_headers.permissions_policy | to_json }} + end +{% endif %} diff --git a/tests/unit/python/plugins/filter/test_security_headers.py b/tests/unit/python/plugins/filter/test_security_headers.py new file mode 100644 index 0000000000..797f9e5f88 --- /dev/null +++ b/tests/unit/python/plugins/filter/test_security_headers.py @@ -0,0 +1,153 @@ +import copy +import unittest + +from plugins.filter.security_headers import FilterModule +from utils.cache.yaml import load_yaml +from utils.roles.applications.security_headers import security_headers + +from . import PROJECT_ROOT + +PLATFORM = { + "nosniff": False, + "referrer_policy": "", + "permissions_policy": "", + "hsts": {"max_age": 31536000, "include_subdomains": False, "preload": False}, +} + + +def apps_with(override): + """Return an applications map whose one app declares *override*. + + Args: + override: the app's ``server.security_headers`` block. + """ + return {"web-app-x": {"server": {"security_headers": override}}} + + +class TestPlatformValues(unittest.TestCase): + def test_an_app_without_a_block_gets_the_platform_values(self): + apps = {"web-app-plain": {"server": {"status_codes": {"default": [200]}}}} + self.assertEqual( + security_headers(apps, "web-app-plain", PLATFORM), + { + "nosniff": False, + "referrer_policy": "", + "permissions_policy": "", + "hsts": "max-age=31536000", + }, + ) + + def test_a_redirect_vhost_passes_its_domain_and_gets_the_platform_values(self): + result = security_headers(apps_with({"nosniff": True}), "old.example", PLATFORM) + self.assertFalse(result["nosniff"]) + self.assertEqual(result["hsts"], "max-age=31536000") + + def test_the_repository_platform_values_are_valid(self): + platform = load_yaml(PROJECT_ROOT / "group_vars/all/04_webserver.yml")[ + "WEBSERVER_SECURITY_HEADERS" + ] + self.assertEqual( + security_headers({}, "web-app-plain", platform)["hsts"], + "max-age=31536000", + ) + + def test_an_incomplete_platform_block_fails(self): + platform = copy.deepcopy(PLATFORM) + del platform["hsts"]["preload"] + with self.assertRaisesRegex(ValueError, "preload"): + security_headers({}, "web-app-plain", platform) + + def test_the_platform_block_is_not_mutated(self): + platform = copy.deepcopy(PLATFORM) + security_headers( + apps_with({"hsts": {"include_subdomains": True}}), "web-app-x", platform + ) + self.assertEqual(platform, PLATFORM) + + +class TestOverrides(unittest.TestCase): + def test_an_override_replaces_only_its_own_keys(self): + result = security_headers( + apps_with({"nosniff": True, "hsts": {"include_subdomains": True}}), + "web-app-x", + PLATFORM, + ) + self.assertTrue(result["nosniff"]) + self.assertEqual(result["referrer_policy"], "") + self.assertEqual(result["hsts"], "max-age=31536000; includeSubDomains") + + def test_preload_follows_include_subdomains(self): + result = security_headers( + apps_with({"hsts": {"include_subdomains": True, "preload": True}}), + "web-app-x", + PLATFORM, + ) + self.assertEqual(result["hsts"], "max-age=31536000; includeSubDomains; preload") + + def test_a_referrer_policy_list_is_accepted(self): + value = "no-referrer, strict-origin-when-cross-origin" + result = security_headers( + apps_with({"referrer_policy": value}), "web-app-x", PLATFORM + ) + self.assertEqual(result["referrer_policy"], value) + + def test_a_permissions_policy_keeps_its_quoted_origins(self): + value = 'camera=(self "https://meet.example.org"), microphone=(self)' + result = security_headers( + apps_with({"permissions_policy": value}), "web-app-x", PLATFORM + ) + self.assertEqual(result["permissions_policy"], value) + + +class TestRejections(unittest.TestCase): + def assert_rejected(self, override, pattern, error=ValueError): + with self.assertRaisesRegex(error, pattern): + security_headers(apps_with(override), "web-app-x", PLATFORM) + + def test_an_unknown_key_fails(self): + self.assert_rejected({"nosnif": True}, "unknown keys") + + def test_an_unknown_hsts_key_fails(self): + self.assert_rejected({"hsts": {"subdomains": True}}, "unknown keys") + + def test_a_non_mapping_block_fails(self): + self.assert_rejected(None, "must be a mapping", TypeError) + + def test_a_string_flag_fails(self): + self.assert_rejected({"nosniff": "yes"}, "must be bool", TypeError) + + def test_a_boolean_max_age_fails(self): + self.assert_rejected({"hsts": {"max_age": True}}, "must be int", TypeError) + + def test_a_negative_max_age_fails(self): + self.assert_rejected({"hsts": {"max_age": -1}}, "negative") + + def test_preload_without_include_subdomains_fails(self): + self.assert_rejected({"hsts": {"preload": True}}, "requires include_subdomains") + + def test_preload_with_a_short_max_age_fails(self): + self.assert_rejected( + {"hsts": {"max_age": 86400, "include_subdomains": True, "preload": True}}, + "at least 31536000", + ) + + def test_an_unknown_referrer_policy_token_fails(self): + self.assert_rejected( + {"referrer_policy": "strict-origin-when-cross-orgin"}, + "unknown policy tokens", + ) + + def test_a_line_break_in_a_header_value_fails(self): + self.assert_rejected( + {"permissions_policy": "camera=()\r\nSet-Cookie: x=1"}, + "printable ASCII", + ) + + +class TestFilterModule(unittest.TestCase): + def test_filter_is_registered(self): + self.assertIs(FilterModule().filters()["security_headers"], security_headers) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-front-tls/__init__.py b/tests/unit/python/roles/sys-front-tls/__init__.py new file mode 100644 index 0000000000..8ee16d7567 --- /dev/null +++ b/tests/unit/python/roles/sys-front-tls/__init__.py @@ -0,0 +1,3 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/sys-front-tls/templates/__init__.py b/tests/unit/python/roles/sys-front-tls/templates/__init__.py new file mode 100644 index 0000000000..087c384b57 --- /dev/null +++ b/tests/unit/python/roles/sys-front-tls/templates/__init__.py @@ -0,0 +1,5 @@ +from pathlib import Path + +PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/sys-front-tls/templates/test_nginx_ssl_header.py b/tests/unit/python/roles/sys-front-tls/templates/test_nginx_ssl_header.py new file mode 100644 index 0000000000..851cbed1b7 --- /dev/null +++ b/tests/unit/python/roles/sys-front-tls/templates/test_nginx_ssl_header.py @@ -0,0 +1,103 @@ +from __future__ import annotations + +import re +import unittest + +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape + +from plugins.filter.security_headers import FilterModule +from utils.tls_common import resolve_enabled + +from . import PROJECT_ROOT + +TEMPLATE = "roles/sys-front-tls/templates/nginx_ssl_header.j2" + +PLATFORM = { + "nosniff": False, + "referrer_policy": "", + "permissions_policy": "", + "hsts": {"max_age": 31536000, "include_subdomains": False, "preload": False}, +} + +PRIMARY_DOMAINS = { + "web-app-x": "x.example.org", + "web-app-onion": "x.abcdefghijklmnop.onion", + "old.example.org": "old.example.org", +} + + +def render(application_id: str, override: dict) -> str: + """Return the TLS server header of one vhost. + + Args: + application_id: the app the vhost belongs to, or a redirect domain. + override: the app's ``server.security_headers`` block. + """ + applications = { + app: {"server": {"security_headers": override}} + for app in ("web-app-x", "web-app-onion") + } + + def lookup(kind, *args, **_kw): + if kind == "applications": + return applications + if kind == "tls": + term, want = args + enabled = resolve_enabled( + applications.get(term, {}), True, primary_domain=PRIMARY_DOMAINS[term] + ) + return {"enabled": enabled, "ports.web": 443 if enabled else 80}[want] + if kind == "cert": + return f"/etc/certs/{args[0]}/{args[1]}" + raise AssertionError(f"unexpected lookup {kind!r}") + + env = Environment( + loader=FileSystemLoader(str(PROJECT_ROOT)), + undefined=StrictUndefined, + autoescape=select_autoescape(), + ) + env.filters.update(FilterModule().filters()) + env.filters["bool"] = bool + return env.get_template(TEMPLATE).render( + application_id=application_id, + lookup=lookup, + WEBSERVER_SECURITY_HEADERS=PLATFORM, + ) + + +def hsts(rendered: str) -> list[str]: + """Return every Strict-Transport-Security value the header adds. + + Args: + rendered: the rendered TLS server header. + """ + return re.findall( + r'^add_header Strict-Transport-Security "([^"]*)" always;$', + rendered, + re.MULTILINE, + ) + + +class TestHsts(unittest.TestCase): + def test_the_platform_value_is_one_year_without_subdomains(self): + self.assertEqual(hsts(render("web-app-x", {})), ["max-age=31536000"]) + + def test_include_subdomains_and_preload_are_opt_in_per_app(self): + rendered = render( + "web-app-x", {"hsts": {"include_subdomains": True, "preload": True}} + ) + self.assertEqual( + hsts(rendered), ["max-age=31536000; includeSubDomains; preload"] + ) + + def test_a_redirect_vhost_sends_the_platform_value(self): + self.assertEqual(hsts(render("old.example.org", {})), ["max-age=31536000"]) + + def test_an_onion_vhost_sends_no_hsts_even_when_opted_in(self): + rendered = render("web-app-onion", {"hsts": {"include_subdomains": True}}) + self.assertNotIn("Strict-Transport-Security", rendered) + self.assertNotIn("ssl", rendered) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/sys-svc-proxy/templates/test_security_headers_lua.py b/tests/unit/python/roles/sys-svc-proxy/templates/test_security_headers_lua.py new file mode 100644 index 0000000000..3baee51efc --- /dev/null +++ b/tests/unit/python/roles/sys-svc-proxy/templates/test_security_headers_lua.py @@ -0,0 +1,117 @@ +"""Exception: a location with its own ``add_header`` drops every server-level one, +so these headers live in the Lua header filter of ``content_security_policy.conf.j2``. +""" + +from __future__ import annotations + +import json +import re +import unittest + +from jinja2 import Environment, FileSystemLoader, StrictUndefined, select_autoescape + +from plugins.filter.security_headers import FilterModule +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +SNIPPET = "roles/sys-svc-proxy/templates/headers/security_headers.lua.j2" +CSP_TEMPLATE = "roles/sys-svc-proxy/templates/headers/content_security_policy.conf.j2" + +PLATFORM = { + "nosniff": False, + "referrer_policy": "", + "permissions_policy": "", + "hsts": {"max_age": 31536000, "include_subdomains": False, "preload": False}, +} + + +def render(override: dict) -> str: + """Return the Lua snippet for an app declaring *override*. + + Args: + override: the app's ``server.security_headers`` block. + """ + applications = {"web-app-x": {"server": {"security_headers": override}}} + + def lookup(kind, *_args, **_kw): + if kind == "applications": + return applications + raise AssertionError(f"unexpected lookup {kind!r}") + + env = Environment( + loader=FileSystemLoader(str(PROJECT_ROOT)), + undefined=StrictUndefined, + autoescape=select_autoescape(), + ) + env.filters.update(FilterModule().filters()) + env.filters["to_json"] = json.dumps + return env.get_template(SNIPPET).render( + application_id="web-app-x", + lookup=lookup, + WEBSERVER_SECURITY_HEADERS=PLATFORM, + ) + + +def assignment(rendered: str, header: str) -> str: + """Return the Lua literal assigned to *header*, or an empty string. + + Args: + rendered: the rendered snippet. + header: the response header name. + """ + match = re.search( + rf'ngx\.header\["{re.escape(header)}"\] = (".*")$', rendered, re.MULTILINE + ) + return match.group(1) if match else "" + + +class TestSecurityHeadersSnippet(unittest.TestCase): + def test_the_platform_values_send_nothing(self): + self.assertNotIn("ngx.header", render({})) + + def test_nosniff_is_sent_when_opted_in(self): + rendered = render({"nosniff": True}) + self.assertEqual( + json.loads(assignment(rendered, "X-Content-Type-Options")), "nosniff" + ) + + def test_the_referrer_policy_never_replaces_the_upstream_one(self): + rendered = render({"referrer_policy": "strict-origin-when-cross-origin"}) + self.assertRegex( + rendered, + r'if not ngx\.header\["Referrer-Policy"\] then\s+' + r'ngx\.header\["Referrer-Policy"\] = "strict-origin-when-cross-origin"\s+end', + ) + + def test_the_permissions_policy_is_sent_on_documents_only(self): + rendered = render({"permissions_policy": "camera=(self)"}) + self.assertRegex( + rendered, + r'if is_html then\s+ngx\.header\["Permissions-Policy"\] = "camera=\(self\)"\s+end', + ) + + def test_quoted_origins_stay_one_lua_string(self): + value = 'camera=(self "https://meet.example.org"), microphone=(self)' + rendered = render({"permissions_policy": value}) + self.assertEqual(json.loads(assignment(rendered, "Permissions-Policy")), value) + + def test_hsts_is_left_to_the_server_level_header(self): + rendered = render({"hsts": {"include_subdomains": True}}) + self.assertNotIn("Strict-Transport-Security", rendered) + + +class TestSnippetPlacement(unittest.TestCase): + def test_the_snippet_runs_inside_the_csp_header_filter_after_is_html(self): + text = read_text(str(PROJECT_ROOT / CSP_TEMPLATE)) + block = text.index("header_filter_by_lua_block {") + is_html = text.index("local is_html") + include = text.index(f"{{% include '{SNIPPET}' %}}") + block_end = text.index("\n}\n", block) + self.assertLess(block, is_html) + self.assertLess(is_html, include) + self.assertLess(include, block_end) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/roles/applications/security_headers.py b/utils/roles/applications/security_headers.py new file mode 100644 index 0000000000..f350bcc626 --- /dev/null +++ b/utils/roles/applications/security_headers.py @@ -0,0 +1,168 @@ +"""Response security headers the front proxy adds for one application. + +``WEBSERVER_SECURITY_HEADERS`` holds the platform values. An application +overrides any of them under ``security_headers`` in its ``meta/server.yml``. +""" + +from __future__ import annotations + +import re +from collections.abc import Mapping +from typing import Any + +from utils.roles.applications.config import get + +HSTS_PRELOAD_MIN_MAX_AGE = 31536000 + +REFERRER_POLICY_TOKENS = frozenset( + { + "no-referrer", + "no-referrer-when-downgrade", + "origin", + "origin-when-cross-origin", + "same-origin", + "strict-origin", + "strict-origin-when-cross-origin", + "unsafe-url", + } +) + +SCHEMA: dict[str, Any] = { + "nosniff": bool, + "referrer_policy": str, + "permissions_policy": str, + "hsts": { + "max_age": int, + "include_subdomains": bool, + "preload": bool, + }, +} + +_FIELD_VALUE = re.compile(r"[\x20-\x7e]*") + + +def _check_type(value: Any, expected: type, where: str) -> None: + if expected is int: + valid = isinstance(value, int) and not isinstance(value, bool) + else: + valid = isinstance(value, expected) + if not valid: + raise TypeError( + f"{where} must be {expected.__name__}, got {type(value).__name__} {value!r}" + ) + + +def _resolve( + schema: Mapping[str, Any], base: Any, override: Any, where: str +) -> dict[str, Any]: + """Validate *override* against *schema* and lay it over *base*. + + Args: + schema: the expected keys and their types. + base: the complete mapping the override applies to, ``None`` when + *override* is the complete mapping itself. + override: the mapping to validate; partial when *base* is given. + where: dotted origin of *override*, for error messages. + + Returns: + A complete mapping with every key of *schema*. + """ + if not isinstance(override, Mapping): + raise TypeError(f"{where} must be a mapping, got {override!r}") + unknown = sorted(set(override) - set(schema)) + if unknown: + raise ValueError(f"{where} has unknown keys {unknown}, known: {sorted(schema)}") + if base is None: + missing = sorted(set(schema) - set(override)) + if missing: + raise ValueError(f"{where} lacks the keys {missing}") + + resolved: dict[str, Any] = {} + for key, expected in schema.items(): + path = f"{where}.{key}" + if key not in override: + resolved[key] = base[key] + elif isinstance(expected, Mapping): + resolved[key] = _resolve( + expected, None if base is None else base[key], override[key], path + ) + else: + _check_type(override[key], expected, path) + resolved[key] = override[key] + return resolved + + +def _field_value(value: str, where: str) -> str: + if not _FIELD_VALUE.fullmatch(value): + raise ValueError(f"{where} must be printable ASCII, got {value!r}") + return value + + +def _referrer_policy(value: str, where: str) -> str: + _field_value(value, where) + if not value: + return value + unknown = [ + token + for token in (part.strip() for part in value.split(",")) + if token not in REFERRER_POLICY_TOKENS + ] + if unknown: + raise ValueError(f"{where} has unknown policy tokens {unknown}") + return value + + +def _hsts(hsts: Mapping[str, Any], where: str) -> str: + if hsts["max_age"] < 0: + raise ValueError(f"{where}.max_age must not be negative") + if hsts["preload"] and not hsts["include_subdomains"]: + raise ValueError(f"{where}.preload requires include_subdomains") + if hsts["preload"] and hsts["max_age"] < HSTS_PRELOAD_MIN_MAX_AGE: + raise ValueError( + f"{where}.preload requires a max_age of at least {HSTS_PRELOAD_MIN_MAX_AGE}" + ) + directives = [f"max-age={hsts['max_age']}"] + if hsts["include_subdomains"]: + directives.append("includeSubDomains") + if hsts["preload"]: + directives.append("preload") + return "; ".join(directives) + + +def security_headers( + applications: Mapping[str, Any], application_id: str, platform: Mapping[str, Any] +) -> dict[str, Any]: + """Return the security header values the proxy sends for *application_id*. + + Args: + applications: the applications SPOT. + application_id: the role whose vhost is rendered; a redirect vhost + passes its domain, which owns no override. + platform: ``WEBSERVER_SECURITY_HEADERS``. + + Returns: + ``nosniff`` as a bool, ``referrer_policy`` and ``permissions_policy`` + as header values (empty when not sent) and ``hsts`` as the complete + ``Strict-Transport-Security`` value. + """ + base = _resolve(SCHEMA, None, platform, "WEBSERVER_SECURITY_HEADERS") + where = f"applications[{application_id!r}].server.security_headers" + override = get( + applications, + application_id, + "server.security_headers", + strict=False, + default={}, + skip_missing_app=True, + ) + resolved = _resolve(SCHEMA, base, override, where) + return { + "nosniff": resolved["nosniff"], + "referrer_policy": _referrer_policy( + resolved["referrer_policy"], f"{where}.referrer_policy" + ), + "permissions_policy": _field_value( + resolved["permissions_policy"], f"{where}.permissions_policy" + ), + "hsts": _hsts(resolved["hsts"], f"{where}.hsts"), + } From a7685e3b215d4ee8d64121ec0e2708198d531261 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 28 Oct 2026 22:38:54 +0100 Subject: [PATCH 03/31] fix(worktree): derive the swarm lab subnet without an octet overflow scripts/system/worktree/up.sh pinned INFINITO_SWARM_LAB_SUBNET to 192.168.$((244 + slot)).0/24. From slot 12 on that third octet exceeds 255, so every worktree past slot 11 carries an invalid subnet (192.168.358.0/24 for slot 114), and make swarm-zombie dies at the lab network creation with `invalid subnet: netip.ParsePrefix(...)`. The lab prefix is now 10.244., valid and distinct for every slot up to max_slot 255, and outside both the primary lab subnet 192.168.244.0/24 and the 172.30.0.0/16 worktree subnets. The host daemon allocates nothing from 10.0.0.0/8. A new lint renders the prefix for every slot and fails on an invalid, repeated or overlapping subnet; against the old derivation it fails 247 of 255 slots. Worktrees that were pinned before this fix keep their custom.env; the ones at slot 12 or above need their INFINITO_SWARM_*_IP and INFINITO_SWARM_LAB_SUBNET pins rewritten to 10.244..x and a make dotenv before they can run swarm. Co-Authored-By: Claude Opus 5.5 --- scripts/system/worktree/up.sh | 26 ++++---- .../env/test_worktree_swarm_lab_subnet.py | 61 +++++++++++++++++++ 2 files changed, 74 insertions(+), 13 deletions(-) create mode 100644 tests/lint/filesystem/env/test_worktree_swarm_lab_subnet.py diff --git a/scripts/system/worktree/up.sh b/scripts/system/worktree/up.sh index f97a72aab2..3387d86737 100755 --- a/scripts/system/worktree/up.sh +++ b/scripts/system/worktree/up.sh @@ -53,7 +53,7 @@ git worktree add "${path}" "${branch}" git_common_dir="$(git rev-parse --path-format=absolute --git-common-dir)" -lab_octet="$((244 + slot))" +lab_prefix="10.244.${slot}" echo ">>> Pinning slot ${slot} in ${path}/custom.env" cat >"${path}/custom.env" <\d+)$", re.MULTILINE) +_LAB_PREFIX_RE = re.compile(r'^lab_prefix="(?P