Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

test(one-doors): route_rules fixture, create_app ratchet, authz one-liners (plan 77 G3/G4)

Juan Denisb07b9882619e
diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py
index 49999869..f52da7cd 100644
--- a/backend/tests/conftest.py
+++ b/backend/tests/conftest.py
@@ -282,6 +282,17 @@ def auth_headers(app):
from factories import make_user, headers_for # noqa: E402
[email protected](scope='session')
+def route_rules(_flask_app):
+ """Frozen URL rules of the session app (plan 77 G3).
+
+ Tests that only need to check "does route X exist" read THIS instead of
+ booting a second app with create_app() — every extra boot re-exposes the
+ state-leak classes documented on _flask_app and costs ~seconds.
+ """
+ return sorted(r.rule for r in _flask_app.url_map.iter_rules())
+
+
@pytest.fixture
def developer_headers(app):
"""JWT headers for a plain developer-role user."""
diff --git a/backend/tests/factories.py b/backend/tests/factories.py
index 1239cd71..98d17864 100644
--- a/backend/tests/factories.py
+++ b/backend/tests/factories.py
@@ -91,3 +91,35 @@ def make_server(db, name='box1', **overrides):
db.session.add(row)
db.session.commit()
return row
+
+
+# ---------------------------------------------------------------------------
+# Authz one-liners (plan 77 G4) — the per-endpoint 401/403 micro-test shapes,
+# promoted from test_raw_infra_authz.py so new endpoint tests are one line.
+# ---------------------------------------------------------------------------
+
+def assert_requires_auth(client, method, url, body=None, expected=401):
+ """No token -> 401 (or ``expected``). Returns the response."""
+ kwargs = {'json': body} if body is not None else {}
+ resp = getattr(client, method.lower())(url, **kwargs)
+ assert resp.status_code == expected, (
+ f'{method.upper()} {url} without auth returned {resp.status_code}, '
+ f'expected {expected}')
+ return resp
+
+
+def assert_admin_only(client, personas, method, url, body=None, ok_status=200,
+ non_admin=('owner', 'member', 'viewer', 'foreign')):
+ """Every non-admin persona is 403; the admin passes the gate.
+
+ ``personas`` is a scoping_rbac-style namespace of per-persona auth
+ headers (see conftest.scoping_rbac).
+ """
+ kwargs = {'json': body} if body is not None else {}
+ for persona in non_admin:
+ resp = getattr(client, method.lower())(url, headers=getattr(personas, persona), **kwargs)
+ assert resp.status_code == 403, f'{persona} reached {method.upper()} {url}'
+ resp = getattr(client, method.lower())(url, headers=personas.admin, **kwargs)
+ assert resp.status_code == ok_status, (
+ f'admin denied {method.upper()} {url}: {resp.status_code}')
+ return resp
diff --git a/backend/tests/test_config_checkpoint_alias.py b/backend/tests/test_config_checkpoint_alias.py
index c625b02b..3754bf9f 100644
--- a/backend/tests/test_config_checkpoint_alias.py
+++ b/backend/tests/test_config_checkpoint_alias.py
@@ -17,9 +17,7 @@ def test_config_checkpoints_resolves_same_handler(app, client, auth_headers):
assert ckpts.get_json() == snaps.get_json()
-def test_both_route_spaces_registered():
- from app import create_app
- application = create_app('testing')
- rules = {r.rule for r in application.url_map.iter_rules()}
- assert any('/snapshots' in r for r in rules)
- assert any('/config-checkpoints' in r for r in rules)
+def test_both_route_spaces_registered(route_rules):
+ # route_rules is the session app's url_map (plan 77 G3) — no second boot.
+ assert any('/snapshots' in r for r in route_rules)
+ assert any('/config-checkpoints' in r for r in route_rules)
diff --git a/backend/tests/test_fixture_scope_guard.py b/backend/tests/test_fixture_scope_guard.py
index e2f8ba81..51870c91 100644
--- a/backend/tests/test_fixture_scope_guard.py
+++ b/backend/tests/test_fixture_scope_guard.py
@@ -51,3 +51,49 @@ def test_app_fixture_stays_function_scoped(request):
"`app` is %r-scoped; it must be 'function' so each test gets a clean "
"database." % (defs[-1].scope,)
)
+
+
+# ---------------------------------------------------------------------------
+# Plan 77 G3 — direct create_app() in test modules is a frozen population.
+# ---------------------------------------------------------------------------
+
+# Files that booted their own app before the session-scoped fixture landed
+# (plan 64). Each extra boot re-exposes the state-leak classes documented on
+# `_flask_app` and costs seconds. New tests use the `app` fixture, the
+# session `route_rules` fixture (for url_map checks), or — when a different
+# config is genuinely needed — a documented fresh-app fixture in the module.
+# Shrinking this list is progress; do not add to it.
+CREATE_APP_BASELINE = {
+ 'test_agent_poll_e2e.py',
+ 'test_ai_lazy_import.py',
+ 'test_api_error_shape.py',
+ 'test_enhancements_integration.py',
+ 'test_fleet_proxy.py',
+ 'test_health_staging.py',
+ 'test_login_bruteforce.py',
+ 'test_no_background_threads.py',
+ 'test_observability_namespace.py',
+ 'test_proxy_stack.py',
+ 'test_services_alias.py',
+ 'test_ssl_unified_surface.py',
+ 'test_trusted_client_ip.py',
+}
+
+
+def test_no_new_direct_create_app_callers():
+ import re
+ from pathlib import Path
+ tests_dir = Path(__file__).resolve().parent
+ found = set()
+ for f in sorted(tests_dir.glob('test_*.py')):
+ if f.name == Path(__file__).name:
+ continue
+ if re.search(r'\bcreate_app\(', f.read_text(encoding='utf-8', errors='replace')):
+ found.add(f.name)
+ new = found - CREATE_APP_BASELINE
+ assert not new, (
+ f'New test files booting their own app: {sorted(new)}. Use the `app` '
+ 'fixture, `route_rules`, or a documented fresh-app fixture (plan 77 G3).'
+ )
+ stale = CREATE_APP_BASELINE - found
+ assert not stale, f'Migrated files still in the baseline: {sorted(stale)} — delete them.'
diff --git a/backend/tests/test_raw_infra_authz.py b/backend/tests/test_raw_infra_authz.py
index fd29dd7c..e0990662 100644
--- a/backend/tests/test_raw_infra_authz.py
+++ b/backend/tests/test_raw_infra_authz.py
@@ -22,18 +22,9 @@ import pytest
from app.services.database_service import DatabaseService
from app.services.docker_service import DockerService
-NON_ADMIN = ('owner', 'member', 'viewer', 'foreign')
-
-
-def _assert_admin_only(client, s, method, url, body=None):
- """Every non-admin persona is 403; the admin passes the gate (the mocked
- service layer answers 200)."""
- kwargs = {'json': body} if body is not None else {}
- for persona in NON_ADMIN:
- resp = getattr(client, method)(url, headers=getattr(s, persona), **kwargs)
- assert resp.status_code == 403, f'{persona} reached {url}'
- resp = getattr(client, method)(url, headers=s.admin, **kwargs)
- assert resp.status_code == 200, f'admin denied {url}: {resp.get_json()}'
+# Promoted to a shared one-liner (plan 77 G4); kept as a local alias so the
+# call sites below read the same.
+from factories import assert_admin_only as _assert_admin_only # noqa: E402
# --------------------------------------------------------------------------- #