mirror of
https://github.com/kevinveenbirkenbach/computer-playbook.git
synced 2026-11-30 14:56:11 +00:00
Merge branch 'feature/ai-agent-employees' into feature/store-i18n
This commit is contained in:
170 files changed
+4745
-566
No files matched your search
@@ -11,6 +11,12 @@ from utils.cache.yaml import load_yaml
|
||||
_AI_VARS = Path(PROJECT_ROOT) / "group_vars" / "all" / "16_ai.yml"
|
||||
|
||||
|
||||
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"):
|
||||
@@ -38,6 +44,7 @@ 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=(), lmstudio_models=()):
|
||||
@@ -45,6 +52,8 @@ class TestLitellmChatModel(unittest.TestCase):
|
||||
self.env.from_string(self.source[name])
|
||||
.render(
|
||||
LITELLM_BACKEND_ROLES=list(roles),
|
||||
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],
|
||||
|
||||
@@ -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, [])
|
||||
|
||||
@@ -28,6 +28,12 @@ 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"):
|
||||
@@ -66,14 +72,11 @@ def render(*, ollama=(), lmstudio=(), keys=None):
|
||||
lmstudio: preload entries svc-ai-lmstudio declares; empty means not deployed.
|
||||
keys: env-name -> provider key for the remote backends.
|
||||
"""
|
||||
group_names = ["svc-ai-litellm"]
|
||||
if ollama:
|
||||
group_names.append("svc-ai-ollama")
|
||||
if lmstudio:
|
||||
group_names.append("svc-ai-lmstudio")
|
||||
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(
|
||||
group_names=group_names,
|
||||
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,
|
||||
|
||||
@@ -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,105 @@
|
||||
"""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 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_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,162 @@
|
||||
"""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\x00") -> None:
|
||||
super().__init__(daemon=True)
|
||||
self._reply_code = reply_code
|
||||
self._greeting = greeting
|
||||
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.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 conn:
|
||||
conn.recv(3)
|
||||
conn.sendall(self._greeting)
|
||||
if self._greeting != b"\x05\x00":
|
||||
return
|
||||
self.request = conn.recv(512)
|
||||
if self._reply_code is None:
|
||||
return
|
||||
conn.sendall(bytes([0x05, self._reply_code, 0x00, 0x01]))
|
||||
self._server.close()
|
||||
|
||||
|
||||
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_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,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,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()
|
||||
+66
@@ -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()
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user