From 641f7a40dd8cc17e5f82deb23391a9c7f81315f7 Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 11 Sep 2026 21:14:55 +0200 Subject: [PATCH] fix(nextcloud): keep the sociallogin uid within 64 chars on onion deploys Sociallogin creates a Nextcloud user as "-", and the provider name was the Keycloak domain. On an onion variant that domain alone is 67 chars, so every OIDC callback died with InvalidArgumentException "Username is too long" and HTTP 500 at /apps/sociallogin/custom_oidc/auth. (run 34615516009, Nextcloud#1, 204 occurrences). The whiteboard and admin OIDC specs failed on the same login. This is the second derived identifier an onion domain overflows; the kernel hostname is the first, clamped to 63 bytes by container_hostname since the pretix and bookwyrm fixes. The domain-or-entity rule now lives in one lookup, bounded_name(application_id, max_length): the primary domain when it fits, otherwise the entity name. container_hostname delegates to it at 63 and keeps its eight callers and its behaviour. The provider name is bounded_name('web-app-keycloak', 64 - 1 - 36), the uid limit minus the separator and the UUID sub. A short clearnet domain stays the name, so existing users keep their uids; an onion deploy gets "keycloak", which, unlike a hash of the domain, survives a rotated onion address. Tests cover the lookup's fit, boundary and fallback cases and its argument validation, container_hostname's delegation at 63, and the provider name's room for the sub. Co-Authored-By: Claude Opus 5 (1M context) --- plugins/lookup/bounded_name.py | 70 +++++++++++++++++++ plugins/lookup/container_hostname.py | 39 ++--------- .../meta/addons/sociallogin.yml | 2 +- .../plugins/lookup/test_bounded_name.py | 70 +++++++++++++++++++ .../plugins/lookup/test_container_hostname.py | 64 ++++------------- .../test_sociallogin_provider_name.py | 46 ++++++++++++ 6 files changed, 204 insertions(+), 87 deletions(-) create mode 100644 plugins/lookup/bounded_name.py create mode 100644 tests/unit/python/plugins/lookup/test_bounded_name.py create mode 100644 tests/unit/python/roles/web-app-nextcloud/test_sociallogin_provider_name.py diff --git a/plugins/lookup/bounded_name.py b/plugins/lookup/bounded_name.py new file mode 100644 index 0000000000..7c8edc390d --- /dev/null +++ b/plugins/lookup/bounded_name.py @@ -0,0 +1,70 @@ +from __future__ import annotations + +from typing import Any + +from ansible.errors import AnsibleError +from ansible.plugins.loader import lookup_loader +from ansible.plugins.lookup import LookupBase + +from utils.domains.primary_domain import get_domain +from utils.roles.entity.name import get_entity_name + + +class LookupModule(LookupBase): + """ + Usage: + {{ lookup('bounded_name', application_id, max_length) }} + + An application's canonical primary domain when it has at most max_length + characters, otherwise its short entity name (e.g. ``keycloak``). + + Args: + application_id: the application whose domain names the value. + max_length: the longest value the consumer accepts; a positive integer. + """ + + def run(self, terms, variables: dict[str, Any] | None = None, **kwargs): + if not terms or len(terms) != 2: + raise AnsibleError( + "lookup('bounded_name', application_id, max_length) expects exactly 2 terms" + ) + + application_id, max_length = terms + if not isinstance(application_id, str) or not application_id.strip(): + raise AnsibleError( + "lookup('bounded_name'): application_id must be a " + f"non-empty string, got {application_id!r}" + ) + application_id = application_id.strip() + + try: + limit = int(max_length) + except (TypeError, ValueError) as e: + raise AnsibleError( + f"lookup('bounded_name'): max_length must be an integer, got {max_length!r}" + ) from e + if limit < 1: + raise AnsibleError( + f"lookup('bounded_name'): max_length must be positive, got {limit}" + ) + + variables = variables or getattr(self._templar, "available_variables", {}) or {} + + domains = lookup_loader.get( + "domains", + loader=getattr(self, "_loader", None), + templar=getattr(self, "_templar", None), + ).run([], variables=variables, roles_dir=kwargs.get("roles_dir"))[0] + + try: + domain = get_domain(domains, application_id) + except Exception as e: + raise AnsibleError( + f"lookup('bounded_name'): failed to resolve domain for " + f"'{application_id}': {e}" + ) from e + + name = str(domain or "") + if 0 < len(name) <= limit: + return [name] + return [get_entity_name(application_id)] diff --git a/plugins/lookup/container_hostname.py b/plugins/lookup/container_hostname.py index 25c28bdb67..fe2b343e98 100644 --- a/plugins/lookup/container_hostname.py +++ b/plugins/lookup/container_hostname.py @@ -6,9 +6,6 @@ from ansible.errors import AnsibleError from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase -from utils.domains.primary_domain import get_domain -from utils.roles.entity.name import get_entity_name - _HOST_NAME_MAX = 63 @@ -17,11 +14,8 @@ class LookupModule(LookupBase): Usage: {{ lookup('container_hostname', application_id) }} - The Docker/OCI hostname for an application's container: its canonical - primary domain when that fits the kernel's 63-byte limit, otherwise the - short entity name (e.g. ``xwiki``). Centralises the domain-or-entity - choice so onion deployments (long ``.onion`` subdomains that overflow - sethostname(2)) never break container init. + The Docker/OCI hostname for an application's container: ``bounded_name`` + at the 63-byte limit sethostname(2) enforces. """ def run(self, terms, variables: dict[str, Any] | None = None, **kwargs): @@ -30,31 +24,8 @@ class LookupModule(LookupBase): "lookup('container_hostname', application_id) expects exactly 1 term" ) - application_id = terms[0] - if not isinstance(application_id, str) or not application_id.strip(): - raise AnsibleError( - "lookup('container_hostname'): application_id must be a " - f"non-empty string, got {application_id!r}" - ) - application_id = application_id.strip() - - variables = variables or getattr(self._templar, "available_variables", {}) or {} - - domains = lookup_loader.get( - "domains", + return lookup_loader.get( + "bounded_name", loader=getattr(self, "_loader", None), templar=getattr(self, "_templar", None), - ).run([], variables=variables, roles_dir=kwargs.get("roles_dir"))[0] - - try: - domain = get_domain(domains, application_id) - except Exception as e: - raise AnsibleError( - f"lookup('container_hostname'): failed to resolve domain for " - f"'{application_id}': {e}" - ) from e - - name = str(domain or "") - if 0 < len(name) <= _HOST_NAME_MAX: - return [name] - return [get_entity_name(application_id)] + ).run([terms[0], _HOST_NAME_MAX], variables=variables, **kwargs) diff --git a/roles/web-app-nextcloud/meta/addons/sociallogin.yml b/roles/web-app-nextcloud/meta/addons/sociallogin.yml index cc23d6f796..00c0606d4d 100644 --- a/roles/web-app-nextcloud/meta/addons/sociallogin.yml +++ b/roles/web-app-nextcloud/meta/addons/sociallogin.yml @@ -31,7 +31,7 @@ config: configkey: "custom_providers" configvalue: custom_oidc: - - name: "{{ lookup('domain','web-app-keycloak') }}" + - name: "{{ lookup('bounded_name', 'web-app-keycloak', 64 - 1 - 36) }}" title: "keycloak" style: "keycloak" authorizeUrl: "{{ OIDC.CLIENT.AUTHORIZE_URL }}" diff --git a/tests/unit/python/plugins/lookup/test_bounded_name.py b/tests/unit/python/plugins/lookup/test_bounded_name.py new file mode 100644 index 0000000000..0fa95092e8 --- /dev/null +++ b/tests/unit/python/plugins/lookup/test_bounded_name.py @@ -0,0 +1,70 @@ +import unittest +from unittest.mock import MagicMock, patch + +from ansible.errors import AnsibleError + +from plugins.lookup.bounded_name import LookupModule + +ONION = "x.wiki." + "a" * 56 + ".onion" + + +class TestBoundedNameLookup(unittest.TestCase): + def setUp(self): + self.lookup = LookupModule() + + def _get(name, *args, **kwargs): + plugin = MagicMock() + + def _run(terms, variables=None, **_kwargs): + return [(variables or {}).get("domains", {})] + + plugin.run.side_effect = _run + return plugin + + self._patchers = [ + patch("plugins.lookup.bounded_name.lookup_loader.get", side_effect=_get), + patch( + "plugins.lookup.bounded_name.get_domain", + side_effect=lambda domains, app: domains[app], + ), + patch( + "plugins.lookup.bounded_name.get_entity_name", + side_effect=lambda app: app.rsplit("-", 1)[-1], + ), + ] + for p in self._patchers: + p.start() + self.addCleanup(lambda: [p.stop() for p in self._patchers]) + + def _run(self, domain, limit, app="web-app-xwiki"): + return self.lookup.run([app, limit], variables={"domains": {app: domain}})[0] + + def test_a_fitting_domain_is_kept(self): + self.assertEqual(self._run("wiki.example.org", 63), "wiki.example.org") + + def test_a_domain_at_the_limit_is_kept(self): + self.assertEqual(self._run("a" * 27, 27), "a" * 27) + + def test_a_longer_domain_falls_back_to_the_entity(self): + self.assertEqual(self._run(ONION, 63), "xwiki") + self.assertEqual(self._run("a" * 28, 27), "xwiki") + + def test_an_empty_domain_falls_back_to_the_entity(self): + self.assertEqual(self._run("", 63), "xwiki") + + def test_bad_arity_raises(self): + with self.assertRaises(AnsibleError): + self.lookup.run(["web-app-xwiki"], variables={}) + + def test_an_empty_application_raises(self): + with self.assertRaises(AnsibleError): + self.lookup.run([" ", 63], variables={}) + + def test_a_non_positive_or_non_integer_limit_raises(self): + for limit in (0, -1, "many"): + with self.subTest(limit=limit), self.assertRaises(AnsibleError): + self.lookup.run(["web-app-xwiki", limit], variables={}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/plugins/lookup/test_container_hostname.py b/tests/unit/python/plugins/lookup/test_container_hostname.py index 373066d99b..89ff6ebef8 100644 --- a/tests/unit/python/plugins/lookup/test_container_hostname.py +++ b/tests/unit/python/plugins/lookup/test_container_hostname.py @@ -7,62 +7,22 @@ from plugins.lookup.container_hostname import LookupModule class TestContainerHostnameLookup(unittest.TestCase): - def setUp(self): - self.lookup = LookupModule() + def test_delegates_to_bounded_name_at_the_kernel_limit(self): + bounded = MagicMock() + bounded.run.return_value = ["xwiki"] + with patch( + "plugins.lookup.container_hostname.lookup_loader.get", + return_value=bounded, + ) as get: + result = LookupModule().run(["web-app-xwiki"], variables={"k": "v"}) - def _get(name, *args, **kwargs): - plugin = MagicMock() - - def _run(terms, variables=None, **_kwargs): - return [(variables or {}).get("domains", {})] - - plugin.run.side_effect = _run - return plugin - - self._patchers = [ - patch( - "plugins.lookup.container_hostname.lookup_loader.get", - side_effect=_get, - ), - patch( - "plugins.lookup.container_hostname.get_domain", - side_effect=lambda domains, app: domains[app], - ), - patch( - "plugins.lookup.container_hostname.get_entity_name", - side_effect=lambda app: app.rsplit("-", 1)[-1], - ), - ] - for p in self._patchers: - p.start() - self.addCleanup(lambda: [p.stop() for p in self._patchers]) - - def _run(self, app, domain): - return self.lookup.run([app], variables={"domains": {app: domain}})[0] - - def test_short_domain_is_kept(self): - self.assertEqual( - self._run("web-app-xwiki", "wiki.example.org"), "wiki.example.org" - ) - - def test_long_onion_domain_falls_back_to_entity(self): - onion = "x.wiki." + "a" * 56 + ".onion" - self.assertEqual(self._run("web-app-xwiki", onion), "xwiki") - - def test_63_char_domain_is_kept(self): - name = "a" * 63 - self.assertEqual(self._run("web-app-xwiki", name), name) - - def test_empty_domain_falls_back(self): - self.assertEqual(self._run("web-app-xwiki", ""), "xwiki") + self.assertEqual(result, ["xwiki"]) + self.assertEqual(get.call_args.args[0], "bounded_name") + bounded.run.assert_called_once_with(["web-app-xwiki", 63], variables={"k": "v"}) def test_bad_arity_raises(self): with self.assertRaises(AnsibleError): - self.lookup.run([], variables={}) - - def test_empty_app_raises(self): - with self.assertRaises(AnsibleError): - self.lookup.run([" "], variables={}) + LookupModule().run([], variables={}) if __name__ == "__main__": diff --git a/tests/unit/python/roles/web-app-nextcloud/test_sociallogin_provider_name.py b/tests/unit/python/roles/web-app-nextcloud/test_sociallogin_provider_name.py new file mode 100644 index 0000000000..cb1dc6ad33 --- /dev/null +++ b/tests/unit/python/roles/web-app-nextcloud/test_sociallogin_provider_name.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +import unittest + +from jinja2 import Environment + +from utils.cache.files import PROJECT_ROOT, read_text +from utils.cache.yaml import load_yaml_str + +ADDON = PROJECT_ROOT / "roles/web-app-nextcloud/meta/addons/sociallogin.yml" +UID_LIMIT = 64 +KEYCLOAK_SUB_LENGTH = 36 + + +def _provider_name_call() -> tuple: + config = load_yaml_str(read_text(str(ADDON)))["config"]["plugin_configuration"] + providers = next( + entry["configvalue"] + for entry in config + if entry["configkey"] == "custom_providers" + ) + calls = [] + + def lookup(*args): + calls.append(args) + return "" + + Environment(autoescape=True).from_string( + providers["custom_oidc"][0]["name"] + ).render(lookup=lookup) + return calls[0] + + +class TestSocialLoginProviderName(unittest.TestCase): + def test_the_provider_name_leaves_room_for_the_keycloak_sub(self) -> None: + kind, application_id, max_length = _provider_name_call() + self.assertEqual((kind, application_id), ("bounded_name", "web-app-keycloak")) + self.assertLessEqual( + max_length + 1 + KEYCLOAK_SUB_LENGTH, + UID_LIMIT, + 'Nextcloud rejects a sociallogin uid ("-") over 64 chars', + ) + + +if __name__ == "__main__": + unittest.main()