Files
Atrium/backend/tests/test_providers_console.py
T
tobayahandClaude Opus 5.5 8bc639c7ae Providers: a disabled provider that computed no run can be deleted
An API key that expires after a day left its provider on the list for good. DELETE /admin/model-providers/{id} binds dredd-core 0.23.2's delete_unused: refused while active (409 provider_still_active) and once any run points at it (409 provider_in_use). The console offers Usuń on a disabled row. No revision: atrium-migrate re-applies the provider grants, which now give the hub DELETE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uwxqKuxvGXDvtwWKrBWYR
2026-11-18 16:50:29 +01:00

240 lines
12 KiB
Python

"""The model-provider screen in the console (Platforma → Dostawcy modeli). DB-free.
Source-reading, like `test_app_token_console.py`, and honest about what that proves: the screen
exists, calls only routes that exist, never renders or stores a key, never reaches a provider
itself (the model list comes through the hub's `discover`/`refresh`), and is in both languages. That the routes really behave is
`test_providers_integration.py`'s job.
"""
from __future__ import annotations
import pathlib
import re
import pytest
ROOT = pathlib.Path(__file__).resolve().parents[2]
@pytest.fixture(scope="module")
def console() -> str:
return (ROOT / "frontend" / "app.js").read_text(encoding="utf-8")
@pytest.fixture(scope="module")
def screen(console) -> str:
start = "/* ── administration: model providers"
end = "/* ── administration: audit log"
assert start in console and end in console
return console.split(start, 1)[1].split(end, 1)[0]
def _i18n(console: str) -> set[str]:
block = console.split("const I18N = {", 1)[1].split("\n};", 1)[0]
return set(re.findall(r"^ '((?:[^'\\]|\\.)*)': '(?:[^'\\]|\\.)*',$", block, re.M))
def test_the_screen_is_routed_and_administrator_only(console):
assert "async function viewAdminProviders(" in console
assert "if (page === 'providers') return viewAdminProviders(C);" in console
settings = console.split("const SETTINGS_NAV = [", 1)[1].split("];", 1)[0]
line = next(ln for ln in settings.splitlines() if "'#/admin/providers'" in ln)
assert "admin: true" in line, "an administrator's entry under Ustawienia"
nav = console.split("const NAV = [", 1)[1].split("];", 1)[0]
assert "providers" not in nav
def test_it_calls_only_routes_that_exist(screen):
router = (ROOT / "backend" / "app" / "routers" / "admin_providers.py").read_text(encoding="utf-8")
prefix = re.search(r'prefix="([^"]+)"', router).group(1)
declared = {prefix + p for p in re.findall(r'@router[.][a-z]+[(]"([^"]*)"', router)}
called = set(re.findall(r"'(/admin/model-providers[^']*)'", screen))
called |= {c.replace("${enc(id)}", "{provider_id}")
for c in re.findall(r"`(/admin/model-providers[^`]*)`", screen)}
called = {c + "{provider_id}" if c.endswith("/") else c for c in called}
assert called and called <= declared, called - declared
def test_the_key_is_write_only_in_the_console_too(screen):
assert 'id="pfKey" type="password"' in screen
assert 'autocomplete="new-password"' in screen
assert "Pozostaw puste, aby zachować obecny klucz" in screen
# Nothing reads a key off a response, and nothing keeps one.
assert not re.search(r"\b(?:p|v|x|row|result)\.api_key", screen)
assert "localStorage" not in screen and "sessionStorage" not in screen
# Only a typed key is sent; removing one is its own action, by name.
assert "if (key) body.api_key = key;" in screen
assert "{ clear: ['api_key'] }" in screen
def test_only_the_hub_reaches_a_provider(screen):
"""The list of models is read by the hub, under its outbound limits; the console only asks for
it through `discover`/`refresh` and never opens a connection of its own."""
assert "fetch(" not in screen
assert "XMLHttpRequest" not in screen
assert "`/admin/model-providers/${enc(id)}/refresh`" in screen
code = re.sub(r"/\*.*?\*/", "", screen, flags=re.S)
assert not re.search(r"test.?connection|probe|połącz", code, re.I)
def test_each_row_offers_refresh_details_and_disable(screen):
rows = screen.split("rows.map((p) =>", 1)[1].split(".join('')", 1)[0]
assert "providerIcon(p)" in rows
assert "(p.models || []).length" in rows
for action in ("refreshProvider(", "openProviderForm(", "disableProvider("):
assert action in rows, action
def test_only_a_disabled_row_offers_delete(screen):
rows = screen.split("rows.map((p) =>", 1)[1].split(".join('')", 1)[0]
active, disabled = rows.split("disableProvider(", 1)[1].split(": `", 1)
assert "deleteProvider(" not in active and "deleteProvider(" in disabled
assert "mutate('DELETE', '/admin/model-providers/' + enc(id)" in screen
def test_details_have_no_models_field(screen):
"""A provider's models are its own list (`discover`/`refresh`), never typed."""
form = screen.split("function openProviderForm(", 1)[1].split("\n}\n", 1)[0]
assert "Modele" not in form and "textarea" not in form
edit = screen.split("function readProviderForm(", 1)[1].split("\n}\n", 1)[0]
assert "models" not in edit
def test_adding_goes_through_discover(console, screen):
"""One field; the hub recognises it (`discover`), the console adds what was checked."""
assert 'onclick="openAddProvider()"' in screen
assert "'/admin/model-providers/discover'" in screen
assert "reopen: showDiscovered" in screen
add = screen.split("function addProvider(", 1)[1].split("\n}\n", 1)[0]
assert "mutate('POST', '/admin/model-providers', body)" in add
assert "models: r.models" in add and "kind: r.kind" in add and "base_url: r.base_url" in add
# The second field shows only for an address.
assert 'id="apKeyRow"' in screen and 'id="apKey" type="password"' in screen
# The prefix catalogue is the backend's alone.
assert "sk-ant-" not in console and "sk-or-" not in console
def test_the_pasted_key_is_never_rendered_or_kept(screen):
preview = screen.split("function showDiscovered(", 1)[1].split("\n}\n", 1)[0]
assert "apInput" not in preview and "apKey" not in preview and "key" not in preview.lower()
add = screen.split("function addProvider(", 1)[1].split("\n}\n", 1)[0]
assert "state." not in add.split("const r = state._discovered;", 1)[1]
assert not re.search(r"state[.]\w+\s*=\s*(?:key|input)", screen)
def test_dynamic_values_are_escaped(screen):
# Every interpolation goes through esc()/dat()/enc() or is markup built here.
for expr in re.findall(r"\$\{([^}]*)\}", screen):
if expr.strip().startswith(("esc(", "dat(", "enc(", "svg(", "lbl(", "choice(", "providerIcon(", "markSvg(",
"hue", "writable", "rows.map",
"p.is_active", "p.trains_on_data", "p.has_key",
"policy.eu_only", "r.models.map", "esc(")):
continue
pytest.fail(f"unescaped interpolation: ${{{expr}}}")
def test_the_look_is_marked_as_replaceable(screen):
assert "Tobiasz" in screen
@pytest.mark.parametrize("phrase", [
"Dostawcy modeli", "Szczegóły", "Polityka użycia", "Kto może używać modeli",
"Tylko dostawcy z UE/EOG (lub lokalni)", "Zapisz politykę", "Brak dostawców modeli.",
"Pozostaw puste, aby zachować obecny klucz", "Usuń klucz", "Wyłącz", "Włącz", "Nikt",
"Tylko administratorzy", "Każdy", "Zgodnie z polityką", "Dostawca trenuje modele na przesłanych danych",
"Klucz jest tylko do zapisu: nikt, także administrator, nie zobaczy go ponownie.",
"Ten serwer nie ma ustawionego MODEL_PROVIDER_SECRET, więc nie może zapisać klucza API.",
"Usunąć zapisany klucz API tego dostawcy?",
"Wyłączyć tego dostawcę? Moduły przestaną go oferować.",
"API (zewnętrzny)", "lokalny", "Podmiot przetwarzający", "Adres umowy powierzenia (DPA)",
"Dodaj dostawcę", "Wklej klucz API albo adres serwera", "Klucz (jeśli serwer go wymaga)", "Sprawdź",
"Dodaj", "Znaleziono modele.", "Odśwież modele", "Odświeżono modele.",
])
def test_it_is_in_both_languages(console, screen, phrase):
assert phrase in screen
assert phrase in _i18n(console), f"no English for {phrase!r}"
def test_cores_english_sentence_is_used_in_english(console):
"""Core's refusals carry `detail` in Polish and `en` in English next to a stable `code`; the
console's source language is Polish, so EN readers get core's own sentence."""
api = console.split("async function api(", 1)[1].split("\n}\n", 1)[0]
assert "coreRefusal(data)" in api
body = console.split("function coreRefusal(", 1)[1].split("\n}\n", 1)[0]
assert "problem.en" in body and "LANG === SRC_LANG" in body
# ── whose key (dredd-core 0.18.0) ────────────────────────────────────────────
@pytest.fixture(scope="module")
def my_keys(console) -> str:
start = "/* ── my model keys"
end = "/* ── administration: overview"
assert start in console and end in console
return console.split(start, 1)[1].split(end, 1)[0]
def test_the_admin_card_shows_and_edits_key_mode(screen):
assert "const KEY_MODE = { firm:" in screen and "user:" in screen and "none:" in screen
assert "choice('pfKeyMode', KEY_MODE, p.key_mode || 'firm')" in screen
assert "key_mode: $('pfKeyMode').value" in screen
assert "KEY_MODE[p.key_mode]" in screen
def test_my_keys_is_everybodys_routed_screen_calling_only_real_routes(console, my_keys):
settings = console.split("const SETTINGS_NAV = [", 1)[1].split("];", 1)[0]
line = next(ln for ln in settings.splitlines() if "'#/my-keys'" in ln)
assert "admin" not in line
assert "else if (seg[0] === 'my-keys') await viewMyKeys(C);" in console
router = (ROOT / "backend" / "app" / "routers" / "models.py").read_text(encoding="utf-8")
assert '@router.get("/me/model-keys")' in router
assert '@router.put("/me/model-keys/{provider_id}")' in router
assert '@router.delete("/me/model-keys/{provider_id}")' in router
assert set(re.findall(r"'(/me/model-keys[^']*)'", my_keys)) == {"/me/model-keys", "/me/model-keys/"}
# Write-only: a password field, nothing kept, nothing reads a key back.
assert 'id="mkKey" type="password" autocomplete="new-password"' in my_keys
assert "localStorage" not in my_keys and "sessionStorage" not in my_keys
assert not re.search(r"\b(?:p|r|row|result)\.api_key", my_keys)
assert "fetch(" not in my_keys
@pytest.mark.parametrize("phrase", [
"Czyj klucz", "Klucz firmy", "Własny klucz użytkownika", "Bez klucza", "Moje klucze modeli",
"Dostawcy modeli, którzy używają twojego własnego klucza API zamiast klucza firmy.",
"Żaden dostawca nie potrzebuje twojego klucza.", "Dodaj klucz", "Zmień klucz",
"Usunąć twój zapisany klucz API tego dostawcy?",
"Zmiana adresu albo odejście od własnych kluczy użytkowników usuwa wszystkie zapisane klucze użytkowników tego dostawcy.",
])
def test_the_key_mode_strings_are_in_both_languages(console, phrase):
assert phrase in console
assert phrase in _i18n(console), f"no English for {phrase!r}"
def test_home_points_at_my_keys_when_a_personal_key_is_missing(console):
home = console.split("async function viewHome(C) {", 1)[1].split("\nasync function loadHomeStats", 1)[0]
assert '<div id="homeKeys"></div>' in home and "loadHomeKeys();" in home
hint = home.split("async function loadHomeKeys() {", 1)[1]
assert "api('GET', '/me/model-keys')" in hint
assert "!p.key_prefix" in hint and "r.keys_writable" in hint
assert 'href="#/my-keys"' in hint and "esc(p.name)" in hint
# The chat says where to add the key instead of a bare "Nie udało się".
assert "'model_provider_user_key_missing'" in console.split("const CHAT_REFUSALS", 1)[1].split(";", 1)[0]
@pytest.mark.parametrize("code", [
"provider_key_refused", "provider_unreachable", "provider_no_models", "provider_unknown_key",
])
def test_discover_refusals_carry_their_english(code):
"""These refusals are worded by `coreRefusal` from the Problem Details `code` + `en`, not by a
dictionary entry: `provider_unreachable` carries the reason inside its sentence."""
backend = ROOT / "backend" / "app"
src = ((backend / "integrations" / "model_server.py").read_text(encoding="utf-8")
+ (backend / "services" / "providers.py").read_text(encoding="utf-8"))
assert "def _refusal(code: str, pl: str, en: str)" in src and '{"code": code, "en": en}' in src
assert re.search(rf'_refusal\(\s*"{code}"|"code": "{code}",\s*"en": ', src), code
def test_a_provider_the_eu_only_policy_hides_says_so_in_the_list() -> None:
# Core drops a non-EU provider from every model list while `eu_only` is on; the list must not
# call it plainly "aktywny" then, or its models vanish from the chat with no visible reason.
src = (pathlib.Path(__file__).resolve().parents[2] / "frontend" / "app.js").read_text(encoding="utf-8")
assert "policy.eu_only && !p.stays_in_the_eu" in src and "ukryty: tylko UE" in src