Files
Atrium/backend/tests/test_providers_integration.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

340 lines
17 KiB
Python

"""Model-provider administration against a real, migrated database, as the runtime role.
Opt in with ATRIUM_RUN_INTEGRATION=1, like `test_integration.py`. The tables exist in both shapes
(revision 0009: the shared identity schema on a platform, Atrium's own standalone), and the code is
the same; run it with IDENTITY_SCHEMA set to exercise the hub's writer grant on `dredd`.
`MODEL_PROVIDER_SECRET` must be set for the key tests (they are skipped otherwise).
Only a disabled provider no run points at may be deleted, and most tests leave theirs behind, so every
name is suffixed per run, and the policy is put back exactly as it was found.
"""
from __future__ import annotations
import importlib.util
import uuid
from pathlib import Path
import pytest
from conftest import ADMIN_EMAIL, ADMIN_PASSWORD, bearer, integration
from app.config import get_settings
pytestmark = integration
RUN = uuid.uuid4().hex[:8]
BASE = "/api/v1/admin/model-providers"
needs_secret = pytest.mark.skipif(not get_settings().model_provider_secret,
reason="MODEL_PROVIDER_SECRET is not set")
_ARBITER = (Path(__file__).resolve().parents[2] / "deploy" / "modules" / "arbiter" / "apps"
/ "arbiter" / "backend" / "app" / "provider_keys.py")
def _body(**over) -> dict:
return {"name": f"Provider {RUN} {uuid.uuid4().hex[:4]}", "kind": "api",
"base_url": "https://api.example.eu/v1/", "trains_on_data": False, "region": "de",
"processor_name": "Example GmbH", "dpa_url": "https://example.eu/dpa",
"models": [{"id": "model-a", "context_window": 32000, "dialect": "openai"}], **over}
def _create(admin_client, **over) -> dict:
r = admin_client.post(BASE, json=_body(**over))
assert r.status_code == 201, r.text
return r.json()
def _audit(admin_client, action: str, entity_id: str) -> list[dict]:
rows = admin_client.get("/api/v1/admin/audit", params={"action": action, "limit": 500}).json()
return [row for row in rows if row.get("entity_id") == entity_id]
@pytest.fixture(scope="module", autouse=True)
def _restore_policy(admin_client):
before = admin_client.get(f"{BASE}/policy").json()
yield
admin_client.put(f"{BASE}/policy", json={"level": before["level"], "eu_only": before["eu_only"]})
def _db():
from app.db import SessionLocal
return SessionLocal()
# ── who may ───────────────────────────────────────────────────────────────────
def test_only_an_administrator_reaches_any_of_it(admin_client, client, make_user):
provider = _create(admin_client)
plain = make_user("providers-plain")
for method, path, body in [
("GET", BASE, None), ("POST", BASE, _body()),
("GET", f"{BASE}/{provider['id']}", None),
("PATCH", f"{BASE}/{provider['id']}", {"name": "x"}),
("POST", f"{BASE}/{provider['id']}/disable", None),
("DELETE", f"{BASE}/{provider['id']}", None),
("GET", f"{BASE}/policy", None), ("PUT", f"{BASE}/policy", {"level": "everyone"})]:
r = client.request(method, path, json=body, headers=bearer(plain["token"]))
assert r.status_code == 403, (method, path, r.status_code)
assert client.get(BASE, headers={"Authorization": "Bearer nope"}).status_code == 401
assert admin_client.get(f"{BASE}/{provider['id']}").json()["is_active"] is True
def test_a_missing_provider_is_404_with_cores_code(admin_client):
r = admin_client.get(f"{BASE}/{uuid.uuid4()}")
assert r.status_code == 404 and r.json()["code"] == "provider_not_found"
assert admin_client.post(f"{BASE}/{uuid.uuid4()}/disable").status_code == 404
assert admin_client.delete(f"{BASE}/{uuid.uuid4()}").status_code == 404
def test_cookie_writes_from_another_site_are_refused():
from fastapi.testclient import TestClient
from app.main import app
browser = TestClient(app) # its own cookie jar, no bearer: a signed-in browser
assert browser.post("/api/v1/auth/login",
json={"email": ADMIN_EMAIL, "password": ADMIN_PASSWORD}).status_code == 200
assert browser.post(BASE, json=_body(), headers={"Sec-Fetch-Site": "same-site"}).status_code == 403
assert browser.put(f"{BASE}/policy", json={"eu_only": True},
headers={"Origin": "http://evil.example.com"}).status_code == 403
r = browser.post(BASE, json=_body(), headers={"Sec-Fetch-Site": "same-origin"})
assert r.status_code == 201, r.text
assert browser.get(BASE, headers={"Sec-Fetch-Site": "cross-site"}).status_code == 200
# ── validation: core's rules, core's codes ────────────────────────────────────
@pytest.mark.parametrize(("over", "code"), [
({"base_url": "ftp://api.example.eu"}, "base_url_invalid"),
({"base_url": "https://user:pw@api.example.eu"}, "base_url_credentials"),
({"base_url": "https://api.example.eu/#x"}, "base_url_fragment"),
({"kind": "local", "base_url": "http://localhost.evil.example:1234"}, "base_url_not_local"),
({"kind": "cloud"}, "kind_unknown"),
({"models": []}, "models_empty"),
({"models": ["model-a"]}, "model_shape"),
({"models": [{"id": " "}]}, "model_id_required"),
({"models": [{"id": "m", "context_window": 0}]}, "model_context_window"),
({"models": [{"id": "m", "dialect": "soap"}]}, "model_dialect"),
({"models": [{"id": "m"}, {"id": "m"}]}, "model_duplicate"),
({"region": "Germany"}, "region_invalid"),
({"allowed_for": "kazdy"}, "policy_unknown"),
({"name": " "}, "name_required"),
])
def test_a_bad_card_is_422_with_cores_code(admin_client, over, code):
r = admin_client.post(BASE, json=_body(**over))
assert r.status_code == 422, r.text
body = r.json()
assert body["code"] == code and body["en"]
assert r.headers["content-type"].startswith("application/problem+json")
def test_update_refusals(admin_client):
provider = _create(admin_client)
other = _create(admin_client)
pid = provider["id"]
for patch, code in [({"kind": "local"}, "kind_fixed"), ({"name": other["name"]}, "name_taken"),
({"clear": ["name"]}, "field_not_clearable"),
({"base_url": "javascript:alert(1)"}, "base_url_invalid")]:
r = admin_client.patch(f"{BASE}/{pid}", json=patch)
assert r.status_code == 422 and r.json()["code"] == code, (patch, r.text)
assert admin_client.post(BASE, json=_body(name=provider["name"])).json()["code"] == "name_taken"
assert admin_client.get(f"{BASE}/{pid}").json() == provider # nothing changed
def test_a_partial_update_and_clearing_by_name(admin_client):
provider = _create(admin_client)
r = admin_client.patch(f"{BASE}/{provider['id']}",
json={"processor_name": "Other GmbH", "clear": ["region", "dpa_url"]})
assert r.status_code == 200, r.text
out = r.json()
assert (out["processor_name"], out["region"], out["dpa_url"]) == ("Other GmbH", None, None)
assert out["base_url"] == "https://api.example.eu/v1" and out["stays_in_the_eu"] is False
assert out["models"] == provider["models"] and out["name"] == provider["name"]
# ── the key: write-only ───────────────────────────────────────────────────────
@needs_secret
def test_the_key_is_write_only_and_compass_reads_it(admin_client):
from dredd_core import model_providers as core
from app.models import ModelProvider
if not _ARBITER.exists():
pytest.skip("the vendored Arbiter checkout is not present")
spec = importlib.util.spec_from_file_location("arbiter_provider_keys", _ARBITER)
arbiter = importlib.util.module_from_spec(spec)
spec.loader.exec_module(arbiter)
secret = get_settings().model_provider_secret
key = f"sk-live-{RUN}-very-secret"
created = _create(admin_client, api_key=key)
pid = created["id"]
assert created["has_key"] is True and created["key_prefix"] == key[:6]
listed = admin_client.get(BASE)
for text in (admin_client.get(f"{BASE}/{pid}").text, listed.text, str(created)):
assert key not in text and "api_key" not in text
def read_back():
with _db() as db:
return core.api_key(db, db.get(ModelProvider, uuid.UUID(pid)),
lambda stored: arbiter.decrypt(stored, secret))
assert read_back() == key
# Leaving the key out keeps it; sending one replaces it; clearing it removes it.
assert admin_client.patch(f"{BASE}/{pid}", json={"name": created["name"] + "!"}).json()["has_key"]
assert read_back() == key
replaced = admin_client.patch(f"{BASE}/{pid}", json={"api_key": "sk-two-" + RUN}).json()
assert replaced["key_prefix"] == "sk-two" and read_back() == "sk-two-" + RUN
assert admin_client.patch(f"{BASE}/{pid}", json={"api_key": " "}).json()["code"] == "api_key_empty"
cleared = admin_client.patch(f"{BASE}/{pid}", json={"clear": ["api_key"]}).json()
assert (cleared["has_key"], cleared["key_prefix"]) == (False, None) and read_back() is None
# The audit says that a key was set or cleared, never what it was.
rows = _audit(admin_client, "model_provider.create", pid) + _audit(
admin_client, "model_provider.update", pid)
assert len(rows) == 4
for row in rows:
assert key not in str(row) and RUN not in str(row.get("diff", {}).get("api_key", ""))
def test_without_the_secret_a_key_is_409_and_a_keyless_write_still_works(admin_client,
monkeypatch):
monkeypatch.setattr(get_settings(), "model_provider_secret", "")
r = admin_client.post(BASE, json=_body(api_key="sk-nowhere"))
assert r.status_code == 409 and r.json()["code"] == "model_provider_secret_missing"
assert admin_client.get(f"{BASE}/policy").json()["keys_writable"] is False
provider = _create(admin_client)
r = admin_client.patch(f"{BASE}/{provider['id']}", json={"api_key": "sk-nowhere"})
assert r.status_code == 409
assert admin_client.get(f"{BASE}/{provider['id']}").json()["has_key"] is False
# ── disable, never delete ─────────────────────────────────────────────────────
def test_disable_switches_off_and_is_audited_once(admin_client):
provider = _create(admin_client)
pid = provider["id"]
for _ in range(2):
r = admin_client.post(f"{BASE}/{pid}/disable")
assert r.status_code == 200 and r.json()["is_active"] is False
assert any(p["id"] == pid for p in admin_client.get(BASE).json()) # still listed
rows = _audit(admin_client, "model_provider.disable", pid)
assert len(rows) == 1 and rows[0]["diff"] == {"is_active": [True, False]}
assert admin_client.patch(f"{BASE}/{pid}", json={"is_active": True}).json()["is_active"] is True
def test_delete_takes_only_a_disabled_provider_and_its_key(admin_client):
provider = _create(admin_client)
pid = provider["id"]
r = admin_client.delete(f"{BASE}/{pid}")
assert r.status_code == 409 and r.json()["code"] == "provider_still_active"
assert admin_client.post(f"{BASE}/{pid}/disable").status_code == 200
assert admin_client.delete(f"{BASE}/{pid}").json() == {"status": "ok"}
assert admin_client.get(f"{BASE}/{pid}").status_code == 404
assert all(p["id"] != pid for p in admin_client.get(BASE).json())
[row] = _audit(admin_client, "model_provider.delete", pid)
assert row["detail"] == provider["name"]
@needs_secret
def test_deleting_a_provider_drops_its_stored_key(admin_client):
provider = _create(admin_client, api_key="sk-delete-me-123456")
pid = provider["id"]
admin_client.post(f"{BASE}/{pid}/disable")
assert admin_client.delete(f"{BASE}/{pid}").status_code == 200
from sqlalchemy import text
from app.db import SessionLocal
with SessionLocal() as db:
assert db.execute(text("SELECT count(*) FROM model_provider_key WHERE provider_id = :p"),
{"p": pid}).scalar() == 0
# ── the policy ────────────────────────────────────────────────────────────────
def test_the_policy_round_trip(admin_client):
r = admin_client.put(f"{BASE}/policy", json={"level": "nobody", "eu_only": False})
assert r.status_code == 200, r.text
assert (r.json()["level"], r.json()["eu_only"]) == ("nobody", False)
assert r.json()["levels"] == ["nobody", "admins_only", "everyone"]
# "nobody" empties what people may USE, never what the administrator may manage.
provider = _create(admin_client)
assert any(p["id"] == provider["id"] for p in admin_client.get(BASE).json())
assert admin_client.get(f"{BASE}/{provider['id']}").status_code == 200
r = admin_client.put(f"{BASE}/policy", json={"level": "everyone"})
assert (r.json()["level"], r.json()["eu_only"]) == ("everyone", False) # partial
bad = admin_client.put(f"{BASE}/policy", json={"level": "kazdy"})
assert bad.status_code == 422 and bad.json()["code"] == "policy_unknown"
rows = admin_client.get("/api/v1/admin/audit",
params={"action": "model_provider.policy", "limit": 5}).json()
assert rows[0]["diff"]["level"] == ["nobody", "everyone"]
# ── whose key: key_mode and a person's own key (dredd-core 0.18.0, revision 0010) ─────────────
def test_key_mode_is_on_the_card_and_checked_by_core(admin_client):
provider = _create(admin_client)
assert provider["key_mode"] == "firm" # the default: every provider keeps the firm's key
assert admin_client.get(f"{BASE}/policy").json()["key_modes"] == ["firm", "user", "none"]
r = admin_client.patch(f"{BASE}/{provider['id']}", json={"key_mode": "user"})
assert r.status_code == 200 and r.json()["key_mode"] == "user"
bad = admin_client.post(BASE, json=_body(key_mode="mine"))
assert bad.status_code == 422 and bad.json()["code"] == "key_mode_unknown"
@needs_secret
def test_a_persons_own_key_round_trip(admin_client, client, make_user):
from app.errors import ConflictError
from app.models import AppUser
from app.services import providers
admin_client.put(f"{BASE}/policy", json={"level": "everyone", "eu_only": False})
model = f"own-{RUN}"
provider = _create(admin_client, key_mode="user",
models=[{"id": model, "context_window": 32000, "dialect": "openai"}])
firm = _create(admin_client)
pid = provider["id"]
person = make_user("own-key")
me = bearer(person["token"])
listed = client.get("/api/v1/me/model-keys", headers=me).json()
mine = next(p for p in listed["providers"] if p["id"] == pid)
assert mine["key_prefix"] is None and listed["keys_writable"] is True
assert all(p["id"] != firm["id"] for p in listed["providers"]) # only `user` providers
def target():
with _db() as db:
return providers.call_target(db, db.get(AppUser, uuid.UUID(person["id"])), model)
# No key yet: the ask is refused with "add your key", before anything is called.
with pytest.raises(ConflictError) as err:
target()
assert err.value.extra["code"] == providers.USER_KEY_MISSING
r = client.post("/api/v1/models/ask", headers=me,
json={"model": model, "messages": [{"role": "user", "content": "hi"}]})
assert r.status_code == 409 and r.json()["code"] == providers.USER_KEY_MISSING
key = f"sk-own-{RUN}-secret"
r = client.put(f"/api/v1/me/model-keys/{pid}", headers=me, json={"api_key": key})
assert r.status_code == 200, r.text
assert r.json()["key_prefix"] == key[:6] and key not in r.text
assert next(p for p in client.get("/api/v1/me/model-keys", headers=me).json()["providers"]
if p["id"] == pid)["key_prefix"] == key[:6]
got = target()
assert (got["key"], got["key_source"]) == (key, "user")
assert key not in admin_client.get(f"{BASE}/{pid}").text # never on the administrator's card
# A firm-key provider takes no personal key, an unknown one neither: 404, never 403.
assert client.put(f"/api/v1/me/model-keys/{firm['id']}", headers=me,
json={"api_key": "sk-x"}).status_code == 404
assert client.put(f"/api/v1/me/model-keys/{uuid.uuid4()}", headers=me,
json={"api_key": "sk-x"}).status_code == 404
assert client.put(f"/api/v1/me/model-keys/{pid}", headers=me,
json={"api_key": " "}).json()["code"] == "api_key_empty"
# The audit says that a key was set, never what it was.
rows = _audit(admin_client, "model_provider.user_key", pid)
assert rows and all(key not in str(row) for row in rows)
# A new address drops every personal key: the key was given to the old target.
admin_client.patch(f"{BASE}/{pid}", json={"base_url": "https://api2.example.eu/v1"})
with pytest.raises(ConflictError):
target()
client.put(f"/api/v1/me/model-keys/{pid}", headers=me, json={"api_key": key})
r = client.delete(f"/api/v1/me/model-keys/{pid}", headers=me)
assert r.status_code == 200 and r.json()["removed"] is True
assert client.delete(f"/api/v1/me/model-keys/{pid}", headers=me).json()["removed"] is False