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
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
52e95a9d3a
commit
6df1f88298
@@ -93,6 +93,14 @@ def disable_provider(provider_id: uuid.UUID, request: Request, db: Session = Dep
|
||||
return out
|
||||
|
||||
|
||||
@router.delete("/{provider_id}")
|
||||
def delete_provider(provider_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_administrator)) -> dict:
|
||||
service.delete(db, admin, provider_id, ip=client_ip(request))
|
||||
db.commit()
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@router.post("/{provider_id}/refresh")
|
||||
async def refresh_provider(provider_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_administrator)) -> dict:
|
||||
|
||||
@@ -118,6 +118,12 @@ def disable(db: DbSession, actor: AppUser, provider_id: uuid.UUID, *, ip: str |
|
||||
return out(provider)
|
||||
|
||||
|
||||
def delete(db: DbSession, actor: AppUser, provider_id: uuid.UUID, *, ip: str | None) -> None:
|
||||
"""Core's `delete_unused`: only a disabled provider no run points at (409 otherwise)."""
|
||||
provider = core.get_or_404(db, provider_id)
|
||||
core.delete_unused(db, actor=actor, provider=provider, ip=ip)
|
||||
|
||||
|
||||
def policy_out(db: DbSession) -> dict:
|
||||
return {"level": core.policy(db), "eu_only": core.eu_only(db), "levels": list(core.POLICIES),
|
||||
"kinds": list(core.KINDS), "dialects": list(core.DIALECTS),
|
||||
|
||||
@@ -56,7 +56,7 @@
|
||||
# v0.21.0 adds the counterparty register: the three shared tables the hub creates and grants in its
|
||||
# identity schema (`alembic/versions/0012_counterparties.py`, re-applied by `app.identity_grants`),
|
||||
# and the import door modules move their own counterparties in through. The hub holds no tier on them.
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.23.1
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.23.2
|
||||
|
||||
# Web framework
|
||||
fastapi==0.115.6
|
||||
|
||||
@@ -84,6 +84,13 @@ def test_each_row_offers_refresh_details_and_disable(screen):
|
||||
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]
|
||||
|
||||
@@ -5,8 +5,8 @@ Opt in with ATRIUM_RUN_INTEGRATION=1, like `test_integration.py`. The tables exi
|
||||
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).
|
||||
|
||||
Providers are never deleted (only disabled), so every name is suffixed per run, and the policy is put
|
||||
back exactly as it was found.
|
||||
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
|
||||
|
||||
@@ -68,6 +68,7 @@ def test_only_an_administrator_reaches_any_of_it(admin_client, client, make_user
|
||||
("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)
|
||||
@@ -79,6 +80,7 @@ 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():
|
||||
@@ -210,13 +212,39 @@ def test_disable_switches_off_and_is_audited_once(admin_client):
|
||||
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 admin_client.delete(f"{BASE}/{pid}").status_code == 405 # there is no delete
|
||||
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})
|
||||
|
||||
+17
-3
@@ -764,7 +764,9 @@ const I18N = {
|
||||
'Pozostaw puste, aby zachować obecny klucz': 'Leave empty to keep the current key',
|
||||
'Klucz jest tylko do zapisu: nikt, także administrator, nie zobaczy go ponownie.': 'The key is write-only: nobody, the administrator included, sees it again.',
|
||||
'Ten serwer nie ma ustawionego MODEL_PROVIDER_SECRET, więc nie może zapisać klucza API.': 'This server has no MODEL_PROVIDER_SECRET, so it cannot store an API key.',
|
||||
'Obowiązuje we wszystkich modułach. Dostawcę można tylko wyłączyć, nie usunąć: przebiegi pamiętają, kto je policzył.': 'Applies in every module. A provider can only be disabled, never deleted: runs remember which one computed them.',
|
||||
'Obowiązuje we wszystkich modułach. Wyłączonego dostawcę można usunąć, dopóki nie policzył żadnego przebiegu; potem zostaje na liście, bo przebiegi pamiętają, kto je policzył.': 'Applies in every module. A disabled provider can be deleted as long as it has computed no run; after that it stays on the list, because runs remember which one computed them.',
|
||||
'Usunąć tego dostawcę razem z jego kluczami? Tego nie da się cofnąć.': 'Delete this provider together with its keys? This cannot be undone.',
|
||||
'Usunięto.': 'Deleted.',
|
||||
'Wyłączyć tego dostawcę? Moduły przestaną go oferować.': 'Disable this provider? Modules stop offering it.',
|
||||
'Usunąć zapisany klucz API tego dostawcy?': 'Remove the stored API key of this provider?',
|
||||
'Dodaj dostawcę': 'Add provider',
|
||||
@@ -5939,7 +5941,7 @@ async function viewAdminProviders(C) {
|
||||
setCrumb([{ label: 'Ustawienia' }, { label: 'Dostawcy modeli' }]);
|
||||
C.innerHTML = pageHead('Dostawcy modeli', '',
|
||||
`<button class="btn primary" onclick="openAddProvider()">${svg(ICN.plus)}<span>Dodaj dostawcę</span></button>`)
|
||||
+ `<div class="faint tiny" style="margin-bottom:10px">Obowiązuje we wszystkich modułach. Dostawcę można tylko wyłączyć, nie usunąć: przebiegi pamiętają, kto je policzył.</div>`
|
||||
+ `<div class="faint tiny" style="margin-bottom:10px">Obowiązuje we wszystkich modułach. Wyłączonego dostawcę można usunąć, dopóki nie policzył żadnego przebiegu; potem zostaje na liście, bo przebiegi pamiętają, kto je policzył.</div>`
|
||||
+ `<div class="card"><h3>Polityka użycia</h3><div class="stack">
|
||||
<label class="field">Kto może używać modeli${choice('ppLevel', PROVIDER_LEVEL, policy.level)}</label>
|
||||
<label class="check"><input type="checkbox" id="ppEu" ${policy.eu_only ? 'checked' : ''} /> <span>Tylko dostawcy z UE/EOG (lub lokalni)</span></label>
|
||||
@@ -5959,7 +5961,8 @@ async function viewAdminProviders(C) {
|
||||
<button class="btn sm" data-pid="${esc(p.id)}" onclick="openProviderForm(this.dataset.pid)">Szczegóły</button>
|
||||
${p.is_active
|
||||
? `<button class="btn sm danger" data-pid="${esc(p.id)}" onclick="disableProvider(this.dataset.pid)">Wyłącz</button>`
|
||||
: `<button class="btn sm" data-pid="${esc(p.id)}" onclick="enableProvider(this.dataset.pid)">Włącz</button>`}
|
||||
: `<button class="btn sm" data-pid="${esc(p.id)}" onclick="enableProvider(this.dataset.pid)">Włącz</button>
|
||||
<button class="btn sm danger" data-pid="${esc(p.id)}" onclick="deleteProvider(this.dataset.pid)">Usuń</button>`}
|
||||
</div></td>
|
||||
</tr>`).join('')}</tbody></table></div></div>` : '<div class="empty">Brak dostawców modeli.</div>');
|
||||
}
|
||||
@@ -6101,6 +6104,17 @@ function confirmDisableProvider(id) {
|
||||
mutate('POST', `/admin/model-providers/${enc(id)}/disable`);
|
||||
}
|
||||
|
||||
// Only a disabled provider offers this; one that has computed a run is refused by core (409, its sentence).
|
||||
function deleteProvider(id) {
|
||||
modal('Usuń', '', '<div class="banner warn">Usunąć tego dostawcę razem z jego kluczami? Tego nie da się cofnąć.</div>',
|
||||
`<button class="btn" onclick="closeModal()">Anuluj</button>
|
||||
<button class="btn danger" data-pid="${esc(id)}" onclick="confirmDeleteProvider(this.dataset.pid)">Usuń</button>`);
|
||||
}
|
||||
|
||||
function confirmDeleteProvider(id) {
|
||||
mutate('DELETE', '/admin/model-providers/' + enc(id), undefined, { done: 'Usunięto.' });
|
||||
}
|
||||
|
||||
function refreshProvider(id) {
|
||||
mutate('POST', `/admin/model-providers/${enc(id)}/refresh`, undefined, { done: 'Odświeżono modele.' });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user