mirror of
https://github.com/kevinveenbirkenbach/computer-playbook.git
synced 2026-11-30 14:56:11 +00:00
Merge remote-tracking branch 'origin/main' into fix/web-app-keycloak/admin-network-allowlist/1121
This commit is contained in:
79 files changed
+1425
-168
No files matched your search
@@ -89,6 +89,47 @@ class TestCspTogglesDashboardLogout(unittest.TestCase):
|
||||
self.assertIn("'unsafe-inline'", attr)
|
||||
self.assertIn("'unsafe-inline'", elem)
|
||||
|
||||
def test_logout_respects_explicit_disable_on_elem_directive(self):
|
||||
apps = copy.deepcopy(self.apps)
|
||||
apps["app1"]["csp"]["flags"]["script-src-elem"] = {"unsafe-inline": False}
|
||||
self._set_service_enabled(apps, "logout", True)
|
||||
|
||||
header = self.filter.build_csp_header(
|
||||
apps,
|
||||
"app1",
|
||||
self.domains,
|
||||
"https",
|
||||
extra_hashes={"script-src-elem": ["console.log('logout');"]},
|
||||
)
|
||||
elem = self._get_directive_tokens(header, "script-src-elem")
|
||||
attr = self._get_directive_tokens(header, "script-src-attr")
|
||||
expected_hash = self.filter.get_csp_hash("console.log('logout');")
|
||||
|
||||
self.assertNotIn("'unsafe-inline'", elem)
|
||||
self.assertIn(expected_hash, elem)
|
||||
self.assertIn("'unsafe-inline'", attr)
|
||||
|
||||
def test_logout_respects_explicit_disable_on_whole_script_family(self):
|
||||
apps = copy.deepcopy(self.apps)
|
||||
for directive in ("script-src", "script-src-elem", "script-src-attr"):
|
||||
apps["app1"]["csp"]["flags"][directive] = {"unsafe-inline": False}
|
||||
self._set_service_enabled(apps, "logout", True)
|
||||
|
||||
header = self.filter.build_csp_header(
|
||||
apps,
|
||||
"app1",
|
||||
self.domains,
|
||||
"https",
|
||||
extra_hashes={"script-src-elem": ["console.log('logout');"]},
|
||||
)
|
||||
expected_hash = self.filter.get_csp_hash("console.log('logout');")
|
||||
|
||||
for directive in ("script-src", "script-src-elem", "script-src-attr"):
|
||||
self.assertNotIn(
|
||||
"'unsafe-inline'", self._get_directive_tokens(header, directive)
|
||||
)
|
||||
self.assertIn(expected_hash, self._get_directive_tokens(header, "script-src"))
|
||||
|
||||
def test_logout_propagates_to_base_when_not_explicitly_disabled(self):
|
||||
apps = copy.deepcopy(self.apps)
|
||||
apps["app1"].setdefault("csp", {}).setdefault("flags", {})
|
||||
|
||||
@@ -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()
|
||||
@@ -0,0 +1,38 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import unittest
|
||||
|
||||
from utils.cache.files import read_text
|
||||
|
||||
from . import PROJECT_ROOT
|
||||
|
||||
ROLE = PROJECT_ROOT / "roles" / "svc-net-tor"
|
||||
TEST_ENV = ROLE / "templates" / "test.env.j2"
|
||||
TORRC = ROLE / "templates" / "torrc.j2"
|
||||
TOR_DEFAULT_SOCKS_TIMEOUT = 120
|
||||
|
||||
|
||||
class TestOnionPortWindow(unittest.TestCase):
|
||||
def test_an_attempt_outlasts_tors_socks_timeout(self) -> None:
|
||||
self.assertNotRegex(
|
||||
read_text(str(TORRC)),
|
||||
r"(?m)^SocksTimeout\b",
|
||||
"torrc now sets SocksTimeout; ONION_PORT_TIMEOUT has to be derived "
|
||||
"from it instead of from Tor's default",
|
||||
)
|
||||
declared = re.search(
|
||||
r"(?m)^ONION_PORT_TIMEOUT=(\d+)$", read_text(str(TEST_ENV))
|
||||
)
|
||||
self.assertIsNotNone(declared, "test.env.j2 declares no ONION_PORT_TIMEOUT")
|
||||
self.assertGreater(
|
||||
int(declared.group(1)),
|
||||
TOR_DEFAULT_SOCKS_TIMEOUT,
|
||||
"a port probe attempt that ends before Tor's SocksTimeout walks away "
|
||||
"from a rendezvous Tor is still building, and Tor never reaches its "
|
||||
"own verdict or logs it",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,3 @@
|
||||
from pathlib import Path
|
||||
|
||||
PROJECT_ROOT: Path = Path(__file__).resolve().parents[5]
|
||||
@@ -0,0 +1,5 @@
|
||||
from pathlib import Path
|
||||
|
||||
PROJECT_ROOT: Path = Path(__file__).resolve().parents[6]
|
||||
|
||||
__all__ = ["PROJECT_ROOT"]
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -0,0 +1,3 @@
|
||||
from pathlib import Path
|
||||
|
||||
PROJECT_ROOT: Path = Path(__file__).resolve().parents[5]
|
||||
@@ -0,0 +1,101 @@
|
||||
import unittest
|
||||
|
||||
from jinja2 import Environment
|
||||
|
||||
from utils.cache.yaml import load_yaml_any
|
||||
|
||||
from . import PROJECT_ROOT
|
||||
|
||||
TASKS = PROJECT_ROOT / "roles" / "web-app-fider" / "tasks"
|
||||
MODES = ("compose", "swarm")
|
||||
|
||||
_TRUTHY = frozenset({"1", "true", "yes", "y", "on"})
|
||||
|
||||
|
||||
def _to_bool(value):
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
return str(value).strip().lower() in _TRUTHY
|
||||
|
||||
|
||||
def _guard_holds(task, context) -> bool:
|
||||
when = task.get("when", [])
|
||||
guards = when if isinstance(when, list) else [when]
|
||||
env = Environment(autoescape=True)
|
||||
env.filters["bool"] = _to_bool
|
||||
return all(bool(env.compile_expression(expr)(**context)) for expr in guards)
|
||||
|
||||
|
||||
def _run_tasks(*, sso: bool, stack_host: bool, mode: str, tenants: int) -> list:
|
||||
context = {
|
||||
"FIDER_OIDC_ENABLED": sso,
|
||||
"FIDER_MCP_ENABLED": False,
|
||||
"IS_STACK_HOST": stack_host,
|
||||
"DEPLOYMENT_MODE": mode,
|
||||
"fider_tenant_count": {"rows": [[tenants]]},
|
||||
}
|
||||
executed: list = []
|
||||
for include in load_yaml_any(str(TASKS / "00_core.yml")):
|
||||
target = include.get("include_tasks")
|
||||
if not isinstance(target, str) or not (TASKS / target).is_file():
|
||||
continue
|
||||
if not _guard_holds(include, context):
|
||||
continue
|
||||
executed.extend(
|
||||
task
|
||||
for task in load_yaml_any(str(TASKS / target))
|
||||
if _guard_holds(task, context)
|
||||
)
|
||||
return executed
|
||||
|
||||
|
||||
def _tenant_posts(tasks: list) -> list:
|
||||
return [
|
||||
task
|
||||
for task in tasks
|
||||
if str(task.get("uri_retry", {}).get("url", "")).endswith("/_api/tenants")
|
||||
or "POST /_api/tenants" in str(task.get("ansible.builtin.shell", ""))
|
||||
]
|
||||
|
||||
|
||||
def _configures_keycloak(tasks: list) -> bool:
|
||||
return any(
|
||||
str(task.get("database_query", {}).get("query_file", "")).endswith(
|
||||
"configure-oidc-provider.sql"
|
||||
)
|
||||
for task in tasks
|
||||
)
|
||||
|
||||
|
||||
class TestTenantBootstrapGate(unittest.TestCase):
|
||||
def test_fresh_stack_host_posts_one_tenant_with_and_without_sso(self):
|
||||
for sso in (True, False):
|
||||
for mode in MODES:
|
||||
with self.subTest(sso=sso, mode=mode):
|
||||
tasks = _run_tasks(sso=sso, stack_host=True, mode=mode, tenants=0)
|
||||
self.assertEqual(len(_tenant_posts(tasks)), 1)
|
||||
|
||||
def test_existing_tenant_is_not_posted_again(self):
|
||||
for sso in (True, False):
|
||||
for mode in MODES:
|
||||
with self.subTest(sso=sso, mode=mode):
|
||||
tasks = _run_tasks(sso=sso, stack_host=True, mode=mode, tenants=1)
|
||||
self.assertEqual(_tenant_posts(tasks), [])
|
||||
|
||||
def test_keycloak_provider_is_configured_only_with_sso(self):
|
||||
for sso in (True, False):
|
||||
for mode in MODES:
|
||||
with self.subTest(sso=sso, mode=mode):
|
||||
tasks = _run_tasks(sso=sso, stack_host=True, mode=mode, tenants=1)
|
||||
self.assertEqual(_configures_keycloak(tasks), sso)
|
||||
|
||||
def test_non_stack_host_runs_no_bootstrap(self):
|
||||
for sso in (True, False):
|
||||
for mode in MODES:
|
||||
with self.subTest(sso=sso, mode=mode):
|
||||
tasks = _run_tasks(sso=sso, stack_host=False, mode=mode, tenants=0)
|
||||
self.assertEqual(tasks, [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -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,68 @@ 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"]}
|
||||
):
|
||||
_M.check_dmarc(_args(), [], self.report)
|
||||
def _check_dmarc_record(self, record, **overrides):
|
||||
with self._patch_query({("_dmarc.example.org", _M.TYPE_TXT): [record]}):
|
||||
_M.check_dmarc(_args(**overrides), [], 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_dmarc_duplicate_rua_invalidates_the_record(self):
|
||||
self._check_dmarc_record(
|
||||
"v=DMARC1; p=reject; rua=mailto:reports@elsewhere.net; "
|
||||
"rua=mailto:administrator@example.org"
|
||||
)
|
||||
self.assertEqual(self.report.failures, 1)
|
||||
|
||||
def test_dmarc_tags_differing_only_in_case_are_duplicates(self):
|
||||
with self.assertRaises(ValueError):
|
||||
_M.dmarc_tags("v=DMARC1; p=reject; P=none")
|
||||
|
||||
def test_dmarc_rua_address_is_percent_decoded(self):
|
||||
self._check_dmarc_record(
|
||||
"v=DMARC1; p=reject; rua=mailto:dmarc%2Breports@example.org!10m",
|
||||
dmarc_rua="dmarc+reports@example.org",
|
||||
)
|
||||
self.assertEqual(self.report.failures, 0)
|
||||
|
||||
def test_dmarc_rua_header_fields_are_not_part_of_the_address(self):
|
||||
self._check_dmarc_record(
|
||||
"v=DMARC1; p=reject; rua=mailto:administrator@example.org?subject=dmarc"
|
||||
)
|
||||
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 +447,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 +474,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 +485,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 +545,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 +561,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()), [])
|
||||
|
||||
|
||||
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,134 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from utils.cache.files import PROJECT_ROOT
|
||||
|
||||
SCRIPT = PROJECT_ROOT / "scripts" / "git" / "assert" / "main_merged.sh"
|
||||
MAIN_COMMIT_ENV = "INFINITO_MAIN_COMMIT" # nocheck: git maintainer tooling knob, not a deployment env key
|
||||
|
||||
|
||||
class MainMergedFixture:
|
||||
"""A bare ``origin`` whose ``main`` moved on after ``head`` branched off it.
|
||||
|
||||
Args:
|
||||
tmp: directory that holds the bare remote and its two clones.
|
||||
"""
|
||||
|
||||
def __init__(self, tmp: str) -> None:
|
||||
root = Path(tmp)
|
||||
inherited = {
|
||||
k: v
|
||||
for k, v in os.environ.items()
|
||||
if not k.startswith(("GIT_", "INFINITO_"))
|
||||
}
|
||||
self.env = {
|
||||
**inherited,
|
||||
"GIT_CONFIG_GLOBAL": os.devnull,
|
||||
"GIT_CONFIG_NOSYSTEM": "1",
|
||||
"GIT_AUTHOR_NAME": "test",
|
||||
"GIT_AUTHOR_EMAIL": "test@example.invalid",
|
||||
"GIT_COMMITTER_NAME": "test",
|
||||
"GIT_COMMITTER_EMAIL": "test@example.invalid",
|
||||
}
|
||||
origin = root / "origin.git"
|
||||
maintainer = root / "maintainer"
|
||||
self.head = root / "head"
|
||||
self.git(root, "init", "--bare", "-b", "main", str(origin))
|
||||
self.git(root, "init", "-b", "main", str(maintainer))
|
||||
self.git(maintainer, "remote", "add", "origin", str(origin))
|
||||
self.base = self.commit(maintainer, "base")
|
||||
self.git(maintainer, "push", "origin", "main")
|
||||
self.git(root, "clone", str(origin), str(self.head))
|
||||
self.git(self.head, "switch", "-c", "feature")
|
||||
self.commit(self.head, "feature")
|
||||
self.main_tip = self.commit(maintainer, "main moved on")
|
||||
self.git(maintainer, "push", "origin", "main")
|
||||
|
||||
def git(self, cwd: Path, *args: str) -> str:
|
||||
return subprocess.run(
|
||||
["git", *args],
|
||||
cwd=cwd,
|
||||
env=self.env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
).stdout.strip()
|
||||
|
||||
def commit(self, repo: Path, message: str) -> str:
|
||||
self.git(repo, "commit", "--allow-empty", "-m", message)
|
||||
return self.git(repo, "rev-parse", "HEAD")
|
||||
|
||||
def merge_main(self) -> None:
|
||||
self.git(self.head, "pull", "--no-rebase", "--no-edit", "origin", "main")
|
||||
|
||||
def run_script(self, main_commit: str | None) -> subprocess.CompletedProcess:
|
||||
"""Run the script in ``head``.
|
||||
|
||||
Args:
|
||||
main_commit: value of the main-commit override; ``None`` leaves it unset.
|
||||
"""
|
||||
env = dict(self.env)
|
||||
if main_commit is not None:
|
||||
env[MAIN_COMMIT_ENV] = main_commit
|
||||
return subprocess.run(
|
||||
["bash", str(SCRIPT)],
|
||||
cwd=self.head,
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
|
||||
|
||||
class TestMainMergedPinnedCommit(unittest.TestCase):
|
||||
def test_contained_commit_passes_after_main_moved_on(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
fixture = MainMergedFixture(tmp)
|
||||
result = fixture.run_script(fixture.base)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn(f"origin/main@{fixture.base} is fully merged", result.stderr)
|
||||
|
||||
def test_commit_missing_from_head_fails(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
fixture = MainMergedFixture(tmp)
|
||||
result = fixture.run_script(fixture.main_tip)
|
||||
self.assertEqual(result.returncode, 1, result.stderr)
|
||||
self.assertIn(
|
||||
f"origin/main@{fixture.main_tip} has 1 commit(s) not merged into HEAD",
|
||||
result.stderr,
|
||||
)
|
||||
|
||||
def test_empty_commit_fails_loudly(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
fixture = MainMergedFixture(tmp)
|
||||
result = fixture.run_script("")
|
||||
self.assertEqual(result.returncode, 2, result.stderr)
|
||||
self.assertIn("must be a full commit SHA", result.stderr)
|
||||
|
||||
|
||||
class TestMainMergedLiveTip(unittest.TestCase):
|
||||
def test_live_tip_missing_from_head_fails(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
fixture = MainMergedFixture(tmp)
|
||||
result = fixture.run_script(None)
|
||||
self.assertEqual(result.returncode, 1, result.stderr)
|
||||
self.assertIn(
|
||||
"origin/main has 1 commit(s) not merged into HEAD", result.stderr
|
||||
)
|
||||
|
||||
def test_merged_live_tip_passes(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
fixture = MainMergedFixture(tmp)
|
||||
fixture.merge_main()
|
||||
result = fixture.run_script(None)
|
||||
self.assertEqual(result.returncode, 0, result.stderr)
|
||||
self.assertIn("origin/main is fully merged into HEAD", result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user