mirror of
https://github.com/kevinveenbirkenbach/computer-playbook.git
synced 2026-11-28 22:06:31 +00:00
Merge branch 'feature/updater' into feature/store-i18n
Brings in feature/updateraccb22da75, which carries main5995766f58. Conflict resolutions: - web-app-fider: main's tenant bootstrap (01_tenant.yml) runs first on the stack host, OIDC setup moves to 02_setup_oidc.yml, design to 03_design.yml; flat includes so main's gate test reads them. - sys-front-tls test_nginx_ssl_header: the tls fake maps the domain term store-i18n passes back to its app. - group_vars 04_webserver.yml, sys-svc-proxy CSP header: store-i18n's webserver_resource lookup plus #1256's WEBSERVER_SECURITY_HEADERS and the security_headers.lua include after the CSP block. - web-app-nextcloud: updater's decoupled Talk stack (Janus, signaling, NATS, recording builds) replaces aio-talk; store-i18n's per-network Talk backends move from the wrapper script into signaling.conf.j2 urls (NEXTCLOUD_HPB_SIGNALING_BACKEND_URLS from network_urls, canonical first); IS_COMPOSE_MODE/IS_SWARM_MODE booleans kept; the integration OpenProject digest stays delegated to STACK_HOST. - users lookup docs, token-store write_many, cache README, meta info lint: both sides combined. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
5e8890d208
130 files changed
+4303
-898
No files matched your search
@@ -4,7 +4,7 @@ from unittest.mock import patch
|
||||
from ansible.errors import AnsibleActionFail
|
||||
|
||||
from plugins.action.applications_carrier import ActionModule
|
||||
from utils.cache.carrier import APPLICATIONS_RENDERED_FACT
|
||||
from utils.cache.carrier import APPLICATIONS_RENDERED_FACT, USERS_RENDERED_FACT
|
||||
|
||||
|
||||
class _FakeTask:
|
||||
@@ -31,6 +31,16 @@ class _FakeLookup:
|
||||
return [self.carrier]
|
||||
|
||||
|
||||
class _FakeLoader:
|
||||
def __init__(self, applications, users):
|
||||
self.lookups = {"applications": applications, "users": users}
|
||||
self.order = []
|
||||
|
||||
def get(self, name, loader=None, templar=None):
|
||||
self.order.append(name)
|
||||
return self.lookups[name]
|
||||
|
||||
|
||||
def _make_action(task: _FakeTask, templar=None) -> ActionModule:
|
||||
action = object.__new__(ActionModule)
|
||||
action._task = task
|
||||
@@ -39,10 +49,19 @@ def _make_action(task: _FakeTask, templar=None) -> ActionModule:
|
||||
return action
|
||||
|
||||
|
||||
def _lookups(templar=None):
|
||||
applications = _FakeLookup(
|
||||
{"key": ["roles", ["a", "b", "c", "d"]], "applications": {"x": {}}}, templar
|
||||
)
|
||||
users = _FakeLookup(
|
||||
{"key": ["roles", ["a", "b", "c", "d", "h"]], "users": {"u": {}}}, templar
|
||||
)
|
||||
return applications, users, _FakeLoader(applications, users)
|
||||
|
||||
|
||||
class TestApplicationsCarrierActionPlugin(unittest.TestCase):
|
||||
def test_parks_the_carrier_as_a_masked_fact(self):
|
||||
carrier = {"key": ["roles", ["a", "b", "c", "d"]], "applications": {"x": {}}}
|
||||
lookup = _FakeLookup(carrier)
|
||||
def test_parks_both_carriers_as_masked_facts(self):
|
||||
applications, users, loader = _lookups()
|
||||
action = _make_action(_FakeTask())
|
||||
with (
|
||||
patch(
|
||||
@@ -52,23 +71,78 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase):
|
||||
),
|
||||
patch(
|
||||
"plugins.action.applications_carrier.lookup_loader.get",
|
||||
return_value=lookup,
|
||||
side_effect=loader.get,
|
||||
),
|
||||
):
|
||||
result = action.run(task_vars={"applications": {}})
|
||||
|
||||
self.assertIs(result["ansible_facts"][APPLICATIONS_RENDERED_FACT], carrier)
|
||||
self.assertIs(
|
||||
result["ansible_facts"][APPLICATIONS_RENDERED_FACT], applications.carrier
|
||||
)
|
||||
self.assertIs(result["ansible_facts"][USERS_RENDERED_FACT], users.carrier)
|
||||
self.assertTrue(result["_ansible_no_log"])
|
||||
self.assertFalse(result["changed"])
|
||||
terms, variables, kwargs = lookup.calls[0]
|
||||
self.assertEqual(terms, [])
|
||||
self.assertEqual(variables, {"applications": {}})
|
||||
self.assertTrue(kwargs["carrier"])
|
||||
for lookup in (applications, users):
|
||||
terms, variables, kwargs = lookup.calls[0]
|
||||
self.assertEqual(terms, [])
|
||||
self.assertEqual(variables, {"applications": {}})
|
||||
self.assertTrue(kwargs["carrier"])
|
||||
|
||||
def _park(self, task_vars):
|
||||
applications, users, loader = _lookups()
|
||||
action = _make_action(_FakeTask())
|
||||
with (
|
||||
patch(
|
||||
"plugins.action.applications_carrier.ActionBase.run",
|
||||
autospec=True,
|
||||
return_value={},
|
||||
),
|
||||
patch(
|
||||
"plugins.action.applications_carrier.lookup_loader.get",
|
||||
side_effect=loader.get,
|
||||
),
|
||||
patch("plugins.action.applications_carrier.revalidate_tokens_file"),
|
||||
):
|
||||
return action.run(task_vars=task_vars), applications, users
|
||||
|
||||
def test_a_users_carrier_that_still_matches_stays_in_place(self):
|
||||
parked = {"key": ["roles", ["a", "b", "c", "d", "h"]], "users": {"u": {}}}
|
||||
result, applications, _ = self._park({USERS_RENDERED_FACT: parked})
|
||||
|
||||
self.assertNotIn(USERS_RENDERED_FACT, result["ansible_facts"])
|
||||
self.assertIs(
|
||||
result["ansible_facts"][APPLICATIONS_RENDERED_FACT], applications.carrier
|
||||
)
|
||||
|
||||
def test_a_stale_users_carrier_is_replaced(self):
|
||||
parked = {"key": ["roles", ["a", "b", "c", "d", "h2"]], "users": {"u": {}}}
|
||||
result, _, users = self._park({USERS_RENDERED_FACT: parked})
|
||||
|
||||
self.assertIs(result["ansible_facts"][USERS_RENDERED_FACT], users.carrier)
|
||||
|
||||
def test_renders_the_applications_before_the_users(self):
|
||||
_, _, loader = _lookups()
|
||||
action = _make_action(_FakeTask())
|
||||
with (
|
||||
patch(
|
||||
"plugins.action.applications_carrier.ActionBase.run",
|
||||
autospec=True,
|
||||
return_value={},
|
||||
),
|
||||
patch(
|
||||
"plugins.action.applications_carrier.lookup_loader.get",
|
||||
side_effect=loader.get,
|
||||
),
|
||||
patch("plugins.action.applications_carrier.revalidate_tokens_file"),
|
||||
):
|
||||
action.run(task_vars={})
|
||||
|
||||
self.assertEqual(loader.order, ["applications", "users"])
|
||||
|
||||
def test_renders_without_the_callers_application_id(self):
|
||||
task_vars = {"applications": {}, "application_id": "web-app-bluesky"}
|
||||
templar = _FakeTemplar(task_vars)
|
||||
lookup = _FakeLookup({"key": ["roles", []], "applications": {}}, templar)
|
||||
applications, users, loader = _lookups(templar)
|
||||
action = _make_action(_FakeTask(), templar)
|
||||
with (
|
||||
patch(
|
||||
@@ -78,22 +152,26 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase):
|
||||
),
|
||||
patch(
|
||||
"plugins.action.applications_carrier.lookup_loader.get",
|
||||
return_value=lookup,
|
||||
side_effect=loader.get,
|
||||
),
|
||||
patch("plugins.action.applications_carrier.revalidate_tokens_file"),
|
||||
):
|
||||
action.run(task_vars=task_vars)
|
||||
|
||||
_, variables, _ = lookup.calls[0]
|
||||
self.assertEqual(variables, {"applications": {}})
|
||||
self.assertEqual(lookup.templar_variables, [{"applications": {}}])
|
||||
for lookup in (applications, users):
|
||||
_, variables, _ = lookup.calls[0]
|
||||
self.assertEqual(variables, {"applications": {}})
|
||||
self.assertEqual(lookup.templar_variables, [{"applications": {}}])
|
||||
self.assertIs(templar.available_variables, task_vars)
|
||||
self.assertEqual(task_vars["application_id"], "web-app-bluesky")
|
||||
|
||||
def test_revalidates_the_tokens_file_before_rendering(self):
|
||||
order = []
|
||||
lookup = _FakeLookup({"key": ["roles", []], "applications": {}})
|
||||
lookup.run = lambda *args, **kwargs: order.append("render") or [{}]
|
||||
applications, users, loader = _lookups()
|
||||
applications.run = lambda *args, **kwargs: (
|
||||
order.append("applications") or [applications.carrier]
|
||||
)
|
||||
users.run = lambda *args, **kwargs: order.append("users") or [users.carrier]
|
||||
action = _make_action(_FakeTask())
|
||||
with (
|
||||
patch(
|
||||
@@ -103,7 +181,7 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase):
|
||||
),
|
||||
patch(
|
||||
"plugins.action.applications_carrier.lookup_loader.get",
|
||||
return_value=lookup,
|
||||
side_effect=loader.get,
|
||||
),
|
||||
patch(
|
||||
"plugins.action.applications_carrier.revalidate_tokens_file",
|
||||
@@ -113,7 +191,8 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase):
|
||||
action.run(task_vars={"FILE_TOKENS": "/x/tokens.yml"})
|
||||
|
||||
self.assertEqual(
|
||||
order, [("revalidate", {"FILE_TOKENS": "/x/tokens.yml"}), "render"]
|
||||
order,
|
||||
[("revalidate", {"FILE_TOKENS": "/x/tokens.yml"}), "applications", "users"],
|
||||
)
|
||||
|
||||
def test_clear_does_not_revalidate(self):
|
||||
@@ -144,8 +223,8 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase):
|
||||
):
|
||||
action.run(task_vars={})
|
||||
|
||||
def test_clear_drops_the_fact_without_rendering(self):
|
||||
lookup = _FakeLookup({"key": ["roles", []], "applications": {}})
|
||||
def test_clear_drops_both_facts_without_rendering(self):
|
||||
applications, users, loader = _lookups()
|
||||
action = _make_action(_FakeTask(args={"clear": True}))
|
||||
with (
|
||||
patch(
|
||||
@@ -155,18 +234,21 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase):
|
||||
),
|
||||
patch(
|
||||
"plugins.action.applications_carrier.lookup_loader.get",
|
||||
return_value=lookup,
|
||||
side_effect=loader.get,
|
||||
),
|
||||
):
|
||||
result = action.run(task_vars={"applications": {}})
|
||||
|
||||
self.assertIsNone(result["ansible_facts"][APPLICATIONS_RENDERED_FACT])
|
||||
self.assertEqual(
|
||||
result["ansible_facts"],
|
||||
{APPLICATIONS_RENDERED_FACT: None, USERS_RENDERED_FACT: None},
|
||||
)
|
||||
self.assertFalse(result["changed"])
|
||||
self.assertEqual(lookup.calls, [])
|
||||
self.assertEqual(applications.calls, [])
|
||||
self.assertEqual(users.calls, [])
|
||||
|
||||
def test_clear_false_still_renders(self):
|
||||
carrier = {"key": ["roles", ["a", "b", "c", "d"]], "applications": {"x": {}}}
|
||||
lookup = _FakeLookup(carrier)
|
||||
applications, users, loader = _lookups()
|
||||
action = _make_action(_FakeTask(args={"clear": "no"}))
|
||||
with (
|
||||
patch(
|
||||
@@ -176,13 +258,17 @@ class TestApplicationsCarrierActionPlugin(unittest.TestCase):
|
||||
),
|
||||
patch(
|
||||
"plugins.action.applications_carrier.lookup_loader.get",
|
||||
return_value=lookup,
|
||||
side_effect=loader.get,
|
||||
),
|
||||
):
|
||||
result = action.run(task_vars={"applications": {}})
|
||||
|
||||
self.assertIs(result["ansible_facts"][APPLICATIONS_RENDERED_FACT], carrier)
|
||||
self.assertEqual(len(lookup.calls), 1)
|
||||
self.assertIs(
|
||||
result["ansible_facts"][APPLICATIONS_RENDERED_FACT], applications.carrier
|
||||
)
|
||||
self.assertIs(result["ansible_facts"][USERS_RENDERED_FACT], users.carrier)
|
||||
self.assertEqual(len(applications.calls), 1)
|
||||
self.assertEqual(len(users.calls), 1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -89,6 +89,47 @@ class TestCspTogglesDashboardLogout(unittest.TestCase):
|
||||
self.assertIn("'unsafe-inline'", attr)
|
||||
self.assertIn("'unsafe-inline'", elem)
|
||||
|
||||
def test_logout_respects_explicit_disable_on_elem_directive(self):
|
||||
apps = copy.deepcopy(self.apps)
|
||||
apps["app1"]["csp"]["flags"]["script-src-elem"] = {"unsafe-inline": False}
|
||||
self._set_service_enabled(apps, "logout", True)
|
||||
|
||||
header = self.filter.build_csp_header(
|
||||
apps,
|
||||
"app1",
|
||||
self.domains,
|
||||
"https",
|
||||
extra_hashes={"script-src-elem": ["console.log('logout');"]},
|
||||
)
|
||||
elem = self._get_directive_tokens(header, "script-src-elem")
|
||||
attr = self._get_directive_tokens(header, "script-src-attr")
|
||||
expected_hash = self.filter.get_csp_hash("console.log('logout');")
|
||||
|
||||
self.assertNotIn("'unsafe-inline'", elem)
|
||||
self.assertIn(expected_hash, elem)
|
||||
self.assertIn("'unsafe-inline'", attr)
|
||||
|
||||
def test_logout_respects_explicit_disable_on_whole_script_family(self):
|
||||
apps = copy.deepcopy(self.apps)
|
||||
for directive in ("script-src", "script-src-elem", "script-src-attr"):
|
||||
apps["app1"]["csp"]["flags"][directive] = {"unsafe-inline": False}
|
||||
self._set_service_enabled(apps, "logout", True)
|
||||
|
||||
header = self.filter.build_csp_header(
|
||||
apps,
|
||||
"app1",
|
||||
self.domains,
|
||||
"https",
|
||||
extra_hashes={"script-src-elem": ["console.log('logout');"]},
|
||||
)
|
||||
expected_hash = self.filter.get_csp_hash("console.log('logout');")
|
||||
|
||||
for directive in ("script-src", "script-src-elem", "script-src-attr"):
|
||||
self.assertNotIn(
|
||||
"'unsafe-inline'", self._get_directive_tokens(header, directive)
|
||||
)
|
||||
self.assertIn(expected_hash, self._get_directive_tokens(header, "script-src"))
|
||||
|
||||
def test_logout_propagates_to_base_when_not_explicitly_disabled(self):
|
||||
apps = copy.deepcopy(self.apps)
|
||||
apps["app1"].setdefault("csp", {}).setdefault("flags", {})
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
import copy
|
||||
import unittest
|
||||
|
||||
from plugins.filter.security_headers import FilterModule
|
||||
from utils.cache.yaml import load_yaml
|
||||
from utils.roles.applications.security_headers import security_headers
|
||||
|
||||
from . import PROJECT_ROOT
|
||||
|
||||
PLATFORM = {
|
||||
"nosniff": False,
|
||||
"referrer_policy": "",
|
||||
"permissions_policy": "",
|
||||
"hsts": {"max_age": 31536000, "include_subdomains": False, "preload": False},
|
||||
}
|
||||
|
||||
|
||||
def apps_with(override):
|
||||
"""Return an applications map whose one app declares *override*.
|
||||
|
||||
Args:
|
||||
override: the app's ``server.security_headers`` block.
|
||||
"""
|
||||
return {"web-app-x": {"server": {"security_headers": override}}}
|
||||
|
||||
|
||||
class TestPlatformValues(unittest.TestCase):
|
||||
def test_an_app_without_a_block_gets_the_platform_values(self):
|
||||
apps = {"web-app-plain": {"server": {"status_codes": {"default": [200]}}}}
|
||||
self.assertEqual(
|
||||
security_headers(apps, "web-app-plain", PLATFORM),
|
||||
{
|
||||
"nosniff": False,
|
||||
"referrer_policy": "",
|
||||
"permissions_policy": "",
|
||||
"hsts": "max-age=31536000",
|
||||
},
|
||||
)
|
||||
|
||||
def test_a_redirect_vhost_passes_its_domain_and_gets_the_platform_values(self):
|
||||
result = security_headers(apps_with({"nosniff": True}), "old.example", PLATFORM)
|
||||
self.assertFalse(result["nosniff"])
|
||||
self.assertEqual(result["hsts"], "max-age=31536000")
|
||||
|
||||
def test_the_repository_platform_values_are_valid(self):
|
||||
platform = load_yaml(PROJECT_ROOT / "group_vars/all/04_webserver.yml")[
|
||||
"WEBSERVER_SECURITY_HEADERS"
|
||||
]
|
||||
self.assertEqual(
|
||||
security_headers({}, "web-app-plain", platform)["hsts"],
|
||||
"max-age=31536000",
|
||||
)
|
||||
|
||||
def test_an_incomplete_platform_block_fails(self):
|
||||
platform = copy.deepcopy(PLATFORM)
|
||||
del platform["hsts"]["preload"]
|
||||
with self.assertRaisesRegex(ValueError, "preload"):
|
||||
security_headers({}, "web-app-plain", platform)
|
||||
|
||||
def test_the_platform_block_is_not_mutated(self):
|
||||
platform = copy.deepcopy(PLATFORM)
|
||||
security_headers(
|
||||
apps_with({"hsts": {"include_subdomains": True}}), "web-app-x", platform
|
||||
)
|
||||
self.assertEqual(platform, PLATFORM)
|
||||
|
||||
|
||||
class TestOverrides(unittest.TestCase):
|
||||
def test_an_override_replaces_only_its_own_keys(self):
|
||||
result = security_headers(
|
||||
apps_with({"nosniff": True, "hsts": {"include_subdomains": True}}),
|
||||
"web-app-x",
|
||||
PLATFORM,
|
||||
)
|
||||
self.assertTrue(result["nosniff"])
|
||||
self.assertEqual(result["referrer_policy"], "")
|
||||
self.assertEqual(result["hsts"], "max-age=31536000; includeSubDomains")
|
||||
|
||||
def test_preload_follows_include_subdomains(self):
|
||||
result = security_headers(
|
||||
apps_with({"hsts": {"include_subdomains": True, "preload": True}}),
|
||||
"web-app-x",
|
||||
PLATFORM,
|
||||
)
|
||||
self.assertEqual(result["hsts"], "max-age=31536000; includeSubDomains; preload")
|
||||
|
||||
def test_a_referrer_policy_list_is_accepted(self):
|
||||
value = "no-referrer, strict-origin-when-cross-origin"
|
||||
result = security_headers(
|
||||
apps_with({"referrer_policy": value}), "web-app-x", PLATFORM
|
||||
)
|
||||
self.assertEqual(result["referrer_policy"], value)
|
||||
|
||||
def test_a_permissions_policy_keeps_its_quoted_origins(self):
|
||||
value = 'camera=(self "https://meet.example.org"), microphone=(self)'
|
||||
result = security_headers(
|
||||
apps_with({"permissions_policy": value}), "web-app-x", PLATFORM
|
||||
)
|
||||
self.assertEqual(result["permissions_policy"], value)
|
||||
|
||||
|
||||
class TestRejections(unittest.TestCase):
|
||||
def assert_rejected(self, override, pattern, error=ValueError):
|
||||
with self.assertRaisesRegex(error, pattern):
|
||||
security_headers(apps_with(override), "web-app-x", PLATFORM)
|
||||
|
||||
def test_an_unknown_key_fails(self):
|
||||
self.assert_rejected({"nosnif": True}, "unknown keys")
|
||||
|
||||
def test_an_unknown_hsts_key_fails(self):
|
||||
self.assert_rejected({"hsts": {"subdomains": True}}, "unknown keys")
|
||||
|
||||
def test_a_non_mapping_block_fails(self):
|
||||
self.assert_rejected(None, "must be a mapping", TypeError)
|
||||
|
||||
def test_a_string_flag_fails(self):
|
||||
self.assert_rejected({"nosniff": "yes"}, "must be bool", TypeError)
|
||||
|
||||
def test_a_boolean_max_age_fails(self):
|
||||
self.assert_rejected({"hsts": {"max_age": True}}, "must be int", TypeError)
|
||||
|
||||
def test_a_negative_max_age_fails(self):
|
||||
self.assert_rejected({"hsts": {"max_age": -1}}, "negative")
|
||||
|
||||
def test_preload_without_include_subdomains_fails(self):
|
||||
self.assert_rejected({"hsts": {"preload": True}}, "requires include_subdomains")
|
||||
|
||||
def test_preload_with_a_short_max_age_fails(self):
|
||||
self.assert_rejected(
|
||||
{"hsts": {"max_age": 86400, "include_subdomains": True, "preload": True}},
|
||||
"at least 31536000",
|
||||
)
|
||||
|
||||
def test_an_unknown_referrer_policy_token_fails(self):
|
||||
self.assert_rejected(
|
||||
{"referrer_policy": "strict-origin-when-cross-orgin"},
|
||||
"unknown policy tokens",
|
||||
)
|
||||
|
||||
def test_a_line_break_in_a_header_value_fails(self):
|
||||
self.assert_rejected(
|
||||
{"permissions_policy": "camera=()\r\nSet-Cookie: x=1"},
|
||||
"printable ASCII",
|
||||
)
|
||||
|
||||
|
||||
class TestFilterModule(unittest.TestCase):
|
||||
def test_filter_is_registered(self):
|
||||
self.assertIs(FilterModule().filters()["security_headers"], security_headers)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -359,6 +359,94 @@ logo:
|
||||
with self.assertRaisesRegex(AnsibleError, "nope"):
|
||||
self._run_lookup(LookupModule(), fake_variables)
|
||||
|
||||
def _add_role(self, role_name, application_id, info_yaml):
|
||||
role_dir = Path(self.test_roles_dir) / role_name
|
||||
(role_dir / "meta").mkdir(parents=True)
|
||||
(role_dir / "vars").mkdir(parents=True)
|
||||
(role_dir / ROLE_FILE_VARS_MAIN).write_text(
|
||||
f"application_id: {application_id}\n", encoding="utf-8"
|
||||
)
|
||||
(role_dir / "README.md").write_text(f"# {role_name}\n", encoding="utf-8")
|
||||
(role_dir / ROLE_FILE_META_MAIN).write_text(
|
||||
'galaxy_info:\n description: "Second role."\n', encoding="utf-8"
|
||||
)
|
||||
(role_dir / ROLE_FILE_META_INFO).write_text(info_yaml, encoding="utf-8")
|
||||
|
||||
def _two_role_variables(self):
|
||||
self._add_role("web-app-other", "other", "logo:\n class: fa-solid fa-cube\n")
|
||||
fake_variables = self._base_fake_variables()
|
||||
fake_variables["domains"]["other"] = "other.example.com"
|
||||
fake_variables["applications"]["other"] = {
|
||||
"services": {"dashboard": {"enabled": True}}
|
||||
}
|
||||
fake_variables["group_names"] = ["portfolio", "other"]
|
||||
return fake_variables
|
||||
|
||||
def test_enabled_false_skips_the_card(self):
|
||||
fake_variables = self._base_fake_variables()
|
||||
fake_variables["applications"]["portfolio"]["services"]["dashboard"][
|
||||
"enabled"
|
||||
] = False
|
||||
|
||||
result = self._run_lookup(LookupModule(), fake_variables)
|
||||
|
||||
self.assertEqual(result, [[]])
|
||||
|
||||
def test_a_role_without_a_dashboard_binding_shows_the_card(self):
|
||||
fake_variables = self._base_fake_variables()
|
||||
fake_variables["applications"]["portfolio"]["services"] = {}
|
||||
|
||||
result = self._run_lookup(LookupModule(), fake_variables)
|
||||
|
||||
self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"])
|
||||
|
||||
def test_enabled_true_shows_the_card(self):
|
||||
fake_variables = self._base_fake_variables()
|
||||
|
||||
result = self._run_lookup(LookupModule(), fake_variables)
|
||||
|
||||
self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"])
|
||||
|
||||
def test_enabled_false_hides_only_its_own_card(self):
|
||||
fake_variables = self._two_role_variables()
|
||||
fake_variables["applications"]["other"]["services"]["dashboard"]["enabled"] = (
|
||||
False
|
||||
)
|
||||
|
||||
result = self._run_lookup(LookupModule(), fake_variables)
|
||||
|
||||
self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"])
|
||||
|
||||
def test_both_cards_render_when_both_are_enabled(self):
|
||||
fake_variables = self._two_role_variables()
|
||||
|
||||
result = self._run_lookup(LookupModule(), fake_variables)
|
||||
|
||||
self.assertEqual(
|
||||
[c["title"] for c in result[0]],
|
||||
["Portfolio Application", "web-app-other"],
|
||||
)
|
||||
|
||||
def test_info_display_false_no_longer_hides_the_card(self):
|
||||
meta_info_path = Path(self.role_dir) / ROLE_FILE_META_INFO
|
||||
meta_info_path.write_text(
|
||||
"logo:\n class: fa-solid fa-briefcase\ndisplay: false\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
result = self._run_lookup(LookupModule(), self._base_fake_variables())
|
||||
|
||||
self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"])
|
||||
|
||||
def test_non_boolean_enabled_fails_loudly(self):
|
||||
fake_variables = self._base_fake_variables()
|
||||
fake_variables["applications"]["portfolio"]["services"]["dashboard"][
|
||||
"enabled"
|
||||
] = "maybe"
|
||||
|
||||
with self.assertRaisesRegex(AnsibleError, "portfolio"):
|
||||
self._run_lookup(LookupModule(), fake_variables)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Unit tests for plugins/lookup/proxy_hops.py."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
import unittest.mock as mock
|
||||
|
||||
from ansible.errors import AnsibleError
|
||||
|
||||
from plugins.lookup.proxy_hops import LookupModule
|
||||
|
||||
_SUBNETS = {
|
||||
"web-app-nextcloud": "192.168.41.0/24",
|
||||
"svc-db-mariadb": "192.168.201.0/24",
|
||||
"svc-prx-openresty": "192.168.107.0/24",
|
||||
}
|
||||
|
||||
|
||||
class _Templar:
|
||||
def __init__(self, vars_=None):
|
||||
self.available_variables = vars_ or {}
|
||||
|
||||
def template(self, value, **_):
|
||||
return value
|
||||
|
||||
|
||||
def _make_lookup(vars_):
|
||||
lm = LookupModule()
|
||||
lm._templar = _Templar(vars_)
|
||||
lm._loader = mock.MagicMock()
|
||||
return lm
|
||||
|
||||
|
||||
def _role_subnets():
|
||||
return mock.MagicMock(
|
||||
run=lambda terms, **_: [[_SUBNETS[role] for role in terms[0]]]
|
||||
)
|
||||
|
||||
|
||||
def _joined(application_id, deployment_mode, **_):
|
||||
if application_id == "svc-prx-openresty":
|
||||
return ["svc-prx-openresty"] if deployment_mode == "swarm" else []
|
||||
if deployment_mode == "swarm":
|
||||
return ["svc-db-mariadb", "svc-prx-openresty", application_id]
|
||||
return ["svc-db-mariadb", application_id]
|
||||
|
||||
|
||||
def _run(mode, terms=("web-app-nextcloud",), joined=_joined):
|
||||
vars_ = {"application_id": "web-app-nextcloud", "DEPLOYMENT_MODE": mode}
|
||||
lm = _make_lookup(vars_)
|
||||
with (
|
||||
mock.patch(
|
||||
"utils.networks.lookup_context.build_service_registry_from_applications",
|
||||
return_value={},
|
||||
),
|
||||
mock.patch("utils.networks.lookup_context.lookup_loader") as context_loader,
|
||||
mock.patch("plugins.lookup.proxy_hops.lookup_loader") as plugin_loader,
|
||||
mock.patch(
|
||||
"plugins.lookup.proxy_hops.compute_external_network_roles",
|
||||
side_effect=lambda **kwargs: joined(
|
||||
kwargs["application_id"], kwargs["deployment_mode"]
|
||||
),
|
||||
) as roles_mock,
|
||||
):
|
||||
context_loader.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [""])
|
||||
plugin_loader.get.return_value = _role_subnets()
|
||||
result = lm.run(list(terms), variables=vars_)
|
||||
return result, roles_mock
|
||||
|
||||
|
||||
class TestProxyHopsLookup(unittest.TestCase):
|
||||
def test_raises_without_application_id_term(self):
|
||||
lm = _make_lookup({"DEPLOYMENT_MODE": "compose"})
|
||||
with self.assertRaises(AnsibleError):
|
||||
lm.run([], variables={})
|
||||
|
||||
def test_raises_on_extra_terms(self):
|
||||
lm = _make_lookup({"DEPLOYMENT_MODE": "compose"})
|
||||
with self.assertRaises(AnsibleError):
|
||||
lm.run(["web-app-nextcloud", "extra"], variables={})
|
||||
|
||||
def test_compose_returns_gateways_of_the_joined_networks(self):
|
||||
result, _ = _run("compose")
|
||||
self.assertEqual(result, [["192.168.41.1", "192.168.201.1"]])
|
||||
|
||||
def test_swarm_returns_the_overlay_shared_with_openresty(self):
|
||||
result, roles_mock = _run("swarm")
|
||||
self.assertEqual(result, [["192.168.107.0/24"]])
|
||||
asked = {call.kwargs["application_id"] for call in roles_mock.call_args_list}
|
||||
self.assertEqual(asked, {"web-app-nextcloud", "svc-prx-openresty"})
|
||||
|
||||
def test_missing_shared_overlay_surfaces_as_ansible_error(self):
|
||||
def isolated(application_id, deployment_mode):
|
||||
return [application_id]
|
||||
|
||||
with self.assertRaises(AnsibleError):
|
||||
_run("swarm", joined=isolated)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -10,6 +10,7 @@ from ansible.errors import AnsibleError
|
||||
|
||||
from plugins.lookup.users import LookupModule, _reset_cache_for_tests
|
||||
from utils.cache import base as runtime_data_base
|
||||
from utils.cache.carrier import USERS_RENDERED_FACT, merged_users_cache_key
|
||||
from utils.cache.yaml import dump_yaml_str
|
||||
from utils.domains.default_primary import default_domain_primary
|
||||
from utils.paths import FILE_TOKENS
|
||||
@@ -305,6 +306,46 @@ class TestUsersLookup(unittest.TestCase):
|
||||
|
||||
self.assertEqual(result["tokens"]["web-app-mailu"], "token-from-default-path")
|
||||
|
||||
def test_carrier_returns_the_users_with_the_key_they_are_valid_under(
|
||||
self,
|
||||
) -> None:
|
||||
roles = str(self._tmp / "roles")
|
||||
variables = {"inventory_hostname": "h1"}
|
||||
result = self.lookup.run(
|
||||
[], variables=variables, roles_dir=roles, carrier=True
|
||||
)[0]
|
||||
key = merged_users_cache_key(variables, roles_dir=roles)
|
||||
self.assertEqual(result["key"], [key[0], list(key[1])])
|
||||
self.assertEqual(
|
||||
result["users"],
|
||||
self.lookup.run([], variables=variables, roles_dir=roles)[0],
|
||||
)
|
||||
|
||||
def test_carrier_takes_no_terms(self) -> None:
|
||||
with self.assertRaises(AnsibleError):
|
||||
self.lookup.run(
|
||||
["alice"],
|
||||
variables={},
|
||||
roles_dir=str(self._tmp / "roles"),
|
||||
carrier=True,
|
||||
)
|
||||
|
||||
def test_a_parked_carrier_answers_a_fresh_worker_without_rendering(self) -> None:
|
||||
roles = str(self._tmp / "roles")
|
||||
self.lookup._templar = _DummyTemplar({"SYSTEM_EMAIL_DOMAIN": "example.org"})
|
||||
variables = {"inventory_hostname": "h1", "SYSTEM_EMAIL_DOMAIN": "example.org"}
|
||||
parked = self.lookup.run(
|
||||
[], variables=variables, roles_dir=roles, carrier=True
|
||||
)[0]
|
||||
_reset_cache_for_tests()
|
||||
variables[USERS_RENDERED_FACT] = parked
|
||||
with patch(
|
||||
"utils.cache.users._render_with_templar",
|
||||
side_effect=AssertionError("rendered"),
|
||||
):
|
||||
result = self.lookup.run(["alice"], variables=variables, roles_dir=roles)[0]
|
||||
self.assertIs(result, parked["users"]["alice"])
|
||||
|
||||
|
||||
class _DummyTemplar:
|
||||
def __init__(self, variables: dict[str, str]) -> None:
|
||||
|
||||
Reference in new issue
Block a user