Merge branch 'main' into feature/store-i18n

Fourteen real conflicts plus the 66 generated READMEs.

utils/cache/files.py and its test: both sides added a skip-dir rule, resolved
as a union so the root `build/` prune and the per-root walk key coexist.

plugins/lookup/database.py and postgres_libraries.py: main's added lookups kept,
with get_entity_name renamed to entity_name as this branch renamed it.

roles/web-app-{mailu,matrix}/meta/services.yml: main's `covers: [email]` and its
MAIL_PROVIDER-gated email entry, plus this branch's gitlab/jira/n8n/jitsi
consumers, which the merge base carried on neither side.

group_vars/all/17_resource.yml: this branch's lookup('resource', ...) refactor;
main's single added literal is already covered by _POSTGRES_MAX_LOCKS_PER_TRANSACTION.

docs/requirements/035-mcp-proxy-expansion.md: this branch moved the design into
ADR 0003, so the requirement keeps only the user story and the criteria. Main's
delta inside the moved block was two new roles, carried into the ADR audit:
web-app-stalwart as adapter_candidate, svc-net-tor-smtp as privileged_control_plane.
The no_surface total said 99 while its own subcategories summed to 112.

inventories/development/default.yml: biber keeps no explicit email. Both sides fixed
the same CI failure; this branch fixed it in _apply_account_defaults, which renders
biber@{{ DOMAIN_PRIMARY }} (utils/cache/users/__init__.py:68) — byte-identical to
the address main hardcoded, so the inventory line is a second copy of one fact.

roles/web-app-{gitlab,keycloak}/files/playwright/playwright.spec.js and
roles/web-app-gitlab/templates/playwright.env.j2: union of both import sets, with
requireDotenvValue kept over decodeDotenvQuotedValue for CANONICAL_DOMAIN because
an empty value must fail rather than match every substring.

The 66 role READMEs take this side: aceb5295ef moved Cosmos, Quick Setup and
Credits to the documentation build, and test_readme.py now rejects them in a
committed README. Main's prose edits inside them are carried over by hand (the
Mailu deprecation banner, Mailu -> Stalwart in erpnext and zammad), and the two
READMEs main added fresh are stripped of the three generated sections.
roles/web-app-sphinx/README.md stays deleted; 6eb9a59d14 merged that role into
web-app-docs. The root README's generated role table was regenerated from the
merged metadata.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
kevinveenbirkenbachandClaude Opus 5 committed 2026-10-04 01:57:17 +02:00
commit f2fedfc677
351 files changed
+9968 -416

No files matched your search

@@ -473,8 +473,9 @@ class TestHandlerFullCycle(unittest.TestCase):
interleave: round-0 sync, round-0 async, then round-1 sync,
round-1 async. Every call carries the zero-based VARIANT_INDEX so
consumers like the test-e2e-playwright role can namespace their
artifacts. Cleanup still runs once between rounds with the full
previous-round include."""
artifacts, plus PRIMARY_APPS so role-owned tests can tell a deploy
target from a pulled-in dependency. Cleanup still runs once between
rounds with the full previous-round include."""
make_compose_mock.return_value = _make_compose_mock()
plan_mock.return_value = [
_entry(0, "/srv/inv-0", {"web-app-multi": 0}),
@@ -494,10 +495,24 @@ class TestHandlerFullCycle(unittest.TestCase):
self.assertEqual(
sequence,
[
("/srv/inv-0", {"VARIANT_INDEX": 0}),
("/srv/inv-0", {"ASYNC_ENABLED": True, "VARIANT_INDEX": 0}),
("/srv/inv-1", {"VARIANT_INDEX": 1}),
("/srv/inv-1", {"ASYNC_ENABLED": True, "VARIANT_INDEX": 1}),
("/srv/inv-0", {"VARIANT_INDEX": 0, "PRIMARY_APPS": ["web-app-multi"]}),
(
"/srv/inv-0",
{
"ASYNC_ENABLED": True,
"VARIANT_INDEX": 0,
"PRIMARY_APPS": ["web-app-multi"],
},
),
("/srv/inv-1", {"VARIANT_INDEX": 1, "PRIMARY_APPS": ["web-app-multi"]}),
(
"/srv/inv-1",
{
"ASYNC_ENABLED": True,
"VARIANT_INDEX": 1,
"PRIMARY_APPS": ["web-app-multi"],
},
),
],
)
purge_mock.assert_called_once()
@@ -577,8 +592,15 @@ class TestHandlerFullCycle(unittest.TestCase):
self.assertEqual(
sequence,
[
("/srv/inv-1", {"VARIANT_INDEX": 1}),
("/srv/inv-1", {"ASYNC_ENABLED": True, "VARIANT_INDEX": 1}),
("/srv/inv-1", {"VARIANT_INDEX": 1, "PRIMARY_APPS": ["web-app-multi"]}),
(
"/srv/inv-1",
{
"ASYNC_ENABLED": True,
"VARIANT_INDEX": 1,
"PRIMARY_APPS": ["web-app-multi"],
},
),
],
)
purge_mock.assert_not_called()
@@ -2,6 +2,7 @@
from __future__ import annotations
import sys
import unittest
from cli.administration.recover import paths, recoverers
@@ -182,7 +183,7 @@ class RegistryTest(unittest.TestCase):
def test_command_starts_with_interpreter_and_script(self):
cmd = recoverers.RECOVERERS["secrets"].command("/gen/files")
self.assertEqual(cmd[0], "python3")
self.assertEqual(cmd[0], sys.executable)
self.assertTrue(
cmd[1].endswith("svc-bkp-secrets-2-local/files/python/recover.py")
)
@@ -2,6 +2,7 @@
from __future__ import annotations
import sys
import unittest
from cli.administration.recover import remote
@@ -43,7 +44,7 @@ class CommandsTest(unittest.TestCase):
self.assertEqual(
steps[0], ["rsync", "-a", "host:/backup/usb.img", remote.IMAGE]
)
self.assertEqual(steps[1][0], "python3")
self.assertEqual(steps[1][0], sys.executable)
self.assertIn(remote.IMAGE, steps[1])
self.assertIn(remote.LOCAL_ROOT, steps[1])
self.assertIn("--passphrase-stdin", steps[1])
@@ -40,6 +40,16 @@ class TestCliMetaApplicationsDomains(TestCase):
code = int(e.code) if e.code is not None else 0
return code, out.getvalue(), err.getvalue()
def test_domain_primary_default_resolution(self) -> None:
with patch.dict(mod.os.environ, {"DOMAIN": "explicit.env"}, clear=False):
self.assertEqual(
mod.parse_args(["--domain-primary", "flag.wins"]).domain_primary,
"flag.wins",
)
self.assertEqual(mod.parse_args([]).domain_primary, "explicit.env")
with patch.dict(mod.os.environ, {}, clear=True):
self.assertEqual(mod.parse_args([]).domain_primary, "infinito.test")
def test_cli_supports_alias_and_www_flags(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
roles_dir = Path(tmp) / "roles"
@@ -6,6 +6,7 @@ from ansible.errors import AnsibleError
from plugins.lookup.container_extra_hosts import LookupModule
ONION = "auth." + "b" * 56 + ".onion"
MAIL_ONION = "mail." + "c" * 56 + ".onion"
class TestContainerExtraHostsLookup(unittest.TestCase):
@@ -18,9 +19,13 @@ class TestContainerExtraHostsLookup(unittest.TestCase):
def _run(terms, variables=None, **_kwargs):
vars_ = variables or {}
if name == "config":
if "services.email.enabled" in terms:
return [vars_.get("_email_enabled", False)]
return [vars_.get("_sso_enabled", False)]
if name == "tls":
return [vars_.get("_provider_domain", "")]
if name == "email":
return [{"host": vars_.get("_mail_host", "")}]
raise AssertionError(f"unexpected lookup '{name}'")
plugin.run.side_effect = _run
@@ -32,7 +37,7 @@ class TestContainerExtraHostsLookup(unittest.TestCase):
patcher.start()
self.addCleanup(patcher.stop)
def _run(self, extra_hosts=None, **overrides):
def _run(self, extra_hosts=None, docker_flags=None, **overrides):
variables = {
"application_id": "web-app-espocrm",
"_sso_enabled": True,
@@ -43,8 +48,75 @@ class TestContainerExtraHostsLookup(unittest.TestCase):
}
variables.update(overrides)
kwargs = {} if extra_hosts is None else {"extra_hosts": extra_hosts}
if docker_flags is not None:
kwargs["docker_flags"] = docker_flags
return self.lookup.run(None, variables=variables, **kwargs)[0]
def test_an_onion_mail_relay_is_pinned_so_a_proxyless_client_can_reach_it(self):
"""GitLab's Net::SMTP takes no proxy, so an unpinned .onion relay
swallows every message: the send is queued and reported successful."""
block = self._run(
_sso_enabled=False, _email_enabled=True, _mail_host=MAIL_ONION
)
self.assertEqual(
block,
'extra_hosts:\n - "host.docker.internal:host-gateway"\n'
f' - "{MAIL_ONION}:host-gateway"',
)
def test_docker_flags_emit_add_host_for_a_launcher_built_container(self):
"""Discourse has no compose service -- its launcher builds the
container from docker_args, so the pins must reach it as run flags."""
block = self._run(
_sso_enabled=False,
_email_enabled=True,
_mail_host=MAIL_ONION,
docker_flags=True,
)
self.assertEqual(
block,
" - --add-host=host.docker.internal:host-gateway\n"
f" - --add-host={MAIL_ONION}:host-gateway",
)
def test_docker_flags_stay_empty_when_there_is_nothing_to_pin(self):
self.assertEqual(
self._run(_sso_enabled=False, _email_enabled=False, docker_flags=True), ""
)
def test_a_clearnet_mail_relay_is_left_alone(self):
self.assertEqual(
self._run(
_sso_enabled=False, _email_enabled=True, _mail_host="mail.example.org"
),
"",
)
def test_mail_disabled_emits_nothing(self):
self.assertEqual(
self._run(_sso_enabled=False, _email_enabled=False, _mail_host=MAIL_ONION),
"",
)
def test_swarm_pins_the_mail_relay_to_the_node_address(self):
block = self._run(
_sso_enabled=False,
_email_enabled=True,
_mail_host=MAIL_ONION,
DEPLOYMENT_MODE="swarm",
ansible_facts={"default_ipv4": {"address": "10.0.0.7"}},
)
self.assertIn(f' - "{MAIL_ONION}:10.0.0.7"', block)
def test_the_sso_and_mail_pins_coexist_without_repeating_the_alias(self):
block = self._run(_email_enabled=True, _mail_host=MAIL_ONION)
self.assertEqual(
block,
'extra_hosts:\n - "host.docker.internal:host-gateway"\n'
f' - "{ONION}:host-gateway"\n'
f' - "{MAIL_ONION}:host-gateway"',
)
def test_compose_pins_the_provider_to_the_host_gateway(self):
self.assertEqual(
self._run(),
@@ -131,7 +203,7 @@ class TestContainerExtraHostsLookup(unittest.TestCase):
variables={"application_id": "web-app-joomla"},
application_id="web-app-penpot",
)
self.assertEqual(seen, ["web-app-penpot"])
self.assertEqual(set(seen), {"web-app-penpot"})
def test_caller_entries_alone_emit_a_block_without_sso(self):
self.assertEqual(
@@ -160,6 +160,7 @@ class DatabaseLookupTests(unittest.TestCase):
self.assertTrue(out["enabled"])
self.assertFalse(out["shared"])
self.assertTrue(out["local"])
self.assertTrue(out["managed"])
self.assertEqual(out["id"], "svc-db-postgres")
@@ -196,6 +197,50 @@ class DatabaseLookupTests(unittest.TestCase):
"5432",
)
def test_dedicated_with_name_override_is_not_managed(self):
applications = {
"web-app-foo": {
"services": {
"postgres": {
"enabled": True,
"shared": False,
"name": "foo-postgres-1",
}
},
"credentials": {"database_password": "pw"},
},
"svc-db-postgres": {
"services": {
"postgres": {
"name": "postgres-central",
"image": "postgis/postgis",
"version": "16",
"ports": {"local": {"postgres": "5432"}},
}
}
},
}
ports = {"localhost": {"database": {"svc-db-postgres": "5432"}}}
vars_ = {
"applications": applications,
"ports": ports,
"DIR_COMPOSITIONS": "/opt/compose/",
}
lookup = self._make_lookup(vars_)
with patch.object(
self.db_lookup_mod,
"get_entity_name",
side_effect=self._fake_get_entity_name,
):
out = lookup.run(["web-app-foo"], variables=vars_)[0]
self.assertTrue(out["enabled"])
self.assertFalse(out["shared"])
self.assertTrue(out["local"])
self.assertFalse(out["managed"])
def test_postgres_shared_uses_central_name_for_host_instance_container_volume(self):
applications = {
"web-app-foo": {
@@ -231,6 +276,7 @@ class DatabaseLookupTests(unittest.TestCase):
self.assertTrue(out["enabled"])
self.assertTrue(out["shared"])
self.assertFalse(out["local"])
self.assertFalse(out["managed"])
self.assertEqual(out["id"], "svc-db-postgres")
@@ -329,6 +375,48 @@ class DatabaseLookupTests(unittest.TestCase):
self.assertEqual(out["version"], "15")
def test_image_override_on_consumer_wins_over_default(self):
applications = {
"web-app-foo": {
"services": {
"postgres": {
"enabled": True,
"shared": False,
"image": "postgres",
"version": "17",
}
},
"credentials": {"database_password": "pw"},
},
"svc-db-postgres": {
"services": {
"postgres": {
"name": "postgres-central",
"image": "postgis/postgis",
"version": "16",
}
}
},
}
ports = {"localhost": {"database": {"svc-db-postgres": "5432"}}}
vars_ = {
"applications": applications,
"ports": ports,
"DIR_COMPOSITIONS": "/opt/compose/",
}
lookup = self._make_lookup(vars_)
with patch.object(
self.db_lookup_mod,
"get_entity_name",
side_effect=self._fake_get_entity_name,
):
out = lookup.run(["web-app-foo"], variables=vars_)[0]
self.assertEqual(out["image"], "postgres")
self.assertEqual(out["version"], "17")
def test_local_flag_for_variant_disabling_dedicated_db(self):
applications = {
"web-app-foo": {
+332 -1
View File
@@ -5,6 +5,7 @@ import os
import tempfile
import unittest
from pathlib import Path
from typing import ClassVar
from unittest.mock import patch
from ansible.errors import AnsibleError
@@ -14,7 +15,7 @@ from utils.cache import _reset_cache_for_tests
from utils.cache import base as cache_base
from utils.cache import users as cache_users
from utils.cache.yaml import dump_yaml_str
from utils.roles.mapping import ROLE_FILE_META_SERVICES
from utils.roles.mapping import ROLE_FILE_META_DOMAINS, ROLE_FILE_META_SERVICES
def _write_role_config(base_dir: Path, role_name: str, payload: dict) -> None:
@@ -96,6 +97,7 @@ class TestEmailLookup(unittest.TestCase):
554 5.7.1. Plaintext submission is port 587; 25 is the inbound MX and
offers no AUTH at all."""
variables = {
"MAIL_PROVIDER": "web-app-mailu",
"groups": {"web-app-mailu": ["host1"]},
"SYSTEM_EMAIL_HOST": "mail.abc123.onion",
"TLS_ENABLED": True,
@@ -109,6 +111,7 @@ class TestEmailLookup(unittest.TestCase):
def test_clearnet_external_keeps_tls(self) -> None:
variables = {
"MAIL_PROVIDER": "web-app-mailu",
"groups": {"web-app-mailu": ["host1"]},
"SYSTEM_EMAIL_HOST": "mail.example.org",
"TLS_ENABLED": True,
@@ -143,6 +146,7 @@ class TestEmailLookup(unittest.TestCase):
for host, tls_enabled, external, expected in cases:
with self.subTest(host=host, tls=tls_enabled, external=external):
variables = {
"MAIL_PROVIDER": "web-app-mailu",
"groups": {"web-app-mailu": ["host1"]} if external else {},
"SYSTEM_EMAIL_HOST": host,
"TLS_ENABLED": tls_enabled,
@@ -168,6 +172,7 @@ class TestEmailLookup(unittest.TestCase):
for host, tls_enabled, external, expected in cases:
with self.subTest(host=host, external=external):
variables = {
"MAIL_PROVIDER": "web-app-mailu",
"groups": {"web-app-mailu": ["host1"]} if external else {},
"SYSTEM_EMAIL_HOST": host,
"TLS_ENABLED": tls_enabled,
@@ -240,6 +245,184 @@ class TestEmailLookup(unittest.TestCase):
with self.assertRaises(AnsibleError):
self.lookup.run(["a", "b"], variables={})
def test_an_onion_relay_never_announces_starttls(self) -> None:
# No CA issues a certificate for a .onion name, so a client that
# verifies the peer can never complete the handshake -- Ruby's
# Net::SMTP drops the mail after three silent retries. Tor already
# carries the confidentiality, which is why `tls` is False here too.
_write_role_config(
self._tmp,
"web-app-mailprov",
{"sso": {"oidc": {"submission_via_relay": True}}},
)
variables = {
"MAIL_PROVIDER": "web-app-mailprov",
"group_names": ["web-app-mailprov", "web-app-keycloak"],
"groups": {"web-app-mailprov": ["host1"], "web-app-keycloak": ["host1"]},
"TLS_ENABLED": True,
"SYSTEM_EMAIL_HOST": "mail." + "a" * 56 + ".onion",
"inventory_hostname": "host1",
}
result = self.lookup.run(
[], variables=variables, roles_dir=str(self._tmp / "roles")
)[0]
self.assertFalse(result["start_tls"])
self.assertFalse(result["tls"])
def test_sso_relay_provider_disables_auth_and_uses_port_25(self) -> None:
# submission_via_relay + Keycloak deployed -> relay on 25, no auth, STARTTLS.
_write_role_config(
self._tmp,
"web-app-mailprov",
{"sso": {"oidc": {"submission_via_relay": True}}},
)
variables = {
"MAIL_PROVIDER": "web-app-mailprov",
"group_names": ["web-app-mailprov", "web-app-keycloak"],
"groups": {"web-app-mailprov": ["host1"], "web-app-keycloak": ["host1"]},
"TLS_ENABLED": True,
"inventory_hostname": "host1",
}
result = self.lookup.run(
[], variables=variables, roles_dir=str(self._tmp / "roles")
)[0]
self.assertEqual(result["port"], 25)
self.assertFalse(result["auth"])
self.assertTrue(result["start_tls"])
def test_sso_relay_inactive_without_keycloak(self) -> None:
# Same provider, but Keycloak is not deployed: keep authenticated 465.
_write_role_config(
self._tmp,
"web-app-mailprov",
{"sso": {"oidc": {"submission_via_relay": True}}},
)
variables = {
"MAIL_PROVIDER": "web-app-mailprov",
"group_names": ["web-app-mailprov"],
"groups": {"web-app-mailprov": ["host1"]},
"TLS_ENABLED": True,
"inventory_hostname": "host1",
}
result = self.lookup.run(
[], variables=variables, roles_dir=str(self._tmp / "roles")
)[0]
self.assertEqual(result["port"], 465)
self.assertTrue(result["auth"])
self.assertFalse(result["start_tls"])
def test_sso_relay_inactive_when_sso_enabled_pinned_false(self) -> None:
# A variant pins the provider's sso.enabled to a literal false while
# submission_via_relay stays true (role default) and Keycloak is still
# deployed: the provider keeps password auth, so no relay mode.
_write_role_config(
self._tmp,
"web-app-mailprov",
{"sso": {"enabled": False, "oidc": {"submission_via_relay": True}}},
)
variables = {
"MAIL_PROVIDER": "web-app-mailprov",
"group_names": ["web-app-mailprov", "web-app-keycloak"],
"groups": {"web-app-mailprov": ["host1"], "web-app-keycloak": ["host1"]},
"TLS_ENABLED": True,
"inventory_hostname": "host1",
}
result = self.lookup.run(
[], variables=variables, roles_dir=str(self._tmp / "roles")
)[0]
self.assertEqual(result["port"], 465)
self.assertTrue(result["auth"])
self.assertFalse(result["start_tls"])
def test_a_provider_without_plaintext_submission_falls_back_to_its_mx(
self,
) -> None:
"""Stalwart's default config binds the implicit-TLS client ports and the
MX, never 587, so the onion path (which drops TLS) has no submission
listener to reach. The port follows what the provider declares, and AUTH
drops with it: an MX offers none, and announcing it aborts msmtp with
EX_UNAVAILABLE before a message is ever sent."""
_write_role_config(
self._tmp,
"web-app-mailprov",
{"mailprov": {"ports": {"public": {"smtp": 25, "smtps": 465}}}},
)
variables = {
"MAIL_PROVIDER": "web-app-mailprov",
"group_names": ["web-app-mailprov"],
"groups": {"web-app-mailprov": ["host1"]},
"SYSTEM_EMAIL_HOST": "mail.x.onion",
"TLS_ENABLED": True,
"DOMAIN_PRIMARY": "x.onion",
"inventory_hostname": "host1",
}
result = self.lookup.run(
[], variables=variables, roles_dir=str(self._tmp / "roles")
)[0]
self.assertFalse(result["tls"])
self.assertEqual(result["port"], 25)
self.assertFalse(result["auth"])
self.assertEqual(result["auth_mechanism"], "off")
def test_a_provider_declaring_submission_keeps_the_authenticated_path(
self,
) -> None:
"""Mailu binds 587, so the same onion target stays on plaintext
submission with AUTH PLAIN. The MX fallback above must not reach a
provider that declares a submission listener."""
_write_role_config(
self._tmp,
"web-app-mailprov",
{
"mailprov": {
"ports": {"public": {"smtp": 25, "smtps": 465, "submission": 587}}
}
},
)
variables = {
"MAIL_PROVIDER": "web-app-mailprov",
"group_names": ["web-app-mailprov"],
"groups": {"web-app-mailprov": ["host1"]},
"SYSTEM_EMAIL_HOST": "mail.x.onion",
"TLS_ENABLED": True,
"DOMAIN_PRIMARY": "x.onion",
"inventory_hostname": "host1",
}
result = self.lookup.run(
[], variables=variables, roles_dir=str(self._tmp / "roles")
)[0]
self.assertFalse(result["tls"])
self.assertEqual(result["port"], 587)
self.assertTrue(result["auth"])
self.assertEqual(result["auth_mechanism"], "plain")
def test_sso_relay_active_with_untemplated_enabled_gate(self) -> None:
# The role default gates sso.enabled on group_names (raw Jinja here);
# the guard must not treat the untemplated string as false.
_write_role_config(
self._tmp,
"web-app-mailprov",
{
"sso": {
"enabled": "{{ 'web-app-keycloak' in group_names }}",
"oidc": {"submission_via_relay": True},
}
},
)
variables = {
"MAIL_PROVIDER": "web-app-mailprov",
"group_names": ["web-app-mailprov", "web-app-keycloak"],
"groups": {"web-app-mailprov": ["host1"], "web-app-keycloak": ["host1"]},
"TLS_ENABLED": True,
"inventory_hostname": "host1",
}
result = self.lookup.run(
[], variables=variables, roles_dir=str(self._tmp / "roles")
)[0]
self.assertEqual(result["port"], 25)
self.assertFalse(result["auth"])
self.assertTrue(result["start_tls"])
def test_computed_defaults_are_templated(self) -> None:
self.lookup._templar = _DummyTemplar(
{"DOMAIN_PRIMARY_RESOLVED": "mail.example.org"}
@@ -252,6 +435,154 @@ class TestEmailLookup(unittest.TestCase):
self.assertEqual(result["domain"], "mail.example.org")
class TestProviderOnionIsClusterWide(unittest.TestCase):
"""In swarm only the manager is in svc-net-tor, so a worker renders the
provider's clearnet name while the provider (onion-primary on the
manager) never deployed a certificate for it. TLS must follow the
provider host's view, not the worker's."""
ONION = "a" * 56 + ".onion"
TOR_ON = "{{ 'svc-net-tor' in group_names }}"
STALWART_PORTS: ClassVar[dict[str, int]] = {"smtp": 25, "smtps": 465}
MAILU_PORTS: ClassVar[dict[str, int]] = {
"smtp": 25,
"smtps": 465,
"submission": 587,
}
@classmethod
def setUpClass(cls) -> None:
_reset_cache_for_tests()
cls.addClassCleanup(_reset_cache_for_tests)
def setUp(self) -> None:
from ansible.parsing.dataloader import DataLoader
from ansible.template import Templar
cache_base._reset()
_reset_cache_for_tests()
self.lookup = LookupModule()
self.lookup._templar = Templar(loader=DataLoader(), variables={})
self._cwd = str(Path.cwd())
self._tmpdir = tempfile.TemporaryDirectory()
self._tmp = Path(self._tmpdir.name)
(self._tmp / "roles").mkdir(parents=True, exist_ok=True)
os.chdir(self._tmp)
self._tokens_store_patcher = patch.object(
cache_users, "_load_store_users", return_value={}
)
self._tokens_store_patcher.start()
def tearDown(self) -> None:
self._tokens_store_patcher.stop()
os.chdir(self._cwd)
self._tmpdir.cleanup()
def _seed(self, *, ports, node=None, provider_tor=None) -> None:
"""Write the tor provider and the mail provider roles.
Args:
ports: the mail provider's published SMTP ports.
node: svc-net-tor's node onion; defaults to ``ONION``.
provider_tor: the mail provider's ``tor`` block; defaults to
enabled on svc-net-tor hosts, inheriting exclusive/primary.
"""
_write_role_config(
self._tmp,
"svc-net-tor",
{
"tor": {
"enabled": True,
"shared": True,
"exclusive": True,
"primary": True,
"node": self.ONION if node is None else node,
}
},
)
_write_role_config(
self._tmp,
"web-app-mailprov",
{
"mailprov": {"ports": {"public": ports}},
"tor": provider_tor or {"enabled": self.TOR_ON},
},
)
domains = self._tmp / "roles" / "web-app-mailprov" / ROLE_FILE_META_DOMAINS
domains.write_text(
dump_yaml_str({"canonical": {"mail": "mail.x.test"}, "aliases": []}),
encoding="utf-8",
)
def _worker(self, *, tor_hosts=("mgr",)) -> dict:
return {
"MAIL_PROVIDER": "web-app-mailprov",
"group_names": ["svc-swarm-node"],
"groups": {
"web-app-mailprov": ["mgr"],
"svc-net-tor": list(tor_hosts),
},
"hostvars": {
"mgr": {"group_names": ["web-app-mailprov", "svc-net-tor"]},
"other": {"group_names": ["svc-net-tor"]},
},
"SYSTEM_EMAIL_HOST": "mail.x.test",
"TLS_ENABLED": True,
"DOMAIN_PRIMARY": "x.test",
"inventory_hostname": "wrk",
}
def _run(self, variables: dict) -> dict:
return self.lookup.run(
[], variables=variables, roles_dir=str(self._tmp / "roles")
)[0]
def test_worker_of_an_onion_stalwart_drops_tls_and_auth(self) -> None:
self._seed(ports=self.STALWART_PORTS)
result = self._run(self._worker())
self.assertFalse(result["tls"])
self.assertFalse(result["start_tls"])
self.assertFalse(result["auth"])
self.assertEqual(result["port"], 25)
def test_worker_of_an_onion_mailu_keeps_plain_submission(self) -> None:
self._seed(ports=self.MAILU_PORTS)
result = self._run(self._worker())
self.assertFalse(result["tls"])
self.assertEqual(result["port"], 587)
self.assertTrue(result["auth"])
self.assertEqual(result["auth_mechanism"], "plain")
def test_tor_on_another_host_keeps_tls(self) -> None:
self._seed(ports=self.STALWART_PORTS)
result = self._run(self._worker(tor_hosts=("other",)))
self.assertTrue(result["tls"])
self.assertEqual(result["port"], 465)
def test_dual_stack_provider_keeps_tls(self) -> None:
self._seed(
ports=self.STALWART_PORTS,
provider_tor={"enabled": self.TOR_ON, "exclusive": False, "primary": False},
)
result = self._run(self._worker())
self.assertTrue(result["tls"])
def test_empty_tor_node_keeps_tls(self) -> None:
self._seed(ports=self.STALWART_PORTS, node="")
result = self._run(self._worker())
self.assertTrue(result["tls"])
class _DummyTemplar:
def __init__(self, available_variables: dict[str, str]) -> None:
self.available_variables = available_variables
@@ -37,6 +37,21 @@ class _DummyTemplar:
return value
class _RenderingTemplar:
"""A templar that actually resolves expressions, like the real one.
``_DummyTemplar`` returns its input unchanged, so it cannot expose a value
that only misbehaves while still an unrendered template.
"""
def __init__(self, available_variables=None, rendered=None):
self.available_variables = available_variables or {}
self._rendered = rendered or {}
def template(self, value):
return self._rendered.get(value, value)
def _email(external=True, host=RELAY):
return {"external": external, "host": host}
@@ -67,6 +82,18 @@ class TestSmtpHostLookup(unittest.TestCase):
vars_ = {"DOCKER_IN_CONTAINER": True, "DEPLOYMENT_MODE": "compose"}
self.assertEqual(self._resolve(vars_), "127.0.0.1")
def test_an_unrendered_group_var_still_reaches_the_rig_loopback(self):
"""DOCKER_IN_CONTAINER is a group_vars expression, and a lookup receives it
raw. Read unrendered it is neither true nor false, so the rig kept the
configured relay instead of loopback — and on an onion node that relay is a
.onion, which msmtp cannot route (EX_UNAVAILABLE, 'proxy failure')."""
raw = "{{ (ansible_facts['env']['container'] | default('')) != '' }}"
vars_ = {"DOCKER_IN_CONTAINER": raw, "DEPLOYMENT_MODE": "compose"}
lm = self.LookupModule()
lm._templar = _RenderingTemplar(vars_, {raw: True})
lm._loader = None
self.assertEqual(lm.run([_email()], variables=vars_)[0], "127.0.0.1")
def test_swarm_node_uses_loopback(self):
vars_ = {
"DOCKER_IN_CONTAINER": True,
@@ -224,6 +224,55 @@ class TestTorPortsLookup(unittest.TestCase):
self.assertEqual(collect_onion_ports(apps, ["web-app-nope"]), [])
def _mail_apps(self) -> dict:
"""Stalwart provides email; Mailu only covers it, as the migration round
deploys both."""
return self._apps(
**{
"web-app-stalwart": {
"stalwart": {
"provides": "email",
"ports": {
"public": {"smtp": 25, "imaps": 993},
"onion": {"smtp": True},
},
}
},
"web-app-mailu": {
"mailu": {
"covers": ["email"],
"ports": {
"public": {"smtp": 25, "submission": 587, "imap": 143},
"onion": {"smtp": True, "submission": True, "imap": True},
},
}
},
}
)
def test_a_coverer_keeps_its_ports_when_it_is_the_only_provider(self) -> None:
ports = collect_onion_ports(self._mail_apps(), ["web-app-mailu"])
self.assertEqual(ports, [25, 143, 587])
def test_a_coverer_is_skipped_when_another_deployed_role_provides(self) -> None:
"""The provider owns the host mail ports, so the co-tenant's forwards
would advertise endpoints nothing answers on."""
ports = collect_onion_ports(
self._mail_apps(), ["web-app-stalwart", "web-app-mailu"]
)
self.assertEqual(ports, [25])
def test_the_provider_keeps_its_own_ports_beside_a_coverer(self) -> None:
both = collect_onion_ports(
self._mail_apps(), ["web-app-stalwart", "web-app-mailu"]
)
self.assertEqual(
both, collect_onion_ports(self._mail_apps(), ["web-app-stalwart"])
)
def test_collect_onion_ports_ignores_non_mappings(self) -> None:
self.assertEqual(collect_onion_ports({}, ["a"]), [])
self.assertEqual(collect_onion_ports(None, ["a"]), [])
@@ -89,6 +89,20 @@ class TestBackupDatabaseContainers(unittest.TestCase):
out = lm.run([], variables={})
self.assertEqual(out, [[]])
def test_dedicated_sidecar_not_listed(self):
apps = {
"web-app-stalwart": {
"services": {
"postgres": {"enabled": True, "shared": False},
}
}
}
lm = _bare(db_mod, [])
with mock.patch.object(db_mod, "lookup_loader") as ll:
ll.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [apps])
out = lm.run([], variables={})
self.assertEqual(out, [[]])
class TestBackupHardRestartProjects(unittest.TestCase):
def test_returns_entity_names_with_marker(self):
@@ -0,0 +1,3 @@
from pathlib import Path
PROJECT_ROOT: Path = Path(__file__).resolve().parents[5]
@@ -0,0 +1,3 @@
from pathlib import Path
PROJECT_ROOT: Path = Path(__file__).resolve().parents[6]
@@ -0,0 +1,153 @@
"""What the Tor SMTP gateway accepts, and where it routes each recipient.
The gateway is not an open relay: it accepts a recipient ONLY when the domain
ends with ``.onion``, and it delivers each ``.onion`` domain's recipients in one
hop. The heavy dependencies (aiosmtpd, PySocks) are stubbed here so the routing
logic is testable without them, and ``_deliver`` is replaced so nothing dials
the network.
"""
from __future__ import annotations
import importlib.util
import os
import sys
import types
import unittest
from unittest import mock
from . import PROJECT_ROOT
MODULE = (
PROJECT_ROOT
/ "roles"
/ "svc-net-tor-smtp"
/ "files"
/ "python"
/ "tor_smtp_gateway.py"
)
REQUIRED_ENV = {
"TOR_SMTP_LISTEN_PORT": "1525",
"TOR_SOCKS_HOST": "tor",
"TOR_SOCKS_PORT": "9050",
"TOR_SMTP_HELO": "node.example.onion",
}
def _load(env=None):
"""Import the daemon with the required env stubbed. A None override drops
the key, so a test can assert a required var is missing."""
socks_stub = types.ModuleType("socks")
socks_stub.SOCKS5 = 2
socks_stub.create_connection = lambda *a, **k: None
controller_stub = types.ModuleType("aiosmtpd.controller")
controller_stub.Controller = object
aiosmtpd_pkg = types.ModuleType("aiosmtpd")
aiosmtpd_pkg.controller = controller_stub
merged = {k: v for k, v in {**REQUIRED_ENV, **(env or {})}.items() if v is not None}
with (
mock.patch.dict(
sys.modules,
{
"socks": socks_stub,
"aiosmtpd": aiosmtpd_pkg,
"aiosmtpd.controller": controller_stub,
},
),
mock.patch.dict(os.environ, merged, clear=True),
):
spec = importlib.util.spec_from_file_location("tor_smtp_gateway", MODULE)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
class _Envelope:
def __init__(self, mail_from="bot@x.onion", rcpt_tos=None, content=b"msg"):
self.mail_from = mail_from
self.rcpt_tos = list(rcpt_tos or [])
self.content = content
class TestDomainGrouping(unittest.TestCase):
def setUp(self):
self.mod = _load()
def test_recipients_group_by_domain(self):
grouped = self.mod._group_by_domain(
["a@one.onion", "b@one.onion", "c@two.onion"]
)
self.assertEqual(
grouped,
{"one.onion": ["a@one.onion", "b@one.onion"], "two.onion": ["c@two.onion"]},
)
def test_domain_match_is_case_insensitive(self):
grouped = self.mod._group_by_domain(["A@One.Onion"])
self.assertEqual(list(grouped), ["one.onion"])
class TestRcptGate(unittest.IsolatedAsyncioTestCase):
def setUp(self):
self.mod = _load()
self.relay = self.mod.OnionRelay()
async def _rcpt(self, address):
env = _Envelope(rcpt_tos=[])
reply = await self.relay.handle_RCPT(None, None, env, address, [])
return reply, env
async def test_an_onion_recipient_is_accepted(self):
reply, env = await self._rcpt("biber@abc.onion")
self.assertTrue(reply.startswith("250"))
self.assertEqual(env.rcpt_tos, ["biber@abc.onion"])
async def test_a_clearnet_recipient_is_refused(self):
reply, env = await self._rcpt("biber@infinito.test")
self.assertTrue(reply.startswith("550"))
self.assertEqual(env.rcpt_tos, [])
class TestDataDelivery(unittest.IsolatedAsyncioTestCase):
def setUp(self):
self.mod = _load()
self.relay = self.mod.OnionRelay()
async def test_each_onion_domain_gets_one_delivery(self):
calls = []
with mock.patch.object(
self.mod, "_deliver", side_effect=lambda *a: calls.append(a)
):
env = _Envelope(rcpt_tos=["a@one.onion", "b@one.onion", "c@two.onion"])
reply = await self.relay.handle_DATA(None, None, env)
self.assertTrue(reply.startswith("250"))
self.assertEqual({c[0] for c in calls}, {"one.onion", "two.onion"})
async def test_a_failed_hop_is_a_transient_error(self):
def boom(*_a):
raise OSError("tor down")
with mock.patch.object(self.mod, "_deliver", side_effect=boom):
env = _Envelope(rcpt_tos=["a@one.onion"])
reply = await self.relay.handle_DATA(None, None, env)
self.assertTrue(reply.startswith("451"))
class TestConfiguration(unittest.TestCase):
def test_the_helo_name_comes_from_the_environment(self):
mod = _load({"TOR_SMTP_HELO": "biber.node.onion"})
self.assertEqual(mod.HELO_NAME, "biber.node.onion")
def test_the_helo_never_falls_back_to_the_bind_address(self):
"""EHLO 0.0.0.0 is malformed; a missing HELO must fail loudly, not
silently announce the bind address to the peer."""
with self.assertRaises(KeyError):
_load({"TOR_SMTP_HELO": None})
def test_the_onion_hop_targets_the_well_known_smtp_port(self):
self.assertEqual(_load().ONION_SMTP_PORT, 25)
if __name__ == "__main__":
unittest.main()
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,107 @@
import os
import subprocess
import tempfile
import unittest
from pathlib import Path
from utils import PROJECT_ROOT
SCRIPT = PROJECT_ROOT / "roles/sys-ca-selfsigned/files/shell/with-ca-trust.sh"
TRUST_TOOLS = ("update-ca-certificates", "update-ca-trust", "trust", "certutil")
ANCHOR_WRITERS = ("mkdir", "cp")
PROBE = 'printf "%s\\n" "$SSL_CERT_FILE"; stat -c %a "$SSL_CERT_FILE"'
class TestWithCaTrust(unittest.TestCase):
def setUp(self):
self._tmp = tempfile.TemporaryDirectory()
self.root = Path(self._tmp.name)
self.bin_dir = self.root / "bin"
self.bin_dir.mkdir()
for tool in TRUST_TOOLS:
self._stub(tool, 0)
for tool in ANCHOR_WRITERS:
self._stub(tool, 1)
self.tmpdir = self.root / "tmp"
self.tmpdir.mkdir()
self.home = self.root / "home"
self.home.mkdir()
self.ca_cert = self.root / "root-ca.crt"
self.ca_cert.write_text("ROOT-CA\n")
def tearDown(self):
self._tmp.cleanup()
def _stub(self, name, code):
stub = self.bin_dir / name
stub.write_text(f"#!/bin/sh\nexit {code}\n")
stub.chmod(0o755)
def run_wrapper(self, **extra_env):
"""Run the wrapper around a probe printing the exported bundle.
Args:
extra_env: additional environment variables for the wrapper.
Returns:
Tuple of the exported SSL_CERT_FILE path and its octal mode.
"""
env = dict(os.environ)
env["PATH"] = f"{self.bin_dir}{os.pathsep}{env['PATH']}"
env["HOME"] = str(self.home)
env["TMPDIR"] = str(self.tmpdir)
env["VERBOSE"] = "0"
env["CA_TRUST_CERT"] = str(self.ca_cert)
env["CA_TRUST_NAME"] = "infinito.test"
env.pop("CA_TRUST_BUNDLE", None)
env.pop("CA_TRUST_CERT_EXTRA", None)
env.update(extra_env)
done = subprocess.run(
["sh", str(SCRIPT), "sh", "-c", PROBE],
env=env,
capture_output=True,
text=True,
check=False,
)
self.assertEqual(done.returncode, 0, done.stderr)
path, mode = done.stdout.split()
return path, mode
def test_readable_bundle_is_used_without_a_temp_file(self):
bundle = self.root / "ca-bundle.crt"
bundle.write_text("ROOT-CA\nPUBLIC-CA\n")
path, _ = self.run_wrapper(CA_TRUST_BUNDLE=str(bundle))
self.assertEqual(path, str(bundle))
self.assertEqual(list(self.tmpdir.iterdir()), [])
def test_extra_cert_bundle_is_world_readable(self):
bundle = self.root / "ca-bundle.crt"
bundle.write_text("ROOT-CA\nPUBLIC-CA\n")
extra = self.root / "extra.crt"
extra.write_text("EXTRA-CA\n")
path, mode = self.run_wrapper(
CA_TRUST_BUNDLE=str(bundle), CA_TRUST_CERT_EXTRA=str(extra)
)
self.assertEqual(mode, "644")
self.assertEqual(
Path(path).read_text(), # nocheck: cache-read
"ROOT-CA\nPUBLIC-CA\nEXTRA-CA\n",
)
def test_combined_system_bundle_is_world_readable(self):
path, mode = self.run_wrapper()
if path != str(self.ca_cert):
self.assertEqual(mode, "644")
combined = Path(path).read_text() # nocheck: cache-read
self.assertTrue(combined.endswith("ROOT-CA\n"))
if __name__ == "__main__":
unittest.main()
@@ -436,6 +436,90 @@ class TestComposeCaInject(unittest.TestCase):
state = self.m.docker_image_has_bin_sh("img:1", cwd=Path("/tmp"), env={})
self.assertIsNone(state)
def test_gather_one_image_pulls_when_absent(self):
"""An absent image is pulled + re-inspected so the /bin/sh probe is accurate."""
calls = []
def fake_run(cmd, *, cwd, env, timeout=None, capture=True):
calls.append(cmd)
if cmd[:3] == ["docker", "image", "inspect"]:
if ["docker", "pull", "img:1"] in calls:
cfg = [{"Config": {"Entrypoint": ["/entry.sh"], "Cmd": ["run"]}}]
return 0, json.dumps(cfg), ""
return 1, "", "No such image: img:1"
if cmd[:2] == ["docker", "pull"]:
return 0, "", ""
if cmd[:5] == ["docker", "run", "--rm", "--entrypoint", "/bin/sh"]:
return 0, "", ""
return 1, "", "unexpected"
with patch.object(self.m, "run", side_effect=fake_run):
exists, ep, cmd, has_sh = self.m._gather_one_image(
"img:1", cwd=Path("/tmp"), env={}
)
self.assertTrue(exists)
self.assertEqual(ep, ["/entry.sh"])
self.assertEqual(cmd, ["run"])
self.assertTrue(has_sh)
self.assertIn(["docker", "pull", "img:1"], calls)
def test_gather_one_image_no_pull_when_present(self):
"""When the image is already present, `_gather_one_image` must NOT pull."""
calls = []
def fake_run(cmd, *, cwd, env, timeout=None, capture=True):
calls.append(cmd)
if cmd[:3] == ["docker", "image", "inspect"]:
cfg = [{"Config": {"Entrypoint": ["/entry.sh"], "Cmd": ["run"]}}]
return 0, json.dumps(cfg), ""
if cmd[:5] == ["docker", "run", "--rm", "--entrypoint", "/bin/sh"]:
return 0, "", ""
return 1, "", "unexpected"
with patch.object(self.m, "run", side_effect=fake_run):
exists, _ep, _cmd, has_sh = self.m._gather_one_image(
"img:1", cwd=Path("/tmp"), env={}
)
self.assertTrue(exists)
self.assertTrue(has_sh)
self.assertNotIn(["docker", "pull", "img:1"], calls)
def test_gather_one_image_never_pulls_built_tags(self):
"""A locally-built tag must not be pulled: the registry would serve an
unrelated base image whose CMD then gets pinned into the override."""
calls = []
def fake_run(cmd, *, cwd, env, timeout=None, capture=True):
calls.append(cmd)
if cmd[:3] == ["docker", "image", "inspect"]:
return 1, "", "No such image: python:3.14-slim"
return 1, "", "unexpected"
with patch.object(self.m, "run", side_effect=fake_run):
exists, _ep, _cmd, _has_sh = self.m._gather_one_image(
"python:3.14-slim", cwd=Path("/tmp"), env={}, pull_if_absent=False
)
self.assertFalse(exists)
self.assertFalse(any(c[:2] == ["docker", "pull"] for c in calls))
def test_gather_image_meta_skips_pull_for_built_images(self):
"""gather_image_meta must route built tags through pull_if_absent=False."""
seen = {}
def fake_gather(image, *, cwd, env, pull_if_absent=True):
seen[image] = pull_if_absent
return (False, [], [], False)
with patch.object(self.m, "_gather_one_image", side_effect=fake_gather):
self.m.gather_image_meta(
["built:1", "pulled:1"],
cwd=Path("/tmp"),
env={},
built_images={"built:1"},
)
self.assertFalse(seen["built:1"])
self.assertTrue(seen["pulled:1"])
def test_render_override_wraps_when_probe_ambiguous(self):
services = {"svc": {"image": "img:1"}}
service_to_cmd = {"svc": ["docker", "compose", "-p", "p", "-f", "compose.yml"]}
@@ -916,7 +1000,12 @@ class TestComposeCaInject(unittest.TestCase):
self.assertIn(
f"{Path(tmp) / 'ca-bundle.crt'}:{bundle_container}:ro", out["volumes"]
)
for key in ("SSL_CERT_FILE", "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE"):
for key in (
"SSL_CERT_FILE",
"CURL_CA_BUNDLE",
"REQUESTS_CA_BUNDLE",
"CA_TRUST_BUNDLE",
):
self.assertEqual(out["environment"].get(key), bundle_container)
self.assertEqual(
out["environment"].get("NODE_EXTRA_CA_CERTS"), CA_CERT_CONTAINER
@@ -953,6 +1042,7 @@ class TestComposeCaInject(unittest.TestCase):
out = doc["services"]["svc"]
self.assertIn("volumes", out)
self.assertEqual(out["environment"].get("SSL_CERT_FILE"), CA_CERT_CONTAINER)
self.assertNotIn("CA_TRUST_BUNDLE", out["environment"])
self.assertNotIn("entrypoint", out)
self.assertNotIn("command", out)
p_ensure.assert_not_called()
@@ -14,7 +14,9 @@ filter shim, since ``bool`` is an Ansible filter.
from __future__ import annotations
import re
import unittest
from typing import Any, ClassVar
from jinja2 import Environment, StrictUndefined
@@ -48,17 +50,38 @@ def _env() -> Environment:
)
env.filters["bool"] = bool
env.filters["on_off"] = lambda value: "on" if value else "off"
env.filters["regex_replace"] = lambda value, pattern, repl="": re.sub(
pattern, repl, str(value)
)
return env
def _render(*, in_container: bool, ca_injected: bool, **extra) -> str:
def _render(
*, in_container: bool, ca_injected: bool, email=None, smtp_host=None, **extra
) -> str:
"""Render msmtprc.
Args:
in_container: whether the rendered file is mounted into a container.
ca_injected: what the ca_injected lookup reports.
email: the email mapping the lookup returns.
smtp_host: the host smtp_host resolves to. Defaults to the configured
relay, which is what the resolver returns outside the rig; pass
loopback to exercise the in-rig path.
"""
email_config = email if email is not None else EMAIL
def lookup(kind, *args, **kwargs):
if kind == "email":
return EMAIL
return email_config
if kind == "smtp_host":
return "relay"
return smtp_host if smtp_host is not None else email_config["host"]
if kind == "ca_injected":
return ca_injected
if kind == "tor_socks_proxy":
return "socks5h://tor:9050"
if kind == "tor_socks":
return "127.0.0.1:9050"
raise AssertionError(f"unexpected lookup: {kind}")
template = _env().from_string(read_text(str(TEMPLATE)))
@@ -70,6 +93,7 @@ def _render(*, in_container: bool, ca_injected: bool, **extra) -> str:
"inject_cert_container": CA_CONTAINER,
"inject_bundle_container": CA_BUNDLE_CONTAINER,
},
DOMAIN_PRIMARY="infinito.example",
**extra,
)
@@ -108,5 +132,62 @@ class TestMsmtprcCaTrust(unittest.TestCase):
)
class TestMsmtprcOnionProxy(unittest.TestCase):
"""Reaching a .onion relay at all.
A .onion peer has no route off the node, so msmtp has to hand the connection
to Tor's SOCKS5 listener. Without it every send fails "cannot connect ...
Connection refused" and the hlth-msmtp unit takes the deploy down with it.
"""
ONION_EMAIL: ClassVar[dict[str, Any]] = dict(
EMAIL, host="mail.abc123.onion", tls=False, port=25
)
def _proxy(self, rendered: str) -> dict[str, str]:
found = {}
for line in rendered.splitlines():
parts = line.split()
if len(parts) == 2 and parts[0] in ("proxy_host", "proxy_port"):
found[parts[0]] = parts[1]
return found
def test_a_clearnet_relay_names_no_proxy(self):
rendered = _render(in_container=False, ca_injected=False)
self.assertEqual(self._proxy(rendered), {})
def test_an_onion_relay_is_reached_through_the_node_socks_listener(self):
rendered = _render(
in_container=False, ca_injected=False, email=self.ONION_EMAIL
)
self.assertEqual(
self._proxy(rendered), {"proxy_host": "127.0.0.1", "proxy_port": "9050"}
)
def test_a_rig_loopback_target_is_never_routed_through_tor(self):
"""Inside the rig smtp_host returns loopback even when the provider's canonical
is an onion. Gating the proxy on email.host instead of the dialled host sent
127.0.0.1 through Tor, and every send hung until the timeout killed it
(rc=124)."""
rendered = _render(
in_container=False,
ca_injected=False,
email=self.ONION_EMAIL,
smtp_host="127.0.0.1",
)
self.assertEqual(self._proxy(rendered), {})
def test_a_container_render_reaches_tor_over_the_shared_endpoint(self):
rendered = _render(
in_container=True,
ca_injected=False,
email=self.ONION_EMAIL,
application_id="web-app-moodle",
)
self.assertEqual(
self._proxy(rendered), {"proxy_host": "tor", "proxy_port": "9050"}
)
if __name__ == "__main__":
unittest.main()
@@ -5,6 +5,8 @@ from pathlib import Path
from ansible.errors import AnsibleFilterError
from utils.cache.yaml import dump_yaml_str
from . import PROJECT_ROOT
@@ -56,6 +58,53 @@ class TestDiscoverPlaywrightRoles(unittest.TestCase):
result = _plugin.discover_playwright_roles(str(self.playbook_dir))
self.assertEqual(result, ["web-app-alpha", "web-app-zeta"])
def _declare_run_after(
self, role_name: str, run_after: list[str], provides: str | None = None
) -> None:
meta_dir = self.playbook_dir / "roles" / role_name / "meta"
meta_dir.mkdir(parents=True, exist_ok=True)
(meta_dir / "main.yml").write_text("---\n", encoding="utf-8")
entity = role_name.removeprefix("web-app-")
primary = {"run_after": run_after}
if provides:
primary["provides"] = provides
(meta_dir / "services.yml").write_text(
dump_yaml_str({entity: primary}), encoding="utf-8"
)
def test_the_sso_provider_runs_first_even_after_its_mail_provider(self):
self._create_role("web-app-idp", with_marker=True)
self._create_role("web-app-mail", with_marker=True)
self._create_role("web-app-app", with_marker=True)
self._declare_run_after("web-app-idp", ["web-app-mail"], provides="sso")
self._declare_run_after("web-app-mail", [])
self._declare_run_after("web-app-app", ["web-app-idp"])
result = _plugin.discover_playwright_roles(str(self.playbook_dir))
self.assertEqual(result, ["web-app-idp", "web-app-mail", "web-app-app"])
def test_a_provider_runs_before_its_consumer_whatever_the_names(self):
self._create_role("web-app-alpha", with_marker=True)
self._create_role("web-app-zeta", with_marker=True)
self._declare_run_after("web-app-alpha", ["web-app-zeta"])
self._declare_run_after("web-app-zeta", [])
result = _plugin.discover_playwright_roles(str(self.playbook_dir))
self.assertEqual(result, ["web-app-zeta", "web-app-alpha"])
def test_the_order_holds_through_a_provider_without_specs(self):
self._create_role("web-app-alpha", with_marker=True)
self._create_role("web-app-mid", with_marker=False)
self._create_role("web-app-zeta", with_marker=True)
self._declare_run_after("web-app-alpha", ["web-app-mid"])
self._declare_run_after("web-app-mid", ["web-app-zeta"])
self._declare_run_after("web-app-zeta", [])
result = _plugin.discover_playwright_roles(
str(self.playbook_dir), only_roles="web-app-alpha,web-app-zeta"
)
self.assertEqual(result, ["web-app-zeta", "web-app-alpha"])
def test_only_and_skip_accept_csv_and_iterable(self):
self._create_role("web-app-a", with_marker=True)
self._create_role("web-app-b", with_marker=True)
@@ -0,0 +1,3 @@
from pathlib import Path
PROJECT_ROOT: Path = Path(__file__).resolve().parents[5]
@@ -0,0 +1,111 @@
"""Whether GitLab announces SMTP AUTH, and on which listener.
Ruby's ``net/smtp`` authenticates whenever a ``user_name`` or ``password`` is
present, falling back to its default auth type — ``authentication: nil`` does
NOT switch it off. So on the provider's SSO relay, where port 25 offers no
AUTH at all, leaving the credentials in the hash makes every send die with
``503 5.5.1 AUTH not allowed`` while GitLab still reports the mail as queued.
The credentials therefore have to be omitted, not merely unaccompanied by an
auth type.
``tls`` and ``enable_starttls_auto`` are the other half: they are mutually
exclusive in ActionMailer, implicit TLS on 465 or STARTTLS on the relay.
"""
from __future__ import annotations
import re
import unittest
from jinja2 import Environment, StrictUndefined
from utils.cache.files import read_text
from . import PROJECT_ROOT
TEMPLATE = (
PROJECT_ROOT
/ "roles"
/ "web-app-gitlab"
/ "templates"
/ "config"
/ "smtp_settings.rb.j2"
)
RELAY = {
"host": "mail.infinito.test",
"port": 25,
"username": "no-reply@infinito.test",
"password": "s3cr3t",
"domain": "infinito.test",
"auth": False,
"start_tls": True,
"tls": False,
}
SUBMISSION = dict(RELAY, port=465, auth=True, start_tls=False, tls=True)
def _render(email: dict, ca_file: str = "") -> str:
env = Environment(
trim_blocks=True,
lstrip_blocks=True,
undefined=StrictUndefined,
autoescape=False, # noqa: S701 - a Ruby config file, and Ansible's templar does not escape either
)
env.filters["bool"] = bool
env.filters["ruby_dq"] = lambda value: '"' + str(value).replace('"', '\\"') + '"'
return env.from_string(read_text(TEMPLATE)).render(
GITLAB_EMAIL=email,
GITLAB_EMAIL_CA_FILE=ca_file,
)
class TestGitlabSmtpSettings(unittest.TestCase):
def test_verification_is_never_weakened(self):
"""An onion relay is handled by turning start_tls off in the email
lookup, not by telling Net::SMTP to skip peer verification."""
self.assertNotIn("openssl_verify_mode", _render(RELAY))
def test_our_own_ca_is_trusted_where_it_is_mounted(self):
rendered = _render(RELAY, ca_file="/tmp/infinito/ca/root-ca.crt")
self.assertIn('ca_file: "/tmp/infinito/ca/root-ca.crt"', rendered)
def test_without_our_ca_no_trust_store_override_is_emitted(self):
self.assertNotIn("ca_file", _render(RELAY))
def test_the_relay_carries_no_credentials_at_all(self):
rendered = _render(RELAY)
self.assertNotIn("user_name", rendered)
self.assertNotIn("password", rendered)
self.assertNotIn("s3cr3t", rendered)
def test_the_relay_announces_no_auth_type(self):
self.assertNotIn("authentication", _render(RELAY))
def test_authenticated_submission_still_sends_credentials(self):
rendered = _render(SUBMISSION)
self.assertIn('user_name: "no-reply@infinito.test"', rendered)
self.assertIn("authentication: :login", rendered)
def test_tls_and_starttls_are_never_both_on(self):
for email in (RELAY, SUBMISSION):
rendered = _render(email)
tls = re.search(r"^\s*tls:\s*(\w+)", rendered, re.MULTILINE).group(1)
starttls = re.search(
r"^\s*enable_starttls_auto:\s*(\w+)", rendered, re.MULTILINE
).group(1)
self.assertNotEqual((tls, starttls), ("true", "true"))
def test_the_relay_uses_starttls_and_the_submission_port_implicit_tls(self):
self.assertIn("enable_starttls_auto: true", _render(RELAY))
self.assertIn("tls: false", _render(RELAY))
self.assertIn("tls: true", _render(SUBMISSION))
def test_the_hash_stays_syntactically_valid_without_credentials(self):
rendered = _render(RELAY).strip()
self.assertTrue(rendered.endswith("}"))
self.assertNotIn(",\n}", rendered)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,109 @@
"""Which Keycloak clients get converged, and — more importantly — which do not.
The realm import also carries Keycloak's own built-in clients (``account``,
``broker``, ``realm-management`` ...). Converging those would be wrong, so the
set is taken from what applications declare about themselves rather than from
the realm document. An application that declares nothing contributes nothing,
which is what keeps this a no-op for every app that needs only the one shared
client.
"""
from __future__ import annotations
import importlib.util
import unittest
from pathlib import Path
PLUGIN = (
Path(__file__).parent
/ "../../../../../../roles/web-app-keycloak/filter_plugins/oidc_clients.py"
).resolve()
def _load():
spec = importlib.util.spec_from_file_location("oidc_clients", PLUGIN)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _app(clients):
return {"services": {"sso": {"oidc": {"clients": clients}}}}
class TestDeclaredClientApps(unittest.TestCase):
def setUp(self):
self.apps = _load().kc_declared_client_apps
def test_only_declaring_apps_are_listed(self):
apps = {
"web-app-stalwart": _app({"webui": "stalwart-webui"}),
"web-app-nextcloud": {"services": {"sso": {"oidc": {}}}},
}
self.assertEqual(
self.apps(apps, ["web-app-stalwart", "web-app-nextcloud"]),
["web-app-stalwart"],
)
def test_an_undeployed_app_is_not_listed(self):
apps = {"web-app-stalwart": _app({"webui": "stalwart-webui"})}
self.assertEqual(self.apps(apps, ["web-app-other"]), [])
def test_a_malformed_map_is_survivable(self):
self.assertEqual(self.apps(None, ["a"]), [])
class TestDeclaredClientIds(unittest.TestCase):
def setUp(self):
self.ids = _load().kc_declared_client_ids
def test_an_application_contributes_the_clients_it_declares(self):
apps = {
"web-app-stalwart": _app(
{"webui": "stalwart-webui", "webmail": "stalwart-webmail"}
)
}
self.assertEqual(
self.ids(apps, ["web-app-stalwart"]),
["stalwart-webmail", "stalwart-webui"],
)
def test_an_application_that_declares_nothing_contributes_nothing(self):
apps = {"web-app-nextcloud": {"services": {"sso": {"oidc": {}}}}}
self.assertEqual(self.ids(apps, ["web-app-nextcloud"]), [])
def test_keycloak_builtins_are_never_included(self):
"""They live in the realm document, not in any application's declaration."""
apps = {"web-app-stalwart": _app({"webui": "stalwart-webui"})}
self.assertNotIn("account", self.ids(apps, ["web-app-stalwart"]))
self.assertNotIn("realm-management", self.ids(apps, ["web-app-stalwart"]))
def test_an_undeployed_application_is_not_consulted(self):
apps = {
"web-app-stalwart": _app({"webui": "stalwart-webui"}),
"web-app-other": _app({"main": "other-client"}),
}
self.assertEqual(self.ids(apps, ["web-app-other"]), ["other-client"])
def test_duplicate_declarations_collapse(self):
apps = {
"a": _app({"one": "shared-client"}),
"b": _app({"two": "shared-client"}),
}
self.assertEqual(self.ids(apps, ["a", "b"]), ["shared-client"])
def test_blank_and_non_string_declarations_are_ignored(self):
apps = {"a": _app({"ok": "real", "blank": " ", "wrong": 7, "none": None})}
self.assertEqual(self.ids(apps, ["a"]), ["real"])
def test_a_malformed_application_map_is_survivable(self):
self.assertEqual(self.ids(None, ["a"]), [])
self.assertEqual(self.ids({"a": "not-a-dict"}, ["a"]), [])
def test_no_app_ids_means_every_application_in_the_map(self):
apps = {"a": _app({"one": "client-a"}), "b": _app({"one": "client-b"})}
self.assertEqual(self.ids(apps), ["client-a", "client-b"])
if __name__ == "__main__":
unittest.main()
@@ -2,6 +2,7 @@ from __future__ import annotations
import importlib.util
import json
import re
import unittest
from jinja2 import Environment, FileSystemLoader, StrictUndefined
@@ -90,12 +91,14 @@ def fake_lookup(name, *_args, **_kwargs):
"""
if name == "email":
return {"enabled": False}
if name == "config":
return str(_args[-1]).rsplit(".", 1)[-1]
return APP_URL
def render(saml_apps: list[str]) -> str:
def render(saml_apps: list[str], client_apps: list[str] | None = None) -> str:
env = Environment(
loader=FileSystemLoader(str(IMPORT_DIR)),
loader=FileSystemLoader([str(IMPORT_DIR), str(PROJECT_ROOT)]),
trim_blocks=True,
keep_trailing_newline=True,
undefined=StrictUndefined,
@@ -104,9 +107,13 @@ def render(saml_apps: list[str]) -> str:
env.filters["path_join"] = path_join
env.filters["to_json"] = json.dumps
env.filters["bool"] = bool
env.filters["regex_replace"] = lambda value, pattern, repl="": re.sub(
pattern, repl, str(value)
)
env.filters.update(role_filters())
return env.get_template("realm.json.j2").render(
KEYCLOAK_SAML_APPS=saml_apps,
KEYCLOAK_DECLARED_CLIENT_APPS=client_apps or [],
lookup=fake_lookup,
application_id="web-app-keycloak",
DOMAIN_PRIMARY="example.com",
@@ -115,6 +122,18 @@ def render(saml_apps: list[str]) -> str:
class TestRealmImportJson(unittest.TestCase):
def test_app_declared_clients_join_the_realm(self) -> None:
"""An app in KEYCLOAK_DECLARED_CLIENT_APPS ships its own client fragment."""
realm = json.loads(render([], client_apps=["web-app-stalwart"]))
client_ids = [c["clientId"] for c in realm["clients"]]
self.assertIn("webui", client_ids)
self.assertIn("webmail", client_ids)
def test_no_declaring_apps_means_no_extra_clients(self) -> None:
with_apps = json.loads(render([], client_apps=["web-app-stalwart"]))
without = json.loads(render([]))
self.assertEqual(len(with_apps["clients"]) - len(without["clients"]), 2)
def test_realm_is_valid_json_without_saml_apps(self) -> None:
realm = json.loads(render([]))
client_ids = [c["clientId"] for c in realm["clients"]]
@@ -0,0 +1,3 @@
from pathlib import Path
PROJECT_ROOT: Path = Path(__file__).resolve().parents[5]
@@ -0,0 +1,3 @@
from pathlib import Path
PROJECT_ROOT: Path = Path(__file__).resolve().parents[6]
@@ -0,0 +1,156 @@
import importlib.util
import sys
import tempfile
import unittest
from pathlib import Path
from . import PROJECT_ROOT
def _load_module():
path = PROJECT_ROOT / "roles/web-app-stalwart/files/python/migrate_from_mailu.py"
spec = importlib.util.spec_from_file_location("migrate_from_mailu", str(path))
mod = importlib.util.module_from_spec(spec)
assert spec and spec.loader
sys.modules["migrate_from_mailu"] = mod
spec.loader.exec_module(mod)
return mod
class _FakeImap:
"""Minimal IMAP fake capturing the calls migrate_account issues."""
def __init__(self, existing_headers: list[bytes] | None = None):
self.created: list[str] = []
self.selected: list[str] = []
self.appended: list[tuple[str, str | None, bytes]] = []
self._existing_headers = existing_headers or []
def create(self, mailbox):
self.created.append(mailbox)
return "OK", [b""]
def select(self, mailbox, readonly=False):
self.selected.append(mailbox)
return "OK", [str(len(self._existing_headers)).encode()]
def search(self, charset, *criteria):
nums = b" ".join(
str(i + 1).encode() for i in range(len(self._existing_headers))
)
return "OK", [nums]
def fetch(self, message_set, message_parts):
data = [
((f"{i + 1} ()").encode(), header)
for i, header in enumerate(self._existing_headers)
]
return "OK", data
def append(self, mailbox, flags, date_time, message):
self.appended.append((mailbox, flags, message))
return "OK", [b""]
class TestFlagAndFolderMapping(unittest.TestCase):
def setUp(self):
self.m = _load_module()
def test_maildir_flags_to_imap(self):
self.assertEqual(self.m.maildir_flags_to_imap("123.M1.host:2,S"), "(\\Seen)")
self.assertEqual(
self.m.maildir_flags_to_imap("123.M1.host:2,FS"),
"(\\Flagged \\Seen)",
)
self.assertEqual(self.m.maildir_flags_to_imap("123.M1.host:2,"), "")
self.assertEqual(self.m.maildir_flags_to_imap("123.M1.host"), "")
self.assertEqual(self.m.maildir_flags_to_imap("a:2,XR"), "(\\Answered)")
def test_maildir_folder_to_imap(self):
self.assertEqual(self.m.maildir_folder_to_imap("", "/"), "INBOX")
self.assertEqual(self.m.maildir_folder_to_imap(".Archive", "/"), "Archive")
self.assertEqual(
self.m.maildir_folder_to_imap(".Archive.2024", "/"), "Archive/2024"
)
self.assertEqual(
self.m.maildir_folder_to_imap(".Archive.2024", "."), "Archive.2024"
)
def test_extract_message_id(self):
raw = b"Message-ID: <x@y>\r\nSubject: s\r\n\r\nbody"
self.assertEqual(self.m.extract_message_id(raw), "<x@y>")
self.assertEqual(self.m.extract_message_id(b"Subject: s\r\n\r\n"), "")
class TestMaildirWalk(unittest.TestCase):
def setUp(self):
self.m = _load_module()
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.account = Path(self.tmp.name) / "alice@example.test"
for folder in ("", ".Archive"):
base = self.account / folder if folder else self.account
for sub in ("cur", "new", "tmp"):
(base / sub).mkdir(parents=True)
(self.account / "cur" / "1.host:2,S").write_bytes(b"Message-ID: <1@x>\r\n\r\na")
(self.account / "new" / "2.host").write_bytes(b"Message-ID: <2@x>\r\n\r\nb")
(self.account / ".Archive" / "cur" / "3.host:2,").write_bytes(
b"Message-ID: <3@x>\r\n\r\nc"
)
(self.account / ".dovecot.sieve.d").mkdir()
def test_iter_maildir_folders_and_messages(self):
folders = self.m.iter_maildir_folders(self.account)
self.assertEqual([name for name, _ in folders], ["", ".Archive"])
root_msgs = self.m.iter_messages(self.account)
self.assertEqual([p.name for p in root_msgs], ["1.host:2,S", "2.host"])
def test_migrate_account_appends_and_dedups(self):
imap = _FakeImap()
stats = self.m.AccountStats()
self.m.migrate_account(imap, self.account, "/", stats)
self.assertEqual(stats.folder("INBOX").appended, 2)
self.assertEqual(stats.folder("Archive").appended, 1)
self.assertEqual(imap.created, ["Archive"])
self.assertEqual(
[(mailbox, flags) for mailbox, flags, _ in imap.appended],
[("INBOX", "(\\Seen)"), ("INBOX", None), ("Archive", None)],
)
def test_migrate_account_skips_existing_message_ids(self):
imap = _FakeImap(
existing_headers=[
b"Message-ID: <1@x>\r\n\r\n",
b"Message-ID: <3@x>\r\n\r\n",
]
)
stats = self.m.AccountStats()
self.m.migrate_account(imap, self.account, "/", stats)
self.assertEqual(stats.folder("INBOX").appended, 1)
self.assertEqual(stats.folder("INBOX").skipped, 1)
self.assertEqual(stats.folder("Archive").skipped, 1)
self.assertEqual(stats.folder("Archive").appended, 0)
class TestExistingMessageIds(unittest.TestCase):
def setUp(self):
self.m = _load_module()
def test_collects_ids_from_fetch(self):
imap = _FakeImap(
existing_headers=[
b"Message-ID: <a@x>\r\n\r\n",
b"Message-ID: <b@x>\r\n\r\n",
]
)
imap.select("INBOX")
self.assertEqual(self.m.existing_message_ids(imap), {"<a@x>", "<b@x>"})
def test_empty_folder(self):
imap = _FakeImap()
imap.select("INBOX")
self.assertEqual(self.m.existing_message_ids(imap), set())
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,536 @@
import argparse
import importlib.util
import socket
import struct
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock
from . import PROJECT_ROOT
def _load_module():
path = PROJECT_ROOT / "roles/web-app-stalwart/files/python/production_facts.py"
spec = importlib.util.spec_from_file_location("production_facts", str(path))
mod = importlib.util.module_from_spec(spec)
assert spec and spec.loader
sys.modules["production_facts"] = mod
spec.loader.exec_module(mod)
return mod
_M = _load_module()
def _txt_rdata(*chunks: str) -> bytes:
out = b""
for chunk in chunks:
raw = chunk.encode()
out += bytes([len(raw)]) + raw
return out
def _response(txid, qname, qtype, answers, *, rcode=0, truncated=False, compress=False):
"""Build a DNS response packet; ``answers`` is a list of (type, rdata)."""
flags = 0x8180 | rcode
if truncated:
flags |= 0x0200
header = struct.pack("!HHHHHH", txid, flags, 1, len(answers), 0, 0)
question = _M.encode_name(qname) + struct.pack("!HH", qtype, 1)
body = b""
for atype, rdata in answers:
name = b"\xc0\x0c" if compress else _M.encode_name(qname)
body += name + struct.pack("!HHIH", atype, 1, 300, len(rdata)) + rdata
return header + question + body
class TestNameCodec(unittest.TestCase):
def test_encode_decode_roundtrip(self):
encoded = _M.encode_name("mail.example.org")
name, offset = _M.decode_name(encoded, 0)
self.assertEqual(name, "mail.example.org")
self.assertEqual(offset, len(encoded))
def test_trailing_dot_is_ignored(self):
self.assertEqual(_M.encode_name("a.b."), _M.encode_name("a.b"))
def test_compression_pointer_does_not_advance_cursor(self):
buf = b"\x00" * 12 + _M.encode_name("mail.example.org") + b"\xc0\x0c"
pointer_at = len(buf) - 2
name, offset = _M.decode_name(buf, pointer_at)
self.assertEqual(name, "mail.example.org")
self.assertEqual(offset, pointer_at + 2)
def test_pointer_loop_is_rejected(self):
buf = b"\x00" * 12 + b"\xc0\x0c"
with self.assertRaises(_M.DnsError):
_M.decode_name(buf, 12)
def test_truncated_name_is_rejected(self):
with self.assertRaises(_M.DnsError):
_M.decode_name(b"\x05ab", 0)
class TestQueryBuilder(unittest.TestCase):
def test_header_and_question(self):
packet = _M.build_query("example.org", _M.TYPE_MX, 0x1234)
txid, flags, qdcount, ancount, _ns, _ar = struct.unpack("!HHHHHH", packet[:12])
self.assertEqual(txid, 0x1234)
self.assertEqual(flags, 0x0100)
self.assertEqual(qdcount, 1)
self.assertEqual(ancount, 0)
name, offset = _M.decode_name(packet, 12)
self.assertEqual(name, "example.org")
self.assertEqual(
struct.unpack("!HH", packet[offset : offset + 4]), (_M.TYPE_MX, 1)
)
class TestParseResponse(unittest.TestCase):
def test_a_record(self):
raw = _response(
1,
"mail.example.org",
_M.TYPE_A,
[(_M.TYPE_A, socket.inet_aton("203.0.113.5"))],
)
self.assertEqual(_M.parse_response(raw, 1, _M.TYPE_A), ["203.0.113.5"])
def test_txt_record_joins_chunks(self):
raw = _response(
2,
"example.org",
_M.TYPE_TXT,
[(_M.TYPE_TXT, _txt_rdata("v=spf1 ", "mx ~all"))],
)
self.assertEqual(_M.parse_response(raw, 2, _M.TYPE_TXT), ["v=spf1 mx ~all"])
def test_mx_record(self):
rdata = struct.pack("!H", 10) + _M.encode_name("mail.example.org")
raw = _response(3, "example.org", _M.TYPE_MX, [(_M.TYPE_MX, rdata)])
self.assertEqual(
_M.parse_response(raw, 3, _M.TYPE_MX), [(10, "mail.example.org")]
)
def test_srv_record(self):
rdata = struct.pack("!HHH", 20, 1, 465) + _M.encode_name("mail.example.org")
raw = _response(
4, "_submissions._tcp.example.org", _M.TYPE_SRV, [(_M.TYPE_SRV, rdata)]
)
self.assertEqual(
_M.parse_response(raw, 4, _M.TYPE_SRV), [(20, 1, 465, "mail.example.org")]
)
def test_ptr_record(self):
rdata = _M.encode_name("mail.example.org")
raw = _response(
5, "5.113.0.203.in-addr.arpa", _M.TYPE_PTR, [(_M.TYPE_PTR, rdata)]
)
self.assertEqual(_M.parse_response(raw, 5, _M.TYPE_PTR), ["mail.example.org"])
def test_compressed_answer_name_is_skipped_correctly(self):
raw = _response(
6,
"mail.example.org",
_M.TYPE_A,
[(_M.TYPE_A, socket.inet_aton("198.51.100.9"))],
compress=True,
)
self.assertEqual(_M.parse_response(raw, 6, _M.TYPE_A), ["198.51.100.9"])
def test_other_answer_types_are_filtered_out(self):
answers = [
(_M.TYPE_CNAME, _M.encode_name("real.example.org")),
(_M.TYPE_A, socket.inet_aton("203.0.113.7")),
]
raw = _response(7, "mail.example.org", _M.TYPE_A, answers)
self.assertEqual(_M.parse_response(raw, 7, _M.TYPE_A), ["203.0.113.7"])
def test_nxdomain_is_empty_not_an_error(self):
raw = _response(8, "absent.example.org", _M.TYPE_A, [], rcode=_M.RCODE_NXDOMAIN)
self.assertEqual(_M.parse_response(raw, 8, _M.TYPE_A), [])
def test_servfail_raises(self):
raw = _response(9, "example.org", _M.TYPE_A, [], rcode=2)
with self.assertRaises(_M.DnsError):
_M.parse_response(raw, 9, _M.TYPE_A)
def test_transaction_id_mismatch_raises(self):
raw = _response(10, "example.org", _M.TYPE_A, [])
with self.assertRaises(_M.DnsError):
_M.parse_response(raw, 11, _M.TYPE_A)
def test_short_response_raises(self):
with self.assertRaises(_M.DnsError):
_M.parse_response(b"\x00\x01", 1, _M.TYPE_A)
def test_truncation_flag(self):
self.assertTrue(
_M._is_truncated(_response(1, "a.b", _M.TYPE_A, [], truncated=True))
)
self.assertFalse(_M._is_truncated(_response(1, "a.b", _M.TYPE_A, [])))
class TestSystemResolvers(unittest.TestCase):
def test_parses_nameserver_lines_in_order(self):
text = "# comment\nsearch example.org\nnameserver 192.0.2.53\nnameserver 198.51.100.53\n"
with mock.patch.object(_M.Path, "read_text", return_value=text):
self.assertEqual(_M.system_resolvers(), ["192.0.2.53", "198.51.100.53"])
def test_missing_file_yields_empty(self):
with mock.patch.object(_M.Path, "read_text", side_effect=OSError):
self.assertEqual(_M.system_resolvers(), [])
def _args(**overrides):
base = {
"mail_host": "mail.example.org",
"mail_domain": "example.org",
"dkim_selector": "sel1",
"smtp_port": 25,
"timeout": 1.0,
"resolver": [],
"retries": 1,
"retry_delay": 0.0,
}
base.update(overrides)
return argparse.Namespace(**base)
class TestChecks(unittest.TestCase):
def setUp(self):
self.report = _M.Report()
def _patch_query(self, table):
def fake_query(name, rtype, _resolvers, _timeout):
return table.get((name, rtype), [])
return mock.patch.object(_M, "query", side_effect=fake_query)
def test_host_address_is_reported(self):
table = {("mail.example.org", _M.TYPE_A): ["203.0.113.5"]}
with self._patch_query(table):
addresses = _M.check_host_address(_args(), [], self.report)
self.assertEqual(addresses, ["203.0.113.5"])
self.assertEqual(self.report.failures, 0)
def test_missing_address_fails(self):
with self._patch_query({}):
addresses = _M.check_host_address(_args(), [], self.report)
self.assertEqual(addresses, [])
self.assertEqual(self.report.failures, 1)
def test_mx_must_be_solo_and_point_at_the_host(self):
with self._patch_query(
{("example.org", _M.TYPE_MX): [(10, "mail.example.org")]}
):
_M.check_mx(_args(), [], self.report)
self.assertEqual(self.report.failures, 0)
def test_second_mx_fails(self):
records = [(10, "mail.example.org"), (20, "backup.example.org")]
with self._patch_query({("example.org", _M.TYPE_MX): records}):
_M.check_mx(_args(), [], self.report)
self.assertEqual(self.report.failures, 1)
def test_foreign_mx_fails(self):
with self._patch_query({("example.org", _M.TYPE_MX): [(10, "elsewhere.net")]}):
_M.check_mx(_args(), [], self.report)
self.assertEqual(self.report.failures, 1)
def test_spf_accepts_mx_mechanism(self):
with self._patch_query({("example.org", _M.TYPE_TXT): ["v=spf1 mx ~all"]}):
_M.check_spf(_args(), [], self.report)
self.assertEqual(self.report.failures, 0)
def test_spf_accepts_explicit_a_mechanism(self):
record = "v=spf1 a:mail.example.org ~all"
with self._patch_query({("example.org", _M.TYPE_TXT): [record]}):
_M.check_spf(_args(), [], self.report)
self.assertEqual(self.report.failures, 0)
def test_spf_without_the_host_fails(self):
with self._patch_query(
{("example.org", _M.TYPE_TXT): ["v=spf1 include:other ~all"]}
):
_M.check_spf(_args(), [], self.report)
self.assertEqual(self.report.failures, 1)
def test_two_spf_records_fail(self):
records = ["v=spf1 mx ~all", "v=spf1 a:mail.example.org -all"]
with self._patch_query({("example.org", _M.TYPE_TXT): records}):
_M.check_spf(_args(), [], self.report)
self.assertEqual(self.report.failures, 1)
def test_missing_spf_fails(self):
with self._patch_query({("example.org", _M.TYPE_TXT): ["unrelated=1"]}):
_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)
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.assertEqual(self.report.failures, 1)
def test_dkim_key_must_be_present(self):
record = "v=DKIM1; k=rsa; p=MIIBIjANBg"
with self._patch_query(
{("sel1._domainkey.example.org", _M.TYPE_TXT): [record]}
):
_M.check_dkim(_args(), [], self.report)
self.assertEqual(self.report.failures, 0)
def test_dkim_empty_key_fails(self):
with self._patch_query(
{("sel1._domainkey.example.org", _M.TYPE_TXT): ["v=DKIM1; p="]}
):
_M.check_dkim(_args(), [], self.report)
self.assertEqual(self.report.failures, 1)
def test_dkim_without_selector_warns_only(self):
with self._patch_query({}):
_M.check_dkim(_args(dkim_selector=""), [], self.report)
self.assertEqual(self.report.failures, 0)
self.assertEqual(self.report.warnings, 1)
def test_srv_records_must_match_host_and_port(self):
table = {
("_submissions._tcp.example.org", _M.TYPE_SRV): [
(20, 1, 465, "mail.example.org")
],
("_imaps._tcp.example.org", _M.TYPE_SRV): [
(20, 1, 993, "mail.example.org")
],
("_pop3s._tcp.example.org", _M.TYPE_SRV): [
(20, 1, 995, "mail.example.org")
],
}
with self._patch_query(table):
_M.check_srv(_args(), [], self.report)
self.assertEqual(self.report.failures, 0)
def test_srv_wrong_port_fails(self):
table = {
("_submissions._tcp.example.org", _M.TYPE_SRV): [
(20, 1, 587, "mail.example.org")
],
}
with self._patch_query(table):
_M.check_srv(_args(), [], self.report)
self.assertEqual(self.report.failures, 3)
def test_ptr_mismatch_fails_but_absence_only_warns(self):
reverse = "5.113.0.203.in-addr.arpa"
with self._patch_query({(reverse, _M.TYPE_PTR): ["other.example.net"]}):
_M.check_ptr(_args(), ["203.0.113.5"], [], self.report)
self.assertEqual(self.report.failures, 1)
absent = _M.Report()
with self._patch_query({}):
_M.check_ptr(_args(), ["203.0.113.5"], [], absent)
self.assertEqual(absent.failures, 0)
self.assertEqual(absent.warnings, 1)
def test_ptr_skips_ipv6_addresses(self):
with self._patch_query({}):
_M.check_ptr(_args(), ["2001:db8::1"], [], self.report)
self.assertEqual(self.report.failures, 0)
self.assertEqual(self.report.warnings, 0)
class TestSmtpBanner(unittest.TestCase):
def setUp(self):
self.report = _M.Report()
def _connection(self, banner: bytes):
sock = mock.MagicMock()
sock.recv.return_value = banner
sock.__enter__.return_value = sock
sock.__exit__.return_value = False
return sock
def test_valid_banner_passes(self):
conn = self._connection(b"220 mail.example.org Stalwart ESMTP\r\n")
with mock.patch.object(_M.socket, "create_connection", return_value=conn):
_M.check_smtp_banner(_args(), self.report)
self.assertEqual(self.report.failures, 0)
def test_banner_without_fqdn_fails(self):
conn = self._connection(b"220 localhost ESMTP\r\n")
with mock.patch.object(_M.socket, "create_connection", return_value=conn):
_M.check_smtp_banner(_args(), self.report)
self.assertEqual(self.report.failures, 1)
def test_non_220_greeting_fails(self):
conn = self._connection(b"554 mail.example.org denied\r\n")
with mock.patch.object(_M.socket, "create_connection", return_value=conn):
_M.check_smtp_banner(_args(), self.report)
self.assertEqual(self.report.failures, 1)
def test_unreachable_port_fails(self):
with mock.patch.object(
_M.socket, "create_connection", side_effect=OSError("refused")
):
_M.check_smtp_banner(_args(), self.report)
self.assertEqual(self.report.failures, 1)
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"]
)
self.assertEqual(rc, 1)
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"]
)
self.assertEqual(rc, 0)
def test_unreachable_resolver_is_a_finding_not_a_traceback(self):
with (
mock.patch.object(_M, "system_resolvers", return_value=["192.0.2.53"]),
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",
]
)
self.assertEqual(rc, 1)
def test_failures_retry_then_report(self):
broken = _M.Report()
broken.failures = 2
with (
mock.patch.object(_M, "system_resolvers", return_value=["192.0.2.53"]),
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",
]
)
self.assertEqual(rc, 1)
self.assertEqual(runner.call_count, 3)
class TestMetricsFile(unittest.TestCase):
"""The Prometheus textfile is what makes a production run visible after the deploy."""
@staticmethod
def _args(metrics_file=""):
return argparse.Namespace(
mail_host="mail.example.org",
mail_domain="example.org",
metrics_file=metrics_file,
)
def test_every_check_becomes_its_own_labelled_series(self):
report = _M.Report()
report.checks = {"mx": 1, "spf": 0}
report.failures = 1
report.warnings = 2
with tempfile.TemporaryDirectory() as tmp:
target = Path(tmp) / "sub" / "stalwart.prom"
_M.write_metrics(report, self._args(), str(target))
body = target.read_text(
encoding="utf-8"
) # nocheck: cache-read — the file was just written in this test; a cached read would serve a stale body
self.assertIn(
'stalwart_mail_fact_up{host="mail.example.org",domain="example.org",check="mx"} 1',
body,
)
self.assertIn('check="spf"} 0', body)
self.assertIn(
'stalwart_mail_facts_failures{host="mail.example.org",domain="example.org"} 1',
body,
)
self.assertIn(
'stalwart_mail_facts_warnings{host="mail.example.org",domain="example.org"} 2',
body,
)
self.assertIn("stalwart_mail_facts_last_run_timestamp_seconds", body)
def test_no_staging_file_survives_the_write(self):
report = _M.Report()
report.checks = {"mx": 1}
with tempfile.TemporaryDirectory() as tmp:
target = Path(tmp) / "stalwart.prom"
_M.write_metrics(report, self._args(), str(target))
self.assertEqual([p.name for p in Path(tmp).iterdir()], ["stalwart.prom"])
def test_a_failing_run_still_publishes_its_metrics(self):
broken = _M.Report()
broken.failures = 2
with tempfile.TemporaryDirectory() as tmp:
target = Path(tmp) / "stalwart.prom"
with (
mock.patch.object(_M, "system_resolvers", return_value=["192.0.2.53"]),
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),
]
)
self.assertEqual(rc, 1)
self.assertIn(
"stalwart_mail_facts_failures",
target.read_text(
encoding="utf-8"
), # nocheck: cache-read — same run wrote this file; caching would hide the write
)
def test_without_the_flag_nothing_is_written(self):
clean = _M.Report()
with tempfile.TemporaryDirectory() as tmp:
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"]
)
self.assertEqual(rc, 0)
self.assertEqual(list(Path(tmp).iterdir()), [])
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,3 @@
from pathlib import Path
PROJECT_ROOT: Path = Path(__file__).resolve().parents[6]
@@ -0,0 +1,102 @@
from __future__ import annotations
import importlib.util
import sys
import unittest
from typing import ClassVar
from unittest.mock import MagicMock, patch
from ansible.errors import AnsibleError
from . import PROJECT_ROOT
def _load_module(rel_path: str, name: str):
path = PROJECT_ROOT / rel_path
spec = importlib.util.spec_from_file_location(name, str(path))
mod = importlib.util.module_from_spec(spec)
assert spec and spec.loader
sys.modules[name] = mod
spec.loader.exec_module(mod)
return mod
MODULE = _load_module(
"roles/web-app-stalwart/lookup_plugins/stalwart_users.py", "stalwart_users"
)
class TestStalwartUsers(unittest.TestCase):
CATALOGUE: ClassVar[dict] = {
"administrator": {
"username": "administrator",
"accounts": ["host", "mailbox", "identity"],
},
"contact": {"username": "contact", "accounts": ["mailbox"]},
"helpdesk": {
"username": "helpdesk",
"accounts": ["mailbox"],
"roles": ["bot"],
},
"relay": {"username": "relay", "accounts": [], "roles": ["bot"]},
"stalwartadmin": {"username": "stalwartadmin", "accounts": []},
"root": {"username": "root", "accounts": ["host"]},
"arduino": {"username": "arduino"},
"broken": "not-a-mapping",
}
def setUp(self):
self.lookup = MODULE.LookupModule()
self.catalogue = dict(self.CATALOGUE)
def _get(name, *args, **kwargs):
plugin = MagicMock()
plugin.run.side_effect = lambda terms, variables=None, **kw: [
self.catalogue
]
return plugin
patcher = patch.object(MODULE.lookup_loader, "get", side_effect=_get)
patcher.start()
self.addCleanup(patcher.stop)
def _run(self):
return self.lookup.run(None, variables={})[0]
def test_selects_mailbox_holders_and_bots_only(self):
self.assertEqual(
sorted(self._run()),
["administrator", "contact", "helpdesk", "relay"],
)
def test_a_bot_without_a_mailbox_survives_the_filter(self):
"""04_manage_user.yml gates the submission credential on the role, so
dropping it would stop persisting that bot a secret."""
self.assertIn("relay", self._run())
def test_the_recovery_admin_gets_no_jmap_account(self):
"""meta/users.yml declares stalwartadmin with accounts: [] -- it is the
STALWART_RECOVERY_ADMIN credential, not a principal in the directory."""
self.assertNotIn("stalwartadmin", self._run())
def test_users_no_stalwart_task_acts_on_are_dropped(self):
selected = self._run()
self.assertNotIn("root", selected)
self.assertNotIn("arduino", selected)
def test_entries_keep_the_shape_lookup_users_yields(self):
self.assertEqual(self._run()["contact"], self.CATALOGUE["contact"])
def test_a_non_list_accounts_declaration_is_loud(self):
self.catalogue = {"bent": {"username": "bent", "accounts": "mailbox"}}
with self.assertRaises(AnsibleError) as ctx:
self._run()
self.assertIn("bent", str(ctx.exception))
def test_positional_terms_are_rejected(self):
with self.assertRaises(AnsibleError):
self.lookup.run(["mailbox"], variables={})
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,133 @@
"""The shared Stalwart JMAP call: what it rejects and what it puts on argv.
A set-level rejection (``notCreated``/``notUpdated``) arrives inside a normal
method response, so checking only for an ``error`` method lets a refused
create pass as success. The admin password and the request body carry
secrets, so neither may reach curl's command line.
"""
from __future__ import annotations
import json
import unittest
from ansible.parsing.dataloader import DataLoader
from ansible.template import Templar
from utils.cache.yaml import load_yaml_any
from utils.templating.ansible import _trust_as_template
from . import PROJECT_ROOT
TASK = PROJECT_ROOT / "roles" / "web-app-stalwart" / "tasks" / "jmap_call.yml"
PASSWORD = 'p"a\\s$s`w#o[r]d é'
def _tasks() -> list[dict]:
return load_yaml_any(str(TASK), default_if_missing=[])
def _module(task: dict, name: str) -> dict:
return task.get(f"ansible.builtin.{name}") or task.get(name) or {}
def _call_task() -> dict:
return next(_module(t, "shell") for t in _tasks() if _module(t, "shell"))
def _assert_task() -> dict:
return next(t for t in _tasks() if _module(t, "assert"))
def _render(template: str, **variables):
templar = Templar(loader=DataLoader(), variables=variables)
return templar.template(_trust_as_template(template))
def _accepted(response: list, **extra) -> bool:
task = _assert_task()
variables = {"stalwart_jmap": {"methodResponses": [response]}, **extra}
for name, raw in (task.get("vars") or {}).items():
variables[name] = _render(raw, **variables)
return all(
_render("{{ (" + expr + ") | bool }}", **variables)
for expr in _module(task, "assert")["that"]
)
class TestJmapRejectionIsAFailure(unittest.TestCase):
def test_a_clean_set_passes(self):
self.assertTrue(
_accepted(["x:Domain/set", {"created": {"d": {"id": "1"}}}, "c0"])
)
def test_null_rejection_maps_pass(self):
self.assertTrue(
_accepted(["x:Domain/set", {"notCreated": None, "notUpdated": None}, "c0"])
)
def test_an_error_method_fails(self):
self.assertFalse(_accepted(["error", {"type": "invalidArguments"}, "c0"]))
def test_not_created_fails(self):
self.assertFalse(
_accepted(
[
"x:Certificate/set",
{"notCreated": {"c": {"type": "invalidProperties"}}},
"c0",
]
)
)
def test_not_updated_fails(self):
self.assertFalse(
_accepted(
[
"x:Tracer/set",
{"notUpdated": {"t": {"type": "notFound"}}},
"c0",
]
)
)
def test_a_caller_reading_the_rejection_itself_may_tolerate_it(self):
self.assertTrue(
_accepted(
[
"x:Account/set",
{"notCreated": {"a": {"type": "alreadyExists"}}},
"c0",
],
stalwart_jmap_tolerate_rejected=True,
)
)
class TestJmapSecretsStayOffArgv(unittest.TestCase):
def setUp(self):
self.task = _call_task()
def test_command_line_carries_no_credentials_or_body(self):
cmd = self.task["cmd"]
self.assertNotIn("-u ", cmd)
self.assertNotIn("STALWART_ADMIN_PASSWORD", cmd)
self.assertNotIn("stalwart_jmap_body", cmd)
self.assertIn("-K -", cmd)
def test_stdin_config_round_trips_hostile_values(self):
body = json.dumps({"secret": 'q"\\x', "name": "Zoë"})
rendered = _render(
self.task["stdin"],
STALWART_ADMIN_USER="stalwartadmin",
STALWART_ADMIN_PASSWORD=PASSWORD,
stalwart_jmap_body=body,
)
config = dict(line.split(" = ", 1) for line in rendered.splitlines())
self.assertEqual(json.loads(config["user"]), f"stalwartadmin:{PASSWORD}")
self.assertEqual(json.loads(config["data-binary"]), body)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,137 @@
"""How Stalwart routes .onion recipients to the Tor SMTP gateway.
Stalwart has no outbound SOCKS of its own, so ``14_onion_route.yml`` provisions
a relay ``MtaRoute`` to the gateway and points the ``MtaOutboundStrategy`` route
expression at it for ``.onion`` recipients. The one property that must never
regress: the strategy still sends local recipients to ``local`` and everything
else to ``mx`` — adding the onion branch must not break normal delivery.
"""
from __future__ import annotations
import json
import unittest
from jinja2 import Environment, StrictUndefined
from utils.cache.files import read_text
from utils.cache.yaml import load_yaml_any
from . import PROJECT_ROOT
ROLE = PROJECT_ROOT / "roles" / "web-app-stalwart"
TASK = ROLE / "tasks" / "14_onion_route.yml"
ROUTE_CREATE = ROLE / "templates" / "jmap" / "route" / "create.json.j2"
STRATEGY_GET = ROLE / "templates" / "jmap" / "strategy" / "get.json.j2"
STRATEGY_CREATE = ROLE / "templates" / "jmap" / "strategy" / "create.json.j2"
STRATEGY_UPDATE = ROLE / "templates" / "jmap" / "strategy" / "update.json.j2"
ROUTE_NAME = "onion"
def _render(template_path, **variables) -> str:
env = Environment(
trim_blocks=True,
lstrip_blocks=True,
undefined=StrictUndefined,
autoescape=False, # noqa: S701 - JMAP request bodies, never HTML
)
env.filters["to_json"] = json.dumps
env.filters["int"] = int
return env.from_string(read_text(template_path)).render(**variables)
def _route_expr_from_task() -> dict:
tasks = load_yaml_any(str(TASK), default_if_missing=[])
for task in tasks:
facts = task.get("set_fact") or task.get("ansible.builtin.set_fact") or {}
if "stalwart_route_expr" in facts:
return facts["stalwart_route_expr"]
raise AssertionError("stalwart_route_expr set_fact not found in 14_onion_route.yml")
class TestOutboundStrategyExpression(unittest.TestCase):
def setUp(self):
self.expr = _route_expr_from_task()
def test_local_recipients_still_route_to_local(self):
first = self.expr["match"]["0"]
self.assertEqual(first["if"], "is_local_domain(rcpt_domain)")
self.assertEqual(first["then"], "'local'")
def test_local_is_evaluated_before_onion(self):
"""A local .onion address must be delivered locally, not relayed out."""
keys = list(self.expr["match"].keys())
self.assertEqual(keys, ["0", "1"])
self.assertIn("is_local_domain", self.expr["match"]["0"]["if"])
self.assertIn("ends_with", self.expr["match"]["1"]["if"])
def test_onion_recipients_route_to_the_onion_route(self):
"""then is a Stalwart expression string literal naming the route, from
the same SPOT var the relay route registers itself under."""
onion = self.expr["match"]["1"]
self.assertEqual(onion["if"], "ends_with(rcpt_domain, '.onion')")
self.assertEqual(onion["then"], "'{{ STALWART_ONION_ROUTE_NAME }}'")
def test_everything_else_falls_back_to_mx(self):
self.assertEqual(self.expr["else"], "'mx'")
class TestStrategyTemplateRendersValidJson(unittest.TestCase):
def test_the_singleton_route_is_set_from_the_expression(self):
expr = _route_expr_from_task()
rendered = _render(STRATEGY_UPDATE, stalwart_route_expr=expr)
body = json.loads(rendered)
method, args, _tag = body["methodCalls"][0]
self.assertEqual(method, "x:MtaOutboundStrategy/set")
self.assertEqual(args["update"]["singleton"]["route"], expr)
def test_create_seeds_a_new_singleton_with_the_route(self):
expr = _route_expr_from_task()
rendered = _render(STRATEGY_CREATE, stalwart_route_expr=expr)
body = json.loads(rendered)
method, args, _tag = body["methodCalls"][0]
self.assertEqual(method, "x:MtaOutboundStrategy/set")
(created,) = args["create"].values()
self.assertEqual(created["route"], expr)
def test_get_queries_the_singleton_by_id(self):
"""The singleton is NOT enumerated by get(ids:null); it must be queried
by its fixed "singleton" id or existence detection is always wrong."""
body = json.loads(_render(STRATEGY_GET))
method, args, _tag = body["methodCalls"][0]
self.assertEqual(method, "x:MtaOutboundStrategy/get")
self.assertEqual(args["ids"], ["singleton"])
class TestRelayRouteRendersValidJson(unittest.TestCase):
def _create(self):
rendered = _render(
ROUTE_CREATE,
STALWART_ONION_ROUTE_NAME=ROUTE_NAME,
STALWART_ONION_RELAY_HOST="tor-smtp",
STALWART_ONION_RELAY_PORT=1525,
)
body = json.loads(rendered)
return body["methodCalls"][0]
def test_it_creates_a_relay_route_to_the_gateway(self):
method, args, _tag = self._create()
self.assertEqual(method, "x:MtaRoute/set")
route = args["create"][ROUTE_NAME]
self.assertEqual(route["@type"], "Relay")
self.assertEqual(route["name"], ROUTE_NAME)
self.assertEqual(route["address"], "tor-smtp")
self.assertEqual(route["port"], 1525)
def test_the_relay_hop_is_plaintext_smtp(self):
"""The gateway speaks plaintext SMTP on an internal network; there is no
cert to validate on a .onion relay hop."""
_method, args, _tag = self._create()
route = args["create"][ROUTE_NAME]
self.assertEqual(route["protocol"], "smtp")
self.assertFalse(route["implicitTls"])
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,104 @@
"""Whether Roundcube forces https on its generated URLs, per canonical scheme.
Roundcube derives the OAuth ``redirect_uri`` from the request scheme, and the
reverse proxy speaks plain HTTP to the container. Forcing https is therefore
right on a clearnet vhost and wrong on an onion one, which is served over HTTP
because Tor carries the encryption. Getting it wrong is not cosmetic: Keycloak
compares the ``redirect_uri`` against the client's registered list verbatim and
answers "Invalid parameter: redirect_uri" on a scheme mismatch, so the webmail
login dies before the form is ever drawn.
Both sides are built from ``canonical_url``, so the assertion here is that the
template follows that one source rather than a hard-coded scheme.
"""
from __future__ import annotations
import unittest
from jinja2 import Environment, StrictUndefined
from utils.cache.files import read_text
from . import PROJECT_ROOT
TEMPLATE = (
PROJECT_ROOT
/ "roles"
/ "web-app-stalwart"
/ "templates"
/ "roundcube-oauth.inc.php.j2"
)
FORCE_HTTPS = "$_SERVER['HTTPS'] = 'on';"
ONION_BASE = (
"http://webmail.4dl6yijmuksgh5bfaf3csqoelji7zptyuo6wy5g5prjpnk6vdbzfwnad.onion"
)
CLEARNET_BASE = "https://webmail.infinito.example"
def _render(base_url: str, *, sso_enabled: bool = True, socks_proxy: str = "") -> str:
env = Environment(
trim_blocks=True,
lstrip_blocks=True,
undefined=StrictUndefined,
autoescape=False, # noqa: S701 - a PHP config file, and Ansible's templar does not escape either
)
env.filters["bool"] = bool
return env.from_string(read_text(TEMPLATE)).render(
STALWART_SSO_ENABLED=sso_enabled,
STALWART_WEBMAIL_BASE_URL=base_url,
STALWART_OIDC_SOCKS_PROXY=socks_proxy,
STALWART_WEBMAIL_OIDC_CLIENT_ID="roundcube",
OIDC={
"BUTTON_TEXT": "Sign in",
"ATTRIBUTES": {"USERNAME": "preferred_username"},
"CLIENT": {
"AUTHORIZE_URL": "https://auth.infinito.example/auth",
"TOKEN_URL": "https://auth.infinito.example/token",
"USER_INFO_URL": "https://auth.infinito.example/userinfo",
"LOGOUT_URL": "https://auth.infinito.example/logout",
},
},
)
class TestRoundcubeOauthScheme(unittest.TestCase):
def test_a_clearnet_vhost_still_forces_https(self):
self.assertIn(FORCE_HTTPS, _render(CLEARNET_BASE))
def test_an_onion_vhost_is_left_on_http(self):
self.assertNotIn(FORCE_HTTPS, _render(ONION_BASE))
def test_the_scheme_is_never_decided_by_the_onion_suffix_alone(self):
self.assertIn(FORCE_HTTPS, _render("https://webmail.example.onion"))
def test_an_onion_issuer_routes_the_back_channel_through_tor(self):
rendered = _render(
ONION_BASE, socks_proxy="socks5h://host.docker.internal:9050"
)
self.assertIn(
"$config['http_client'] = ['proxy' => 'socks5h://host.docker.internal:9050'];",
rendered,
)
def test_the_proxy_must_hand_the_name_to_tor_to_resolve(self):
"""socks5:// resolves locally, which is what cURL refuses to do for .onion."""
rendered = _render(
ONION_BASE, socks_proxy="socks5h://host.docker.internal:9050"
)
self.assertNotIn("'proxy' => 'socks5://", rendered)
def test_a_clearnet_issuer_gets_no_proxy_at_all(self):
self.assertNotIn("http_client", _render(CLEARNET_BASE))
def test_nothing_is_emitted_without_sso(self):
rendered = _render(
CLEARNET_BASE, sso_enabled=False, socks_proxy="socks5h://tor:9050"
)
self.assertNotIn(FORCE_HTTPS, rendered)
self.assertNotIn("oauth_client_id", rendered)
self.assertNotIn("http_client", rendered)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,188 @@
"""The generic WordPress plugin installer decides by state, not by exit code.
WP-CLI can exit 255 after an install that finished, because WordPress' fatal
handler requires the ``.maintenance`` file the install has just removed. The
installer therefore never fails on the install's exit code: it stops retrying on
``Success:``, asks ``wp plugin is-installed`` afterwards, and only a required
plugin that is really missing fails the deploy. A pinned plugin is reinstalled
only when the installed version differs from its pin, so a redeploy neither
downloads it again nor reports a change.
Each case evaluates the conditions of
``roles/web-app-wordpress/tasks/utils/install/plugin.yml`` itself.
"""
from __future__ import annotations
import unittest
from ansible.parsing.dataloader import DataLoader
from ansible.template import Templar
from utils.cache.yaml import load_yaml_any
from utils.templating.ansible import _trust_as_template
from . import PROJECT_ROOT
TASK_FILE = PROJECT_ROOT / "roles/web-app-wordpress/tasks/utils/install/plugin.yml"
SKIPPED = {"skipped": True, "changed": False}
FINISHED_BUT_255 = {
"rc": 255,
"stdout": "Installing MCP Adapter\nPlugin installed successfully.\nSuccess: Installed 1 of 1 plugins.",
}
DOWNLOAD_FAILED = {"rc": 1, "stdout": "Error: Download failed. Not Found"}
def _tasks() -> list[dict]:
return load_yaml_any(str(TASK_FILE), default_if_missing=[])
def _task(fragment: str) -> dict:
return next(t for t in _tasks() if fragment in t["name"])
def _block_task(fragment: str) -> dict:
block = next(t for t in _tasks() if "block" in t)
return next(t for t in block["block"] if fragment in t["name"])
def _truthy(expression, **variables) -> bool:
expressions = expression if isinstance(expression, list) else [expression]
templar = Templar(loader=DataLoader(), variables=variables)
return all(
templar.template(_trust_as_template("{{ (" + str(e) + ") | bool }}"))
for e in expressions
)
def _installed(install: dict, verify_rc: int | None) -> bool:
expression = _task("Resolve whether")["ansible.builtin.set_fact"][
"wp_plugin_installed"
]
verified = SKIPPED if verify_rc is None else {"rc": verify_rc}
templar = Templar(
loader=DataLoader(),
variables={"wp_plugin_install": install, "wp_plugin_verified": verified},
)
return bool(templar.template(_trust_as_template(expression)))
class TestInstallDecision(unittest.TestCase):
def _installs(self, *, present_rc, pinned, installed_version, pin) -> bool:
return _truthy(
_task("Install WordPress plugin")["when"],
wp_plugin_present={"rc": present_rc},
wp_plugin_pinned=pinned,
wp_plugin_installed_version=installed_version,
wp_plugin_pinned_version=pin,
)
def test_a_missing_plugin_is_installed(self):
self.assertTrue(
self._installs(
present_rc=1, pinned=False, installed_version=SKIPPED, pin=""
)
)
def test_a_pinned_plugin_at_its_pin_is_left_alone(self):
self.assertFalse(
self._installs(
present_rc=0,
pinned=True,
installed_version={"stdout": "0.5.0\n"},
pin="0.5.0",
)
)
def test_a_pinned_plugin_behind_its_pin_is_upgraded(self):
self.assertTrue(
self._installs(
present_rc=0,
pinned=True,
installed_version={"stdout": "0.4.1"},
pin="0.5.0",
)
)
def test_an_unpinned_plugin_that_is_present_is_left_alone(self):
self.assertFalse(
self._installs(
present_rc=0, pinned=False, installed_version=SKIPPED, pin=""
)
)
def test_the_pin_is_compared_without_its_tag_prefix(self):
normalise = _task("Normalise the install contract")["ansible.builtin.set_fact"]
self.assertIn("regex_replace('^v', '')", normalise["wp_plugin_pinned_version"])
class TestExitCodeIsNotTheVerdict(unittest.TestCase):
def test_install_task_never_fails_on_its_exit_code(self):
self.assertIs(_task("Install WordPress plugin")["failed_when"], False)
def test_a_finished_install_that_exits_255_stops_retrying(self):
self.assertTrue(
_truthy(
_task("Install WordPress plugin")["until"],
wp_plugin_install=FINISHED_BUT_255,
)
)
def test_a_failed_download_is_retried(self):
self.assertFalse(
_truthy(
_task("Install WordPress plugin")["until"],
wp_plugin_install=DOWNLOAD_FAILED,
)
)
def test_the_verify_probe_only_fails_on_an_unexpected_exit_code(self):
failed_when = _task("Verify WordPress plugin")["failed_when"]
self.assertFalse(_truthy(failed_when, wp_plugin_verified={"rc": 1}))
self.assertTrue(_truthy(failed_when, wp_plugin_verified={"rc": 2}))
def test_a_255_install_that_landed_counts_as_installed(self):
self.assertTrue(_installed(FINISHED_BUT_255, verify_rc=0))
def test_a_skipped_install_counts_as_installed(self):
self.assertTrue(_installed(SKIPPED, verify_rc=None))
def test_a_failed_install_counts_as_missing(self):
self.assertFalse(_installed(DOWNLOAD_FAILED, verify_rc=1))
class TestMissingPluginOutcome(unittest.TestCase):
def _runs(self, fragment: str, *, installed: bool, required: bool) -> bool:
block = next(t for t in _tasks() if "block" in t)
variables = {"wp_plugin_installed": installed, "wp_plugin_required": required}
return _truthy(block["when"], **variables) and _truthy(
_block_task(fragment)["when"], **variables
)
def test_a_missing_required_plugin_fails_the_deploy(self):
self.assertTrue(
self._runs("Fail because required", installed=False, required=True)
)
self.assertFalse(self._runs("Skip optional", installed=False, required=True))
def test_a_missing_optional_plugin_only_warns(self):
self.assertFalse(
self._runs("Fail because required", installed=False, required=False)
)
self.assertTrue(self._runs("Skip optional", installed=False, required=False))
def test_an_installed_plugin_reaches_neither_branch(self):
self.assertFalse(
self._runs("Fail because required", installed=True, required=True)
)
self.assertFalse(self._runs("Skip optional", installed=True, required=False))
def test_only_an_installed_plugin_is_activated(self):
activate = _task("Activate WordPress plugin")["when"]
self.assertTrue(_truthy(activate, wp_plugin_installed=True))
self.assertFalse(_truthy(activate, wp_plugin_installed=False))
if __name__ == "__main__":
unittest.main()
@@ -50,6 +50,12 @@ def _install_role_local_kcadm_json_into_ansible_module_utils() -> None:
sys.modules["ansible.module_utils.kcadm_json"] = role_modutils
scopes_modutils = _load_py_module(
"role_web_app_keycloak_module_utils_keycloak_scopes_for_ansible",
PROJECT_ROOT / "utils" / "keycloak_scopes.py",
)
sys.modules["ansible.module_utils.keycloak_scopes"] = scopes_modutils
class DummyModule:
def fail_json(self, **kwargs):
@@ -224,6 +230,82 @@ class TestKeycloakKcadmUpdate(unittest.TestCase):
)
self.assertEqual(cur, {"id": "abc", "name": "thing"})
def _run_converge(self, desired, assignments, catalog):
"""Drive converge_client_scope_lists with a fake kcadm; returns the
mutating commands it issued, in order."""
m = self.mod
dummy = DummyModule()
mutations = []
def fake_run_kcadm(_module, cmd, ignore_rc=False):
for kind, payload in assignments.items():
if f"get clients/c1/{kind} " in cmd:
return 0, payload, ""
if "get client-scopes " in cmd:
return 0, catalog, ""
mutations.append(cmd)
return 0, "", ""
changed = m.converge_client_scope_lists(
fake_run_kcadm, dummy, "c1", desired, "example", "kcadm"
)
return changed, mutations
def test_converge_client_scopes_adds_and_removes(self):
changed, mutations = self._run_converge(
desired={"defaultClientScopes": ["a", "b"]},
assignments={
"default-client-scopes": '[{"id":"s-old","name":"old"},{"id":"s-a","name":"a"}]'
},
catalog='[{"id":"s-b","name":"b"},{"id":"s-old","name":"old"}]',
)
self.assertTrue(changed)
self.assertEqual(
mutations,
[
"kcadm delete clients/c1/default-client-scopes/s-old -r example",
"kcadm update clients/c1/default-client-scopes/s-b -r example",
],
)
def test_converge_client_scopes_noop_when_in_sync(self):
changed, mutations = self._run_converge(
desired={"defaultClientScopes": ["a"]},
assignments={"default-client-scopes": '[{"id":"s-a","name":"a"}]'},
catalog='[{"id":"s-a","name":"a"}]',
)
self.assertFalse(changed)
self.assertEqual(mutations, [])
def test_converge_client_scopes_removals_precede_additions_across_lists(self):
"""Scope `x` moves default -> optional: it must be unassigned from
default BEFORE it is assigned to optional."""
changed, mutations = self._run_converge(
desired={"defaultClientScopes": [], "optionalClientScopes": ["x"]},
assignments={
"default-client-scopes": '[{"id":"s-x","name":"x"}]',
"optional-client-scopes": "[]",
},
catalog='[{"id":"s-x","name":"x"}]',
)
self.assertTrue(changed)
self.assertEqual(
mutations,
[
"kcadm delete clients/c1/default-client-scopes/s-x -r example",
"kcadm update clients/c1/optional-client-scopes/s-x -r example",
],
)
def test_converge_client_scopes_skips_undeclared_lists(self):
changed, mutations = self._run_converge(
desired={"clientId": "no-scope-lists-here"},
assignments={"default-client-scopes": '[{"id":"s-a","name":"a"}]'},
catalog="[]",
)
self.assertFalse(changed)
self.assertEqual(mutations, [])
if __name__ == "__main__":
unittest.main()
@@ -29,6 +29,15 @@ GIT_IDENTITY = {
"GIT_COMMITTER_NAME": "test",
"GIT_COMMITTER_EMAIL": "test@example.invalid",
}
GIT_REPO_SCOPE = (
"GIT_DIR",
"GIT_WORK_TREE",
"GIT_INDEX_FILE",
"GIT_COMMON_DIR",
"GIT_PREFIX",
"GIT_OBJECT_DIRECTORY",
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
)
NEEDS_UNPRIVILEGED = "clearing the write bit does not restrain root"
@@ -40,7 +49,8 @@ class WorktreeDownFixture:
self.repo = self.root / "repo"
self.base = self.root / "worktrees"
self.checkout = self.base / "feat"
self.env = {**os.environ, **GIT_IDENTITY}
inherited = {k: v for k, v in os.environ.items() if k not in GIT_REPO_SCOPE}
self.env = {**inherited, **GIT_IDENTITY}
scripts = self.repo / "scripts" / "system" / "worktree"
scripts.parent.mkdir(parents=True)
+13
View File
@@ -106,6 +106,19 @@ class TestIterProjectFiles(_ProjectRootFixture, unittest.TestCase):
f"cli/build is source and must survive the prune: {all_paths}",
)
def test_git_local_exclude_dirs_pruned(self) -> None:
"""Plain directory entries in .git/info/exclude are pruned; file
patterns and globs are left to git."""
_touch(
self.root / ".git/info/exclude",
"# comment\n/local-tool-out/\nsettings.local.json\n*.tmp\n",
)
_touch(self.root / "local-tool-out/report.md", "generated")
_reset()
all_paths = set(iter_project_files())
self.assertFalse(any("/local-tool-out/" in p for p in all_paths))
self.assertTrue(any(p.endswith("readme.md") for p in all_paths))
def test_extensions_filter(self) -> None:
ymls = list(iter_project_files(extensions=(".yml",)))
self.assertEqual(len(ymls), 1)
@@ -142,11 +142,33 @@ class TestOtherFlavors(unittest.TestCase):
blackhole="void@example",
)
self.assertIn("if [ ! -f /tmp/email_sent ]", argv[1])
self.assertIn("msmtp -t void@example", argv[1])
self.assertIn("msmtp --domain=app.example -t void@example", argv[1])
self.assertTrue(
argv[1].endswith("curl -f --noproxy '*' http://127.0.0.1:80/ || exit 1")
)
def test_the_ehlo_identity_is_named_so_a_strict_relay_accepts_it(self):
"""msmtp defaults EHLO to "localhost", which Stalwart answers with 550."""
argv = probe(
"msmtp_curl",
port=80,
email_enabled=True,
domain="app.example",
blackhole="void@example",
)
self.assertIn("--domain=app.example", argv[1])
def test_without_a_domain_no_empty_ehlo_flag_is_emitted(self):
argv = probe(
"msmtp_curl",
port=80,
email_enabled=True,
domain="",
blackhole="void@example",
)
self.assertNotIn("--domain=", argv[1])
self.assertIn("msmtp -t void@example", argv[1])
def test_msmtp_curl_probe_behaviour(self):
argv = probe(
"msmtp_curl",
+3
View File
@@ -0,0 +1,3 @@
from pathlib import Path
PROJECT_ROOT: Path = Path(__file__).resolve().parents[5]
@@ -0,0 +1,120 @@
"""The mail provider a deploy actually resolves to.
``MAIL_PROVIDER`` is the operator's flag and wins whenever the role it names is
deployed. The fallback exists for the round that deploys only the alternative
provider, and it must stay single-valued: if two roles could both consider
themselves active they would both bind the public SMTP ports.
"""
from __future__ import annotations
import unittest
from utils.mail.provider import (
declaring_roles,
deployed_roles,
resolve_active_provider,
)
from . import PROJECT_ROOT
ROLES_DIR = PROJECT_ROOT / "roles"
STALWART = "web-app-stalwart"
MAILU = "web-app-mailu"
class TestDeclaringRoles(unittest.TestCase):
def test_both_providers_are_discovered(self):
roles = declaring_roles(ROLES_DIR)
self.assertIn(STALWART, roles)
self.assertIn(MAILU, roles)
def test_provides_outranks_covers(self):
roles = declaring_roles(ROLES_DIR)
self.assertLess(
roles.index(STALWART),
roles.index(MAILU),
"the role declaring provides: email must win the fallback",
)
class TestResolveActiveProvider(unittest.TestCase):
def test_configured_provider_wins_when_deployed(self):
self.assertEqual(
resolve_active_provider(STALWART, [STALWART, MAILU], ROLES_DIR), STALWART
)
def test_configured_provider_wins_alone(self):
self.assertEqual(
resolve_active_provider(STALWART, [STALWART], ROLES_DIR), STALWART
)
def test_falls_back_to_the_provider_that_is_deployed(self):
self.assertEqual(resolve_active_provider(STALWART, [MAILU], ROLES_DIR), MAILU)
def test_mailu_configured_wins_over_stalwart_priority(self):
self.assertEqual(
resolve_active_provider(MAILU, [STALWART, MAILU], ROLES_DIR), MAILU
)
def test_exactly_one_provider_is_active_when_both_deployed(self):
deployed = [STALWART, MAILU]
for configured in (STALWART, MAILU, "web-app-absent"):
active = resolve_active_provider(configured, deployed, ROLES_DIR)
others = [r for r in deployed if r != active]
self.assertNotIn(
active,
others,
f"configured={configured!r} produced more than one active provider",
)
self.assertIn(active, deployed)
def test_no_provider_deployed_keeps_the_configured_value(self):
self.assertEqual(
resolve_active_provider(STALWART, ["web-app-gitea"], ROLES_DIR), STALWART
)
def test_empty_group_names_keeps_the_configured_value(self):
self.assertEqual(resolve_active_provider(STALWART, [], ROLES_DIR), STALWART)
class TestDeployedRoles(unittest.TestCase):
"""Resolution is cluster-wide, so it reads ``groups``, not ``group_names``.
A swarm worker's ``group_names`` lacks the manager-pinned provider. Deriving
presence per-host would give workers a different provider than the manager
and render their relay config against a server they must not use.
"""
def test_only_groups_with_hosts_count_as_deployed(self):
groups = {
STALWART: ["mgr-01"],
MAILU: [],
"all": ["mgr-01", "wrk-01"],
}
result = deployed_roles(groups)
self.assertIn(STALWART, result)
self.assertNotIn(MAILU, result)
def test_none_and_empty_are_tolerated(self):
self.assertEqual(deployed_roles(None), [])
self.assertEqual(deployed_roles({}), [])
def test_worker_resolves_the_same_provider_as_the_manager(self):
groups = {STALWART: ["mgr-01"], "all": ["mgr-01", "wrk-01", "wrk-02"]}
self.assertEqual(
resolve_active_provider(STALWART, deployed_roles(groups), ROLES_DIR),
STALWART,
"a manager-pinned provider must still resolve on worker nodes",
)
def test_mailu_only_cluster_resolves_mailu_on_every_node(self):
groups = {MAILU: ["mgr-01"], "all": ["mgr-01", "wrk-01"]}
self.assertEqual(
resolve_active_provider(STALWART, deployed_roles(groups), ROLES_DIR), MAILU
)
if __name__ == "__main__":
unittest.main()
@@ -204,6 +204,43 @@ class TestTemplatingRenderStrict(unittest.TestCase):
)
self.assertEqual(out, ca_cert_host("infinito.nexus"))
def test_inline_conditional_with_concat(self):
raw = (
"{{ ('mail.' ~ DOMAIN_PRIMARY) if MAIL_PROVIDER == 'web-app-mailu' "
"else ('legacy-mail.' ~ DOMAIN_PRIMARY) }}"
)
base = {"DOMAIN_PRIMARY": "example.com"}
self.assertEqual(
render_ansible_strict(
templar=None,
raw=raw,
var_name="x",
err_prefix="t",
variables={**base, "MAIL_PROVIDER": "web-app-mailu"},
),
"mail.example.com",
)
self.assertEqual(
render_ansible_strict(
templar=None,
raw=raw,
var_name="x",
err_prefix="t",
variables={**base, "MAIL_PROVIDER": "web-app-stalwart"},
),
"legacy-mail.example.com",
)
self.assertEqual(
render_ansible_strict(
templar=None,
raw=raw,
var_name="x",
err_prefix="t",
variables=base,
),
"legacy-mail.example.com",
)
def test_filters_lower_upper_default(self):
variables = {"NAME": "MiXeD", "EMPTY": ""}
out1 = render_ansible_strict(
@@ -0,0 +1,94 @@
# Ensure repo root is importable so `utils.*` resolves in all runners
import sys
import unittest
from . import PROJECT_ROOT
sys.path.insert(0, str(PROJECT_ROOT))
from utils.templating.expr import (
find_top_level_op,
is_paren_wrapped,
split_list_items,
split_top_level,
)
class TestSplitListItems(unittest.TestCase):
def test_bare_and_quoted_tokens(self):
self.assertEqual(
split_list_items("DIR_BIN, 'ca-inject'"), ["DIR_BIN", "'ca-inject'"]
)
def test_comma_inside_quotes_is_not_a_separator(self):
self.assertEqual(split_list_items("'a,b', c"), ["'a,b'", "c"])
def test_mixed_quote_styles(self):
self.assertEqual(split_list_items("\"x\", 'y'"), ['"x"', "'y'"])
def test_empty_and_whitespace_tokens_dropped(self):
self.assertEqual(split_list_items(" a ,, b , "), ["a", "b"])
def test_empty_string(self):
self.assertEqual(split_list_items(""), [])
class TestFindTopLevelOp(unittest.TestCase):
def test_finds_operator_at_depth_zero(self):
self.assertEqual(find_top_level_op("A == B", "=="), 2)
def test_skips_operator_inside_parens(self):
expr = "(A == B) != C"
self.assertEqual(find_top_level_op(expr, "!="), expr.index("!="))
self.assertEqual(find_top_level_op("(A == B)", "=="), -1)
def test_skips_operator_inside_quotes(self):
expr = "'x == y' == Z"
self.assertEqual(find_top_level_op(expr, "=="), 9)
def test_word_operator_padded_with_spaces(self):
"""A padded ` if ` must not match inside identifiers like `notify`."""
self.assertEqual(find_top_level_op("gift if COND else b", " if "), 4)
self.assertEqual(find_top_level_op("gifted", " if "), -1)
def test_not_found(self):
self.assertEqual(find_top_level_op("A ~ B", "=="), -1)
def test_bracket_kinds_all_count_as_depth(self):
self.assertEqual(find_top_level_op("[a == b] == c", "=="), 9)
self.assertEqual(find_top_level_op("{a == b} == c", "=="), 9)
class TestSplitTopLevel(unittest.TestCase):
def test_simple_split(self):
self.assertEqual(split_top_level("a ~ b ~ c", "~"), ["a ", " b ", " c"])
def test_separator_inside_quotes_kept(self):
self.assertEqual(split_top_level("'a ~ b' ~ c", "~"), ["'a ~ b' ", " c"])
def test_separator_inside_parens_kept(self):
self.assertEqual(split_top_level("(a ~ b) ~ c", "~"), ["(a ~ b) ", " c"])
def test_no_separator_returns_whole(self):
self.assertEqual(split_top_level("abc", "~"), ["abc"])
class TestIsParenWrapped(unittest.TestCase):
def test_fully_wrapped(self):
self.assertTrue(is_paren_wrapped("(a ~ b)"))
def test_adjacent_groups_are_not_wrapped(self):
self.assertFalse(is_paren_wrapped("(a) ~ (b)"))
def test_no_parens(self):
self.assertFalse(is_paren_wrapped("a ~ b"))
def test_nested_wrap(self):
self.assertTrue(is_paren_wrapped("((a) ~ (b))"))
def test_close_paren_inside_quotes_ignored(self):
self.assertTrue(is_paren_wrapped("(a ~ ')' ~ b)"))
if __name__ == "__main__": # pragma: no cover
unittest.main()