From 890fd055a1734838ff267ade729fa8554ccc8c42 Mon Sep 17 00:00:00 2001 From: mrveiss Date: Sun, 8 Nov 2026 10:14:44 +0200 Subject: [PATCH 1/6] test(slm): login-standalone work in progress (#21153) --- .../test_slm_login_standalone_21153.py | 132 ++++++++++++++++++ 1 file changed, 132 insertions(+) create mode 100644 autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py diff --git a/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py b/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py new file mode 100644 index 0000000000..c1068f5db3 --- /dev/null +++ b/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py @@ -0,0 +1,132 @@ +# Copyright 2025-2026 mrveiss +# SPDX-License-Identifier: Apache-2.0 +# AutoBot - AI-Powered Automation Platform +# Author: mrveiss +"""SLM login needs nothing from the main app at request time (#21153, #10200, ADR-012). + +The SLM authenticates against its own ``users`` table (the copy the main app keeps current +through ``/internal/person-copy``). Here a real in-memory database holds an admin, the one +outbound client the SLM has for the main app is made to raise a connection error, and the +login lookup still succeeds. A source guard pins that the login modules never import that +client, so a later request-time call would fail this file rather than a user. +""" + +import ast +import importlib +import secrets +import sys +import uuid +from pathlib import Path +from unittest.mock import AsyncMock, patch + +import pytest + +from autobot_shared.user_management.base_service import TenantContext + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "api")) +from _real_orm_import import real_modules_swapped # noqa: E402 + +_SLM = Path(__file__).resolve().parents[2] +with real_modules_swapped(): + from sqlalchemy.dialects.postgresql import JSONB + from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine + from sqlalchemy.ext.compiler import compiles + + # Modules another test already bound to its own copy of sqlalchemy would mix two copies here: load fresh ones. + _OWN = ("user_management", "autobot_shared.user_management") + _stubs = {k: sys.modules.pop(k) for k in [k for k in sys.modules if k.startswith(_OWN)]} + try: # the conftest stands in for the SLM's ORM models; the real ones are the system under test + for _mod in ("user", "organization", "role", "team", "api_key", "mfa", "sso", "audit"): + importlib.import_module(f"user_management.models.{_mod}") + User = sys.modules["user_management.models.user"].User + UserService = importlib.import_module("autobot_shared.user_management.user_service").UserService + finally: + for _k in [k for k in sys.modules if k.startswith(_OWN)]: + del sys.modules[_k] + sys.modules.update(_stubs) + + +@compiles(JSONB, "sqlite") +def _jsonb_as_json(element, compiler, **kw): # noqa: ANN001 + return "JSON" + + +class _SlmUserService(UserService): + user_model = User + + +@pytest.fixture() +async def session(): + # the conftest stubs sqlalchemy; the dialect plugin and lazy ORM imports need the real one for the whole test + with real_modules_swapped(): + engine = create_async_engine("sqlite+aiosqlite://") # canonical: ignore py-adhoc-db-engine + async with engine.begin() as conn: + await conn.run_sync(User.metadata.create_all) + maker = async_sessionmaker(engine, expire_on_commit=False) # canonical: ignore py-adhoc-db-engine + async with maker() as db: + yield db + await engine.dispose() + + +_PASSWORD = secrets.token_urlsafe(16) + + +async def _seed_admin(db): + svc = _SlmUserService(db, TenantContext(is_platform_admin=True)) + db.add( + User( + id=uuid.uuid4(), + username="admin", + email="admin@example.test", + password_hash=svc.hash_password(_PASSWORD), + is_active=True, + is_platform_admin=True, + ) + ) + await db.commit() + return svc + + +@pytest.mark.asyncio +async def test_login_works_from_the_local_copy_with_the_main_app_unreachable(session): + svc = await _seed_admin(session) + down = AsyncMock(side_effect=ConnectionError("main app unreachable")) + with patch("services.main_backend_client.call_main_backend", down): + user = await svc.authenticate("admin", _PASSWORD) + by_email = await svc.authenticate("admin@example.test", _PASSWORD) + assert user is not None and user.username == "admin" and user.is_platform_admin + assert by_email is not None and by_email.id == user.id + down.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_a_wrong_password_is_refused_not_an_error_with_the_main_app_unreachable(session): + svc = await _seed_admin(session) + down = AsyncMock(side_effect=ConnectionError("main app unreachable")) + with patch("services.main_backend_client.call_main_backend", down): + assert await svc.authenticate("admin", _PASSWORD + "x") is None + down.assert_not_awaited() + + +_LOGIN_PATH = ( + "api/auth.py", + "api/login_rate_limit.py", + "services/auth.py", + "services/token_denylist.py", + "user_management/services/__init__.py", +) +_FORBIDDEN = ("main_backend_client", "httpx", "aiohttp", "requests", "urllib3") + + +@pytest.mark.parametrize("rel", _LOGIN_PATH) +def test_the_login_path_imports_no_client_for_the_main_app(rel): + tree = ast.parse((_SLM / rel).read_text(encoding="utf-8")) + imported = [] + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imported += [a.name for a in node.names] + elif isinstance(node, ast.ImportFrom): + imported.append(node.module or "") + imported += [a.name for a in node.names] + bad = [m for m in imported if any(m == f or m.startswith(f + ".") or m.endswith("." + f) for f in _FORBIDDEN)] + assert not bad, f"{rel} reaches the main app at request time: {bad}" From b3e2041b961a13a34804d6caf36d7d043328df35 Mon Sep 17 00:00:00 2001 From: mrveiss Date: Sun, 8 Nov 2026 17:27:29 +0200 Subject: [PATCH 2/6] fix(slm): pin that SLM login needs nothing from the main app (#21153) --- .../tests/services/test_slm_login_standalone_21153.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py b/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py index c1068f5db3..d9943b6cdf 100644 --- a/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py +++ b/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py @@ -36,8 +36,13 @@ _OWN = ("user_management", "autobot_shared.user_management") _stubs = {k: sys.modules.pop(k) for k in [k for k in sys.modules if k.startswith(_OWN)]} try: # the conftest stands in for the SLM's ORM models; the real ones are the system under test - for _mod in ("user", "organization", "role", "team", "api_key", "mfa", "sso", "audit"): + # Held strongly: SQLAlchemy's class registry keeps only weak references, and the finally below drops the modules + # from sys.modules, so a model nothing else references (Organization) is collected and ``Role`` can no longer + # resolve it by name when mappers configure (#21153). + _MODELS = [ importlib.import_module(f"user_management.models.{_mod}") + for _mod in ("user", "organization", "role", "team", "api_key", "mfa", "sso", "audit") + ] User = sys.modules["user_management.models.user"].User UserService = importlib.import_module("autobot_shared.user_management.user_service").UserService finally: From 17dca1bd6998705b8bae0995555b9d0e91f6e006 Mon Sep 17 00:00:00 2001 From: mrveiss Date: Sun, 8 Nov 2026 17:44:42 +0200 Subject: [PATCH 3/6] fix(slm): keep the SLM model modules loaded so the class registry resolves (#21153) --- .../test_slm_login_standalone_21153.py | 22 ++++++++----------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py b/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py index d9943b6cdf..214af9ae8e 100644 --- a/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py +++ b/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py @@ -32,23 +32,19 @@ from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine from sqlalchemy.ext.compiler import compiles - # Modules another test already bound to its own copy of sqlalchemy would mix two copies here: load fresh ones. + # The conftest stands in for the SLM's ``user_management`` package; the real one is the system under test, so the + # stand-ins are lifted for the import only. The real modules stay in ``sys.modules`` (SQLAlchemy's class registry + # holds weak references, so dropping them lets ``Organization`` be collected and ``Role`` stop resolving it). _OWN = ("user_management", "autobot_shared.user_management") - _stubs = {k: sys.modules.pop(k) for k in [k for k in sys.modules if k.startswith(_OWN)]} - try: # the conftest stands in for the SLM's ORM models; the real ones are the system under test - # Held strongly: SQLAlchemy's class registry keeps only weak references, and the finally below drops the modules - # from sys.modules, so a model nothing else references (Organization) is collected and ``Role`` can no longer - # resolve it by name when mappers configure (#21153). - _MODELS = [ + with pytest.MonkeyPatch.context() as _mp: + for _k in [k for k in sys.modules if k.startswith(_OWN)]: + _mp.delitem(sys.modules, _k) + for _mod in ("user", "organization", "role", "team", "api_key", "mfa", "sso", "audit"): importlib.import_module(f"user_management.models.{_mod}") - for _mod in ("user", "organization", "role", "team", "api_key", "mfa", "sso", "audit") - ] User = sys.modules["user_management.models.user"].User UserService = importlib.import_module("autobot_shared.user_management.user_service").UserService - finally: - for _k in [k for k in sys.modules if k.startswith(_OWN)]: - del sys.modules[_k] - sys.modules.update(_stubs) + for _k in [k for k in sys.modules if k.startswith(_OWN) and ".models" not in k]: + del sys.modules[_k] # the services keep the stand-ins other tests bind to; only the models stay @compiles(JSONB, "sqlite") From b131a492d66c96c9757b1a6c8c2ecd99102427b2 Mon Sep 17 00:00:00 2001 From: mrveiss Date: Sun, 8 Nov 2026 18:29:54 +0200 Subject: [PATCH 4/6] fix(slm): login-standalone test restores every sys.modules change (#21153) --- .../tests/services/test_slm_login_standalone_21153.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py b/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py index 214af9ae8e..259d9fc2d8 100644 --- a/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py +++ b/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py @@ -36,6 +36,7 @@ # stand-ins are lifted for the import only. The real modules stay in ``sys.modules`` (SQLAlchemy's class registry # holds weak references, so dropping them lets ``Organization`` be collected and ``Role`` stop resolving it). _OWN = ("user_management", "autobot_shared.user_management") + _before = set(sys.modules) with pytest.MonkeyPatch.context() as _mp: for _k in [k for k in sys.modules if k.startswith(_OWN)]: _mp.delitem(sys.modules, _k) @@ -43,8 +44,13 @@ importlib.import_module(f"user_management.models.{_mod}") User = sys.modules["user_management.models.user"].User UserService = importlib.import_module("autobot_shared.user_management.user_service").UserService - for _k in [k for k in sys.modules if k.startswith(_OWN) and ".models" not in k]: - del sys.modules[_k] # the services keep the stand-ins other tests bind to; only the models stay + _created = [k for k in sys.modules if k.startswith(_OWN) and ".models" not in k and k not in _before] + # ``_mp`` has put every stand-in back; the services imported above did not exist before, so a restore would keep + # them (bound to a second ``password_epoch``) for the next module. They are dropped through a MonkeyPatch whose + # record is deliberately never undone, which leaves ``sys.modules`` as it was found; only the models stay. + _drop = pytest.MonkeyPatch() + for _k in _created: + _drop.delitem(sys.modules, _k, raising=False) @compiles(JSONB, "sqlite") From 56d5d8adbaa4b70f542f5487f29c3b0dcaefe460 Mon Sep 17 00:00:00 2001 From: mrveiss Date: Sun, 8 Nov 2026 19:11:23 +0200 Subject: [PATCH 5/6] fix(slm): login-standalone test stubs the main-app client at its seam (#21153) --- .../tests/api/_real_orm_import.py | 66 +++++++++++++++- .../test_slm_login_standalone_21153.py | 79 ++++++++++--------- 2 files changed, 107 insertions(+), 38 deletions(-) diff --git a/autobot-slm-backend/tests/api/_real_orm_import.py b/autobot-slm-backend/tests/api/_real_orm_import.py index bb63adfe35..ca5c6fb274 100644 --- a/autobot-slm-backend/tests/api/_real_orm_import.py +++ b/autobot-slm-backend/tests/api/_real_orm_import.py @@ -145,8 +145,9 @@ def import_modules_with_real_orm(import_names: tuple, path_loaded: dict | None = try: with real_modules_swapped(): loaded = [load_real_module(name, path) for name, path in path_loaded.items()] - for name in import_names: + for name in import_names: # all evicted first: a name imported by an earlier one is bound once, not twice sys.modules.pop(name, None) + for name in import_names: loaded.append(importlib.import_module(name)) return tuple(loaded) finally: @@ -191,6 +192,69 @@ def _evict_stub_built_modules(exclude: tuple) -> dict: continue if any(isinstance(v, NonCallableMock) and id(_mock_root(v)) in stubs for v in vars(mod).values()): evicted[name] = sys.modules.pop(name) + evicted.update(_evict_built_on_another_sqlalchemy(exclude, evicted)) + return evicted + + +_SHARED_ROOTS = ("autobot_shared", "user_management") + + +def _built_on_another_sqlalchemy(mod) -> bool: + """Whether *mod* holds a sqlalchemy name that is not the one ``REAL_MODULES`` carries. + + A module first imported while another test module had its own private copy of sqlalchemy + swapped in (``test_deactivated_user_token_20443``) keeps that copy's ``Column`` and ``Mapped``. + Mixed with the copy used here, a model declares no primary key. + """ + homes = [REAL_MODULES[n] for n in ("sqlalchemy", "sqlalchemy.orm") if n in REAL_MODULES] + for value in vars(mod).values(): + if not str(getattr(value, "__module__", "")).startswith("sqlalchemy"): + continue + for home in homes: + ours = getattr(home, getattr(value, "__name__", ""), value) + if ours is not value: + return True + return False + + +def _derives_from(mod, names: set) -> bool: + """Whether *mod* holds a name defined in, or a class subclassing a class defined in, one of *names*.""" + for value in vars(mod).values(): + if isinstance(value, types.ModuleType): + if value.__name__ in names: + return True + continue + mro = value.__mro__ if isinstance(value, type) else (value,) + if any(getattr(k, "__module__", None) in names for k in mro): + return True + return False + + +def _evict_built_on_another_sqlalchemy(exclude: tuple, already: dict) -> dict: + """Pop, and return, cached shared-model modules bound to a different sqlalchemy copy (see above). + + Taken to a fixed point: a module that only subclasses an evicted ``Base`` (``organization``) holds no + sqlalchemy name itself, yet is bound to the same copy, and must be rebuilt with the rest. + """ + candidates = { + name: mod + for name, mod in sys.modules.items() + if name not in exclude + and name not in already + and name.split(".")[0] in _SHARED_ROOTS + and isinstance(mod, types.ModuleType) + and not hasattr(mod, "__path__") + } + evicted = {n: m for n, m in candidates.items() if _built_on_another_sqlalchemy(m)} + grew = True + while grew: + grew = False + for name, mod in candidates.items(): + if name not in evicted and _derives_from(mod, set(evicted)): + evicted[name] = mod + grew = True + for name in evicted: + sys.modules.pop(name, None) return evicted diff --git a/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py b/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py index 259d9fc2d8..efe7203d3e 100644 --- a/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py +++ b/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py @@ -12,48 +12,44 @@ """ import ast -import importlib import secrets import sys import uuid from pathlib import Path -from unittest.mock import AsyncMock, patch import pytest from autobot_shared.user_management.base_service import TenantContext sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "api")) -from _real_orm_import import real_modules_swapped # noqa: E402 +from _real_orm_import import import_modules_with_real_orm, real_modules_swapped # noqa: E402 _SLM = Path(__file__).resolve().parents[2] + +# This directory's conftest stands in for sqlalchemy and the SLM's ``user_management`` package; the real ones are the +# system under test. The shared helper imports them once, for real, and the references are held for the whole module +# (SQLAlchemy's class registry is weak, so a dropped ``Organization`` would stop ``Role`` resolving it). +_LOADED = import_modules_with_real_orm( + import_names=( + "user_management", + "user_management.models", + "user_management.models.api_key", + "user_management.models.user", + "autobot_shared.user_management.user_service", + "services.main_backend_client", + ) +) +User = _LOADED[3].User +UserService = _LOADED[-2].UserService +main_backend_client = _LOADED[-1] + with real_modules_swapped(): - from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine from sqlalchemy.ext.compiler import compiles - # The conftest stands in for the SLM's ``user_management`` package; the real one is the system under test, so the - # stand-ins are lifted for the import only. The real modules stay in ``sys.modules`` (SQLAlchemy's class registry - # holds weak references, so dropping them lets ``Organization`` be collected and ``Role`` stop resolving it). - _OWN = ("user_management", "autobot_shared.user_management") - _before = set(sys.modules) - with pytest.MonkeyPatch.context() as _mp: - for _k in [k for k in sys.modules if k.startswith(_OWN)]: - _mp.delitem(sys.modules, _k) - for _mod in ("user", "organization", "role", "team", "api_key", "mfa", "sso", "audit"): - importlib.import_module(f"user_management.models.{_mod}") - User = sys.modules["user_management.models.user"].User - UserService = importlib.import_module("autobot_shared.user_management.user_service").UserService - _created = [k for k in sys.modules if k.startswith(_OWN) and ".models" not in k and k not in _before] - # ``_mp`` has put every stand-in back; the services imported above did not exist before, so a restore would keep - # them (bound to a second ``password_epoch``) for the next module. They are dropped through a MonkeyPatch whose - # record is deliberately never undone, which leaves ``sys.modules`` as it was found; only the models stay. - _drop = pytest.MonkeyPatch() - for _k in _created: - _drop.delitem(sys.modules, _k, raising=False) - - -@compiles(JSONB, "sqlite") + +# the JSONB class the models were declared with (a second import of the dialect would be a different class) +@compiles(type(User.metadata.tables["organizations"].c.settings.type), "sqlite") def _jsonb_as_json(element, compiler, **kw): # noqa: ANN001 return "JSON" @@ -94,25 +90,34 @@ async def _seed_admin(db): return svc +@pytest.fixture() +def main_app_down(monkeypatch): + """The SLM's one client for the main app, made to fail; ``awaited`` records every call that reaches it.""" + awaited = [] + + async def _down(*args, **kwargs): + awaited.append((args, kwargs)) + raise ConnectionError("main app unreachable") + + monkeypatch.setattr(main_backend_client, "call_main_backend", _down) + return awaited + + @pytest.mark.asyncio -async def test_login_works_from_the_local_copy_with_the_main_app_unreachable(session): +async def test_login_works_from_the_local_copy_with_the_main_app_unreachable(session, main_app_down): svc = await _seed_admin(session) - down = AsyncMock(side_effect=ConnectionError("main app unreachable")) - with patch("services.main_backend_client.call_main_backend", down): - user = await svc.authenticate("admin", _PASSWORD) - by_email = await svc.authenticate("admin@example.test", _PASSWORD) + user = await svc.authenticate("admin", _PASSWORD) + by_email = await svc.authenticate("admin@example.test", _PASSWORD) assert user is not None and user.username == "admin" and user.is_platform_admin assert by_email is not None and by_email.id == user.id - down.assert_not_awaited() + assert main_app_down == [] @pytest.mark.asyncio -async def test_a_wrong_password_is_refused_not_an_error_with_the_main_app_unreachable(session): +async def test_a_wrong_password_is_refused_not_an_error_with_the_main_app_unreachable(session, main_app_down): svc = await _seed_admin(session) - down = AsyncMock(side_effect=ConnectionError("main app unreachable")) - with patch("services.main_backend_client.call_main_backend", down): - assert await svc.authenticate("admin", _PASSWORD + "x") is None - down.assert_not_awaited() + assert await svc.authenticate("admin", _PASSWORD + "x") is None + assert main_app_down == [] _LOGIN_PATH = ( From fa080fb6133723d70059a013b9ef78acb2982187 Mon Sep 17 00:00:00 2001 From: mrveiss Date: Sun, 8 Nov 2026 19:43:34 +0200 Subject: [PATCH 6/6] test(slm): guard every login-path module against main-app imports (#21153) --- .../services/test_slm_login_standalone_21153.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py b/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py index efe7203d3e..3614b60443 100644 --- a/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py +++ b/autobot-slm-backend/tests/services/test_slm_login_standalone_21153.py @@ -126,6 +126,23 @@ async def test_a_wrong_password_is_refused_not_an_error_with_the_main_app_unreac "services/auth.py", "services/token_denylist.py", "user_management/services/__init__.py", + # the shared user service ``authenticate`` runs: the class, its two mixins, the base and what they import + *( + f"../autobot_shared/user_management/{m}.py" + for m in ( + "user_service", + "user_service_access", + "user_service_base", + "user_service_lifecycle", + "user_service_conflict", + "user_service_errors", + "login_eligibility", + "audit_rows", + "grant_scope", + "role_permission_query", + ) + ), + "../autobot_shared/auth/jwt_core.py", ) _FORBIDDEN = ("main_backend_client", "httpx", "aiohttp", "requests", "urllib3")