Merge origin/main into feature/svc-net-wireguard

Brings in 225 commits, including the merged web-app-openbao work and the
LMStudio loopback fix.

Seven conflicts:

- The legacy svc-net-wireguard-core/plain/firewalled roles this branch deleted
  in e706170a0 were modified upstream. The deletion stands, which is the whole
  premise of the branch.
- The MCP audit takes upstream's list plus svc-net-firewall, with the three
  legacy wireguard entries collapsed into the single svc-net-wireguard: 23.
- web-app-openbao/README.md takes main's reviewed version wholesale.
- matrix.py takes both sides: upstream's app_id argument to _reset_credentials
  and this branch's _write_mesh call after it.

The merge pushed matrix.py to 511 lines against the 500 cap, so the step
runner moved to utils/tests/swarm/run.py, which is self-contained and leaves
matrix.py at 427. Its test moved with it.
This commit is contained in:
evangelostsak committed 2026-09-24 21:14:25 +02:00
commit 0a6700e378
437 files changed
+12903 -1724

No files matched your search

@@ -53,6 +53,10 @@ users:
6e6577730a
biber:
password: VeryUnsecurePassword!1
keycloak-bot:
password: !vault |
$ANSIBLE_VAULT;1.1;AES256
626f740a
"""
DECLARED_USERS = """\
@@ -63,6 +67,14 @@ newsletter:
uid: 1002
"""
KEYCLOAK_USERS = (
DECLARED_USERS
+ """\
keycloak-bot:
uid: 1003
"""
)
class TestResetCredentials(unittest.TestCase):
def setUp(self):
@@ -70,10 +82,14 @@ class TestResetCredentials(unittest.TestCase):
self.addCleanup(shutil.rmtree, self.workdir, ignore_errors=True)
self.roles_dir = self.workdir / "roles"
for application_id in ("web-app-a", "web-app-keycloak"):
declarations = {
"web-app-a": DECLARED_USERS,
"web-app-keycloak": KEYCLOAK_USERS,
}
for application_id, declared in declarations.items():
users_file = self.roles_dir / application_id / ROLE_FILE_META_USERS
users_file.parent.mkdir(parents=True, exist_ok=True)
users_file.write_text(DECLARED_USERS, encoding="utf-8")
users_file.write_text(declared, encoding="utf-8")
self.host_vars_file = self.workdir / "host_vars" / "localhost.yml"
self.host_vars_file.parent.mkdir(parents=True, exist_ok=True)
@@ -125,6 +141,32 @@ class TestResetCredentials(unittest.TestCase):
self._reset(exclude={"administrator", "web-app-keycloak"})
self.assertIn("database_password", self._credentials("web-app-keycloak"))
def test_an_application_outside_the_rotation_keeps_its_credentials(self):
"""Dropping must not outrun regeneration.
The drop side walks the document while the generate side walks
`credential_ids`. A matrix host_vars file carries a block per mirror
artefact too, so a document-wide drop would delete credentials the
caller never writes back.
"""
_, credentials, _ = self._reset(credential_ids=["web-app-a"])
self.assertIn("database_password", self._credentials("web-app-keycloak"))
self.assertNotIn("api_key", self._credentials("web-app-a"))
self.assertEqual(credentials.call_args.kwargs["application_ids"], ["web-app-a"])
def test_narrowing_the_credentials_still_rotates_every_user(self):
"""A narrowed credential scope must not narrow the user passwords.
Both halves used to share one id list, so scoping the credentials to
the round silently stopped rotating the users of every other role.
"""
_, _, users = self._reset(credential_ids=["web-app-a"])
self.assertNotIn("password", self._document()["users"]["keycloak-bot"])
self.assertEqual(
users.call_args.kwargs["application_ids"],
["web-app-a", "web-app-keycloak"],
)
def test_an_excluded_user_keeps_its_password(self):
self._reset()
users = self._document()["users"]
@@ -164,7 +206,7 @@ class TestResetCredentials(unittest.TestCase):
def test_the_rotated_count_covers_both_sections(self):
rotated, _, _ = self._reset()
self.assertEqual(rotated, 4)
self.assertEqual(rotated, 5)
def test_rotating_nothing_aborts(self):
with self.assertRaises(SystemExit):
@@ -188,6 +188,36 @@ class TestApplyServicesDisabled(unittest.TestCase):
dump_yaml(role_dir / ROLE_FILE_META_SERVICES, services)
dump_yaml(role_dir / ROLE_FILE_VARS_MAIN, {"application_id": role_name})
def test_a_role_without_shared_in_its_contract_does_not_get_one(self):
self._write_host_vars(
{"applications": {"web-svc-cdn": {"services": {"dashboard": {}}}}}
)
self._make_role("web-svc-cdn", {"dashboard": {"enabled": False}})
apply_services_disabled(self.host_vars, ["dashboard"], self.roles_dir)
service = self._read_host_vars()["applications"]["web-svc-cdn"]["services"][
"dashboard"
]
self.assertEqual(False, service["enabled"])
self.assertNotIn("shared", service)
def test_a_role_declaring_both_toggles_still_gets_both(self):
self._write_host_vars(
{"applications": {"web-app-nextcloud": {"services": {"dashboard": {}}}}}
)
self._make_role(
"web-app-nextcloud", {"dashboard": {"enabled": True, "shared": True}}
)
apply_services_disabled(self.host_vars, ["dashboard"], self.roles_dir)
service = self._read_host_vars()["applications"]["web-app-nextcloud"][
"services"
]["dashboard"]
self.assertEqual(False, service["enabled"])
self.assertEqual(False, service["shared"])
def test_disables_service_in_host_vars_and_removes_from_inventory(self):
self._write_host_vars(
{
@@ -7,7 +7,7 @@ import unittest
from cli.meta.ci.dev_runtime import image_label, workspace_matrix
from utils.symbol_glossary import to_emoji
IMAGES = ["debian:bookworm", "fedora:latest", "ubuntu:latest", "quay.io/centos:latest"]
IMAGES = ["debian:13", "fedora:latest", "ubuntu:latest", "quay.io/centos:latest"]
class TestWorkspaceMatrix(unittest.TestCase):
@@ -55,7 +55,7 @@ class TestWorkspaceMatrix(unittest.TestCase):
def test_a_label_keeps_only_the_last_two_segments(self) -> None:
self.assertEqual(image_label("quay.io/centos/centos:latest"), "centos:latest")
self.assertEqual(image_label("manjarolinux/base"), "manjarolinux/base")
self.assertEqual(image_label("debian:bookworm"), "debian:bookworm")
self.assertEqual(image_label("debian:13"), "debian:13")
self.assertEqual(image_label("ghcr.io/foo/bar/baz:1.2"), "baz:1.2")
self.assertEqual(image_label("plainname"), "plainname")
@@ -54,6 +54,11 @@ class TestProblems(unittest.TestCase):
self.assertEqual(errors, [])
self.assertIn("web-app-gone", warnings[0])
def test_a_pinned_role_the_run_never_discovers_only_warns(self) -> None:
errors, warnings = _problems("web-app-gone#0,2")
self.assertEqual(errors, [])
self.assertIn("web-app-gone", warnings[0])
def test_a_bare_role_the_run_discovers_is_silent(self) -> None:
self.assertEqual(_problems("web-app-a"), ([], []))
@@ -13,6 +13,7 @@ from utils.cache.yaml import dump_yaml
from utils.roles.mapping import (
ROLE_FILE_META_MAIN,
ROLE_FILE_META_SERVICES,
ROLE_FILE_META_VARIANTS,
ROLE_FILE_VARS_MAIN,
)
@@ -38,6 +39,22 @@ def _write_run_after(root: Path, role: str, run_after: list[str]) -> None:
)
def _write_sso_consumer(root: Path, role: str, variants: list[bool]) -> None:
"""A role consuming shared `sso`, with one variant per `variants` entry
that either keeps the consumption or switches it off."""
dump_yaml(
root / "roles" / role / ROLE_FILE_META_SERVICES,
{role: {}, "sso": {"enabled": True, "shared": True, "flavor": "oidc"}},
)
dump_yaml(
root / "roles" / role / ROLE_FILE_META_VARIANTS,
[
{"services": {"sso": {"enabled": consumes, "shared": consumes}}}
for consumes in variants
],
)
def _write_dependencies(root: Path, role: str, deps: list[str]) -> None:
dump_yaml(
root / "roles" / role / ROLE_FILE_META_MAIN,
@@ -104,6 +121,59 @@ class TestAffected(unittest.TestCase):
self.assertIn("web-app-keycloak", got)
self.assertIn("web-app-consumer", got)
def test_only_the_variants_reaching_the_seed_are_kept(self) -> None:
with tempfile.TemporaryDirectory() as td:
root = Path(td)
_mk_app_role(root, "web-app-keycloak", "keycloak")
_mk_app_role(root, "web-app-consumer", "consumer")
_write_sso_consumer(root, "web-app-consumer", [True, False, True])
with patch.object(repo_paths, "PROJECT_ROOT", root):
got = affected_main.affected_selection(["web-app-keycloak"])
self.assertIn("web-app-consumer#0,2", got)
def test_a_role_whose_variants_all_reach_the_seed_stays_bare(self) -> None:
with tempfile.TemporaryDirectory() as td:
root = Path(td)
_mk_app_role(root, "web-app-keycloak", "keycloak")
_mk_app_role(root, "web-app-consumer", "consumer")
_write_sso_consumer(root, "web-app-consumer", [True, True])
with patch.object(repo_paths, "PROJECT_ROOT", root):
got = affected_main.affected_selection(["web-app-keycloak"])
self.assertIn("web-app-consumer", got)
def test_the_narrowing_follows_a_parents_variant_one_generation_up(self) -> None:
with tempfile.TemporaryDirectory() as td:
root = Path(td)
_mk_app_role(root, "web-app-keycloak", "keycloak")
_mk_app_role(root, "web-app-matomo", "matomo")
_mk_app_role(root, "web-app-consumer", "consumer")
_write_sso_consumer(root, "web-app-matomo", [True, False])
dump_yaml(
root / "roles" / "web-app-consumer" / ROLE_FILE_META_SERVICES,
{"consumer": {}, "matomo": {"enabled": True, "shared": True}},
)
dump_yaml(
root / "roles" / "web-app-consumer" / ROLE_FILE_META_VARIANTS,
[{"services": {"matomo": {"enabled": True, "shared": True}}}] * 2,
)
with patch.object(repo_paths, "PROJECT_ROOT", root):
got = affected_main.affected_selection(["web-app-keycloak"])
self.assertIn("web-app-consumer#0", got)
def test_a_seed_keeps_every_variant_of_its_own_role(self) -> None:
with tempfile.TemporaryDirectory() as td:
root = Path(td)
_mk_app_role(root, "web-app-keycloak", "keycloak")
_mk_app_role(root, "web-app-consumer", "consumer")
_write_sso_consumer(root, "web-app-consumer", [True, False])
with patch.object(repo_paths, "PROJECT_ROOT", root):
got = affected_main.affected_selection(["web-app-consumer"])
self.assertEqual(got, ["web-app-consumer"])
def test_unknown_role_raises(self) -> None:
with tempfile.TemporaryDirectory() as td:
root = Path(td)
@@ -11,10 +11,18 @@ from utils.cache.yaml import load_yaml
_AI_VARS = Path(PROJECT_ROOT) / "group_vars" / "all" / "16_ai.yml"
def _stub_lookup(preload_models):
def _ansible_bool(value):
if isinstance(value, str):
return value.strip().lower() in ("true", "yes", "on", "1")
return bool(value)
def _stub_lookup(preload_models, lmstudio_models):
def lookup(kind, role, path, *args):
if (kind, path) == ("config", "services.ollama.preload_models"):
return preload_models
if (kind, path) == ("config", "services.lmstudio.preload_models"):
return lmstudio_models
raise AssertionError(f"unexpected lookup({kind!r}, {role!r}, {path!r})")
return lookup
@@ -36,15 +44,24 @@ class TestLitellmChatModel(unittest.TestCase):
cls.env.tests["search"] = lambda value, pattern: bool(
re.search(pattern, str(value))
)
cls.env.filters["bool"] = _ansible_bool
cls.source = load_yaml(_AI_VARS)
def _render(self, name, *, roles, api_key, preload_models=()):
def _render(self, name, *, roles, api_key, preload_models=(), lmstudio_models=()):
return (
self.env.from_string(self.source[name])
.render(
LITELLM_BACKEND_ROLES=list(roles),
OPENROUTER_API_KEY=api_key,
lookup=_stub_lookup(list(preload_models)),
LITELLM_OLLAMA_BACKEND=str("svc-ai-ollama" in roles),
LITELLM_LMSTUDIO_BACKEND=str("svc-ai-lmstudio" in roles),
AI_REMOTE_ALIASES=(["openrouter/auto"] if api_key else []),
lookup=_stub_lookup(
[{"alias": alias, "name": alias} for alias in preload_models],
[
{"alias": alias, "name": f"{alias}-gguf"}
for alias in lmstudio_models
],
),
)
.strip()
)
@@ -66,10 +83,35 @@ class TestLitellmChatModel(unittest.TestCase):
self.assertEqual(served, "True")
def test_lmstudio_wins_over_the_openrouter_fallback(self):
model, served = self._both(roles=["svc-ai-lmstudio"], api_key="")
self.assertEqual(model, "lmstudio/default")
model, served = self._both(
roles=["svc-ai-lmstudio"], api_key="", lmstudio_models=["qwen2.5:0.5b"]
)
self.assertEqual(model, "qwen2.5:0.5b")
self.assertEqual(served, "True")
def test_lmstudio_without_a_preloaded_model_serves_nothing(self):
served = self._render(
"LITELLM_CHAT_MODEL_SERVED", roles=["svc-ai-lmstudio"], api_key=""
)
self.assertEqual(served, "False")
def test_both_backends_name_the_same_model(self):
alias = "qwen2.5:0.5b"
with_ollama = self._render(
"LITELLM_CHAT_MODEL",
roles=["svc-ai-ollama"],
api_key="",
preload_models=[alias],
)
with_lmstudio = self._render(
"LITELLM_CHAT_MODEL",
roles=["svc-ai-lmstudio"],
api_key="",
lmstudio_models=[alias],
)
self.assertEqual(with_ollama, with_lmstudio)
self.assertEqual(with_ollama, alias)
def test_ollama_serves_its_first_non_embedding_model(self):
model, served = self._both(
roles=["svc-ai-ollama"],
@@ -90,15 +132,19 @@ class TestLitellmChatModel(unittest.TestCase):
def test_the_model_is_named_exactly_when_one_is_served(self):
cases = (
(["web-app-mattermost"], "", ()),
(["web-app-mattermost"], "sk-test", ()),
(["svc-ai-lmstudio"], "", ()),
(["svc-ai-ollama"], "", ("llama3.2",)),
(["web-app-mattermost"], "", (), ()),
(["web-app-mattermost"], "sk-test", (), ()),
(["svc-ai-lmstudio"], "", (), ()),
(["svc-ai-lmstudio"], "", (), ("qwen2.5:0.5b",)),
(["svc-ai-ollama"], "", ("llama3.2",), ()),
)
for roles, api_key, preload in cases:
with self.subTest(roles=roles, api_key=bool(api_key)):
for roles, api_key, preload, lmstudio in cases:
with self.subTest(roles=roles, api_key=bool(api_key), lmstudio=lmstudio):
model, served = self._both(
roles=roles, api_key=api_key, preload_models=preload
roles=roles,
api_key=api_key,
preload_models=preload,
lmstudio_models=lmstudio,
)
self.assertEqual(bool(model), served == "True")
@@ -68,6 +68,46 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase):
):
action.run(task_vars={})
def test_clear_drops_the_fact_without_rendering(self):
lookup = _FakeLookup({"key": ["roles", []], "applications": {}})
action = _make_action(_FakeTask(args={"clear": True}))
with (
patch(
"plugins.action.applications_carrier.ActionBase.run",
autospec=True,
return_value={},
),
patch(
"plugins.action.applications_carrier.lookup_loader.get",
return_value=lookup,
),
):
result = action.run(task_vars={"applications": {}})
self.assertIsNone(result["ansible_facts"][APPLICATIONS_RENDERED_FACT])
self.assertFalse(result["changed"])
self.assertEqual(lookup.calls, [])
def test_clear_false_still_renders(self):
carrier = {"key": ["roles", ["a", "b", "c", "d"]], "applications": {"x": {}}}
lookup = _FakeLookup(carrier)
action = _make_action(_FakeTask(args={"clear": "no"}))
with (
patch(
"plugins.action.applications_carrier.ActionBase.run",
autospec=True,
return_value={},
),
patch(
"plugins.action.applications_carrier.lookup_loader.get",
return_value=lookup,
),
):
result = action.run(task_vars={"applications": {}})
self.assertIs(result["ansible_facts"][APPLICATIONS_RENDERED_FACT], carrier)
self.assertEqual(len(lookup.calls), 1)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,74 @@
import sys
import unittest
from . import PROJECT_ROOT
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
from ansible.errors import AnsibleFilterError
from plugins.filter.redirect_sources import FilterModule, redirect_sources
class TestRedirectSources(unittest.TestCase):
def test_every_reference_form_is_covered(self):
self.assertEqual(
redirect_sources("unpkg.com"),
[
"https://unpkg.com/",
"http://unpkg.com/",
"/",
],
)
def test_the_catch_all_comes_last(self):
sources = redirect_sources("unpkg.com")
self.assertEqual(
sources[-1],
"/",
"the bare slash is the widest form and reads as the fallback only "
"while it stays at the end",
)
def test_no_form_is_a_prefix_of_another(self):
sources = redirect_sources("unpkg.com")
for index, source in enumerate(sources):
for other in sources[:index]:
self.assertFalse(
source.startswith(other),
f"{source!r} starts with {other!r}, so the two forms "
f"cannot be told apart by a prefix comparison",
)
def test_surrounding_whitespace_is_dropped(self):
self.assertEqual(redirect_sources(" unpkg.com ")[0], "https://unpkg.com/")
def test_the_host_is_not_otherwise_rewritten(self):
self.assertEqual(
redirect_sources("CDN.Example.COM")[1], "http://CDN.Example.COM/"
)
def test_a_subdomain_host_keeps_every_label(self):
self.assertEqual(
redirect_sources("cdn.jsdelivr.net")[0], "https://cdn.jsdelivr.net/"
)
def test_an_empty_host_is_rejected(self):
for value in ("", " "):
with self.assertRaises(AnsibleFilterError):
redirect_sources(value)
def test_a_non_string_host_is_rejected(self):
for value in (None, 42, ["unpkg.com"]):
with self.assertRaises(AnsibleFilterError):
redirect_sources(value)
def test_the_filter_is_exported(self):
self.assertIs(FilterModule().filters()["redirect_sources"], redirect_sources)
if __name__ == "__main__":
unittest.main()
@@ -1,13 +1,20 @@
"""Unit tests for plugins/lookup/alert_rule_roles.py.
Mocks the Ansible-side machinery and asserts the plugin returns exactly the
deployed roles that ship a ``templates/prometheus/alert_rules.yml.j2``.
scraped roles that ship a ``templates/prometheus/alert_rules.yml.j2``.
Activation is delegated to ``native_metrics_apps`` rather than re-derived here,
so these tests stub that lookup and assert the intersection. A role that is
deployed but not scraped must not contribute rules: its alert would fire on
``absent()`` forever.
"""
from __future__ import annotations
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path
import plugins.lookup.alert_rule_roles as module
from plugins.lookup.alert_rule_roles import LookupModule
@@ -39,19 +46,26 @@ def _seed_roles(tmp_path, roles_with_template, roles_without_template=()):
class TestAlertRuleRolesLookup(unittest.TestCase):
def setUp(self):
self._tmp = mock.patch.object(module, "ROLES_DIR")
self.roles_dir = self._tmp.start()
self.addCleanup(self._tmp.stop)
self._roles_dir = mock.patch.object(module, "ROLES_DIR")
self.roles_dir = self._roles_dir.start()
self.addCleanup(self._roles_dir.stop)
def _patch_scraped(self, scraped):
"""Stand in for the native_metrics_apps lookup."""
inner = mock.MagicMock()
inner.run.return_value = [list(scraped)]
loader = mock.patch.object(module, "lookup_loader")
started = loader.start()
started.get.return_value = inner
self.addCleanup(loader.stop)
def test_raises_when_positional_terms_supplied(self):
self._patch_scraped([])
lm = _make_lookup({"group_names": []})
with self.assertRaises(ValueError):
lm.run(["unexpected"], variables=lm._templar.available_variables)
def test_returns_only_deployed_roles_that_ship_a_template(self):
import tempfile
from pathlib import Path
def test_returns_only_scraped_roles_that_ship_a_template(self):
with tempfile.TemporaryDirectory() as td:
tmp_path = Path(td)
_seed_roles(
@@ -60,35 +74,40 @@ class TestAlertRuleRolesLookup(unittest.TestCase):
roles_without_template=["web-app-matomo"],
)
module.ROLES_DIR = tmp_path
self._patch_scraped(["web-app-matomo", "web-app-openbao"])
vars_ = {
"group_names": [
"web-app-matomo",
"web-app-openbao",
"web-app-never-deployed",
]
}
lm = _make_lookup(vars_)
self.assertEqual(lm.run([], variables=vars_), [["web-app-openbao"]])
lm = _make_lookup({})
self.assertEqual(lm.run([], variables={}), [["web-app-openbao"]])
def test_a_deployed_role_that_is_not_scraped_contributes_no_rules(self):
"""The whole point of moving the filter out of the fragments.
svc-db-postgres ships a template here but native_metrics_apps does not
list it, so its rules must not reach the file.
"""
with tempfile.TemporaryDirectory() as td:
tmp_path = Path(td)
_seed_roles(tmp_path, roles_with_template=["svc-db-postgres"])
module.ROLES_DIR = tmp_path
self._patch_scraped([])
lm = _make_lookup({})
self.assertEqual(lm.run([], variables={}), [[]])
def test_result_is_sorted_and_deduplicated(self):
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as td:
tmp_path = Path(td)
_seed_roles(tmp_path, roles_with_template=["b-role", "a-role"])
module.ROLES_DIR = tmp_path
self._patch_scraped(["b-role", "a-role", "b-role"])
vars_ = {"group_names": ["b-role", "a-role", "b-role"]}
lm = _make_lookup(vars_)
self.assertEqual(lm.run([], variables=vars_), [["a-role", "b-role"]])
def test_returns_empty_list_without_group_names(self):
import tempfile
from pathlib import Path
lm = _make_lookup({})
self.assertEqual(lm.run([], variables={}), [["a-role", "b-role"]])
def test_returns_empty_list_when_nothing_is_scraped(self):
with tempfile.TemporaryDirectory() as td:
module.ROLES_DIR = Path(td)
self._patch_scraped([])
lm = _make_lookup({})
self.assertEqual(lm.run([], variables={}), [[]])
+12 -2
View File
@@ -90,9 +90,19 @@ class TestApiLookup(unittest.TestCase):
self.lookup.run(["cloudflare.api_token"], variables={"API": "nope"})
self.assertIn("mapping", str(ctx.exception))
def test_missing_api_global_raises_unknown_key(self):
def test_missing_api_global_falls_back_to_the_declaration(self):
self.assertEqual(self.lookup.run(["cloudflare.api_token"], variables={})[0], "")
def test_a_provider_the_scope_omits_still_resolves(self):
out = self.lookup.run(
["github.client_id"],
variables={"API": {"cloudflare": {"api_token": "cf"}}},
)
self.assertEqual(out, [""])
def test_an_undeclared_provider_still_raises(self):
with self.assertRaises(AnsibleError):
self.lookup.run(["cloudflare.api_token"], variables={})
self.lookup.run(["nope.api_key"], variables=self.vars)
def test_templar_resolves_jinja_values(self):
self.lookup._templar = _FakeTemplar(mapping={"{{ vault_cf }}": "secret-cf"})
@@ -119,5 +119,133 @@ class TestContainerPortsLookup(unittest.TestCase):
self.assertEqual(out, ['ports:\n - "10.0.0.1:8002:3000"'])
def _edge_apps():
return {
"web-svc-coturn": {
"services": {
"coturn": {
"ports": {
"public": {
"stun_turn": 3481,
"relay": {"start": 20000, "end": 39999},
}
}
},
"openresty": {
"ports": {
"internal": {"http": 80},
"public": {"http": 80},
}
},
"api": {"ports": {"internal": {"http": 5000}}},
}
}
}
def _run_edge(terms):
lookup = LookupModule()
lookup._loader = mock.MagicMock()
apps = _edge_apps()
with patch("plugins.lookup.container_ports.lookup_loader") as loader_mock:
loader_mock.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [apps])
return lookup.run(terms, variables={"application_id": "web-svc-coturn"})[0]
class TestContainerPortsDictTerms(unittest.TestCase):
def test_one_list_item_per_transport(self):
out = _run_edge(
[
{
"service": "coturn",
"protocol": "stun_turn",
"transport": ["udp", "tcp"],
"container": "same",
}
]
)
self.assertEqual(out, 'ports:\n - "3481:3481/udp"\n - "3481:3481/tcp"')
def test_a_range_renders_on_both_sides(self):
out = _run_edge(
[
{
"service": "coturn",
"protocol": "relay",
"transport": "udp",
"container": "same",
}
]
)
self.assertEqual(out, 'ports:\n - "20000-39999:20000-39999/udp"')
def test_host_mode_emits_the_long_block(self):
out = _run_edge([{"service": "openresty", "protocol": "http", "mode": "host"}])
self.assertEqual(
out,
"ports:\n - target: 80\n published: 80\n"
" protocol: tcp\n mode: host",
)
def test_ephemeral_publishes_only_the_container_port(self):
out = _run_edge(
[{"service": "api", "protocol": "http", "publish": "ephemeral"}]
)
self.assertEqual(out, 'ports:\n - "5000"')
def test_host_mode_rejects_an_ip(self):
with self.assertRaises(AnsibleError):
_run_edge(
[
{
"service": "openresty",
"protocol": "http",
"mode": "host",
"ip": "10.0.0.1",
}
]
)
def test_an_unknown_term_key_is_rejected(self):
with self.assertRaises(AnsibleError):
_run_edge([{"service": "openresty", "protocol": "http", "protokol": "tcp"}])
def test_key_names_the_block(self):
lookup = LookupModule()
lookup._loader = mock.MagicMock()
with patch("plugins.lookup.container_ports.lookup_loader") as loader_mock:
loader_mock.get.return_value = mock.MagicMock(
run=lambda *_a, **_k: [_edge_apps()]
)
out = lookup.run(
[["openresty", "http"]],
variables={"application_id": "web-svc-coturn"},
key="expose",
)
self.assertEqual(out, ['expose:\n - "80:80"'])
def test_an_unknown_block_key_is_rejected(self):
lookup = LookupModule()
lookup._loader = mock.MagicMock()
with (
patch("plugins.lookup.container_ports.lookup_loader") as loader_mock,
self.assertRaises(AnsibleError),
):
loader_mock.get.return_value = mock.MagicMock(
run=lambda *_a, **_k: [_edge_apps()]
)
lookup.run(
[["openresty", "http"]],
variables={"application_id": "web-svc-coturn"},
key="publish",
)
def test_an_unknown_transport_is_rejected(self):
with self.assertRaises(AnsibleError):
_run_edge(
[{"service": "openresty", "protocol": "http", "transport": "sctp"}]
)
if __name__ == "__main__":
unittest.main()
@@ -66,9 +66,28 @@ class OidcFlavorLookupTests(unittest.TestCase):
self._patcher = mock.patch.object(self.mod, "lookup_loader")
self._loader_mock = self._patcher.start()
self._stub_payload = None
self._loader_mock.get.return_value = mock.MagicMock(
run=lambda *_a, **_k: [self._stub_payload]
)
self._loader_mock.get.side_effect = self._stub_lookup
def _stub_lookup(self, name, *_args, **_kwargs):
"""Stand in for the lookups the plugin consumes.
``config`` resolves a dotted path against the payload the way
``lookup('config', app, path, default)`` does with a default supplied;
anything else answers with the payload itself.
"""
if name == "config":
return mock.MagicMock(
run=lambda terms, **_kw: [self._stub_config(*terms)],
)
return mock.MagicMock(run=lambda *_a, **_kw: [self._stub_payload])
def _stub_config(self, application_id, config_path, default=None):
node = (self._stub_payload or {}).get(application_id)
for part in str(config_path).split("."):
if not isinstance(node, dict) or part not in node:
return default
node = node[part]
return node
def tearDown(self):
self._patcher.stop()
@@ -9,7 +9,7 @@ from ansible.errors import AnsibleError
from plugins.lookup.tor_ports import (
LookupModule,
collect_exposed_ports,
collect_public_ports,
collect_onion_ports,
)
from utils.cache import _reset_cache_for_tests
from utils.cache.yaml import dump_yaml_str
@@ -33,7 +33,15 @@ class TestTorPortsLookup(unittest.TestCase):
_write_services(
self.roles_dir,
"web-app-gitea",
{"gitea": {"ports": {"public": {"ssh": 2201}, "local": {"http": 8002}}}},
{
"gitea": {
"ports": {
"public": {"ssh": 2201},
"local": {"http": 8002},
"onion": {"ssh": True},
}
}
},
)
_write_services(
self.roles_dir,
@@ -68,40 +76,159 @@ class TestTorPortsLookup(unittest.TestCase):
_reset_cache_for_tests()
self._tmpdir.cleanup()
def test_collects_public_single_ints_sorted(self) -> None:
ports = collect_public_ports(
["web-app-gitea", "svc-db-openldap"], self.roles_dir
@staticmethod
def _apps(**roles: dict) -> dict:
"""The variant-merged applications view for the given roles.
Every entity keeps its own ``ports``; the top-level ``tor:`` block of
``meta/services.yml`` merges in as one more entity alongside them.
"""
return {role: {"services": dict(entities)} for role, entities in roles.items()}
def test_only_named_categories_are_forwarded_sorted(self) -> None:
apps = self._apps(
**{
"web-app-gitea": {
"gitea": {
"ports": {"public": {"ssh": 2201}, "onion": {"ssh": True}}
}
},
"web-app-mailu": {
"mailu": {
"ports": {
"public": {"smtp": 25, "smtps": 465, "imap": 143},
"onion": {"smtp": True},
}
}
},
}
)
self.assertEqual(ports, [636, 2201])
def test_relay_ranges_excluded(self) -> None:
ports = collect_public_ports(["web-svc-coturn"], self.roles_dir)
self.assertEqual(ports, [3481, 5351])
ports = collect_onion_ports(apps, ["web-app-gitea", "web-app-mailu"])
def test_media_category_excluded(self) -> None:
_write_services(
self.roles_dir,
"web-app-jitsi",
{"jitsi": {"ports": {"public": {"media": 10000}, "local": {"http": 8084}}}},
self.assertEqual(ports, [25, 2201])
def test_local_wins_over_public_for_the_same_category(self) -> None:
"""``container_ports`` publishes the local port when the category has
one, so the forward must target that and not the public alias."""
apps = self._apps(
**{
"web-app-x": {
"x": {
"ports": {
"local": {"http": 8080},
"public": {"http": 80},
"onion": {"http": True},
}
}
}
}
)
self.assertEqual(collect_public_ports(["web-app-jitsi"], self.roles_dir), [])
def test_roles_without_public_ports_yield_nothing(self) -> None:
self.assertEqual(collect_public_ports(["web-app-hugo"], self.roles_dir), [])
self.assertEqual(collect_onion_ports(apps, ["web-app-x"]), [8080])
def test_tor_disabled_role_excluded(self) -> None:
_write_services(
self.roles_dir,
"web-app-optout",
{
"optout": {"ports": {"public": {"ssh": 2299}}},
"tor": {"enabled": False},
},
def test_a_falsy_or_unrendered_flag_forwards_nothing(self) -> None:
"""The input must be the rendered view: template text left in the flag
is not quietly read as enabled."""
apps = self._apps(
**{
"web-app-a": {
"a": {"ports": {"public": {"ssh": 22}, "onion": {"ssh": False}}}
},
"web-app-b": {
"b": {
"ports": {
"public": {"ssh": 23},
"onion": {"ssh": "{{ 'svc-net-tor' in group_names }}"},
}
}
},
}
)
self.assertEqual(collect_public_ports(["web-app-optout"], self.roles_dir), [])
def test_unknown_role_ignored(self) -> None:
self.assertEqual(collect_public_ports(["web-app-nope"], self.roles_dir), [])
self.assertEqual(collect_onion_ports(apps, ["web-app-a", "web-app-b"]), [])
def test_udp_only_categories_are_never_forwarded(self) -> None:
apps = self._apps(
**{
"web-svc-coturn": {
"coturn": {
"ports": {
"public": {
"media": 10000,
"stun_turn": 3481,
"stun_turn_tls": 5351,
"ssh": 2299,
"relay": {"start": 20000, "end": 39999},
},
"onion": {
"media": True,
"relay": True,
"stun_turn": True,
"stun_turn_tls": True,
"ssh": True,
},
}
}
}
}
)
self.assertEqual(collect_onion_ports(apps, ["web-svc-coturn"]), [2299])
def test_a_category_with_no_declared_port_is_skipped(self) -> None:
apps = self._apps(
**{
"web-app-x": {
"x": {"ports": {"public": {"ssh": 2201}, "onion": {"typo": True}}}
}
}
)
self.assertEqual(collect_onion_ports(apps, ["web-app-x"]), [])
def test_a_role_without_an_onion_block_forwards_nothing(self) -> None:
apps = self._apps(
**{"web-app-hugo": {"hugo": {"ports": {"local": {"http": 8008}}}}}
)
self.assertEqual(collect_onion_ports(apps, ["web-app-hugo"]), [])
def test_the_port_flag_is_the_gate_not_the_tor_flag(self) -> None:
"""``services.tor.enabled`` is the dependency edge onto svc-net-tor, not
the port forward; ``ports.onion`` alone decides what gets a
HiddenServicePort."""
apps = self._apps(
**{
"web-app-gitea": {
"tor": {"enabled": False},
"gitea": {
"ports": {"public": {"ssh": 2201}, "onion": {"ssh": True}}
},
}
}
)
self.assertEqual(collect_onion_ports(apps, ["web-app-gitea"]), [2201])
def test_role_outside_the_deploy_is_ignored(self) -> None:
apps = self._apps(
**{
"web-app-gitea": {
"gitea": {
"ports": {"public": {"ssh": 2201}, "onion": {"ssh": True}}
}
}
}
)
self.assertEqual(collect_onion_ports(apps, ["web-app-nope"]), [])
def test_collect_onion_ports_ignores_non_mappings(self) -> None:
self.assertEqual(collect_onion_ports({}, ["a"]), [])
self.assertEqual(collect_onion_ports(None, ["a"]), [])
apps = {"a": {"services": {"s": {"ports": {"onion": True}}}}}
self.assertEqual(collect_onion_ports(apps, ["a"]), [])
def test_collect_exposed_ports_gated_and_deployed(self) -> None:
apps = {
@@ -151,6 +278,14 @@ class TestTorPortsLookup(unittest.TestCase):
)[0]
self.assertEqual(result, [{"onion_port": 2201, "target": "127.0.0.1:2201"}])
def test_run_forwards_nothing_without_an_onion_opt_in(self) -> None:
result = self.lookup.run(
[],
variables={"group_names": ["svc-db-openldap", "web-svc-coturn"]},
roles_dir=str(self.roles_dir),
)[0]
self.assertEqual(result, [])
def test_empty_group_names(self) -> None:
result = self.lookup.run([], variables={}, roles_dir=str(self.roles_dir))[0]
self.assertEqual(result, [])
@@ -0,0 +1,216 @@
"""Unit tests for the svc-ai-litellm routing probe's verdict logic."""
from __future__ import annotations
import importlib.util
import unittest
from . import PROJECT_ROOT
MODULE_PATH = PROJECT_ROOT / "roles/svc-ai-litellm/files/test/probe.py"
spec = importlib.util.spec_from_file_location("litellm_probe", MODULE_PATH)
probe = importlib.util.module_from_spec(spec)
spec.loader.exec_module(probe)
ALIAS = "qwen2.5:0.5b"
LMSTUDIO_ONLY = "mistral:latest"
def verdict(**overrides) -> list[str]:
kwargs = {
"served": set(),
"expected": [],
"chat_model": "",
"chat_model_served": False,
"ollama_enabled": False,
"lmstudio_enabled": False,
"lmstudio_aliases": [LMSTUDIO_ONLY],
"remote_aliases": [],
}
kwargs.update(overrides)
return probe.evaluate(**kwargs)
class TestOllamaOnlyDeployment(unittest.TestCase):
"""svc-ai-ollama deployed, svc-ai-lmstudio not — variant 0."""
def test_a_consistent_gateway_passes(self) -> None:
self.assertEqual(
verdict(
served={ALIAS},
expected=[ALIAS],
chat_model=ALIAS,
chat_model_served=True,
ollama_enabled=True,
),
[],
)
def test_an_lmstudio_alias_without_its_backend_fails(self) -> None:
failures = verdict(
served={ALIAS, LMSTUDIO_ONLY},
expected=[ALIAS],
chat_model=ALIAS,
chat_model_served=True,
ollama_enabled=True,
)
self.assertEqual(len(failures), 1)
self.assertIn("svc-ai-lmstudio is not deployed", failures[0])
def test_a_declared_model_the_gateway_dropped_fails(self) -> None:
failures = verdict(
served=set(),
expected=[ALIAS],
chat_model=ALIAS,
chat_model_served=True,
ollama_enabled=True,
)
self.assertTrue(
any("does not serve" in failure for failure in failures), failures
)
def test_the_model_consumers_ask_for_must_be_routable(self) -> None:
failures = verdict(
served={ALIAS},
expected=[ALIAS],
chat_model="llama3:latest",
chat_model_served=True,
ollama_enabled=True,
)
self.assertEqual(len(failures), 1)
self.assertIn("llama3:latest", failures[0])
class TestLmstudioOnlyDeployment(unittest.TestCase):
"""svc-ai-lmstudio deployed, svc-ai-ollama not — variant 2."""
def test_the_same_alias_ollama_would_serve_passes(self) -> None:
self.assertEqual(
verdict(
served={ALIAS},
expected=[ALIAS],
chat_model=ALIAS,
chat_model_served=True,
lmstudio_enabled=True,
lmstudio_aliases=[ALIAS],
),
[],
)
def test_a_declared_alias_the_gateway_never_routed_fails(self) -> None:
failures = verdict(
served=set(),
expected=[ALIAS],
chat_model=ALIAS,
chat_model_served=True,
lmstudio_enabled=True,
lmstudio_aliases=[ALIAS],
)
self.assertTrue(
any("declared and not routed" in failure for failure in failures), failures
)
def test_an_ollama_model_without_its_backend_fails(self) -> None:
failures = verdict(
served={ALIAS, "llama3:latest"},
expected=[ALIAS],
chat_model=ALIAS,
chat_model_served=True,
lmstudio_enabled=True,
lmstudio_aliases=[ALIAS],
)
self.assertTrue(
any("svc-ai-ollama is not deployed" in failure for failure in failures),
failures,
)
class TestBothBackendsDeployment(unittest.TestCase):
"""Variant 0 plus lmstudio: a shared alias proves nothing about lmstudio."""
def test_only_the_exclusive_alias_is_demanded(self) -> None:
self.assertEqual(
verdict(
served={ALIAS, LMSTUDIO_ONLY},
expected=[ALIAS, LMSTUDIO_ONLY],
chat_model=ALIAS,
chat_model_served=True,
ollama_enabled=True,
lmstudio_enabled=True,
),
[],
)
def test_a_missing_exclusive_alias_still_fails(self) -> None:
failures = verdict(
served={ALIAS},
expected=[ALIAS],
chat_model=ALIAS,
chat_model_served=True,
ollama_enabled=True,
lmstudio_enabled=True,
)
self.assertTrue(
any("declared and not routed" in failure for failure in failures), failures
)
class TestRemoteProviders(unittest.TestCase):
"""A configured provider key publishes its alias and serves the gateway."""
def test_a_keyed_provider_is_the_only_backend_needed(self) -> None:
self.assertEqual(
verdict(
served={"openai/gpt-4o-mini"},
expected=["openai/gpt-4o-mini"],
chat_model="openai/gpt-4o-mini",
chat_model_served=True,
remote_aliases=["openai/gpt-4o-mini"],
),
[],
)
def test_a_remote_alias_is_not_mistaken_for_an_ollama_model(self) -> None:
self.assertEqual(
verdict(
served={"anthropic/claude-sonnet-4-5", ALIAS},
expected=["anthropic/claude-sonnet-4-5", ALIAS],
chat_model=ALIAS,
chat_model_served=True,
lmstudio_enabled=True,
lmstudio_aliases=[ALIAS],
remote_aliases=["anthropic/claude-sonnet-4-5"],
),
[],
)
def test_a_declared_provider_the_gateway_dropped_fails(self) -> None:
failures = verdict(
served=set(),
expected=["openrouter/auto"],
chat_model="openrouter/auto",
chat_model_served=True,
remote_aliases=["openrouter/auto"],
)
self.assertTrue(
any("does not serve" in failure for failure in failures), failures
)
class TestNoBackendDeployment(unittest.TestCase):
def test_an_empty_gateway_passes(self) -> None:
self.assertEqual(verdict(), [])
def test_any_published_model_fails(self) -> None:
failures = verdict(served={"openrouter/auto"})
self.assertTrue(
any("no backend is deployed" in failure for failure in failures), failures
)
def test_the_chat_model_is_not_demanded_when_nothing_serves_it(self) -> None:
self.assertEqual(verdict(chat_model=ALIAS), [])
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,3 @@
from pathlib import Path
PROJECT_ROOT: Path = Path(__file__).resolve().parents[6]
@@ -0,0 +1,169 @@
"""The gateway config publishes one alias per model, whichever backend serves it.
``config.yaml.j2`` is where the two local backends meet: Ollama pulls a model
under the alias and LM Studio under its own hub name, and both must surface to
consumers as the same ``model_name``. A wrong accessor or a missing de-duplicate
condition does not fail the render, it publishes a route nothing answers, so the
template is rendered here rather than read.
"""
from __future__ import annotations
import unittest
import yaml
from jinja2 import Environment, StrictUndefined
from utils.cache.files import read_text
from . import PROJECT_ROOT
TEMPLATE = PROJECT_ROOT / "roles/svc-ai-litellm/templates/config.yaml.j2"
SHARED = {"alias": "qwen2.5:0.5b", "name": "qwen2.5-0.5b-instruct"}
OLLAMA_ONLY = {"alias": "llama3:latest", "name": "llama-3.2-3b-instruct"}
LMSTUDIO_ONLY = {"alias": "mistral:latest", "name": "mistral-7b-instruct-v0.3"}
OLLAMA_URL = "http://ollama:11434"
LMSTUDIO_URL = "http://lmstudio:1234"
def _ansible_bool(value):
if isinstance(value, str):
return value.strip().lower() in ("true", "yes", "on", "1")
return bool(value)
def _stub_lookup(ollama_models, lmstudio_models):
def lookup(kind, role, path, *args):
if (kind, path) == ("config", "services.ollama.preload_models"):
return ollama_models
if (kind, path) == ("config", "services.lmstudio.preload_models"):
return lmstudio_models
raise AssertionError(f"unexpected lookup({kind!r}, {role!r}, {path!r})")
return lookup
REMOTE_BACKENDS = (
("openai/gpt-4o-mini", "openai/gpt-4o-mini", "OPENAI_API_KEY"),
("anthropic/claude-sonnet-4-5", "anthropic/claude-sonnet-4-5", "ANTHROPIC_API_KEY"),
("openrouter/auto", "openrouter/openrouter/auto", "OPENROUTER_API_KEY"),
)
def _remote(keys):
"""The LITELLM_REMOTE_BACKENDS list vars/main.yml builds, with these keys.
Args:
keys: env-name -> key value; a provider absent from it stays unkeyed.
"""
return [
{"alias": alias, "model": model, "env": env, "key": keys.get(env, "")}
for alias, model, env in REMOTE_BACKENDS
]
def render(*, ollama=(), lmstudio=(), keys=None):
"""The rendered config as a parsed mapping.
Args:
ollama: preload entries svc-ai-ollama declares; empty means not deployed.
lmstudio: preload entries svc-ai-lmstudio declares; empty means not deployed.
keys: env-name -> provider key for the remote backends.
"""
env = Environment(undefined=StrictUndefined, autoescape=False) # noqa: S701 - YAML, not markup
env.filters["bool"] = _ansible_bool
rendered = env.from_string(read_text(str(TEMPLATE))).render(
LITELLM_OLLAMA_BACKEND=str(bool(ollama)),
LITELLM_LMSTUDIO_BACKEND=str(bool(lmstudio)),
lookup=_stub_lookup(list(ollama), list(lmstudio)),
OLLAMA_BASE_LOCAL_URL=OLLAMA_URL,
LMSTUDIO_BASE_LOCAL_URL=LMSTUDIO_URL,
LITELLM_MAX_OUTPUT_TOKENS=512,
LITELLM_UPSTREAM_TIMEOUT=60,
LITELLM_REMOTE_BACKENDS=_remote(keys or {}),
)
return yaml.safe_load(
rendered
) # nocheck: direct-yaml - parses this test's own render
def routes(config) -> dict:
return {
entry["model_name"]: entry["litellm_params"]
for entry in (config.get("model_list") or [])
}
class TestOllamaOnly(unittest.TestCase):
def test_every_alias_is_published_against_the_ollama_backend(self) -> None:
published = routes(render(ollama=[SHARED, OLLAMA_ONLY]))
self.assertEqual(set(published), {SHARED["alias"], OLLAMA_ONLY["alias"]})
self.assertEqual(
published[SHARED["alias"]]["model"], f"ollama/{SHARED['alias']}"
)
self.assertEqual(published[SHARED["alias"]]["api_base"], OLLAMA_URL)
class TestLmstudioOnly(unittest.TestCase):
def test_the_alias_is_published_against_the_lmstudio_name(self) -> None:
published = routes(render(lmstudio=[SHARED, LMSTUDIO_ONLY]))
self.assertEqual(set(published), {SHARED["alias"], LMSTUDIO_ONLY["alias"]})
self.assertEqual(
published[SHARED["alias"]]["model"], f"openai/{SHARED['name']}"
)
self.assertEqual(published[SHARED["alias"]]["api_base"], f"{LMSTUDIO_URL}/v1")
def test_an_alias_reaches_the_same_name_ollama_would_publish(self) -> None:
self.assertEqual(
set(routes(render(lmstudio=[SHARED]))),
set(routes(render(ollama=[SHARED]))),
)
class TestBothBackends(unittest.TestCase):
def test_a_shared_alias_is_published_once_and_routed_to_ollama(self) -> None:
published = routes(
render(ollama=[SHARED, OLLAMA_ONLY], lmstudio=[SHARED, LMSTUDIO_ONLY])
)
self.assertEqual(
set(published),
{SHARED["alias"], OLLAMA_ONLY["alias"], LMSTUDIO_ONLY["alias"]},
)
self.assertEqual(published[SHARED["alias"]]["api_base"], OLLAMA_URL)
self.assertEqual(
published[LMSTUDIO_ONLY["alias"]]["api_base"], f"{LMSTUDIO_URL}/v1"
)
class TestNoBackend(unittest.TestCase):
def test_the_model_list_is_empty(self) -> None:
self.assertEqual(render()["model_list"], [])
def test_one_provider_key_alone_publishes_its_route(self) -> None:
published = routes(render(keys={"OPENROUTER_API_KEY": "sk-or-test"}))
self.assertEqual(set(published), {"openrouter/auto"})
self.assertEqual(
published["openrouter/auto"]["api_key"], "os.environ/OPENROUTER_API_KEY"
)
def test_each_keyed_provider_gets_its_own_route(self) -> None:
published = routes(
render(
keys={
"OPENAI_API_KEY": "sk-test",
"ANTHROPIC_API_KEY": "sk-ant-test",
}
)
)
self.assertEqual(
set(published), {"openai/gpt-4o-mini", "anthropic/claude-sonnet-4-5"}
)
def test_an_unkeyed_provider_publishes_nothing(self) -> None:
self.assertEqual(render(keys={"OPENAI_API_KEY": ""})["model_list"], [])
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,3 @@
from pathlib import Path
PROJECT_ROOT: Path = Path(__file__).resolve().parents[5]
@@ -0,0 +1,236 @@
"""Every role's nftables fragment parses, and replaces its table instead of merging.
``nft -f`` on ``table inet x { ... }`` MERGES into an existing table: a rule
dropped from the declaration stays in the kernel, and the ruleset can only ever
grow. The three-line idiom below is what makes a fragment a replacement:
table inet x <- creates it when absent, so the delete cannot fail
delete table inet x <- removes whatever the last deploy left
table inet x { ... } <- the declaration, applied in the same transaction
``nft -f`` is atomic, so the table is never observed empty. Without the first
line the delete fails on a fresh host; without the second the fragment merges.
The checks run the real ``nft`` over the rendered text, so a fragment that is
valid Jinja but invalid nftables fails here rather than on the host. They render
every deploy mode, because a fragment may branch on one, and feed plausible
rather than real values: nft needs shapes, not this host's addresses.
"""
from __future__ import annotations
import os
import re
import shutil
import subprocess
import tempfile
import unittest
from contextlib import contextmanager
from functools import lru_cache
from pathlib import Path
import jinja2
from utils.cache.files import iter_project_files, read_text
from utils.cache.yaml import load_yaml_any
from utils.roles.mapping import ROLE_FILE_VARS_MAIN
from . import PROJECT_ROOT
FRAGMENT = "templates/nftables.conf.j2"
TABLE = "infinito_probe"
PROBE_PORTS = {
"TOR_TRANS_PORT": "9040",
"TOR_DNS_PORT": "9053",
"TOR_SOCKS_PORT": "9050",
"TOR_DNSMASQ_PORT": "53",
}
_PORT_VARIABLE = re.compile(r"\{\{\s*([A-Z][A-Z0-9_]*)\s*\}\}")
def _guarded_ports() -> list[dict]:
"""The role's own guard list, with its port variables filled from stand-ins.
The shape has to come from the declaration: an entry that gains a key, a
protocol or a whole port must reach the rendered table here, or this check
keeps passing on a fixture the role stopped shipping.
"""
declared = load_yaml_any(
str(PROJECT_ROOT / "roles" / "svc-net-tor" / ROLE_FILE_VARS_MAIN)
)["TOR_EGRESS_GUARDED_PORTS"]
return [
{**entry, "port": PROBE_PORTS[_PORT_VARIABLE.search(entry["port"]).group(1)]}
for entry in declared
]
COMMON = {
"FIREWALL_TABLE": TABLE,
"TOR_EGRESS_CLIENT_CIDRS": ["127.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"],
"TOR_EGRESS_GUARDED_PORTS": _guarded_ports(),
"TOR_EGRESS_VIRTUAL_NET_IPV4": "10.192.0.0/10",
**PROBE_PORTS,
"TOR_CONTAINER_DNS_HOST": "172.17.0.1",
"NETWORK_INTERNAL_CIDRS": [
"127.0.0.0/8",
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
],
}
MODES = ("compose", "swarm")
def _run(argv: list[str]) -> subprocess.CompletedProcess[str]:
return subprocess.run(argv, capture_output=True, text=True, check=False)
@lru_cache(maxsize=1)
def _nft_can_check() -> bool:
"""Whether `nft -c` works here.
It is not a parser: it opens netlink and builds a cache against the live
kernel first, so on a runner without CAP_NET_ADMIN it fails on a valid
ruleset. Probing the binary's presence would make this suite red there.
"""
if shutil.which("nft") is None:
return False
with tempfile.NamedTemporaryFile("w", suffix=".conf") as handle:
handle.write("table inet infinito_capability_probe\n")
handle.flush()
return _run(["nft", "-c", "-f", handle.name]).returncode == 0
@contextmanager
def _network_namespace(name: str):
"""An empty namespace, so a loaded ruleset cannot reach the live one."""
created = _run(["ip", "netns", "add", name])
if created.returncode != 0:
raise unittest.SkipTest(f"cannot create a network namespace: {created.stderr}")
try:
yield ["ip", "netns", "exec", name]
finally:
_run(["ip", "netns", "del", name])
def _fragments() -> list[str]:
suffix = "/" + FRAGMENT
return sorted(
path
for path in iter_project_files(extensions=(".j2",), exclude_tests=True)
if path.endswith(suffix)
)
def _render(path: str, mode: str = "swarm") -> str:
environment = jinja2.Environment(
keep_trailing_newline=True,
trim_blocks=True,
autoescape=False, # noqa: S701 nftables, not markup
)
return environment.from_string(read_text(path)).render(
DEPLOYMENT_MODE=mode, **COMMON
)
class TestFirewallFragments(unittest.TestCase):
def test_at_least_one_fragment_exists(self) -> None:
"""Otherwise every assertion below passes over an empty list."""
self.assertTrue(_fragments(), "no role declares templates/nftables.conf.j2")
def test_each_fragment_replaces_its_table(self) -> None:
for path in _fragments():
rel = Path(path).relative_to(PROJECT_ROOT).as_posix()
with self.subTest(fragment=rel):
lines = [
line.strip() for line in _render(path).splitlines() if line.strip()
]
declarations = [
line for line in lines if re.match(r"^(delete )?table inet ", line)
]
self.assertEqual(
declarations[:3],
[
f"table inet {TABLE}",
f"delete table inet {TABLE}",
f"table inet {TABLE} {{",
],
f"{rel} must open with the create, delete and declare idiom, "
"or nft merges the new rules into the old table",
)
def test_each_fragment_parses(self) -> None:
if not _nft_can_check():
self.skipTest("nft -c needs CAP_NET_ADMIN, which this runner lacks")
nft = shutil.which("nft")
for path in _fragments():
rel = Path(path).relative_to(PROJECT_ROOT).as_posix()
for mode in MODES:
with self.subTest(fragment=rel, mode=mode):
with tempfile.NamedTemporaryFile("w", suffix=".conf") as handle:
handle.write(_render(path, mode))
handle.flush()
result = subprocess.run(
[nft, "-c", "-f", handle.name],
capture_output=True,
text=True,
check=False,
)
self.assertEqual(
result.returncode,
0,
f"{rel} is not valid nftables in {mode}:\n{result.stderr}",
)
def test_each_fragment_loads_and_reloads(self) -> None:
"""A dry run cannot show what happens on the second deploy.
Loading the same fragment twice is what proves the idiom: the second
pass meets the table the first one left and must replace it, which is
exactly the case ``nft -c`` never sees.
"""
if not _nft_can_check() or shutil.which("ip") is None:
self.skipTest("loading a ruleset needs nft with CAP_NET_ADMIN and ip")
for index, path in enumerate(_fragments()):
rel = Path(path).relative_to(PROJECT_ROOT).as_posix()
for mode in MODES:
with self.subTest(fragment=rel, mode=mode):
with (
tempfile.NamedTemporaryFile("w", suffix=".conf") as handle,
_network_namespace(f"nftprobe{os.getpid()}x{index}") as netns,
):
handle.write(_render(path, mode))
handle.flush()
listings = []
for attempt in ("first", "second"):
loaded = _run([*netns, "nft", "-f", handle.name])
self.assertEqual(
loaded.returncode,
0,
f"{rel} failed to load on the {attempt} pass "
f"in {mode}:\n{loaded.stderr}",
)
listed = _run(
[*netns, "nft", "list", "table", "inet", TABLE]
)
self.assertEqual(
listed.returncode,
0,
f"{rel} loaded but left no table on the {attempt} "
f"pass in {mode}:\n{listed.stderr}",
)
listings.append(listed.stdout)
self.assertIn(f"table inet {TABLE}", listings[0])
self.assertEqual(
listings[0],
listings[1],
f"{rel} grew on the second pass in {mode}, so it merges "
"into the table it found instead of replacing it",
)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,101 @@
"""The egress guard admits every address a container can come from.
The guard drops any source outside ``tor_egress_clients``, and containers reach
the TransPort and the DNSPort through exactly those rules. So the list is not a
convenience: if it ever stops covering docker's own address pools, every
container loses the resolver and the transparent proxy at once, and it fails in
production rather than here.
This runs the real lookup over the repository's real network declarations. A
narrowed pool, a renamed key or a dropped entry in the lookup all surface as a
failure of the property the rules depend on.
"""
from __future__ import annotations
import importlib.util
import sys
import unittest
from unittest import mock
import jinja2
from utils.cache.yaml import load_yaml_any
from . import PROJECT_ROOT
NETWORKS = PROJECT_ROOT / "group_vars/all/08_networks.yml"
LOOKUP = "roles/svc-net-tor/lookup_plugins/tor_egress_clients.py"
def _load_lookup():
path = PROJECT_ROOT / LOOKUP
spec = importlib.util.spec_from_file_location("tor_egress_clients_lookup", path)
module = importlib.util.module_from_spec(spec)
assert spec and spec.loader
sys.modules["tor_egress_clients_lookup"] = module
spec.loader.exec_module(module)
return module
class _Templar:
"""Resolves the group_vars cross-references the lookup renders."""
def __init__(self, variables: dict):
self.available_variables = variables
def template(self, value):
return (
jinja2.Environment(autoescape=False) # noqa: S701 - renders CIDRs, not markup
.from_string(str(value))
.render(**self.available_variables)
)
class TestEgressClients(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.module = _load_lookup()
cls.variables = load_yaml_any(str(NETWORKS))
def _admitted(self) -> list[str]:
lookup = self.module.LookupModule()
lookup._templar = _Templar(self.variables)
lookup._loader = mock.MagicMock()
with mock.patch.object(self.module, "lookup_loader") as loader:
loader.get.return_value = mock.MagicMock(
run=mock.MagicMock(return_value=[[]])
)
return lookup.run([], variables=self.variables)[0]
def test_every_docker_address_pool_is_admitted(self) -> None:
admitted = self._admitted()
pools = self.variables["NETWORK_DOCKER_ADDRESS_POOLS"]
self.assertTrue(pools, "no docker address pool is declared")
for pool in pools:
with self.subTest(pool=pool["base"]):
self.assertIn(
pool["base"],
admitted,
"containers draw their address from this pool and reach the "
"guarded ports through the guard, so dropping it from the "
"admitted list takes the resolver away from every container",
)
def test_loopback_is_admitted(self) -> None:
"""The host resolves .onion through its own loopback."""
self.assertIn(self.variables["NETWORK_LOOPBACK_CIDR"], self._admitted())
def test_the_lan_is_not_admitted_wholesale(self) -> None:
"""The guarded ports carry no access policy, so the LAN is not a client.
Admitting 10.0.0.0/8 would hand a transparent proxy and a resolver to
every host the operator's network happens to contain.
"""
self.assertNotIn(
self.variables["NETWORK_PRIVATE_CIDRS"]["class_a"], self._admitted()
)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,135 @@
"""The node onion forwards HTTP whether or not the proxy is in the inventory.
``lookup('tor_ports')`` collects what the roles in ``group_names`` declare under
``ports.onion``. Port 80 belongs to ``svc-prx-openresty``, which a node acquires
through ``sys-stk-front-proxy`` and which therefore appears in no dependency
list an inventory holds. A node provisioned with ``--include svc-net-tor`` alone
published an onion forwarding SSH and nothing else.
These run the real lookup over a stubbed ``tor_ports``, so a flag that stops
reaching the forward list, or a derived port that starts duplicating a flagged
one, fails here rather than on the node.
"""
from __future__ import annotations
import importlib.util
import sys
import unittest
from typing import Any
from unittest import mock
from ansible.errors import AnsibleError
from . import PROJECT_ROOT
LOOKUP = "roles/svc-net-tor/lookup_plugins/tor_extra_ports.py"
SSH_ENTRY = {"onion_port": 22, "target": "127.0.0.1:22"}
HTTP_ENTRY = {"onion_port": 80, "target": "127.0.0.1:80"}
ENABLED = {"TOR_ONION_SSH_ENABLED": True, "TOR_ONION_HTTP_ENABLED": True}
def _load_lookup():
path = PROJECT_ROOT / LOOKUP
spec = importlib.util.spec_from_file_location("tor_extra_ports_lookup", path)
module = importlib.util.module_from_spec(spec)
assert spec and spec.loader
sys.modules["tor_extra_ports_lookup"] = module
spec.loader.exec_module(module)
return module
class _DerivedPorts:
"""Stands in for the tor_ports lookup the plugin composes with."""
def __init__(self, entries: list[dict[str, Any]]):
self.entries = entries
def run(self, _terms, **_kwargs):
return [self.entries]
class _Templar:
"""Resolves a group_var reference the way the play's templar does."""
def __init__(self, rendered: Any):
self.rendered = rendered
def template(self, _value):
return self.rendered
class TestExtraPorts(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.module = _load_lookup()
def _ports(self, derived: list[dict], **variables) -> list[dict]:
lookup = self.module.LookupModule()
lookup._templar = None
lookup._loader = None
with mock.patch.object(
self.module.lookup_loader, "get", return_value=_DerivedPorts(derived)
):
return lookup.run([], variables={**ENABLED, **variables})[0]
def test_a_flag_that_arrives_as_template_text_is_still_read(self) -> None:
lookup = self.module.LookupModule()
lookup._templar = _Templar(True)
lookup._loader = None
variables = dict.fromkeys(
ENABLED,
"{{ lookup('config', application_id, 'services.tor.forwards.x') | bool }}",
)
with mock.patch.object(
self.module.lookup_loader, "get", return_value=_DerivedPorts([])
):
ports = lookup.run([], variables=variables)[0]
self.assertIn(
HTTP_ENTRY,
ports,
"group vars reach a lookup unrendered, so the flag arrives as its own "
"template text; reading it without templating aborts the torrc render "
"on every tor row",
)
def test_http_is_forwarded_without_the_proxy_in_the_inventory(self) -> None:
self.assertIn(
HTTP_ENTRY,
self._ports([]),
"a node whose inventory lists only svc-net-tor still serves its apps "
"over the onion, so the forward cannot depend on the proxy being listed",
)
def test_a_derived_port_does_not_duplicate_a_flagged_one(self) -> None:
ports = self._ports([HTTP_ENTRY])
self.assertEqual(
[entry for entry in ports if entry["onion_port"] == 80],
[HTTP_ENTRY],
"torrc writes one HiddenServicePort line per entry, so a duplicate "
"publishes the same forward twice",
)
def test_derived_ports_still_reach_the_forward_list(self) -> None:
onion_dns = {"onion_port": 9053, "target": "127.0.0.1:9053"}
self.assertIn(
onion_dns,
self._ports([onion_dns]),
"the flags add to what the services declare, they do not replace it",
)
def test_a_flag_turns_its_forward_off(self) -> None:
ports = self._ports([], TOR_ONION_HTTP_ENABLED=False)
self.assertNotIn(HTTP_ENTRY, ports)
self.assertIn(SSH_ENTRY, ports, "the other flag is untouched")
def test_an_undeclared_flag_is_refused(self) -> None:
lookup = self.module.LookupModule()
lookup._templar = None
with self.assertRaises(AnsibleError) as raised:
lookup.run([], variables={"TOR_ONION_SSH_ENABLED": True})
self.assertIn("TOR_ONION_HTTP_ENABLED", str(raised.exception))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,130 @@
"""Every port the egress router binds locally is dropped for foreign sources.
The guard chain is the only thing between these listeners and anyone who can
route a packet to the node. A port that is bound but not named in a drop rule
answers the whole reachable network: the transparent proxy relays, the DNSPort
resolves, and the split-DNS forwarder both resolves recursively and hands out
the node's own ``.onion`` records.
This walks the real declaration chain rather than a fixture: ``meta/services.yml``
names the ports tor itself binds, ``vars/main.yml`` turns each into a
``TOR_*_PORT`` variable, and the guard list plus the fragment template spend
those variables on drop rules. A port added to the service declaration without a
rule fails the first test.
The forwarder sits outside that chain because it is not tor's own port: it takes
the well-known resolver port from ``NETWORK_DNS_PORT``, and the host already
assigns that number to whichever resolver owns it. The second test covers it by
name instead.
"""
from __future__ import annotations
import re
import unittest
from utils.cache.files import read_text
from utils.cache.yaml import load_yaml_any
from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_VARS_MAIN
from . import PROJECT_ROOT
ROLE = PROJECT_ROOT / "roles/svc-net-tor"
SERVICES = ROLE / ROLE_FILE_META_SERVICES
VARS = ROLE / ROLE_FILE_VARS_MAIN
FRAGMENT = ROLE / "templates/nftables.conf.j2"
_VARIABLE = re.compile(r"\{\{\s*([A-Z][A-Z0-9_]*)\s*\}\}")
_PORT_KEY = re.compile(r"services\.tor\.ports\.local\.([a-z0-9_]+)")
_DROP_RULE = re.compile(r"^\s*(?!#).*\b(?P<protocol>tcp|udp)\s+dport\b.*\bdrop\b")
def _declared_ports() -> dict[str, int]:
return load_yaml_any(str(SERVICES))["tor"]["ports"]["local"]
def _port_variables() -> dict[str, str]:
"""Maps each ``TOR_*_PORT`` variable to the port key it reads."""
declared = load_yaml_any(str(VARS))
names = {}
for name, value in declared.items():
if not isinstance(value, str):
continue
key = _PORT_KEY.search(value)
if key is not None:
names[name] = key.group(1)
return names
def _entries_for(variable: str) -> list[dict]:
"""Guard entries whose port comes from *variable*."""
return [
entry
for entry in load_yaml_any(str(VARS))["TOR_EGRESS_GUARDED_PORTS"]
if _VARIABLE.search(str(entry["port"])).group(1) == variable
]
def _guarded_keys() -> set[str]:
"""Port keys that reach a drop rule, through the vars list or the template."""
variables = _port_variables()
guarded: set[str] = set()
for entry in load_yaml_any(str(VARS))["TOR_EGRESS_GUARDED_PORTS"]:
name = _VARIABLE.search(str(entry["port"]))
if name is not None and name.group(1) in variables:
guarded.add(variables[name.group(1)])
for line in read_text(str(FRAGMENT)).splitlines():
if _DROP_RULE.match(line) is None:
continue
for name in _VARIABLE.findall(line):
if name in variables:
guarded.add(variables[name])
return guarded
class TestGuardedPorts(unittest.TestCase):
def test_every_locally_bound_port_reaches_a_drop_rule(self) -> None:
declared = _declared_ports()
self.assertTrue(declared, f"{SERVICES} declares no local ports")
unguarded = sorted(set(declared) - _guarded_keys())
self.assertEqual(
unguarded,
[],
"these ports are bound on the node but no guard rule drops a "
"foreign source for them, so they answer everything that can route "
f"to the node: {', '.join(f'{key} ({declared[key]})' for key in unguarded)}",
)
def test_the_forwarder_is_guarded_on_both_transports(self) -> None:
entries = _entries_for("TOR_DNSMASQ_PORT")
self.assertEqual(
{entry["protocol"] for entry in entries},
{"tcp", "udp"},
"dnsmasq answers on both transports, and a TCP query returns the "
"same records a UDP one does",
)
def test_the_forwarder_admits_every_source_the_node_calls_internal(self) -> None:
"""The resolver may not be stricter than the proxy it sits next to.
``internal`` is ``NETWORK_INTERNAL_CIDRS``, the same list ``torrc.j2``
spends on ``SocksPolicy accept``. ``containers`` is narrower: out of
``10.0.0.0/8`` it carries only the docker pool and the exception role,
which leaves out swarm's ingress network and every overlay docker
allocates without an ipam block. Guarding the resolver with the narrow
set hands a source a full SOCKS proxy and refuses it a name lookup.
"""
self.assertEqual(
{entry["admitted"] for entry in _entries_for("TOR_DNSMASQ_PORT")},
{"internal"},
"the resolver carries ordinary name resolution for everything the "
"node routes, so it takes the internal set, not the container pools",
)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,203 @@
"""The onion port probe speaks SOCKS5 and reports only real successes.
The handshake used to live in a heredoc inside a shell script, where no linter
and no test could reach it: forty lines assembling protocol bytes, checked by
nothing. These tests run it against a fake proxy that answers by script, so the
bytes on the wire and the verdict drawn from the reply are both pinned.
"""
from __future__ import annotations
import importlib.util
import socket
import threading
import unittest
from . import PROJECT_ROOT
def _load_probe():
path = PROJECT_ROOT / "roles" / "svc-net-tor" / "files" / "test" / "onion_ports.py"
spec = importlib.util.spec_from_file_location("onion_ports_probe", str(path))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
PROBE = _load_probe()
class _FakeSocks(threading.Thread):
"""A one-shot SOCKS5 proxy that replies with a scripted CONNECT code."""
def __init__(
self,
reply_code: int | None,
greeting: bytes = b"\x05\x02",
auth_reply: bytes = b"\x01\x00",
) -> None:
super().__init__(daemon=True)
self._reply_code = reply_code
self._greeting = greeting
self._auth_reply = auth_reply
self._server = socket.socket()
self._server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self._server.bind(("127.0.0.1", 0))
self._server.listen(1)
self.offered = b""
self.auth = b""
self.request = b""
@property
def endpoint(self) -> str:
host, port = self._server.getsockname()
return f"{host}:{port}"
def run(self) -> None:
conn, _ = self._server.accept()
with self._server, conn:
self.offered = conn.recv(3)
conn.sendall(self._greeting)
if self._greeting != b"\x05\x02":
return
self.auth = conn.recv(512)
conn.sendall(self._auth_reply)
if self._auth_reply != b"\x01\x00":
return
self.request = conn.recv(512)
if self._reply_code is None:
return
conn.sendall(bytes([0x05, self._reply_code, 0x00, 0x01]))
class TestConnectThroughSocks(unittest.TestCase):
def test_a_success_reply_passes_and_carries_the_target(self) -> None:
proxy = _FakeSocks(reply_code=0x00)
proxy.start()
PROBE.connect_through_socks(proxy.endpoint, "example.onion", 25, 5)
proxy.join(timeout=5)
self.assertTrue(
proxy.request.startswith(b"\x05\x01\x00\x03"),
f"the CONNECT request is malformed: {proxy.request!r}",
)
self.assertIn(b"example.onion", proxy.request)
self.assertTrue(
proxy.request.endswith((25).to_bytes(2, "big")),
"the port must travel big-endian in the last two bytes",
)
def test_every_attempt_isolates_itself_with_fresh_credentials(self) -> None:
seen: list[bytes] = []
for _ in range(2):
proxy = _FakeSocks(reply_code=0x00)
proxy.start()
PROBE.connect_through_socks(proxy.endpoint, "example.onion", 80, 5)
proxy.join(timeout=5)
self.assertEqual(
proxy.offered,
b"\x05\x01\x02",
"only username/password may be offered, or Tor may pick no-auth "
"and put the attempt on the shared circuit",
)
self.assertEqual(
proxy.auth[0], 0x01, f"bad RFC 1929 version: {proxy.auth!r}"
)
seen.append(proxy.auth)
self.assertNotEqual(
seen[0],
seen[1],
"a retry that reuses the credentials reuses the dead rendezvous circuit",
)
def test_rejected_credentials_fail(self) -> None:
proxy = _FakeSocks(reply_code=None, auth_reply=b"\x01\x01")
proxy.start()
with self.assertRaises(PROBE.ProbeError) as raised:
PROBE.connect_through_socks(proxy.endpoint, "example.onion", 25, 5)
self.assertIn("credentials", str(raised.exception))
def test_a_refusal_reply_fails(self) -> None:
proxy = _FakeSocks(reply_code=0x05)
proxy.start()
with self.assertRaises(PROBE.ProbeError) as raised:
PROBE.connect_through_socks(proxy.endpoint, "example.onion", 25, 5)
self.assertIn("0x05", str(raised.exception))
def test_a_refused_auth_method_fails(self) -> None:
proxy = _FakeSocks(reply_code=None, greeting=b"\x05\xff")
proxy.start()
with self.assertRaises(PROBE.ProbeError):
PROBE.connect_through_socks(proxy.endpoint, "example.onion", 25, 5)
def test_a_closed_connection_fails(self) -> None:
proxy = _FakeSocks(reply_code=None)
proxy.start()
with self.assertRaises(PROBE.ProbeError):
PROBE.connect_through_socks(proxy.endpoint, "example.onion", 25, 5)
def test_an_unreachable_proxy_fails(self) -> None:
with self.assertRaises(PROBE.ProbeError) as raised:
PROBE.connect_through_socks("127.0.0.1:1", "example.onion", 25, 1)
self.assertIn("unreachable", str(raised.exception))
class TestProbe(unittest.TestCase):
def test_only_the_failures_are_retried(self) -> None:
attempts: list[int] = []
def _connect(_proxy, _host, port, _timeout):
attempts.append(port)
if port == 25:
raise PROBE.ProbeError("still down")
original = PROBE.connect_through_socks
PROBE.connect_through_socks = _connect
try:
failures = PROBE.probe(
proxy="p:9050",
host="example.onion",
ports=[25, 143],
timeout=1,
retries=3,
sleep_seconds=0,
sleeper=lambda _seconds: None,
)
finally:
PROBE.connect_through_socks = original
self.assertEqual(failures, {25: "still down"})
self.assertEqual(
attempts.count(143),
1,
"a healthy port must not be probed again on a retry pass",
)
self.assertEqual(attempts.count(25), 3)
def test_a_port_that_recovers_is_not_reported(self) -> None:
seen: list[int] = []
def _connect(_proxy, _host, port, _timeout):
seen.append(port)
if len(seen) == 1:
raise PROBE.ProbeError("first pass fails")
original = PROBE.connect_through_socks
PROBE.connect_through_socks = _connect
try:
failures = PROBE.probe(
proxy="p:9050",
host="example.onion",
ports=[25],
timeout=1,
retries=2,
sleep_seconds=0,
sleeper=lambda _seconds: None,
)
finally:
PROBE.connect_through_socks = original
self.assertEqual(failures, {})
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,75 @@
"""The rendered test.env survives the shell that sources it.
test-e2e-cli loads test.env with ``set -a && . test.env && set +a``. An unquoted
space-separated value there is not an assignment but a command with a one-word
environment prefix: ``ONION_PORTS=25 80`` runs ``80``, bash reports
``command not found`` and carries on, and the probe reads an empty port list as
nothing to check.
"""
from __future__ import annotations
import subprocess
import unittest
from jinja2 import Environment, StrictUndefined, select_autoescape
from plugins.filter.dotenv import FilterModule
from utils.cache.files import read_text
from . import PROJECT_ROOT
TEMPLATE = PROJECT_ROOT / "roles" / "svc-net-tor" / "templates" / "test.env.j2"
PORTS = [25, 80, 587]
def _lookup(name: str, *_args: str) -> object:
return {
"config": "example.onion",
"nginx": "/etc/nginx/conf.d/servers",
"tor_ports": [
{"onion_port": port, "target": f"127.0.0.1:{port}"} for port in PORTS
],
"tor_socks": "127.0.0.1:9050",
}[name]
def _render(mode: str) -> str:
env = Environment(
undefined=StrictUndefined,
autoescape=select_autoescape(default_for_string=False),
)
env.filters.update(FilterModule().filters())
return env.from_string(read_text(str(TEMPLATE))).render(
lookup=_lookup,
DEPLOYMENT_MODE=mode,
TOR_DNSMASQ_CONF="/etc/dnsmasq.d/tor-onion.conf",
)
class TestTestEnvSourcing(unittest.TestCase):
def test_every_onion_port_reaches_the_probe(self) -> None:
for mode in ("compose", "swarm"):
with self.subTest(mode=mode):
result = subprocess.run(
[
"bash",
"-c",
(
"set -a && . /dev/stdin && set +a && "
'printf %s "${ONION_PORTS-unset}"'
),
],
input=_render(mode),
capture_output=True,
text=True,
check=False,
)
self.assertEqual(
result.stderr, "", "sourcing test.env must not run anything"
)
self.assertEqual(result.stdout, " ".join(str(port) for port in PORTS))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,124 @@
from __future__ import annotations
import importlib.util
import sys
import unittest
import unittest.mock as mock
from unittest.mock import patch
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
class _DummyTemplar:
def __init__(self, available_variables: dict | None = None):
self.available_variables = available_variables or {}
class CspAcceptStatusLookupTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.module = _load_module(
"roles/sys-ctl-hlth-csp/lookup_plugins/csp_accept_status.py",
"csp_accept_status_lookup",
)
def _run(self, applications, **kwargs):
lm = self.module.LookupModule()
lm._templar = _DummyTemplar()
lm._loader = mock.MagicMock()
with patch.object(self.module, "lookup_loader") as loader_mock:
loader_mock.get.return_value = mock.MagicMock(
run=lambda *_a, **_k: [applications]
)
return lm.run(terms=[], variables={}, **kwargs)[0]
def test_empty_applications_returns_empty_list(self):
self.assertEqual(self._run({}), [])
def test_non_mapping_applications_returns_empty(self):
self.assertEqual(self._run([]), [])
def test_a_declared_4xx_is_named_with_its_domain(self):
apps = {
"web-svc-mirror": {
"domains": {"canonical": ["mirror.example.com"]},
"server": {"status_codes": {"default": [404]}},
}
}
self.assertEqual(self._run(apps), ["mirror.example.com=404"])
def test_aliases_are_named_too(self):
apps = {
"web-app-bridgy": {
"domains": {
"canonical": ["bridgy.example.com"],
"aliases": ["fed.example.com"],
},
"server": {"status_codes": {"default": [200, 404]}},
}
}
self.assertEqual(
self._run(apps),
["bridgy.example.com=404", "fed.example.com=404"],
)
def test_a_2xx_only_declaration_names_nothing(self):
apps = {
"web-app-foo": {
"domains": {"canonical": ["foo.example.com"]},
"server": {"status_codes": {"default": [200]}},
}
}
self.assertEqual(self._run(apps), [])
def test_a_redirect_is_named_because_the_checker_rejects_it(self):
apps = {
"web-app-foo": {
"domains": {"canonical": ["foo.example.com"]},
"server": {"status_codes": {"default": [200, 301]}},
}
}
self.assertEqual(self._run(apps), ["foo.example.com=301"])
def test_two_vhosts_of_one_role_keep_their_own_codes(self):
apps = {
"web-app-split": {
"domains": {
"canonical": {
"api": "api.example.com",
"web": "web.example.com",
}
},
"server": {
"status_codes": {
"api": [405],
"web": [200],
"default": [200],
}
},
}
}
self.assertEqual(self._run(apps), ["api.example.com=405"])
def test_several_codes_of_one_domain_are_joined(self):
apps = {
"web-app-foo": {
"domains": {"canonical": ["foo.example.com"]},
"server": {"status_codes": {"default": [200, 403, 404]}},
}
}
self.assertEqual(self._run(apps), ["foo.example.com=403,404"])
if __name__ == "__main__":
unittest.main(verbosity=2)
@@ -24,6 +24,13 @@ class _DummyTemplar:
self.available_variables = available_variables or {}
def _app(service_enabled, domain="filer.example.com"):
return {
"server": {"domains": {"canonical": {"filer": domain}}},
"services": {"filer": {"enabled": service_enabled, "domains": ["filer"]}},
}
class CspSkipDomainsLookupTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
@@ -45,89 +52,47 @@ class CspSkipDomainsLookupTests(unittest.TestCase):
def test_empty_applications_returns_empty_list(self):
self.assertEqual(self._run({}), [])
def test_app_with_status_code_ge_400_skips_canonical_and_aliases(self):
apps = {
"web-app-bridgy": {
"domains": {
"canonical": ["bridgy.example.com"],
"aliases": ["fed.example.com"],
},
"server": {
"status_codes": {"default": [200, 404]},
},
}
}
self.assertEqual(self._run(apps), ["bridgy.example.com", "fed.example.com"])
def test_non_mapping_applications_returns_empty(self):
self.assertEqual(self._run([]), [])
def test_app_without_status_code_ge_400_is_not_skipped(self):
def test_a_disabled_service_hides_its_canonical_domain(self):
self.assertEqual(
self._run({"web-app-seaweedfs": _app(False)}),
["filer.example.com"],
)
def test_an_enabled_service_keeps_its_domain_under_probe(self):
self.assertEqual(self._run({"web-app-seaweedfs": _app(True)}), [])
def test_a_service_without_domains_is_ignored(self):
apps = {
"web-app-foo": {
"domains": {"canonical": ["foo.example.com"]},
"server": {
"status_codes": {"default": [200]},
},
"server": {"domains": {"canonical": {"web": "foo.example.com"}}},
"services": {"worker": {"enabled": False}},
}
}
self.assertEqual(self._run(apps), [])
def test_app_without_status_codes_field_is_not_skipped(self):
apps = {"web-app-foo": {"domains": {"canonical": ["foo.example.com"]}}}
self.assertEqual(self._run(apps), [])
def test_group_names_selection_filters_apps(self):
def test_the_selection_filters_which_apps_are_inspected(self):
apps = {
"web-app-bridgy": {
"domains": {"canonical": ["bridgy.example.com"]},
"server": {
"status_codes": {"default": [404]},
},
},
"web-app-other": {
"domains": {"canonical": ["other.example.com"]},
"server": {
"status_codes": {"default": [404]},
},
},
"web-app-a": _app(False, "a.example.com"),
"web-app-b": _app(False, "b.example.com"),
}
self.assertEqual(
self._run(apps, group_names=["web-app-bridgy"]),
["bridgy.example.com"],
self._run(apps, group_names=["web-app-a"]),
["a.example.com"],
)
def test_group_names_csv_string_is_accepted(self):
apps = {
"a": {
"domains": {"canonical": ["a.example.com"]},
"server": {
"status_codes": {"default": [404]},
},
},
"b": {
"domains": {"canonical": ["b.example.com"]},
"server": {
"status_codes": {"default": [404]},
},
},
"web-app-a": _app(False, "a.example.com"),
"web-app-b": _app(False, "b.example.com"),
}
self.assertEqual(
self._run(apps, group_names="a,b"),
self._run(apps, group_names="web-app-a,web-app-b"),
["a.example.com", "b.example.com"],
)
def test_non_4xx_codes_dont_count(self):
apps = {
"web-app-foo": {
"domains": {"canonical": ["foo.example.com"]},
"server": {
"status_codes": {"default": [200, 301, 302]},
},
}
}
self.assertEqual(self._run(apps), [])
def test_non_mapping_applications_returns_empty(self):
self.assertEqual(self._run([]), [])
if __name__ == "__main__":
unittest.main(verbosity=2)
@@ -0,0 +1,57 @@
import importlib.util
import unittest
from . import PROJECT_ROOT
SCRIPT = PROJECT_ROOT / "roles" / "sys-ctl-hlth-csp" / "files" / "python" / "script.py"
ONION = "mirror.b5abfs7uwr23x6vbjxqjatyscpmkm6qkmkla7eyapdi4zpwtrz6o4nqd.onion"
DOMAINS = ["mirror.infinito.test", ONION, "html.infinito.test"]
def _expand(accept_status, domains=None):
spec = importlib.util.spec_from_file_location("csp_wrapper", SCRIPT)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module.expand_accept_status(
accept_status, DOMAINS if domains is None else domains
)
class TestAcceptStatusReachesOnions(unittest.TestCase):
def test_the_onion_sibling_inherits_the_declaration(self):
expanded = _expand(["mirror.infinito.test=404"])
self.assertIn(
f"{ONION}=404",
expanded,
"the checker matches accepted codes by hostname, so a code declared "
"for the clearnet vhost never reaches its onion twin on its own",
)
def test_a_vhost_without_an_onion_twin_gains_nothing(self):
self.assertEqual(
_expand(["html.infinito.test=403"]), ["html.infinito.test=403"]
)
def test_several_codes_carry_over_unchanged(self):
expanded = _expand(["mirror.infinito.test=301,302,404"])
self.assertIn(f"{ONION}=301,302,404", expanded)
def test_an_onion_entry_is_not_expanded_again(self):
self.assertEqual(_expand([f"{ONION}=404"]), [f"{ONION}=404"])
def test_an_entry_without_codes_is_left_alone(self):
self.assertEqual(_expand(["mirror.infinito.test"]), ["mirror.infinito.test"])
def test_only_the_matching_label_is_extended(self):
expanded = _expand(["html.infinito.test=403", "mirror.infinito.test=404"])
self.assertEqual(
[e for e in expanded if e.endswith(".onion=404")], [f"{ONION}=404"]
)
self.assertEqual([e for e in expanded if e.endswith(".onion=403")], [])
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,55 @@
import importlib.util
import unittest
from . import PROJECT_ROOT
SCRIPT = PROJECT_ROOT / "roles" / "sys-ctl-hlth-csp" / "files" / "python" / "script.py"
URLS = ["https://a.test/", "https://b.test/"]
def _load():
spec = importlib.util.spec_from_file_location("csp_wrapper", SCRIPT)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def _cmd(**kwargs):
return _load().build_docker_cmd(
image="img",
urls=URLS,
short_mode=False,
ignore_network_blocks_from=kwargs.get("ignore", []),
accept_status=kwargs.get("accept", []),
)
class TestListFlagsAreSeparatedFromUrls(unittest.TestCase):
def test_accept_status_is_separated_from_the_urls(self):
cmd = _cmd(accept=["a.test=403"])
self.assertEqual(
cmd[cmd.index("--accept-status") + 2],
"--",
"the checker consumes every token after a list flag that does not "
"start with '--', and a URL does not, so the URLs would be read as "
"more status declarations",
)
def test_two_list_flags_share_a_single_separator(self):
cmd = _cmd(ignore=["x.test"], accept=["y.test=403"])
self.assertEqual(cmd.count("--"), 1)
self.assertLess(cmd.index("--"), cmd.index(URLS[0]))
def test_without_a_list_flag_no_separator_is_emitted(self):
self.assertNotIn("--", _cmd())
def test_every_url_survives_the_separator(self):
cmd = _cmd(accept=["y.test=403"])
self.assertEqual(cmd[cmd.index("--") + 1 :], URLS)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,75 @@
import re
import subprocess
import sys
import unittest
from utils.cache.files import read_text
from . import PROJECT_ROOT
ROLE = PROJECT_ROOT / "roles" / "sys-ctl-hlth-csp"
TASKS = ROLE / "tasks" / "00_core.yml"
SCRIPT = ROLE / "files" / "python" / "script.py"
_FLAG = re.compile(r"'\s*(--[a-z][a-z0-9-]*)")
_VALUE = {
"--nginx-config-dir": "/nonexistent",
"--image": "img",
"--tor-proxy": "socks5://127.0.0.1:9050",
"--onion-timeout": "1000",
}
_LIST_VALUE = {
"--ignore-network-blocks-from": "a.test",
"--skip-domain": "a.test",
"--accept-status": "a.test=403",
}
def _flags_the_unit_passes() -> set[str]:
return set(_FLAG.findall(read_text(str(TASKS))))
def _invoke(flag: str) -> subprocess.CompletedProcess:
argv = [
sys.executable,
str(SCRIPT),
"--nginx-config-dir",
"/nonexistent",
"--image",
"img",
]
if flag in _LIST_VALUE:
argv.extend([flag, _LIST_VALUE[flag]])
elif flag in _VALUE and flag not in ("--nginx-config-dir", "--image"):
argv.extend([flag, _VALUE[flag]])
elif flag not in _VALUE:
argv.append(flag)
return subprocess.run(argv, capture_output=True, text=True, timeout=60, check=False)
class TestUnitFlagsAreParsable(unittest.TestCase):
def test_the_unit_passes_at_least_the_known_flags(self):
found = _flags_the_unit_passes()
self.assertIn("--accept-status", found)
self.assertIn("--onion-timeout", found)
def test_every_flag_the_unit_passes_is_accepted_by_the_script(self):
for flag in sorted(_flags_the_unit_passes()):
with self.subTest(flag=flag):
completed = _invoke(flag)
self.assertNotIn(
"unrecognized arguments",
completed.stderr,
f"the systemd unit passes {flag} but script.py rejects it, "
f"which fails the service with status=2/INVALIDARGUMENT",
)
def test_an_undeclared_flag_is_still_rejected(self):
completed = _invoke("--definitely-not-a-flag")
self.assertIn("unrecognized arguments", completed.stderr)
if __name__ == "__main__":
unittest.main()
@@ -4,7 +4,7 @@ import unittest
from utils.cache.files import PROJECT_ROOT, read_text
CONFIG = PROJECT_ROOT / "roles/web-app-discourse/templates/config.yml.j2"
SETTINGS = PROJECT_ROOT / "roles/web-app-discourse/files/ruby/apply_settings.rb"
PREREQUISITES = (
"openid_connect_discovery_document",
"openid_connect_client_id",
@@ -14,15 +14,13 @@ PREREQUISITES = (
def _line_of(lines: list[str], setting: str) -> int:
return next(
index
for index, line in enumerate(lines)
if f'rails r "SiteSetting.{setting} = ' in line
index for index, line in enumerate(lines) if f"SiteSetting.{setting} = " in line
)
class TestDiscourseOidcSettingOrder(unittest.TestCase):
def test_oidc_is_enabled_only_after_its_prerequisites_are_set(self) -> None:
lines = read_text(str(CONFIG)).splitlines()
lines = read_text(str(SETTINGS)).splitlines()
enable = _line_of(lines, "openid_connect_enabled")
for setting in PREREQUISITES:
with self.subTest(setting=setting):
@@ -12,6 +12,11 @@ SOCKS_ERROR = (
"for https://garm3.nextcloud.com/api/v1/apps.json"
)
TIMEOUT_ERROR = "cURL error 28: Connection timed out after 120002 milliseconds"
ARTIFACT_404 = (
"Error: Client error: `GET https://github.com/ONLYOFFICE/onlyoffice-nextcloud"
"/releases/download/v10.2.0/onlyoffice.tar.gz` resulted in a "
"`404 Not Found` response:\nNot Found"
)
def _load_module(rel_path: str, name: str):
@@ -56,6 +61,11 @@ class TestNextcloudInstallStatus(unittest.TestCase):
self.assertFalse(status["unavailable"])
self.assertFalse(_tolerated(status))
def test_an_advertised_release_whose_artifact_is_gone_stays_fatal(self):
status = _status(stdout=ARTIFACT_404)
self.assertFalse(status["unavailable"])
self.assertFalse(_tolerated(status))
def test_an_incompatible_plugin_stays_terminal_and_not_runnable(self):
status = _status(
stdout="deck is not compatible with this version of the server"
@@ -0,0 +1,68 @@
"""The OIDC addon must not be on when Nextcloud has no SSO provider.
``meta/addons/oidc_login.yml`` gates on ``lookup('sso_oidc_plugin')``, which the
applications render evaluates while it is still in flight. Under that re-entry
guard the merged view hands out service flags as their own Jinja text, and
``bool("{{ ... }}")`` is True: the lookup read ``services.ldap.enabled`` as
enabled on a deployment that has neither Keycloak nor OpenLDAP and announced
``oidc_login``. Nextcloud then advertised a login hand-off to a provider that is
not deployed, while ``templates/config/oidc.config.php.j2`` re-read the same
setting at task time and correctly wrote nothing.
The stubbed lookup tests next to the plugin cannot see this: a stub resolves the
path but does not render it. This renders for real.
"""
from __future__ import annotations
import unittest
from utils.cache import _reset_cache_for_tests
from utils.cache.applications import get_merged_applications
def _templar(variables: dict):
from ansible.parsing.dataloader import DataLoader
from ansible.template import Templar
templar = Templar(loader=DataLoader(), variables=dict(variables))
templar.available_variables = dict(variables)
return templar
def _addon_flags(*deployed: str) -> dict:
variables = {"group_names": list(deployed), "applications": {}}
_reset_cache_for_tests()
try:
applications = get_merged_applications(
variables=variables, templar=_templar(variables)
)
finally:
_reset_cache_for_tests()
nextcloud = applications["web-app-nextcloud"]
addons = nextcloud.get("addons") or {}
services = nextcloud.get("services") or {}
return {
"sso": (services.get("sso") or {}).get("enabled"),
"ldap": (services.get("ldap") or {}).get("enabled"),
**{
name: (addons.get(name) or {}).get("enabled")
for name in ("oidc_login", "user_oidc", "sociallogin")
},
}
class TestOidcAddonFollowsSso(unittest.TestCase):
def test_no_provider_means_no_oidc_addon(self) -> None:
flags = _addon_flags("web-app-nextcloud")
self.assertEqual(flags["sso"], False)
self.assertEqual(
(flags["oidc_login"], flags["user_oidc"], flags["sociallogin"]),
(False, False, False),
"no OIDC plugin may be announced without an SSO provider",
)
if __name__ == "__main__":
unittest.main()
@@ -1,8 +1,9 @@
"""Guards for the per-deploy credential rotation path of web-app-openbao.
The platform regenerates generated-algorithm credentials on every deploy, so the
seal key and AppRole a run is handed differ from the ones the running instance
was configured with. Three things carry that transition, and each fails silently
AppRole a run is handed differs from the one the running instance was configured
with. The seal key is pinned out of that and moves only when an operator changes
it, but the same transition then has to carry it. Each part fails silently
rather than loudly when broken -- a sealed node and an unusable AppRole look
identical to ordinary drift. These tests pin them.
"""
@@ -15,6 +16,7 @@ from jinja2 import Environment, FileSystemLoader, StrictUndefined
from utils.cache.files import read_text
from utils.cache.yaml import load_yaml_any
from utils.roles.mapping import ROLE_FILE_META_SECRETS
from . import PROJECT_ROOT
@@ -53,6 +55,30 @@ def tasks_of(name: str) -> list[dict]:
return load_yaml_any(str(TASKS_DIR / name))
class TestWhichCredentialsRotate(unittest.TestCase):
"""The seal key survives a deploy; the AppRole does not.
The static seal carries one generation of slack, and rotating every deploy
spends it continuously: a run that skips a generation leaves the raft store
readable only from a volume backup plus the key that wrapped it. The
AppRole is the opposite case -- the live authentication path, whose
rotation the fallback login in 01_init.yml exists to absorb.
"""
def setUp(self):
self.credentials = load_yaml_any(str(ROLE_DIR / ROLE_FILE_META_SECRETS))[
"credentials"
]
def test_the_seal_key_is_pinned(self):
self.assertIs(self.credentials["seal_key"].get("rotatable"), False)
def test_both_approle_credentials_still_rotate(self):
for name in ("approle_role_id", "approle_secret_id"):
with self.subTest(credential=name):
self.assertIsNot(self.credentials[name].get("rotatable"), False)
class TestSealStanzaRotation(unittest.TestCase):
def _render(self, rotating: bool) -> str:
env = jinja_env(ROLE_DIR / "templates")
@@ -223,6 +249,97 @@ class TestTheSecretIdSwapIsGuarded(unittest.TestCase):
self.assertNotIn("when", task)
class TestTheRecoveryKeyIsKeptAndUsable(unittest.TestCase):
"""The one authority that does not rotate, and the way back it buys.
`bao operator init` issues a recovery key once and nothing reissues it.
Dropping it leaves the AppRole as the only administrative path, so a reset,
a replaced manager, or a run that dies between the two pins in
06_rotate.yml locks the instance out for good while its data stays
readable. sys-token-store holds it rather than the inventory, which no role
writes.
"""
def setUp(self):
self.tasks = tasks_of("01_init.yml")
def _init_block(self) -> list[dict]:
return next(
task["block"]
for task in self.tasks
if "block" in task and "openbao_initialized" in str(task.get("when", ""))
)
def test_the_key_is_persisted_on_the_deploy_that_creates_it(self):
store = next(
task
for task in self._init_block()
if task.get("ansible.builtin.include_role", {}).get("name")
== "sys-token-store"
)
self.assertEqual(
store["ansible.builtin.include_role"]["tasks_from"], "write.yml"
)
self.assertIn("recovery_keys_b64", store["vars"]["sys_token_store_token"])
def test_the_key_is_loaded_before_the_logins_that_may_need_it(self):
load = next(
i
for i, task in enumerate(self.tasks)
if task.get("ansible.builtin.include_role", {}).get("tasks_from")
== "01_load.yml"
)
login = next(
i
for i, task in enumerate(self.tasks)
if task.get("register") == "openbao_approle_login"
)
self.assertLess(load, login)
def test_recovery_runs_only_when_both_logins_failed_and_a_key_exists(self):
block = next(
task
for task in self.tasks
if "openbao_approle_login_recovered" in str(task)
)
conditions = " ".join(block["when"])
self.assertIn("openbao_approle_login.rc != 0", conditions)
self.assertIn("openbao_approle_login_previous.rc", conditions)
self.assertIn("OPENBAO_RECOVERY_KEY", conditions)
def test_the_rebuilt_approle_is_the_one_the_inventory_holds(self):
"""Recovering to the recorded pair would strand the deploy again.
02_auth.yml re-pins both halves to the inventory values, so the login
that proves recovery worked has to use those, not the applied ones.
"""
block = next(
task
for task in self.tasks
if "openbao_approle_login_recovered" in str(task)
)
login = next(
task
for task in block["block"]
if task.get("register") == "openbao_approle_login_recovered"
)
self.assertIn("OPENBAO_APPROLE_ROLE_ID", login["ansible.builtin.shell"])
self.assertIn("OPENBAO_APPROLE_SECRET_ID", login["args"]["stdin"])
def test_the_recovery_path_ends_by_rebuilding_the_approle(self):
tasks = tasks_of("utils/recover.yml")
self.assertEqual(
tasks[-1]["ansible.builtin.include_tasks"],
"../02_auth.yml",
"minting a root token without re-pinning leaves the deploy no better off",
)
def test_a_rejected_recovery_key_fails_loudly(self):
tasks = tasks_of("utils/recover.yml")
guard = next(task for task in tasks if "ansible.builtin.fail" in task)
self.assertIn("complete", guard["when"])
class TestTheRegisteredSecretIdComesFromTheLogin(unittest.TestCase):
def test_it_is_the_credential_that_was_just_accepted(self):
"""Deriving it from the state file instead would be wrong.
+24 -2
View File
@@ -111,13 +111,35 @@ class TestStableVariablesSignature(unittest.TestCase):
def test_empty_variables_collapses_to_canonical_tuple(self):
self.assertEqual(
base._stable_variables_signature(None),
("0", "0", "", ""),
("0", "0", "", "", ""),
)
self.assertEqual(
base._stable_variables_signature({}),
("0", "0", "", ""),
("0", "0", "", "", ""),
)
def test_two_hosts_of_one_play_do_not_share_a_key(self):
shared = {"applications": {"web-app-pretix": {}}, "DOMAIN_PRIMARY": "x.test"}
member = base._stable_variables_signature(
{**shared, "group_names": ["web-app-pretix", "svc-db-postgres"]}
)
outsider = base._stable_variables_signature(
{**shared, "group_names": ["web-app-pretix"]}
)
self.assertNotEqual(
member,
outsider,
"a service flag may read group_names, so one host's payload must "
"never answer for a host whose groups differ",
)
def test_group_order_does_not_split_the_key(self):
first = base._stable_variables_signature({"group_names": ["a", "b"]})
second = base._stable_variables_signature({"group_names": ["b", "a"]})
self.assertEqual(first, second)
def test_includes_domain_primary_and_email_domain_strings(self):
sig = base._stable_variables_signature(
{
+2 -2
View File
@@ -129,8 +129,8 @@ class TestStableVariablesSignature(unittest.TestCase):
_reset_cache_for_tests()
def test_empty_variables_returns_sentinel(self):
self.assertEqual(_stable_variables_signature(None), ("0", "0", "", ""))
self.assertEqual(_stable_variables_signature({}), ("0", "0", "", ""))
self.assertEqual(_stable_variables_signature(None), ("0", "0", "", "", ""))
self.assertEqual(_stable_variables_signature({}), ("0", "0", "", "", ""))
def test_captures_key_subset(self):
sig = _stable_variables_signature(
+66
View File
@@ -337,5 +337,71 @@ class TestOnionDomainInjection(unittest.TestCase):
self.assertEqual(out["web-app-x"], ["infinito.test", self.ONION])
class TestOnionFlagsAreRendered(unittest.TestCase):
"""`services.tor.*` reaches this map as Jinja in 99 of the 105 roles that
declare it, and as its own source text whenever the applications render is
still in flight. Reading that text as a boolean answers False and drops the
onion domains for every app, which is what froze a clearnet asset URL into
the applications payload of run 34922994823.
"""
ONION = TestOnionDomainInjection.ONION
JINJA_ON = "{{ 'svc-net-tor' in group_names }}"
_apps = TestOnionDomainInjection._apps
def _templar(self, **variables):
from ansible.parsing.dataloader import DataLoader
from ansible.template import Templar
templar = Templar(loader=DataLoader(), variables=dict(variables))
templar.available_variables = dict(variables)
return templar
def _inject(self, apps, **variables):
return cache_domains._inject_onion_domains(
{"web-app-x": ["x.infinito.test"]},
apps,
"infinito.test",
self.ONION,
templar=self._templar(**variables),
variables=dict(variables),
)
def test_a_templated_enabled_flag_still_injects_the_onion(self):
out = self._inject(
self._apps(enabled=self.JINJA_ON),
group_names=["svc-net-tor", "web-app-x"],
)
self.assertEqual(out["web-app-x"], ["x.infinito.test", f"x.{self.ONION}"])
def test_a_templated_flag_resolving_false_leaves_the_clearnet_domain(self):
out = self._inject(self._apps(enabled=self.JINJA_ON), group_names=["web-app-x"])
self.assertEqual(out["web-app-x"], ["x.infinito.test"])
def test_templated_exclusive_replaces_the_clearnet_domain(self):
out = self._inject(
self._apps(enabled=self.JINJA_ON, exclusive=self.JINJA_ON),
group_names=["svc-net-tor", "web-app-x"],
)
self.assertEqual(out["web-app-x"], [f"x.{self.ONION}"])
def test_a_flag_that_cannot_be_rendered_is_an_error(self):
"""Without a templar the text cannot resolve, and answering False
would drop the onion domains without saying so."""
with self.assertRaisesRegex(ValueError, "services.tor.enabled"):
cache_domains._inject_onion_domains(
{"web-app-x": ["x.infinito.test"]},
self._apps(enabled=self.JINJA_ON),
"infinito.test",
self.ONION,
templar=None,
variables={"group_names": ["svc-net-tor"]},
)
if __name__ == "__main__":
unittest.main()
+28
View File
@@ -164,5 +164,33 @@ class TestReset(_ProjectRootFixture, unittest.TestCase):
self.assertEqual(read_text(str(self.root / "x.txt")), "v1-changed")
class TestWalkIsKeyedOnTheRoot(_ProjectRootFixture, unittest.TestCase):
def test_a_second_root_is_walked_rather_than_answered_from_the_first(
self,
) -> None:
_touch(self.root / "first.txt", "a")
self.assertEqual(
{str(self.root / "first.txt")},
set(iter_project_files()),
)
with TemporaryDirectory() as other:
other_root = Path(other)
_touch(other_root / "second.txt", "b")
with patch.object(files_module, "PROJECT_ROOT", other_root):
self.assertEqual(
{str(other_root / "second.txt")},
set(iter_project_files()),
"the walk answered for the previous root, so a test that "
"points PROJECT_ROOT at a fixture silently sweeps the real "
"repository instead",
)
self.assertEqual(
{str(self.root / "first.txt")},
set(iter_project_files()),
)
if __name__ == "__main__": # pragma: no cover
unittest.main()
@@ -0,0 +1,99 @@
from __future__ import annotations
import unittest
from utils.docker.image.discovery import docker_hub_source, image_source
from utils.docker.image.pin import (
DIGEST,
REF,
RULE_BY_CLASS,
SEMVER,
is_digest,
pin_class,
pull_reference,
reference_separator,
)
DIGEST_VALUE = "sha256:d5591131b1d898cd02fc7a17adb8ea026352d67809bc9289707778e9e03a76a4"
class TestPinClass(unittest.TestCase):
def test_a_semver_tag_is_a_semver_pin(self):
for value in ("3.0.1", "16", "17-3.5", "5.4.5-php8.3-apache", "v1.12.27"):
self.assertEqual(pin_class(value), SEMVER, value)
def test_a_content_address_is_a_digest_pin(self):
self.assertEqual(pin_class(DIGEST_VALUE), DIGEST)
def test_a_moving_name_is_neither(self):
for value in ("latest", "main", "stable", "buildx-stable-1"):
self.assertEqual(pin_class(value), REF, value)
def test_surrounding_whitespace_does_not_change_the_class(self):
self.assertEqual(pin_class(f" {DIGEST_VALUE} "), DIGEST)
self.assertEqual(pin_class(" 3.0.1 "), SEMVER)
def test_a_digest_declares_itself_apart_from_a_tag(self):
self.assertNotEqual(
RULE_BY_CLASS[DIGEST],
RULE_BY_CLASS[REF],
"a digest is chosen for a reason a non-semver tag never carries, so "
"the two cannot share one marker",
)
self.assertEqual(RULE_BY_CLASS[DIGEST], "docker-digest")
self.assertEqual(RULE_BY_CLASS[REF], "docker-version")
def test_a_semver_pin_needs_no_declaration(self):
self.assertNotIn(SEMVER, RULE_BY_CLASS)
class TestPullReference(unittest.TestCase):
def test_a_digest_is_joined_with_an_at_sign(self):
self.assertEqual(reference_separator(DIGEST_VALUE), "@")
self.assertEqual(
pull_reference("ghcr.io/owner/app", DIGEST_VALUE),
f"ghcr.io/owner/app@{DIGEST_VALUE}",
)
def test_a_tag_is_joined_with_a_colon(self):
self.assertEqual(reference_separator("3.0.1"), ":")
self.assertEqual(
pull_reference("ghcr.io/owner/app", "3.0.1"), "ghcr.io/owner/app:3.0.1"
)
def test_is_digest_rejects_a_tag_that_merely_mentions_sha256(self):
self.assertFalse(is_digest("v2-sha256:abc"))
class TestSourceKeepsTheDigest(unittest.TestCase):
"""A pull ref that silently drops the digest pins nothing at all."""
def test_image_source_keeps_a_digest(self):
self.assertEqual(
image_source("ghcr.io/owner/app", DIGEST_VALUE),
f"ghcr.io/owner/app@{DIGEST_VALUE}",
)
def test_image_source_still_tags_a_semver(self):
self.assertEqual(
image_source("ghcr.io/owner/app", "3.0.1"), "ghcr.io/owner/app:3.0.1"
)
def test_docker_hub_source_keeps_a_digest(self):
self.assertEqual(
docker_hub_source("postgres", DIGEST_VALUE),
f"docker.io/library/postgres@{DIGEST_VALUE}",
)
def test_a_digest_never_yields_a_tag_separator(self):
source = image_source("quay.io/owner/app", DIGEST_VALUE)
self.assertNotIn(
f":{DIGEST_VALUE}",
source,
"a colon here would make the registry read the digest as a tag name",
)
if __name__ == "__main__":
unittest.main()
@@ -199,6 +199,11 @@ class TestApply(unittest.TestCase):
def test_a_bare_role_that_matches_nothing_is_tolerated(self) -> None:
self.assertEqual(selection.apply(_ROWS, selection.parse_list("web-app-c")), [])
def test_a_pin_on_an_undiscovered_role_is_tolerated_like_a_bare_one(self) -> None:
self.assertEqual(
selection.apply(_ROWS, selection.parse_list("web-app-c#0,2")), []
)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,260 @@
import json
import re
import shutil
import subprocess
import sys
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from utils import PROJECT_ROOT
from utils.cache.files import read_text
from utils.cache.yaml import load_yaml_any
from utils.install.collections import declared_pins, unsatisfied
_DOCKERFILE = PROJECT_ROOT / "Dockerfile"
_COPY = re.compile(r"^COPY\s+(?P<source>\S+)\s+\$\{INFINITO_SRC_DIR\}/(?P<target>\S+)$")
def _materialise_image_slice(destination: Path) -> None:
"""Reproduce what the image holds when it first runs the collection check.
The Dockerfile copies a handful of paths, runs ``scripts/install/ansible.sh``
against them, and only afterwards copies the rest of the tree. Anything
``utils.install.collections`` imports beyond that slice is absent in the
layer that executes it, which no import inside a full checkout can show.
The list is read from the Dockerfile rather than restated here, so a COPY
added or dropped moves this probe with it.
The caller must run the slice under ``python -S``. This repository installs
``utils`` into site-packages, so without it the interpreter resolves every
submodule from the checkout however the slice is built, and the probe
passes on a module that cannot import inside the image.
Args:
destination: an empty directory to build the slice in.
"""
for line in read_text(str(_DOCKERFILE)).splitlines():
if line.startswith("COPY . "):
return
match = _COPY.match(line.strip())
if not match:
continue
source = PROJECT_ROOT / match.group("source")
target = destination / match.group("target")
target.parent.mkdir(parents=True, exist_ok=True)
if source.is_dir():
shutil.copytree(source, target, dirs_exist_ok=True)
else:
shutil.copy2(source, target)
_REQUIREMENTS = (
PROJECT_ROOT / "requirements" / "requirements.galaxy.yml",
PROJECT_ROOT / "requirements" / "requirements.git.yml",
)
_BOOTSTRAP_PROBE = """
import sys
class _NoPyYAML:
def find_spec(self, fullname, path=None, target=None):
if fullname == "yaml" or fullname.startswith("yaml."):
raise ImportError("PyYAML is absent during the lint bootstrap")
return None
sys.meta_path.insert(0, _NoPyYAML())
from pathlib import Path
from utils.install.lint.ansible import collections as lint_collections
from utils.install.collections import declared_pins
for fqcn, version in declared_pins(Path("requirements/requirements.galaxy.yml")):
print(fqcn, version)
"""
REQUIREMENTS = """---
collections:
- name: community.general
version: 13.4.0
- name: hetzner.hcloud
version: 7.0.1
"""
def _write_requirements(root: Path, body: str = REQUIREMENTS) -> Path:
path = root / "requirements.galaxy.yml"
path.write_text(body, encoding="utf-8")
return path
def _install(collections_dir: Path, fqcn: str, version: str) -> None:
namespace, _, name = fqcn.partition(".")
target = collections_dir / "ansible_collections" / namespace / name
target.mkdir(parents=True)
(target / "MANIFEST.json").write_text(
json.dumps({"collection_info": {"version": version}}), encoding="utf-8"
)
class TestAgainstPyYAML(unittest.TestCase):
def test_the_hand_parser_agrees_with_pyyaml(self):
for path in _REQUIREMENTS:
with self.subTest(requirements=path.name):
declared = load_yaml_any(str(path), default_if_missing={}) or {}
expected = [
(str(entry.get("name")), entry.get("version"))
for entry in declared.get("collections") or []
if isinstance(entry, dict) and entry.get("name")
]
expected = [
(name, None if version is None else str(version))
for name, version in expected
]
self.assertEqual(declared_pins(path), expected)
def test_the_parser_runs_with_pyyaml_unimportable(self):
result = subprocess.run(
[sys.executable, "-c", _BOOTSTRAP_PROBE],
cwd=str(PROJECT_ROOT),
capture_output=True,
text=True,
check=False,
)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("community.general", result.stdout)
def test_the_checker_runs_on_the_slice_the_dockerfile_copies(self):
tmp = TemporaryDirectory()
self.addCleanup(tmp.cleanup)
slice_root = Path(tmp.name)
_materialise_image_slice(slice_root)
requirements = slice_root / "requirements" / "requirements.galaxy.yml"
self.assertTrue(
requirements.is_file(),
"the Dockerfile stopped copying requirements/ before the ansible "
"install layer; this probe needs it to have something to check",
)
result = subprocess.run(
[
sys.executable,
"-S",
"-m",
"utils.install.collections",
str(requirements),
str(slice_root / "collections"),
],
cwd=str(slice_root),
capture_output=True,
text=True,
check=False,
)
self.assertNotIn(
"ModuleNotFoundError",
result.stderr,
"utils.install.collections reached for a module the image layer "
"that runs it does not hold; keep it on the standard library",
)
self.assertEqual(
result.returncode,
1,
f"an empty collections dir satisfies nothing, so the checker owes "
f"exit 1 and a list; stderr: {result.stderr}",
)
self.assertIn("community.general", result.stdout)
class TestDeclaredPins(unittest.TestCase):
def test_a_quoted_version_is_read_without_its_quotes(self):
body = (
"---\ncollections:\n"
' - name: double.quoted\n version: "13.4.0"\n'
" - name: single.quoted\n version: '1.0.0'\n"
" - name: commented\n version: 2.2.2 # pinned\n"
)
with TemporaryDirectory() as tmp:
root = Path(tmp)
requirements = _write_requirements(root, body)
self.assertEqual(
declared_pins(requirements),
[
("double.quoted", "13.4.0"),
("single.quoted", "1.0.0"),
("commented", "2.2.2"),
],
)
def test_an_entry_without_a_version_stays_unpinned(self):
body = "---\ncollections:\n - name: bare.entry\n"
with TemporaryDirectory() as tmp:
root = Path(tmp)
self.assertEqual(
declared_pins(_write_requirements(root, body)), [("bare.entry", None)]
)
def test_a_missing_file_declares_nothing(self):
with TemporaryDirectory() as tmp:
self.assertEqual(declared_pins(Path(tmp) / "absent.yml"), [])
class TestUnsatisfied(unittest.TestCase):
def test_every_pin_installed_at_its_version_is_satisfied(self):
with TemporaryDirectory() as tmp:
root = Path(tmp)
requirements = _write_requirements(root)
_install(root, "community.general", "13.4.0")
_install(root, "hetzner.hcloud", "7.0.1")
self.assertEqual(unsatisfied(requirements, root), [])
def test_absent_collection_is_reported(self):
with TemporaryDirectory() as tmp:
root = Path(tmp)
requirements = _write_requirements(root)
_install(root, "community.general", "13.4.0")
self.assertEqual(unsatisfied(requirements, root), ["hetzner.hcloud:7.0.1"])
def test_wrong_version_is_reported_although_the_directory_exists(self):
with TemporaryDirectory() as tmp:
root = Path(tmp)
requirements = _write_requirements(root)
_install(root, "community.general", "13.4.0")
_install(root, "hetzner.hcloud", "6.9.0")
self.assertEqual(unsatisfied(requirements, root), ["hetzner.hcloud:7.0.1"])
def test_unpinned_entry_can_never_be_confirmed(self):
body = "---\ncollections:\n - name: community.general\n"
with TemporaryDirectory() as tmp:
root = Path(tmp)
requirements = _write_requirements(root, body)
_install(root, "community.general", "13.4.0")
self.assertEqual(unsatisfied(requirements, root), ["community.general"])
def test_unreadable_manifest_is_reported(self):
with TemporaryDirectory() as tmp:
root = Path(tmp)
requirements = _write_requirements(root)
_install(root, "community.general", "13.4.0")
_install(root, "hetzner.hcloud", "7.0.1")
manifest = (
root / "ansible_collections" / "hetzner" / "hcloud" / "MANIFEST.json"
)
manifest.write_text("{not json", encoding="utf-8")
self.assertEqual(unsatisfied(requirements, root), ["hetzner.hcloud:7.0.1"])
if __name__ == "__main__":
unittest.main()
@@ -1,13 +1,16 @@
import base64
import tempfile
from pathlib import Path
from typing import ClassVar
from unittest import TestCase, main, mock
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
from utils.cache.files import PROJECT_ROOT
from utils.cache.yaml import load_yaml_any
from utils.handler.vault import VaultScalar
from utils.manager.inventory import InventoryManager
from utils.manager.inventory import InventoryManager, validate_supplied_value
from utils.manager.value_generator import ValueGenerator
from utils.roles.mapping import (
ROLE_FILE_META_SECRETS,
@@ -760,5 +763,104 @@ class TestInventoryManagerVariant(TestCase):
self.assertEqual(cfg, {})
class TestSuppliedValueValidation(TestCase):
"""A schema that declares a shape must reject a value contradicting it.
Without this the declaration is decoration: the 192 `validation:` blocks
already in the role schemas are enforced nowhere, and a `regex` would have
joined them.
"""
SCHEMA: ClassVar[dict[str, str]] = {
"type": "string",
"regex": "sk-[A-Za-z0-9]{4,}",
}
def test_a_matching_value_passes(self):
validate_supplied_value("credentials.api_key", "sk-abcd1234", self.SCHEMA)
def test_an_empty_value_is_not_configured_and_passes(self):
validate_supplied_value("credentials.api_key", "", self.SCHEMA)
validate_supplied_value("credentials.api_key", None, self.SCHEMA)
def test_a_value_failing_the_pattern_aborts(self):
with self.assertRaises(SystemExit):
validate_supplied_value("credentials.api_key", "nope", self.SCHEMA)
def test_a_partial_match_is_not_enough(self):
with self.assertRaises(SystemExit):
validate_supplied_value("credentials.api_key", "sk-ab!!", self.SCHEMA)
def test_a_value_of_the_wrong_type_aborts(self):
with self.assertRaises(SystemExit):
validate_supplied_value("credentials.port", 8080, {"type": "string"})
def test_an_unknown_declared_type_aborts(self):
with self.assertRaises(SystemExit):
validate_supplied_value("credentials.x", "v", {"type": "uuid"})
def test_a_schema_declaring_neither_accepts_anything(self):
validate_supplied_value("credentials.x", "anything", {"description": "free"})
def test_an_unrendered_template_is_not_a_value(self):
for value in ("{{ API.openai.api_key }}", "{% if x %}a{% endif %}"):
with self.subTest(value=value):
validate_supplied_value("credentials.api_key", value, self.SCHEMA)
class TestProviderKeyPattern(TestCase):
"""The shipped provider-key pattern must outlive a vendor's format change.
OpenAI moved from `sk-` to `sk-proj-` without notice. A schema that pinned
the prefix would reject a valid key and abort inventory creation, so the
pattern checks what a paste can get wrong instead.
"""
ACCEPTED: ClassVar[tuple[str, ...]] = (
"sk-proj-AbCdEfGh1234567890xyz",
"sk-ant-api03-AbCdEfGh1234567890",
"sk-or-v1-AbCdEfGh1234567890abc",
"sk-AbCdEfGh1234567890legacyKey",
"some-future-format-2099-abcdef",
)
REJECTED: ClassVar[tuple[str, ...]] = (
"sk-proj-AbCdEfGh1234567890xyz\n",
"sk-short",
"<your-key-here>",
"sk-proj-Ab Cd 1234567890 xyz",
)
def _credentials(self) -> dict:
path = PROJECT_ROOT / "roles/svc-ai-litellm" / ROLE_FILE_META_SECRETS
return load_yaml_any(str(path))["credentials"]
def _schema(self) -> dict:
return self._credentials()["openai_api_key"]
def test_every_declared_default_survives_its_own_schema(self):
"""A default is written verbatim and read back as a supplied value.
Run 34883491022 died in every job because the provider keys' own
`{{ API.<vendor>.api_key }}` reached the pattern on the second read.
"""
for key, schema in self._credentials().items():
if "default" not in schema:
continue
with self.subTest(key=key):
validate_supplied_value(f"credentials.{key}", schema["default"], schema)
def test_every_known_provider_form_is_accepted(self):
schema = self._schema()
for value in self.ACCEPTED:
with self.subTest(value=value):
validate_supplied_value("credentials.openai_api_key", value, schema)
def test_a_broken_paste_is_rejected(self):
schema = self._schema()
for value in self.REJECTED:
with self.subTest(value=value), self.assertRaises(SystemExit):
validate_supplied_value("credentials.openai_api_key", value, schema)
if __name__ == "__main__":
main()
@@ -4,12 +4,15 @@ import tempfile
import unittest
from pathlib import Path
from utils.cache.files import PROJECT_ROOT, read_text
from utils.cache.yaml import dump_yaml_str
from utils.roles.applications.services.registry import (
GROUP_GATED_CONSTANTS,
ServiceRegistryError,
build_service_registry_from_applications,
detect_service_bucket,
detect_service_channel,
is_explicit_truth,
ordered_primary_service_entries,
resolve_service_dependency_roles_from_config,
)
@@ -335,5 +338,40 @@ class TestServiceRegistryOrdering(unittest.TestCase):
ordered_primary_service_entries(registry, roles_dir)
class TestExplicitTruth(unittest.TestCase):
"""A flag may resolve a dependency through a group-gated constant.
The substring rule reads the role id out of the flag itself, so a SPOT
constant hides it. Roles referencing one keep their provider only while
the constant is registered.
"""
def test_a_literal_true_resolves(self):
self.assertTrue(is_explicit_truth(True))
def test_the_in_group_names_form_resolves(self):
self.assertTrue(is_explicit_truth("{{ 'web-app-keycloak' in group_names }}"))
def test_every_registered_constant_resolves(self):
for constant in GROUP_GATED_CONSTANTS:
with self.subTest(constant=constant):
self.assertTrue(is_explicit_truth("{{ " + constant + " }}"))
def test_an_unregistered_jinja_expression_does_not_resolve(self):
self.assertFalse(
is_explicit_truth("{{ lookup('config', 'web-app-gitea', 'mcp.enabled') }}")
)
def test_a_literal_false_does_not_resolve(self):
self.assertFalse(is_explicit_truth(False))
def test_every_registered_constant_is_defined_in_group_vars(self):
group_vars = PROJECT_ROOT / "group_vars" / "all"
defined = "".join(read_text(str(path)) for path in group_vars.glob("*.yml"))
for constant in GROUP_GATED_CONSTANTS:
with self.subTest(constant=constant):
self.assertIn(f"{constant}:", defined)
if __name__ == "__main__":
unittest.main()
@@ -1,4 +1,4 @@
"""Unit tests for `cli.administration.deploy.development.inventory.nested_overrides`.
"""Unit tests for `utils.roles.applications.variants`' provider overrides.
The service registry is stubbed: what matters is which role a claim is
attributed to, not how a service key resolves to its provider.
@@ -9,7 +9,7 @@ from __future__ import annotations
import unittest
from unittest.mock import patch
from cli.administration.deploy.development.inventory.nested_overrides import (
from utils.roles.applications.variants import (
NestedOverrideConflictError,
collect_provider_overrides,
)
@@ -19,10 +19,7 @@ _REGISTRY = {
"gitea": {"role": "web-app-gitea"},
}
_PATCH = (
"cli.administration.deploy.development.inventory.nested_overrides"
".build_service_registry_from_roles_dir"
)
_PATCH = "utils.roles.applications.variants.build_service_registry_from_roles_dir"
class TestCollectProviderOverrides(unittest.TestCase):
+51
View File
@@ -0,0 +1,51 @@
import unittest
from utils.api import declared_api, provider_enabled, resolve_api
class TestResolveApi(unittest.TestCase):
def test_a_partial_override_keeps_the_declared_providers(self) -> None:
declared = declared_api()
self.assertIn("github", declared)
resolved = resolve_api({"API": {"openai": {"api_key": "sk-test"}}})
self.assertEqual(set(resolved), set(declared))
self.assertEqual(resolved["openai"]["api_key"], "sk-test")
self.assertEqual(resolved["github"]["client_id"], "")
def test_an_override_wins_per_key(self) -> None:
resolved = resolve_api({"API": {"github": {"client_id": "ID42"}}})
self.assertEqual(resolved["github"]["client_id"], "ID42")
self.assertEqual(resolved["github"]["client_secret"], "")
def test_a_missing_api_falls_back_to_the_declaration(self) -> None:
self.assertEqual(resolve_api({}), declared_api())
def test_a_non_mapping_api_is_an_error(self) -> None:
with self.assertRaises(TypeError):
resolve_api({"API": "nope"})
class TestProviderEnabled(unittest.TestCase):
def test_every_credential_must_carry_a_value(self) -> None:
api = {"github": {"client_id": "ID42", "client_secret": "SEC42"}}
self.assertTrue(provider_enabled(api, "github"))
def test_one_empty_credential_disables_the_provider(self) -> None:
api = {"github": {"client_id": "ID42", "client_secret": " "}}
self.assertFalse(provider_enabled(api, "github"))
def test_a_provider_without_credentials_is_disabled(self) -> None:
self.assertFalse(provider_enabled({"github": {}}, "github"))
def test_an_undeclared_provider_is_an_error(self) -> None:
with self.assertRaises(KeyError):
provider_enabled({}, "github")
if __name__ == "__main__":
unittest.main()
@@ -3,7 +3,7 @@ import io
import unittest
from unittest import mock
from utils.tests.swarm import matrix
from utils.tests.swarm import run
class TestRunReporting(unittest.TestCase):
@@ -18,10 +18,10 @@ class TestRunReporting(unittest.TestCase):
def _run_capturing(self, rc: int) -> tuple[int, str]:
buffer = io.StringIO()
with (
mock.patch.object(matrix, "_run_watched", return_value=rc) as watched,
mock.patch.object(run, "run_watched", return_value=rc) as watched,
contextlib.redirect_stdout(buffer),
):
returned = matrix._run(["true"], env={"A": "b"}, label="demo phase")
returned = run.run_step(["true"], env={"A": "b"}, label="demo phase")
watched.assert_called_once_with(["true"], env={"A": "b"})
return returned, buffer.getvalue()
@@ -0,0 +1,143 @@
"""Immutable tags the updater could not order before.
Two shapes reach the repository that name a fixed release yet failed the semver
gate, so the bump job skipped them and nothing could tell whether a newer one
existed: a vendor patch counter such as ``2.4.0p32`` and a five-component
version such as ``26.04.2.1.1``.
"""
from __future__ import annotations
import unittest
from utils.update.base import (
is_semver,
latest_semver,
version_depth,
version_flavor,
version_key,
)
def _latest(current: str, tags: list[str]) -> str | None:
return latest_semver(tags, version_depth(current), version_flavor(current))
class TestPatchCounterTags(unittest.TestCase):
def test_a_patch_counter_is_orderable(self):
self.assertTrue(is_semver("2.4.0p32"))
def test_it_bumps_within_its_own_counter(self):
self.assertEqual(_latest("2.4.0p32", ["2.4.0p32", "2.4.0p33"]), "2.4.0p33")
def test_the_counter_orders_numerically_not_lexically(self):
self.assertEqual(_latest("2.4.0p9", ["2.4.0p9", "2.4.0p10"]), "2.4.0p10")
def test_a_later_release_wins_over_a_later_counter(self):
self.assertEqual(_latest("2.4.0p32", ["2.4.0p99", "2.4.1p1"]), "2.4.1p1")
def test_it_never_crosses_into_a_four_component_version(self):
self.assertEqual(
_latest("2.4.0p32", ["2.4.0p32", "2.4.0.99"]),
"2.4.0p32",
"2.4.0.99 is a different tag family and bumping into it would "
"silently change what the role deploys",
)
def test_the_counter_letter_keeps_families_apart(self):
self.assertEqual(version_flavor("2.4.0p32"), "p")
self.assertEqual(version_flavor("2.4.0.32"), "")
self.assertNotEqual(version_depth("2.4.0p32"), version_depth("2.4.0.32"))
def test_a_plain_release_does_not_bump_into_a_counter(self):
self.assertEqual(_latest("2.4.0", ["2.4.0", "2.4.0p1"]), "2.4.0")
class TestFiveComponentTags(unittest.TestCase):
def test_five_components_are_orderable(self):
self.assertTrue(is_semver("26.04.2.1.1"))
self.assertEqual(version_depth("26.04.2.1.1"), 5)
def test_it_bumps_within_its_own_depth(self):
self.assertEqual(
_latest("26.04.2.1.1", ["26.04.2.1.1", "26.04.2.1.2"]), "26.04.2.1.2"
)
def test_it_never_crosses_into_a_shorter_version(self):
self.assertEqual(
_latest("26.04.2.1.1", ["26.04.2.1.1", "27.0.0.0"]), "26.04.2.1.1"
)
class TestNothingElseChanged(unittest.TestCase):
"""The shapes the updater already handled must keep their family key."""
def test_known_shapes_keep_their_classification(self):
cases = {
"1.2.3": (True, 3, "", (1, 2, 3, 0)),
"v1.12.27": (True, 3, "", (1, 12, 27, 0)),
"16": (True, 1, "", (16, 0, 0, 0)),
"5.4.5-php8.3-apache": (True, 3, "-php8.3-apache", (5, 4, 5, 0)),
}
for tag, (semver, depth, flavor, key) in cases.items():
self.assertEqual(is_semver(tag), semver, tag)
self.assertEqual(version_depth(tag), depth, tag)
self.assertEqual(version_flavor(tag), flavor, tag)
self.assertEqual(version_key(tag), key, tag)
def test_moving_names_are_still_refused(self):
for tag in ("latest", "stable", "lts", "alpine", "main"):
self.assertFalse(is_semver(tag), tag)
def test_a_flavored_tag_still_refuses_a_different_runtime(self):
self.assertEqual(
_latest("5.4.5-php8.3-apache", ["5.4.6-php8.4-apache", "5.4.6"]),
None,
)
class TestChannelPrefixedTags(unittest.TestCase):
"""A release line written before the number is a family, not a version."""
def test_a_channel_prefixed_tag_is_orderable(self):
self.assertTrue(is_semver("main-v1.77.7-stable"))
self.assertEqual(version_depth("main-v1.77.7-stable"), 3)
self.assertEqual(version_key("main-v1.77.7-stable"), (1, 77, 7, 0))
def test_it_bumps_inside_its_own_channel(self):
tags = ["main-v1.77.7-stable", "main-v1.83.14-stable"]
self.assertEqual(_latest("main-v1.77.7-stable", tags), "main-v1.83.14-stable")
def test_it_never_crosses_into_a_sibling_channel(self):
tags = ["main-v1.83.14-nightly", "main-v1.83.14-stable"]
self.assertEqual(_latest("main-v1.77.7-stable", tags), "main-v1.83.14-stable")
self.assertEqual(_latest("main-v1.77.7-nightly", tags), "main-v1.83.14-nightly")
def test_a_bare_number_is_a_different_family_than_a_channelled_one(self):
self.assertNotEqual(version_flavor("stable-9646"), version_flavor("9646"))
self.assertEqual(
_latest("stable-9646", ["stable-9646", "9999"]),
"stable-9646",
"a bare build number leaves the stable channel and would change "
"what the role deploys",
)
def test_it_bumps_inside_the_stable_channel(self):
self.assertEqual(
_latest("stable-9646", ["stable-9646", "stable-9999"]), "stable-9999"
)
def test_a_channel_without_a_number_stays_refused(self):
for tag in ("act-latest", "bookworm-slim", "main-latest", "buildx-stable-1"):
self.assertFalse(is_semver(tag), tag)
def test_a_date_stamped_tag_orders_as_one_number(self):
self.assertEqual(version_depth("20260917"), 1)
self.assertEqual(
_latest("20260702", ["20260702", "20260706", "20260917"]), "20260917"
)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,114 @@
import json
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from utils.update.collection_source import (
RATIO,
WINDOW,
append_sample,
decide,
load_history,
)
def _samples(galaxy, git, count=WINDOW):
return [{"galaxy": galaxy, "git": git} for _ in range(count)]
class TestAppendSample(unittest.TestCase):
def test_the_window_never_grows_past_its_size(self):
history = _samples(10.0, 10.0, WINDOW)
grown = append_sample(history, {"galaxy": 99.0, "git": 1.0})
self.assertEqual(len(grown), WINDOW)
self.assertEqual(grown[-1], {"galaxy": 99.0, "git": 1.0})
def test_the_oldest_sample_is_the_one_dropped(self):
history = [{"galaxy": float(i), "git": 1.0} for i in range(WINDOW)]
grown = append_sample(history, {"galaxy": 99.0, "git": 1.0})
self.assertEqual(grown[0]["galaxy"], 1.0)
class TestDecide(unittest.TestCase):
def test_below_a_full_window_the_default_is_left_alone(self):
history = _samples(300.0, 10.0, WINDOW - 1)
verdict = decide(history, "galaxy")
self.assertFalse(verdict.changed)
self.assertEqual(verdict.samples, WINDOW - 1)
def test_exactly_the_ratio_swaps_the_preferred_source(self):
history = _samples(30.0, 10.0)
verdict = decide(history, "galaxy")
self.assertTrue(verdict.changed)
self.assertEqual(verdict.proposed, "git")
def test_just_under_the_ratio_keeps_the_preferred_source(self):
history = _samples(10.0 * RATIO - 0.1, 10.0)
self.assertFalse(decide(history, "galaxy").changed)
def test_a_failed_install_ranks_worse_than_any_duration(self):
history = _samples(None, 10.0)
verdict = decide(history, "galaxy")
self.assertTrue(verdict.changed)
self.assertEqual(verdict.proposed, "git")
self.assertEqual(verdict.medians["galaxy"], float("inf"))
def test_the_faster_source_is_never_swapped_away_from(self):
history = _samples(10.0, 300.0)
self.assertFalse(decide(history, "galaxy").changed)
def test_both_sources_failing_changes_nothing(self):
history = _samples(None, None)
self.assertFalse(decide(history, "galaxy").changed)
def test_a_single_outlier_does_not_move_the_median(self):
history = _samples(10.0, 10.0, WINDOW - 1)
history = append_sample(history, {"galaxy": 9000.0, "git": 10.0})
self.assertFalse(decide(history, "galaxy").changed)
def test_the_verdict_is_taken_from_the_preferred_side(self):
history = _samples(10.0, 30.0)
verdict = decide(history, "git")
self.assertTrue(verdict.changed)
self.assertEqual(verdict.proposed, "galaxy")
class TestLoadHistory(unittest.TestCase):
def test_a_missing_file_reads_as_an_empty_history(self):
with TemporaryDirectory() as tmp:
self.assertEqual(load_history(Path(tmp) / "absent.json"), [])
def test_a_corrupt_file_reads_as_an_empty_history(self):
with TemporaryDirectory() as tmp:
path = Path(tmp) / "history.json"
path.write_text("{not json", encoding="utf-8")
self.assertEqual(load_history(path), [])
def test_a_written_history_round_trips(self):
with TemporaryDirectory() as tmp:
path = Path(tmp) / "history.json"
history = _samples(1.0, 2.0, 3)
path.write_text(json.dumps(history), encoding="utf-8")
self.assertEqual(load_history(path), history)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,112 @@
"""Several images of one role at one version move together or not at all.
Upstream does not push a release group atomically. Measured on Docker Hub:
``jitsi/prosody``, ``jitsi/jicofo`` and ``jitsi/jvb`` all publish
``stable-9457`` while ``jitsi/web`` does not, so a bump run landing in that
window would raise three components and leave the fourth behind.
"""
from __future__ import annotations
import unittest
from pathlib import Path
from utils.roles.mapping import ROLE_FILE_META_SERVICES
from utils.update.docker import (
DockerImageVersionEntry,
DockerImageVersionUpdate,
_held_to_release_groups,
)
JITSI = ("web", "prosody", "jicofo", "jvb")
def _entry(role: str, service: str, image: str, version: str):
return DockerImageVersionEntry(
role=role,
service=service,
image=image,
version=version,
config_path=Path(ROLE_FILE_META_SERVICES),
)
def _jitsi_updates(version: str, latest: str):
return [
DockerImageVersionUpdate(
entry=_entry("web-app-jitsi", name, f"jitsi/{name}", version),
latest=latest,
)
for name in JITSI
]
class TestReleaseGroupsMoveTogether(unittest.TestCase):
def test_a_partial_publish_holds_the_whole_group_back(self):
tags = {
"jitsi/web": ["stable-9400", "stable-9646"],
"jitsi/prosody": ["stable-9400", "stable-9646", "stable-9700"],
"jitsi/jicofo": ["stable-9400", "stable-9646", "stable-9700"],
"jitsi/jvb": ["stable-9400", "stable-9646", "stable-9700"],
}
updates = _jitsi_updates("stable-9400", "stable-9700")
held = _held_to_release_groups(updates, tags)
self.assertEqual({update.latest for update in held}, {"stable-9646"})
self.assertEqual(len(held), 4)
def test_a_group_all_publish_moves_to_the_head(self):
tags = {f"jitsi/{name}": ["stable-9400", "stable-9700"] for name in JITSI}
updates = _jitsi_updates("stable-9400", "stable-9700")
held = _held_to_release_groups(updates, tags)
self.assertEqual({update.latest for update in held}, {"stable-9700"})
def test_a_group_with_nothing_in_common_is_dropped(self):
tags = {
"jitsi/web": ["stable-9400", "stable-9701"],
"jitsi/prosody": ["stable-9400", "stable-9702"],
"jitsi/jicofo": ["stable-9400", "stable-9703"],
"jitsi/jvb": ["stable-9400", "stable-9704"],
}
updates = _jitsi_updates("stable-9400", "stable-9704")
self.assertEqual(_held_to_release_groups(updates, tags), [])
def test_a_lone_entry_is_untouched(self):
update = DockerImageVersionUpdate(
entry=_entry("web-app-fider", "fider", "getfider/fider", "v0.35.0"),
latest="v0.36.0",
)
held = _held_to_release_groups([update], {"getfider/fider": ["v0.36.0"]})
self.assertEqual(held, [update])
def test_two_roles_on_one_version_are_not_one_group(self):
tags = {
"jitsi/web": ["stable-9400", "stable-9700"],
"other/thing": ["stable-9400"],
}
updates = [
DockerImageVersionUpdate(
entry=_entry("web-app-jitsi", "web", "jitsi/web", "stable-9400"),
latest="stable-9700",
),
DockerImageVersionUpdate(
entry=_entry("web-app-other", "thing", "other/thing", "stable-9400"),
latest="stable-9400",
),
]
held = _held_to_release_groups(updates, tags)
self.assertEqual(
[update.latest for update in held], ["stable-9700", "stable-9400"]
)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,127 @@
import unittest
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest.mock import patch
from utils.update.galaxy import apply_updates, collect_pins, find_outdated_updates
GALAXY = """---
collections:
- name: community.general
version: 13.2.0
- name: kewlfft.aur
version: 0.13.0
"""
GIT = """---
collections:
- name: community.general
source: https://github.com/ansible-collections/community.general.git
type: git
version: 13.2.0
- name: kewlfft.aur
source: https://github.com/kewlfft/ansible-aur.git
type: git
version: master
"""
def _read(root: Path, name: str) -> str:
path = root / "requirements" / name
return path.read_text() # nocheck: cache-read -- rewritten by this test
def _repo(root: Path) -> Path:
(root / "requirements").mkdir()
(root / "requirements" / "requirements.galaxy.yml").write_text(
GALAXY, encoding="utf-8"
)
(root / "requirements" / "requirements.git.yml").write_text(GIT, encoding="utf-8")
return root
class TestCollectPins(unittest.TestCase):
def test_only_collections_pinned_to_a_semver_in_both_files_are_collected(self):
with TemporaryDirectory() as tmp:
root = _repo(Path(tmp))
pins = collect_pins(root)
self.assertEqual([pin.fqcn for pin in pins], ["community.general"])
def test_a_version_the_two_files_disagree_on_is_not_collected(self):
with TemporaryDirectory() as tmp:
root = _repo(Path(tmp))
(root / "requirements" / "requirements.galaxy.yml").write_text(
GALAXY.replace("13.2.0", "13.4.0"), encoding="utf-8"
)
self.assertEqual(collect_pins(root), [])
class TestFindOutdatedUpdates(unittest.TestCase):
def test_a_higher_tag_of_the_same_depth_is_an_update(self):
with TemporaryDirectory() as tmp:
root = _repo(Path(tmp))
with patch(
"utils.update.galaxy.git_ls_remote_tags",
return_value=["13.1.0", "13.2.0", "13.4.0"],
):
updates = find_outdated_updates(root)
self.assertEqual([u.latest for u in updates], ["13.4.0"])
def test_the_newest_tag_already_pinned_is_no_update(self):
with TemporaryDirectory() as tmp:
root = _repo(Path(tmp))
with patch(
"utils.update.galaxy.git_ls_remote_tags",
return_value=["13.1.0", "13.2.0"],
):
self.assertEqual(find_outdated_updates(root), [])
def test_a_tag_of_a_different_depth_is_not_a_candidate(self):
with TemporaryDirectory() as tmp:
root = _repo(Path(tmp))
with patch(
"utils.update.galaxy.git_ls_remote_tags",
return_value=["13.2.0", "14"],
):
self.assertEqual(find_outdated_updates(root), [])
class TestApplyUpdates(unittest.TestCase):
def test_both_requirement_files_are_bumped_together(self):
with TemporaryDirectory() as tmp:
root = _repo(Path(tmp))
with patch(
"utils.update.galaxy.git_ls_remote_tags",
return_value=["13.4.0"],
):
updates = find_outdated_updates(root)
changed = apply_updates(root, updates)
self.assertEqual(len(changed), 2)
galaxy_text = _read(root, "requirements.galaxy.yml")
git_text = _read(root, "requirements.git.yml")
self.assertIn("version: 13.4.0", galaxy_text)
self.assertIn("version: 13.4.0", git_text)
self.assertNotIn("13.2.0", galaxy_text)
self.assertNotIn("13.2.0", git_text)
def test_an_entry_outside_the_update_keeps_its_version(self):
with TemporaryDirectory() as tmp:
root = _repo(Path(tmp))
with patch(
"utils.update.galaxy.git_ls_remote_tags",
return_value=["13.4.0"],
):
apply_updates(root, find_outdated_updates(root))
self.assertIn("version: master", _read(root, "requirements.git.yml"))
self.assertIn("version: 0.13.0", _read(root, "requirements.galaxy.yml"))
if __name__ == "__main__":
unittest.main()
@@ -5,10 +5,12 @@ import unittest
from pathlib import Path
from utils.cache.files import read_text
from utils.roles.mapping import ROLE_DIR_META_ADDONS, ROLE_FILE_META_SERVICES
from utils.update.repository import (
RepositoryRefEntry,
RepositoryRefUpdate,
apply_updates,
collect_entries,
suppressed_ref_lines,
update_config_refs,
walk_repo_ref_pairs,
@@ -216,5 +218,46 @@ class TestApplyUpdates(unittest.TestCase):
self.assertEqual(read_text(str(config_b)), " ref: v2.1.0\n")
class TestCollectEntriesCoversAddons(unittest.TestCase):
def _role(self, root: Path) -> Path:
role = root / "roles" / "web-app-example"
(role / ROLE_DIR_META_ADDONS).mkdir(parents=True)
return role
def test_addon_ref_is_collected_beside_the_service_ref(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
role = self._role(root)
(role / ROLE_FILE_META_SERVICES).write_text(
"app:\n repository: https://example.test/app.git\n ref: v1.0.0\n",
encoding="utf-8",
)
(role / ROLE_DIR_META_ADDONS / "plug.yml").write_text(
"config:\n repository: https://example.test/plug.git\n ref: v2.0.0\n",
encoding="utf-8",
)
by_ref = {entry.ref: entry for entry in collect_entries(root)}
self.assertEqual(set(by_ref), {"v1.0.0", "v2.0.0"})
addon = by_ref["v2.0.0"]
self.assertEqual(addon.entity_path[:2], ("addons", "plug"))
self.assertEqual(addon.config_path.name, "plug.yml")
def test_addon_ref_honours_its_own_suppression_marker(self) -> None:
with tempfile.TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
role = self._role(root)
(role / ROLE_DIR_META_ADDONS / "plug.yml").write_text(
"config:\n"
" repository: https://example.test/plug.git\n"
" # nocheck: repository-version\n"
" ref: v2.0.0\n",
encoding="utf-8",
)
self.assertEqual(collect_entries(root), [])
if __name__ == "__main__":
unittest.main()