Compare commits

...
5 Commits
Author SHA1 Message Date
adminandClaude Opus 5.5 2d8ab6ccb6 Submodules: point at the Gitea repositories
The GitHub repositories are gone with the suspended account (or are
mirrored on Gitea). Relative URLs (../<repo>.git) resolve against wherever
this repository is cloned from.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 16:37:52 +01:00
adminandClaude Opus 5.5 841ab09084 Submodules: point at the Gitea repositories
The GitHub repositories are gone with the suspended account (or are
mirrored on Gitea). Relative URLs (../<repo>.git) resolve against wherever
this repository is cloned from.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 16:36:31 +01:00
tobayahandClaude Opus 5.5 61dc63aabb Personal keys: English texts for the new screens; the personal-keys chip beside the status
Found in a browser run (Edge, EN): the My keys screen and the new dialogs stayed half Polish, and the chip sat in the monospaced model-count column.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Claude-Session: https://claude.ai/code/session_016uwxqGRpAezXG78YwnHRka
2026-11-07 00:56:03 +01:00
tobayahandClaude Opus 5.5 21b3195712 Personal keys: add a provider and its admin key in one transaction; refresh without the usage filter
Found by review of the previous commit. Adding a provider with personal keys sent two requests: the
provider was committed, then storing the administrator's key could be refused by the usage filter
(only EU/EEA with no region yet), leaving a provider without a key and its name taken. Now the
console sends one request and services.create stores the pasted key as the administrator's own in
the same transaction; a refusal undoes both (409 model_provider_not_usable).

refresh had moved onto key_for, which applies the usage filter, so an administrator could no longer
refresh a disabled or EU-hidden provider. It now reads the firm key with core's api_key and, for a
personal-key provider, the administrator's own stored key, as before the change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uwxqGRpAezXG78YwnHRka
2026-11-06 23:02:33 +01:00
tobayahandClaude Opus 5.5 e5fb3b80c1 Personal API keys per provider (dredd-core 0.18.0)
An administrator can switch a provider to "every person uses their own key" (key_mode user). Each
person then pastes their key under Settings > My keys, and Home's chat calls that provider with the
asker's own key. Firm keys keep working as before.

- dredd-core pinned to v0.18.0. Revision 0010 runs core's upgrade in its order (key_mode column and
  CHECK, then the model_provider_user_key table); the grant block re-applied by identity_grants on
  every migrate names the new table (hub only, no module). 0009's drop list names the new table too,
  so a fresh platform install can drop create_all's local copy.
- call_target and refresh take the key through core's key_for (the policy re-checked on every call).
  No personal key: 409 model_provider_user_key_missing, never a keyless call. A stored personal key
  that will not decrypt: 409 model_provider_key_unreadable. A user-mode provider is refreshed with the
  administrator's own personal key.
- GET/PUT/DELETE /api/v1/models/keys[/{provider_id}] for the signed-in person; write-only, the prefix
  only. /models marks the models that wait for the person's key (needs_key).
- Console: "Każda osoba używa własnego klucza API" when adding an API provider (the pasted key is
  stored as the administrator's own), the key mode under Details with a warning before an address or
  mode change drops everyone's personal keys, the "Moje klucze" screen, "(dodaj swój klucz)" in the
  model picker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uwxqGRpAezXG78YwnHRka
2026-11-06 22:06:08 +01:00
13 changed files with 438 additions and 43 deletions
+5 -5
View File
@@ -1,15 +1,15 @@
[submodule "deploy/modules/galena"]
path = deploy/modules/galena
url = https://github.com/Alpaq92/Galena
url = ../Galena.git
[submodule "deploy/modules/counsel"]
path = deploy/modules/counsel
url = https://github.com/Alpaq92/CounselScorecard
url = ../CounselScorecard.git
[submodule "deploy/modules/sygna"]
path = deploy/modules/sygna
url = https://github.com/Alpaq92/Sygna
url = ../Sygna.git
[submodule "deploy/modules/compass"]
path = deploy/modules/compass
url = https://github.com/Alpaq92/compass-contract-hub
url = ../compass-contract-hub.git
[submodule "deploy/modules/insider"]
path = deploy/modules/insider
url = https://github.com/Alpaq92/Insider.git
url = ../Insider.git
@@ -66,8 +66,12 @@ APPEND_ONLY = ("audit_log",)
NO_DELETE: tuple[str, ...] = ()
READ_ONLY = ("alembic_version",)
# Children first, for the drops.
_DROP_ORDER = ("model_provider_key", "model_provider_policy", "model_provider")
# Children first, for the drops. `model_provider_user_key` (dredd-core 0.18.0, revision 0010) is
# here too: on a FRESH platform install `0001`'s `create_all` builds a local copy of it as well, and
# its foreign key would block dropping the local `model_provider`. A database already past 0009
# never re-runs this, so naming a table that did not exist then changes nothing for it.
_DROP_ORDER = ("model_provider_user_key", "model_provider_key", "model_provider_policy",
"model_provider")
def _has(bind, schema_sql: str, table: str) -> bool:
@@ -0,0 +1,57 @@
"""Personal API keys per provider (dredd-core 0.18.0): `model_provider.key_mode` and
`model_provider_user_key`, the hub's half of core's 0.18.0 notes, in their order:
1. `model_provider_key_mode_sql` — the `key_mode` column (`firm` / `user` / `none`) and its CHECK,
idempotent; every existing provider stays `firm`, so nothing changes until an administrator
switches one to `user`.
2. `create_model_provider_tables` — adds only the missing `model_provider_user_key` (`checkfirst`).
3. The grant block — re-applied on every migrate by `python -m app.identity_grants`
(`model_provider_statements`), which `atrium-migrate` runs right after `alembic upgrade head`. In
0.18.0 it names the new table: the hub reads and writes it, no module reaches it (not even the key
opt-in, Compass), and `managed check` reports any such grant as `key exposure`.
The hub must migrate before any module moves to 0.18.0: until then a module's `managed check` sees the
new table as missing. Standalone (`IDENTITY_SCHEMA` empty) the same two steps run in Atrium's own
schema, and `0003`'s runtime sweep is re-run for the new table.
Downgrade on the platform does nothing, for 0009's reason: the shared tables hold people's keys.
"""
from __future__ import annotations
from dredd_core import model_providers as mp
from dredd_core.schema import runtime_grants_sql
from sqlalchemy import text
from alembic import op
from app.config import get_settings
revision = "0010"
down_revision = "0009"
branch_labels = None
depends_on = None
# The same evidence tables as 0003 / 0008 / 0009.
APPEND_ONLY = ("audit_log",)
NO_DELETE: tuple[str, ...] = ()
READ_ONLY = ("alembic_version",)
def upgrade() -> None:
settings = get_settings()
bind = op.get_bind()
schema = (settings.identity_schema if settings.shares_identity
else bind.execute(text("SELECT current_schema()")).scalar())
op.execute(mp.model_provider_key_mode_sql(schema))
mp.create_model_provider_tables(bind, schema)
if not settings.shares_identity:
op.execute(runtime_grants_sql(settings.db_app_role, append_only=APPEND_ONLY,
no_delete=NO_DELETE, read_only=READ_ONLY))
def downgrade() -> None:
settings = get_settings()
if settings.shares_identity:
return
op.execute("DROP TABLE IF EXISTS model_provider_user_key")
op.execute("ALTER TABLE model_provider DROP CONSTRAINT IF EXISTS ck_model_provider_key_mode")
op.execute("ALTER TABLE model_provider DROP COLUMN IF EXISTS key_mode")
+10 -4
View File
@@ -35,9 +35,15 @@ from dredd_core import (
)
# Opt-in (dredd-core 0.15.0): registers `model_provider`, `model_provider_policy` and
# `model_provider_key` on the metadata. Atrium is the hub that writes them; on the platform they live
# in the identity schema (revision 0009), standalone in Atrium's own like any table.
from dredd_core.model_providers import ModelProvider, ModelProviderKey, ModelProviderPolicy
# `model_provider_key` (0.18.0: and `model_provider_user_key`) on the metadata. Atrium is the hub that
# writes them; on the platform they live in the identity schema (revisions 0009, 0010), standalone in
# Atrium's own like any table.
from dredd_core.model_providers import (
ModelProvider,
ModelProviderKey,
ModelProviderPolicy,
ModelProviderUserKey,
)
from .marketplace import AccessRequest, Module, ModuleAssignment
@@ -46,5 +52,5 @@ __all__ = [
"AppUser", "Session", "ModulePermission", "AppSetting", "AuditLog",
"Node", "PermissionGrant", "Favorite",
"Module", "ModuleAssignment", "AccessRequest",
"ModelProvider", "ModelProviderPolicy", "ModelProviderKey",
"ModelProvider", "ModelProviderPolicy", "ModelProviderKey", "ModelProviderUserKey",
]
+25
View File
@@ -27,6 +27,7 @@ from ..deps import client_ip, get_current_user
from ..errors import ConflictError, ValidationError
from ..integrations import model_server
from ..models import AppUser
from ..schemas import MyKeyIn
from ..services import audit, providers
router = APIRouter(tags=["models"])
@@ -60,6 +61,30 @@ def list_models(db: Session = Depends(get_db), user: AppUser = Depends(get_curre
return {"configured": bool(models), "models": models, "choices": {}, "modules": []}
# ── Settings › My keys: a person's own API key per provider (`key_mode == "user"`) ──
# Write-only like every key: the list says the prefix, never the key.
@router.get("/models/keys")
def my_keys(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
return {"keys": providers.my_keys(db, user), "keys_writable": providers.keys_writable()}
@router.put("/models/keys/{provider_id}")
def set_my_key(provider_id: uuid.UUID, body: MyKeyIn, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
out = providers.set_my_key(db, user, provider_id, body.api_key, ip=client_ip(request))
db.commit()
return out
@router.delete("/models/keys/{provider_id}")
def clear_my_key(provider_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
user: AppUser = Depends(get_current_user)) -> dict:
removed = providers.clear_my_key(db, user, provider_id, ip=client_ip(request))
db.commit()
return {"removed": removed}
class Message(BaseModel):
role: str = Field(pattern="^(user|assistant|tool)$")
content: str | None = Field(default=None, max_length=MAX_PROMPT_CHARS)
+7
View File
@@ -248,6 +248,7 @@ class ProviderUpdateIn(BaseModel):
dpa_url: str | None = Field(default=None, max_length=2000)
allowed_for: str | None = Field(default=None, max_length=20)
is_active: bool | None = None
key_mode: str | None = Field(default=None, max_length=20) # core: firm / user / none
clear: list[str] = Field(default_factory=list, max_length=10)
@@ -262,6 +263,12 @@ class ProviderCreateIn(BaseModel):
processor_name: str | None = Field(default=None, max_length=200)
dpa_url: str | None = Field(default=None, max_length=2000)
allowed_for: str | None = Field(default=None, max_length=20)
key_mode: str = Field(default="firm", max_length=20)
class MyKeyIn(BaseModel):
"""A person's own API key for one provider. Write-only, like every key here."""
api_key: str = Field(min_length=1, max_length=4096, repr=False)
class ProviderDiscoverIn(BaseModel):
+89 -14
View File
@@ -43,6 +43,7 @@ from . import audit
KEY_SECRET_MISSING = "model_provider_secret_missing"
KEY_UNREADABLE = "model_provider_key_unreadable"
USER_KEY_MISSING = "model_provider_user_key_missing"
def _secret() -> str:
@@ -81,6 +82,7 @@ def out(provider: ModelProvider) -> dict[str, Any]:
"processor_name": provider.processor_name, "dpa_url": provider.dpa_url,
"trains_on_data": provider.trains_on_data, "models": list(provider.models or []),
"allowed_for": provider.allowed_for, "is_active": provider.is_active,
"key_mode": provider.key_mode,
"has_key": provider.key_prefix is not None, "key_prefix": provider.key_prefix,
"stays_in_the_eu": core.stays_in_the_eu(provider),
"created_at": provider.created_at.isoformat() if provider.created_at else None,
@@ -97,8 +99,24 @@ def get(db: DbSession, provider_id: uuid.UUID) -> dict:
def create(db: DbSession, actor: AppUser, fields: dict, *, ip: str | None) -> dict:
encrypt = _encrypt_or_refuse(fields.get("api_key"))
"""With `key_mode == "user"` a pasted key is the administrator's OWN personal key, stored in the
same transaction as the provider: a refusal undoes both, so no provider is left without it."""
personal = fields.pop("api_key", None) if fields.get("key_mode") == "user" else None
encrypt = _encrypt_or_refuse(fields.get("api_key") or personal)
provider = core.create(db, actor=actor, encrypt=encrypt, ip=ip, **fields)
if personal:
db.flush()
try:
core.set_user_key(db, actor=actor, provider=provider, api_key=personal, encrypt=encrypt,
is_admin=bool(actor.is_admin), ip=ip)
except NotFoundError:
# Core's usage filter: inactive, `nobody`, or hidden by "only EU/EEA" (no EU region yet).
raise ConflictError(
f"Polityka użycia nie pozwala używać dostawcy {provider.name}, więc nie da się zapisać "
"twojego klucza. Podaj region z UE/EOG albo wyłącz „Tylko dostawcy z UE/EOG”.",
{"code": "model_provider_not_usable",
"en": f"The usage policy does not allow {provider.name}, so your key cannot be stored. "
"Give an EU/EEA region or switch off \"only EU/EEA providers\"."}) from None
return out(provider)
@@ -119,7 +137,7 @@ def disable(db: DbSession, actor: AppUser, provider_id: uuid.UUID, *, ip: str |
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),
"kinds": list(core.KINDS), "dialects": list(core.DIALECTS), "key_modes": list(core.KEY_MODES),
"keys_writable": keys_writable()}
@@ -183,12 +201,23 @@ async def refresh(db: DbSession, actor: AppUser, provider_id: uuid.UUID, *, ip:
(audited like any change). A refused listing — empty included — raises before anything is
written, so the old list stays. Ends the read transaction before the outbound call."""
provider = core.get_or_404(db, provider_id)
base_url, name = provider.base_url, provider.name
key = core.api_key(db, provider, decrypt) if provider.key_prefix is not None else None
if provider.key_prefix is not None and key is None:
raise ConflictError(
f"Klucza API dostawcy {name} nie da się odczytać. Zapisz go ponownie.",
{"code": KEY_UNREADABLE, "en": f"The API key of {name} cannot be read. Store it again."})
base_url = provider.base_url
# Administration, not use: no usage filter here (a disabled or EU-hidden provider is refreshed
# too). A `user` provider has no firm key, so the administrator's own personal key lists it.
if provider.key_mode == "user":
row = db.get(core.ModelProviderUserKey, (provider.id, actor.id))
key = decrypt(row.api_key_encrypted) if row else None
if key is None:
raise ConflictError(
f"{provider.name} działa na kluczach osobistych. Dodaj swój w Ustawienia › Moje klucze, aby odświeżyć modele.",
{"code": USER_KEY_MISSING, "provider_id": str(provider.id),
"en": f"{provider.name} runs on personal keys. Add yours in Settings › My keys to refresh its models."})
else:
key = core.api_key(db, provider, decrypt) if provider.key_prefix is not None else None
if provider.key_prefix is not None and key is None:
raise ConflictError(
f"Klucza API dostawcy {provider.name} nie da się odczytać. Zapisz go ponownie.",
{"code": KEY_UNREADABLE, "en": f"The API key of {provider.name} cannot be read. Store it again."})
db.commit() # nothing written yet: only closes the transaction the outbound call must not hold
models = await model_server.list_models(base_url, key, vendor_of(base_url))
return update(db, actor, provider_id, {"models": models}, ip=ip)
@@ -204,7 +233,8 @@ CHAT_DIALECT = "openai"
def usable_models(db: DbSession, user: AppUser) -> list[dict]:
"""The models this person may ask, in provider order. Never an address or a key."""
return [
{"id": m["id"], "provider": p.name, "kind": p.kind, "stays_in_the_eu": core.stays_in_the_eu(p)}
{"id": m["id"], "provider": p.name, "kind": p.kind, "stays_in_the_eu": core.stays_in_the_eu(p),
"needs_key": p.key_mode == "user" and core.user_key_prefix(db, p, user.id) is None}
for p in core.usable_providers(db, is_admin=bool(user.is_admin))
for m in p.models or [] if m.get("dialect", CHAT_DIALECT) == CHAT_DIALECT
]
@@ -219,11 +249,56 @@ def call_target(db: DbSession, user: AppUser, model_id: str) -> dict:
raise NotFoundError(f"Modelu {model_id} nie ma na liście dostępnych dla ciebie.",
{"code": "model_not_offered", "en": f"Model {model_id} is not offered to you."})
provider, _model = found
key = core.api_key(db, provider, decrypt) if provider.key_prefix is not None else None
if provider.key_prefix is not None and key is None:
# A changed MODEL_PROVIDER_SECRET or a tampered row: say so, never call keyless.
key = _key_or_refuse(db, user, provider)
return {"base_url": provider.base_url, "key": key, "provider": provider.name, "kind": provider.kind,
"key_source": provider.key_mode if key else "none"}
def _key_or_refuse(db: DbSession, user: AppUser, provider: ModelProvider) -> str | None:
"""The key to call `provider` with for `user`, through core's `key_for` (which re-checks the
policy on every call). Never calls keyless where a key is expected: a stored key that will not
decrypt (a changed MODEL_PROVIDER_SECRET, a tampered row) and a missing personal key are 409s."""
key, source = core.key_for(db, provider, user_id=user.id, is_admin=bool(user.is_admin),
decrypt=decrypt)
if key is not None or source == "none":
return key
if source == "firm":
if provider.key_prefix is None:
return None # a firm provider without a key: a local server
raise ConflictError(
f"Klucza API dostawcy {provider.name} nie da się odczytać. Poproś administratora o jego ponowne zapisanie.",
{"code": KEY_UNREADABLE, "en": f"The API key of {provider.name} cannot be read. Ask an administrator to store it again."})
return {"base_url": provider.base_url, "key": key, "provider": provider.name, "kind": provider.kind,
"key_source": "firm" if key else "none"}
if core.user_key_prefix(db, provider, user.id) is not None:
raise ConflictError(
f"Twojego klucza API do {provider.name} nie da się odczytać. Zapisz go ponownie w Ustawienia › Moje klucze.",
{"code": KEY_UNREADABLE, "en": f"Your API key for {provider.name} cannot be read. Store it again in Settings › My keys."})
raise ConflictError(
f"{provider.name} działa na Twoim własnym kluczu API. Dodaj go w Ustawienia › Moje klucze.",
{"code": USER_KEY_MISSING, "provider_id": str(provider.id),
"en": f"{provider.name} runs on your own API key. Add it in Settings › My keys."})
# ── a person's own keys: Settings › My keys ──────────────────────────────────
# Core decides everything (who may store a key where, the audit, the purge when an administrator moves
# a provider's address); this binds it to the signed-in person and Atrium's cipher.
def my_keys(db: DbSession, user: AppUser) -> list[dict]:
"""The providers this person may use that run on a personal key, with their key's prefix."""
return [
{"provider_id": str(p.id), "provider": p.name, "kind": p.kind, "base_url": p.base_url,
"key_prefix": core.user_key_prefix(db, p, user.id)}
for p in core.usable_providers(db, is_admin=bool(user.is_admin)) if p.key_mode == "user"
]
def set_my_key(db: DbSession, user: AppUser, provider_id: uuid.UUID, api_key: str, *,
ip: str | None) -> dict:
provider = core.get_or_404(db, provider_id)
prefix = core.set_user_key(db, actor=user, provider=provider, api_key=api_key,
encrypt=_encrypt_or_refuse(api_key), is_admin=bool(user.is_admin), ip=ip)
return {"provider_id": str(provider.id), "key_prefix": prefix}
def clear_my_key(db: DbSession, user: AppUser, provider_id: uuid.UUID, *, ip: str | None) -> bool:
# Never refused by core: a person can always take their key back.
return core.clear_user_key(db, actor=user, provider=core.get_or_404(db, provider_id), ip=ip)
+1 -1
View File
@@ -49,7 +49,7 @@
# halves: `0004` (the cutover, which has still never run anywhere) moves it to the shared schema,
# and `0006_module_permission.py` renames it in this app's OWN schema — which `0001` being stamped
# could never have reached, and which is the `node_kind` mistake the family has made once already.
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.16.0
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.18.0
# Web framework
fastapi==0.115.6
+62 -7
View File
@@ -15,15 +15,29 @@ from app.main import app
from app.routers import models
from app.services import providers
ADMIN, PERSON = SimpleNamespace(is_admin=True), SimpleNamespace(is_admin=False)
ADMIN = SimpleNamespace(id=uuid.uuid4(), is_admin=True)
PERSON = SimpleNamespace(id=uuid.uuid4(), is_admin=False)
def _provider(kind="local", key_prefix=None, models_=None, name="LM Studio"):
return SimpleNamespace(name=name, kind=kind, base_url="http://host.docker.internal:1234/v1",
key_prefix=key_prefix, region=None,
def _provider(kind="local", key_prefix=None, models_=None, name="LM Studio", key_mode="firm"):
return SimpleNamespace(id=uuid.uuid4(), name=name, kind=kind,
base_url="http://host.docker.internal:1234/v1",
key_prefix=key_prefix, region=None, key_mode=key_mode,
models=models_ if models_ is not None else [{"id": "qwen", "dialect": "openai"}])
def _key_for(monkeypatch, key, personal_prefix=None):
"""Core's one door out for a key, as the hub sees it: `(key, source)` for this person."""
calls = []
def key_for(db, provider, *, user_id, is_admin, decrypt):
calls.append(user_id)
return key, provider.key_mode
monkeypatch.setattr(providers.core, "key_for", key_for)
monkeypatch.setattr(providers.core, "user_key_prefix", lambda db, provider, user_id: personal_prefix)
return calls
def _offering(monkeypatch, found):
calls = []
@@ -52,6 +66,7 @@ def test_a_model_in_another_dialect_is_not_offered(monkeypatch):
def test_the_address_comes_from_the_row_and_the_asker_is_judged_by_their_own_tier(monkeypatch):
p = _provider()
calls = _offering(monkeypatch, (p, p.models[0]))
_key_for(monkeypatch, None)
target = providers.call_target(None, PERSON, "qwen")
assert target == {"base_url": p.base_url, "key": None, "provider": "LM Studio", "kind": "local",
"key_source": "none"}
@@ -62,7 +77,7 @@ def test_the_address_comes_from_the_row_and_the_asker_is_judged_by_their_own_tie
def test_a_stored_key_goes_with_the_call(monkeypatch):
p = _provider(kind="api", key_prefix="sk-abc")
_offering(monkeypatch, (p, p.models[0]))
monkeypatch.setattr(providers.core, "api_key", lambda db, provider, decrypt: "sk-abcdef")
_key_for(monkeypatch, "sk-abcdef")
target = providers.call_target(None, PERSON, "qwen")
assert (target["key"], target["key_source"]) == ("sk-abcdef", "firm")
@@ -70,9 +85,49 @@ def test_a_stored_key_goes_with_the_call(monkeypatch):
def test_an_unreadable_key_refuses_instead_of_calling_without_it(monkeypatch):
p = _provider(kind="api", key_prefix="sk-abc")
_offering(monkeypatch, (p, p.models[0]))
monkeypatch.setattr(providers.core, "api_key", lambda db, provider, decrypt: None)
with pytest.raises(ConflictError):
_key_for(monkeypatch, None)
with pytest.raises(ConflictError) as exc:
providers.call_target(None, PERSON, "qwen")
assert exc.value.extra["code"] == providers.KEY_UNREADABLE
# ── personal keys (dredd-core 0.18.0, `key_mode == "user"`) ─────────────
def test_a_personal_key_is_the_askers_own(monkeypatch):
p = _provider(kind="api", key_mode="user")
_offering(monkeypatch, (p, p.models[0]))
calls = _key_for(monkeypatch, "sk-mine")
target = providers.call_target(None, PERSON, "qwen")
assert (target["key"], target["key_source"]) == ("sk-mine", "user")
assert calls == [PERSON.id]
def test_no_personal_key_asks_the_person_to_add_one_and_never_calls_keyless(monkeypatch):
p = _provider(kind="api", key_mode="user")
_offering(monkeypatch, (p, p.models[0]))
_key_for(monkeypatch, None)
with pytest.raises(ConflictError) as exc:
providers.call_target(None, PERSON, "qwen")
assert exc.value.extra["code"] == providers.USER_KEY_MISSING
assert exc.value.extra["provider_id"] == str(p.id)
def test_a_stored_personal_key_that_will_not_decrypt_says_store_it_again(monkeypatch):
p = _provider(kind="api", key_mode="user")
_offering(monkeypatch, (p, p.models[0]))
_key_for(monkeypatch, None, personal_prefix="sk-min")
with pytest.raises(ConflictError) as exc:
providers.call_target(None, PERSON, "qwen")
assert exc.value.extra["code"] == providers.KEY_UNREADABLE
def test_the_list_says_which_models_wait_for_the_persons_key(monkeypatch):
firm, mine = _provider(), _provider(kind="api", key_mode="user", models_=[{"id": "claude"}])
monkeypatch.setattr(providers.core, "usable_providers", lambda db, *, is_admin: [firm, mine])
monkeypatch.setattr(providers.core, "stays_in_the_eu", lambda provider: True)
monkeypatch.setattr(providers.core, "user_key_prefix", lambda db, provider, user_id: None)
assert {m["id"]: m["needs_key"] for m in providers.usable_models(None, PERSON)} == {
"qwen": False, "claude": True}
def test_the_list_shows_chat_models_only_and_never_an_address(monkeypatch):
+1 -1
View File
@@ -119,7 +119,7 @@ def test_dynamic_values_are_escaped(screen):
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",
"p.is_active", "p.trains_on_data", "p.has_key", "p.key_mode",
"policy.eu_only", "r.models.map", "esc(")):
continue
pytest.fail(f"unescaped interpolation: ${{{expr}}}")
+31 -4
View File
@@ -105,7 +105,8 @@ KEY = "sk-ant-api03-SECRETVALUE"
@pytest.fixture
def stored(monkeypatch):
row = types.SimpleNamespace(id=uuid.uuid4(), name="Anthropic", base_url="https://api.anthropic.com/v1",
key_prefix="sk-ant-a", models=[{"id": "old", "dialect": "openai"}])
key_prefix="sk-ant-a", key_mode="firm",
models=[{"id": "old", "dialect": "openai"}])
seen = {"list": [], "update": [], "commits": 0, "listing": MODELS}
async def fake_list(base_url, key, vendor):
@@ -119,17 +120,26 @@ def stored(monkeypatch):
row.models = fields["models"]
return {"id": str(provider_id), "models": row.models}
db = types.SimpleNamespace(commit=lambda: seen.__setitem__("commits", seen["commits"] + 1))
monkeypatch.setattr(providers.core, "get_or_404", lambda _db, _id: row)
def get(_model, pk):
seen["personal_for"] = pk
return types.SimpleNamespace(api_key_encrypted="enc") if seen.get("personal") else None
db = types.SimpleNamespace(commit=lambda: seen.__setitem__("commits", seen["commits"] + 1), get=get)
# Administration: the firm key straight from core, never through the usage filter (`key_for`).
monkeypatch.setattr(providers.core, "api_key", lambda _db, _p, _decrypt: KEY)
monkeypatch.setattr(providers.core, "key_for", lambda *_a, **_k: pytest.fail("refresh used key_for"))
monkeypatch.setattr(providers, "decrypt", lambda stored: seen.get("personal"))
monkeypatch.setattr(providers.model_server, "list_models", fake_list)
monkeypatch.setattr(providers, "update", fake_update)
return row, seen, db
ADMIN = types.SimpleNamespace(id=uuid.uuid4(), is_admin=True)
def _refresh(row, db):
actor = types.SimpleNamespace(id=uuid.uuid4())
return asyncio.run(providers.refresh(db, actor, row.id, ip="10.0.0.1"))
return asyncio.run(providers.refresh(db, ADMIN, row.id, ip="10.0.0.1"))
def test_refresh_replaces_the_models_and_ends_the_read_first(stored):
@@ -168,6 +178,23 @@ def test_an_unreadable_key_refuses_before_calling(stored, monkeypatch):
assert seen["list"] == [] and seen["update"] == []
def test_refresh_of_a_personal_key_provider_lists_with_the_administrators_own_key(stored):
row, seen, db = stored
row.key_mode, row.key_prefix, seen["personal"] = "user", None, "sk-ant-admins-own"
_refresh(row, db)
assert seen["personal_for"] == (row.id, ADMIN.id)
assert seen["list"] == [("https://api.anthropic.com/v1", "sk-ant-admins-own", "anthropic")]
def test_refresh_of_a_personal_key_provider_without_the_administrators_key_says_add_yours(stored):
row, seen, db = stored
row.key_mode, row.key_prefix = "user", None
with pytest.raises(providers.ConflictError) as exc:
_refresh(row, db)
assert exc.value.extra["code"] == providers.USER_KEY_MISSING
assert seen["list"] == []
@pytest.mark.parametrize("url, vendor", [("https://api.anthropic.com/v1", "anthropic"),
("https://api.openai.com/v1/", "openai")])
def test_a_pasted_cloud_address_is_asked_the_way_its_vendor_answers(calls, url, vendor):
@@ -234,3 +234,71 @@ def test_the_policy_round_trip(admin_client):
rows = admin_client.get("/api/v1/admin/audit",
params={"action": "model_provider.policy", "limit": 5}).json()
assert rows[0]["diff"]["level"] == ["nobody", "everyone"]
# ── personal keys (dredd-core 0.18.0, revision 0010) ──────────────────────────
KEYS = "/api/v1/models/keys"
@needs_secret
def test_a_personal_key_is_the_persons_own_and_never_follows_a_moved_address(admin_client, client,
make_user):
from app.errors import ConflictError
from app.models import AppUser
from app.services import providers as service
admin_client.put(f"{BASE}/policy", json={"level": "everyone", "eu_only": False})
provider = _create(admin_client, key_mode="user",
models=[{"id": f"own-{RUN}", "context_window": 32000, "dialect": "openai"}])
assert provider["key_mode"] == "user" and provider["has_key"] is False
firm = _create(admin_client)
anna, ben = make_user("keys-anna"), make_user("keys-ben")
as_anna, as_ben = bearer(anna["token"]), bearer(ben["token"])
mine = [k for k in client.get(KEYS, headers=as_anna).json()["keys"] if k["provider_id"] == provider["id"]]
assert mine == [{"provider_id": provider["id"], "provider": provider["name"], "kind": "api",
"base_url": provider["base_url"], "key_prefix": None}]
listed = {m["id"]: m for m in client.get("/api/v1/models", headers=as_anna).json()["models"]}
assert listed[f"own-{RUN}"]["needs_key"] is True
secret = f"sk-anna-{RUN}-SECRET"
r = client.put(f"{KEYS}/{provider['id']}", json={"api_key": secret}, headers=as_anna)
assert r.status_code == 200, r.text
assert secret not in r.text and secret not in client.get(KEYS, headers=as_anna).text
# A firm provider takes no personal key: 404, as if it were not there.
assert client.put(f"{KEYS}/{firm['id']}", json={"api_key": secret}, headers=as_anna).status_code == 404
with _db() as db:
target = service.call_target(db, db.get(AppUser, uuid.UUID(anna["id"])), f"own-{RUN}")
assert (target["key"], target["key_source"]) == (secret, "user")
with pytest.raises(ConflictError) as exc:
service.call_target(db, db.get(AppUser, uuid.UUID(ben["id"])), f"own-{RUN}")
assert exc.value.extra["code"] == service.USER_KEY_MISSING
db.rollback()
# The administrator moves the address: every personal key of that provider is gone.
moved = admin_client.patch(f"{BASE}/{provider['id']}", json={"base_url": "https://api.example.eu/v2/"})
assert moved.status_code == 200, moved.text
after = [k for k in client.get(KEYS, headers=as_anna).json()["keys"] if k["provider_id"] == provider["id"]]
assert after[0]["key_prefix"] is None
assert client.delete(f"{KEYS}/{provider['id']}", headers=as_anna).json() == {"removed": False}
assert client.put(f"{KEYS}/{provider['id']}", json={"api_key": secret}, headers=as_ben).status_code == 200
assert client.delete(f"{KEYS}/{provider['id']}", headers=as_ben).json() == {"removed": True}
@needs_secret
def test_adding_a_personal_key_provider_stores_the_admins_key_or_nothing(admin_client, client):
admin_client.put(f"{BASE}/policy", json={"level": "everyone", "eu_only": True})
secret = f"sk-admin-{RUN}-SECRET"
# Hidden by "only EU/EEA" (no region): refused as a whole, so no provider is left without the key.
name = f"Personal {RUN} us"
r = admin_client.post(BASE, json=_body(name=name, region=None, key_mode="user", api_key=secret))
assert r.status_code == 409 and r.json()["code"] == "model_provider_not_usable", r.text
assert secret not in r.text
assert name not in [p["name"] for p in admin_client.get(BASE).json()]
# Allowed: the provider has no firm key, and the pasted key is the administrator's own.
created = _create(admin_client, key_mode="user", api_key=secret)
assert created["has_key"] is False and secret not in str(created)
mine = [k for k in admin_client.get(KEYS).json()["keys"] if k["provider_id"] == created["id"]]
assert mine and mine[0]["key_prefix"]
+76 -5
View File
@@ -459,6 +459,27 @@ const I18N = {
// connected apps (app tokens) — minting lives only in the hub, so this screen is the family's
// only one. Every string that tells someone what a token reaches is here, in both languages.
'Połączone aplikacje': 'Connected apps',
'Moje klucze': 'My keys',
'Twoje klucze API do dostawców modeli, za które płacisz sam.': 'Your own API keys for model providers, paid for by you.',
'Klucz': 'Key',
'Zmień': 'Change',
'Usunięto.': 'Removed.',
'Wklej swój klucz API': 'Paste your API key',
'Żaden dostawca nie wymaga własnego klucza.': 'No provider needs a key of your own.',
'Klucz jest tylko do zapisu: nikt, także administrator, nie zobaczy go ponownie. Gdy administrator zmieni adres dostawcy, klucz zostanie usunięty.':
'The key is write-only: nobody, an administrator included, will see it again. If an administrator changes the provider\'s address, the key is removed.',
'(dodaj swój klucz)': '(add your key)',
'klucze osobiste': 'personal keys',
'Czyj klucz': 'Whose key',
'Firmowy (wpisuje administrator)': 'The firm\'s (an administrator enters it)',
'Każda osoba własny': 'Each person their own',
'Bez klucza': 'No key',
'Każda osoba używa własnego klucza API': 'Each person uses their own API key',
'Wklejony klucz zostanie zapisany jako twój własny, a nie firmowy. Pozostali dodają swoje w Ustawienia › Moje klucze.':
'The pasted key is stored as your own, not the firm\'s. Everyone else adds theirs under Settings › My keys.',
'Zmiana adresu albo trybu klucza usunie klucze osobiste wszystkich osób do tego dostawcy. Każdy będzie musiał wkleić swój ponownie.':
'Changing the address or the key mode removes everybody\'s personal keys for this provider. Each person will have to paste theirs again.',
'Zapisz i usuń klucze': 'Save and remove the keys',
'Aplikacje i skrypty, które logują się twoim kontem bez hasła.': 'Apps and scripts that sign in as you, without a password.',
'Twoje tokeny': 'Your tokens',
'Nowy token': 'New token',
@@ -899,6 +920,7 @@ const NAV = [
holds INSERT on `session` — so a desktop client's user who cannot find it has no way left but curl. */
const SETTINGS_NAV = [
{ hash: '#/tokens', icon: 'key', label: 'Połączone aplikacje' },
{ hash: '#/my-keys', icon: 'key', label: 'Moje klucze' },
{ hash: '#/admin/settings', icon: 'settings', label: 'Ogólne', admin: true },
{ hash: '#/admin/providers', icon: 'globe', label: 'Dostawcy modeli', admin: true },
];
@@ -1062,6 +1084,7 @@ async function router() {
else if (seg[0] === 'marketplace') await viewMarketplace(C, q);
else if (seg[0] === 'requests') await viewMyRequests(C);
else if (seg[0] === 'tokens') await viewTokens(C);
else if (seg[0] === 'my-keys') await viewMyKeys(C);
else if (seg[0] === 'settings' && seg[1]) viewModuleSettings(C, seg[1]);
else if (seg[0] === 'admin' && isAdmin()) await adminRoute(C, seg.slice(1), q);
else { setCrumb([]); C.innerHTML = '<div class="empty">Nie znaleziono strony.</div>'; }
@@ -1263,7 +1286,7 @@ function modelOptions(models, selected, none) {
}
return `<option value="">${esc(none)}</option>` + groups.map((g) =>
`<optgroup label="${esc(g.provider)}" data-no-i18n>` + g.models.map((m) =>
`<option value="${esc(m.id)}" title="${esc(m.id)}"${m.id === selected ? ' selected' : ''} data-no-i18n>${esc(prettyModel(m.id))}</option>`).join('')
`<option value="${esc(m.id)}" title="${esc(m.id)}"${m.id === selected ? ' selected' : ''} data-no-i18n>${esc(prettyModel(m.id))}${m.needs_key ? ' ' + esc(_tr('(dodaj swój klucz)')) : ''}</option>`).join('')
+ '</optgroup>').join('');
}
@@ -3491,6 +3514,36 @@ async function viewTokens(C) {
</div>`;
}
/* ── Ustawienia › Moje klucze: a person's own API key per provider (key_mode "user") ──
Write-only like every key: the server says the prefix, never the key. Removing is never refused,
so a key can be taken back even from a provider this person may no longer use. */
async function viewMyKeys(C) {
const r = await api('GET', '/models/keys');
setCrumb([{ label: 'Ustawienia' }, { label: 'Moje klucze' }]);
C.innerHTML = pageHead('Moje klucze', 'Twoje klucze API do dostawców modeli, za które płacisz sam.', '')
+ (r.keys_writable ? '' : '<div class="banner warn">Ten serwer nie ma ustawionego MODEL_PROVIDER_SECRET, więc nie może zapisać klucza API.</div>')
+ (r.keys.length ? `<div class="card"><div class="tablewrap"><table class="rt"><thead><tr>
<th>Dostawca</th><th>Klucz</th><th></th>
</tr></thead><tbody>${r.keys.map((k) => `<tr>
<td><div class="row">${providerIcon({ name: k.provider, kind: k.kind, base_url: k.base_url })}<div>${dat(k.provider)}</div></div></td>
<td${lbl('Klucz')}>${k.key_prefix ? `<span class="chip ok">ustawiony</span> <span class="mono tiny faint" data-no-i18n>${esc(k.key_prefix)}…</span>`
: '<span class="chip warn">brak</span>'}</td>
<td class="acts-cell shrink"><div class="row">
<button class="btn sm" data-pid="${esc(k.provider_id)}" ${r.keys_writable ? '' : 'disabled'} onclick="openMyKey(this.dataset.pid)">${k.key_prefix ? 'Zmień' : 'Dodaj'}</button>
${k.key_prefix ? `<button class="btn sm danger" data-pid="${esc(k.provider_id)}" onclick="mutate('DELETE', '/models/keys/' + enc(this.dataset.pid), undefined, { done: 'Usunięto.' })">Usuń</button>` : ''}
</div></td>
</tr>`).join('')}</tbody></table></div>
<div class="faint tiny" style="margin-top:10px">Klucz jest tylko do zapisu: nikt, także administrator, nie zobaczy go ponownie. Gdy administrator zmieni adres dostawcy, klucz zostanie usunięty.</div></div>`
: '<div class="empty">Żaden dostawca nie wymaga własnego klucza.</div>');
}
function openMyKey(id) {
modal('Klucz API', '', `<label class="field">Wklej swój klucz API<input id="mkKey" type="password"
autocomplete="new-password" maxlength="4096" /></label>`,
`<button class="btn" onclick="closeModal()">Anuluj</button>
<button class="btn primary" data-pid="${esc(id)}" onclick="mutate('PUT', '/models/keys/' + enc(this.dataset.pid), () => ({ api_key: $('mkKey').value.trim() }))">Zapisz</button>`);
}
function openTokenNew() {
const policy = tokenPolicy();
const max = policy.max_idle_days || 365;
@@ -4267,6 +4320,7 @@ function providerIcon(p) {
return `<span class="mi h-${hue}" style="--mi:28px">${markSvg(PROVIDER_BRAND[host], letter)}</span>`;
}
const PROVIDER_LEVEL = { nobody: 'Nikt', admins_only: 'Tylko administratorzy', everyone: 'Każdy' };
const KEY_MODE = { firm: 'Firmowy (wpisuje administrator)', user: 'Każda osoba własny', none: 'Bez klucza' };
async function viewAdminProviders(C) {
const [rows, policy] = await Promise.all([api('GET', '/admin/model-providers'),
@@ -4289,7 +4343,7 @@ async function viewAdminProviders(C) {
<td${lbl('Status')}>${p.is_active === false ? '<span class="chip err">wyłączony</span>'
: policy.eu_only && !p.stays_in_the_eu
? '<span class="chip warn" title="Polityka „Tylko dostawcy z UE/EOG” ukrywa jego modele. Odznacz ją albo podaj region w Szczegółach.">ukryty: tylko UE</span>'
: '<span class="chip ok">aktywny</span>'}</td>
: '<span class="chip ok">aktywny</span>'}${p.key_mode === 'user' ? ' <span class="chip">klucze osobiste</span>' : ''}</td>
<td class="acts-cell shrink"><div class="row">
<button class="btn sm" data-pid="${esc(p.id)}" onclick="refreshProvider(this.dataset.pid)">${svg(ICN.refresh)}<span>Odśwież modele</span></button>
<button class="btn sm" data-pid="${esc(p.id)}" onclick="openProviderForm(this.dataset.pid)">Szczegóły</button>
@@ -4312,7 +4366,9 @@ function openAddProvider() {
autocomplete="off" spellcheck="false" maxlength="4096" oninput="addProviderInput()" /></label>
<label class="field hidden" id="apKeyRow">Klucz (jeśli serwer go wymaga)<input id="apKey" type="password"
autocomplete="new-password" maxlength="4096" oninput="addProviderInput()" /></label>
<div id="apPreview" class="stack"></div>`,
<div id="apPreview" class="stack"></div>
<div id="apOwnRow" class="hidden"><label class="check"><input type="checkbox" id="apOwnKeys" /> <span>Każda osoba używa własnego klucza API</span></label>
<div class="faint tiny">Wklejony klucz zostanie zapisany jako twój własny, a nie firmowy. Pozostali dodają swoje w Ustawienia › Moje klucze.</div></div>`,
`<button class="btn" onclick="closeModal()">Anuluj</button>
<button class="btn" onclick="discoverProvider()">Sprawdź</button>
<button class="btn primary hidden" id="apAdd" onclick="addProvider()">Dodaj</button>`,
@@ -4341,6 +4397,7 @@ function showDiscovered(r) {
<label class="field">Nazwa<input id="apName" maxlength="120" value="${esc(r.name)}" /></label></div>
<div class="faint tiny">${esc(PROVIDER_KIND[r.kind] || r.kind)} · <span class="mono" data-no-i18n>${esc(r.base_url)}</span></div>
<ul class="mono tiny" data-no-i18n>${r.models.map((m) => `<li>${esc(m.id)}</li>`).join('')}</ul>`;
$('apOwnRow').classList.toggle('hidden', r.kind !== 'api');
localize($('apPreview'));
$('apAdd').classList.remove('hidden');
}
@@ -4355,6 +4412,8 @@ function addProvider() {
const body = { name: $('apName').value.trim(), kind: r.kind, base_url: r.base_url, models: r.models,
trains_on_data: false };
if (r.vendor) body.processor_name = r.name;
// With personal keys the server stores the pasted key as the administrator's own, in one transaction.
if (r.kind === 'api' && $('apOwnKeys').checked) body.key_mode = 'user';
if (key) body.api_key = key;
mutate('POST', '/admin/model-providers', body);
}
@@ -4377,6 +4436,7 @@ function openProviderForm(id) {
<label class="field">Adres umowy powierzenia (DPA)<input id="pfDpa" maxlength="2000" value="${esc(p.dpa_url || '')}" /></label>
<label class="check"><input type="checkbox" id="pfTrains" ${p.trains_on_data ? 'checked' : ''} /> <span>Dostawca trenuje modele na przesłanych danych</span></label>
<label class="check"><input type="checkbox" id="pfActive" ${p.is_active ? 'checked' : ''} /> <span>Aktywny</span></label>
<label class="field">Czyj klucz${choice('pfKeyMode', KEY_MODE, p.key_mode || 'firm')}</label>
<label class="field">Klucz API<input id="pfKey" type="password" autocomplete="new-password" maxlength="4096"
placeholder="Pozostaw puste, aby zachować obecny klucz" ${writable ? '' : 'disabled'} /></label>
<div class="faint tiny">${writable ? 'Klucz jest tylko do zapisu: nikt, także administrator, nie zobaczy go ponownie.'
@@ -4396,7 +4456,7 @@ function readProviderForm() {
const text = (id) => $(id).value.trim();
const body = {
name: text('pfName'), base_url: text('pfUrl'), trains_on_data: $('pfTrains').checked,
is_active: $('pfActive').checked,
is_active: $('pfActive').checked, key_mode: $('pfKeyMode').value,
};
const clear = [];
[['region', 'pfRegion'], ['processor_name', 'pfProcessor'], ['dpa_url', 'pfDpa'], ['allowed_for', 'pfAllowed']]
@@ -4411,8 +4471,19 @@ function readProviderForm() {
return body;
}
/* The server drops every personal key of a provider whose address moves or that stops taking them
(dredd-core 0.18.0: a key given for one address never follows to another), so ask first. */
function saveProvider(id) {
mutate('PATCH', '/admin/model-providers/' + enc(id), readProviderForm);
const p = (state._providers || []).find((x) => x.id === id);
const body = readProviderForm();
if (!p || p.key_mode !== 'user' || (body.base_url === p.base_url && body.key_mode === 'user')) {
mutate('PATCH', '/admin/model-providers/' + enc(id), body);
return;
}
state._pendingProvider = body;
modal('Zapisz', '', '<div class="banner warn">Zmiana adresu albo trybu klucza usunie klucze osobiste wszystkich osób do tego dostawcy. Każdy będzie musiał wkleić swój ponownie.</div>',
`<button class="btn" onclick="closeModal()">Anuluj</button>
<button class="btn danger" data-pid="${esc(id)}" onclick="mutate('PATCH', '/admin/model-providers/' + enc(this.dataset.pid), state._pendingProvider)">Zapisz i usuń klucze</button>`);
}
function removeProviderKey(id) {