diff --git a/plugins/filter/status_codes.py b/plugins/filter/status_codes.py new file mode 100644 index 0000000000..30b2b4e90a --- /dev/null +++ b/plugins/filter/status_codes.py @@ -0,0 +1,22 @@ +"""Expose the status codes that prove a domain is served to templates.""" + +from __future__ import annotations + +import sys +from pathlib import Path + +# nocheck: project-root-import +_BASE_DIR = str(Path(__file__).resolve().parents[2]) +_MODULE_UTILS_DIR = str(Path(_BASE_DIR) / "utils") +for _p in (_BASE_DIR, _MODULE_UTILS_DIR): + if _p not in sys.path: + sys.path.insert(0, _p) + +from utils.roles.applications.status_codes import ( # noqa: E402 + accepted_status_codes, +) + + +class FilterModule: + def filters(self): + return {"accepted_status_codes": accepted_status_codes} diff --git a/roles/sys-ctl-hlth-webserver/filter_plugins/web_health_expectations.py b/roles/sys-ctl-hlth-webserver/filter_plugins/web_health_expectations.py index 169d635acf..e8cd9b50f7 100644 --- a/roles/sys-ctl-hlth-webserver/filter_plugins/web_health_expectations.py +++ b/roles/sys-ctl-hlth-webserver/filter_plugins/web_health_expectations.py @@ -3,6 +3,7 @@ from collections.abc import Mapping from pathlib import Path from utils.roles.applications.config import get +from utils.roles.applications.status_codes import DEFAULT_OK, codes_by_key # nocheck: project-root-import _BASE_DIR = str(Path(__file__).resolve().parents[3]) @@ -11,8 +12,6 @@ for _p in (_BASE_DIR, _MODULE_UTILS_DIR): if _p not in sys.path: sys.path.insert(0, _p) -DEFAULT_OK = [200, 302, 301] - def _to_list(x, *, allow_mapping: bool = True): """Normalize into a flat list of **strings only**.""" @@ -46,15 +45,6 @@ def _to_list(x, *, allow_mapping: bool = True): return [] -def _valid_http_code(x): - """Return int(x) if 100 <= code <= 599 else None.""" - try: - v = int(x) - except (TypeError, ValueError): - return None - return v if 100 <= v <= 599 else None - - def _extract_redirect_sources(redirect_maps): """Extract a set of source domains from redirect maps.""" sources = set() @@ -94,28 +84,6 @@ def _normalize_selection(group_names): return sel -def _normalize_codes(x): - """ - Accepts: - - single code (int or str) - - list/tuple/set of codes - Returns a de-duplicated list of valid ints (100..599) in original order. - """ - if x is None: - return [] - if isinstance(x, (list, tuple, set)): - out = [] - seen = set() - for v in x: - c = _valid_http_code(v) - if c is not None and c not in seen: - seen.add(c) - out.append(c) - return out - c = _valid_http_code(x) - return [c] if c is not None else [] - - def _apply_onion_deploy_view(per_app, applications, primary_domain, node_onion): """Rewrite each app's expectation domains to what the current deploy serves: for a ``services.tor.enabled`` app the onion domains replace (``exclusive``) @@ -190,15 +158,9 @@ def web_health_expectations( ) aliases = _to_list(aliases_raw, allow_mapping=True) - sc_raw = get( - applications, app_id, "server.status_codes", strict=False, default={} + sc_map = codes_by_key( + get(applications, app_id, "server.status_codes", strict=False, default={}) ) - sc_map = {} - if isinstance(sc_raw, Mapping): - for k, v in sc_raw.items(): - codes = _normalize_codes(v) - if codes: - sc_map[str(k)] = codes suppressed = set() services_raw = get(applications, app_id, "services", strict=False, default={}) diff --git a/roles/sys-stk-front-proxy/tasks/main.yml b/roles/sys-stk-front-proxy/tasks/main.yml index 9d1ff678aa..ab066a945a 100644 --- a/roles/sys-stk-front-proxy/tasks/main.yml +++ b/roles/sys-stk-front-proxy/tasks/main.yml @@ -35,6 +35,7 @@ ) ) }} + front_proxy_status_codes: "{{ lookup('applications') | accepted_status_codes(application_id, lookup('tls', application_id, 'domain')) }}" front_proxy_domain_conf_dst_resolved: >- {{ lookup( @@ -106,10 +107,7 @@ - name: "🔍 Check if {{ lookup('domain', front_proxy_application_id) }} is reachable" uri_probe: url: "{{ lookup('tls', front_proxy_application_id, 'url.base') }}" - status_code: - - 200 - - 301 - - 302 + status_code: "{{ front_proxy_status_codes }}" register: site_check failed_when: false changed_when: false @@ -120,7 +118,7 @@ notify: restart-openresty when: - site_check.status is defined - - site_check.status not in [200, 301, 302] + - site_check.status not in front_proxy_status_codes when: not nginx_conf.changed - name: "🔄 Restart Webserver for '{{ front_proxy_domain_conf_dst_resolved }}'" @@ -129,10 +127,7 @@ - name: "🔍 Verify '{{ front_proxy_domain }}' is served after the reload" uri_probe: url: "{{ lookup('tls', front_proxy_application_id, 'url.base') }}" - status_code: - - 200 - - 301 - - 302 + status_code: "{{ front_proxy_status_codes }}" register: front_proxy_reload_check failed_when: false changed_when: false @@ -145,7 +140,7 @@ when: - nginx_conf.changed - front_proxy_reload_check.status is defined - - front_proxy_reload_check.status not in [200, 301, 302] + - front_proxy_reload_check.status not in front_proxy_status_codes - name: "🔄 Flush the fallback redeploy for '{{ front_proxy_domain }}'" ansible.builtin.meta: flush_handlers diff --git a/tests/unit/python/plugins/filter/test_status_codes.py b/tests/unit/python/plugins/filter/test_status_codes.py new file mode 100644 index 0000000000..4da0ef76b2 --- /dev/null +++ b/tests/unit/python/plugins/filter/test_status_codes.py @@ -0,0 +1,157 @@ +import unittest + +from plugins.filter.status_codes import FilterModule +from utils.roles.applications.status_codes import ( + DEFAULT_OK, + accepted_status_codes, + declared_status_codes, +) + +SEAWEEDFS = { + "web-app-seaweedfs": { + "domains": { + "canonical": { + "api": "s3.example.org", + "filer": "filer.example.org", + "master": "master.example.org", + } + }, + "server": { + "status_codes": { + "api": [301, 302, 403, 405], + "filer": [302, 403], + "master": [302, 403], + } + }, + } +} + + +class TestDeclaredStatusCodes(unittest.TestCase): + def test_per_vhost_key_wins(self): + for domain, codes in ( + ("s3.example.org", [301, 302, 403, 405]), + ("filer.example.org", [302, 403]), + ("master.example.org", [302, 403]), + ): + with self.subTest(domain=domain): + self.assertEqual( + declared_status_codes(SEAWEEDFS, "web-app-seaweedfs", domain), + codes, + ) + + def test_undeclared_app_declares_nothing(self): + apps = {"web-app-plain": {"domains": {"canonical": ["plain.example.org"]}}} + self.assertEqual( + declared_status_codes(apps, "web-app-plain", "plain.example.org"), [] + ) + + def test_flat_canonical_uses_the_default_key(self): + apps = { + "web-app-prometheus": { + "domains": {"canonical": ["metrics.example.org"]}, + "server": {"status_codes": {"default": [405]}}, + } + } + self.assertEqual( + declared_status_codes(apps, "web-app-prometheus", "metrics.example.org"), + [405], + ) + + def test_unknown_domain_falls_back_to_the_declared_default(self): + apps = { + "web-app-x": { + "domains": {"canonical": {"api": "api.example.org"}}, + "server": {"status_codes": {"api": [403], "default": [404]}}, + } + } + self.assertEqual( + declared_status_codes(apps, "web-app-x", "other.example.org"), [404] + ) + + def test_a_key_without_its_own_codes_uses_the_default(self): + apps = { + "web-app-x": { + "domains": {"canonical": {"api": "api.example.org"}}, + "server": {"status_codes": {"other": [403], "default": [404]}}, + } + } + self.assertEqual( + declared_status_codes(apps, "web-app-x", "api.example.org"), [404] + ) + + def test_scalar_and_string_codes_are_normalized(self): + apps = { + "web-app-x": { + "domains": {"canonical": {"api": ["api.example.org"]}}, + "server": {"status_codes": {"api": "403"}}, + } + } + self.assertEqual( + declared_status_codes(apps, "web-app-x", "api.example.org"), [403] + ) + + def test_out_of_range_declarations_are_dropped(self): + apps = { + "web-app-x": { + "domains": {"canonical": {"api": "api.example.org"}}, + "server": {"status_codes": {"api": [999, "nope"]}}, + } + } + self.assertEqual( + declared_status_codes(apps, "web-app-x", "api.example.org"), [] + ) + + +class TestAcceptedStatusCodes(unittest.TestCase): + def test_filter_is_registered(self): + self.assertIn("accepted_status_codes", FilterModule().filters()) + + def test_declared_codes_are_added_to_the_default(self): + self.assertEqual( + accepted_status_codes(SEAWEEDFS, "web-app-seaweedfs", "filer.example.org"), + [200, 302, 301, 403], + ) + + def test_a_narrower_declaration_never_narrows_the_gate(self): + apps = { + "web-app-mailu": { + "domains": {"canonical": ["mail.example.org"]}, + "server": {"status_codes": {"default": [200, 301]}}, + } + } + self.assertEqual( + accepted_status_codes(apps, "web-app-mailu", "mail.example.org"), + DEFAULT_OK, + ) + + def test_a_disjoint_declaration_only_adds(self): + apps = { + "web-svc-mirror": { + "domains": {"canonical": ["mirror.example.org"]}, + "server": {"status_codes": {"default": [404]}}, + } + } + self.assertEqual( + accepted_status_codes(apps, "web-svc-mirror", "mirror.example.org"), + [200, 302, 301, 404], + ) + + def test_undeclared_app_gets_the_default(self): + apps = {"web-app-plain": {"domains": {"canonical": ["plain.example.org"]}}} + self.assertEqual( + accepted_status_codes(apps, "web-app-plain", "plain.example.org"), + DEFAULT_OK, + ) + + def test_the_result_is_a_copy(self): + first = accepted_status_codes(SEAWEEDFS, "web-app-seaweedfs", "unknown.org") + first.append(418) + self.assertEqual( + accepted_status_codes(SEAWEEDFS, "web-app-seaweedfs", "unknown.org"), + DEFAULT_OK, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/utils/roles/applications/status_codes.py b/utils/roles/applications/status_codes.py new file mode 100644 index 0000000000..79aae9e57a --- /dev/null +++ b/utils/roles/applications/status_codes.py @@ -0,0 +1,119 @@ +"""HTTP status codes for a deployed domain. + +``roles//meta/server.yml`` declares ``status_codes`` keyed like +``domains.canonical``; it is the single source of truth for every prober. +""" + +from __future__ import annotations + +from collections.abc import Mapping + +from utils.roles.applications.config import get + +DEFAULT_OK = [200, 302, 301] + + +def normalize_codes(value) -> list[int]: + """Return *value* as a list of plausible HTTP status codes. + + Args: + value: a scalar, list or mapping straight out of the declaration. + + Returns: + The codes as de-duplicated integers, dropping anything outside 100-599. + """ + if value is None: + return [] + candidates = value if isinstance(value, (list, tuple, set)) else [value] + codes: list[int] = [] + for candidate in candidates: + if isinstance(candidate, bool): + continue + try: + code = int(candidate) + except (TypeError, ValueError): + continue + if 100 <= code <= 599 and code not in codes: + codes.append(code) + return codes + + +def codes_by_key(raw) -> dict[str, list[int]]: + """Normalize a raw ``server.status_codes`` declaration. + + Args: + raw: the declaration as read from the app config. + + Returns: + The declared keys mapped to their codes, dropping keys that declare + nothing usable. + """ + if not isinstance(raw, Mapping): + return {} + resolved: dict[str, list[int]] = {} + for key, value in raw.items(): + codes = normalize_codes(value) + if codes: + resolved[str(key)] = codes + return resolved + + +def declared_status_codes(applications, app_id: str, domain: str) -> list[int]: + """Return what *app_id* declares for *domain*, or an empty list. + + The vhost is identified by the ``domains.canonical`` key that carries the + domain, which is the same key ``server.status_codes`` uses. A domain that + is not canonical, or a key that declares nothing, falls back to the + declared ``default``. + + Args: + applications: the applications SPOT. + app_id: the role the domain belongs to. + domain: the fully qualified domain being probed. + + Returns: + The declared codes, empty when the app declares none for this domain. + """ + declared = codes_by_key( + get(applications, app_id, "server.status_codes", strict=False, default={}) + ) + if not declared: + return [] + + wanted = str(domain or "").strip() + canonical = get(applications, app_id, "domains.canonical", strict=False, default=[]) + if wanted and isinstance(canonical, Mapping): + for key, domains in canonical.items(): + entries = domains if isinstance(domains, (list, tuple, set)) else [domains] + if wanted in {str(entry).strip() for entry in entries if entry}: + codes = declared.get(str(key)) + if codes: + return list(codes) + break + + return list(declared.get("default") or []) + + +def accepted_status_codes(applications, app_id: str, domain: str) -> list[int]: + """Return the codes that prove *domain* is being served at all. + + Most declarations are narrower than :data:`DEFAULT_OK`, so this gate adds + to the default instead of replacing it; narrowing it would escalate vhosts + that answer perfectly well. Contract checking is a different question and + belongs to ``sys-ctl-hlth-webserver``. + + Args: + applications: the applications SPOT. + app_id: the role the domain belongs to. + domain: the fully qualified domain being probed. + + Returns: + :data:`DEFAULT_OK` plus whatever the app declares for this domain. + """ + accepted = list(DEFAULT_OK) + accepted.extend( + code + for code in declared_status_codes(applications, app_id, domain) + if code not in accepted + ) + return accepted