Skip to content

Commit 1e088df

Browse files
olivermeyerclaude
andcommitted
refactor(gui): extract _frame_context to reduce cognitive complexity
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent 8833534 commit 1e088df

2 files changed

Lines changed: 176 additions & 9 deletions

File tree

src/aignostics_foundry_core/gui/auth.py

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def dashboard(user: dict) -> None:
4242
import contextlib
4343
import inspect
4444
import time
45-
from collections.abc import Awaitable, Callable
45+
from collections.abc import Awaitable, Callable, Generator
4646
from dataclasses import dataclass
4747
from enum import StrEnum
4848
from typing import Any
@@ -219,6 +219,19 @@ async def require_gui_user(request: Request, return_to: str | None = None) -> di
219219
# ---------------------------------------------------------------------------
220220

221221

222+
@contextlib.contextmanager
223+
def _frame_context(
224+
frame_func: FrameFunc,
225+
title: str,
226+
user: dict[str, Any] | None,
227+
) -> Generator[None, None, None]:
228+
if frame_func is not None:
229+
with frame_func(title, user=user):
230+
yield
231+
else:
232+
yield
233+
234+
222235
def _actualize_public(
223236
path: str,
224237
title: str | None = None,
@@ -238,7 +251,7 @@ def decorator(
238251
async def wrapper(request: Request) -> None:
239252
resolved_title = title if title is not None else get_context().name.title()
240253
user = await get_gui_user(request)
241-
with frame_func(resolved_title, user=user) if frame_func is not None else contextlib.nullcontext():
254+
with _frame_context(frame_func, resolved_title, user):
242255
await _invoke_page_func(func, user)
243256

244257
wrapper.__name__ = func.__name__
@@ -271,7 +284,7 @@ async def wrapper(request: Request) -> None:
271284
user = await require_gui_user(request)
272285
if not user:
273286
return
274-
with frame_func(resolved_title, user=user) if frame_func is not None else contextlib.nullcontext():
287+
with _frame_context(frame_func, resolved_title, user):
275288
await _invoke_page_func(func, user)
276289

277290
wrapper.__name__ = func.__name__
@@ -308,11 +321,11 @@ async def wrapper(request: Request) -> None:
308321
auth_settings = load_settings(AuthSettings)
309322
role = user.get(auth_settings.auth0_role_claim)
310323
if role != AUTH0_ROLE_ADMIN:
311-
with frame_func(resolved_title, user=user) if frame_func is not None else contextlib.nullcontext():
324+
with _frame_context(frame_func, resolved_title, user):
312325
ui.label(f"{MSG_403_FORBIDDEN} - Admin access required").classes(CLASS_FORBIDDEN_ERROR)
313326
return
314327

315-
with frame_func(resolved_title, user=user) if frame_func is not None else contextlib.nullcontext():
328+
with _frame_context(frame_func, resolved_title, user):
316329
await _invoke_page_func(func, user)
317330

318331
wrapper.__name__ = func.__name__
@@ -349,11 +362,11 @@ async def wrapper(request: Request) -> None:
349362
auth_settings = load_settings(AuthSettings)
350363
org_id = user.get("org_id")
351364
if org_id != auth_settings.internal_org_id:
352-
with frame_func(resolved_title, user=user) if frame_func is not None else contextlib.nullcontext():
365+
with _frame_context(frame_func, resolved_title, user):
353366
ui.label(f"{MSG_403_FORBIDDEN} - Internal access required").classes(CLASS_FORBIDDEN_ERROR)
354367
return
355368

356-
with frame_func(resolved_title, user=user) if frame_func is not None else contextlib.nullcontext():
369+
with _frame_context(frame_func, resolved_title, user):
357370
await _invoke_page_func(func, user)
358371

359372
wrapper.__name__ = func.__name__
@@ -392,11 +405,11 @@ async def wrapper(request: Request) -> None:
392405
role = user.get(auth_settings.auth0_role_claim)
393406

394407
if org_id != auth_settings.internal_org_id or role != AUTH0_ROLE_ADMIN:
395-
with frame_func(resolved_title, user=user) if frame_func is not None else contextlib.nullcontext():
408+
with _frame_context(frame_func, resolved_title, user):
396409
ui.label(f"{MSG_403_FORBIDDEN} - Internal admin access required").classes(CLASS_FORBIDDEN_ERROR)
397410
return
398411

399-
with frame_func(resolved_title, user=user) if frame_func is not None else contextlib.nullcontext():
412+
with _frame_context(frame_func, resolved_title, user):
400413
await _invoke_page_func(func, user)
401414

402415
wrapper.__name__ = func.__name__

tests/aignostics_foundry_core/gui/gui_test.py

Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,14 @@
2626

2727
_PATCH_GET_GUI_USER = "aignostics_foundry_core.gui.auth.get_gui_user"
2828
_PATCH_REQUIRE_GUI_USER = "aignostics_foundry_core.gui.auth.require_gui_user"
29+
_PATCH_LOAD_SETTINGS = "aignostics_foundry_core.gui.auth.load_settings"
2930
_PATH_NAV_LOCATE = "aignostics_foundry_core.gui.nav.locate_subclasses"
3031
_PATH_CORE_LOCATE = "aignostics_foundry_core.gui.core.locate_subclasses"
3132

3233
_TEST_PATH = "/test-page"
3334
_OTHER_ORG = "org_other"
35+
_INTERNAL_ORG_ID = "org_internal_test"
36+
_ROLE_CLAIM = "https://example.com/roles"
3437
_FIXED_PORT = 9000
3538
_DOCS_PATH = "/docs"
3639
_USER_SUB = "auth0|x"
@@ -846,6 +849,157 @@ def my_page(user: object) -> None: ...
846849

847850
assert titles_received == ["My Page"]
848851

852+
def test_page_admin_renders_forbidden_when_role_is_missing(self) -> None:
853+
"""Authenticated user without admin role gets a 403 forbidden label."""
854+
from aignostics_foundry_core.gui.auth import page_admin
855+
856+
user = {_ROLE_CLAIM: "other_role"}
857+
fake_auth = MagicMock()
858+
fake_auth.auth0_role_claim = _ROLE_CLAIM
859+
860+
page_admin(_TEST_PATH)(lambda u: None) # pyright: ignore[reportUnknownLambdaType]
861+
wrappers, nicegui_mock = self._actualize_via_register_pages()
862+
863+
with (
864+
patch(_PATCH_REQUIRE_GUI_USER, new=AsyncMock(return_value=user)),
865+
patch(_PATCH_LOAD_SETTINGS, return_value=fake_auth),
866+
):
867+
asyncio.run(wrappers[0](MagicMock())) # type: ignore[arg-type]
868+
869+
nicegui_mock.ui.label.assert_called_once_with("403 Forbidden - Admin access required")
870+
871+
def test_page_admin_invokes_page_func_when_user_is_admin(self) -> None:
872+
"""Authenticated user with admin role triggers the page function."""
873+
from aignostics_foundry_core.gui.auth import page_admin
874+
875+
page_func_called: list[bool] = []
876+
877+
def my_page(user: object) -> None:
878+
page_func_called.append(True)
879+
880+
user = {_ROLE_CLAIM: "admin"}
881+
fake_auth = MagicMock()
882+
fake_auth.auth0_role_claim = _ROLE_CLAIM
883+
884+
page_admin(_TEST_PATH)(my_page)
885+
wrappers, _ = self._actualize_via_register_pages()
886+
887+
with (
888+
patch(_PATCH_REQUIRE_GUI_USER, new=AsyncMock(return_value=user)),
889+
patch(_PATCH_LOAD_SETTINGS, return_value=fake_auth),
890+
):
891+
asyncio.run(wrappers[0](MagicMock())) # type: ignore[arg-type]
892+
893+
assert page_func_called == [True]
894+
895+
def test_page_internal_renders_forbidden_when_org_id_does_not_match(self) -> None:
896+
"""User from a non-internal org gets a 403 forbidden label."""
897+
from aignostics_foundry_core.gui.auth import page_internal
898+
899+
user = {"org_id": _OTHER_ORG}
900+
fake_auth = MagicMock()
901+
fake_auth.internal_org_id = _INTERNAL_ORG_ID
902+
903+
page_internal(_TEST_PATH)(lambda u: None) # pyright: ignore[reportUnknownLambdaType]
904+
wrappers, nicegui_mock = self._actualize_via_register_pages()
905+
906+
with (
907+
patch(_PATCH_REQUIRE_GUI_USER, new=AsyncMock(return_value=user)),
908+
patch(_PATCH_LOAD_SETTINGS, return_value=fake_auth),
909+
):
910+
asyncio.run(wrappers[0](MagicMock())) # type: ignore[arg-type]
911+
912+
nicegui_mock.ui.label.assert_called_once_with("403 Forbidden - Internal access required")
913+
914+
def test_page_internal_invokes_page_func_when_user_is_internal(self) -> None:
915+
"""User from the internal org triggers the page function."""
916+
from aignostics_foundry_core.gui.auth import page_internal
917+
918+
page_func_called: list[bool] = []
919+
920+
def my_page(user: object) -> None:
921+
page_func_called.append(True)
922+
923+
user = {"org_id": _INTERNAL_ORG_ID}
924+
fake_auth = MagicMock()
925+
fake_auth.internal_org_id = _INTERNAL_ORG_ID
926+
927+
page_internal(_TEST_PATH)(my_page)
928+
wrappers, _ = self._actualize_via_register_pages()
929+
930+
with (
931+
patch(_PATCH_REQUIRE_GUI_USER, new=AsyncMock(return_value=user)),
932+
patch(_PATCH_LOAD_SETTINGS, return_value=fake_auth),
933+
):
934+
asyncio.run(wrappers[0](MagicMock())) # type: ignore[arg-type]
935+
936+
assert page_func_called == [True]
937+
938+
def test_page_internal_admin_renders_forbidden_when_only_org_matches(self) -> None:
939+
"""User from internal org but without admin role gets a 403 forbidden label."""
940+
from aignostics_foundry_core.gui.auth import page_internal_admin
941+
942+
user = {"org_id": _INTERNAL_ORG_ID, _ROLE_CLAIM: "other_role"}
943+
fake_auth = MagicMock()
944+
fake_auth.internal_org_id = _INTERNAL_ORG_ID
945+
fake_auth.auth0_role_claim = _ROLE_CLAIM
946+
947+
page_internal_admin(_TEST_PATH)(lambda u: None) # pyright: ignore[reportUnknownLambdaType]
948+
wrappers, nicegui_mock = self._actualize_via_register_pages()
949+
950+
with (
951+
patch(_PATCH_REQUIRE_GUI_USER, new=AsyncMock(return_value=user)),
952+
patch(_PATCH_LOAD_SETTINGS, return_value=fake_auth),
953+
):
954+
asyncio.run(wrappers[0](MagicMock())) # type: ignore[arg-type]
955+
956+
nicegui_mock.ui.label.assert_called_once_with("403 Forbidden - Internal admin access required")
957+
958+
def test_page_internal_admin_renders_forbidden_when_only_role_matches(self) -> None:
959+
"""Admin-role user from a non-internal org gets a 403 forbidden label."""
960+
from aignostics_foundry_core.gui.auth import page_internal_admin
961+
962+
user = {"org_id": _OTHER_ORG, _ROLE_CLAIM: "admin"}
963+
fake_auth = MagicMock()
964+
fake_auth.internal_org_id = _INTERNAL_ORG_ID
965+
fake_auth.auth0_role_claim = _ROLE_CLAIM
966+
967+
page_internal_admin(_TEST_PATH)(lambda u: None) # pyright: ignore[reportUnknownLambdaType]
968+
wrappers, nicegui_mock = self._actualize_via_register_pages()
969+
970+
with (
971+
patch(_PATCH_REQUIRE_GUI_USER, new=AsyncMock(return_value=user)),
972+
patch(_PATCH_LOAD_SETTINGS, return_value=fake_auth),
973+
):
974+
asyncio.run(wrappers[0](MagicMock())) # type: ignore[arg-type]
975+
976+
nicegui_mock.ui.label.assert_called_once_with("403 Forbidden - Internal admin access required")
977+
978+
def test_page_internal_admin_invokes_page_func_when_user_is_internal_admin(self) -> None:
979+
"""User from internal org with admin role triggers the page function."""
980+
from aignostics_foundry_core.gui.auth import page_internal_admin
981+
982+
page_func_called: list[bool] = []
983+
984+
def my_page(user: object) -> None:
985+
page_func_called.append(True)
986+
987+
user = {"org_id": _INTERNAL_ORG_ID, _ROLE_CLAIM: "admin"}
988+
fake_auth = MagicMock()
989+
fake_auth.internal_org_id = _INTERNAL_ORG_ID
990+
fake_auth.auth0_role_claim = _ROLE_CLAIM
991+
992+
page_internal_admin(_TEST_PATH)(my_page)
993+
wrappers, _ = self._actualize_via_register_pages()
994+
995+
with (
996+
patch(_PATCH_REQUIRE_GUI_USER, new=AsyncMock(return_value=user)),
997+
patch(_PATCH_LOAD_SETTINGS, return_value=fake_auth),
998+
):
999+
asyncio.run(wrappers[0](MagicMock())) # type: ignore[arg-type]
1000+
1001+
assert page_func_called == [True]
1002+
8491003

8501004
# ---------------------------------------------------------------------------
8511005
# GUINamespace

0 commit comments

Comments
 (0)