Files
computer-playbook/tests/unit/python/plugins/lookup/test_users.py
T
kevinveenbirkenbachandClaude Opus 5 677a63931c Merge branch 'feature/network/multi-network-serving' into feature/store-i18n
Resolves 68 conflicted files. The governing rule was our structure with their
network semantics: the tor boolean becomes a network mode (clearnet | tor |
multi) throughout the variant layer, while this branch's architecture and mesh
axes, its extracted modules and its i18n content stay.

Where the two sides covered different ground, both are kept rather than one
picked:

- ca_injected answers a ca_client on the deployment's TLS mode OR on an SSO
  issuer that resolves self-signed. 3a3e9ed2c9 records why: an issuer is not
  an object store, so keeping only one side drops the other's coverage.
- get_merged_domains keeps the loud refusal when svc-net-tor is deployed
  without a provisioned node, now gated on their tor_serves_host; their
  node_onion_of returns an empty string there, which would have served every
  onion-exclusive app on clearnet in silence.
- sso_cookie_domains stays the single source for oauth2-proxy's cookie scope.
  Their per-network branch omitted the issuer domain on the onion arm, which
  breaks the callback leg.
- The clearnet CSP batch carries --clearnet-timeout again; their batch dict
  hardcoded zero while the role still passes the flag.
- The dashboard keeps its i18n content dir, image, version and design
  resolution; their side reduced the logo sources to the bare service
  provider values.

Their side wins where it is measurably better: the onion mirror rewrite is
gated per vhost rather than per app, the Playwright onion decision reads the
pass's own domain instead of the role's canonical one, and the matomo
reinjection and dashboard config render per network sibling.

Eight files were broken by the merge without ever carrying a conflict marker,
because git marks only the lines both sides touched:

- utils/cache/domains.py lost the onionize block that sat between two hunks
- roles/sys-front-inj-all/templates/body_filter.lua.j2 called it
- web-app-bluesky, keycloak sso_proxy: the get_entity_name filter was renamed
- trigger/__main__.py, playwright_coverage.py and its test: the deleted tor
  module
- cli/administration/deploy/ci/timings.py read Label.tor
- plugins/filter/csp_filters.py called _aligned_url with four of six arguments
- tests/unit/python/utils/cache/test_domains.py referenced a renamed class
- tests/.../sys-ctl-hlth-csp/files/test_script.py mocked a function main no
  longer calls

Verified: the variant layer (155 tests, 65 subtests), ca_injected (18),
the CI layer (175), the domains cache including the restored guard (32),
retrigger inputs (9), timings and the CSP health script (53). make
quality-high clears autoformat; its remaining findings are tracked separately.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-10-23 09:53:41 +02:00

358 lines
12 KiB
Python

from __future__ import annotations
import os
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
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.yaml import dump_yaml_str
from utils.domains.default_primary import default_domain_primary
from utils.paths import FILE_TOKENS
from utils.roles.mapping import ROLE_FILE_META_USERS
DOMAIN = default_domain_primary()
def _write_users(base_dir: Path, role_name: str, users: dict) -> None:
"""Write meta/users.yml — file root IS the users map."""
users_path = base_dir / "roles" / role_name / ROLE_FILE_META_USERS
users_path.parent.mkdir(parents=True, exist_ok=True)
users_path.write_text(dump_yaml_str(users), encoding="utf-8")
class TestUsersLookup(unittest.TestCase):
def setUp(self) -> None:
self.lookup = LookupModule()
self._cwd = str(Path.cwd())
self._tmpdir = tempfile.TemporaryDirectory()
self._tmp = Path(self._tmpdir.name)
os.chdir(self._tmp)
_reset_cache_for_tests()
_write_users(
self._tmp,
"identity",
{
"alice": {
"username": "alice",
"email": "alice@example.org",
"authorized_keys": ["ssh-ed25519 AAAA alice@example.org"],
}
},
)
self.lookup._templar = None
def tearDown(self) -> None:
_reset_cache_for_tests()
os.chdir(self._cwd)
self._tmpdir.cleanup()
def test_returns_full_mapping(self) -> None:
result = self.lookup.run([], variables={}, roles_dir=str(self._tmp / "roles"))[
0
]
self.assertIn("alice", result)
self.assertEqual(result["alice"]["email"], "alice@example.org")
def test_returns_single_entry(self) -> None:
result = self.lookup.run(
["alice"],
variables={},
roles_dir=str(self._tmp / "roles"),
)[0]
self.assertEqual(result["username"], "alice")
def test_applies_inventory_override(self) -> None:
result = self.lookup.run(
["alice"],
variables={"users": {"alice": {"email": "override@example.org"}}},
roles_dir=str(self._tmp / "roles"),
)[0]
self.assertEqual(result["email"], "override@example.org")
self.assertEqual(result["username"], "alice")
def test_ignores_non_mapping_runtime_users_placeholder(self) -> None:
result = self.lookup.run(
["alice"],
variables={"users": "alice"},
roles_dir=str(self._tmp / "roles"),
)[0]
self.assertEqual(result["email"], "alice@example.org")
self.assertEqual(result["username"], "alice")
def test_missing_entry_raises_without_default(self) -> None:
with self.assertRaises(AnsibleError):
self.lookup.run(
["bob"],
variables={},
roles_dir=str(self._tmp / "roles"),
)
def test_missing_entry_returns_default_when_provided(self) -> None:
default_value = {"fallback": True}
result = self.lookup.run(
["bob", default_value],
variables={},
roles_dir=str(self._tmp / "roles"),
)[0]
self.assertEqual(result, default_value)
def test_renders_templated_defaults_with_templar(self) -> None:
_write_users(
self._tmp,
"templated",
{
"blackhole": {
"email": "blackhole@{{ SYSTEM_EMAIL_DOMAIN }}",
"password": "{{ 42 | strong_password }}",
}
},
)
_reset_cache_for_tests()
self.lookup._templar = _SplitTemplar(
{"SYSTEM_EMAIL_DOMAIN": "mail.example.org"}
)
result = self.lookup.run(
["blackhole"],
variables={"SYSTEM_EMAIL_DOMAIN": "mail.example.org"},
roles_dir=str(self._tmp / "roles"),
)[0]
self.assertEqual(result["email"], "blackhole@mail.example.org")
self.assertEqual(result["password"], "strong-password-42")
def test_domain_primary_falls_back_to_system_email_domain(self) -> None:
_write_users(
self._tmp,
"templated",
{
"sld": {
"username": "{{ DOMAIN_PRIMARY.split('.')[0] }}",
"accounts": [],
}
},
)
_reset_cache_for_tests()
self.lookup._templar = _SplitTemplar(
{"SYSTEM_EMAIL_DOMAIN": "mail.example.org"}
)
result = self.lookup.run(
["domain_label_0"],
variables={"SYSTEM_EMAIL_DOMAIN": "mail.example.org"},
roles_dir=str(self._tmp / "roles"),
)[0]
self.assertEqual(result["username"], "mail")
def test_materializes_sld_without_templar_when_domain_primary_is_available(
self,
) -> None:
_write_users(
self._tmp,
"templated",
{
"sld": {
"username": "{{ DOMAIN_PRIMARY.split('.')[0] }}",
"accounts": [],
}
},
)
_reset_cache_for_tests()
self.lookup._templar = None
result = self.lookup.run(
["domain_label_0"],
variables={"DOMAIN_PRIMARY": "portal.example.org"},
roles_dir=str(self._tmp / "roles"),
)[0]
self.assertEqual(result["username"], "portal")
def test_role_domain_no_longer_stands_in_for_the_primary_domain(
self,
) -> None:
_write_users(
self._tmp,
"templated",
{
"sld": {
"username": "{{ DOMAIN_PRIMARY.split('.')[0] }}",
"accounts": [],
}
},
)
_reset_cache_for_tests()
self.lookup._templar = None
with self.assertRaises(AnsibleError):
self.lookup.run(
["domain_label_0"],
variables={"domain": f"auth.{DOMAIN}"},
roles_dir=str(self._tmp / "roles"),
)
def test_reserves_domain_labels_from_env_backed_domain_primary(self) -> None:
_write_users(
self._tmp,
"templated",
{
"sld": {
"username": "{{ DOMAIN_PRIMARY.split('.')[0] }}",
"accounts": [],
}
},
)
_reset_cache_for_tests()
self.lookup._templar = None
with patch.dict(os.environ, {"DOMAIN": "infinito.localhost"}, clear=False):
result = self.lookup.run(
["domain_label_0"],
variables={
"DOMAIN_PRIMARY": "{{ lookup('env', 'DOMAIN') | default('infinito.localhost', true) }}"
},
roles_dir=str(self._tmp / "roles"),
)[0]
self.assertEqual(result["username"], "infinito")
def test_renders_templated_defaults_when_templar_returns_unchanged(self) -> None:
_write_users(
self._tmp,
"templated",
{
"blackhole": {
"email": "blackhole@{{ SYSTEM_EMAIL_DOMAIN }}",
"password": "{{ 16 | strong_password }}",
}
},
)
_reset_cache_for_tests()
self.lookup._templar = _NoopTemplar({"SYSTEM_EMAIL_DOMAIN": "mail.example.org"})
result = self.lookup.run(
["blackhole"],
variables={"SYSTEM_EMAIL_DOMAIN": "mail.example.org"},
roles_dir=str(self._tmp / "roles"),
)[0]
self.assertEqual(result["email"], "blackhole@mail.example.org")
self.assertNotRegex(result["password"], r"\{\{.*?\}\}")
self.assertGreaterEqual(len(result["password"]), 12)
def test_hydrates_tokens_from_dir_secrets_when_file_tokens_missing(self) -> None:
secrets_dir = self._tmp / "var" / "lib" / "infinito" / "secrets"
secrets_dir.mkdir(parents=True, exist_ok=True)
(secrets_dir / FILE_TOKENS.name).write_text(
dump_yaml_str(
{
"users": {
"alice": {
"tokens": {
"web-app-mailu": "token-from-dir-secrets",
}
}
}
}
),
encoding="utf-8",
)
result = self.lookup.run(
["alice"],
variables={"DIR_SECRETS": str(secrets_dir)},
roles_dir=str(self._tmp / "roles"),
)[0]
self.assertEqual(result["tokens"]["web-app-mailu"], "token-from-dir-secrets")
def test_hydrates_tokens_from_default_store_path_when_path_vars_missing(
self,
) -> None:
default_tokens = self._tmp / "default" / "tokens.yml"
default_tokens.parent.mkdir(parents=True, exist_ok=True)
default_tokens.write_text(
dump_yaml_str(
{
"users": {
"alice": {
"tokens": {
"web-app-mailu": "token-from-default-path",
}
}
}
}
),
encoding="utf-8",
)
previous_default = runtime_data_base.DEFAULT_TOKENS_FILE
runtime_data_base.DEFAULT_TOKENS_FILE = default_tokens
try:
result = self.lookup.run(
["alice"],
variables={},
roles_dir=str(self._tmp / "roles"),
)[0]
finally:
runtime_data_base.DEFAULT_TOKENS_FILE = previous_default
self.assertEqual(result["tokens"]["web-app-mailu"], "token-from-default-path")
class _DummyTemplar:
def __init__(self, variables: dict[str, str]) -> None:
self.available_variables = dict(variables)
def template(self, value, fail_on_undefined=False):
if isinstance(value, dict):
return {
key: self.template(item, fail_on_undefined=fail_on_undefined)
for key, item in value.items()
}
if isinstance(value, list):
return [
self.template(item, fail_on_undefined=fail_on_undefined)
for item in value
]
if not isinstance(value, str):
return value
rendered = value
for key, replacement in self.available_variables.items():
rendered = rendered.replace("{{ " + key + " }}", str(replacement))
return rendered.replace("{{ 42 | strong_password }}", "strong-password-42")
class _NoopTemplar:
def __init__(self, variables: dict[str, str]) -> None:
self.available_variables = dict(variables)
def template(self, value, fail_on_undefined=False):
return value
class _SplitTemplar(_DummyTemplar):
def template(self, value, fail_on_undefined=False):
rendered = super().template(value, fail_on_undefined=fail_on_undefined)
if not isinstance(rendered, str):
return rendered
domain_primary = self.available_variables.get("DOMAIN_PRIMARY")
if domain_primary:
rendered = rendered.replace(
"{{ DOMAIN_PRIMARY.split('.')[0] }}",
str(domain_primary).split(".")[0],
)
return rendered
if __name__ == "__main__":
unittest.main()