Compare commits
264
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6134e3360e | ||
|
|
b0c58bace9 | ||
|
|
9a0d79a0b5 | ||
|
|
9304f102f7 | ||
|
|
7c4c276771 | ||
|
|
142832a03b | ||
|
|
84723bc357 | ||
|
|
42f4a1cc1d | ||
|
|
1a79b361e6 | ||
|
|
d7f678194a | ||
|
|
20a24b228b | ||
|
|
8f4fa25a0c | ||
|
|
a29fd61a7a | ||
|
|
67bdec6ac2 | ||
|
|
c0fe65a7b4 | ||
|
|
d288c926fc | ||
|
|
db37a5d1e7 | ||
|
|
699b341d71 | ||
|
|
b7c3cad02c | ||
|
|
a3da37fe4f | ||
|
|
8741687465 | ||
|
|
703d7ce6da | ||
|
|
0a2a93f77d | ||
|
|
6ad3b82c86 | ||
|
|
086b4016b1 | ||
|
|
082a0927bb | ||
|
|
1ebce8b146 | ||
|
|
8e9171b870 | ||
|
|
44e3ef78fa | ||
|
|
8591432bb1 | ||
|
|
fc7fd4a276 | ||
|
|
4b5ed7bb45 | ||
|
|
937828e0e5 | ||
|
|
6ebcc660bb | ||
|
|
e9a11ab969 | ||
|
|
8382de385c | ||
|
|
ecdd5dfcbd | ||
|
|
786b689897 | ||
|
|
b329d65aab | ||
|
|
c5e209aa73 | ||
|
|
396e874322 | ||
|
|
ab05db8480 | ||
|
|
17c44c5edf | ||
|
|
d4413d084e | ||
|
|
cdbd8b8da1 | ||
|
|
811b33e140 | ||
|
|
ece89497d6 | ||
|
|
ad920ed7e8 | ||
|
|
22dde4dadf | ||
|
|
c65ddf0ca0 | ||
|
|
cdd1779c40 | ||
|
|
77b8370675 | ||
|
|
b17d17e0f8 | ||
|
|
b79c8870af | ||
|
|
f69e31733b | ||
|
|
436e1ae52c | ||
|
|
6bc1464a23 | ||
|
|
84402c5645 | ||
|
|
93ddce120a | ||
|
|
726683b016 | ||
|
|
a6c16d4fd1 | ||
|
|
69e60c2a39 | ||
|
|
374f46a7a8 | ||
|
|
da45b8bf63 | ||
|
|
3153dcfe80 | ||
|
|
71926415c6 | ||
|
|
f50456ebde | ||
|
|
b9fe6b669f | ||
|
|
fa5c6ea070 | ||
|
|
80e6b90cbc | ||
|
|
62e4c9fe5b | ||
|
|
0de9f1626b | ||
|
|
abc88467dc | ||
|
|
2134d37464 | ||
|
|
def67f9e12 | ||
|
|
a28bad65b1 | ||
|
|
7f753f58e3 | ||
|
|
e8a359a923 | ||
|
|
8892ed4909 | ||
|
|
757ac7d2b4 | ||
|
|
fbb59340af | ||
|
|
c1c7dd4f9c | ||
|
|
d401fd757e | ||
|
|
b4fc85c0ab | ||
|
|
08078a658b | ||
|
|
73e29dfb8c | ||
|
|
b49e01f129 | ||
|
|
b395345657 | ||
|
|
3ea611f29d | ||
|
|
8d5d3290fa | ||
|
|
ca8c5c6e70 | ||
|
|
40120e69bd | ||
|
|
3e5be21c81 | ||
|
|
7884267843 | ||
|
|
b9e04798c8 | ||
|
|
49a47aac95 | ||
|
|
d9281da2e5 | ||
|
|
ee108148a2 | ||
|
|
43a4dbd82d | ||
|
|
a67bb5fde3 | ||
|
|
079a77d932 | ||
|
|
b9996f08fd | ||
|
|
8dbf1f91d8 | ||
|
|
b97bbc49cb | ||
|
|
b9b718d7e1 | ||
|
|
f5ebe67d0b | ||
|
|
56d948eba3 | ||
|
|
0a265ebafb | ||
|
|
aaa161b5d5 | ||
|
|
a6c0ee03b7 | ||
|
|
7e86594dde | ||
|
|
6df1f88298 | ||
|
|
98ff301912 | ||
|
|
d854f8a1e4 | ||
|
|
3a2589eee1 | ||
|
|
52e95a9d3a | ||
|
|
3ea477bf44 | ||
|
|
fac5e3155e | ||
|
|
b95a0da99e | ||
|
|
b1993ea8c2 | ||
|
|
21cd2e2703 | ||
|
|
b2b0c2e4c1 | ||
|
|
b11559f0a7 | ||
|
|
69204a3e63 | ||
|
|
b690e26de6 | ||
|
|
1e88a29fad | ||
|
|
0a050587f1 | ||
|
|
a3b54e8c3e | ||
|
|
1ed348d2bd | ||
|
|
91c83ce233 | ||
|
|
cc3099c55a | ||
|
|
fdfb37d22e | ||
|
|
8135a334b0 | ||
|
|
767e527545 | ||
|
|
2f8b745870 | ||
|
|
b637f96033 | ||
|
|
bfbf02b4fc | ||
|
|
38f5c367a0 | ||
|
|
8ab82d019d | ||
|
|
22a369fd31 | ||
|
|
23955cc0dc | ||
|
|
4f942d7f81 | ||
|
|
63f64d06b7 | ||
|
|
8a0c6bda29 | ||
|
|
f9761e98d8 | ||
|
|
a9d5002e19 | ||
|
|
350f4435de | ||
|
|
dd67e6922e | ||
|
|
fb1385c0e6 | ||
|
|
b06df51a47 | ||
|
|
f37c2d677d | ||
|
|
a8879c83ad | ||
|
|
5170b5fda3 | ||
|
|
027a5ca526 | ||
|
|
ee6bee1c0b | ||
|
|
0ce670272c | ||
|
|
4154e652af | ||
|
|
5f9bf4079d | ||
|
|
da5b3c99e2 | ||
|
|
d5023ca0fe | ||
|
|
cb79063de8 | ||
|
|
e689d247e2 | ||
|
|
1b3d78cc44 | ||
|
|
161f4dd83e | ||
|
|
cf006e7a53 | ||
|
|
c9b1e70c74 | ||
|
|
5c3163639e | ||
|
|
fab55989dc | ||
|
|
ca421b3609 | ||
|
|
0d8bcaef05 | ||
|
|
2d0f639e32 | ||
|
|
a35db0d77f | ||
|
|
362cd396a6 | ||
|
|
8e0c72b2a8 | ||
|
|
36ef5ecaa2 | ||
|
|
e12e71a143 | ||
|
|
54a5904da8 | ||
|
|
4482919413 | ||
|
|
1546533642 | ||
|
|
a7d6cdbc31 | ||
|
|
03ee5f5326 | ||
|
|
71ef21835d | ||
|
|
7837db33c4 | ||
|
|
02442605ee | ||
|
|
5ffc8ff924 | ||
|
|
e776cb8a39 | ||
|
|
5c9c44c9ef | ||
|
|
59556bb771 | ||
|
|
5efef56427 | ||
|
|
e940dbf1df | ||
|
|
77d5071536 | ||
|
|
2cc87b40ad | ||
|
|
7542d76089 | ||
|
|
f20b077125 | ||
|
|
360ea7b101 | ||
|
|
e330fd2cf3 | ||
|
|
ab8de6dc26 | ||
|
|
c10cb5bccd | ||
|
|
b3782d33a4 | ||
|
|
18623f0fee | ||
|
|
113eb1ed1a | ||
|
|
e67a4829a0 | ||
|
|
1c690e3e75 | ||
|
|
ce95d8a678 | ||
|
|
06123286f1 | ||
|
|
3dcec4631e | ||
|
|
9c9bd2b595 | ||
|
|
b8324372b0 | ||
|
|
ab96fdef8a | ||
|
|
63901c29d0 | ||
|
|
8a2300d15e | ||
|
|
ea8818faf4 | ||
|
|
6760b4510e | ||
|
|
67cfc64a6a | ||
|
|
7c37d9e02a | ||
|
|
313fe660e9 | ||
|
|
b98b5557c5 | ||
|
|
4efa125f93 | ||
|
|
b2b321e40f | ||
|
|
7751e92466 | ||
|
|
1adb783d4a | ||
|
|
694da4972c | ||
|
|
d4855c01d3 | ||
|
|
951247ebf5 | ||
|
|
33e8916c4d | ||
|
|
ee436650fa | ||
|
|
093cc976f0 | ||
|
|
f6f528b63d | ||
|
|
bb454f54ca | ||
|
|
236cfb71bc | ||
|
|
e2c8632d30 | ||
|
|
01f272207d | ||
|
|
e7f2b8d5f1 | ||
|
|
e37b915896 | ||
|
|
dac401c47f | ||
|
|
4330c13499 | ||
|
|
efd522a575 | ||
|
|
a8240c6fee | ||
|
|
dee27d91ce | ||
|
|
4a356b6d94 | ||
|
|
e341da9924 | ||
|
|
44b689943b | ||
|
|
7b402a10e0 | ||
|
|
7372f275d2 | ||
|
|
8cdf8ab70b | ||
|
|
7c38536059 | ||
|
|
c61d4d6f08 | ||
|
|
1081a1dba8 | ||
|
|
6e23283014 | ||
|
|
d0061dc517 | ||
|
|
0601a9d376 | ||
|
|
6a757cc1c7 | ||
|
|
3fa428b3a6 | ||
|
|
2db3565409 | ||
|
|
cba0eaf123 | ||
|
|
116279b917 | ||
|
|
439edfc611 | ||
|
|
bf8139b4db | ||
|
|
b3539b8c22 | ||
|
|
143a1194ad | ||
|
|
37d29b3277 | ||
|
|
92eaf939b5 | ||
|
|
d08ac447aa | ||
|
|
c3cb1b9a4e |
+24
-6
@@ -19,7 +19,7 @@ ROOT_PATH=
|
||||
# streams every other module to its backend. This is that FIXED map, slug=http://service:port,
|
||||
# comma-separated; the upstream never comes from a request. A slug left out answers 404. Empty for
|
||||
# the standalone stack in docker-compose.yml (Atrium alone, at /atrium).
|
||||
# FRONTDOOR_UPSTREAMS=galena=http://galena-backend:8000,sygna=http://sygna-backend:8000,counsel=http://counsel-backend:8000,compass=http://compass-backend:8000,insider=http://insider-backend:8000
|
||||
# FRONTDOOR_UPSTREAMS=galena=http://galena-backend:8000,sygna=http://sygna-backend:8000,counsel=http://counsel-backend:8000,insider=http://insider-backend:8000,arbiter=http://arbiter-backend:8000,lexicon=http://lexicon-backend:8000,agora=http://agora-backend:8000,parafa=http://parafa-backend:8000,scribe=http://scribe-backend:8000,workflow=http://workflow-backend:8000
|
||||
FRONTDOOR_UPSTREAMS=
|
||||
|
||||
# ── Database ─────────────────────────────────────────────────────────────────
|
||||
@@ -100,14 +100,28 @@ IDENTITY_MIGRATOR_ROLES=
|
||||
# role in IDENTITY_READER_ROLES reads the list and the policy; these two name the modules that need
|
||||
# more, and each takes effect only for a role that is also in the matching identity list above.
|
||||
# key readers: runtime roles that may READ THE API KEYS (a module that calls a model itself,
|
||||
# e.g. compass_app); removing one here and migrating revokes it
|
||||
# e.g. arbiter_app); removing one here and migrating revokes it
|
||||
# migrators: migrators that may REFERENCE model_provider from their own tables (e.g.
|
||||
# compass_migrator); the first is also the one the one-shot import door is opened for
|
||||
# Empty standalone. The deploy kit's env/atrium.env.example names Compass's two.
|
||||
# arbiter_migrator); the first is also the one the one-shot import door is opened for
|
||||
# Empty standalone. The deploy kit's env/atrium.env.example names Arbiter's two.
|
||||
MODEL_PROVIDER_KEY_READER_ROLES=
|
||||
MODEL_PROVIDER_MIGRATOR_ROLES=
|
||||
# The modules' runtime roles that take part in the shared event log `module_event` (dredd-core
|
||||
# 0.20.0, revision 0011): SELECT + INSERT under row-level security, each only once it is also in
|
||||
# IDENTITY_READER_ROLES. The hub's own runtime role always takes part. Empty standalone.
|
||||
MODULE_EVENT_EMITTER_ROLES=
|
||||
# The READER tier (dredd-core 0.23.0): runtime roles that may only SELECT the log (a module that
|
||||
# reports on it and says nothing). A role is an emitter or a reader, never both. Empty standalone.
|
||||
MODULE_EVENT_READER_ROLES=
|
||||
# The shared counterparty register (dredd-core 0.21.0, revision 0012): the modules' runtime roles
|
||||
# that WRITE it (Sygna, Galena), the ones that only READ it (Agora, Parafa), and the migrators that move their own counterparties in (import door) and point foreign keys
|
||||
# at it. Each only once also joined (IDENTITY_READER_ROLES / IDENTITY_MIGRATOR_ROLES). The hub's own
|
||||
# runtime role holds nothing there. Empty standalone.
|
||||
COUNTERPARTY_WRITER_ROLES=
|
||||
COUNTERPARTY_READER_ROLES=
|
||||
COUNTERPARTY_MIGRATOR_ROLES=
|
||||
# The platform's model-provider secret: provider API keys are encrypted under a key derived from it,
|
||||
# by the hub and by every opted-in module alike, so it must be IDENTICAL in Compass's env. Never in
|
||||
# by the hub and by every opted-in module alike, so it must be IDENTICAL in the opted-in modules' env. Never in
|
||||
# the database, never logged; never regenerate it once keys are stored (they become unreadable).
|
||||
# Generate with: python -c "import secrets; print(secrets.token_urlsafe(48))"
|
||||
MODEL_PROVIDER_SECRET=
|
||||
@@ -128,7 +142,7 @@ CORS_ALLOW_ORIGINS=
|
||||
# ── Bootstrap admin (seed) ───────────────────────────────────────────────────
|
||||
BOOTSTRAP_ADMIN_EMAIL=admin@example.com
|
||||
BOOTSTRAP_ADMIN_PASSWORD=admin12345
|
||||
# The seed also puts the Dredd family (Galena, Sygna, Counsel Scorecard, Compass, Insider) into the module
|
||||
# The seed also puts the Dredd family (Galena, Sygna, Counsel Scorecard, Insider, Arbiter, Lexicon, Agora, Parafa, Scribe, Workflow) into the module
|
||||
# catalog — once per instance, without addresses; add those under Administration → Modules.
|
||||
|
||||
# ── App tokens ───────────────────────────────────────────────────────────────
|
||||
@@ -144,3 +158,7 @@ APP_TOKEN_RENEW_AFTER_HOURS=12
|
||||
OTEL_ENABLED=false
|
||||
OTEL_SERVICE_NAME=atrium-backend
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
|
||||
|
||||
# The Archive's technical account (Atrium#53): the fixed id the seed creates it under, to
|
||||
# be granted user access in Parafa, Workflow, Agora and Arbiter only. Keep the default.
|
||||
ARCHIVE_READER_ID=a2c41e00-0000-4000-8000-000000000053
|
||||
|
||||
+34
-19
@@ -1,5 +1,19 @@
|
||||
name: CI
|
||||
on: [push, pull_request]
|
||||
on:
|
||||
push:
|
||||
# main only: a branch is tested through its pull request (a push of many branches at once
|
||||
# must not flood the runners)
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
# dredd-core is private on the Haski Gitea, and so is every repository this workflow may fetch.
|
||||
# All git traffic to the Gitea host (pip installing dredd-core from requirements, above all) goes
|
||||
# through the read-only bot haski-reader: its token is the Haski org secret DREDD_CORE_TOKEN,
|
||||
# which Gitea masks in logs. Docker builds get the same token as a BuildKit secret instead.
|
||||
env:
|
||||
GIT_CONFIG_COUNT: "1"
|
||||
GIT_CONFIG_KEY_0: url.http://x-access-token:${{ secrets.DREDD_CORE_TOKEN }}@77.216.148.202:3000/.insteadOf
|
||||
GIT_CONFIG_VALUE_0: http://77.216.148.202:3000/
|
||||
|
||||
jobs:
|
||||
backend:
|
||||
@@ -43,17 +57,6 @@ jobs:
|
||||
-- EXISTS then no-ops, so the least-privilege migrator never needs extension rights.
|
||||
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
|
||||
SQL
|
||||
- name: Authenticate to dredd-core
|
||||
# dredd-core is a PRIVATE repo, so the `git+https://` requirement cannot be fetched
|
||||
# anonymously — without this step `pip install` fails with a git auth prompt/404.
|
||||
# The rewrite injects the token for that ONE repo URL; every other GitHub URL is untouched,
|
||||
# and the secret stays out of the requirements file and the pip log.
|
||||
# Add the secret under Settings → Secrets and variables → Actions → DREDD_CORE_TOKEN
|
||||
# (a fine-grained PAT with read-only Contents access on Alpaq92/dredd-core).
|
||||
env:
|
||||
TOKEN: ${{ secrets.DREDD_CORE_TOKEN }}
|
||||
run: |
|
||||
git config --global url."https://x-access-token:${TOKEN}@github.com/Alpaq92/dredd-core".insteadOf "https://github.com/Alpaq92/dredd-core"
|
||||
- name: Install deps
|
||||
working-directory: backend
|
||||
run: pip install -r requirements-dev.txt
|
||||
@@ -62,7 +65,9 @@ jobs:
|
||||
run: alembic upgrade head && python -m app.identity_grants && python -m app.seed
|
||||
- name: Tests
|
||||
working-directory: backend
|
||||
run: pytest -q --cov=app --cov-report=term-missing
|
||||
# The deploy kit's tests (tests/test_deploy_*.py) run once, in deploy-kit-tests: they drive
|
||||
# init.sh/push.sh on files and need no database, so they need not run per Postgres version.
|
||||
run: pytest -q --cov=app --cov-report=term-missing --ignore-glob='tests/test_deploy_*.py'
|
||||
- name: Console syntax
|
||||
# A duplicate `const` inside one function silently stops the whole file parsing, so every
|
||||
# function after it disappears — and the symptom is a blank screen with no console error.
|
||||
@@ -165,11 +170,6 @@ jobs:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-python@v6
|
||||
with: { python-version: "3.12" }
|
||||
- name: Authenticate to dredd-core
|
||||
env:
|
||||
TOKEN: ${{ secrets.DREDD_CORE_TOKEN }}
|
||||
run: |
|
||||
git config --global url."https://x-access-token:${TOKEN}@github.com/Alpaq92/dredd-core".insteadOf "https://github.com/Alpaq92/dredd-core"
|
||||
- name: Install deps
|
||||
working-directory: backend
|
||||
run: pip install -r requirements-dev.txt
|
||||
@@ -229,7 +229,7 @@ jobs:
|
||||
run: alembic upgrade head && python -m app.identity_grants && python -m app.seed
|
||||
- name: Tests (as atrium_app)
|
||||
working-directory: backend
|
||||
run: pytest -q
|
||||
run: pytest -q --ignore-glob='tests/test_deploy_*.py' # those run in deploy-kit-tests
|
||||
- name: Managed check, as the runtime role and as the migrator
|
||||
# `--identity-tier owner`, not `writer`: Atrium's migrator OWNS the shared schema, so
|
||||
# measuring it against the writer tier reports an "escalation" on a perfectly correct
|
||||
@@ -301,6 +301,21 @@ jobs:
|
||||
# docker-compose.yml, the Dockerfile (and its front door) or db/init — and the private dredd-core install
|
||||
# inside the image is exactly what broke unnoticed before. This job runs the real stack, the way a
|
||||
# deployer does. (Modelled on Sygna's compose-smoke job, which proved the approach.)
|
||||
deploy-kit-tests:
|
||||
# The deploy kit's own tests: each runs init.sh / push.sh (a bash-heavy ~10 s apiece) against
|
||||
# files, no database. Once, not per Postgres version, and spread over every core.
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions/setup-python@v6
|
||||
with: { python-version: "3.12" }
|
||||
- name: Install deps
|
||||
working-directory: backend
|
||||
run: pip install -r requirements-dev.txt
|
||||
- name: Deploy kit tests
|
||||
working-directory: backend
|
||||
run: pytest -q -n auto tests/test_deploy_*.py
|
||||
|
||||
compose-smoke:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
name: deploy box
|
||||
# Co niedzielę o 22:00 (czas polski) i na żądanie aktualizuje rodzinę Dredd na
|
||||
# deploy@185.252.234.165 (/srv/atrium, projekt Compose dredd-family) z gałęzi main na Gitei, krokami
|
||||
# deploy/README.md §11 "Updates":
|
||||
# git pull + submodule update -> preflight.sh -> docker compose build -> push.sh -> up -d
|
||||
#
|
||||
# Bezpieczniki:
|
||||
# - tryb "dry-run" (domyślny) niczego nie zmienia: pokazuje, co by weszło, i uruchamia
|
||||
# push.sh --dry-run na obecnym checkoucie;
|
||||
# - przed buildem zrzut całej bazy (pg_dumpall, ~4 GB) do ~/predeploy/, trzymane 2 ostatnie;
|
||||
# zrzut nie startuje, jeśli po nim zostałoby mniej niż 15 GB wolnego miejsca;
|
||||
# - tylko fast-forward: jeśli checkout na serwerze rozjechał się z main, job staje;
|
||||
# - każdy krok przerywa przy błędzie (set -e); push.sh zatrzymuje się, zanim cokolwiek
|
||||
# zrestartuje, a działające kontenery zostają na starych obrazach do `up -d`;
|
||||
# - skrypt trafia na serwer jako plik i działa ze stdin = /dev/null: żadne polecenie w nim nie
|
||||
# może "zjeść" reszty skryptu (tak 30.11 `docker compose exec` przerwał nocny przebieg po zrzucie).
|
||||
#
|
||||
# Sekret DEPLOY_SSH_KEY_B64: klucz prywatny w base64, jedna linia (Gitea maskuje w logach tylko
|
||||
# sekrety jednoliniowe); klucz przyjmowany przez serwer tylko z IP Gitei (from= w authorized_keys).
|
||||
# Zmienna DEPLOY_KNOWN_HOSTS: klucz hosta serwera (ssh-keyscan), żeby nikt się nie podszył.
|
||||
on:
|
||||
# Co tydzień: niedziela 22:00 czasu polskiego (prawdziwe wdrożenie, włączone na prośbę 2026-11-30).
|
||||
schedule:
|
||||
- cron: "CRON_TZ=Europe/Warsaw 0 22 * * 0"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
mode:
|
||||
description: "dry-run = tylko pokaż i sprawdź; deploy = wdroż"
|
||||
required: true
|
||||
default: dry-run
|
||||
type: choice
|
||||
options: [dry-run, deploy]
|
||||
|
||||
concurrency:
|
||||
group: deploy-box
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: deploy # osobny runner: wdrozenie nie czeka w kolejce CI
|
||||
timeout-minutes: 180
|
||||
env:
|
||||
BOX: deploy@185.252.234.165
|
||||
MODE: ${{ github.event_name == 'schedule' && 'deploy' || github.event.inputs.mode || 'dry-run' }}
|
||||
steps:
|
||||
- name: SSH to the box
|
||||
env:
|
||||
KEY_B64: ${{ secrets.DEPLOY_SSH_KEY_B64 }}
|
||||
KNOWN: ${{ vars.DEPLOY_KNOWN_HOSTS }}
|
||||
run: |
|
||||
mkdir -p ~/.ssh && chmod 700 ~/.ssh
|
||||
printf '%s' "$KEY_B64" | base64 -d > ~/.ssh/deploy && chmod 600 ~/.ssh/deploy
|
||||
printf '%s\n' "$KNOWN" > ~/.ssh/known_hosts
|
||||
ssh -i ~/.ssh/deploy -o BatchMode=yes "$BOX" 'echo "connected to $(hostname)"' </dev/null
|
||||
|
||||
- name: Copy the update script to the box
|
||||
run: |
|
||||
ssh -i ~/.ssh/deploy -o BatchMode=yes "$BOX" 'cat > ~/deploy-box.sh && chmod 700 ~/deploy-box.sh' <<'REMOTE'
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
MODE=$1
|
||||
GITEA=http://77.216.148.202:3000/Haski/Atrium.git
|
||||
cd /srv/atrium
|
||||
[ "$(git remote get-url origin)" = "$GITEA" ] || git remote set-url origin "$GITEA"
|
||||
git fetch --quiet --no-recurse-submodules origin main
|
||||
BEFORE=$(git rev-parse HEAD); TARGET=$(git rev-parse origin/main)
|
||||
echo "box: ${BEFORE:0:7} gitea main: ${TARGET:0:7}"
|
||||
if ! git merge-base --is-ancestor "$BEFORE" "$TARGET"; then
|
||||
echo "::error::the box's checkout is not an ancestor of main - refusing (fix by hand)"; exit 1
|
||||
fi
|
||||
echo "--- commits to deploy:"; git log --oneline "$BEFORE..$TARGET" | head -40
|
||||
echo "--- module pins that move:"; git diff "$BEFORE" "$TARGET" -- deploy/modules | grep '^[-+]Subproject' || echo "(none)"
|
||||
|
||||
if [ "$MODE" != deploy ]; then
|
||||
echo "--- dry run: push.sh --dry-run on the current checkout"
|
||||
cd deploy && ./push.sh --dry-run
|
||||
echo "dry run done, nothing changed"; exit 0
|
||||
fi
|
||||
if [ "$BEFORE" = "$TARGET" ]; then echo "already at main - nothing to deploy"; exit 0; fi
|
||||
|
||||
TS=$(date +%Y%m%d-%H%M)
|
||||
LOG=~/build-$TS.log
|
||||
echo "--- full log on the box: $LOG"
|
||||
exec > >(tee -a "$LOG") 2>&1
|
||||
|
||||
echo "--- 1/6 database dump (before anything changes)"
|
||||
mkdir -p ~/predeploy
|
||||
LAST=$(ls -1t ~/predeploy/dredd-*.sql.gz 2>/dev/null | head -1 || true)
|
||||
NEED_KB=$(( ${LAST:+$(du -k "$LAST" | cut -f1)} + 0 ))
|
||||
FREE_KB=$(df -Pk ~ | awk 'NR==2 {print $4}')
|
||||
if [ $(( FREE_KB - NEED_KB )) -lt $(( 15 * 1024 * 1024 )) ]; then
|
||||
echo "::error::not enough disk for a dump: $((FREE_KB/1024/1024)) GB free, last dump $((NEED_KB/1024/1024)) GB, 15 GB must stay free"; exit 1
|
||||
fi
|
||||
(cd deploy && docker compose exec -T postgres pg_dumpall -U postgres </dev/null) | gzip > ~/predeploy/dredd-$TS.sql.gz
|
||||
ls -1t ~/predeploy/dredd-*.sql.gz | tail -n +3 | xargs -r rm -f
|
||||
echo "dump: $(du -h ~/predeploy/dredd-$TS.sql.gz | cut -f1)"
|
||||
|
||||
echo "--- 2/6 fetch the code (rollback: git -C /srv/atrium checkout ${BEFORE:0:7} && git submodule update)"
|
||||
git merge --ff-only --quiet origin/main
|
||||
git submodule sync --quiet --recursive
|
||||
git submodule update --init --recursive
|
||||
git submodule status
|
||||
|
||||
cd deploy
|
||||
echo "--- 3/6 preflight"; bash preflight.sh
|
||||
echo "--- 4/6 build"
|
||||
# dredd-core is private: the build fetches it with haski-reader's read-only token, kept on the box
|
||||
export DREDD_CORE_TOKEN=$(cat ~/.config/haski/reader-token)
|
||||
docker compose build
|
||||
unset DREDD_CORE_TOKEN
|
||||
echo "--- 5/6 push (migrations + checks)"; ./push.sh
|
||||
echo "--- 6/6 restart"; docker compose up -d
|
||||
sleep 20
|
||||
docker compose ps --format '{{.Service}}\t{{.Status}}'
|
||||
if docker compose ps --format '{{.Status}}' | grep -q -i -E 'unhealthy|exited|restarting'; then
|
||||
echo "::error::a service is not healthy after the restart"; exit 1
|
||||
fi
|
||||
echo "deployed ${TARGET:0:7}"
|
||||
REMOTE
|
||||
|
||||
- name: Update the box (${{ env.MODE }})
|
||||
run: ssh -i ~/.ssh/deploy -o BatchMode=yes -o ServerAliveInterval=30 "$BOX" "bash ~/deploy-box.sh $MODE" </dev/null
|
||||
|
||||
- name: Clean up
|
||||
if: always()
|
||||
run: rm -f ~/.ssh/deploy
|
||||
@@ -12,6 +12,7 @@ name: deploy kit
|
||||
# complete.
|
||||
on:
|
||||
push:
|
||||
branches: [main] # main only; branches are tested through their PR
|
||||
paths:
|
||||
- "deploy/**"
|
||||
- ".github/workflows/deploy-kit.yml"
|
||||
|
||||
@@ -16,3 +16,5 @@ certs/
|
||||
# The family deploy kit: real inputs and env files hold secrets (their *.example templates are tracked).
|
||||
deploy/db.env
|
||||
deploy/env/*.env
|
||||
# Parafa's signer (PKCS#12 + passphrase), mounted read-only into parafa-backend: never committed.
|
||||
deploy/parafa-signer/
|
||||
|
||||
+22
-7
@@ -1,15 +1,30 @@
|
||||
[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
|
||||
[submodule "deploy/modules/compass"]
|
||||
path = deploy/modules/compass
|
||||
url = https://github.com/Alpaq92/compass-contract-hub
|
||||
url = ../Sygna.git
|
||||
[submodule "deploy/modules/insider"]
|
||||
path = deploy/modules/insider
|
||||
url = https://github.com/Alpaq92/Insider.git
|
||||
url = ../Insider.git
|
||||
[submodule "deploy/modules/lexicon"]
|
||||
path = deploy/modules/lexicon
|
||||
url = ../Lexicon.git
|
||||
[submodule "deploy/modules/agora"]
|
||||
path = deploy/modules/agora
|
||||
url = ../Agora.git
|
||||
[submodule "deploy/modules/parafa"]
|
||||
path = deploy/modules/parafa
|
||||
url = ../Parafa.git
|
||||
[submodule "deploy/modules/scribe"]
|
||||
path = deploy/modules/scribe
|
||||
url = ../Scribe.git
|
||||
[submodule "deploy/modules/arbiter"]
|
||||
path = deploy/modules/arbiter
|
||||
url = ../Arbiter.git
|
||||
[submodule "deploy/modules/workflow"]
|
||||
path = deploy/modules/workflow
|
||||
url = ../Workflow.git
|
||||
|
||||
@@ -4,9 +4,9 @@ Guidance for Claude Code when working in this repository.
|
||||
|
||||
## What this is
|
||||
|
||||
**Atrium** — the Dredd family's front door: a launcher (the sidebar's *Apps* + the top-bar app
|
||||
switcher), a home page (*Strona główna*: search over the modules, places to start, the figures,
|
||||
your pending access requests and, for an administrator, the platform's state), a **marketplace** of modules (Galena, Sygna, Counsel Scorecard, Compass, Insider) and the
|
||||
**Atrium** — the Dredd family's front door: a launcher (the sidebar's *Apps*), a home page
|
||||
(*Strona główna*: search over the modules, the figures,
|
||||
your pending access requests and, for an administrator, the platform's state), a **marketplace** of modules (Galena, Sygna, Counsel Scorecard, Insider, Arbiter, …; Workflow/`compass` was retired 2026-11-14 — revision `0014` drops its catalogue row and `module_permission` rows; Panorama was taken off the platform in Atrium#53 — its trends are home's `GET /home/trends`, revision `0018` hides its row) and the
|
||||
administration that decides who is offered what. Built on **dredd-core**, the shared substrate of
|
||||
this app family:
|
||||
identity, sessions, auth, the access-control resolver, the org tree, audit and the security
|
||||
@@ -18,7 +18,7 @@ permissive (no copyleft).
|
||||
The core is pinned by tag in `backend/requirements.txt`:
|
||||
|
||||
```
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.15.0
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.21.0
|
||||
```
|
||||
|
||||
It is a **private** repository, so installing it needs a token — see `README.md` for the
|
||||
@@ -46,7 +46,7 @@ in every `env/<app>.env`, and the shipped-on modules' roles in `env/atrium.env`'
|
||||
`IDENTITY_READER_ROLES`/`IDENTITY_MIGRATOR_ROLES`; the first `push.sh` builds it from an empty database
|
||||
(provision every app → Atrium's 0004 → each module's cutover, each with nothing to move) and refuses
|
||||
the half-done shapes by name. `init.sh --standalone` is the explicit opt-out;
|
||||
`deploy/RUNBOOK-one-account.md` only converts an existing standalone box. Compass and **Insider**
|
||||
`deploy/RUNBOOK-one-account.md` only converts an existing standalone box. **Insider**
|
||||
(`deploy/modules/insider`, slug/schema `insider`, subnet 172.30.15.0/24) ship switched off, each under
|
||||
a Compose profile of its own name (`PROFILED` in `init.sh`/`push.sh`); `init.sh --add <module>` lists
|
||||
its roles and turns its profile on (`deploy/RUNBOOK-insider.md`). Insider's optional OCR worker is a
|
||||
@@ -83,17 +83,22 @@ also runs for `current`/`stamp`/`downgrade`/`--sql`.
|
||||
(schema-qualified; standalone in Atrium's own schema), drops the empty local copies a fresh platform's
|
||||
`0001` built (refusing non-empty ones), and applies `model_provider_grants_sql`; `app.identity_grants`
|
||||
re-applies that block on every migrate too. Readers = `IDENTITY_READER_ROLES`; the key opt-in
|
||||
(`MODEL_PROVIDER_KEY_READER_ROLES`, `compass_app`) and the REFERENCES tier
|
||||
(`MODEL_PROVIDER_MIGRATOR_ROLES`, `compass_migrator`) take effect only for roles also in the identity
|
||||
lists, so a box with Compass switched off migrates cleanly. **The import door**
|
||||
(`MODEL_PROVIDER_KEY_READER_ROLES`, `arbiter_app,lexicon_app`) and the REFERENCES tier
|
||||
(`MODEL_PROVIDER_MIGRATOR_ROLES`, `arbiter_migrator`) take effect only for roles also in the identity
|
||||
lists, so a box with Arbiter switched off migrates cleanly. **The import door**
|
||||
(`import_model_providers`, Compass's `0021` moves its rows through it) is a STATE recomputed on every
|
||||
migrate (`import_door_wanted`): open only while a joined importer exists, the shared `model_provider`
|
||||
is empty and some module still holds a `model_provider` of its own; dropped otherwise. Never drop it
|
||||
in a revision — Atrium migrates before Compass in one deploy, so a revision would close it before
|
||||
Compass used it. `MODEL_PROVIDER_SECRET` is ONE value in `env/atrium.env` and `env/compass.env`
|
||||
(init.sh writes both; `--add compass` reuses the hub's); the cipher is Compass's
|
||||
Compass used it. `MODEL_PROVIDER_SECRET` is ONE value in `env/atrium.env`, `env/arbiter.env` and `env/lexicon.env`
|
||||
(init.sh writes them; `--add arbiter`/`--add lexicon` reuse the hub's); the cipher is byte-compatible with Arbiter's
|
||||
`app/provider_keys.py` (Argon2id `derive_key`, salt `dredd.model_provider.v1`, AES-256-GCM,
|
||||
`v1.<nonce>.<ct>`). No admin screen and no Home endpoint yet — that is later UI work.
|
||||
`v1.<nonce>.<ct>`). The administrator writes them on *Dostawcy modeli* (`#/admin/providers`, API `routers/admin_providers.py`). **Home asks through these rows only** (`routers/models.py` → `services/providers.call_target` → `offering` + `api_key`): the request names a model id, never an address, and there is no door for modules — a module that calls a model reads the provider (and, opted in, its key) itself.
|
||||
**Personal keys (dredd-core 0.18.0, revision `0010`).** `model_provider.key_mode` says whose key a call carries: `firm` (the administrator's, `model_provider_key`), `user` (the caller's own, `model_provider_user_key` — the hub's alone, no module tier, not even the key opt-in) or `none`. `0010` runs core's three idempotent steps in order (`model_provider_key_mode_sql`, `create_model_provider_tables`, the grant block via `model_provider_statements`, i.e. 0009's arguments). `call_target` takes the key from `key_for` only, never `api_key`; `(None, "user")` is a 409 `model_provider_user_key_missing` ("add your key"), and `key_source` in the `model.ask` audit row is the mode that paid. A person writes their own key on *Moje klucze modeli* (`#/my-keys`, API `/me/model-keys`, `set_user_key` / `clear_user_key`, shown only as `user_key_prefix`). A `base_url` change, or moving `key_mode` off `user`, deletes every personal key (core).
|
||||
**Module events (dredd-core 0.20.0, revision `0011`; the Compass split's K1).** The shared log `module_event` lives in the identity schema; the hub creates it there (`create_event_tables`, schema-qualified), drops empty local copies of the three event tables (refusing non-empty ones), then `app.identity_grants.event_statements` applies `event_policies_sql(schema)` (RLS: everybody reads, a role inserts only rows whose `source_role` is itself; any other policy dropped) and `event_grants_sql` (SELECT + INSERT for the emitters, nothing else for anybody: append-only). **Emitters = the hub's own runtime role (always; `managed check` holds the writer tier to it) + `MODULE_EVENT_EMITTER_ROLES` filtered to joined identity readers** (`event_emitters`; `galena_app,compass_app` in the deploy kit). Both blocks are authoritative and re-applied on every migrate, so a module listed later gets its tier on its next deploy, and a module NOT listed reaches nothing (its check without `--events` proves it). `dredd_core.events` is imported **lazily** (in `0011` and `identity_grants`): a module-level import would register its models before `0001`'s `create_all` and build local shadows on a fresh install. Standalone the log is Atrium's own in `current_schema()`, with the same policies, and `module_event` joins the runtime sweep's APPEND_ONLY — a later revision re-running the sweep must keep it there. The hub receives nothing (no cursor/receipt tables) and emits nothing yet; it holds the grant because the check requires it. Deploy order: Atrium's `0011` before Galena's `0011` / Compass's `0027` (push.sh migrates atrium first); push.sh checks galena and compass with `--events` and refuses a push whose `env/atrium.env` does not list their runtime role in `MODULE_EVENT_EMITTER_ROLES`. `assert_identity_schema` in the lifespan covers `EVENT_TABLES` too.
|
||||
**Counterparties (dredd-core 0.21.0, revision `0012`; the Compass split's K2).** The platform's one counterparty register (`counterparty`, `counterparty_alias`, `counterparty_contact`) lives in the identity schema; the hub creates it there (`create_counterparty_tables`, schema-qualified), drops empty local copies (refusing non-empty ones), then `app.identity_grants.counterparty_statements` applies `counterparty_grants_sql` and opens or drops the import door. **The hub holds no tier and no counterparty logic** (plan P3): writers = `COUNTERPARTY_WRITER_ROLES` (SELECT, INSERT, UPDATE; never DELETE a counterparty, TRUNCATE nowhere — `sygna_app`; without Sygna, the module that needs counterparties), readers = `COUNTERPARTY_READER_ROLES` (SELECT), migrators = `COUNTERPARTY_MIGRATOR_ROLES` (SELECT + REFERENCES), each filtered to joined roles (`counterparty_tiers`; a role in both runtime lists is a writer). Authoritative and re-applied on every migrate. The door `import_counterparties(...)` (SECURITY DEFINER, insert-only plus filling NULL numbers) is open while `counterparty_door_wanted` sees a module schema still holding a `counterparty` table (Compass before its `0028`) or a `party` table without `counterparty_id` (Sygna before its `0006`); it closes on the next migrate. Standalone `0012` is a no-op (the hub has no counterparties; a standalone module keeps its register in its own schema). `dredd_core.counterparties` is imported lazily, like events. push.sh checks each module with `--counterparties <tier>` from the hub env once its own pin is 0.21.0+, and refuses Sygna/Compass on 0.21.0+ unless both the runtime role (a tier) and the migrator are listed. `assert_identity_schema` covers `COUNTERPARTY_TABLES`.
|
||||
**Route walks go through `dredd_core.routes.iter_routes`** (0.18.1): `_ConsoleUnlessApi` and every route-sweep test. A plain walk over `app.routes` sees no API route from FastAPI 0.15x on.
|
||||
**Only an administrator's ask may switch the model loaded on a `local` provider** (`integrations/model_server.py`): anyone else asking for a different model gets a 409 `model_busy` naming the running model, the console shows it as is, and nothing is loaded or evicted; asking with the loaded model, or loading the first one, is open to everybody. `ensure_loaded` decides again under `LOAD_LOCK`, so a stale read at the door cannot evict (there the refusal arrives as the stream's `error` event). A switch unloads chat models only (`CHAT_TYPES`, `type` from `/api/v0/models`, instance ids from `/api/v1/models`); embedding models stay loaded.
|
||||
|
||||
**Three words for what somebody may do, used verbatim everywhere** — table, API, guard names,
|
||||
audit actions and console copy — because two words for one idea is how a permission model rots:
|
||||
@@ -182,8 +187,8 @@ every module, so it says where a leaked credential was issued and whose audit lo
|
||||
leaked app token that could mint would outlive its own revocation (a token row has no parent).
|
||||
Listing and revoking stay open to any credential, because revoking is how a leak is contained.
|
||||
That endpoint has a **screen**: *Połączone aplikacje / Connected apps* (`viewTokens` in
|
||||
`frontend/app.js`), in the main nav rather than under Administration, because everybody holds their
|
||||
own credentials. It is the family's only one — a console that cannot mint leaves curl as the user's
|
||||
`frontend/app.js`), under *Ustawienia / Settings* — the section everybody has, not Administration —
|
||||
because everybody holds their own credentials. It is the family's only one — a console that cannot mint leaves curl as the user's
|
||||
route, which is exactly what the three modules now have — so keep its two promises: it says out loud
|
||||
that a token authenticates in *every* module, and it shows the secret exactly once, in the reply to
|
||||
the mint (`mutate(..., { reopen })`, never the default close-and-re-render).
|
||||
@@ -231,7 +236,7 @@ dredd-core (installed) Base · NAMING_CONVENTION · UUIDPkMixin · TimestampMi
|
||||
|
||||
backend/app/
|
||||
main.py config.py db.py deps.py errors.py security.py enums.py schemas.py seed.py
|
||||
identity_grants.py (atrium-migrate step: re-applies the shared identity tiers every run)
|
||||
identity_grants.py (atrium-migrate step: re-applies the shared identity, model-provider and event tiers every run)
|
||||
observability.py logging_config.py (db/errors/security/enums are shims)
|
||||
models/ __init__ (re-exports core's AppUser/Session/ModulePermission/AppSetting/AuditLog/
|
||||
Node/PermissionGrant/Favorite next to this app's own models)
|
||||
|
||||
+6
-15
@@ -25,6 +25,7 @@ gate (`backend/scripts/license_gate.py`) fails the build on GPL, AGPL or SSPL.
|
||||
|---|---|---|
|
||||
| [Open Color](https://yeun.github.io/open-color/) | MIT | the colour palette, light and dark |
|
||||
| [Tabler Icons](https://tabler.io/icons) | MIT | outline icon set — path data is **vendored** into `frontend/app.js`'s `ICN` map, never loaded from a CDN, because the console's CSP allows no third-party origins |
|
||||
| [Simple Icons](https://simpleicons.org) | CC0-1.0 | brand logotypes for model families and providers — path data **vendored** into `frontend/app.js`'s `BRAND` map at commit `e451c581` (no per-icon licence in the set's data): `anthropic`, `google` (Google Gemini), `qwen`, `meta`, `mistral` (Mistral AI), `openrouter`. OpenAI is not in the set, Bielik neither — those keep a monogram. The marks remain their owners' trademarks; they only name the vendor a model comes from |
|
||||
| [Inter](https://rsms.me/inter/) | SIL OFL 1.1 | the console font, `frontend/ui/v1/InterVariable.woff2` beside its licence (`LICENSE-Inter.txt`), served from this origin |
|
||||
| [legalwork](https://github.com/eigenweltlabs/legalwork) | MIT | the look: colour, shape, type and motion values read from its code (HEAD `8255eba9`) into `frontend/ui/v1/tokens.css`; no legalwork code is included |
|
||||
|
||||
@@ -44,18 +45,8 @@ The least-privilege database model (`app` DML / `migrator` DDL) follows it.
|
||||
## The platform kit (`deploy/`)
|
||||
|
||||
Everything above is Atrium itself. The deploy kit in `deploy/` also builds and runs the family's
|
||||
other modules from their own repositories, under their own licences, and one of them is the
|
||||
exception to "every shipped dependency is permissive": **Compass**'s image carries its
|
||||
contract-analysis engine, which reads PDFs with **PyMuPDF, AGPL-3.0**.
|
||||
|
||||
The platform accepts it on these terms (`deploy/ONBOARDING-compass.md` §3): the engine runs as a
|
||||
separate process behind a JSON-file boundary and is never imported (Compass's ADR-005, proved by its
|
||||
install-closure test); Compass's licence gate allows PyMuPDF on the engine path only; and the Compass
|
||||
module offers the source of the exact engine build it runs, as AGPL-3.0 §13 asks of software people
|
||||
use over a network. That build is named by `ENGINE_COMMIT`, which `deploy/compose.yaml` stamps into
|
||||
the image and `deploy/push.sh` checks against the checkout. Compass ships **off** (Compose profile
|
||||
`compass`): a deployment that never switches it on ships no AGPL code.
|
||||
|
||||
| Project | License | Where |
|
||||
|---|---|---|
|
||||
| [PyMuPDF](https://pymupdf.readthedocs.io) | AGPL-3.0 (or Artifex's commercial licence) | Compass's analysis engine, a separate process in Compass's image — not in Atrium |
|
||||
other modules from their own repositories, under their own licences. None of them ships copyleft
|
||||
code today. Compass's image used to carry a contract-analysis engine that reads PDFs with PyMuPDF
|
||||
(AGPL-3.0), with a source offer; its revision 0030 dropped that engine, and Workflow (Compass) itself
|
||||
was retired on 2026-11-14 and left the kit. Arbiter's image, which took over the
|
||||
analysis queue, carries no engine either (`ENGINE_PYTHON` empty: orders run on a workstation).
|
||||
|
||||
@@ -12,8 +12,8 @@ Atrium is where people in the organisation find and open the family's applicatio
|
||||
app launcher and Marketplace work in Google Workspace — and where an administrator decides who is
|
||||
offered what.
|
||||
|
||||
- The sidebar's **Apps** section and the **app switcher** in the top bar list the modules you can
|
||||
open. **Home** has one search box over the modules, places to start, *At a glance* (your numbers
|
||||
- The sidebar's **Apps** section lists the modules you can open. **Home** has one search box over
|
||||
the modules, *At a glance* (your numbers
|
||||
and 14-day charts; the platform's for an administrator), your pending access requests and, for an
|
||||
administrator, the platform's state (module counts and health checks). A module is a path on this
|
||||
same origin, so opening one replaces Atrium in this tab by default (a new tab instead is an
|
||||
@@ -65,7 +65,7 @@ unit, resolved through dredd-core's authz, so policy overlays apply.
|
||||
> standalone deployment, including exactly what happens to its four `admin@example.com` rows.
|
||||
|
||||
The seed puts the family in the catalog — **Galena**, **Sygna**, **Counsel Scorecard** and
|
||||
**Compass** (coming soon) — without addresses: an installation decides where it serves its modules,
|
||||
the modules that joined later — without addresses: an installation decides where it serves its modules,
|
||||
so an administrator sets each address under *Modules → Manage* and the module then appears
|
||||
in everyone's launcher. On the standard layout that address is this origin plus the module's path
|
||||
(`http://<host>/galena`) — an ordinary absolute URL, which is why nothing about the address gates
|
||||
@@ -76,7 +76,7 @@ changes when the family shares a host.
|
||||
| Who | Endpoints (under `/api/v1`) |
|
||||
|---|---|
|
||||
| anyone | `GET /health` · `POST /auth/login` · `POST /auth/logout` |
|
||||
| any signed-in user | `GET /auth/me` · `GET /launcher` · `GET /marketplace?q=&category=` · `GET /marketplace/{slug}` · `POST /marketplace/{slug}/requests` · `GET /me/access-requests` · `GET /config` · `GET /users` · `POST /me/password` · `GET/POST /me/tokens` · `DELETE /me/tokens/{id}` · `POST /me/modules/{slug}/tokens` (an app token for a module — minting lives only here, because no module holds `INSERT` on `session`) · the org tree, filtered to units you can read: `GET /tree/containers` · `GET /nodes/{id}/children` |
|
||||
| any signed-in user | `GET /auth/me` · `GET /launcher` · `GET /marketplace?q=&category=` · `GET /marketplace/{slug}` · `POST /marketplace/{slug}/requests` · `GET /me/access-requests` · `GET /config` · `GET /users` (names and email addresses; who holds which tier is told to an administrator only) · `POST /me/password` · `GET/POST /me/tokens` · `DELETE /me/tokens/{id}` · `POST /me/modules/{slug}/tokens` (an app token for a module — minting lives only here, because no module holds `INSERT` on `session`) · the org tree, filtered to units you can read: `GET /tree/containers` · `GET /nodes/{id}/children` |
|
||||
| administrators | `POST /users` · `POST /users/{id}/deactivate\|reactivate` · `POST /users/{id}/administrator` (the platform-wide tier; refuses to remove the last one) · `GET/POST /admin/modules` · `GET/PATCH/DELETE /admin/modules/{slug}` · `GET/POST /admin/modules/{slug}/moderators` · `DELETE /admin/modules/{slug}/moderators/{user_id}` · `POST /admin/modules/{slug}/assignments` · `DELETE /admin/modules/{slug}/assignments/{id}` · `POST /admin/modules/{slug}/probe` · `GET /admin/access-requests?status=` · `POST /admin/access-requests/{id}/approve\|decline` · `GET/PUT /admin/settings` · `GET /admin/overview` · `GET /admin/audit?action=` |
|
||||
| unit managers (and administrators) | `POST /nodes` (a top-level workspace: administrators only) · `DELETE /nodes/{id}` · `GET/PUT /nodes/{id}/grants` · `DELETE /nodes/{id}/grants/{user_id}` |
|
||||
|
||||
@@ -92,8 +92,8 @@ code, latency and the `version` field of the family's `/api/v1/health` JSON. Eve
|
||||
cookie sessions, an append-only audit log enforced by database grants, RFC 9457 Problem Details
|
||||
errors, opt-in OpenTelemetry, and a **no-build vanilla-JS console** (Open Color palette, Tabler
|
||||
icons, light/dark theme, two languages). Shipped with Docker Compose, no reverse proxy: the backend is its own edge. Apache-2.0, and CI
|
||||
refuses any GPL/AGPL/SSPL dependency in Atrium itself. The deploy kit can also run Compass, whose
|
||||
analysis engine is AGPL-3.0 in a separate process — see [`CREDITS.md`](CREDITS.md#the-platform-kit-deploy).
|
||||
refuses any GPL/AGPL/SSPL dependency in Atrium itself. No image in the deploy kit ships copyleft code either —
|
||||
see [`CREDITS.md`](CREDITS.md#the-platform-kit-deploy).
|
||||
|
||||
## dredd-core
|
||||
|
||||
@@ -102,7 +102,7 @@ writer, the security primitives, the shared enums and error types, and the engin
|
||||
factories all come from one installed package. `backend/requirements.txt` pins it by tag:
|
||||
|
||||
```
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.15.0
|
||||
dredd-core @ git+https://github.com/Alpaq92/dredd-core@v0.21.0
|
||||
```
|
||||
|
||||
The app-side files that used to hold that code (`services/auth.py`, `services/authz.py`,
|
||||
@@ -168,7 +168,7 @@ The API is served under `/api/v1`, with OpenAPI docs at `/api/v1/docs` — relat
|
||||
app is mounted. The image runs the **front door** (`backend/app/frontdoor.py`,
|
||||
`uvicorn app.frontdoor:outer`), standalone and on the platform alike: `/` redirects to `/atrium/`,
|
||||
Atrium itself is mounted at `/atrium` (so the API is `/atrium/api/v1`), and on the platform every
|
||||
other module path (`/galena`, `/sygna`, `/counsel`, `/compass`, `/insider`) is streamed to that module's backend
|
||||
other module path (`/galena`, `/sygna`, `/counsel`, `/insider`, `/arbiter`, …) is streamed to that module's backend
|
||||
from the fixed `FRONTDOOR_UPSTREAMS` map. Standalone that map is empty and those paths answer 404.
|
||||
The front door refuses encoded separators and dot segments, replaces any inbound `X-Forwarded-*`,
|
||||
caps uploads at 100 MB and answers 502/504 as Problem Details. `ROOT_PATH` must be empty or
|
||||
|
||||
+3
-3
@@ -1,7 +1,7 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
|
||||
# ── build stage: resolve dependencies, including the private one ─────────────
|
||||
# `dredd-core` is a private GitHub repository pinned by tag in requirements.txt, so installing it
|
||||
# `dredd-core` is a private repository on the Haski Gitea pinned by tag in requirements.txt, so installing it
|
||||
# needs two things the runtime image should never have: `git`, and a credential.
|
||||
#
|
||||
# The credential arrives as a BuildKit SECRET, not a build argument. A build arg is baked into the
|
||||
@@ -27,8 +27,8 @@ RUN --mount=type=secret,id=dredd_core_token,required=true \
|
||||
test -s /run/secrets/dredd_core_token \
|
||||
|| { echo "build secret dredd_core_token is empty - export DREDD_CORE_TOKEN" >&2; exit 1; }; \
|
||||
GIT_CONFIG_COUNT=1 \
|
||||
GIT_CONFIG_KEY_0="url.https://x-access-token:$(tr -d '\r\n' < /run/secrets/dredd_core_token)@github.com/.insteadOf" \
|
||||
GIT_CONFIG_VALUE_0="https://github.com/" \
|
||||
GIT_CONFIG_KEY_0="url.http://x-access-token:$(tr -d '\r\n' < /run/secrets/dredd_core_token)@77.216.148.202:3000/.insteadOf" \
|
||||
GIT_CONFIG_VALUE_0="http://77.216.148.202:3000/" \
|
||||
pip install --no-cache-dir --prefix=/install -r requirements.txt
|
||||
|
||||
# ── runtime stage: no git, no credential, no compiler ────────────────────────
|
||||
|
||||
@@ -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) is on the metadata
|
||||
# too, so `0001` builds a local copy of it on a fresh platform install, and it references the local
|
||||
# `model_provider`: it has to go first or that drop fails. Absent on every database `0001` ran on
|
||||
# before 0.18.0, where the `_has` check skips 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,73 @@
|
||||
"""Personal model keys (dredd-core 0.18.0): `model_provider.key_mode` and `model_provider_user_key`.
|
||||
|
||||
A provider now says whose key a call carries — `firm` (the administrator's, as before), `user` (the
|
||||
calling person's own) or `none` — and a person's own key lives in `model_provider_user_key`, a table
|
||||
**only the hub may reach** (no module tier, the key opt-in included; `managed check` reports any
|
||||
grant on it to a module as `key exposure`). This revision, run as the hub's migrator after `0009`,
|
||||
does the 0.18.0 notes' three steps in their order:
|
||||
|
||||
1. `model_provider_key_mode_sql(schema)` — adds `key_mode NOT NULL DEFAULT 'firm'` and its CHECK to
|
||||
the existing `model_provider`, so every provider keeps the firm's key; a no-op on a table built
|
||||
at 0.18.0.
|
||||
2. `create_model_provider_tables(conn, schema)` — creates just `model_provider_user_key` where the
|
||||
other three already exist (`checkfirst`), schema-qualified.
|
||||
3. `model_provider_grants_sql` — with exactly the arguments `0009` passes: both go through
|
||||
`app.identity_grants.model_provider_statements`, which also opens or closes the import door by
|
||||
the same rule, and which `atrium-migrate` re-applies after every upgrade anyway. The block is
|
||||
authoritative, so this is also what gives the new table its tiers (the hub's runtime role
|
||||
only).
|
||||
|
||||
All three are idempotent, so the revision is too: re-running it on an upgraded database changes
|
||||
nothing.
|
||||
|
||||
**On the platform** the schema is the identity schema. **Standalone** it is `current_schema()`, as
|
||||
in `0009`, and the runtime role's sweep (`0003`'s, with the same evidence tables as `0008`) is
|
||||
re-run so `atrium_app` may write the new table.
|
||||
|
||||
No `%` and no `:name` sequence anywhere in the SQL below (``op.execute`` wraps it in ``text()``).
|
||||
"""
|
||||
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
|
||||
from app.identity_grants import model_provider_statements
|
||||
|
||||
revision = "0010"
|
||||
down_revision = "0009"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
# The same evidence tables as 0003 / 0008 / 0009 (a shorter list would re-open them).
|
||||
APPEND_ONLY = ("audit_log",)
|
||||
NO_DELETE: tuple[str, ...] = ()
|
||||
READ_ONLY = ("alembic_version",)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
settings = get_settings()
|
||||
bind = op.get_bind()
|
||||
if not settings.shares_identity:
|
||||
own = bind.execute(text("SELECT current_schema()")).scalar()
|
||||
op.execute(mp.model_provider_key_mode_sql(own))
|
||||
mp.create_model_provider_tables(bind, own)
|
||||
op.execute(runtime_grants_sql(settings.db_app_role, append_only=APPEND_ONLY,
|
||||
no_delete=NO_DELETE, read_only=READ_ONLY))
|
||||
return
|
||||
|
||||
identity = settings.identity_schema
|
||||
op.execute(mp.model_provider_key_mode_sql(identity))
|
||||
mp.create_model_provider_tables(bind, identity)
|
||||
owner = bind.execute(text("SELECT current_user")).scalar()
|
||||
for statement in model_provider_statements(settings, owner, bind):
|
||||
op.execute(statement)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# Not reverted. Dropping `model_provider_user_key` destroys every person's stored key, and
|
||||
# dropping `key_mode` silently turns each `user` provider back into a firm-key one; neither is an
|
||||
# undo anybody wants from a schema downgrade. Remove them by hand if that is really the intent.
|
||||
pass
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Module events (dredd-core 0.20.0, the Compass split's K1): the shared event log and its tiers.
|
||||
|
||||
`dredd_core.events` lets one module say something happened (`document.version_added`,
|
||||
`workflow.approved`, ...) and another act on it later. On the platform the log, `module_event`,
|
||||
lives where `module_permission` does, in the identity schema, and the hub creates it. This revision,
|
||||
run as the hub's migrator (the schema's owner), does the hub's half of the 0.20.0 notes, in their
|
||||
order, and must reach a box BEFORE any module's events revision (Galena's `0011`, Compass's `0027`)
|
||||
— which `deploy/push.sh` already guarantees, Atrium migrating first:
|
||||
|
||||
1. `create_event_tables(conn, <identity schema>)` — `module_event` only, schema-qualified (Atrium's
|
||||
own schema is first on its search_path, so an unqualified CREATE would build a shadow) and
|
||||
idempotent (`checkfirst`). The receiver tables (`module_event_cursor`, `module_event_receipt`)
|
||||
are each RECEIVING module's own; the hub receives nothing, so it has none.
|
||||
2. Local copies of the three event tables in Atrium's own schema are dropped while empty and
|
||||
refused when not — the same rule as `0009`'s. `dredd_core.events` is imported lazily (here and
|
||||
in `app.identity_grants`) so `0001`'s `create_all` never sees its models; the drop is the belt
|
||||
to that brace, should anything ever import it at load time.
|
||||
3. `event_policies_sql(<identity schema>)` — row-level security with exactly two policies: everybody
|
||||
reads, a role inserts only rows whose `source_role` is itself. So `galena_app` cannot write an
|
||||
event claiming to be `compass_app`'s.
|
||||
4. `event_grants_sql` — `SELECT, INSERT` for the emitters and nothing else for anybody, no UPDATE,
|
||||
DELETE or TRUNCATE (the log is append-only). The emitters are the hub's own runtime role (which
|
||||
`managed check` always holds to the writer tier) plus `MODULE_EVENT_EMITTER_ROLES`, filtered to
|
||||
the joined identity readers: both steps go through `app.identity_grants.event_statements`, which
|
||||
`atrium-migrate` re-applies after every upgrade, so a module added to the list later gets its
|
||||
tier on its first deploy without a revision.
|
||||
|
||||
**Standalone** (`IDENTITY_SCHEMA` empty) the log is Atrium's own, in `current_schema()` as in `0009`:
|
||||
created there, given the same two policies (`event_policies_sql()` with no schema), and the runtime
|
||||
role's sweep (`0003`'s) is re-run with `module_event` added to the append-only evidence. Nothing in
|
||||
the hub emits yet; the table is there so both shapes have the same schema. A later revision that
|
||||
re-runs the sweep must keep `module_event` in APPEND_ONLY, or it re-opens the log.
|
||||
|
||||
All of it is idempotent: re-running the revision on an upgraded database changes nothing.
|
||||
|
||||
No `%` and no `:name` sequence anywhere in the SQL below (``op.execute`` wraps it in ``text()``);
|
||||
every name is a validated identifier, rendered.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dredd_core.schema import runtime_grants_sql
|
||||
from sqlalchemy import text
|
||||
|
||||
from alembic import op
|
||||
from app.config import get_settings
|
||||
from app.identity_grants import _literal, _quoted, event_statements
|
||||
|
||||
revision = "0011"
|
||||
down_revision = "0010"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
# 0010's evidence tables plus the standalone event log (a shorter list would re-open them).
|
||||
APPEND_ONLY = ("audit_log", "module_event")
|
||||
NO_DELETE: tuple[str, ...] = ()
|
||||
READ_ONLY = ("alembic_version",)
|
||||
|
||||
# Children first, for the drops: the receipt references the log.
|
||||
_LOCAL_DROP_ORDER = ("module_event_receipt", "module_event_cursor", "module_event")
|
||||
|
||||
|
||||
def _has(bind, table: str) -> bool:
|
||||
return bool(bind.execute(text(
|
||||
"SELECT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace "
|
||||
f"WHERE n.nspname = current_schema() AND c.relname = {_literal(table)} "
|
||||
"AND c.relkind IN ('r', 'p'))")).scalar())
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
from dredd_core import events
|
||||
|
||||
settings = get_settings()
|
||||
bind = op.get_bind()
|
||||
own = bind.execute(text("SELECT current_schema()")).scalar()
|
||||
if not settings.shares_identity:
|
||||
events.create_event_tables(bind, own)
|
||||
op.execute(events.event_policies_sql())
|
||||
op.execute(runtime_grants_sql(settings.db_app_role, append_only=APPEND_ONLY,
|
||||
no_delete=NO_DELETE, read_only=READ_ONLY))
|
||||
return
|
||||
|
||||
identity = settings.identity_schema
|
||||
events.create_event_tables(bind, identity)
|
||||
for table in _LOCAL_DROP_ORDER:
|
||||
if not _has(bind, table):
|
||||
continue
|
||||
if bind.execute(text(f"SELECT EXISTS (SELECT 1 FROM {_quoted(own)}.{table})")).scalar():
|
||||
raise RuntimeError(
|
||||
f"{table} in this schema holds rows, and on the platform the event log lives in "
|
||||
f"{identity}: move them deliberately (they are not discarded here), then migrate again")
|
||||
op.execute(f"DROP TABLE {_quoted(own)}.{table}")
|
||||
owner = bind.execute(text("SELECT current_user")).scalar()
|
||||
for statement in event_statements(settings, owner, bind):
|
||||
op.execute(statement)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# Standalone the log is Atrium's alone: dropped (it is data; take a backup first). On the
|
||||
# platform it is not undone: the shared log is what every module's cursor and receipts point
|
||||
# into, and dropping it would strand them. Downgrade the modules first, then drop it by hand if
|
||||
# that is really the intent.
|
||||
if not get_settings().shares_identity:
|
||||
op.execute("DROP TABLE IF EXISTS module_event")
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Counterparties (dredd-core 0.21.0, the Compass split's K2): the shared register and its tiers.
|
||||
|
||||
`dredd_core.counterparties` is the platform's one register of counterparties (Tobiasz's D10): every
|
||||
module that opts in reads it, nobody copies it, and the link from a contract or a matter to a
|
||||
counterparty stays in the module. On the platform the three tables (`counterparty`,
|
||||
`counterparty_alias`, `counterparty_contact`) live where `app_user` does, in the identity schema, and
|
||||
the hub creates them. The hub holds **no counterparty logic and no tier** on them (the plan's P3:
|
||||
Atrium migrates the schema, writes are for the opt-in roles). This revision, run as the hub's migrator
|
||||
(the schema's owner), must reach a box BEFORE any module's counterparty revision (Sygna's `0006`,
|
||||
Compass's `0028`) — which `deploy/push.sh` already guarantees, Atrium migrating first:
|
||||
|
||||
1. `create_counterparty_tables(conn, <identity schema>)` — schema-qualified (Atrium's own schema is
|
||||
first on its search_path, so an unqualified CREATE would build a shadow) and idempotent.
|
||||
2. Local copies of the three tables in Atrium's own schema are dropped while empty and refused when
|
||||
not, the rule of `0009` and `0011`. `dredd_core.counterparties` is imported lazily (here and in
|
||||
`app.identity_grants`), so `0001`'s `create_all` never sees its models.
|
||||
3. `app.identity_grants.counterparty_statements` — the grant block (writers: SELECT, INSERT, UPDATE,
|
||||
never DELETE a counterparty; readers: SELECT; migrators: SELECT, REFERENCES; nobody else anything)
|
||||
and the import door, open while some module still holds counterparties of its own. The same call
|
||||
runs in `atrium-migrate` after every upgrade, so a module listed later gets its tier on its first
|
||||
deploy without a revision, and the door closes on the migrate after the last module moved in.
|
||||
|
||||
**Standalone** (`IDENTITY_SCHEMA` empty) this is a no-op: a standalone Atrium has no module to share
|
||||
a register with and keeps no counterparties of its own, and a standalone module keeps its register in
|
||||
its own schema (same code, its own revision).
|
||||
|
||||
No `%` and no `:name` sequence anywhere in the SQL below (``op.execute`` wraps it in ``text()``);
|
||||
every name is a validated identifier, rendered.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from alembic import op
|
||||
from app.config import get_settings
|
||||
from app.identity_grants import _literal, _quoted, counterparty_statements
|
||||
|
||||
revision = "0012"
|
||||
down_revision = "0011"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
# Children first, for the drops: aliases and contacts reference the counterparty.
|
||||
_LOCAL_DROP_ORDER = ("counterparty_contact", "counterparty_alias", "counterparty")
|
||||
|
||||
|
||||
def _has(bind, table: str) -> bool:
|
||||
return bool(bind.execute(text(
|
||||
"SELECT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace "
|
||||
f"WHERE n.nspname = current_schema() AND c.relname = {_literal(table)} "
|
||||
"AND c.relkind IN ('r', 'p'))")).scalar())
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
settings = get_settings()
|
||||
if not settings.shares_identity:
|
||||
return
|
||||
from dredd_core import counterparties
|
||||
|
||||
bind = op.get_bind()
|
||||
own = bind.execute(text("SELECT current_schema()")).scalar()
|
||||
identity = settings.identity_schema
|
||||
counterparties.create_counterparty_tables(bind, identity)
|
||||
for table in _LOCAL_DROP_ORDER:
|
||||
if not _has(bind, table):
|
||||
continue
|
||||
if bind.execute(text(f"SELECT EXISTS (SELECT 1 FROM {_quoted(own)}.{table})")).scalar():
|
||||
raise RuntimeError(
|
||||
f"{table} in this schema holds rows, and on the platform the counterparty register "
|
||||
f"lives in {identity}: move them deliberately (they are not discarded here), then "
|
||||
"migrate again")
|
||||
op.execute(f"DROP TABLE {_quoted(own)}.{table}")
|
||||
owner = bind.execute(text("SELECT current_user")).scalar()
|
||||
for statement in counterparty_statements(settings, owner, bind):
|
||||
op.execute(statement)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
# Not undone on the platform: modules' foreign keys (Compass's contract links, Sygna's parties)
|
||||
# point into the shared register, and dropping it would strand them. Downgrade the modules first,
|
||||
# then drop it by hand if that is really the intent. Standalone there is nothing to undo.
|
||||
return
|
||||
@@ -0,0 +1,75 @@
|
||||
"""The catalogue calls Compass "Workflow": rename the seeded entry on a box seeded before.
|
||||
|
||||
Since its revision 0030 Compass does one thing, approval workflows on documents, and the owner
|
||||
presents it as **Workflow**. `app/seed.py` says so for a fresh install, but the seed writes the
|
||||
catalogue ONCE (`_seed.catalog`) and `ADDED_AFTER_FIRST_SEED` only offers a missing slug, so an
|
||||
already-seeded box would show "Compass" for ever. This revision updates that one row.
|
||||
|
||||
Only what people see changes: `name`, `tagline`, `description`, `category`, and `status`
|
||||
goes from `coming_soon` to `live` (the module is deployed and in use). The slug stays
|
||||
`compass` — it is the module's path, its schema and roles, and the `module_permission.module_slug`
|
||||
every grant was written under. And only the row the seed wrote: `name = 'Compass'`. An entry an
|
||||
administrator renamed, or a box without the entry, is left alone, so the revision is idempotent
|
||||
(a second run matches nothing) and never overrides a human's choice. Grants are untouched.
|
||||
|
||||
The values travel as bound parameters of a SQLAlchemy `update`, not as SQL text, so nothing here
|
||||
is scanned for `:name` sequences. Downgrade restores the seeded Compass wording on the same terms.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "0013"
|
||||
down_revision = "0012"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_module = sa.table(
|
||||
"module",
|
||||
sa.column("slug", sa.String),
|
||||
sa.column("name", sa.Text),
|
||||
sa.column("tagline", sa.Text),
|
||||
sa.column("description", sa.Text),
|
||||
sa.column("category", sa.Text),
|
||||
sa.column("status", sa.Text),
|
||||
)
|
||||
|
||||
WORKFLOW = {
|
||||
"name": "Workflow",
|
||||
"status": "live",
|
||||
"category": "Dokumenty",
|
||||
"tagline": "Obiegi akceptacji dokumentów.",
|
||||
"description": (
|
||||
"Workflow prowadzi dokument przez jego akceptujących, etap po etapie: plik przesłany do "
|
||||
"modułu albo dokument z Galeny, etapy z szablonu lub ustawione ręcznie, a każdy krok "
|
||||
"trafia na niezmienialną oś czasu."
|
||||
),
|
||||
}
|
||||
|
||||
COMPASS = {
|
||||
"name": "Compass",
|
||||
"status": "coming_soon",
|
||||
"category": "Umowy",
|
||||
"tagline": "Zarządzanie umowami dla zespołów prawnych.",
|
||||
"description": (
|
||||
"Compass to system zarządzania umowami dla działów prawnych i kancelarii działających "
|
||||
"w wielu jurysdykcjach — z wariantami klauzul i asystą AI. W przygotowaniu."
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _rename(frm: dict, to: dict) -> None:
|
||||
op.get_bind().execute(
|
||||
_module.update()
|
||||
.where(_module.c.slug == "compass", _module.c.name == frm["name"])
|
||||
.values(**to))
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
_rename(COMPASS, WORKFLOW)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
_rename(WORKFLOW, COMPASS)
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Workflow (slug `compass`) is retired: take it out of the catalogue and out of `module_permission`.
|
||||
|
||||
The owner retired the Workflow module on 2026-11-14 (its code stayed in the archived
|
||||
`compass-contract-hub`; Arbiter and the engine moved to `Alpaq92/Arbiter`). `app/seed.py` no longer
|
||||
offers it, but the seed writes the catalogue ONCE, so a box seeded before keeps a launcher tile that
|
||||
points at a path the front door no longer serves. This revision removes what the hub holds for it:
|
||||
|
||||
- the `module` row with slug `compass` — its `module_assignment` and `access_request` rows go with it
|
||||
(both `ON DELETE CASCADE`);
|
||||
- every `module_permission` row for `compass`. That table is the hub's (the shared identity schema on
|
||||
the platform, this schema standalone) and `module_permission.module_slug` is deliberately NOT a
|
||||
foreign key to `module`, so nothing cascades: without this a slug recreated later would silently
|
||||
resurrect the old roster. Exactly what `services/marketplace.delete_module` does through the API.
|
||||
|
||||
Idempotent: a second run, or a box that never had the entry, matches nothing. `module_permission` is
|
||||
addressed through the search_path like everything else here (`atrium, dredd, extensions` for the
|
||||
hub's migrator, which owns the identity schema), and only when `to_regclass` finds it. Each deletion
|
||||
is audited (`module.delete`, `module_permission.revoke_all`, actor = the migration). The `module_event`
|
||||
rows Workflow emitted stay: the event log is append-only history.
|
||||
|
||||
Downgrade does not restore anything: the module is gone, and a roster brought back from nowhere would
|
||||
admit people nobody re-approved. Re-adding Workflow would be a catalogue entry made by an administrator.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "0014"
|
||||
down_revision = "0013"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
SLUG = "compass"
|
||||
|
||||
_module = sa.table("module", sa.column("id", sa.Uuid), sa.column("slug", sa.String))
|
||||
_permission = sa.table("module_permission", sa.column("module_slug", sa.String))
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
from app.models import AuditLog
|
||||
|
||||
bind = op.get_bind()
|
||||
module_id = bind.execute(sa.select(_module.c.id).where(_module.c.slug == SLUG)).scalar()
|
||||
removed = 0
|
||||
if bind.execute(sa.text("SELECT to_regclass('module_permission') IS NOT NULL")).scalar():
|
||||
removed = bind.execute(_permission.delete().where(_permission.c.module_slug == SLUG)).rowcount
|
||||
if module_id is not None:
|
||||
bind.execute(_module.delete().where(_module.c.id == module_id))
|
||||
# Core inserts on the model's table, so its Python-side defaults (id, timestamp) apply exactly as
|
||||
# they do for `dredd_core.audit.record`; actor_id NULL = the system.
|
||||
audit = AuditLog.__table__
|
||||
if module_id is not None:
|
||||
bind.execute(audit.insert().values(
|
||||
actor_id=None, action="module.delete", entity_type="module", entity_id=module_id,
|
||||
detail=f"{SLUG} (Workflow retired, revision 0014)", result="ok"))
|
||||
if removed:
|
||||
bind.execute(audit.insert().values(
|
||||
actor_id=None, action="module_permission.revoke_all", entity_type="module_permission",
|
||||
detail=f"{SLUG} ({removed})", result="ok"))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
pass
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Skills and agents: seven tables in Atrium's own schema, and frozen versions the runtime cannot rewrite.
|
||||
|
||||
The tables are `app/models/skills.py`'s. `0001` builds from the live metadata, so on a fresh database
|
||||
they already exist and the `checkfirst` create is a no-op; on a database migrated before this
|
||||
revision it creates them. Their foreign keys to `app_user` are rendered unqualified and resolve
|
||||
through the search_path — to the shared identity schema on a platform (where `0004` dropped the local
|
||||
copy, and on a fresh platform install `0004`'s metadata-driven repoint already moved them), to
|
||||
Atrium's own schema standalone.
|
||||
|
||||
Then the grants, in two steps:
|
||||
|
||||
1. `runtime_grants_sql` with the same evidence tables as `0003` / `0008` / `0009`, `read_only`
|
||||
explicit (see 0008), so the runtime role gets its DML on the new tables.
|
||||
2. A separate `REVOKE UPDATE, DELETE, TRUNCATE` on the four version tables — `skill_version`,
|
||||
`skill_file`, `agent_version`, `agent_version_skill`. A version is frozen: changing content is a
|
||||
new version, never an edit, and an agent pins the exact version it was built on. Not through
|
||||
`read_only`, because that takes INSERT too, and inserting a version is the one thing the runtime
|
||||
does to these tables. The block then verifies, and raises if the runtime role still holds UPDATE
|
||||
(table- or column-level), DELETE or TRUNCATE some other way (PUBLIC, an inherited role).
|
||||
|
||||
**A later revision that re-runs `runtime_grants_sql` re-opens these tables** — its
|
||||
`GRANT ... ON ALL TABLES` hands UPDATE and DELETE back. Such a revision must run
|
||||
`immutable_versions_sql` again after it (copy the block; revisions are not importable).
|
||||
|
||||
The identity rows (`skill`, `agent`) and `publish_request` stay mutable: scope, status and
|
||||
`current_version_id` move through publication and archiving.
|
||||
|
||||
No `%` and no `:name` sequence in the SQL below (``op.execute`` wraps it in ``text()``); the role is a
|
||||
validated identifier, rendered.
|
||||
|
||||
Downgrade drops the seven tables, children first (`drop_all` drops the `use_alter` cycle constraints
|
||||
first). The grants die with them.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dredd_core import Base
|
||||
from dredd_core.schema import runtime_grants_sql
|
||||
|
||||
from alembic import op
|
||||
from app.config import get_settings
|
||||
from app.identity_grants import _literal, _quoted
|
||||
from app.models import (
|
||||
Agent,
|
||||
AgentVersion,
|
||||
AgentVersionSkill,
|
||||
PublishRequest,
|
||||
Skill,
|
||||
SkillFile,
|
||||
SkillVersion,
|
||||
)
|
||||
|
||||
revision = "0015"
|
||||
down_revision = "0014"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
# The same evidence tables as 0011 (see 0008's note: a shorter list would re-open them). `module_event`
|
||||
# is skipped where it does not exist (on a platform it lives in the identity schema, not here).
|
||||
APPEND_ONLY = ("audit_log", "module_event")
|
||||
NO_DELETE: tuple[str, ...] = ()
|
||||
READ_ONLY = ("alembic_version",)
|
||||
|
||||
# Parents first, for the create; reversed for the drop.
|
||||
_TABLES = [Skill.__table__, SkillVersion.__table__, SkillFile.__table__, Agent.__table__,
|
||||
AgentVersion.__table__, AgentVersionSkill.__table__, PublishRequest.__table__]
|
||||
|
||||
#: Insert and read only: a version is never edited or removed by the runtime.
|
||||
IMMUTABLE = ("skill_version", "skill_file", "agent_version", "agent_version_skill")
|
||||
|
||||
|
||||
def immutable_versions_sql(app_role: str) -> str:
|
||||
"""REVOKE UPDATE/DELETE/TRUNCATE on the version tables from `app_role`, then prove it holds."""
|
||||
role, role_lit = _quoted(app_role), _literal(app_role)
|
||||
tables = ", ".join(IMMUTABLE)
|
||||
names = ", ".join(f"'{t}'" for t in IMMUTABLE)
|
||||
return f"""
|
||||
DO $$
|
||||
DECLARE
|
||||
t text;
|
||||
BEGIN
|
||||
REVOKE UPDATE, DELETE, TRUNCATE ON {tables} FROM {role};
|
||||
FOREACH t IN ARRAY ARRAY[{names}] LOOP
|
||||
IF has_table_privilege({role_lit}, quote_ident(t), 'UPDATE')
|
||||
OR has_any_column_privilege({role_lit}, quote_ident(t), 'UPDATE')
|
||||
OR has_table_privilege({role_lit}, quote_ident(t), 'DELETE')
|
||||
OR has_table_privilege({role_lit}, quote_ident(t), 'TRUNCATE') THEN
|
||||
RAISE EXCEPTION USING MESSAGE =
|
||||
'the runtime role {app_role} can still UPDATE, DELETE or TRUNCATE ' || t;
|
||||
END IF;
|
||||
END LOOP;
|
||||
END $$;
|
||||
"""
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
settings = get_settings()
|
||||
Base.metadata.create_all(bind=op.get_bind(), tables=_TABLES, checkfirst=True)
|
||||
op.execute(runtime_grants_sql(settings.db_app_role, append_only=APPEND_ONLY,
|
||||
no_delete=NO_DELETE, read_only=READ_ONLY))
|
||||
op.execute(immutable_versions_sql(settings.db_app_role))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
Base.metadata.drop_all(bind=op.get_bind(), tables=list(reversed(_TABLES)), checkfirst=True)
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Service modules: `module.in_menu`, and Galena becomes one (Atrium#53).
|
||||
|
||||
Galena is on everywhere and not in the menu: other modules (Workflow, the contracts module, the chat)
|
||||
open its screens by link. That is a new state, not `availability = off` — `off` takes access away
|
||||
(`sync_module` empties the roster) while a service module keeps everything it had: its launcher
|
||||
entry, its deep links inside Atrium's frame, its stats tiles on Home and every `module_permission`
|
||||
row. Only the sidebar entry and the catalogue card go (`services/marketplace.py`, `frontend/app.js`).
|
||||
|
||||
**Idempotent.** On a fresh database `0001` builds `module` from the live metadata, which already has
|
||||
the column, so it is added only `IF NOT EXISTS`. Galena is switched to a service only in the row the
|
||||
seed wrote (slug `galena`); an administrator can switch it back under Administration → Modules, and
|
||||
a second run of this revision never happens (Alembic records it). Nothing is granted: no new table.
|
||||
|
||||
Downgrade drops the column, and with it the choice — every module is a menu entry again.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "0016"
|
||||
down_revision = "0015"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_module = sa.table("module", sa.column("slug", sa.String), sa.column("in_menu", sa.Boolean))
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.execute("ALTER TABLE module ADD COLUMN IF NOT EXISTS in_menu boolean NOT NULL DEFAULT true")
|
||||
op.get_bind().execute(_module.update().where(_module.c.slug == "galena").values(in_menu=False))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.execute("ALTER TABLE module DROP COLUMN IF EXISTS in_menu")
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Arbiter becomes a service module, as Galena did in `0016`.
|
||||
|
||||
Contracts are checked from the chat (the report panel beside it), and Arbiter's own screens open by
|
||||
link: the panel, a contract card's "Otwórz analizę". So on the platform it loses its sidebar entry
|
||||
and catalogue card and keeps everything else (launcher, deep links, stats tiles, access). Its screens
|
||||
that have no home in Atrium yet (subjects, red lines, card corrections, the laptop worker) stay where
|
||||
they are, reachable by link and by administrators in the catalogue; they move one by one.
|
||||
|
||||
Only the seeded row (slug `arbiter`) changes; an administrator can switch it back under
|
||||
Administration → Modules. Downgrade puts it back in the menu. Nothing is granted.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "0017"
|
||||
down_revision = "0016"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_module = sa.table("module", sa.column("slug", sa.String), sa.column("in_menu", sa.Boolean))
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.get_bind().execute(_module.update().where(_module.c.slug == "arbiter").values(in_menu=False))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.get_bind().execute(_module.update().where(_module.c.slug == "arbiter").values(in_menu=True))
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Panorama folds into Atrium's home: it leaves the menu and the catalogue.
|
||||
|
||||
Its trends now live on the home page (`services/trends`, `GET /home/trends`), and the module tiles
|
||||
were already the home page's. So Panorama's row becomes a service module (`in_menu` false, as Galena
|
||||
in `0016` and Arbiter in `0017`): nobody is offered it any more, and nothing anybody had is taken
|
||||
away while it still runs. Removing it from the platform (its container, the front door, its event
|
||||
reader grant) is a deploy step of its own, after this.
|
||||
|
||||
Downgrade puts it back in the menu.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "0018"
|
||||
down_revision = "0017"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_module = sa.table("module", sa.column("slug", sa.String), sa.column("in_menu", sa.Boolean))
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.get_bind().execute(_module.update().where(_module.c.slug == "panorama").values(in_menu=False))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.get_bind().execute(_module.update().where(_module.c.slug == "panorama").values(in_menu=True))
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Lexicon and Scribe become service modules: the chat is the only screen for contracts.
|
||||
|
||||
Decision 1 of 18.11 (issue #53): Arbiter, Lexicon and Scribe are one module „Umowy” under the chat;
|
||||
the logic stays in each module and the chat calls it. Arbiter left the menu in `0017`; Lexicon and
|
||||
Scribe no longer have a console at all, so they leave the menu and the catalogue the same way. The
|
||||
console shows the three as one entry, „Umowy”, which opens the chat (CONTRACTS in app.js).
|
||||
|
||||
Only the seeded rows (slugs `lexicon`, `scribe`) change, and setting `in_menu` false again is a
|
||||
no-op, so this is idempotent. Downgrade puts them back in the menu. Nothing is granted.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "0019"
|
||||
down_revision = "0018"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
_module = sa.table("module", sa.column("slug", sa.String), sa.column("in_menu", sa.Boolean))
|
||||
_SLUGS = ("lexicon", "scribe")
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.get_bind().execute(_module.update().where(_module.c.slug.in_(_SLUGS)).values(in_menu=False))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.get_bind().execute(_module.update().where(_module.c.slug.in_(_SLUGS)).values(in_menu=True))
|
||||
@@ -0,0 +1,35 @@
|
||||
"""The shared `session` table refuses a module that revives or prolongs a credential (dredd-core 0.26.1).
|
||||
|
||||
Every module runtime role holds `UPDATE (last_seen_at, expires_at, revoked_at)` on `<identity>.session`
|
||||
(the reader tier), and a column grant cannot say which VALUES may be written: any one module role could
|
||||
set `revoked_at = NULL` on a session the hub revoked, or push `expires_at` to infinity. Core's
|
||||
`session_update_guard_sql` installs a row-level BEFORE UPDATE trigger that refuses exactly that for
|
||||
every role but the identity owner (this migrator) and the hub's runtime role. Idempotent; standalone a
|
||||
no-op (there is no shared table). Downgrade leaves the guard in place: removing a protection is not a
|
||||
rollback anybody needs.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dredd_core.schema import session_update_guard_sql
|
||||
from sqlalchemy import text
|
||||
|
||||
from alembic import op
|
||||
from app.config import get_settings
|
||||
|
||||
revision = "0020"
|
||||
down_revision = "0019"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
settings = get_settings()
|
||||
if not settings.shares_identity:
|
||||
return
|
||||
owner = op.get_bind().execute(text("SELECT current_user")).scalar()
|
||||
op.execute(session_update_guard_sql(settings.identity_schema, owner_role=owner,
|
||||
writer_role=settings.db_app_role))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
pass
|
||||
@@ -0,0 +1,40 @@
|
||||
"""Mint the Archive's read-only token (Atrium#53) and print it once, for Galena's deployment.
|
||||
|
||||
docker compose run --rm --no-deps -T atrium-migrate python -m app.archive_reader
|
||||
|
||||
Prints the raw token on stdout and nothing else, so it can be piped straight into a secret store;
|
||||
put it into Galena's env file as ARCHIVE_READER_TOKEN (never a committed file). Run it again to
|
||||
rotate: the old token stays valid until it is revoked in the hub (Users → the account → tokens).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
from dredd_core.db import make_engine, make_session_factory
|
||||
from sqlalchemy.pool import NullPool
|
||||
|
||||
from .config import get_settings
|
||||
from .services import archive_reader
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if not get_settings().shares_identity:
|
||||
print("IDENTITY_SCHEMA is empty: a standalone hub has no modules to read from.",
|
||||
file=sys.stderr)
|
||||
return 2
|
||||
engine = make_engine(get_settings().database_url, poolclass=NullPool)
|
||||
try:
|
||||
db = make_session_factory(engine)()
|
||||
try:
|
||||
_row, raw = archive_reader.mint(db)
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
finally:
|
||||
engine.dispose()
|
||||
print(raw)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+56
-5
@@ -12,6 +12,7 @@ no-op instead of a crash.
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import uuid
|
||||
from functools import lru_cache
|
||||
|
||||
from dredd_core.db import require_verified_tls
|
||||
@@ -108,19 +109,46 @@ class Settings(BaseSettings):
|
||||
# the modules that need MORE, and only take effect for a role that is also in the matching
|
||||
# identity list (a module not provisioned yet is left out until it joins, and that is logged):
|
||||
# * MODEL_PROVIDER_KEY_READER_ROLES — runtime roles opted in to READ THE API KEYS, for a module
|
||||
# that calls a model itself (Compass's analyses: `compass_app`). Every other module reaches
|
||||
# that calls a model itself (Arbiter's runs: `arbiter_app`; Lexicon's typing: `lexicon_app`). Every other module reaches
|
||||
# nothing in `model_provider_key`, and removing a role here and migrating revokes it.
|
||||
# * MODEL_PROVIDER_MIGRATOR_ROLES — migrators that may REFERENCE `model_provider` from their own
|
||||
# tables (Compass's `analysis.model_provider_id`: `compass_migrator`). The first one listed is
|
||||
# tables (Arbiter's `analysis.model_provider_id`: `arbiter_migrator`). The first one listed is
|
||||
# also the role the one-shot import door `import_model_providers` is opened for while that
|
||||
# module still holds providers of its own (see `app.identity_grants`).
|
||||
model_provider_key_reader_roles: str = ""
|
||||
model_provider_migrator_roles: str = ""
|
||||
# ── module events (dredd-core 0.20.0) ───────────────────────────────────────────
|
||||
# The shared event log `module_event` lives in the identity schema (revision 0011, re-applied by
|
||||
# `app.identity_grants` on every migrate). The hub's own runtime role (db_app_role) always takes
|
||||
# part; this names the MODULES' runtime roles that do (`galena_app,agora_app,parafa_app`), each getting
|
||||
# SELECT + INSERT under row-level security and nothing more. Like the model-provider opt-ins it
|
||||
# takes effect only for a role also in IDENTITY_READER_ROLES, and a module NOT listed reaches
|
||||
# nothing in the log — which is what its `managed check` without `--events` proves. Removing a
|
||||
# role here and migrating revokes it.
|
||||
module_event_emitter_roles: str = ""
|
||||
# The READER tier (dredd-core 0.23.0): runtime roles that may SELECT the log and nothing else
|
||||
# (none since Panorama left the platform; kept for a module that reports on the log). Same rules: only
|
||||
# once also in IDENTITY_READER_ROLES, removed = revoked on the next migrate, and a role is an
|
||||
# emitter or a reader, never both (the grant block refuses the overlap).
|
||||
module_event_reader_roles: str = ""
|
||||
# ── counterparties (dredd-core 0.21.0) ──────────────────────────────────────────
|
||||
# The shared counterparty register (`counterparty`, `counterparty_alias`, `counterparty_contact`)
|
||||
# lives in the identity schema (revision 0012, re-applied by `app.identity_grants` on every
|
||||
# migrate). The hub holds NO tier on it (it migrates and grants, P3). Writers are the opt-in
|
||||
# modules that write it (`sygna_app`): SELECT, INSERT, UPDATE and
|
||||
# never DELETE a counterparty. Readers get SELECT only. A role in both lists is a writer.
|
||||
# Migrators get SELECT + REFERENCES (their foreign keys, the import's deduplication) and, while a
|
||||
# module still holds counterparties of its own, EXECUTE on the import door. Each takes effect only
|
||||
# for a role also in IDENTITY_READER_ROLES (runtime) / IDENTITY_MIGRATOR_ROLES (migrator); a module
|
||||
# not listed reaches nothing, which is what its `managed check` without `--counterparties` proves.
|
||||
counterparty_writer_roles: str = ""
|
||||
counterparty_reader_roles: str = ""
|
||||
counterparty_migrator_roles: str = ""
|
||||
# The platform's model-provider secret. Provider API keys are stored encrypted under a key
|
||||
# derived from it (Argon2id via dredd_core.security.derive_key, salt `dredd.model_provider.v1`,
|
||||
# then AES-256-GCM as `v1.<nonce>.<ciphertext>` — Compass's `app/provider_keys.py` is the
|
||||
# reference), by the hub and by every opted-in module alike, so it is ONE value shared with
|
||||
# Compass: deploy/init.sh writes it into env/atrium.env and env/compass.env together. Never in
|
||||
# then AES-256-GCM as `v1.<nonce>.<ciphertext>` — `app/provider_keys.py`, byte-compatible with
|
||||
# Arbiter's), by the hub and by every opted-in module alike, so it is ONE value shared with
|
||||
# them: deploy/init.sh writes it into env/atrium.env, env/arbiter.env and env/lexicon.env together. Never in
|
||||
# the database and never logged; a restore without it leaves every key unreadable, which is the
|
||||
# right failure. Nothing in Atrium reads a key yet (the admin screens and Home's "ask the
|
||||
# model" come later); it is wired now so the two env files cannot start out disagreeing.
|
||||
@@ -130,6 +158,9 @@ class Settings(BaseSettings):
|
||||
# open the launcher, so a `user` row would say nothing, and the hub has administrators whose job
|
||||
# is not delegable one module at a time.
|
||||
module_slug: str = "atrium"
|
||||
# The Archive's technical account (Atrium#53, services/archive_reader.py): the fixed id the seed
|
||||
# creates it under and every module fences to its evidence routes (their ARCHIVE_READER_ID).
|
||||
archive_reader_id: uuid.UUID = uuid.UUID("a2c41e00-0000-4000-8000-000000000053")
|
||||
|
||||
# Auth / sessions (cookie-based, DB-backed — one `session` row is the whole of single sign-on)
|
||||
# The cookie's name. One account means one cookie: at the cutover every app in the family is set
|
||||
@@ -257,6 +288,26 @@ class Settings(BaseSettings):
|
||||
def model_provider_migrator_roles_list(self) -> list[str]:
|
||||
return [r.strip() for r in self.model_provider_migrator_roles.split(",") if r.strip()]
|
||||
|
||||
@property
|
||||
def module_event_emitter_roles_list(self) -> list[str]:
|
||||
return [r.strip() for r in self.module_event_emitter_roles.split(",") if r.strip()]
|
||||
|
||||
@property
|
||||
def module_event_reader_roles_list(self) -> list[str]:
|
||||
return [r.strip() for r in self.module_event_reader_roles.split(",") if r.strip()]
|
||||
|
||||
@property
|
||||
def counterparty_writer_roles_list(self) -> list[str]:
|
||||
return [r.strip() for r in self.counterparty_writer_roles.split(",") if r.strip()]
|
||||
|
||||
@property
|
||||
def counterparty_reader_roles_list(self) -> list[str]:
|
||||
return [r.strip() for r in self.counterparty_reader_roles.split(",") if r.strip()]
|
||||
|
||||
@property
|
||||
def counterparty_migrator_roles_list(self) -> list[str]:
|
||||
return [r.strip() for r in self.counterparty_migrator_roles.split(",") if r.strip()]
|
||||
|
||||
@property
|
||||
def shares_identity(self) -> bool:
|
||||
"""True when this deployment is a platform rather than a standalone Atrium.
|
||||
|
||||
@@ -21,6 +21,7 @@ from .enums import SessionKind, TokenScope
|
||||
from .errors import AuthenticationError, AuthorizationError
|
||||
from .models import AppUser
|
||||
from .services import auth as auth_service
|
||||
from .services import skills as skill_service
|
||||
|
||||
SESSION_COOKIE = get_settings().session_cookie_name
|
||||
|
||||
@@ -145,3 +146,12 @@ def require_administrator(user: AppUser = Depends(get_current_user)) -> AppUser:
|
||||
if not user.is_admin:
|
||||
raise AuthorizationError("This area is for administrators.")
|
||||
return user
|
||||
|
||||
|
||||
def require_skill_approver(user: AppUser = Depends(get_current_user),
|
||||
db: Session = Depends(get_db)) -> AppUser:
|
||||
"""Whoever decides publish requests: an administrator, or an approver on the firm's workspace.
|
||||
Wider than `require_administrator` on purpose; the rule itself is `skills.may_approve`."""
|
||||
if not skill_service.may_approve(db, user):
|
||||
raise AuthorizationError("This area is for approvers.")
|
||||
return user
|
||||
|
||||
@@ -60,6 +60,39 @@ class AccessRequestStatus(StrEnum):
|
||||
declined = "declined"
|
||||
|
||||
|
||||
# Skills and agents (`models/skills.py`): Text + CHECK for the same reason as the marketplace ones.
|
||||
class SkillScope(StrEnum):
|
||||
personal = "personal" # the owner's own; nobody else sees it, an administrator included
|
||||
firm = "firm" # published to everybody on the instance
|
||||
|
||||
|
||||
class CatalogStatus(StrEnum):
|
||||
"""Shared by skills and agents. No `draft`: a draft is simply a personal skill."""
|
||||
active = "active"
|
||||
archived = "archived"
|
||||
|
||||
|
||||
class SkillOrigin(StrEnum):
|
||||
authored = "authored"
|
||||
imported = "imported"
|
||||
bundled = "bundled"
|
||||
|
||||
|
||||
class AgentKind(StrEnum):
|
||||
assistant = "assistant"
|
||||
|
||||
|
||||
class PublishKind(StrEnum):
|
||||
skill = "skill"
|
||||
agent = "agent"
|
||||
|
||||
|
||||
class PublishRequestStatus(StrEnum):
|
||||
pending = "pending"
|
||||
approved = "approved"
|
||||
declined = "declined"
|
||||
|
||||
|
||||
__all__ = [
|
||||
# from dredd-core, unchanged
|
||||
"NodeRole",
|
||||
@@ -71,4 +104,10 @@ __all__ = [
|
||||
"ModuleStatus",
|
||||
"Availability",
|
||||
"AccessRequestStatus",
|
||||
"SkillScope",
|
||||
"CatalogStatus",
|
||||
"SkillOrigin",
|
||||
"AgentKind",
|
||||
"PublishKind",
|
||||
"PublishRequestStatus",
|
||||
]
|
||||
|
||||
@@ -53,7 +53,8 @@ Send = Callable[[dict], Awaitable[None]]
|
||||
#: Atrium is served in-process; these are the modules it may proxy to. A slug outside this set can
|
||||
#: never be configured, so a typo in FRONTDOOR_UPSTREAMS refuses start-up.
|
||||
ATRIUM = "atrium"
|
||||
MODULES = ("galena", "sygna", "counsel", "compass", "insider")
|
||||
MODULES = ("galena", "sygna", "counsel", "insider", "arbiter", "lexicon", "agora",
|
||||
"parafa", "scribe", "workflow")
|
||||
SLUGS = (ATRIUM, *MODULES)
|
||||
|
||||
#: Uploads above this are refused: 413 up front on a declared Content-Length, or as soon as a chunked
|
||||
@@ -63,7 +64,8 @@ MAX_BODY = 100 * 1024 * 1024
|
||||
|
||||
TIMEOUT = httpx.Timeout(connect=5.0, read=300.0, write=300.0, pool=10.0)
|
||||
|
||||
NOT_FOUND = b"Not found. This server serves /atrium, /galena, /sygna, /counsel, /compass and /insider."
|
||||
NOT_FOUND = (b"Not found. This server serves /atrium, /galena, /sygna, /counsel, /insider, "
|
||||
b"/arbiter, /lexicon, /agora, /parafa, /scribe and /workflow.")
|
||||
|
||||
# RFC 9110 7.6.1, plus the two non-standard ones still seen in the wild. Never forwarded either way,
|
||||
# together with every header a `Connection` header names.
|
||||
|
||||
@@ -29,6 +29,22 @@ opt-ins (``MODEL_PROVIDER_KEY_READER_ROLES`` / ``MODEL_PROVIDER_MIGRATOR_ROLES``
|
||||
already in the identity lists), and the one-shot import door is opened or dropped by
|
||||
:func:`import_door_wanted` — which is why the door needs no "drop it later" revision.
|
||||
|
||||
**The module events** (dredd-core 0.20.0, revision ``0011``) ride along the same way: once the
|
||||
shared ``module_event`` exists, its row-level security (``event_policies_sql``) and its grant block
|
||||
(``event_grants_sql``) are re-applied, the emitters being the hub's own runtime role plus every role
|
||||
in ``MODULE_EVENT_EMITTER_ROLES`` that is also an identity reader (:func:`event_emitters`), the
|
||||
readers (dredd-core 0.23.0: ``SELECT`` only) every such role in ``MODULE_EVENT_READER_ROLES``. Both blocks
|
||||
are authoritative (a stray policy is dropped, a privilege nobody listed is revoked), so a module
|
||||
added to the list later gets its tier on its first deploy and one removed loses it on the next.
|
||||
|
||||
**The counterparty register** (dredd-core 0.21.0, revision ``0012``; the Compass split's K2) rides
|
||||
along too: once the three shared tables exist, ``counterparty_grants_sql`` is re-applied with the tiers
|
||||
of :func:`counterparty_tiers` — writers (``COUNTERPARTY_WRITER_ROLES``: Sygna, or without Sygna the
|
||||
module that needs counterparties), readers (``COUNTERPARTY_READER_ROLES``) and migrators
|
||||
(``COUNTERPARTY_MIGRATOR_ROLES``), each only once joined — and the import door is opened or dropped by
|
||||
:func:`counterparty_door_wanted`. The hub's own runtime role gets nothing: it holds no counterparty
|
||||
logic.
|
||||
|
||||
Standalone (``IDENTITY_SCHEMA`` empty) it is a no-op that does not even connect. It never runs as the
|
||||
runtime role: it refuses an empty ``MIGRATION_DATABASE_URL`` and one that logs in as ``DB_APP_ROLE``.
|
||||
"""
|
||||
@@ -110,8 +126,8 @@ def model_provider_tiers(settings: Settings) -> dict[str, list[str]]:
|
||||
|
||||
Readers are exactly the identity readers (every module may see which models exist and the
|
||||
policy). The two opt-ins take effect only for a role that is ALSO in the matching identity
|
||||
list, i.e. a module that is provisioned and joined: a fresh box ships `compass_app` /
|
||||
`compass_migrator` here while Compass is still switched off, and the grant block refuses a
|
||||
list, i.e. a module that is provisioned and joined: a fresh box ships `arbiter_app` /
|
||||
`arbiter_migrator` here while Arbiter is still switched off, and the grant block refuses a
|
||||
role that does not exist."""
|
||||
readers = settings.identity_reader_roles_list
|
||||
migrators = settings.identity_migrator_roles_list
|
||||
@@ -190,6 +206,146 @@ def model_provider_statements(settings: Settings, owner: str, conn) -> list[str]
|
||||
return statements
|
||||
|
||||
|
||||
# ── module events (dredd-core 0.20.0) ───────────────────────────────────────────
|
||||
|
||||
|
||||
def event_emitters(settings: Settings) -> dict[str, list[str]]:
|
||||
"""Who may write (and read) the shared event log, from this env.
|
||||
|
||||
The hub's runtime role always: `managed check` holds it to the writer tier, which on the event
|
||||
log means SELECT + INSERT. Then each role in MODULE_EVENT_EMITTER_ROLES that is ALSO an identity
|
||||
reader — a module provisioned and joined; a listed role not joined yet waits (``pending``), since
|
||||
the grant block refuses a role that does not exist. A module not listed reaches nothing."""
|
||||
readers = settings.identity_reader_roles_list
|
||||
wanted = settings.module_event_emitter_roles_list
|
||||
modules = [r for r in wanted if r in readers and r != settings.db_app_role]
|
||||
# The reader tier (dredd-core 0.23.0): SELECT only, for a module that reports on the log and emits
|
||||
# nothing (Panorama). Joined the same way; a role listed in both tiers is passed through to
|
||||
# event_grants_sql, which refuses the overlap by name rather than this guessing a tier.
|
||||
log_readers = [r for r in settings.module_event_reader_roles_list
|
||||
if r in readers and r != settings.db_app_role]
|
||||
return {"emitters": [settings.db_app_role, *dict.fromkeys(modules)],
|
||||
"readers": list(dict.fromkeys(log_readers)),
|
||||
"pending": [r for r in wanted if r not in readers and r != settings.db_app_role]
|
||||
+ [r for r in settings.module_event_reader_roles_list
|
||||
if r not in readers and r != settings.db_app_role]}
|
||||
|
||||
|
||||
def event_table_exists(conn, schema: str) -> bool:
|
||||
from dredd_core.identity import EVENT_TABLE
|
||||
|
||||
return bool(conn.execute(text(
|
||||
"SELECT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace "
|
||||
f"WHERE n.nspname = {_literal(schema)} AND c.relname = {_literal(EVENT_TABLE)} "
|
||||
"AND c.relkind IN ('r', 'p'))")).scalar())
|
||||
|
||||
|
||||
def event_statements(settings: Settings, owner: str, conn) -> list[str]:
|
||||
"""The event log's policies and grant block, for this env and this database. Empty standalone
|
||||
(there the log is Atrium's own and the runtime sweep covers it), and empty until revision 0011
|
||||
has created the shared table. Imported lazily: importing ``dredd_core.events`` registers its
|
||||
tables on the metadata, and ``0001``'s ``create_all`` must not see them."""
|
||||
if not settings.shares_identity:
|
||||
return []
|
||||
schema = settings.identity_schema
|
||||
if not event_table_exists(conn, schema):
|
||||
return []
|
||||
from dredd_core import events
|
||||
|
||||
tiers = event_emitters(settings)
|
||||
try:
|
||||
return [events.event_policies_sql(schema),
|
||||
events.event_grants_sql(schema, owner_role=owner,
|
||||
emitter_roles=tiers["emitters"],
|
||||
reader_roles=tiers["readers"])]
|
||||
except ValueError as exc:
|
||||
raise GrantsRefused(f"module event grants: {exc} (MODULE_EVENT_EMITTER_ROLES / "
|
||||
"MODULE_EVENT_READER_ROLES in env/atrium.env)") from None
|
||||
|
||||
|
||||
# ── counterparties (dredd-core 0.21.0) ──────────────────────────────────────────
|
||||
|
||||
|
||||
def counterparty_tiers(settings: Settings) -> dict[str, list[str]]:
|
||||
"""Who gets which tier on the shared counterparty register, from this env.
|
||||
|
||||
Each list takes effect only for a role that is ALSO joined (runtime roles in
|
||||
IDENTITY_READER_ROLES, migrators in IDENTITY_MIGRATOR_ROLES); a listed role not joined yet waits
|
||||
(``pending``), since the grant block refuses a role that does not exist. A role in both runtime
|
||||
lists is a writer (a writer reads too). The hub's own runtime role is never a grantee."""
|
||||
readers = settings.identity_reader_roles_list
|
||||
migrators = settings.identity_migrator_roles_list
|
||||
hub = settings.db_app_role
|
||||
writers = [r for r in dict.fromkeys(settings.counterparty_writer_roles_list)
|
||||
if r in readers and r != hub]
|
||||
plain = [r for r in dict.fromkeys(settings.counterparty_reader_roles_list)
|
||||
if r in readers and r != hub and r not in writers]
|
||||
importers = [r for r in dict.fromkeys(settings.counterparty_migrator_roles_list) if r in migrators]
|
||||
wanted = [*settings.counterparty_writer_roles_list, *settings.counterparty_reader_roles_list]
|
||||
return {
|
||||
"writers": writers,
|
||||
"readers": plain,
|
||||
"migrators": importers,
|
||||
"pending": [r for r in dict.fromkeys(wanted) if r not in readers and r != hub]
|
||||
+ [r for r in settings.counterparty_migrator_roles_list if r not in migrators],
|
||||
}
|
||||
|
||||
|
||||
def counterparty_tables_exist(conn, schema: str) -> bool:
|
||||
from dredd_core.identity import COUNTERPARTY_TABLES
|
||||
|
||||
found = conn.execute(text(
|
||||
"SELECT count(*) FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace "
|
||||
f"WHERE n.nspname = {_literal(schema)} AND c.relkind IN ('r', 'p') AND c.relname IN ("
|
||||
+ ", ".join(_literal(t) for t in sorted(COUNTERPARTY_TABLES)) + ")")).scalar()
|
||||
return found == len(COUNTERPARTY_TABLES)
|
||||
|
||||
|
||||
def counterparty_door_wanted(conn, schema: str, importers: list[str]) -> bool:
|
||||
"""Whether the ``import_counterparties`` door should be open right now: some migrator is listed,
|
||||
and some module still holds counterparties of its own to bring in — a schema other than the
|
||||
identity schema and the hub's own with a ``counterparty`` table (Compass before its revision
|
||||
``0028``), or a ``party`` table without a ``counterparty_id`` column (Sygna before its ``0006``).
|
||||
Atrium migrates first on a deploy, so the door is open when those revisions run, and closes on the
|
||||
next migrate after them. Catalog queries only (readable by everyone)."""
|
||||
if not importers:
|
||||
return False
|
||||
return bool(conn.execute(text(
|
||||
"SELECT EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace "
|
||||
f"WHERE c.relkind IN ('r', 'p') AND n.nspname NOT IN ({_literal(schema)}, current_schema(), "
|
||||
"'pg_catalog', 'information_schema') AND (c.relname = 'counterparty' OR (c.relname = 'party' "
|
||||
"AND NOT EXISTS (SELECT 1 FROM pg_attribute a WHERE a.attrelid = c.oid "
|
||||
"AND a.attname = 'counterparty_id' AND NOT a.attisdropped))))")).scalar())
|
||||
|
||||
|
||||
def counterparty_statements(settings: Settings, owner: str, conn) -> list[str]:
|
||||
"""The counterparty grant block and the import door's open/close, for this env and this database.
|
||||
Empty standalone, and empty until revision 0012 has created the tables. ``dredd_core.counterparties``
|
||||
is imported lazily, for the reason :func:`event_statements` gives."""
|
||||
if not settings.shares_identity:
|
||||
return []
|
||||
schema = settings.identity_schema
|
||||
if not counterparty_tables_exist(conn, schema):
|
||||
return []
|
||||
from dredd_core import counterparties as cp
|
||||
|
||||
tiers = counterparty_tiers(settings)
|
||||
try:
|
||||
statements = [cp.counterparty_grants_sql(
|
||||
schema, owner_role=owner, writer_roles=tiers["writers"], reader_roles=tiers["readers"],
|
||||
migrator_roles=tiers["migrators"])]
|
||||
if counterparty_door_wanted(conn, schema, tiers["migrators"]):
|
||||
statements += cp.counterparty_import_sql(schema, owner_role=owner,
|
||||
importer_roles=tiers["migrators"])
|
||||
else:
|
||||
statements.append(cp.drop_counterparty_import_sql(schema))
|
||||
except ValueError as exc:
|
||||
raise GrantsRefused(f"counterparty grants: {exc} (COUNTERPARTY_WRITER_ROLES / "
|
||||
"COUNTERPARTY_READER_ROLES / COUNTERPARTY_MIGRATOR_ROLES in "
|
||||
"env/atrium.env)") from None
|
||||
return statements
|
||||
|
||||
|
||||
def apply(settings: Settings) -> bool:
|
||||
"""Apply the grants in one transaction. Returns False standalone (nothing done)."""
|
||||
sql = build_sql(settings)
|
||||
@@ -207,6 +363,12 @@ def apply(settings: Settings) -> bool:
|
||||
providers = model_provider_statements(settings, owner, conn)
|
||||
for statement in providers:
|
||||
conn.execute(text(statement))
|
||||
event_sql = event_statements(settings, owner, conn)
|
||||
for statement in event_sql:
|
||||
conn.execute(text(statement))
|
||||
counterparty_sql = counterparty_statements(settings, owner, conn)
|
||||
for statement in counterparty_sql:
|
||||
conn.execute(text(statement))
|
||||
finally:
|
||||
engine.dispose()
|
||||
if providers:
|
||||
@@ -217,6 +379,22 @@ def apply(settings: Settings) -> bool:
|
||||
if tiers["pending"]:
|
||||
log.info("model provider opt-ins waiting for their module to join the identity lists: %s",
|
||||
",".join(tiers["pending"]))
|
||||
if event_sql:
|
||||
tiers = event_emitters(settings)
|
||||
log.info("module event grants re-applied: emitters=%s readers=%s", ",".join(tiers["emitters"]),
|
||||
",".join(tiers["readers"]) or "-")
|
||||
if tiers["pending"]:
|
||||
log.info("module event roles waiting for their module to join the identity lists: %s",
|
||||
",".join(tiers["pending"]))
|
||||
if counterparty_sql:
|
||||
tiers = counterparty_tiers(settings)
|
||||
log.info("counterparty grants re-applied: writers=%s readers=%s migrators=%s, import door %s",
|
||||
",".join(tiers["writers"]) or "-", ",".join(tiers["readers"]) or "-",
|
||||
",".join(tiers["migrators"]) or "-",
|
||||
"closed" if counterparty_sql[-1].startswith("DROP FUNCTION") else "open")
|
||||
if tiers["pending"]:
|
||||
log.info("counterparty roles waiting for their module to join the identity lists: %s",
|
||||
",".join(tiers["pending"]))
|
||||
log.info("shared identity grants re-applied on schema %s: readers=%s migrators=%s",
|
||||
settings.identity_schema, ",".join(settings.identity_reader_roles_list) or "-",
|
||||
",".join(settings.identity_migrator_roles_list) or "-")
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
"""Speaking to a model server on a provider row: the OpenAI chat protocol, and LM Studio's loading.
|
||||
|
||||
The address and key are ARGUMENTS, taken by the caller from `model_provider` through core's
|
||||
`offering()` and `api_key()` — never from settings and never from a request, so nothing a caller
|
||||
sends can point this process somewhere else.
|
||||
|
||||
**One model at a time on LM Studio.** The card this targets holds one model; a second load next to
|
||||
the first ends in LM Studio's `HTTP 400 {"error":"terminated"}`. So every load goes through
|
||||
`LOAD_LOCK`, unloads whatever is in memory first, and re-reads the listing once it holds the lock
|
||||
(somebody ahead in the queue may have loaded the same model already). Asks are not serialised: LM
|
||||
Studio queues requests to the one loaded model on its own. Other servers (Ollama, vLLM, a cloud API)
|
||||
load on their own; `loaded_models` answers `None` for them and nothing is loaded by hand.
|
||||
|
||||
**Only an administrator switches the model.** Everybody shares the one card, so anyone else asking
|
||||
for another model is refused (`ModelBusy`) and nothing is loaded or evicted; with nothing in memory
|
||||
anyone may load the first. The router refuses up front with a 409, and `ensure_loaded` decides again
|
||||
under the lock, because the answer read before the queue can be stale by the time it gets its turn.
|
||||
|
||||
**"Whatever is in memory" means chat models.** An embedding model is not what a switch replaces and
|
||||
stays loaded. `/api/v1/models` is the listing with instance ids, the ones an unload takes;
|
||||
`/api/v0/models` is the one whose `type` we rely on. So `ensure_loaded` reads both, and an instance
|
||||
with no chat type in `/api/v0` is left alone.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
import httpx
|
||||
|
||||
from app.errors import ValidationError
|
||||
|
||||
#: Loading an 11B model from disk took about a minute on the reference machine.
|
||||
LOAD_TIMEOUT = httpx.Timeout(connect=5.0, read=300.0, write=30.0, pool=10.0)
|
||||
LIST_TIMEOUT = httpx.Timeout(5.0)
|
||||
#: The window Atrium loads a model with when nothing is in memory.
|
||||
DEFAULT_CONTEXT = 65536 # history, up to 8 rounds of tool results (~6k chars each) and a thinking model's answer
|
||||
#: LM Studio model types that answer a chat. `embeddings` models only turn text into vectors.
|
||||
CHAT_TYPES = frozenset({"llm", "vlm"})
|
||||
|
||||
LOAD_LOCK = asyncio.Lock()
|
||||
|
||||
|
||||
class GatewayError(Exception):
|
||||
"""The model server is unreachable or refused; the message is a sentence for a person."""
|
||||
|
||||
|
||||
class ModelBusy(GatewayError):
|
||||
"""Another model is running and this asker may not switch it."""
|
||||
|
||||
code = "model_busy"
|
||||
|
||||
def __init__(self, running: str) -> None:
|
||||
super().__init__(f"Teraz działa model {running}. Zmienić go może tylko administrator.")
|
||||
self.running = running
|
||||
self.en = f"The model running now is {running}. Only an administrator can switch it."
|
||||
|
||||
|
||||
def server_root(base_url: str) -> str:
|
||||
"""`http://host:1234` and `http://host:1234/v1` name the same server — the same reading as
|
||||
Compass's `agents/client.server_root`, so one provider row means one thing in both."""
|
||||
base = base_url.rstrip("/")
|
||||
return base[:-3].rstrip("/") if base.endswith("/v1") else base
|
||||
|
||||
|
||||
def _headers(key: str | None) -> dict[str, str]:
|
||||
return {"Authorization": f"Bearer {key}"} if key else {}
|
||||
|
||||
|
||||
async def _json(client: httpx.AsyncClient, method: str, url: str, key: str | None,
|
||||
body: dict | None = None):
|
||||
try:
|
||||
resp = await client.request(method, url, headers=_headers(key), json=body)
|
||||
except httpx.HTTPError as exc:
|
||||
raise GatewayError(f"Serwer modeli nie odpowiada ({type(exc).__name__}).") from exc
|
||||
if resp.status_code != 200:
|
||||
raise GatewayError(f"Serwer modeli odpowiedział HTTP {resp.status_code}.")
|
||||
return resp.json()
|
||||
|
||||
|
||||
async def loaded_models(root: str, key: str | None) -> dict[str, bool] | None:
|
||||
"""`{model id: in memory}` from LM Studio's own listing, or `None` when this server has no such
|
||||
listing (it is not LM Studio, or it does not answer): then nothing is loaded by hand."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=LIST_TIMEOUT) as client:
|
||||
listing = await _json(client, "GET", f"{root}/api/v0/models", key)
|
||||
except GatewayError:
|
||||
return None
|
||||
return {m["id"]: m.get("state") == "loaded"
|
||||
for m in listing.get("data", []) if m.get("type") in CHAT_TYPES and m.get("id")}
|
||||
|
||||
|
||||
def refuse_switch(loaded: dict[str, bool], model: str) -> None:
|
||||
"""`ModelBusy` when a chat model other than `model` is in memory; nothing loaded passes."""
|
||||
running = [m for m, in_memory in loaded.items() if in_memory]
|
||||
if running and model not in running:
|
||||
raise ModelBusy(running[0])
|
||||
|
||||
|
||||
async def ensure_loaded(root: str, key: str | None, model: str, *, may_switch: bool) -> None:
|
||||
"""Put `model` in memory on LM Studio, unloading the chat model there first. Without `may_switch`
|
||||
a different chat model in memory is `ModelBusy`, and nothing is touched."""
|
||||
async with LOAD_LOCK, httpx.AsyncClient(timeout=LOAD_TIMEOUT) as client:
|
||||
typed = await _json(client, "GET", f"{root}/api/v0/models", key)
|
||||
chat = {m.get("id") for m in typed.get("data", []) if m.get("type") in CHAT_TYPES}
|
||||
listing = await _json(client, "GET", f"{root}/api/v1/models", key)
|
||||
instances = [(entry.get("key"), inst["id"])
|
||||
for entry in listing.get("models", []) for inst in entry.get("loaded_instances", ())
|
||||
if entry.get("key") in chat or inst["id"] in chat]
|
||||
if any(model in pair for pair in instances):
|
||||
return # loaded by whoever held the lock before us
|
||||
if instances and not may_switch:
|
||||
raise ModelBusy(instances[0][0] or instances[0][1])
|
||||
for _, instance_id in instances:
|
||||
await _json(client, "POST", f"{root}/api/v1/models/unload", key, {"instance_id": instance_id})
|
||||
await _json(client, "POST", f"{root}/api/v1/models/load", key,
|
||||
{"model": model, "context_length": DEFAULT_CONTEXT})
|
||||
|
||||
|
||||
async def stream_chat(root: str, key: str | None, model: str, messages: list[dict],
|
||||
max_tokens: int, **extra) -> AsyncIterator[bytes]:
|
||||
"""The server's own server-sent events for one answer, passed through unchanged. `extra` carries
|
||||
the OpenAI `tools` / `tool_choice` when the caller offers tools, and the sampling and reasoning
|
||||
fields the person set (`temperature`, `top_p`, `top_k`, `presence_penalty`, `reasoning_effort`)."""
|
||||
body = {"model": model, "messages": messages, "max_tokens": max_tokens, "stream": True, **extra}
|
||||
async with httpx.AsyncClient(timeout=LOAD_TIMEOUT) as client:
|
||||
try:
|
||||
# Identity: the raw bytes pass through to the browser with no Content-Encoding of ours, and a
|
||||
# cloud API gzips by default (api.anthropic.com did, 2026-11-06) — the chat read garbage.
|
||||
async with client.stream("POST", f"{root}/v1/chat/completions",
|
||||
headers={**_headers(key), "Accept-Encoding": "identity"},
|
||||
json=body) as resp:
|
||||
if resp.status_code != 200:
|
||||
# The server's own reason (OpenAI-shaped `error.message`), capped: a bare "HTTP 400"
|
||||
# left a refused parameter invisible. The key travels in a header, never echoed here.
|
||||
raw = b""
|
||||
async for chunk in resp.aiter_raw():
|
||||
raw += chunk
|
||||
if len(raw) > 4096:
|
||||
break
|
||||
try:
|
||||
why = json.loads(raw)["error"]["message"]
|
||||
except (ValueError, KeyError, TypeError):
|
||||
why = ""
|
||||
why = f": {str(why)[:300]}" if why else ""
|
||||
raise GatewayError(f"Serwer modeli odpowiedział HTTP {resp.status_code}{why}")
|
||||
async for chunk in resp.aiter_raw():
|
||||
yield chunk
|
||||
except httpx.HTTPError as exc:
|
||||
raise GatewayError(f"Serwer modeli nie odpowiada ({type(exc).__name__}).") from exc
|
||||
|
||||
|
||||
# ── listing what a provider offers (the administrator's "discover" / "refresh") ──────────────────
|
||||
# An administrator-steered outbound call, SSRF-shaped like the module probe: no redirects, one
|
||||
# deadline for the whole exchange, and a capped body. The key travels only in a header and never
|
||||
# appears in an error.
|
||||
|
||||
LIST_DEADLINE = 10.0
|
||||
LIST_MAX_BYTES = 2 * 1024 * 1024
|
||||
#: Vendors whose address is a cloud API, not somebody's own server: no LM Studio listing to ask.
|
||||
CLOUD_VENDORS = frozenset({"openai", "openrouter", "anthropic"})
|
||||
# ponytail: a pattern, not a catalogue of model ids — extend it when a non-chat model leaks through.
|
||||
NON_CHAT = re.compile(r"embed|tts|whisper|dall-e|image|moderation|audio|transcribe|realtime|rerank", re.I)
|
||||
|
||||
|
||||
def _refusal(code: str, pl: str, en: str) -> ValidationError:
|
||||
return ValidationError(pl, {"code": code, "en": en})
|
||||
|
||||
|
||||
def _unreachable(why_pl: str, why_en: str) -> ValidationError:
|
||||
return _refusal("provider_unreachable", f"Serwer modeli nie odpowiada: {why_pl}.",
|
||||
f"The model server does not answer: {why_en}.")
|
||||
|
||||
|
||||
class _NotFound(Exception):
|
||||
"""A non-200 answer that is not a refusal of the key — for an optional listing, just absent."""
|
||||
|
||||
|
||||
async def _capped_json(client: httpx.AsyncClient, url: str, headers: dict[str, str]):
|
||||
# Raw bytes, identity only: a decoded read is a decompression bomb (one gzip chunk → many MB).
|
||||
async with client.stream("GET", url, headers={**headers, "Accept-Encoding": "identity"}) as resp:
|
||||
if resp.is_redirect:
|
||||
raise _unreachable("przekierowanie odrzucone", "redirect refused")
|
||||
if resp.status_code in (401, 403):
|
||||
raise _refusal("provider_key_refused", "Serwer modeli odrzucił klucz.",
|
||||
"The model server refused the key.")
|
||||
if resp.status_code != 200:
|
||||
raise _NotFound(resp.status_code)
|
||||
if resp.headers.get("content-encoding", "identity").lower() != "identity":
|
||||
raise _unreachable("odpowiedź jest skompresowana", "the answer is compressed")
|
||||
body = bytearray()
|
||||
async for chunk in resp.aiter_raw():
|
||||
body += chunk
|
||||
if len(body) > LIST_MAX_BYTES:
|
||||
raise _unreachable("odpowiedź jest za duża", "the answer is too large")
|
||||
try:
|
||||
return json.loads(body)
|
||||
except (ValueError, RecursionError): # 2 MB of `[` nests deeper than the decoder recurses
|
||||
raise _unreachable("odpowiedź nie jest JSON-em", "the answer is not JSON") from None
|
||||
|
||||
|
||||
def _data(listing) -> list:
|
||||
"""`listing["data"]` when somebody else's server answered the documented shape; anything else
|
||||
is a 422, never an AttributeError (a 500) on untrusted input."""
|
||||
data = listing.get("data") if isinstance(listing, dict) else None
|
||||
if not isinstance(data, list):
|
||||
raise _unreachable("nieoczekiwany kształt odpowiedzi", "unexpected answer shape")
|
||||
return data
|
||||
|
||||
|
||||
async def _openai_models(client: httpx.AsyncClient, base_url: str, key: str | None,
|
||||
vendor: str | None) -> list[dict]:
|
||||
root, headers = server_root(base_url), _headers(key)
|
||||
try:
|
||||
listing = await _capped_json(client, f"{root}/v1/models", headers)
|
||||
except _NotFound as exc:
|
||||
raise _unreachable(f"HTTP {exc.args[0]}", f"HTTP {exc.args[0]}") from None
|
||||
models = [{"id": m["id"], "dialect": "openai",
|
||||
**({"context_window": m["max_model_len"]}
|
||||
if isinstance(m.get("max_model_len"), int) and m["max_model_len"] > 0 else {})}
|
||||
for m in _data(listing) if isinstance(m, dict) and isinstance(m.get("id"), str)]
|
||||
if vendor not in CLOUD_VENDORS:
|
||||
# LM Studio's own listing says which models chat; `/v1/models` lists embeddings too. Same
|
||||
# reading as `loaded_models`, but through the capped reader. Not LM Studio → no listing.
|
||||
# Optional: a server behind a login page answers this path with a 302, HTML or a 401, and
|
||||
# that says nothing about `/v1/models`, which already answered — any refusal = no listing.
|
||||
try:
|
||||
lm_data = _data(await _capped_json(client, f"{root}/api/v0/models", headers))
|
||||
except (_NotFound, ValidationError):
|
||||
lm_data = []
|
||||
types = {m.get("id"): m.get("type") for m in lm_data if isinstance(m, dict)}
|
||||
models = [m for m in models if types.get(m["id"], "llm") in CHAT_TYPES]
|
||||
return models
|
||||
|
||||
|
||||
#: https://platform.claude.com/docs/en/api/versioning (latest on 2026-11-06); the listing itself is
|
||||
#: https://platform.claude.com/docs/en/api/models-list — `lifecycle`, `max_input_tokens`.
|
||||
ANTHROPIC_VERSION = "2026-10-21"
|
||||
|
||||
|
||||
async def _anthropic_models(client: httpx.AsyncClient, base_url: str, key: str | None) -> list[dict]:
|
||||
headers = {"anthropic-version": ANTHROPIC_VERSION, **({"x-api-key": key} if key else {})}
|
||||
# ponytail: one page of 1000 (the maximum), no `after_id` paging — the catalogue is far smaller.
|
||||
try:
|
||||
listing = await _capped_json(client, f"{base_url.rstrip('/')}/models?limit=1000", headers)
|
||||
except _NotFound as exc:
|
||||
raise _unreachable(f"HTTP {exc.args[0]}", f"HTTP {exc.args[0]}") from None
|
||||
# The default listing includes `deprecated` models, closed to new adopters: offer active only.
|
||||
return [{"id": m["id"], "dialect": "openai",
|
||||
**({"context_window": m["max_input_tokens"]}
|
||||
if isinstance(m.get("max_input_tokens"), int) and m["max_input_tokens"] > 0 else {})}
|
||||
for m in _data(listing)
|
||||
if isinstance(m, dict) and isinstance(m.get("id"), str) and m.get("lifecycle") == "active"]
|
||||
|
||||
|
||||
async def list_models(base_url: str, key: str | None, vendor: str | None, *,
|
||||
transport: httpx.AsyncBaseTransport | None = None) -> list[dict]:
|
||||
"""The chat models a provider offers under this key, as `{id, context_window?, dialect}`.
|
||||
Refusals are 422 Problem Details with `code` `provider_key_refused` / `provider_unreachable` /
|
||||
`provider_no_models`. `transport` exists for tests."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=LIST_DEADLINE, follow_redirects=False,
|
||||
transport=transport) as client:
|
||||
listing = (_anthropic_models(client, base_url, key) if vendor == "anthropic"
|
||||
else _openai_models(client, base_url, key, vendor))
|
||||
models = await asyncio.wait_for(listing, LIST_DEADLINE)
|
||||
except (httpx.HTTPError, TimeoutError) as exc:
|
||||
raise _unreachable(type(exc).__name__, type(exc).__name__) from None
|
||||
models = [m for m in models if not NON_CHAT.search(m["id"])]
|
||||
if not models:
|
||||
raise _refusal("provider_no_models", "Pod tym kluczem/adresem nie ma żadnego modelu czatu.",
|
||||
"There is no chat model under this key/address.")
|
||||
return models
|
||||
+31
-9
@@ -3,13 +3,19 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
from contextlib import asynccontextmanager
|
||||
from collections.abc import Sequence
|
||||
from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from dredd_core.identity import MODEL_PROVIDER_TABLES, SHARED_IDENTITY_TABLES
|
||||
from dredd_core.identity import (
|
||||
COUNTERPARTY_TABLES,
|
||||
EVENT_TABLES,
|
||||
MODEL_PROVIDER_TABLES,
|
||||
SHARED_IDENTITY_TABLES,
|
||||
)
|
||||
from dredd_core.identity_schema import assert_identity_schema
|
||||
from dredd_core.json_charset import ensure_json_charset
|
||||
from dredd_core.routes import iter_routes
|
||||
from fastapi import Depends, FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
@@ -29,7 +35,18 @@ from .deps import refuse_cross_site_write
|
||||
from .errors import ProblemDetailErrorMiddleware, install_error_handlers, problem_response
|
||||
from .logging_config import configure_logging
|
||||
from .observability import setup_observability
|
||||
from .routers import admin, admin_modules, admin_providers, auth, health, marketplace, nodes, users
|
||||
from .routers import (
|
||||
admin,
|
||||
admin_modules,
|
||||
admin_providers,
|
||||
auth,
|
||||
health,
|
||||
marketplace,
|
||||
models,
|
||||
nodes,
|
||||
skills,
|
||||
users,
|
||||
)
|
||||
|
||||
API_PREFIX = "/api/v1"
|
||||
|
||||
@@ -64,10 +81,13 @@ async def lifespan(_app: FastAPI):
|
||||
with engine.connect() as conn:
|
||||
own = conn.scalar(text("SELECT current_schema()")) or ""
|
||||
# The model providers too (revision 0009): a copy left in Atrium's own schema would be
|
||||
# a private list the modules never see.
|
||||
# a private list the modules never see. The event log too (revision 0011): a local one
|
||||
# would be a log no module writes to or reads. The counterparty register too
|
||||
# (revision 0012): a local copy would be a register no module sees.
|
||||
assert_identity_schema(conn, own_schema=own,
|
||||
identity_schema=settings.identity_schema,
|
||||
tables=SHARED_IDENTITY_TABLES | MODEL_PROVIDER_TABLES)
|
||||
tables=SHARED_IDENTITY_TABLES | MODEL_PROVIDER_TABLES | EVENT_TABLES
|
||||
| COUNTERPARTY_TABLES)
|
||||
log.info("Shared identity schema %s: every identity table resolves there",
|
||||
settings.identity_schema)
|
||||
yield
|
||||
@@ -148,7 +168,8 @@ async def _security_headers(request, call_next):
|
||||
|
||||
for router in (
|
||||
health.router, auth.router, users.router, admin.router, admin_modules.router,
|
||||
admin_providers.router, nodes.router, marketplace.router,
|
||||
admin_providers.router, nodes.router, marketplace.router, models.router, skills.router,
|
||||
skills.agents, skills.publish_requests,
|
||||
):
|
||||
app.include_router(router, prefix=API_PREFIX)
|
||||
|
||||
@@ -176,8 +197,9 @@ class _ConsoleUnlessApi:
|
||||
method (asked via Starlette's own `route.matches`, so there is no second copy of the path
|
||||
regexes), 404 when none does. Ported from Galena's main._ConsoleUnlessApi.
|
||||
|
||||
FastAPI is pinned at 0.115.x, where `app.routes` is flat; from 0.137 included routers nest and
|
||||
this would need `fastapi.routing.iter_route_contexts`.
|
||||
The walk goes through `dredd_core.routes.iter_routes` (0.18.1): FastAPI 0.115.x keeps
|
||||
`app.routes` flat, but from 0.15x each included router is one `_IncludedRouter` entry and a
|
||||
plain walk would see no API route at all (every 405 back to a 404).
|
||||
"""
|
||||
|
||||
def __init__(self, console: ASGIApp, routes: Sequence[BaseRoute]) -> None:
|
||||
@@ -195,7 +217,7 @@ class _ConsoleUnlessApi:
|
||||
await self._console(scope, receive, send)
|
||||
return
|
||||
allowed: set[str] = set()
|
||||
for route in self._routes:
|
||||
for _, route in iter_routes(self._routes):
|
||||
methods = getattr(route, "methods", None)
|
||||
if methods and route.matches(scope)[0] is Match.PARTIAL:
|
||||
allowed |= set(methods)
|
||||
|
||||
@@ -40,11 +40,22 @@ from dredd_core import (
|
||||
from dredd_core.model_providers import ModelProvider, ModelProviderKey, ModelProviderPolicy
|
||||
|
||||
from .marketplace import AccessRequest, Module, ModuleAssignment
|
||||
from .skills import (
|
||||
Agent,
|
||||
AgentVersion,
|
||||
AgentVersionSkill,
|
||||
PublishRequest,
|
||||
Skill,
|
||||
SkillFile,
|
||||
SkillVersion,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"Base", "TimestampMixin", "UUIDPkMixin", "SafeInet", "pg_enum",
|
||||
"AppUser", "Session", "ModulePermission", "AppSetting", "AuditLog",
|
||||
"Node", "PermissionGrant", "Favorite",
|
||||
"Module", "ModuleAssignment", "AccessRequest",
|
||||
"Skill", "SkillVersion", "SkillFile", "Agent", "AgentVersion", "AgentVersionSkill",
|
||||
"PublishRequest",
|
||||
"ModelProvider", "ModelProviderPolicy", "ModelProviderKey",
|
||||
]
|
||||
|
||||
@@ -17,6 +17,7 @@ import uuid
|
||||
|
||||
from dredd_core import Base, TimestampMixin, UUIDPkMixin
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
CheckConstraint,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
@@ -56,6 +57,11 @@ class Module(UUIDPkMixin, TimestampMixin, Base):
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
availability: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
sort_order: Mapped[int] = mapped_column(Integer, nullable=False, server_default=text("100"))
|
||||
# False: a SERVICE module — on and reachable like any other (launcher, deep links, stats tiles,
|
||||
# module_permission all unchanged), but not an entry in the sidebar or the catalogue. Galena is
|
||||
# one (on everywhere, not in the menu): other modules open its screens by link.
|
||||
# Separate from `availability` on purpose: `off` takes access away, this only takes the entry.
|
||||
in_menu: Mapped[bool] = mapped_column(Boolean, nullable=False, server_default=text("true"))
|
||||
created_by: Mapped[uuid.UUID | None] = mapped_column(ForeignKey("app_user.id"))
|
||||
|
||||
__table_args__ = (
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
"""Skills and agents: a person's own instructions, reference files and the agents built on them.
|
||||
|
||||
A stable identity (`skill`, `agent`) points at frozen versions (`skill_version`, `agent_version`):
|
||||
changing content is a new version, never an edit, which is why the runtime role holds no UPDATE or
|
||||
DELETE on the version tables (revision 0015). The identity rows stay mutable — scope, status and
|
||||
`current_version_id` move through publication and archiving.
|
||||
|
||||
These are NOT nodes of the org tree (the tree holds units only), so access is not `authz`'s: it is
|
||||
computed in one place, `services/skills.visible_to`. Every table lives in Atrium's own schema — no
|
||||
module reads the catalogue, and the shared schema is readable by every module.
|
||||
|
||||
Every foreign key to `app_user` is RESTRICT: an account is deactivated, never deleted, and a skill
|
||||
must not silently lose its author. Vocabularies are Text + CHECK built from `app/enums.py`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import uuid
|
||||
|
||||
from dredd_core import Base, TimestampMixin, UUIDPkMixin
|
||||
from sqlalchemy import (
|
||||
CheckConstraint,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
LargeBinary,
|
||||
String,
|
||||
Text,
|
||||
UniqueConstraint,
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import ARRAY, JSONB
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from ..enums import (
|
||||
AgentKind,
|
||||
CatalogStatus,
|
||||
PublishKind,
|
||||
PublishRequestStatus,
|
||||
SkillOrigin,
|
||||
SkillScope,
|
||||
)
|
||||
from .marketplace import _one_of
|
||||
|
||||
|
||||
def _user_fk(nullable: bool = False):
|
||||
return mapped_column(ForeignKey("app_user.id", ondelete="RESTRICT"), nullable=nullable)
|
||||
|
||||
|
||||
def _created_at():
|
||||
return mapped_column(DateTime(timezone=True), nullable=False, server_default=text("now()"))
|
||||
|
||||
|
||||
class Skill(UUIDPkMixin, TimestampMixin, Base):
|
||||
__tablename__ = "skill"
|
||||
|
||||
slug: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
name: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
owner_id: Mapped[uuid.UUID] = _user_fk()
|
||||
scope: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, server_default=SkillScope.personal.value)
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, server_default=CatalogStatus.active.value)
|
||||
# For a firm skill: only the approved version. use_alter breaks the skill ↔ version cycle.
|
||||
current_version_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||
ForeignKey("skill_version.id", ondelete="RESTRICT", use_alter=True))
|
||||
origin: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, server_default=SkillOrigin.authored.value)
|
||||
|
||||
__table_args__ = (
|
||||
CheckConstraint(_one_of("scope", SkillScope), name="scope"),
|
||||
CheckConstraint(_one_of("status", CatalogStatus), name="status"),
|
||||
CheckConstraint(_one_of("origin", SkillOrigin), name="origin"),
|
||||
CheckConstraint(r"slug ~ '^[a-z0-9]+(-[a-z0-9]+)*$'", name="slug"),
|
||||
UniqueConstraint("owner_id", "slug", name="uq_skill_owner_slug"),
|
||||
Index("ix_skill_scope", "scope"),
|
||||
)
|
||||
|
||||
|
||||
class SkillVersion(UUIDPkMixin, Base):
|
||||
__tablename__ = "skill_version"
|
||||
|
||||
skill_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("skill.id", ondelete="RESTRICT"), nullable=False)
|
||||
n: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
description: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
# 30 000 characters: the chat tool's result limit.
|
||||
body_md: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
# An imported licence is the author's and is never overwritten (the service's rule).
|
||||
license: Mapped[str] = mapped_column(Text, nullable=False, server_default="proprietary")
|
||||
# Frontmatter outside the schema. `metadata` is reserved on declarative classes, hence `meta`.
|
||||
meta: Mapped[dict] = mapped_column(
|
||||
"metadata", JSONB, nullable=False, server_default=text("'{}'::jsonb"))
|
||||
content_sha256: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
provenance: Mapped[dict | None] = mapped_column(JSONB)
|
||||
created_at: Mapped[dt.datetime] = _created_at()
|
||||
created_by: Mapped[uuid.UUID] = _user_fk()
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint("skill_id", "n", name="uq_skill_version_skill_n"),
|
||||
CheckConstraint("n >= 1", name="n_positive"),
|
||||
CheckConstraint("char_length(description) <= 1024", name="description_length"),
|
||||
CheckConstraint("char_length(body_md) <= 30000", name="body_length"),
|
||||
CheckConstraint("octet_length(metadata::text) <= 8192", name="metadata_size"),
|
||||
CheckConstraint("content_sha256 ~ '^[0-9a-f]{64}$'", name="content_sha256"),
|
||||
)
|
||||
|
||||
|
||||
class SkillFile(UUIDPkMixin, Base):
|
||||
__tablename__ = "skill_file"
|
||||
|
||||
skill_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("skill_version.id", ondelete="RESTRICT"), nullable=False)
|
||||
path: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
media_type: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
size: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
sha256: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
# The original bytes, kept for export.
|
||||
content: Mapped[bytes] = mapped_column(LargeBinary, nullable=False)
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint("skill_version_id", "path", name="uq_skill_file_version_path"),
|
||||
CheckConstraint("size >= 0", name="size"),
|
||||
CheckConstraint("sha256 ~ '^[0-9a-f]{64}$'", name="sha256"),
|
||||
)
|
||||
|
||||
|
||||
class Agent(UUIDPkMixin, TimestampMixin, Base):
|
||||
__tablename__ = "agent"
|
||||
|
||||
name: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
owner_id: Mapped[uuid.UUID] = _user_fk()
|
||||
scope: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, server_default=SkillScope.personal.value)
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, server_default=CatalogStatus.active.value)
|
||||
kind: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, server_default=AgentKind.assistant.value)
|
||||
current_version_id: Mapped[uuid.UUID | None] = mapped_column(
|
||||
ForeignKey("agent_version.id", ondelete="RESTRICT", use_alter=True))
|
||||
|
||||
__table_args__ = (
|
||||
CheckConstraint(_one_of("scope", SkillScope), name="scope"),
|
||||
CheckConstraint(_one_of("status", CatalogStatus), name="status"),
|
||||
CheckConstraint(_one_of("kind", AgentKind), name="kind"),
|
||||
Index("ix_agent_owner_id", "owner_id"),
|
||||
Index("ix_agent_scope", "scope"),
|
||||
)
|
||||
|
||||
|
||||
class AgentVersion(UUIDPkMixin, Base):
|
||||
__tablename__ = "agent_version"
|
||||
|
||||
agent_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("agent.id", ondelete="RESTRICT"), nullable=False)
|
||||
n: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
instructions_md: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
# A hint, never a grant (D3): the platform decides which model and tools an agent gets.
|
||||
model_policy: Mapped[dict | None] = mapped_column(JSONB)
|
||||
tools_requested: Mapped[list[str]] = mapped_column(
|
||||
ARRAY(Text), nullable=False, server_default=text("'{}'::text[]"))
|
||||
created_at: Mapped[dt.datetime] = _created_at()
|
||||
created_by: Mapped[uuid.UUID] = _user_fk()
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint("agent_id", "n", name="uq_agent_version_agent_n"),
|
||||
CheckConstraint("n >= 1", name="n_positive"),
|
||||
)
|
||||
|
||||
|
||||
class AgentVersionSkill(Base):
|
||||
"""A skill VERSION pinned to an agent version — a row, not a UUID array, so RESTRICT holds:
|
||||
archiving a skill leaves every agent running on the version it pinned."""
|
||||
__tablename__ = "agent_version_skill"
|
||||
|
||||
agent_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("agent_version.id", ondelete="RESTRICT"), primary_key=True)
|
||||
skill_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||
ForeignKey("skill_version.id", ondelete="RESTRICT"), primary_key=True)
|
||||
position: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint("agent_version_id", "position",
|
||||
name="uq_agent_version_skill_version_position"),
|
||||
Index("ix_agent_version_skill_skill_version_id", "skill_version_id"),
|
||||
)
|
||||
|
||||
|
||||
class PublishRequest(UUIDPkMixin, TimestampMixin, Base):
|
||||
"""Asks an administrator to publish ONE version to the firm (T1: every version, not only the
|
||||
first). `version_id` names a `skill_version` or an `agent_version` according to `kind`, so it
|
||||
carries no foreign key; the service resolves it, and versions are never deleted."""
|
||||
__tablename__ = "publish_request"
|
||||
|
||||
kind: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
version_id: Mapped[uuid.UUID] = mapped_column(nullable=False)
|
||||
requested_by: Mapped[uuid.UUID] = _user_fk()
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(16), nullable=False, server_default=PublishRequestStatus.pending.value)
|
||||
decided_by: Mapped[uuid.UUID | None] = _user_fk(nullable=True)
|
||||
decided_at: Mapped[dt.datetime | None] = mapped_column(DateTime(timezone=True))
|
||||
note: Mapped[str | None] = mapped_column(Text)
|
||||
|
||||
__table_args__ = (
|
||||
CheckConstraint(_one_of("kind", PublishKind), name="kind"),
|
||||
CheckConstraint(_one_of("status", PublishRequestStatus), name="status"),
|
||||
# One open request per version; decided ones accumulate as history.
|
||||
Index("uq_publish_request_pending", "kind", "version_id", unique=True,
|
||||
postgresql_where=text("status = 'pending'")),
|
||||
Index("ix_publish_request_status", "status"),
|
||||
)
|
||||
@@ -1,8 +1,9 @@
|
||||
"""A model provider's API key at rest — the platform's one cipher, as the hub writes it.
|
||||
|
||||
**Byte-compatible with Compass** (`apps/compass/backend/app/provider_keys.py`, by Tobiasz Badura,
|
||||
Apache-2.0): Compass's analyses decrypt the keys this file encrypts, and the keys Compass imported
|
||||
through `import_model_providers` are decrypted here. dredd-core 0.15.0 holds no key and stores
|
||||
**Byte-compatible with Arbiter** (`apps/arbiter/backend/app/provider_keys.py` in `Alpaq92/Arbiter`,
|
||||
itself ported from the retired Compass's, by Tobiasz Badura, Apache-2.0): Arbiter's runs decrypt the
|
||||
keys this file encrypts, and the keys Compass once imported through `import_model_providers` are
|
||||
decrypted here. dredd-core 0.15.0 holds no key and stores
|
||||
whatever string it is handed (`dredd_core.model_providers`, "The key at rest"), so this format IS
|
||||
the contract between the two apps:
|
||||
|
||||
@@ -10,15 +11,15 @@ the contract between the two apps:
|
||||
* AES-256-GCM, a 12-byte random nonce, no associated data;
|
||||
* stored as ``v1.<nonce>.<ciphertext>``, both URL-safe base64.
|
||||
|
||||
`tests/test_provider_keys_unit.py` encrypts here and decrypts with Compass's own code from the
|
||||
vendored `deploy/modules/compass` checkout, and the other way round — change neither side without
|
||||
`tests/test_provider_keys_unit.py` encrypts here and decrypts with Arbiter's own code from the
|
||||
vendored `deploy/modules/arbiter` checkout, and the other way round — change neither side without
|
||||
the other. The cipher belongs in dredd-core once both apps move to it; until then two copies kept
|
||||
honest by that test beat one app importing the other.
|
||||
|
||||
The secret is ONE value for the whole platform (`env/atrium.env` and `env/compass.env`, written by
|
||||
`deploy/init.sh`), never in the database. Unlike Compass, the hub has no fallback to another key:
|
||||
The secret is ONE value for the whole platform (`env/atrium.env`, `env/arbiter.env` and `env/lexicon.env`,
|
||||
written by `deploy/init.sh`), never in the database. Unlike a standalone module, the hub has no fallback to another key:
|
||||
with `MODEL_PROVIDER_SECRET` empty it refuses to store a key (`services/providers.py`) rather than
|
||||
write one Compass could never read.
|
||||
write one no module could ever read.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
@@ -5,8 +5,8 @@ sent for every module at once, so the platform-wide tier is the only one that ma
|
||||
module's moderator sees them read-only in that module, and its writes are 409s there).
|
||||
|
||||
Never returns a key: a key is write-only, set or replaced through `api_key`, removed with
|
||||
`clear: ["api_key"]`, and described by `has_key` / `key_prefix` alone. Nothing here calls a provider
|
||||
(`services/providers.py` says why there is no "test connection").
|
||||
`clear: ["api_key"]`, and described by `has_key` / `key_prefix` alone. Only `discover` and `refresh`
|
||||
call a provider — to list its models — and both end the DB transaction before they do.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -18,13 +18,19 @@ from sqlalchemy.orm import Session
|
||||
from ..db import get_db
|
||||
from ..deps import client_ip, require_administrator
|
||||
from ..models import AppUser
|
||||
from ..schemas import ProviderCreateIn, ProviderPolicyIn, ProviderUpdateIn
|
||||
from ..schemas import (
|
||||
ProviderCreateIn,
|
||||
ProviderDiscoverIn,
|
||||
ProviderDiscoverOut,
|
||||
ProviderPolicyIn,
|
||||
ProviderUpdateIn,
|
||||
)
|
||||
from ..services import providers as service
|
||||
|
||||
router = APIRouter(prefix="/admin/model-providers", tags=["admin: model providers"])
|
||||
|
||||
|
||||
# The policy routes come before `/{provider_id}`, so "policy" is never parsed as an id.
|
||||
# The policy and discover routes come before `/{provider_id}`, so neither word is parsed as an id.
|
||||
@router.get("/policy")
|
||||
def read_policy(db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(require_administrator)) -> dict:
|
||||
@@ -40,6 +46,15 @@ def update_policy(body: ProviderPolicyIn, request: Request, db: Session = Depend
|
||||
return out
|
||||
|
||||
|
||||
@router.post("/discover", response_model=ProviderDiscoverOut)
|
||||
async def discover_provider(body: ProviderDiscoverIn, request: Request, db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_administrator)) -> dict:
|
||||
db.commit() # no transaction held across the outbound call (up to model_server.LIST_DEADLINE)
|
||||
out = await service.discover(db, admin, body.input, body.key, ip=client_ip(request))
|
||||
db.commit() # the audit row
|
||||
return out
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_providers(db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(require_administrator)) -> list[dict]:
|
||||
@@ -76,3 +91,19 @@ def disable_provider(provider_id: uuid.UUID, request: Request, db: Session = Dep
|
||||
out = service.disable(db, admin, provider_id, ip=client_ip(request))
|
||||
db.commit()
|
||||
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:
|
||||
out = await service.refresh(db, admin, provider_id, ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
@@ -9,11 +9,11 @@ from fastapi import APIRouter, Depends, Query, Request
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..deps import client_ip, get_current_user
|
||||
from ..deps import client_ip, get_current_user, require_administrator
|
||||
from ..models import AppUser
|
||||
from ..schemas import NoteIn
|
||||
from ..services import marketplace as service
|
||||
from ..services import stats
|
||||
from ..services import stats, trends
|
||||
|
||||
router = APIRouter(tags=["marketplace"])
|
||||
|
||||
@@ -30,6 +30,14 @@ def home_stats(db: Session = Depends(get_db),
|
||||
return stats.home(db, user)
|
||||
|
||||
|
||||
@router.get("/home/trends")
|
||||
def home_trends(db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(require_administrator)) -> dict:
|
||||
"""Trends from the event log: events per day and kind over 30 days, and how long documents took
|
||||
from their first version to signature. Platform-wide sums, so platform administrators only."""
|
||||
return trends.home(db)
|
||||
|
||||
|
||||
@router.get("/marketplace")
|
||||
def browse(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user),
|
||||
q: str = Query("", max_length=100),
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
"""Home's "ask the model": the models a person may use, and one streamed answer.
|
||||
|
||||
The address and key come only from `model_provider` (dredd-core, written by the hub's administrator
|
||||
through `admin_providers`), resolved by `services/providers.call_target` from a model id — never from
|
||||
settings, never from the request. Roman's conditions (Atrium #6) hold: session checked on the server,
|
||||
a rate limit and caps on the question and the answer, an audit row per ask (who, which model, which
|
||||
provider, whose key — never the question), and a refusal when nobody offers the model.
|
||||
|
||||
Only an administrator's ask may switch the model loaded on a local provider: anyone else asking for
|
||||
another one gets a 409 naming the running model, before anything is loaded, evicted or audited.
|
||||
|
||||
There is no door for modules here: a module that calls a model itself reads the provider, and with
|
||||
the key opt-in its key, from the shared tables (core's design).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
from collections import defaultdict, deque
|
||||
from datetime import date
|
||||
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
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 MyModelKeyIn
|
||||
from ..services import audit, providers
|
||||
|
||||
router = APIRouter(tags=["models"])
|
||||
|
||||
MAX_ANSWER_TOKENS = 8192 # thinking models spend most of it reasoning; 1024 cut Qwen off before a word
|
||||
#: The whole question as sent: history, tool calls, tool results AND the tool definitions. Counting
|
||||
#: only `content` left `tools` / `tool_calls` unbounded (review on #27).
|
||||
MAX_PROMPT_CHARS = 160_000 # history plus up to 8 rounds of tool results (up to 30k chars each); context is 64k tokens
|
||||
#: Model rounds per person per minute: one question is several (each tool call costs a round).
|
||||
#: ponytail: in-process, per worker; the image runs one worker.
|
||||
ASKS_PER_MINUTE = 40
|
||||
_asks: dict[uuid.UUID, deque] = defaultdict(deque)
|
||||
|
||||
#: The browser sends the sources (Home reads the modules with the asker's session); the model only reads them.
|
||||
SYSTEM = """Jesteś asystentem kancelarii. Dziś jest {today}. Odpowiadasz WYŁĄCZNIE na podstawie ponumerowanych źródeł z pytania.
|
||||
Zasady:
|
||||
1. Każde zdanie z faktem kończ numerem źródła w nawiasie kwadratowym, np. [2].
|
||||
2. Sumy, liczby i rankingi przepisuj ze źródeł typu „zestawienie” albo „ranking”. Nie licz sam.
|
||||
3. Jeśli źródła nie zawierają odpowiedzi, napisz: „W danych, do których masz dostęp, nie znalazłem odpowiedzi.” i nic nie dopowiadaj. Nie twierdź, że czegoś nie ma w ogóle.
|
||||
4. Pisz krótko, po polsku (po angielsku, jeśli pytanie jest po angielsku), bez identyfikatorów technicznych.
|
||||
5. Pytanie niezwiązane z pracą kancelarii: odpowiedz jednym zdaniem, że pomagasz w danych kancelarii.
|
||||
6. Dwie pierwsze wymiany w tej rozmowie to PRZYKŁADY formatu z fikcyjnymi danymi. Nigdy nie cytuj z nich nazw ani liczb.
|
||||
7. Wcześniejsze odpowiedzi w tej rozmowie mogą być błędne. Każde nowe twierdzenie opieraj na aktualnych źródłach. Gdy użytkownik poprawia odpowiedź, sprawdź to w źródłach i albo przyznaj mu rację, albo wskaż źródło, które mówi inaczej."""
|
||||
|
||||
|
||||
@router.get("/models")
|
||||
def list_models(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
|
||||
"""`configured` is false when this person may use no model at all, and Home stays the plain search.
|
||||
ponytail: `choices` / `modules` stay empty for the console in #29 until its Models page goes."""
|
||||
models = providers.usable_models(db, user)
|
||||
return {"configured": bool(models), "models": models, "choices": {}, "modules": []}
|
||||
|
||||
|
||||
# ── a person's own keys (dredd-core 0.18.0, key_mode = "user") ───────────────
|
||||
# Write-only like the firm's key: in through `set_user_key`, out only as `key_prefix`.
|
||||
|
||||
@router.get("/me/model-keys")
|
||||
def my_model_keys(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
|
||||
return providers.my_keys(db, user)
|
||||
|
||||
|
||||
@router.put("/me/model-keys/{provider_id}")
|
||||
def set_my_model_key(provider_id: uuid.UUID, body: MyModelKeyIn, 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("/me/model-keys/{provider_id}")
|
||||
def clear_my_model_key(provider_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = providers.clear_my_key(db, user, provider_id, ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
class Message(BaseModel):
|
||||
role: str = Field(pattern="^(user|assistant|tool)$")
|
||||
content: str | None = Field(default=None, max_length=MAX_PROMPT_CHARS)
|
||||
tool_calls: list[dict] | None = Field(default=None, max_length=10)
|
||||
tool_call_id: str | None = Field(default=None, max_length=200)
|
||||
|
||||
|
||||
class AskIn(BaseModel):
|
||||
"""The tools are the browser's: it runs each call against the modules with the asker's own
|
||||
session, so what the model may read is decided by the modules, never here."""
|
||||
model: str = Field(min_length=1, max_length=200)
|
||||
messages: list[Message] = Field(min_length=1, max_length=80)
|
||||
tools: list[dict] | None = Field(default=None, max_length=10)
|
||||
tool_choice: str | None = Field(default=None, pattern="^(auto|required|none)$")
|
||||
temperature: float | None = Field(default=None, ge=0, le=2)
|
||||
top_p: float | None = Field(default=None, ge=0, le=1)
|
||||
top_k: int | None = Field(default=None, ge=1, le=200)
|
||||
presence_penalty: float | None = Field(default=None, ge=-2, le=2)
|
||||
max_tokens: int | None = Field(default=None, ge=64, le=16384)
|
||||
thinking: bool | None = None
|
||||
|
||||
|
||||
def prompt_size(body: AskIn) -> int:
|
||||
"""Characters of everything the model is sent besides the system prompt."""
|
||||
return len(json.dumps(body.model_dump(include={"messages", "tools"}, exclude_none=True),
|
||||
ensure_ascii=False))
|
||||
|
||||
|
||||
def _sampling(body: AskIn, vendor: str | None = None) -> dict:
|
||||
"""The person's sampling knobs, only those they set; the model's defaults otherwise.
|
||||
|
||||
`thinking=False` is `reasoning_effort: "none"`: against LM Studio with qwen/qwen3.5-9b (2026-10-29)
|
||||
it alone stopped the reasoning (4 completion tokens, 0.4 s, no reasoning_content, against 316-863
|
||||
tokens and 3-27 s by default). `chat_template_kwargs {"enable_thinking": false}`, `reasoning: "off"`
|
||||
and a trailing `/no_think` were ignored or only shortened it, so they are not sent.
|
||||
Do not swap this for the `chat_template_kwargs` form the Qwen3.5 model card recommends: re-measured
|
||||
2026-11-03 (LM Studio, llama.cpp CUDA 2.41.0) the model still reasoned, spent the whole max_tokens
|
||||
on it and returned an EMPTY answer, on /v1 and /api/v0 alike."""
|
||||
out = body.model_dump(include={"temperature", "top_p", "top_k", "presence_penalty"},
|
||||
exclude_none=True)
|
||||
if body.thinking is False:
|
||||
out["reasoning_effort"] = "none"
|
||||
if vendor == "anthropic":
|
||||
# Newer Claude models refuse `temperature` outright (400 "deprecated for this model",
|
||||
# claude-opus-5-5, 2026-11-06); the knobs were tuned for small local models anyway.
|
||||
for k in ("temperature", "top_p", "top_k"):
|
||||
out.pop(k, None)
|
||||
return out
|
||||
|
||||
|
||||
def _rate_limit(user_id: uuid.UUID) -> None:
|
||||
now = time.monotonic()
|
||||
seen = _asks[user_id]
|
||||
while seen and now - seen[0] > 60:
|
||||
seen.popleft()
|
||||
if len(seen) >= ASKS_PER_MINUTE:
|
||||
raise ConflictError(f"Za dużo pytań naraz: najwyżej {ASKS_PER_MINUTE} na minutę.")
|
||||
seen.append(now)
|
||||
|
||||
|
||||
def _busy(exc: model_server.ModelBusy) -> dict:
|
||||
"""The Problem Details extras of a refusal, also carried by the stream's `error` event."""
|
||||
return {"code": exc.code, "en": exc.en, "running": exc.running}
|
||||
|
||||
|
||||
def _event(payload: dict) -> bytes:
|
||||
return f"event: atrium\ndata: {json.dumps(payload, ensure_ascii=False)}\n\n".encode()
|
||||
|
||||
|
||||
@router.post("/models/ask")
|
||||
async def ask(body: AskIn, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> StreamingResponse:
|
||||
"""Server-sent events: the model server's own chunks, plus `event: atrium` for loading and errors."""
|
||||
if prompt_size(body) > MAX_PROMPT_CHARS:
|
||||
raise ValidationError("Pytanie z historią rozmowy jest za długie.")
|
||||
target = providers.call_target(db, user, body.model)
|
||||
_rate_limit(user.id)
|
||||
root, key = model_server.server_root(target["base_url"]), target["key"]
|
||||
may_switch = bool(user.is_admin)
|
||||
loaded = await model_server.loaded_models(root, key) if target["kind"] == "local" else None
|
||||
if loaded is not None and not may_switch:
|
||||
try:
|
||||
model_server.refuse_switch(loaded, body.model)
|
||||
except model_server.ModelBusy as exc:
|
||||
raise ConflictError(str(exc), _busy(exc)) from exc
|
||||
audit.record(db, action="model.ask", entity_type="model", actor_id=user.id,
|
||||
detail=body.model, ip=client_ip(request),
|
||||
diff={"model": body.model, "provider": target["provider"],
|
||||
"key_source": target["key_source"]})
|
||||
db.commit()
|
||||
messages = [{"role": "system", "content": SYSTEM.format(today=date.today())},
|
||||
*(m.model_dump(exclude_none=True) for m in body.messages)]
|
||||
tools = {"tools": body.tools, "tool_choice": body.tool_choice} if body.tools else {}
|
||||
extra = {**tools, **_sampling(body, providers.vendor_of(target["base_url"]))}
|
||||
max_tokens = body.max_tokens or MAX_ANSWER_TOKENS
|
||||
|
||||
async def events():
|
||||
try:
|
||||
if loaded is not None and not loaded.get(body.model):
|
||||
yield _event({"loading": body.model})
|
||||
await model_server.ensure_loaded(root, key, body.model, may_switch=may_switch)
|
||||
yield _event({"loaded": body.model})
|
||||
async for chunk in model_server.stream_chat(root, key, body.model, messages, max_tokens, **extra):
|
||||
yield chunk
|
||||
except model_server.ModelBusy as exc: # lost the race for the lock: same refusal, mid-stream
|
||||
yield _event({"error": str(exc), **_busy(exc)})
|
||||
except model_server.GatewayError as exc:
|
||||
yield _event({"error": str(exc)})
|
||||
|
||||
return StreamingResponse(events(), media_type="text/event-stream",
|
||||
headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"})
|
||||
@@ -0,0 +1,260 @@
|
||||
"""A person's skills and agents: list, read, write versions, archive, publish, export and import —
|
||||
and the approvers' queue of publish requests that the T1 setting (`skills_firm_publish`) fills.
|
||||
|
||||
No access rule lives here. Skills are not org-tree nodes, so `authz` has nothing to say about them;
|
||||
`services/skills.py` is the one place that decides who sees and changes what (its docstring says why
|
||||
that is a deliberate exception) — somebody else's personal skill is a 404 from the service.
|
||||
|
||||
Import takes the ZIP as the raw request body (`application/zip`, the name in `?filename=`) rather
|
||||
than a multipart form: one fewer dependency (`python-multipart`), and the 10 MB ceiling is enforced
|
||||
while reading, not after a whole upload sits in memory.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, Request, Response
|
||||
from fastapi.routing import APIRoute
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_db
|
||||
from ..deps import client_ip, get_current_user, require_skill_approver
|
||||
from ..models import AppUser
|
||||
from ..schemas import AgentCreateIn, AgentVersionIn, NoteIn, SkillCreateIn, SkillVersionIn
|
||||
from ..services import skills as service
|
||||
from ..services.skill_pack import MAX_PACK_BYTES, PackRejected
|
||||
|
||||
# A version with every file in base64: 10 MB of files is ~13.4 MB of JSON, plus the text fields.
|
||||
MAX_JSON_BODY_BYTES = 14 * 1024 * 1024
|
||||
|
||||
|
||||
class CappedBodyRoute(APIRoute):
|
||||
"""Reads a JSON body under `MAX_JSON_BODY_BYTES` while it streams, before FastAPI parses it.
|
||||
Without this the whole body (up to the front door's 100 MB) sits in memory before
|
||||
`_decoded_files` counts the 10 MB. The ZIP import is left to `zip_body`, which streams its own."""
|
||||
|
||||
def get_route_handler(self):
|
||||
handler = super().get_route_handler()
|
||||
|
||||
async def capped(request: Request) -> Response:
|
||||
if (request.method in ("POST", "PUT", "PATCH")
|
||||
and not request.headers.get("content-type", "").startswith("application/zip")):
|
||||
declared = request.headers.get("content-length", "")
|
||||
if declared.isdigit() and int(declared) > MAX_JSON_BODY_BYTES:
|
||||
raise PackRejected("pack_too_large")
|
||||
body = bytearray()
|
||||
async for chunk in request.stream():
|
||||
body += chunk
|
||||
if len(body) > MAX_JSON_BODY_BYTES:
|
||||
raise PackRejected("pack_too_large")
|
||||
request._body = bytes(body) # Starlette's cache: FastAPI's `request.body()` reads it
|
||||
return await handler(request)
|
||||
|
||||
return capped
|
||||
|
||||
|
||||
router = APIRouter(prefix="/skills", tags=["skills"], route_class=CappedBodyRoute)
|
||||
agents = APIRouter(prefix="/agents", tags=["agents"], route_class=CappedBodyRoute)
|
||||
publish_requests = APIRouter(prefix="/admin/publish-requests", tags=["admin: publish requests"])
|
||||
|
||||
_ZIP_BODY = {"requestBody": {"required": True, "content": {
|
||||
"application/zip": {"schema": {"type": "string", "format": "binary"}}}}}
|
||||
|
||||
|
||||
async def zip_body(request: Request, _: AppUser = Depends(get_current_user)) -> bytes:
|
||||
"""The raw body, refused as soon as it passes `MAX_PACK_BYTES` — the same `pack_too_large` an
|
||||
oversized pack gets from `read_pack`, so the console words both alike. Depends on the user so
|
||||
nobody unauthenticated makes us read 10 MB."""
|
||||
declared = request.headers.get("content-length", "")
|
||||
if declared.isdigit() and int(declared) > MAX_PACK_BYTES:
|
||||
raise PackRejected("pack_too_large")
|
||||
data = bytearray()
|
||||
async for chunk in request.stream():
|
||||
data += chunk
|
||||
if len(data) > MAX_PACK_BYTES:
|
||||
raise PackRejected("pack_too_large")
|
||||
return bytes(data)
|
||||
|
||||
|
||||
def zip_response(name: str, data: bytes) -> Response:
|
||||
# `name` is `<kebab slug>-v<n>.zip`, so it needs no quoting beyond the quotes.
|
||||
return Response(data, media_type="application/zip",
|
||||
headers={"Content-Disposition": f'attachment; filename="{name}"'})
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_skills(db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> list[dict]:
|
||||
return service.list_skills(db, user)
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
def create_skill(body: SkillCreateIn, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = service.create_skill(db, user, body.model_dump(), ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
# Before `/{skill_id}/...` only for readability: no other POST route has one segment.
|
||||
@router.post("/import", openapi_extra=_ZIP_BODY)
|
||||
def import_skills(request: Request, filename: str | None = Query(default=None, max_length=255),
|
||||
add_version: bool = False, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user),
|
||||
data: bytes = Depends(zip_body)) -> dict:
|
||||
out = service.import_skills(db, user, data, filename, add_version=add_version,
|
||||
ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
# Before `/{skill_id}`, which would take "permissions" for an id and answer 422.
|
||||
@router.get("/permissions")
|
||||
def permissions(db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
|
||||
return {"approve": service.may_approve(db, user)}
|
||||
|
||||
|
||||
@router.get("/{skill_id}")
|
||||
def get_skill(skill_id: uuid.UUID, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
return service.get_skill(db, user, skill_id)
|
||||
|
||||
|
||||
@router.post("/{skill_id}/versions", status_code=201)
|
||||
def new_version(skill_id: uuid.UUID, body: SkillVersionIn, request: Request,
|
||||
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user)) -> dict:
|
||||
# model_dump(), not exclude_none: the service reads None as "carry over" per field.
|
||||
out = service.new_version(db, user, skill_id, body.model_dump(), ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/{skill_id}/versions/{n}")
|
||||
def get_version(skill_id: uuid.UUID, n: int, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
return service.get_version(db, user, skill_id, n)
|
||||
|
||||
|
||||
@router.get("/{skill_id}/versions/{n}/files/{path:path}")
|
||||
def get_file(skill_id: uuid.UUID, n: int, path: str, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> Response:
|
||||
media_type, content = service.get_file(db, user, skill_id, n, path)
|
||||
return Response(content=content, media_type=media_type)
|
||||
|
||||
|
||||
@router.post("/{skill_id}/archive")
|
||||
def archive_skill(skill_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = service.archive_skill(db, user, skill_id, ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@router.post("/{skill_id}/publish")
|
||||
def publish_skill(skill_id: uuid.UUID, request: Request, n: int | None = Query(default=None, ge=1),
|
||||
db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = service.publish_skill(db, user, skill_id, n, ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@router.get("/{skill_id}/export")
|
||||
def export_skill(skill_id: uuid.UUID, request: Request, n: int | None = Query(default=None, ge=1),
|
||||
db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> Response:
|
||||
name, data = service.export_skill(db, user, skill_id, n, ip=client_ip(request))
|
||||
db.commit() # the export's audit row
|
||||
return zip_response(name, data)
|
||||
|
||||
|
||||
@agents.get("")
|
||||
def list_agents(db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> list[dict]:
|
||||
return service.list_agents(db, user)
|
||||
|
||||
|
||||
@agents.post("", status_code=201)
|
||||
def create_agent(body: AgentCreateIn, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = service.create_agent(db, user, body.model_dump(), ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@agents.post("/import", openapi_extra=_ZIP_BODY)
|
||||
def import_agent(request: Request, filename: str | None = Query(default=None, max_length=255),
|
||||
db: Session = Depends(get_db), user: AppUser = Depends(get_current_user),
|
||||
data: bytes = Depends(zip_body)) -> dict:
|
||||
out = service.import_agent(db, user, data, filename, ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@agents.get("/{agent_id}")
|
||||
def get_agent(agent_id: uuid.UUID, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
return service.get_agent(db, user, agent_id)
|
||||
|
||||
|
||||
@agents.post("/{agent_id}/versions", status_code=201)
|
||||
def new_agent_version(agent_id: uuid.UUID, body: AgentVersionIn, request: Request,
|
||||
db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = service.new_agent_version(db, user, agent_id, body.model_dump(), ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@agents.post("/{agent_id}/archive")
|
||||
def archive_agent(agent_id: uuid.UUID, request: Request, db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = service.archive_agent(db, user, agent_id, ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@agents.post("/{agent_id}/publish")
|
||||
def publish_agent(agent_id: uuid.UUID, request: Request, n: int | None = Query(default=None, ge=1),
|
||||
db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> dict:
|
||||
out = service.publish_agent(db, user, agent_id, n, ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@agents.get("/{agent_id}/export")
|
||||
def export_agent(agent_id: uuid.UUID, request: Request, n: int | None = Query(default=None, ge=1),
|
||||
db: Session = Depends(get_db),
|
||||
user: AppUser = Depends(get_current_user)) -> Response:
|
||||
name, data = service.export_agent(db, user, agent_id, n, ip=client_ip(request))
|
||||
db.commit()
|
||||
return zip_response(name, data)
|
||||
|
||||
|
||||
# The service checks the approver again; the guard here is what keeps the routes out of reach
|
||||
# of anybody else before a database is touched.
|
||||
@publish_requests.get("")
|
||||
def pending_publish_requests(db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_skill_approver)) -> list[dict]:
|
||||
return service.pending_publish_requests(db, admin)
|
||||
|
||||
|
||||
@publish_requests.post("/{request_id}/approve")
|
||||
def approve_publish(request_id: uuid.UUID, request: Request, body: NoteIn | None = None,
|
||||
db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_skill_approver)) -> dict:
|
||||
out = service.decide_publish(db, admin, request_id, approve=True,
|
||||
note=body.note if body else None, ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
|
||||
|
||||
@publish_requests.post("/{request_id}/decline")
|
||||
def decline_publish(request_id: uuid.UUID, request: Request, body: NoteIn | None = None,
|
||||
db: Session = Depends(get_db),
|
||||
admin: AppUser = Depends(require_skill_approver)) -> dict:
|
||||
out = service.decide_publish(db, admin, request_id, approve=False,
|
||||
note=body.note if body else None, ip=client_ip(request))
|
||||
db.commit()
|
||||
return out
|
||||
@@ -34,6 +34,7 @@ from ..schemas import (
|
||||
ModuleTokenIn,
|
||||
PasswordChangeIn,
|
||||
PasswordResetIn,
|
||||
UserBriefOut,
|
||||
UserCreateIn,
|
||||
UserOut,
|
||||
UserProfileIn,
|
||||
@@ -54,15 +55,31 @@ def _user_out(u: AppUser, modules: dict[str, str] | None = None) -> dict:
|
||||
"modules": modules or {}}
|
||||
|
||||
|
||||
@router.get("/users", response_model=list[UserOut])
|
||||
def _user_brief(u: AppUser) -> UserBriefOut:
|
||||
"""What anybody signed in may know about an account: who it is, and whether it can be picked."""
|
||||
return UserBriefOut(id=str(u.id), email=u.email, full_name=u.full_name, is_active=u.is_active)
|
||||
|
||||
|
||||
@router.get("/users", response_model=list[UserOut] | list[UserBriefOut])
|
||||
def list_users(db: Session = Depends(get_db),
|
||||
_: AppUser = Depends(get_current_user)) -> list[dict]:
|
||||
"""Every signed-in user may list users: the console needs names to render "assigned to"
|
||||
pickers, and an email address inside the instance is not the secret worth hiding here."""
|
||||
user: AppUser = Depends(get_current_user)) -> list[UserOut] | list[UserBriefOut]:
|
||||
"""Every signed-in user may list users: a picker needs names, and an email address inside the
|
||||
instance is not the secret worth hiding here.
|
||||
|
||||
**Who holds which tier is another matter, and only an administrator is told.** `is_admin` and
|
||||
the per-module roles are the map of whose account is worth taking over, and this route answers
|
||||
any credential — an ordinary account, a read-only app token. They used to come along because
|
||||
one helper built every row. So an administrator gets the whole standing (`UserOut`, what the
|
||||
Users screen draws) and everybody else gets `UserBriefOut`: the fields a picker uses and nothing
|
||||
about tiers. Absent, not `false` or empty: a row that said `is_admin: false` about an
|
||||
administrator would be a lie, and a client must not be able to mistake "not told" for "none".
|
||||
"""
|
||||
users = auth_service.list_users(db)
|
||||
if not user.is_admin:
|
||||
return [_user_brief(u) for u in users]
|
||||
# One query for the whole page, not one per row — see services/moderation.py.
|
||||
standing = moderation.module_roles_by_user(db, [u.id for u in users])
|
||||
return [_user_out(u, standing.get(u.id)) for u in users]
|
||||
return [UserOut(**_user_out(u, standing.get(u.id))) for u in users]
|
||||
|
||||
|
||||
@router.post("/users", response_model=UserOut, status_code=201)
|
||||
|
||||
+120
-3
@@ -6,15 +6,19 @@ field that is confirmed by sending mail to it anyway.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import json
|
||||
import re
|
||||
import uuid
|
||||
from typing import Annotated, Any
|
||||
|
||||
from dredd_core.identity import MODULE_ROLES
|
||||
from dredd_core.moderation import USER
|
||||
from pydantic import AfterValidator, BaseModel, Field
|
||||
from pydantic import AfterValidator, BaseModel, BeforeValidator, Field
|
||||
|
||||
from .enums import NodeRole
|
||||
from .services.skill_pack import MAX_PACK_BYTES
|
||||
|
||||
_EMAIL = re.compile(r"^[^@\s]+@[^@\s.]+(\.[^@\s.]+)+$")
|
||||
|
||||
@@ -70,6 +74,16 @@ class UserOut(BaseModel):
|
||||
modules: dict[str, str] = {}
|
||||
|
||||
|
||||
class UserBriefOut(BaseModel):
|
||||
"""A person as anybody signed in may see them in `GET /users`: enough to pick somebody, and
|
||||
nothing about what they may do. The tiers (`is_admin`, `modules`) are for administrators only
|
||||
and are left out here rather than blanked — see `routers/users.list_users`."""
|
||||
id: str
|
||||
email: str
|
||||
full_name: str
|
||||
is_active: bool
|
||||
|
||||
|
||||
class LoginOut(BaseModel):
|
||||
"""The reply to a sign-in: who signed in, and NOT the session token. That lives in the HttpOnly
|
||||
cookie only, where no page script can read it (`routers/auth.py`). `response_model` filters the
|
||||
@@ -201,6 +215,8 @@ class ModuleUpdateIn(BaseModel):
|
||||
status: str | None = Field(default=None, max_length=16)
|
||||
availability: str | None = Field(default=None, max_length=16)
|
||||
sort_order: int | None = Field(default=None, ge=0, le=10000)
|
||||
# False makes a service module: reachable as before, but no entry in the sidebar or catalogue.
|
||||
in_menu: bool | None = None
|
||||
|
||||
|
||||
class ModuleCreateIn(ModuleUpdateIn):
|
||||
@@ -240,7 +256,7 @@ class ProviderUpdateIn(BaseModel):
|
||||
name: str | None = Field(default=None, max_length=120)
|
||||
kind: str | None = Field(default=None, max_length=20)
|
||||
base_url: str | None = Field(default=None, max_length=2000)
|
||||
models: list[Any] | None = Field(default=None, max_length=100)
|
||||
models: list[Any] | None = Field(default=None, max_length=1000) # OpenRouter lists hundreds; the 2 MB listing cap bounds the rest
|
||||
trains_on_data: bool | None = None
|
||||
api_key: str | None = Field(default=None, max_length=4096, repr=False)
|
||||
region: str | None = Field(default=None, max_length=8)
|
||||
@@ -248,6 +264,9 @@ 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
|
||||
#: dredd-core 0.18.0: whose key a call carries (`firm` | `user` | `none`, core's `KEY_MODES`).
|
||||
#: Moving away from `user`, or changing `base_url`, deletes every personal key (core).
|
||||
key_mode: str | None = Field(default=None, max_length=20)
|
||||
clear: list[str] = Field(default_factory=list, max_length=10)
|
||||
|
||||
|
||||
@@ -255,16 +274,114 @@ class ProviderCreateIn(BaseModel):
|
||||
name: str = Field(max_length=120)
|
||||
kind: str = Field(max_length=20)
|
||||
base_url: str = Field(max_length=2000)
|
||||
models: list[Any] = Field(max_length=100)
|
||||
models: list[Any] = Field(max_length=1000)
|
||||
trains_on_data: bool
|
||||
api_key: str | None = Field(default=None, max_length=4096, repr=False)
|
||||
region: str | None = Field(default=None, max_length=8)
|
||||
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 ProviderDiscoverIn(BaseModel):
|
||||
"""What the administrator pasted: an API key, or a server's address (with its key if it needs one)."""
|
||||
input: str = Field(min_length=1, max_length=4096, repr=False)
|
||||
key: str | None = Field(default=None, max_length=4096, repr=False)
|
||||
|
||||
|
||||
class ProviderDiscoverOut(BaseModel):
|
||||
"""What `discover` recognised. Nothing is stored; the console sends it back through `POST ""`."""
|
||||
vendor: str | None
|
||||
name: str
|
||||
kind: str
|
||||
base_url: str
|
||||
models: list[Any]
|
||||
|
||||
|
||||
class ProviderPolicyIn(BaseModel):
|
||||
"""`None` = leave as it is."""
|
||||
level: str | None = Field(default=None, max_length=20)
|
||||
eu_only: bool | None = None
|
||||
|
||||
|
||||
# ── skills ─────────────────────────────────────────────────────────────────────
|
||||
# Lengths and transport only. What a skill may say (kebab slug, description ≤ 1024, body ≤ 30 000,
|
||||
# file types and signatures) is `services/skill_pack.read_pack`'s, so a typed skill and an imported
|
||||
# one are refused with the same `code`; a second copy here would answer a bare 422 first.
|
||||
|
||||
def _decoded_files(v: Any) -> Any:
|
||||
"""path -> base64 in, path -> bytes out, at most `MAX_PACK_BYTES` in total — the same ceiling
|
||||
as an uploaded pack, so a skill typed in the console cannot grow past what it could export."""
|
||||
if not isinstance(v, dict):
|
||||
return v # None, or a wrong type the field's own validation refuses
|
||||
out, total = {}, 0
|
||||
for path, b64 in v.items():
|
||||
try:
|
||||
out[path] = base64.b64decode(b64, validate=True)
|
||||
except (binascii.Error, ValueError, TypeError):
|
||||
raise ValueError(f"{path}: not valid base64.") from None
|
||||
total += len(out[path])
|
||||
if total > MAX_PACK_BYTES:
|
||||
raise ValueError("The files come to more than 10 MB.")
|
||||
return out
|
||||
|
||||
|
||||
SkillFiles = Annotated[dict[str, bytes] | None, BeforeValidator(_decoded_files)]
|
||||
|
||||
MAX_JSON_FIELD_BYTES = 8 * 1024
|
||||
|
||||
|
||||
def _small_json(v: Any) -> Any:
|
||||
"""A free-form JSON object capped at 8 KB serialised — the bound `metadata`'s CHECK already
|
||||
keeps in the database, enforced here too so an oversized one is a 422, not a database error."""
|
||||
if v is not None and len(json.dumps(v, allow_nan=False).encode("utf-8")) > MAX_JSON_FIELD_BYTES:
|
||||
raise ValueError("More than 8 KB of JSON.")
|
||||
return v
|
||||
|
||||
|
||||
SmallJson = Annotated[dict[str, Any] | None, AfterValidator(_small_json)]
|
||||
|
||||
|
||||
class SkillVersionIn(BaseModel):
|
||||
"""A new version. `None` = carried over from the base version; `files: {}` removes them all.
|
||||
|
||||
The base is `base_n` when given (the version the person was looking at, which they must be able
|
||||
to read: Ruling 15). Without it, Ruling 9: the actor's own newest version if it is newer than
|
||||
the current one, else the current one, else the owner's newest. Never "the newest overall",
|
||||
which may be somebody else's proposal."""
|
||||
name: str | None = Field(default=None, max_length=200)
|
||||
description: str | None = Field(default=None, max_length=2000)
|
||||
body: str | None = Field(default=None, max_length=60_000)
|
||||
license: str | None = Field(default=None, max_length=200)
|
||||
metadata: SmallJson = None
|
||||
files: SkillFiles = Field(default=None, max_length=200)
|
||||
# path -> base64: the previous version's files with these replaced or added. Not with `files`.
|
||||
file_updates: SkillFiles = Field(default=None, max_length=200)
|
||||
# The version this one is made on (the one the person was looking at); None = the default base.
|
||||
base_n: int | None = Field(default=None, ge=1)
|
||||
|
||||
|
||||
class SkillCreateIn(SkillVersionIn):
|
||||
slug: str = Field(min_length=1, max_length=64)
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
description: str = Field(min_length=1, max_length=2000)
|
||||
body: str = Field(max_length=60_000)
|
||||
|
||||
|
||||
class AgentVersionIn(BaseModel):
|
||||
"""A new agent version. `None` = carried over from the newest one; `skill_version_ids: []`
|
||||
unpins everything. `model_policy` and `tools` are a hint and a request, never a grant (D3)."""
|
||||
name: str | None = Field(default=None, max_length=200)
|
||||
instructions: str | None = Field(default=None, max_length=60_000)
|
||||
model_policy: SmallJson = None
|
||||
tools: list[Annotated[str, Field(max_length=200)]] | None = Field(default=None, max_length=50)
|
||||
skill_version_ids: list[uuid.UUID] | None = Field(default=None, max_length=100)
|
||||
|
||||
|
||||
class AgentCreateIn(AgentVersionIn):
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
instructions: str = Field(max_length=60_000)
|
||||
class MyModelKeyIn(BaseModel):
|
||||
"""A person's own API key for a `key_mode = "user"` provider. Write-only, like the firm's."""
|
||||
api_key: str = Field(max_length=4096, repr=False)
|
||||
|
||||
+98
-11
@@ -16,6 +16,7 @@ from .config import get_settings
|
||||
from .db import SessionLocal
|
||||
from .enums import Availability, ModuleStatus, NodeKind
|
||||
from .models import AppSetting, Module, Node
|
||||
from .services import archive_reader
|
||||
from .services import auth as auth_service
|
||||
from .services import marketplace
|
||||
|
||||
@@ -35,8 +36,11 @@ CATALOG_SEEDED = "_seed.catalog"
|
||||
# is already in the catalogue — an administrator added it by hand — only the marker is written; once
|
||||
# the marker exists the entry is never offered again, so deleting it afterwards sticks. A fresh
|
||||
# install gets these with the rest of FAMILY and sets their markers then. The next module that
|
||||
# joins appends its slug here; nothing ever leaves this tuple.
|
||||
ADDED_AFTER_FIRST_SEED: tuple[str, ...] = ("insider",)
|
||||
# joins appends its slug here. The one exception is Panorama, retired from the platform:
|
||||
# it left FAMILY and this tuple, a box seeded earlier keeps its row, hidden from the menu by
|
||||
# revision 0018, and a fresh install never offers it.
|
||||
ADDED_AFTER_FIRST_SEED: tuple[str, ...] = ("insider", "arbiter", "lexicon", "agora",
|
||||
"parafa", "scribe", "workflow")
|
||||
|
||||
|
||||
def _marker(slug: str) -> str:
|
||||
@@ -63,6 +67,8 @@ def _marker(slug: str) -> str:
|
||||
FAMILY: list[dict] = [
|
||||
{
|
||||
"slug": "galena", "name": "Galena", "hue": "violet", "glyph": "galena", "sort_order": 10,
|
||||
# A service, not a menu entry: other modules open its screens by link.
|
||||
"in_menu": False,
|
||||
"category": "Dokumenty",
|
||||
"tagline": "Dysk w chmurze z pełną historią zmian w repozytoriach git.",
|
||||
"description": (
|
||||
@@ -95,15 +101,6 @@ FAMILY: list[dict] = [
|
||||
"z wyszukiwaniem pełnotekstowym i kontrolą dostępu."
|
||||
),
|
||||
},
|
||||
{
|
||||
"slug": "compass", "name": "Compass", "hue": "blue", "glyph": "compass", "sort_order": 40,
|
||||
"category": "Umowy", "status": ModuleStatus.coming_soon.value,
|
||||
"tagline": "Zarządzanie umowami dla zespołów prawnych.",
|
||||
"description": (
|
||||
"Compass to system zarządzania umowami dla działów prawnych i kancelarii działających "
|
||||
"w wielu jurysdykcjach — z wariantami klauzul i asystą AI. W przygotowaniu."
|
||||
),
|
||||
},
|
||||
{
|
||||
# The catalogue is Polish-first and carries one language; in English the tagline reads
|
||||
# "Legal acts and case law". The slug is the module's own: its path (/insider), its schema,
|
||||
@@ -117,6 +114,92 @@ FAMILY: list[dict] = [
|
||||
"z cytatami, pełnymi tekstami aktów i serwerem MCP dla asystentów AI."
|
||||
),
|
||||
},
|
||||
{
|
||||
# Split out of Compass (the split plan's M1): the contract analysis — the queue, the engine
|
||||
# runner, the workstation and the lawyer's sign-off. Indigo is Arbiter's own brand colour
|
||||
# (Open Color indigo, its CLAUDE.md). In English the tagline reads "Contract analysis with
|
||||
# a lawyer's sign-off". The slug is its path (/arbiter), schema, roles and MODULE_SLUG.
|
||||
"slug": "arbiter", "name": "Arbiter", "hue": "indigo", "glyph": "shield", "sort_order": 60,
|
||||
# A service too, and a headless one: Arbiter has no console (Atrium#53, stage 2). Contracts
|
||||
# are checked from the chat and its report panel, which call Arbiter's API.
|
||||
"in_menu": False,
|
||||
"category": "Umowy",
|
||||
"tagline": "Analiza umów z akceptacją prawnika.",
|
||||
"description": (
|
||||
"Arbiter analizuje umowy: kolejka zleceń, silnik analizy uruchamiany na serwerze albo na "
|
||||
"stacji roboczej, czerwone linie i maskowanie danych, a na końcu akceptacja analizy "
|
||||
"przez prawnika i zamrożona karta umowy jako dowód."
|
||||
),
|
||||
},
|
||||
{
|
||||
# The clause and standards library (the split plan's M2). Green is Lexicon's own brand colour
|
||||
# (Open Color green, its CLAUDE.md). In English the tagline reads "The clause library and
|
||||
# standards". The slug is its path (/lexicon), schema, roles and MODULE_SLUG.
|
||||
"slug": "lexicon", "name": "Lexicon", "hue": "green", "glyph": "file", "sort_order": 70,
|
||||
# No console of its own (decision of 18.11, issue #53): a service the chat calls; the
|
||||
# catalogue and the menu show the three contract modules as one entry, „Umowy”.
|
||||
"in_menu": False,
|
||||
"category": "Umowy",
|
||||
"tagline": "Biblioteka klauzul.",
|
||||
"description": (
|
||||
"Lexicon tnie wzory umów na klauzule, indeksuje je do wyszukiwania pełnotekstowego, "
|
||||
"porządkuje według typów. Standardy sprawdzania umów są w skillach (Atrium → Skille)."
|
||||
),
|
||||
},
|
||||
{
|
||||
# Contract negotiations (the split plan's M3). Red is Agora's own brand colour (Open Color
|
||||
# red, its CLAUDE.md). In English the tagline reads "Contract negotiation rooms".
|
||||
"slug": "agora", "name": "Agora", "hue": "red", "glyph": "users", "sort_order": 80,
|
||||
"category": "Umowy",
|
||||
"tagline": "Pokoje negocjacji umów.",
|
||||
"description": (
|
||||
"Agora prowadzi negocjacje umowy: pokój na jednym dokumencie, rundy obu stron zapisywane "
|
||||
"jako kolejne wersje w Galenie, porównanie dwóch rund i wewnętrzne komentarze zespołu."
|
||||
),
|
||||
},
|
||||
{
|
||||
# Electronic signing of PDFs (the split plan's M6): PAdES signatures through pyHanko, on an
|
||||
# uploaded file or a Galena document. Yellow is Parafa's own brand colour (Open Color yellow,
|
||||
# its CLAUDE.md). In English the tagline reads "Electronic signing of PDF documents". The slug
|
||||
# is its path (/parafa), schema, roles and MODULE_SLUG.
|
||||
"slug": "parafa", "name": "Parafa", "hue": "yellow", "glyph": "key", "sort_order": 100,
|
||||
"category": "Dokumenty", "status": ModuleStatus.live.value,
|
||||
"tagline": "Podpisywanie dokumentów PDF podpisem elektronicznym.",
|
||||
"description": (
|
||||
"Parafa przyjmuje prośby o podpis dokumentu PDF — pliku przesłanego do modułu albo "
|
||||
"dokumentu z Galeny — podpisuje go podpisem PAdES, zapisuje podpisaną wersję z powrotem "
|
||||
"i sprawdza podpisy w dokumentach, które przychodzą z zewnątrz."
|
||||
),
|
||||
},
|
||||
{
|
||||
# Drafting from templates and clauses (the split plan's M7). Lime is Scribe's own brand colour
|
||||
# (Open Color lime, its CLAUDE.md). In English the tagline reads "Drafting documents from
|
||||
# templates and clauses". The slug is its path (/scribe), schema, roles and MODULE_SLUG.
|
||||
"slug": "scribe", "name": "Scribe", "hue": "lime", "glyph": "file", "sort_order": 110,
|
||||
# No console of its own (decision of 18.11, issue #53): a service the chat calls; the
|
||||
# catalogue and the menu show the three contract modules as one entry, „Umowy”.
|
||||
"in_menu": False,
|
||||
"category": "Dokumenty", "status": ModuleStatus.live.value,
|
||||
"tagline": "Tworzenie dokumentów z szablonów i klauzul.",
|
||||
"description": (
|
||||
"Scribe składa dokument z szablonu i klauzul z biblioteki Lexicon, sprawdza go regułami "
|
||||
"zapisanymi w kodzie i eksportuje gotowy projekt do Galeny jako nowy dokument."
|
||||
),
|
||||
},
|
||||
{
|
||||
# The platform's general approval engine (decision of 2026-11-18; not the retired `compass`,
|
||||
# whose slug revision 0014 removed). Gray is the one tile hue no sibling wears. In English the
|
||||
# tagline reads "Approval runs for documents, files and requests". The slug is its path
|
||||
# (/workflow), schema, roles and MODULE_SLUG.
|
||||
"slug": "workflow", "name": "Workflow", "hue": "gray", "glyph": "clock", "sort_order": 120,
|
||||
"category": "Dokumenty", "status": ModuleStatus.live.value,
|
||||
"tagline": "Obiegi akceptacji dokumentów, plików i wniosków.",
|
||||
"description": (
|
||||
"Workflow prowadzi obieg akceptacji — na dokumencie z Galeny, przesłanym pliku albo "
|
||||
"wniosku — przez etapy zatwierdzane przez osoby, grupy zatwierdzających albo role z "
|
||||
"Galeny, z historią każdej decyzji i powrotem do wcześniejszego etapu po odrzuceniu."
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
@@ -196,6 +279,10 @@ def run(session_factory: sessionmaker | None = None) -> None:
|
||||
for module in db.scalars(select(Module)).all():
|
||||
marketplace.sync_module(db, None, module)
|
||||
|
||||
# The Archive's technical account and its four grants (Atrium#53). Idempotent; its token is
|
||||
# minted once by an operator (`python -m app.archive_reader`), never here.
|
||||
archive_reader.ensure(db)
|
||||
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
@@ -57,6 +57,28 @@ def count_administrators(db: DbSession, *, excluding: uuid.UUID | None = None) -
|
||||
return db.scalar(stmt) or 0
|
||||
|
||||
|
||||
def _lock_administrators(db: DbSession) -> None:
|
||||
"""Hold every usable administrator's row until this transaction ends, so that the count that
|
||||
follows is still true when the change is written.
|
||||
|
||||
Without it the guard is a check followed by a write with nothing in between: "demote A" and
|
||||
"demote B", in flight at once, each count the other as still there, both pass, and the platform
|
||||
is left with nobody — the very state the guard is for, reached by two clicks landing together.
|
||||
With it the second request waits here; when the first commits, PostgreSQL re-checks the rows it
|
||||
waited for, and the count below (a new statement) sees what was committed, so the second one is
|
||||
refused.
|
||||
|
||||
`FOR NO KEY UPDATE`, not `FOR UPDATE`: every row another table writes with a foreign key to
|
||||
`app_user` — a session, an audit row, in any module — takes a key-share lock on the person, and
|
||||
`FOR UPDATE` would make all of those wait on an administrator's row. The weaker lock still
|
||||
excludes itself and every `UPDATE` of the row, which is all this needs. Ordered by id, so two
|
||||
requests always take the rows in the same order and cannot deadlock each other.
|
||||
"""
|
||||
db.execute(select(AppUser.id)
|
||||
.where(AppUser.is_admin.is_(True), AppUser.is_active.is_(True))
|
||||
.order_by(AppUser.id).with_for_update(key_share=True)).all()
|
||||
|
||||
|
||||
def _assert_not_last_administrator(db: DbSession, user: AppUser) -> None:
|
||||
"""Refuse a change that would leave the platform with no administrator who can sign in.
|
||||
|
||||
@@ -64,9 +86,14 @@ def _assert_not_last_administrator(db: DbSession, user: AppUser) -> None:
|
||||
administrator is perfectly ordinary while somebody else still holds the tier. What is refused is
|
||||
the *last* one, and the message says what to do instead, because a person who hits this guard
|
||||
has a job to finish and a bare 409 does not help them finish it.
|
||||
|
||||
Counted under a lock on the administrators' rows (`_lock_administrators`): the caller writes
|
||||
straight after this returns, in the same transaction, and two such changes must not each pass on
|
||||
a count the other is about to make false.
|
||||
"""
|
||||
if not user.is_admin or not user.is_active:
|
||||
return
|
||||
_lock_administrators(db)
|
||||
if count_administrators(db, excluding=user.id) == 0:
|
||||
raise ConflictError(
|
||||
"This is the last administrator. Make someone else an administrator first: with "
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
"""The Archive's technical account (Atrium#53, step 4): how Galena reads evidence without a person.
|
||||
|
||||
When Galena hears `document.signed` or `workflow.signed_on_paper` there is no person's token to
|
||||
collect the archive package with, so it uses this account's. Least privilege, in four layers:
|
||||
|
||||
* **No password, so no sign-in.** `password_hash` is NULL; `authenticate` refuses such an account
|
||||
with the same timing as a wrong password. The only credential is the app token minted here.
|
||||
* **A read-only token.** `scope = read`: every module refuses an unsafe method with it at the edge
|
||||
(the one exception is Parafa's `POST /seal`, which Parafa allows to this account alone).
|
||||
* **User tier in exactly four modules** — Parafa, Workflow, Agora, Arbiter — written directly, not
|
||||
through the catalogue's assignments, and kept out of the reconciliation (`marketplace._active_ids`
|
||||
leaves it out), so a module whose availability is `everyone` never admits it as well, and a sweep
|
||||
never takes these four away.
|
||||
* **A fixed id** (`ARCHIVE_READER_ID`) every module knows, which fences it to `GET /evidence` there
|
||||
(404 on every other route). An id, not an e-mail, so nobody can register their way into it.
|
||||
|
||||
The seed calls `ensure` on every deploy (idempotent). The token is minted once by an operator —
|
||||
`python -m app.archive_reader` in the hub's migrate container — and goes into Galena's deployment
|
||||
as `ARCHIVE_READER_TOKEN`; it is printed once and never stored here.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from ..config import get_settings
|
||||
from ..models import AppUser, Session
|
||||
from . import accounts, audit, moderation
|
||||
|
||||
EMAIL = "archive-reader@archiwum.galena"
|
||||
FULL_NAME = "Archiwum (konto techniczne)"
|
||||
#: The modules Galena collects evidence from, as `user`. Nothing else.
|
||||
MODULES = ("parafa", "workflow", "agora", "arbiter")
|
||||
TOKEN_NAME = "Galena: archiwum"
|
||||
|
||||
|
||||
def reader_id():
|
||||
"""The fixed id every module fences (their `ARCHIVE_READER_ID`): change both together."""
|
||||
return get_settings().archive_reader_id
|
||||
|
||||
|
||||
def ensure(db: DbSession) -> AppUser:
|
||||
"""The account and its four grants, created when missing. No commit; nothing when it is there."""
|
||||
user = db.get(AppUser, reader_id())
|
||||
if user is None:
|
||||
user = AppUser(id=reader_id(), email=EMAIL, full_name=FULL_NAME, password_hash=None,
|
||||
is_admin=False, is_active=True)
|
||||
db.add(user)
|
||||
db.flush()
|
||||
audit.record(db, action="archive_reader.created", entity_type="user", entity_id=user.id,
|
||||
actor_id=None, detail=",".join(MODULES))
|
||||
if get_settings().shares_identity and user.is_active:
|
||||
held = moderation.module_roles(db, user.id)
|
||||
for slug in MODULES:
|
||||
if slug not in held:
|
||||
moderation.grant(db, None, module_slug=slug, user_id=user.id,
|
||||
role=moderation.USER)
|
||||
return user
|
||||
|
||||
|
||||
def mint(db: DbSession) -> tuple[Session, str]:
|
||||
"""A read-only app token for the account, with the longest idle window the policy allows (each
|
||||
use slides it forward). Returns (row, raw); the raw value exists only in the return."""
|
||||
user = ensure(db)
|
||||
row, raw = accounts.create_module_token(
|
||||
db, user, module_slug="galena", name=TOKEN_NAME, scope="read",
|
||||
idle_days=get_settings().app_token_max_idle_days)
|
||||
audit.record(db, action="archive_reader.token_minted", entity_type="session",
|
||||
entity_id=row.id, actor_id=None, detail=row.token_prefix)
|
||||
return row, raw
|
||||
|
||||
|
||||
__all__ = ["MODULES", "ensure", "mint", "reader_id"]
|
||||
@@ -91,7 +91,7 @@ _log = logging.getLogger("atrium.marketplace")
|
||||
|
||||
# The console draws these; keep them in step with the `.mi.h-<hue>` classes in frontend/app.css
|
||||
# and `HUES`/`GLYPH` in frontend/app.js (tests/test_marketplace_unit.py fails when they drift).
|
||||
HUES = ("grape", "violet", "indigo", "blue", "cyan", "teal", "green", "lime",
|
||||
HUES = ("grape", "violet", "indigo", "blue", "cyan", "teal", "green", "lime", "yellow",
|
||||
"orange", "red", "pink", "gray")
|
||||
GLYPHS = ("galena", "sygna", "percent", "compass", "scale", "folder", "file", "users", "shield",
|
||||
"chart", "clock", "lock", "star", "bell", "plug", "grid", "key")
|
||||
@@ -99,7 +99,7 @@ GLYPHS = ("galena", "sygna", "percent", "compass", "scale", "folder", "file", "u
|
||||
SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9-]{0,39}$")
|
||||
TEXT_LIMITS = {"name": 80, "tagline": 140, "description": 4000, "category": 40}
|
||||
EDITABLE = ("name", "tagline", "description", "category", "hue", "glyph", "url", "health_url",
|
||||
"status", "availability", "sort_order")
|
||||
"status", "availability", "sort_order", "in_menu")
|
||||
NOTE_LIMIT = 1000
|
||||
# Closed vocabularies a field must come from.
|
||||
_CHOICES = {"hue": HUES, "glyph": GLYPHS, "status": tuple(ModuleStatus),
|
||||
@@ -151,6 +151,10 @@ def _clean_field(field: str, value):
|
||||
if not isinstance(value, int) or isinstance(value, bool) or not 0 <= value <= 10000:
|
||||
raise ValidationError("sort_order must be a whole number from 0 to 10000.")
|
||||
return value
|
||||
if field == "in_menu":
|
||||
if not isinstance(value, bool):
|
||||
raise ValidationError("in_menu must be true or false.")
|
||||
return value
|
||||
raise ValidationError(f"{field} cannot be changed.")
|
||||
|
||||
|
||||
@@ -268,7 +272,10 @@ def _active_ids(db: DbSession) -> set[uuid.UUID]:
|
||||
every module they moderated. Their rows are frozen until they come back, and the thing that
|
||||
keeps them out meanwhile is that they cannot sign in at all.
|
||||
"""
|
||||
return set(db.scalars(select(AppUser.id).where(AppUser.is_active.is_(True))).all())
|
||||
# The Archive's technical account (services/archive_reader.py) holds exactly the grants its
|
||||
# seed writes: no assignment, no `everyone` module admits it and no sweep revokes them.
|
||||
return set(db.scalars(select(AppUser.id).where(
|
||||
AppUser.is_active.is_(True), AppUser.id != app_settings.archive_reader_id)).all())
|
||||
|
||||
|
||||
def _catalogue(db: DbSession) -> list[Module]:
|
||||
@@ -503,17 +510,38 @@ def _pending_module_ids(db: DbSession, user: AppUser) -> set[uuid.UUID]:
|
||||
)).all())
|
||||
|
||||
|
||||
def served_here(slug: str) -> bool:
|
||||
"""Does this deployment's front door serve `slug` (`FRONTDOOR_UPSTREAMS`)? Empty standalone."""
|
||||
from ..frontdoor import parse_upstreams # the front door's own parser: one reading of the map
|
||||
try:
|
||||
return slug in parse_upstreams(get_settings().frontdoor_upstreams)
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def module_url(m: Module) -> str | None:
|
||||
"""Where the module opens. An administrator's address wins; without one, a module the front door
|
||||
serves is at its own path on this very site (`../<slug>/`, relative to Atrium's console), so a
|
||||
module added by `init.sh --add` is launchable on its first deploy instead of waiting for someone
|
||||
to type the address the platform already knows. Standalone (no front door) it stays unset."""
|
||||
if m.url is not None:
|
||||
return m.url
|
||||
return f"../{m.slug}/" if served_here(m.slug) else None
|
||||
|
||||
|
||||
def _card(m: Module, user: AppUser, *, has_access: bool, pending: bool,
|
||||
allow_requests: bool) -> dict:
|
||||
launchable = has_access and m.url is not None and m.status != ModuleStatus.coming_soon
|
||||
url = module_url(m)
|
||||
launchable = has_access and url is not None and m.status != ModuleStatus.coming_soon
|
||||
out = {
|
||||
"slug": m.slug, "name": m.name, "tagline": m.tagline, "category": m.category,
|
||||
"hue": m.hue, "glyph": m.glyph, "status": m.status,
|
||||
"configured": m.url is not None,
|
||||
"in_menu": m.in_menu,
|
||||
"configured": url is not None,
|
||||
"has_access": has_access, "launchable": launchable,
|
||||
# Withheld unless offered — which keeps an unoffered module out of the launcher, and does
|
||||
# not keep anyone out of the module: see the docstring.
|
||||
"url": m.url if (launchable or user.is_admin) else None,
|
||||
"url": url if (launchable or user.is_admin) else None,
|
||||
"request_pending": pending,
|
||||
"can_request": (allow_requests and not has_access and not pending
|
||||
and m.availability == Availability.selected
|
||||
@@ -535,7 +563,10 @@ def launcher(db: DbSession, user: AppUser) -> list[dict]:
|
||||
|
||||
|
||||
def browse(db: DbSession, user: AppUser, *, q: str = "", category: str = "") -> dict:
|
||||
where = [] if user.is_admin else [Module.availability != Availability.off]
|
||||
# A service module (`in_menu` false) is not something to pick from a catalogue: everyone who
|
||||
# should have it already does, and its screens open by link from the modules that use it.
|
||||
where = [] if user.is_admin else [Module.availability != Availability.off,
|
||||
Module.in_menu.is_(True)]
|
||||
modules = _ordered(db, *where)
|
||||
categories = sorted({m.category for m in modules if m.category}, key=str.casefold)
|
||||
needle = q.strip().casefold()
|
||||
@@ -623,7 +654,7 @@ def _admin_out(m: Module) -> dict:
|
||||
"id": str(m.id), "slug": m.slug, "name": m.name, "tagline": m.tagline,
|
||||
"description": m.description, "category": m.category, "hue": m.hue, "glyph": m.glyph,
|
||||
"url": m.url, "health_url": m.health_url, "status": m.status,
|
||||
"availability": m.availability, "sort_order": m.sort_order,
|
||||
"availability": m.availability, "sort_order": m.sort_order, "in_menu": m.in_menu,
|
||||
"created_at": m.created_at.isoformat() if m.created_at else None,
|
||||
"updated_at": m.updated_at.isoformat() if m.updated_at else None,
|
||||
}
|
||||
@@ -939,10 +970,10 @@ def overview(db: DbSession) -> dict:
|
||||
|
||||
return {
|
||||
"modules": len(modules),
|
||||
"launchable": sum(1 for m in modules if m.url and m.status != ModuleStatus.coming_soon
|
||||
"launchable": sum(1 for m in modules if module_url(m) and m.status != ModuleStatus.coming_soon
|
||||
and reaches_someone(m)),
|
||||
# Switched off on purpose is not "unconfigured".
|
||||
"unconfigured": sum(1 for m in modules if not m.url and m.availability != Availability.off
|
||||
"unconfigured": sum(1 for m in modules if not module_url(m) and m.availability != Availability.off
|
||||
and m.status != ModuleStatus.coming_soon),
|
||||
"off": sum(1 for m in modules if m.availability == Availability.off),
|
||||
"users": db.scalar(select(func.count()).select_from(AppUser)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""The platform's model providers, administered from the hub.
|
||||
|
||||
Since dredd-core 0.15.0 (Atrium revision `0009`) the providers, their keys and the usage policy live
|
||||
in the shared identity schema, and **the hub is the only writer** — every module, Compass included,
|
||||
in the shared identity schema, and **the hub is the only writer** — every module, Arbiter included,
|
||||
reads them and answers 409 on a write. This file is that writer: a thin binding of core's
|
||||
`dredd_core.model_providers` to Atrium's administrator and Atrium's key cipher. Every rule (what an
|
||||
address may be, what a model entry looks like, which fields may be emptied, the audit rows and what a
|
||||
@@ -10,8 +10,8 @@ diff may say about a key) is core's; nothing here re-states one.
|
||||
Three things this file adds, and only these:
|
||||
|
||||
* **The key cipher.** Core never holds an encryption key: the writer passes `encrypt`. Here it is
|
||||
`app/provider_keys.py` under `MODEL_PROVIDER_SECRET`, byte-compatible with Compass's, which is
|
||||
what lets Compass decrypt a key written here. With the secret empty, **storing a key is refused
|
||||
`app/provider_keys.py` under `MODEL_PROVIDER_SECRET`, byte-compatible with Arbiter's, which is
|
||||
what lets Arbiter decrypt a key written here. With the secret empty, **storing a key is refused
|
||||
(409)** — a key written under anything else is one no module could ever read. Writes that carry
|
||||
no key (a local provider, the policy, disabling) still work without it.
|
||||
* **The administrator's view.** An administrator sees every row, disabled ones and the `nobody`
|
||||
@@ -20,24 +20,29 @@ Three things this file adds, and only these:
|
||||
* **The shape out.** A key never leaves: not to the administrator, not in a list, not in a diff.
|
||||
The card says `has_key` and `key_prefix` (core's six-character, non-secret prefix) and nothing else.
|
||||
|
||||
**Nothing here calls a provider.** These endpoints store configuration; there is deliberately no
|
||||
"test connection", because a hub that fetches an administrator-typed URL is an SSRF primitive with
|
||||
an administrator's reach.
|
||||
**One thing here calls a provider: `discover`**, which lists the models under a pasted key or address.
|
||||
It is an administrator-typed outbound request (SSRF by nature), so it is held like the module probe:
|
||||
administrator only, the address through core's `check_base_url`, the limits in
|
||||
`integrations/model_server.list_models`, and an audit row naming the host — never the key.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from typing import Any
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from dredd_core import model_providers as core
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from .. import provider_keys
|
||||
from ..config import get_settings
|
||||
from ..errors import ConflictError
|
||||
from ..errors import ConflictError, NotFoundError, ValidationError
|
||||
from ..integrations import model_server
|
||||
from ..models import AppUser, ModelProvider
|
||||
from . import audit
|
||||
|
||||
KEY_SECRET_MISSING = "model_provider_secret_missing"
|
||||
KEY_UNREADABLE = "model_provider_key_unreadable"
|
||||
|
||||
|
||||
def _secret() -> str:
|
||||
@@ -76,6 +81,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,
|
||||
@@ -112,9 +118,16 @@ 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),
|
||||
"key_modes": list(core.KEY_MODES),
|
||||
"keys_writable": keys_writable()}
|
||||
|
||||
|
||||
@@ -122,3 +135,168 @@ def set_policy(db: DbSession, actor: AppUser, *, level: str | None, eu_only: boo
|
||||
ip: str | None) -> dict:
|
||||
core.set_policy(db, actor=actor, level=level, only_eu=eu_only, ip=ip)
|
||||
return policy_out(db)
|
||||
|
||||
|
||||
# ── discovering a provider: paste a key or an address, get its models ────────
|
||||
# Longest prefix first: `sk-` would swallow the other two. The console does not repeat this table.
|
||||
KEY_PREFIXES: tuple[tuple[str, str, str, str], ...] = (
|
||||
# prefix, vendor, name, base_url
|
||||
("sk-ant-", "anthropic", "Anthropic", "https://api.anthropic.com/v1"),
|
||||
("sk-or-", "openrouter", "OpenRouter", "https://openrouter.ai/api/v1"),
|
||||
("sk-", "openai", "OpenAI", "https://api.openai.com/v1"),
|
||||
)
|
||||
|
||||
|
||||
def recognise(text: str, key: str | None) -> tuple[str | None, str, str, str, str | None]:
|
||||
"""`(vendor, name, kind, base_url, key)` for what the administrator pasted. Anything with `://`
|
||||
is an address and goes through core's `check_base_url` (http(s) only, no credentials, a sane
|
||||
host); a local host is `kind=local` by core's own `LOCAL_HOSTS`."""
|
||||
text = (text or "").strip()
|
||||
if "://" in text:
|
||||
host = (urlsplit(text).hostname or "").lower() if text.lower().startswith(("http://", "https://")) else ""
|
||||
kind = "local" if host in core.LOCAL_HOSTS else "api"
|
||||
base_url = core.check_base_url(text, kind)
|
||||
# A pasted cloud address is asked the way its vendor answers (Anthropic is not Bearer).
|
||||
return vendor_of(base_url), host, kind, base_url, (key or "").strip() or None
|
||||
for prefix, vendor, name, base_url in KEY_PREFIXES:
|
||||
if text.startswith(prefix):
|
||||
return vendor, name, "api", base_url, text
|
||||
raise ValidationError("Nie rozpoznaję tego klucza — wklej adres serwera.",
|
||||
{"code": "provider_unknown_key",
|
||||
"en": "I don't recognise this key — paste the server's address."})
|
||||
|
||||
|
||||
async def discover(db: DbSession, actor: AppUser, text: str, key: str | None, *,
|
||||
ip: str | None) -> dict:
|
||||
"""The provider a pasted key or address names, with its chat models. Stores no provider; the
|
||||
audit row (host only) is the caller's to commit. Call it with no transaction open — the
|
||||
outbound request can take up to `model_server.LIST_DEADLINE`."""
|
||||
vendor, name, kind, base_url, key = recognise(text, key)
|
||||
# ponytail: a refused discovery is not audited — the 422 rolls the row back; record it in its
|
||||
# own transaction if failed attempts need to be answerable.
|
||||
models = await model_server.list_models(base_url, key, vendor)
|
||||
audit.record(db, action="model_provider.discover", entity_type="model_provider",
|
||||
actor_id=actor.id, detail=urlsplit(base_url).hostname, ip=ip)
|
||||
return {"vendor": vendor, "name": name, "kind": kind, "base_url": base_url, "models": models}
|
||||
|
||||
|
||||
def vendor_of(base_url: str) -> str | None:
|
||||
"""The vendor whose address this row has (`list_models` asks Anthropic differently)."""
|
||||
host = urlsplit(base_url).hostname
|
||||
return next((v for _p, v, _n, url in KEY_PREFIXES if urlsplit(url).hostname == host), None)
|
||||
|
||||
|
||||
async def refresh(db: DbSession, actor: AppUser, provider_id: uuid.UUID, *, ip: str | None) -> dict:
|
||||
"""Re-read a stored provider's models from the provider itself and store them through `update`
|
||||
(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."})
|
||||
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)
|
||||
|
||||
|
||||
# ── using a provider: Home's "ask the model" ─────────────────────────────────
|
||||
# Who may use what is core's `_use_filter` (policy, `allowed_for`, `eu_only`); the hub passes the
|
||||
# platform administrator as `is_admin`. Only `openai`-dialect models: Home speaks chat completions.
|
||||
|
||||
CHAT_DIALECT = "openai"
|
||||
KEY_UNREADABLE = "model_provider_key_unreadable"
|
||||
USER_KEY_MISSING = "model_provider_user_key_missing"
|
||||
USER_KEY_UNREADABLE = "model_provider_user_key_unreadable"
|
||||
|
||||
|
||||
def usable_models(db: DbSession, user: AppUser) -> list[dict]:
|
||||
"""The models this person may ask, in provider order. Never an address or a key. `key_mode`
|
||||
tells Home that a `user` provider needs the person's own key (Settings → My model keys)."""
|
||||
return [
|
||||
{"id": m["id"], "provider": p.name, "kind": p.kind, "stays_in_the_eu": core.stays_in_the_eu(p),
|
||||
"key_mode": p.key_mode}
|
||||
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
|
||||
]
|
||||
|
||||
|
||||
def call_target(db: DbSession, user: AppUser, model_id: str) -> dict:
|
||||
"""Where to send this person's question about `model_id`: the provider row's address, and the key
|
||||
core's `key_for` hands out for this person (dredd-core 0.18.0: the firm's, their own, or none —
|
||||
one source per provider, never a fallback). The request names a model id and nothing else.
|
||||
404 when nobody here offers it to this person (which providers exist is privileged).
|
||||
`key_source` is what the audit row records: whose key paid for the call."""
|
||||
is_admin = bool(user.is_admin)
|
||||
found = core.offering(db, model_id, is_admin=is_admin)
|
||||
if found is None or found[1].get("dialect", CHAT_DIALECT) != CHAT_DIALECT:
|
||||
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, source = core.key_for(db, provider, user_id=user.id, is_admin=is_admin, decrypt=decrypt)
|
||||
if key is None and source == "user":
|
||||
if core.user_key_prefix(db, provider, user.id) is None:
|
||||
raise ConflictError(
|
||||
f"Dostawca {provider.name} używa twojego własnego klucza API, a nie zapisałeś go jeszcze. "
|
||||
"Dodaj swój klucz w ustawieniach: Moje klucze modeli.",
|
||||
{"code": USER_KEY_MISSING,
|
||||
"en": f"{provider.name} uses your own API key and you have not added one yet. "
|
||||
"Add your key under Settings: My model keys."})
|
||||
# Stored, but `decrypt` cannot read it (a changed MODEL_PROVIDER_SECRET): never call keyless.
|
||||
raise ConflictError(
|
||||
f"Twojego klucza API dostawcy {provider.name} nie da się odczytać. Zapisz go ponownie.",
|
||||
{"code": USER_KEY_UNREADABLE,
|
||||
"en": f"Your API key for {provider.name} cannot be read. Store it again."})
|
||||
if key is None and source == "firm" and provider.key_prefix is not None:
|
||||
# A changed MODEL_PROVIDER_SECRET or a tampered row: say so, never call keyless.
|
||||
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": source if key is not None else "none"}
|
||||
|
||||
|
||||
# ── a person's own keys (key_mode = "user") ─────────────────────────────────
|
||||
# Written only here, by the person themselves, through core's `set_user_key` / `clear_user_key`.
|
||||
# Like the firm's key, it never leaves: the screen shows `key_prefix` (core's `user_key_prefix`).
|
||||
|
||||
|
||||
def _my_card(db: DbSession, user: AppUser, provider: ModelProvider) -> dict:
|
||||
return {"id": str(provider.id), "name": provider.name, "kind": provider.kind,
|
||||
"stays_in_the_eu": core.stays_in_the_eu(provider),
|
||||
"models": [m["id"] for m in provider.models or []],
|
||||
"key_prefix": core.user_key_prefix(db, provider, user.id)}
|
||||
|
||||
|
||||
def my_keys(db: DbSession, user: AppUser) -> dict:
|
||||
"""The providers that take this person's own key and that they may use now, each with the prefix
|
||||
of the key they stored (or None)."""
|
||||
cards = [_my_card(db, user, p) for p in core.usable_providers(db, is_admin=bool(user.is_admin))
|
||||
if p.key_mode == "user"]
|
||||
return {"providers": cards, "keys_writable": keys_writable()}
|
||||
|
||||
|
||||
def set_my_key(db: DbSession, user: AppUser, provider_id: uuid.UUID, api_key: str, *,
|
||||
ip: str | None) -> dict:
|
||||
"""Store or replace this person's own key. 404 (core) unless the provider takes personal keys and
|
||||
this person may use it now — checked before the secret, so a provider nobody showed them stays
|
||||
unconfirmed even on a box without MODEL_PROVIDER_SECRET."""
|
||||
is_admin = bool(user.is_admin)
|
||||
provider = core.for_reading(db, provider_id, is_admin=is_admin)
|
||||
if provider.key_mode != "user":
|
||||
polish, english = core.MESSAGES["provider_not_found"]
|
||||
raise NotFoundError(polish, {"code": "provider_not_found", "en": english})
|
||||
encrypt = _encrypt_or_refuse(api_key)
|
||||
core.set_user_key(db, actor=user, provider=provider, api_key=api_key, encrypt=encrypt,
|
||||
is_admin=is_admin, ip=ip)
|
||||
return _my_card(db, user, provider)
|
||||
|
||||
|
||||
def clear_my_key(db: DbSession, user: AppUser, provider_id: uuid.UUID, *, ip: str | None) -> dict:
|
||||
"""Remove this person's own key. Never refused by the policy (core): a person can always take
|
||||
their key back, also from a provider they may no longer use. Unknown id: 404."""
|
||||
provider = core.get_or_404(db, provider_id)
|
||||
removed = core.clear_user_key(db, actor=user, provider=provider, ip=ip)
|
||||
return {"id": str(provider.id), "removed": removed}
|
||||
|
||||
@@ -50,6 +50,11 @@ SPECS: dict[str, Spec] = {
|
||||
# The availability a newly added module starts with.
|
||||
"default_availability": Spec(CHOICE, Availability.everyone.value,
|
||||
choices=tuple(a.value for a in Availability)),
|
||||
# Whether a firm skill or agent (and each of its later versions) waits for an administrator's
|
||||
# approval before the firm sees it, or is published at once.
|
||||
"skills_firm_publish": Spec(CHOICE, "approval", choices=("approval", "direct")),
|
||||
# Who may export a firm skill or agent as a pack. Your own you may always export.
|
||||
"skills_firm_export": Spec(CHOICE, "administrator", choices=("administrator", "everyone")),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,554 @@
|
||||
"""A skill pack (ZIP) — pure functions, no database.
|
||||
|
||||
`read_pack` is the ONE gate an uploaded archive passes before anything of it is kept. It refuses
|
||||
the whole pack, never a part of it: a pack that silently loses a file is a pack whose author and
|
||||
importer disagree about what it says. Every refusal is a `PackRejected` carrying a machine-readable
|
||||
`code` (and the offending paths), the same shape as `module_admission_refused`, so the console can
|
||||
word it in the reader's language.
|
||||
|
||||
The archive rules are checked on the central directory BEFORE a single byte is decompressed, and
|
||||
on the raw names (`ZipInfo.orig_filename`): on Windows `zipfile` rewrites `\\` to `/` in
|
||||
`filename`, which would let a backslash path through on a developer machine and not in CI.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import stat
|
||||
import struct
|
||||
import unicodedata
|
||||
import zipfile
|
||||
import zlib
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass
|
||||
|
||||
import yaml
|
||||
|
||||
from app.errors import ValidationError
|
||||
|
||||
MAX_PACK_BYTES = 10 * 1024 * 1024
|
||||
MAX_FILES = 200
|
||||
MAX_UNPACKED_BYTES = 50 * 1024 * 1024
|
||||
MAX_RATIO = 100
|
||||
|
||||
#: code -> (PL, EN). The console words a refusal by `code`; keep `frontend/app.js` in step.
|
||||
MESSAGES = {
|
||||
"pack_too_large": ("Paczka jest większa niż 10 MB.", "The pack is larger than 10 MB."),
|
||||
"pack_not_zip": ("Plik nie jest poprawnym archiwum ZIP.", "The file is not a valid ZIP archive."),
|
||||
"pack_zip64": ("Archiwa ZIP64 nie są przyjmowane.", "ZIP64 archives are not accepted."),
|
||||
"pack_too_many_files": ("Paczka ma więcej niż 200 plików.", "The pack has more than 200 files."),
|
||||
"pack_unpacked_too_large": ("Po rozpakowaniu paczka przekracza 50 MB.",
|
||||
"The pack exceeds 50 MB once unpacked."),
|
||||
"pack_compression_ratio": ("Plik jest skompresowany ponad 100:1.",
|
||||
"A file is compressed more than 100:1."),
|
||||
"pack_bad_path": ("Niedozwolona ścieżka pliku (.., ścieżka absolutna albo \\).",
|
||||
"Forbidden file path (.., absolute path or \\)."),
|
||||
"pack_link": ("Paczka zawiera dowiązanie.", "The pack contains a link."),
|
||||
"pack_duplicate_name": ("Paczka zawiera dwa pliki o tej samej nazwie.",
|
||||
"The pack contains two files with the same name."),
|
||||
"pack_case_collision": ("Paczka zawiera nazwy różniące się tylko wielkością liter.",
|
||||
"The pack contains names that differ only in letter case."),
|
||||
"pack_file_type": ("Niedozwolony typ pliku (dozwolone: .md .txt .docx .pdf .xlsx .csv .json "
|
||||
".yaml .yml).",
|
||||
"Forbidden file type (allowed: .md .txt .docx .pdf .xlsx .csv .json "
|
||||
".yaml .yml)."),
|
||||
"pack_signature_mismatch": ("Treść pliku nie zgadza się z jego rozszerzeniem.",
|
||||
"A file's content does not match its extension."),
|
||||
"pack_macros": ("Dokument zawiera makra (vbaProject.bin).",
|
||||
"A document contains macros (vbaProject.bin)."),
|
||||
"pack_nested_zip": ("Paczka zawiera archiwum ZIP, które nie jest dokumentem Word ani Excel.",
|
||||
"The pack contains a ZIP archive that is not a Word or Excel document."),
|
||||
"pack_plugin_code": ("Wtyczka zawiera skrypty, hooki albo serwery MCP.",
|
||||
"The plugin contains scripts, hooks or MCP servers."),
|
||||
"pack_manifest_invalid": ("Plik atrium-pack.json jest uszkodzony.",
|
||||
"The atrium-pack.json file is malformed."),
|
||||
"pack_manifest_mismatch": ("Pliki paczki nie zgadzają się z sumami w atrium-pack.json.",
|
||||
"The pack's files do not match the sums in atrium-pack.json."),
|
||||
"pack_no_skill": ("Paczka nie zawiera pliku SKILL.md.", "The pack contains no SKILL.md."),
|
||||
"pack_not_agent": ("Paczka nie zawiera pliku agent.md — zaimportuj ją jako skill.",
|
||||
"The pack contains no agent.md — import it as a skill."),
|
||||
"pack_agent_kind": ("Ten rodzaj agenta nie jest obsługiwany (tylko assistant).",
|
||||
"This kind of agent is not supported (assistant only)."),
|
||||
"pack_is_agent": ("To paczka agenta — zaimportuj ją jako agenta.",
|
||||
"This is an agent pack — import it as an agent."),
|
||||
"skill_not_utf8": ("SKILL.md albo agent.md nie jest zapisany w UTF-8.",
|
||||
"SKILL.md or agent.md is not UTF-8."),
|
||||
"skill_frontmatter_too_large": ("Nagłówek SKILL.md albo agent.md jest większy niż 8 KB.",
|
||||
"The SKILL.md or agent.md frontmatter is larger than 8 KB."),
|
||||
"skill_frontmatter_alias": ("Nagłówek SKILL.md albo agent.md używa aliasów albo kotwic YAML.",
|
||||
"The SKILL.md or agent.md frontmatter uses YAML aliases or anchors."),
|
||||
"skill_frontmatter_invalid": ("Nagłówek SKILL.md albo agent.md nie jest poprawnym YAML.",
|
||||
"The SKILL.md or agent.md frontmatter is not valid YAML."),
|
||||
"skill_frontmatter_not_mapping": ("Nagłówek SKILL.md albo agent.md nie jest mapą klucz: wartość.",
|
||||
"The SKILL.md or agent.md frontmatter is not a key: value mapping."),
|
||||
"skill_missing_field": ("SKILL.md albo agent.md nie ma pola name albo description.",
|
||||
"SKILL.md or agent.md lacks a name or a description."),
|
||||
"skill_bad_name": ("Pole name musi być w formacie kebab-case, najwyżej 64 znaki.",
|
||||
"The name must be kebab-case, at most 64 characters."),
|
||||
"skill_description_too_long": ("Opis (description) jest dłuższy niż 1024 znaki.",
|
||||
"The description is longer than 1024 characters."),
|
||||
"skill_body_too_long": ("Treść SKILL.md jest dłuższa niż 30 000 znaków.",
|
||||
"The SKILL.md body is longer than 30,000 characters."),
|
||||
}
|
||||
|
||||
TEXT_TYPES = {".md", ".txt", ".csv", ".json", ".yaml", ".yml"}
|
||||
OFFICE_TYPES = {".docx", ".xlsx"}
|
||||
ALLOWED_TYPES = TEXT_TYPES | OFFICE_TYPES | {".pdf"}
|
||||
MAX_MANIFEST_BYTES = 1024 * 1024
|
||||
#: Content types that make an OOXML document carry code (VBA, macro sheets, ActiveX), lower-cased.
|
||||
_MACRO_TYPES = ("vbaproject", "macroenabled", "macrosheet", "activex")
|
||||
_ZIP_MAGIC = (b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08")
|
||||
|
||||
|
||||
class PackRejected(ValidationError):
|
||||
"""The whole pack is refused. `code` is a key of `MESSAGES`; `files` names what caused it."""
|
||||
|
||||
def __init__(self, code: str, files=()):
|
||||
self.code = code
|
||||
self.files = sorted(set(files))
|
||||
self.message_pl, self.message_en = MESSAGES[code]
|
||||
# Polish `detail` + English `en`, the shape of dredd-core's refusals: the console's
|
||||
# `coreRefusal` words it in either language without a second copy of MESSAGES.
|
||||
super().__init__(self.message_pl, extra={"code": code, "files": self.files,
|
||||
"en": self.message_en})
|
||||
|
||||
|
||||
MAX_FRONTMATTER_BYTES = 8 * 1024
|
||||
MAX_NAME = 64
|
||||
MAX_DESCRIPTION = 1024
|
||||
MAX_BODY = 30_000 # the chat tool's result limit
|
||||
_KEBAB = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*")
|
||||
#: D3: kept as information, never granted. The platform decides what a skill may do.
|
||||
INFO_ONLY_KEYS = ("allowed-tools", "model", "hooks", "mcpServers", "permissionMode")
|
||||
#: Plugin manifest keys that declare code inline (D1).
|
||||
_PLUGIN_CODE_KEYS = ("hooks", "mcpServers")
|
||||
_PLUGIN_CODE_DIRS = ("hooks/", "scripts/", "bin/")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SkillDoc:
|
||||
path: str # of its SKILL.md inside the pack
|
||||
name: str
|
||||
description: str
|
||||
body: str
|
||||
frontmatter: dict # every key, the info-only ones included
|
||||
info_only: dict # D3: what the file asked for and was not given
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class AgentDoc:
|
||||
name: str
|
||||
description: str
|
||||
body: str # the instructions
|
||||
frontmatter: dict # `kind`, `tools`, `model` (a hint) — the service decides what to keep
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Pack:
|
||||
files: dict[str, bytes] # path -> content, directories and the manifest left out
|
||||
skills: tuple[SkillDoc, ...] = () # one per SKILL.md, in path order
|
||||
agent: AgentDoc | None = None # from a root `agent.md`
|
||||
kind: str | None = None # the manifest's `type`; None for a pack without one
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SkillContent:
|
||||
"""One skill as it is hashed and packed: its folder name, frontmatter, body and the files beside
|
||||
its SKILL.md (paths relative to the folder). The service builds it from a stored version."""
|
||||
folder: str
|
||||
frontmatter: dict
|
||||
body: str
|
||||
files: dict[str, bytes]
|
||||
|
||||
|
||||
MANIFEST = "atrium-pack.json"
|
||||
FORMAT_VERSION = 1
|
||||
AGENT_DOC = "agent.md"
|
||||
|
||||
|
||||
_ZIP64_EXTRA = 0x0001
|
||||
_LOCAL_HEADER = struct.Struct("<4s2B4HL2L2H") # zipfile's own `structFileHeader`
|
||||
|
||||
|
||||
def _extra_ids(extra: bytes) -> set[int]:
|
||||
ids, i = set(), 0
|
||||
while i + 4 <= len(extra):
|
||||
tag, size = struct.unpack_from("<HH", extra, i)
|
||||
ids.add(tag)
|
||||
i += 4 + size
|
||||
return ids
|
||||
|
||||
|
||||
def _is_zip64(data: bytes, infos: list[zipfile.ZipInfo]) -> bool:
|
||||
# ponytail: a ZIP64 locator signature anywhere in the tail refuses, a comment quoting it included
|
||||
# — fail closed. The local headers are read too: `force_zip64` writes the extra only there.
|
||||
if b"PK\x06\x07" in data[-(65535 + 22 + 20):]:
|
||||
return True
|
||||
for info in infos:
|
||||
if _ZIP64_EXTRA in _extra_ids(info.extra):
|
||||
return True
|
||||
head = data[info.header_offset:info.header_offset + _LOCAL_HEADER.size]
|
||||
if len(head) < _LOCAL_HEADER.size:
|
||||
continue # a truncated header fails the read below
|
||||
fields = _LOCAL_HEADER.unpack(head)
|
||||
start = info.header_offset + _LOCAL_HEADER.size + fields[10]
|
||||
if _ZIP64_EXTRA in _extra_ids(data[start:start + fields[11]]):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def bad_path(name: str) -> bool:
|
||||
return (not name or "\\" in name or "\0" in name or name.startswith("/")
|
||||
or (len(name) > 1 and name[1] == ":")
|
||||
or any(part == ".." for part in name.split("/")))
|
||||
|
||||
|
||||
def _open_archive(data: bytes) -> tuple[zipfile.ZipFile, list[zipfile.ZipInfo]]:
|
||||
"""Every archive rule, on the central directory alone — nothing is decompressed here. Shared by
|
||||
the pack and by each DOCX/XLSX inside it ("the same limits")."""
|
||||
if len(data) > MAX_PACK_BYTES:
|
||||
raise PackRejected("pack_too_large")
|
||||
try:
|
||||
zf = zipfile.ZipFile(io.BytesIO(data))
|
||||
except (zipfile.BadZipFile, ValueError, EOFError):
|
||||
raise PackRejected("pack_not_zip") from None
|
||||
infos = zf.infolist()
|
||||
if _is_zip64(data, infos):
|
||||
raise PackRejected("pack_zip64")
|
||||
members = [i for i in infos if not i.is_dir()]
|
||||
if len(members) > MAX_FILES:
|
||||
raise PackRejected("pack_too_many_files")
|
||||
|
||||
names = [i.orig_filename for i in infos]
|
||||
bad = [n for n in names if bad_path(n)]
|
||||
if bad:
|
||||
raise PackRejected("pack_bad_path", bad)
|
||||
links = [i.orig_filename for i in infos if stat.S_ISLNK(i.external_attr >> 16)]
|
||||
if links:
|
||||
raise PackRejected("pack_link", links)
|
||||
seen, dupes = set(), set()
|
||||
for n in names:
|
||||
(dupes if n in seen else seen).add(n)
|
||||
if dupes:
|
||||
raise PackRejected("pack_duplicate_name", dupes)
|
||||
folded: dict[str, str] = {}
|
||||
clashes = set()
|
||||
for n in names:
|
||||
other = folded.setdefault(n.rstrip("/").casefold(), n)
|
||||
if other != n:
|
||||
clashes |= {n, other}
|
||||
if clashes:
|
||||
raise PackRejected("pack_case_collision", clashes)
|
||||
|
||||
if sum(i.file_size for i in members) > MAX_UNPACKED_BYTES:
|
||||
raise PackRejected("pack_unpacked_too_large")
|
||||
steep = [i.orig_filename for i in members if i.file_size > MAX_RATIO * max(i.compress_size, 1)]
|
||||
if steep:
|
||||
raise PackRejected("pack_compression_ratio", steep)
|
||||
return zf, members
|
||||
|
||||
|
||||
def _suffix(path: str) -> str:
|
||||
name = path.rsplit("/", 1)[-1]
|
||||
return name[name.rfind("."):].lower() if "." in name else ""
|
||||
|
||||
|
||||
def _bounded_read(zf: zipfile.ZipFile, info: zipfile.ZipInfo) -> bytes:
|
||||
"""A member's bytes, never inflating more than its declared size + 1. `zf.read(info)` is NOT
|
||||
bounded: `ZipExtFile.read()` with no size decompresses the whole stream (up to ~2 GB) and only
|
||||
then trims to the declared size, so a 300 KB member declaring 5 MB took 600 MB of memory. A
|
||||
sized read passes the size down to `decompress(max_length=...)`. A stream longer or shorter
|
||||
than declared is a lie about the size, refused like any other broken archive."""
|
||||
with zf.open(info) as member:
|
||||
data = member.read(info.file_size + 1)
|
||||
if len(data) != info.file_size:
|
||||
raise PackRejected("pack_not_zip")
|
||||
return data
|
||||
|
||||
|
||||
def _check_office(path: str, data: bytes) -> None:
|
||||
# Only `[Content_Types].xml` is ever inflated (capped first); no other part is read. The name
|
||||
# `vbaProject.bin` is a convention, not a rule — a renamed part still has to declare its content
|
||||
# type, so the manifest is searched too (as bytes: nothing here parses XML).
|
||||
# ponytail: an embedded document (word/embeddings/*.docm) is not recursed into; Word itself asks
|
||||
# before running its macros. Recurse here if that stops being enough.
|
||||
try:
|
||||
zf, parts = _open_archive(data)
|
||||
by_name = {p.orig_filename: p for p in parts}
|
||||
manifest = by_name.get("[Content_Types].xml")
|
||||
if manifest is None or manifest.file_size > MAX_MANIFEST_BYTES:
|
||||
raise PackRejected("pack_signature_mismatch")
|
||||
types = _bounded_read(zf, manifest)
|
||||
# Fail closed on anything a substring search could be fooled by: UTF-16/32 (NULs), XML
|
||||
# character references (`vbaProject`), bytes that are not UTF-8. Office writes none.
|
||||
if b"\0" in types or b"&#" in types:
|
||||
raise PackRejected("pack_signature_mismatch")
|
||||
types = types.decode("utf-8").lower()
|
||||
except PackRejected as inner:
|
||||
raise PackRejected(inner.code, [path]) from None
|
||||
except UnicodeDecodeError:
|
||||
raise PackRejected("pack_signature_mismatch", [path]) from None
|
||||
except (zipfile.BadZipFile, RuntimeError, NotImplementedError, EOFError, zlib.error):
|
||||
raise PackRejected("pack_not_zip", [path]) from None
|
||||
if (any(n.rsplit("/", 1)[-1].lower() == "vbaproject.bin" for n in by_name)
|
||||
or any(marker in types for marker in _MACRO_TYPES)):
|
||||
raise PackRejected("pack_macros", [path])
|
||||
|
||||
|
||||
def _check_files(files: dict[str, bytes]) -> None:
|
||||
"""The file rules: an allowed extension, and content that is what the extension says. Nothing
|
||||
here reads text (variant b): a signature is checked, never parsed."""
|
||||
wrong_type = [p for p in files if _suffix(p) not in ALLOWED_TYPES]
|
||||
if wrong_type:
|
||||
raise PackRejected("pack_file_type", wrong_type)
|
||||
for path, data in files.items():
|
||||
kind = _suffix(path)
|
||||
if kind in OFFICE_TYPES:
|
||||
if not data.startswith(b"PK\x03\x04"):
|
||||
raise PackRejected("pack_signature_mismatch", [path])
|
||||
_check_office(path, data)
|
||||
elif kind == ".pdf":
|
||||
if not data.startswith(b"%PDF-"):
|
||||
raise PackRejected("pack_signature_mismatch", [path])
|
||||
elif data.startswith(_ZIP_MAGIC):
|
||||
raise PackRejected("pack_nested_zip", [path])
|
||||
elif b"\0" in data:
|
||||
# ponytail: "text" = no NUL byte, so any binary (and UTF-16) is refused while a
|
||||
# Windows-1250 CSV still passes; the encoding itself is SKILL.md's rule, not a resource's.
|
||||
raise PackRejected("pack_signature_mismatch", [path])
|
||||
|
||||
|
||||
def _check_plugin(files: dict[str, bytes]) -> None:
|
||||
"""A Claude Code plugin (a `.claude-plugin/` folder) is read for its `skills/*/SKILL.md`; code
|
||||
in it refuses the whole pack WITH the list of files (D1), never by quietly leaving it out — a
|
||||
skill may lean on its plugin's hook, and the importer must know it did not come along. Runs
|
||||
before the extension rule, so a plugin's `.sh` is named as plugin code, not as a wrong type."""
|
||||
# By path segment, every one of them: a plugin nested in another is judged against both roots.
|
||||
roots = set()
|
||||
for path in files:
|
||||
parts = path.split("/")
|
||||
roots |= {"/".join(parts[:i]) + "/" if i else "" for i, part in enumerate(parts[:-1])
|
||||
if part == ".claude-plugin"}
|
||||
code = []
|
||||
for path, data in files.items():
|
||||
for rel in (path[len(r):] for r in roots if path.startswith(r)):
|
||||
if (_suffix(rel) not in ALLOWED_TYPES or rel.startswith(_PLUGIN_CODE_DIRS)
|
||||
or rel.rsplit("/", 1)[-1] == ".mcp.json"):
|
||||
code.append(path)
|
||||
elif rel.startswith(".claude-plugin/") and rel.endswith(".json"):
|
||||
try:
|
||||
manifest = json.loads(data)
|
||||
except ValueError:
|
||||
raise PackRejected("pack_signature_mismatch", [path]) from None
|
||||
if isinstance(manifest, dict) and any(k in manifest for k in _PLUGIN_CODE_KEYS):
|
||||
code.append(path)
|
||||
if code:
|
||||
raise PackRejected("pack_plugin_code", code)
|
||||
|
||||
|
||||
class _JsonLoader(yaml.SafeLoader):
|
||||
"""SafeLoader that keeps `2025-01-01` a string. Frontmatter lands in a JSONB column, and the
|
||||
stock resolver turns dates into `datetime.date`, which JSON cannot carry (a 500 on save).
|
||||
Explicit tags that build non-JSON values (`!!binary`, `!!set`) are caught after loading."""
|
||||
|
||||
|
||||
_JsonLoader.yaml_implicit_resolvers = {
|
||||
first: [(tag, regexp) for tag, regexp in resolvers if tag != "tag:yaml.org,2002:timestamp"]
|
||||
for first, resolvers in yaml.SafeLoader.yaml_implicit_resolvers.items()
|
||||
}
|
||||
|
||||
|
||||
def _has_alias(text: str) -> bool:
|
||||
return any(isinstance(t, yaml.AliasToken | yaml.AnchorToken)
|
||||
for t in yaml.scan(text, Loader=yaml.SafeLoader))
|
||||
|
||||
|
||||
def _split_frontmatter(text: str) -> tuple[str, str]:
|
||||
"""`---` line, YAML, `---` line, body. No opening fence = no frontmatter (and so no name)."""
|
||||
if not text.startswith("---\n"):
|
||||
return "", text
|
||||
end = text.find("\n---\n", 3)
|
||||
if end == -1:
|
||||
return (text[4:], "") if text.endswith("\n---") else ("", text)
|
||||
return text[4:end + 1], text[end + 5:]
|
||||
|
||||
|
||||
_FLAT_KEY = re.compile(r"([A-Za-z][\w-]*):(?:[ \t]+(.*))?")
|
||||
_YAML_INDICATORS = set("[]{}!&*|>'\"%@`#,?-")
|
||||
|
||||
|
||||
def _flat_frontmatter(head: str) -> dict | None:
|
||||
"""Claude Code reads `description: Use when ... SKIP: x` as one string; strict YAML refuses the
|
||||
second `: `. Most real SKILL.md files are written that way, so when YAML fails we accept the
|
||||
shape only if every line is a top-level `key: text` or an indented continuation of one —
|
||||
every value a plain string. Anything nested still has to be valid YAML."""
|
||||
meta: dict = {}
|
||||
last = None
|
||||
for line in head.split("\n"):
|
||||
if not line.strip():
|
||||
continue
|
||||
m = None if line[0] in " \t" else _FLAT_KEY.fullmatch(line.rstrip())
|
||||
if m and (m.group(2) or "")[:1] in _YAML_INDICATORS:
|
||||
# `paths: ["*.gs"]`, `hint: "[review]"`: that one value is YAML, read alone. A broken
|
||||
# one (`[x`, `!!python/...`, a dangling `*alias`) refuses the whole frontmatter.
|
||||
try:
|
||||
meta[m.group(1)] = yaml.load(m.group(2), Loader=_JsonLoader) # noqa: S506 - SafeLoader subclass
|
||||
except yaml.YAMLError:
|
||||
return None
|
||||
last = None # a structured value takes no continuation lines
|
||||
continue
|
||||
if m:
|
||||
last = m.group(1)
|
||||
meta[last] = (m.group(2) or "").strip()
|
||||
elif last is not None and line[0] in " \t":
|
||||
meta[last] = f"{meta[last]} {line.strip()}".strip()
|
||||
else:
|
||||
return None
|
||||
return meta
|
||||
|
||||
|
||||
def _read_doc(path: str, data: bytes) -> tuple[dict, str, str, str]:
|
||||
"""The frontmatter rules SKILL.md and agent.md share: -> (frontmatter, name, description, body)."""
|
||||
try:
|
||||
text = data.decode("utf-8-sig")
|
||||
except UnicodeDecodeError:
|
||||
raise PackRejected("skill_not_utf8", [path]) from None
|
||||
head, body = _split_frontmatter(text.replace("\r\n", "\n").replace("\r", "\n"))
|
||||
# The size gate comes first: it is what bounds the YAML parser's work.
|
||||
if len(head.encode("utf-8")) > MAX_FRONTMATTER_BYTES:
|
||||
raise PackRejected("skill_frontmatter_too_large", [path])
|
||||
try:
|
||||
# A billion-laughs bomb fits in 8 KB, and a skill's frontmatter has no use for aliases.
|
||||
try:
|
||||
if _has_alias(head):
|
||||
raise PackRejected("skill_frontmatter_alias", [path])
|
||||
meta = yaml.load(head, Loader=_JsonLoader) if head.strip() else {} # noqa: S506 - SafeLoader subclass
|
||||
except yaml.YAMLError:
|
||||
# Not YAML at all: flat text, never interpreted, so no alias can expand in it.
|
||||
meta = _flat_frontmatter(head)
|
||||
if meta is None:
|
||||
raise
|
||||
# What reaches JSONB must be JSON: `!!binary`, `!!set`, a timestamp tag, `.nan` (JSONB refuses NaN).
|
||||
json.dumps(meta, allow_nan=False)
|
||||
except (yaml.YAMLError, RecursionError, TypeError, ValueError): # 8 KB of `[` nests deeper than the composer recurses
|
||||
raise PackRejected("skill_frontmatter_invalid", [path]) from None
|
||||
if not isinstance(meta, dict):
|
||||
raise PackRejected("skill_frontmatter_not_mapping", [path])
|
||||
name, description = meta.get("name"), meta.get("description")
|
||||
if not (isinstance(name, str) and name and isinstance(description, str) and description.strip()):
|
||||
raise PackRejected("skill_missing_field", [path])
|
||||
return meta, name, description, body
|
||||
|
||||
|
||||
def _read_skill(path: str, data: bytes) -> SkillDoc:
|
||||
meta, name, description, body = _read_doc(path, data)
|
||||
if len(name) > MAX_NAME or not _KEBAB.fullmatch(name):
|
||||
raise PackRejected("skill_bad_name", [path])
|
||||
if len(description) > MAX_DESCRIPTION:
|
||||
raise PackRejected("skill_description_too_long", [path])
|
||||
if len(body) > MAX_BODY:
|
||||
raise PackRejected("skill_body_too_long", [path])
|
||||
return SkillDoc(path=path, name=name, description=description, body=body, frontmatter=meta,
|
||||
info_only={k: meta[k] for k in INFO_ONLY_KEYS if k in meta})
|
||||
|
||||
|
||||
def read_pack(data: bytes) -> Pack:
|
||||
"""Check an uploaded archive against every archive rule and every file rule, and return its
|
||||
files, or raise `PackRejected`. Sizes are trusted from the central directory only because
|
||||
`_bounded_read` never inflates past a member's declared size + 1 and refuses a member whose
|
||||
stream disagrees with it, so the declared total bounds what is actually inflated."""
|
||||
zf, members = _open_archive(data)
|
||||
try:
|
||||
files = {i.filename: _bounded_read(zf, i) for i in members}
|
||||
except (zipfile.BadZipFile, RuntimeError, NotImplementedError, EOFError, zlib.error):
|
||||
# A CRC mismatch, an encrypted member, an unknown compression method, a truncated stream.
|
||||
raise PackRejected("pack_not_zip") from None
|
||||
_check_plugin(files)
|
||||
_check_files(files)
|
||||
kind = _check_manifest(files)
|
||||
# ponytail: a pack with no SKILL.md is not refused here — an agent pack may pin none; whether a
|
||||
# skill import needs one is the import's rule (services/skills.py).
|
||||
skills = tuple(_read_skill(p, d) for p, d in sorted(files.items())
|
||||
if p.rsplit("/", 1)[-1] == "SKILL.md")
|
||||
agent = None
|
||||
if AGENT_DOC in files:
|
||||
meta, name, description, body = _read_doc(AGENT_DOC, files[AGENT_DOC])
|
||||
agent = AgentDoc(name=name, description=description, body=body, frontmatter=meta)
|
||||
return Pack(files=files, skills=skills, agent=agent, kind=kind)
|
||||
|
||||
|
||||
def _sha(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def _check_manifest(files: dict[str, bytes]) -> str | None:
|
||||
"""Verify `atrium-pack.json` and take it out of `files`. A pack without one (a skill ZIP from
|
||||
elsewhere) is accepted: the sums guard a pack against change on the way, they say nothing of
|
||||
its author, so their absence takes nothing away."""
|
||||
raw = files.pop(MANIFEST, None)
|
||||
if raw is None:
|
||||
return None
|
||||
try:
|
||||
manifest = json.loads(raw)
|
||||
listed = {f["path"]: f["sha256"] for f in manifest["files"]}
|
||||
kind = manifest["type"]
|
||||
if manifest["format"] != FORMAT_VERSION or kind not in ("skill", "agent"):
|
||||
raise ValueError
|
||||
except (ValueError, KeyError, TypeError):
|
||||
raise PackRejected("pack_manifest_invalid", [MANIFEST]) from None
|
||||
# Both directions: a file added on the way is as much a change as one altered.
|
||||
wrong = {p for p in listed.keys() | files.keys()
|
||||
if p not in files or listed.get(p) != _sha(files[p])}
|
||||
if wrong:
|
||||
raise PackRejected("pack_manifest_mismatch", wrong)
|
||||
return kind
|
||||
|
||||
|
||||
def skill_content(pack: Pack, skill: SkillDoc) -> SkillContent:
|
||||
"""The skill as `content_sha256` and `build_pack` see it: everything under its SKILL.md's folder."""
|
||||
# ponytail: a SKILL.md nested inside another skill's folder is counted in both; packs this module
|
||||
# builds never nest, and an import keeps one skill per folder.
|
||||
prefix = skill.path[: -len("SKILL.md")]
|
||||
files = {p[len(prefix):]: d for p, d in pack.files.items()
|
||||
if p.startswith(prefix) and p != skill.path and not (prefix == "" and p == AGENT_DOC)}
|
||||
return SkillContent(folder=prefix.rstrip("/").rsplit("/", 1)[-1] or skill.name,
|
||||
frontmatter=skill.frontmatter, body=skill.body, files=files)
|
||||
|
||||
|
||||
def _document(frontmatter: dict, body: str) -> str:
|
||||
"""The canonical text: NFC, LF, the frontmatter re-dumped with its keys in alphabetical order —
|
||||
so a pack that went out and came back in hashes the same however its YAML was spelt."""
|
||||
head = yaml.safe_dump(frontmatter, sort_keys=True, allow_unicode=True, default_flow_style=False)
|
||||
text = f"---\n{head}---\n{body}".replace("\r\n", "\n").replace("\r", "\n")
|
||||
return unicodedata.normalize("NFC", text)
|
||||
|
||||
|
||||
def content_sha256(skill: SkillContent) -> str:
|
||||
"""SHA-256 of the canonical SKILL.md and the sorted `path\\0sha256` lines of its files."""
|
||||
listing = "\n".join(f"{p}\0{_sha(d)}" for p, d in sorted(skill.files.items()))
|
||||
return _sha(_document(skill.frontmatter, skill.body).encode("utf-8") + b"\0\0"
|
||||
+ listing.encode("utf-8"))
|
||||
|
||||
|
||||
def build_pack(skills: Sequence[SkillContent], agent: AgentDoc | None = None) -> bytes:
|
||||
"""A ZIP of one skill (`agent=None`) or of an agent with the skills it pins, each in its own
|
||||
folder, plus `atrium-pack.json` listing every file's sha256. What it writes, `read_pack` reads."""
|
||||
folders = [s.folder for s in skills]
|
||||
if len(set(folders)) != len(folders) or (agent is None and len(skills) != 1):
|
||||
raise ValueError("a pack holds one skill, or an agent with skills in distinct folders")
|
||||
files: dict[str, bytes] = {}
|
||||
for s in skills:
|
||||
files[f"{s.folder}/SKILL.md"] = _document(s.frontmatter, s.body).encode("utf-8")
|
||||
files.update({f"{s.folder}/{p}": d for p, d in s.files.items()})
|
||||
if agent is not None:
|
||||
files[AGENT_DOC] = _document(agent.frontmatter, agent.body).encode("utf-8")
|
||||
manifest = {"format": FORMAT_VERSION, "type": "skill" if agent is None else "agent",
|
||||
"files": [{"path": p, "sha256": _sha(d)} for p, d in sorted(files.items())]}
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for path, data in sorted(files.items()):
|
||||
zf.writestr(path, data)
|
||||
zf.writestr(MANIFEST, json.dumps(manifest, ensure_ascii=False, indent=2))
|
||||
return buf.getvalue()
|
||||
@@ -0,0 +1,989 @@
|
||||
"""Skills: a person's own instructions and reference files, versioned and frozen.
|
||||
|
||||
A deliberate exception to "`authz` is the only access authority"
|
||||
-----------------------------------------------------------------
|
||||
Skills (and agents) are not nodes of the org tree — the tree holds units only — so
|
||||
`authz.assert_can_read` has nothing to say about them. Who may see one is decided HERE, in one
|
||||
rule: **the owner, plus everybody for a `firm` one**. `visible_to` is that rule as SQL (lists) and
|
||||
`can_see` the same rule on a loaded row (single reads); every read and write path goes through one
|
||||
of them. Somebody else's personal skill is a 404, never a 403 — its existence is the owner's
|
||||
business. An administrator gets no exception here: a personal skill is a lawyer's working notes,
|
||||
and an administrator sees one only inside a publish request (the publication path, not this one).
|
||||
|
||||
Who may CHANGE one (`can_edit`): the owner, and for a firm skill also an administrator. Everybody
|
||||
else may PROPOSE on an active firm skill (`can_propose`): a new version that waits for approval.
|
||||
A proposer reads the current version and the versions they wrote themselves, nothing more
|
||||
(`readable_version_ids`); only an editor reads every version. A proposer's publish is always a
|
||||
request, and so is anybody's publish of a version a non-editor wrote (`publish_skill`).
|
||||
|
||||
Who decides a publish request (`may_approve`): an administrator, or somebody holding `approver` or
|
||||
better on the firm's workspace node of the org tree. The existing grant screen hands that out, so
|
||||
there is no second permission table. A role on a group or folder is not the firm's. An approver who
|
||||
is not an editor reads one more version than a proposer: the one sitting in a PENDING request,
|
||||
because they cannot decide on what they cannot read (`_readable_version`). Once decided, the
|
||||
request grants nothing.
|
||||
|
||||
Versions are frozen
|
||||
-------------------
|
||||
Changing content is a new `skill_version` (`n + 1`), never an edit; the runtime role holds no
|
||||
UPDATE or DELETE on the version tables (revision 0015). Every version is validated the way an
|
||||
import is — it is packed with `skill_pack.build_pack` and read back with `skill_pack.read_pack` — so
|
||||
a skill typed in the console and one uploaded as a ZIP obey the same rules and hash the same way.
|
||||
|
||||
`current_version_id` of a PERSONAL skill follows its newest version. A FIRM skill's is the approved
|
||||
one, and only publication moves it — a new version of a firm skill is readable only by its editors
|
||||
and its author until then.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import unicodedata
|
||||
import uuid
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import or_, select
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
from ..enums import (
|
||||
AgentKind,
|
||||
CatalogStatus,
|
||||
NodeKind,
|
||||
NodeRole,
|
||||
PublishKind,
|
||||
PublishRequestStatus,
|
||||
SkillOrigin,
|
||||
SkillScope,
|
||||
)
|
||||
from ..errors import AuthorizationError, ConflictError, NotFoundError, ValidationError
|
||||
from ..models import (
|
||||
Agent,
|
||||
AgentVersion,
|
||||
AgentVersionSkill,
|
||||
AppUser,
|
||||
Node,
|
||||
PublishRequest,
|
||||
Skill,
|
||||
SkillFile,
|
||||
SkillVersion,
|
||||
)
|
||||
from . import audit, authz, settings, skill_pack
|
||||
from .marketplace import _clean_note
|
||||
from .skill_pack import PackRejected, SkillContent
|
||||
|
||||
DEFAULT_LICENSE = "proprietary"
|
||||
#: The frontmatter keys that have columns of their own; everything else is kept in `metadata`.
|
||||
_OWN_KEYS = ("name", "description", "license")
|
||||
MEDIA_TYPES = {
|
||||
".md": "text/markdown", ".txt": "text/plain", ".csv": "text/csv",
|
||||
".json": "application/json", ".yaml": "application/yaml", ".yml": "application/yaml",
|
||||
".pdf": "application/pdf",
|
||||
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
}
|
||||
|
||||
|
||||
# ---- who may see and change ------------------------------------------------------------------
|
||||
|
||||
def can_see(user: AppUser, item) -> bool:
|
||||
"""The visibility rule on a loaded skill (or agent: same columns)."""
|
||||
return item.owner_id == user.id or item.scope == SkillScope.firm
|
||||
|
||||
|
||||
def can_edit(user: AppUser, item) -> bool:
|
||||
"""Owner, or an administrator for a firm one; everybody else makes a personal copy."""
|
||||
return item.owner_id == user.id or (item.scope == SkillScope.firm and bool(user.is_admin))
|
||||
|
||||
|
||||
def can_propose(user: AppUser, item) -> bool:
|
||||
"""Whoever may edit, and anybody for an active firm skill: a new version is a proposal there
|
||||
(`_add_version` never moves a firm skill's current version; only an approval does)."""
|
||||
return can_edit(user, item) or (item.scope == SkillScope.firm
|
||||
and item.status == CatalogStatus.active)
|
||||
|
||||
|
||||
def visible_to(db: DbSession, user: AppUser) -> list[Skill]:
|
||||
"""Every skill `user` may see — `can_see` as SQL. Archived ones included: an agent may still pin
|
||||
one, and the console says so."""
|
||||
return list(db.scalars(
|
||||
select(Skill).where(or_(Skill.owner_id == user.id, Skill.scope == SkillScope.firm))
|
||||
.order_by(Skill.name, Skill.id)))
|
||||
|
||||
|
||||
def _get(db: DbSession, user: AppUser, skill_id: uuid.UUID) -> Skill:
|
||||
skill = db.get(Skill, skill_id)
|
||||
if skill is None or not can_see(user, skill):
|
||||
raise NotFoundError("Skill not found.")
|
||||
return skill
|
||||
|
||||
|
||||
def _get_editable(db: DbSession, user: AppUser, skill_id: uuid.UUID) -> Skill:
|
||||
skill = _get(db, user, skill_id)
|
||||
if not can_edit(user, skill):
|
||||
# A firm skill is visible, so refusing to change it reveals nothing.
|
||||
raise AuthorizationError("Only the owner or an administrator may change a firm skill.")
|
||||
return skill
|
||||
|
||||
|
||||
def _get_proposable(db: DbSession, user: AppUser, skill_id: uuid.UUID) -> Skill:
|
||||
skill = _get(db, user, skill_id)
|
||||
if not can_propose(user, skill):
|
||||
raise AuthorizationError("Only the owner or an administrator may change this skill.")
|
||||
return skill
|
||||
|
||||
|
||||
def may_approve(db: DbSession, user: AppUser) -> bool:
|
||||
"""May `user` decide publish requests? An administrator, or `approver`+ on any workspace node.
|
||||
The workspace is the firm (the root of the org tree), and a grant there reaches everything
|
||||
below; a grant on a group or folder does not make anyone the firm's approver. The role is
|
||||
resolved by `authz.effective_role` and compared by dredd-core's rank, never by its string."""
|
||||
if user.is_admin:
|
||||
return True
|
||||
needed = NodeRole.rank(NodeRole.approver)
|
||||
return any(NodeRole.rank(authz.effective_role(db, user, node)) >= needed
|
||||
for node in db.scalars(select(Node).where(Node.kind == NodeKind.workspace)))
|
||||
|
||||
|
||||
def readable_version_ids(user: AppUser, skill: Skill, versions) -> set[uuid.UUID]:
|
||||
"""The ids among `versions` this person may read. An editor reads every version. Anybody else
|
||||
reads the current one (for a firm skill: approved) and the versions they wrote themselves, so a
|
||||
proposer sees their own proposal but not other people's, nor the owner's earlier personal
|
||||
drafts of a skill that later became the firm's."""
|
||||
if can_edit(user, skill):
|
||||
return {v.id for v in versions}
|
||||
return {v.id for v in versions
|
||||
if v.id == skill.current_version_id or v.created_by == user.id}
|
||||
|
||||
|
||||
# ---- content -----------------------------------------------------------------------------------
|
||||
|
||||
def next_n(latest: int | None) -> int:
|
||||
"""The number of the next version; the (skill_id, n) constraint settles a race."""
|
||||
return (latest or 0) + 1
|
||||
|
||||
|
||||
def frontmatter(slug: str, description: str, license: str, meta: Mapping) -> dict:
|
||||
"""The SKILL.md frontmatter a version stands for: its own columns win over `metadata`."""
|
||||
head = {k: v for k, v in meta.items() if k not in _OWN_KEYS}
|
||||
head.update(name=slug, description=description, license=license)
|
||||
return head
|
||||
|
||||
|
||||
def version_content(skill: Skill, version: SkillVersion, files) -> SkillContent:
|
||||
"""A stored version as `content_sha256` and `build_pack` see it (export reads it the same way)."""
|
||||
return SkillContent(folder=skill.slug,
|
||||
frontmatter=frontmatter(skill.slug, version.description, version.license,
|
||||
version.meta),
|
||||
body=version.body_md, files={f.path: f.content for f in files})
|
||||
|
||||
|
||||
def checked(slug: str, description: str, body: str, license: str, meta: Mapping,
|
||||
files: Mapping[str, bytes]) -> tuple[skill_pack.SkillDoc, SkillContent, str]:
|
||||
"""Pack the content and read it back: every import rule applies, `PackRejected` otherwise.
|
||||
-> (the parsed SKILL.md, the content as it will be stored, its `content_sha256`)."""
|
||||
# Checked before packing: zipfile rewrites `\` to `/` on Windows, and an empty segment (`a//b`,
|
||||
# `/a`) would be stored under another name than the one it was given.
|
||||
bad = [p for p in files if skill_pack.bad_path(p) or "" in p.split("/")]
|
||||
if bad:
|
||||
raise PackRejected("pack_bad_path", bad)
|
||||
if "SKILL.md" in files: # build_pack would let it overwrite the document written from the fields
|
||||
raise PackRejected("pack_duplicate_name", ["SKILL.md"])
|
||||
content = SkillContent(folder=slug, frontmatter=frontmatter(slug, description, license, meta),
|
||||
body=body, files=dict(files))
|
||||
pack = skill_pack.read_pack(skill_pack.build_pack([content]))
|
||||
doc = pack.skills[0]
|
||||
stored = skill_pack.skill_content(pack, doc)
|
||||
return doc, stored, skill_pack.content_sha256(stored)
|
||||
|
||||
|
||||
def _media_type(path: str) -> str:
|
||||
name = path.rsplit("/", 1)[-1]
|
||||
return MEDIA_TYPES[name[name.rfind("."):].lower()] # read_pack has already refused the rest
|
||||
|
||||
|
||||
def _add_version(db: DbSession, actor: AppUser, skill: Skill, n: int, *, description: str,
|
||||
body: str, license: str, meta: Mapping, files: Mapping[str, bytes],
|
||||
provenance: dict | None = None) -> SkillVersion:
|
||||
doc, stored, sha = checked(skill.slug, description, body, license, meta, files)
|
||||
version = SkillVersion(
|
||||
skill_id=skill.id, n=n, description=doc.description, body_md=doc.body,
|
||||
license=doc.frontmatter["license"],
|
||||
meta={k: v for k, v in doc.frontmatter.items() if k not in _OWN_KEYS},
|
||||
content_sha256=sha, provenance=provenance, created_by=actor.id)
|
||||
db.add(version)
|
||||
db.flush()
|
||||
for path, data in sorted(stored.files.items()):
|
||||
db.add(SkillFile(skill_version_id=version.id, path=path, media_type=_media_type(path),
|
||||
size=len(data), sha256=hashlib.sha256(data).hexdigest(), content=data))
|
||||
if skill.scope == SkillScope.personal:
|
||||
skill.current_version_id = version.id
|
||||
# A firm skill's current version moves only through publication (`_make_current`).
|
||||
db.flush()
|
||||
return version
|
||||
|
||||
|
||||
def _audit(db: DbSession, actor: AppUser, action: str, skill: Skill,
|
||||
version: SkillVersion | None = None, *, ip: str | None) -> None:
|
||||
detail = skill.slug if version is None else f"{skill.slug} v{version.n} {version.content_sha256}"
|
||||
audit.record(db, action=action, entity_type="skill", entity_id=skill.id, actor_id=actor.id,
|
||||
detail=detail, ip=ip)
|
||||
|
||||
|
||||
# ---- output ------------------------------------------------------------------------------------
|
||||
|
||||
def _files(db: DbSession, version_id: uuid.UUID) -> list[SkillFile]:
|
||||
return list(db.scalars(select(SkillFile).where(SkillFile.skill_version_id == version_id)
|
||||
.order_by(SkillFile.path)))
|
||||
|
||||
|
||||
def skill_out(user: AppUser, skill: Skill) -> dict[str, Any]:
|
||||
"""The identity row as the API shows it, with what this person may do to it."""
|
||||
return {"id": skill.id, "slug": skill.slug, "name": skill.name, "owner_id": skill.owner_id,
|
||||
"scope": skill.scope, "status": skill.status, "origin": skill.origin,
|
||||
"current_version_id": skill.current_version_id, "mine": skill.owner_id == user.id,
|
||||
"editable": can_edit(user, skill),
|
||||
"proposable": can_propose(user, skill)}
|
||||
|
||||
|
||||
def version_out(version: SkillVersion, files: list[SkillFile]) -> dict[str, Any]:
|
||||
"""One version in full, files listed without their bytes (export carries those)."""
|
||||
return {"id": version.id, "n": version.n, "description": version.description,
|
||||
"body": version.body_md, "license": version.license, "metadata": version.meta,
|
||||
"content_sha256": version.content_sha256, "provenance": version.provenance,
|
||||
"created_at": version.created_at, "created_by": version.created_by,
|
||||
"files": [{"path": f.path, "media_type": f.media_type, "size": f.size,
|
||||
"sha256": f.sha256} for f in files]}
|
||||
|
||||
|
||||
# ---- reads -------------------------------------------------------------------------------------
|
||||
|
||||
def list_skills(db: DbSession, user: AppUser) -> list[dict]:
|
||||
"""Own skills and firm ones; the console splits them into Mine / The firm's."""
|
||||
return [skill_out(user, s) for s in visible_to(db, user)]
|
||||
|
||||
|
||||
def get_skill(db: DbSession, user: AppUser, skill_id: uuid.UUID) -> dict:
|
||||
"""The skill, the versions this person may read (newest first) and the current one in full."""
|
||||
skill = _get(db, user, skill_id)
|
||||
versions = list(db.scalars(select(SkillVersion).where(SkillVersion.skill_id == skill.id)
|
||||
.order_by(SkillVersion.n.desc())))
|
||||
readable = readable_version_ids(user, skill, versions)
|
||||
current = next((v for v in versions if v.id == skill.current_version_id), None)
|
||||
return {**skill_out(user, skill),
|
||||
"versions": [{"n": v.n, "id": v.id, "created_at": v.created_at,
|
||||
"content_sha256": v.content_sha256}
|
||||
for v in versions if v.id in readable],
|
||||
"current": (version_out(current, _files(db, current.id))
|
||||
if current is not None and current.id in readable else None)}
|
||||
|
||||
|
||||
def _pending_for_approver(db: DbSession, user: AppUser, version: SkillVersion) -> bool:
|
||||
"""A version waiting in a publish request is readable by whoever may decide that request."""
|
||||
return bool(db.scalar(select(PublishRequest.id).where(
|
||||
PublishRequest.kind == PublishKind.skill, PublishRequest.version_id == version.id,
|
||||
PublishRequest.status == PublishRequestStatus.pending))) and may_approve(db, user)
|
||||
|
||||
|
||||
def _readable_version(db: DbSession, user: AppUser, skill_id: uuid.UUID,
|
||||
n: int) -> tuple[Skill, SkillVersion]:
|
||||
"""The skill and its version `n`, if this person may read it; an unapproved firm version is a
|
||||
404 to others. The one exception to `can_see`: an approver reads a version in a pending request
|
||||
even of somebody's personal skill, because the request is what puts it in front of them."""
|
||||
skill = db.get(Skill, skill_id)
|
||||
if skill is None:
|
||||
raise NotFoundError("Skill not found.")
|
||||
version = db.scalar(select(SkillVersion).where(SkillVersion.skill_id == skill.id,
|
||||
SkillVersion.n == n))
|
||||
if version is not None:
|
||||
if can_see(user, skill) and readable_version_ids(user, skill, [version]):
|
||||
return skill, version
|
||||
if _pending_for_approver(db, user, version):
|
||||
return skill, version
|
||||
# A personal skill nobody may see stays "Skill not found", as `_get` says.
|
||||
raise NotFoundError("Version not found." if can_see(user, skill) else "Skill not found.")
|
||||
|
||||
|
||||
def get_version(db: DbSession, user: AppUser, skill_id: uuid.UUID, n: int) -> dict:
|
||||
"""Version `n`, if this person may read it. `approved_for_firm` tells the checking service
|
||||
whether this is the version the firm approved: an editor or the author can read a proposal, and a
|
||||
check run against one must not pass as the firm's own. An archived skill has no approved version:
|
||||
archiving is the firm's kill switch, and the checking service reads this flag fresh on every
|
||||
real-contract order, so it stops there at once."""
|
||||
skill, version = _readable_version(db, user, skill_id, n)
|
||||
return {**version_out(version, _files(db, version.id)), "skill_name": skill.name,
|
||||
"approved_for_firm": (skill.scope == SkillScope.firm
|
||||
and skill.status == CatalogStatus.active
|
||||
and skill.current_version_id == version.id)}
|
||||
|
||||
|
||||
def get_file(db: DbSession, user: AppUser, skill_id: uuid.UUID, n: int,
|
||||
path: str) -> tuple[str, bytes]:
|
||||
"""(media_type, bytes) of one file of a readable version; the same read rule as `get_version`.
|
||||
A read, so no audit entry."""
|
||||
_, version = _readable_version(db, user, skill_id, n)
|
||||
stored = db.scalar(select(SkillFile).where(SkillFile.skill_version_id == version.id,
|
||||
SkillFile.path == path))
|
||||
if stored is None:
|
||||
raise NotFoundError("File not found.")
|
||||
return stored.media_type, stored.content
|
||||
|
||||
|
||||
# ---- writes ------------------------------------------------------------------------------------
|
||||
|
||||
def create_skill(db: DbSession, actor: AppUser, fields: Mapping, *, ip: str | None) -> dict:
|
||||
"""A personal skill with its version 1. `fields`: slug, name, description, body, and optionally
|
||||
license, metadata (extra frontmatter) and files (path -> bytes)."""
|
||||
slug = fields["slug"]
|
||||
if db.scalar(select(Skill.id).where(Skill.owner_id == actor.id, Skill.slug == slug)):
|
||||
raise ConflictError(f"You already have a skill called {slug}.")
|
||||
skill = Skill(slug=slug, name=fields["name"], owner_id=actor.id, scope=SkillScope.personal,
|
||||
status=CatalogStatus.active, origin=SkillOrigin.authored)
|
||||
db.add(skill)
|
||||
db.flush()
|
||||
version = _add_version(db, actor, skill, 1, description=fields["description"],
|
||||
body=fields["body"], license=fields.get("license") or DEFAULT_LICENSE,
|
||||
meta=fields.get("metadata") or {}, files=fields.get("files") or {})
|
||||
_audit(db, actor, "skill.create", skill, version, ip=ip)
|
||||
return skill_out(actor, skill)
|
||||
|
||||
|
||||
def _base_version(db: DbSession, actor: AppUser, skill: Skill) -> SkillVersion:
|
||||
"""What an unset field is carried over from. NOT the newest version overall: that may be a
|
||||
stranger's proposal, which an editor's next save would then inherit unseen. The base is the
|
||||
actor's own newest version when it is newer than the current one (or nothing is current yet),
|
||||
else the current version, else the newest one the owner wrote."""
|
||||
mine = db.scalar(select(SkillVersion).where(SkillVersion.skill_id == skill.id,
|
||||
SkillVersion.created_by == actor.id)
|
||||
.order_by(SkillVersion.n.desc()).limit(1))
|
||||
current = (db.get(SkillVersion, skill.current_version_id)
|
||||
if skill.current_version_id is not None else None)
|
||||
if mine is not None and (current is None or mine.n > current.n):
|
||||
return mine
|
||||
if current is not None:
|
||||
return current
|
||||
owners = db.scalar(select(SkillVersion).where(SkillVersion.skill_id == skill.id,
|
||||
SkillVersion.created_by == skill.owner_id)
|
||||
.order_by(SkillVersion.n.desc()).limit(1))
|
||||
if owners is None:
|
||||
# Every skill starts with its owner's version 1, so this is not expected; failing beats
|
||||
# falling back to the newest version overall, which may be a stranger's proposal.
|
||||
raise ConflictError("This skill has no version to build on.")
|
||||
return owners
|
||||
|
||||
|
||||
def _named_base(db: DbSession, actor: AppUser, skill: Skill, n: int) -> SkillVersion:
|
||||
"""Version `n` as the base, when the caller names the one it was looking at (the console's
|
||||
editor always does): an explicit choice, so Ruling 9's worry (inheriting a stranger's proposal
|
||||
unseen) does not apply. It must still be a version this person may read, with the same 404."""
|
||||
version = db.scalar(select(SkillVersion).where(SkillVersion.skill_id == skill.id,
|
||||
SkillVersion.n == n))
|
||||
if version is None or not readable_version_ids(actor, skill, [version]):
|
||||
raise NotFoundError("Version not found.")
|
||||
return version
|
||||
|
||||
|
||||
def new_version(db: DbSession, actor: AppUser, skill_id: uuid.UUID, fields: Mapping, *,
|
||||
ip: str | None) -> dict:
|
||||
"""Version `n + 1`. A field that is None is carried over from the base version: `base_n` when
|
||||
given (`_named_base`), else `_base_version` (the actor's own newer one, else the current one —
|
||||
never a stranger's proposal); `files`
|
||||
included — `{}` is how to remove them all). `file_updates` (path -> bytes) instead replaces or
|
||||
adds just those files and carries every other one over byte for byte, so a caller that holds
|
||||
one file need not hold the rest. An imported licence is the author's: it stays. On a firm skill
|
||||
this is a proposal: it waits for publication like any other new version."""
|
||||
skill = _get_proposable(db, actor, skill_id)
|
||||
if skill.status == CatalogStatus.archived:
|
||||
raise ConflictError("An archived skill takes no new versions.")
|
||||
if fields.get("files") is not None and fields.get("file_updates") is not None:
|
||||
raise ValidationError("Send files or file_updates, not both.")
|
||||
latest = db.scalar(select(SkillVersion).where(SkillVersion.skill_id == skill.id)
|
||||
.order_by(SkillVersion.n.desc()).limit(1))
|
||||
base = (_named_base(db, actor, skill, fields["base_n"]) if fields.get("base_n") is not None
|
||||
else _base_version(db, actor, skill))
|
||||
license = fields.get("license") or base.license
|
||||
if skill.origin == SkillOrigin.imported:
|
||||
license = base.license
|
||||
files = fields.get("files")
|
||||
if files is None:
|
||||
files = {f.path: f.content for f in _files(db, base.id)}
|
||||
files.update(fields.get("file_updates") or {})
|
||||
# The name sits on the identity row, outside versioning: a proposal must not rename a firm skill.
|
||||
if fields.get("name") and can_edit(actor, skill):
|
||||
skill.name = fields["name"]
|
||||
version = _add_version(
|
||||
db, actor, skill, next_n(latest.n),
|
||||
description=fields.get("description") or base.description,
|
||||
body=fields["body"] if fields.get("body") is not None else base.body_md,
|
||||
license=license,
|
||||
meta=fields["metadata"] if fields.get("metadata") is not None else base.meta,
|
||||
files=files)
|
||||
_audit(db, actor, "skill.version", skill, version, ip=ip)
|
||||
return version_out(version, _files(db, version.id))
|
||||
|
||||
|
||||
def archive_skill(db: DbSession, actor: AppUser, skill_id: uuid.UUID, *, ip: str | None) -> dict:
|
||||
"""Archived, not deleted: agents keep running on the versions they pinned (FK RESTRICT)."""
|
||||
skill = _get_editable(db, actor, skill_id)
|
||||
if skill.status != CatalogStatus.archived:
|
||||
skill.status = CatalogStatus.archived
|
||||
db.flush()
|
||||
_audit(db, actor, "skill.archive", skill, ip=ip)
|
||||
return skill_out(actor, skill)
|
||||
|
||||
|
||||
# ---- publication (T1) --------------------------------------------------------------------------
|
||||
# One path for skills and agents: `_publish` is the ONLY reader of `skills_firm_publish`, and
|
||||
# `_make_current` the only place a firm item's current version moves.
|
||||
|
||||
def _make_current(item, version) -> None:
|
||||
item.scope = SkillScope.firm
|
||||
item.current_version_id = version.id
|
||||
|
||||
|
||||
def _publish(db: DbSession, actor: AppUser, kind: PublishKind, item, version, *,
|
||||
ip: str | None, request_only: bool = False) -> dict:
|
||||
"""`approval` -> a request for THIS version (every version, not only the first); `direct` ->
|
||||
published now. The item stays where it was until an administrator says yes. `request_only`:
|
||||
a proposer who may not edit never publishes on their own, and neither does an editor publishing
|
||||
a version a non-editor wrote: both file a request, whatever the setting says."""
|
||||
if item.status == CatalogStatus.archived:
|
||||
raise ConflictError("An archived item cannot be published.")
|
||||
if item.scope == SkillScope.firm and item.current_version_id == version.id:
|
||||
raise ConflictError("This version is already published.")
|
||||
target = f"{getattr(item, 'slug', item.name)} v{version.n}"
|
||||
if not request_only and settings.get(db, "skills_firm_publish") == "direct":
|
||||
_make_current(item, version)
|
||||
db.flush()
|
||||
# No request and nobody else's yes: the setting is the approval, the detail says so.
|
||||
audit.record(db, action=f"{kind}.publish_approve", entity_type=str(kind),
|
||||
entity_id=item.id, actor_id=actor.id, detail=f"{target} direct", ip=ip)
|
||||
return {"status": "published", "request_id": None}
|
||||
if db.scalar(select(PublishRequest.id).where(
|
||||
PublishRequest.kind == kind, PublishRequest.version_id == version.id,
|
||||
PublishRequest.status == PublishRequestStatus.pending)):
|
||||
raise ConflictError("This version is already waiting for an approver.")
|
||||
req = PublishRequest(kind=kind.value, version_id=version.id, requested_by=actor.id,
|
||||
status=PublishRequestStatus.pending.value)
|
||||
db.add(req)
|
||||
db.flush() # the partial unique index turns a double-submit race into a 409 here
|
||||
audit.record(db, action=f"{kind}.publish_request", entity_type=str(kind), entity_id=item.id,
|
||||
actor_id=actor.id, detail=target, ip=ip)
|
||||
return {"status": "pending", "request_id": req.id}
|
||||
|
||||
|
||||
def publish_skill(db: DbSession, actor: AppUser, skill_id: uuid.UUID, n: int | None = None, *,
|
||||
ip: str | None) -> dict:
|
||||
"""Publish version `n` (default: the newest) to the firm — by the owner, or for a firm skill
|
||||
also by an administrator. Without `n` it is the actor's OWN newest version, never a stranger's.
|
||||
It goes live directly (setting `direct`) only when the actor may edit AND so could the version's
|
||||
author; anything else — a proposer's publish, or an editor publishing a proposal — is a request."""
|
||||
skill = _get_proposable(db, actor, skill_id)
|
||||
query = select(SkillVersion).where(SkillVersion.skill_id == skill.id)
|
||||
query = (query.where(SkillVersion.n == n) if n is not None
|
||||
else query.where(SkillVersion.created_by == actor.id)
|
||||
.order_by(SkillVersion.n.desc()).limit(1))
|
||||
version = db.scalar(query)
|
||||
# A non-editor publishes only what they wrote; anything else is as unreadable (and as 404) to
|
||||
# them as a read of it would be, so no number can be probed and no draft lands in the queue.
|
||||
if version is None or (not can_edit(actor, skill) and version.created_by != actor.id):
|
||||
raise NotFoundError("Version not found.")
|
||||
author = db.get(AppUser, version.created_by)
|
||||
request_only = not (can_edit(actor, skill) and author is not None and can_edit(author, skill))
|
||||
return {**_publish(db, actor, PublishKind.skill, skill, version, ip=ip,
|
||||
request_only=request_only),
|
||||
"skill": skill_out(actor, skill)}
|
||||
|
||||
|
||||
def _require_approver(db: DbSession, actor: AppUser) -> None:
|
||||
# The router guards too; this is what keeps someone's personal skill out of other hands.
|
||||
if not may_approve(db, actor):
|
||||
raise AuthorizationError("Only an approver decides publish requests.")
|
||||
|
||||
|
||||
def _resolve(db: DbSession, req: PublishRequest):
|
||||
"""-> (item, version) a request names; versions are never deleted, so both exist."""
|
||||
if req.kind == PublishKind.skill:
|
||||
version = db.get(SkillVersion, req.version_id)
|
||||
return db.get(Skill, version.skill_id), version
|
||||
version = db.get(AgentVersion, req.version_id)
|
||||
return db.get(Agent, version.agent_id), version
|
||||
|
||||
|
||||
def refuses_older(item, current_n: int | None, version) -> bool:
|
||||
"""Approving v2 after v3 went out would quietly roll the firm back: refuse it."""
|
||||
return item.scope == SkillScope.firm and current_n is not None and version.n < current_n
|
||||
|
||||
|
||||
def decide_publish(db: DbSession, actor: AppUser, request_id: uuid.UUID, *, approve: bool,
|
||||
note: str | None = None, ip: str | None = None) -> dict:
|
||||
"""An approver's yes or no. Yes moves the firm's current version to the requested one. An
|
||||
approver who is not an administrator never decides a request they filed, nor one for a version
|
||||
they wrote (an owner's publish of an approver's proposal is a request, Ruling 10): that is the
|
||||
second pair of eyes. An administrator may, as before."""
|
||||
_require_approver(db, actor)
|
||||
# Row lock: two administrators deciding the same request at once must not both "win".
|
||||
req = db.scalar(select(PublishRequest).where(PublishRequest.id == request_id)
|
||||
.with_for_update())
|
||||
if req is None:
|
||||
raise NotFoundError("Request not found.")
|
||||
if req.status != PublishRequestStatus.pending:
|
||||
raise ConflictError("This request has already been decided.")
|
||||
own = "You cannot decide your own request."
|
||||
if req.requested_by == actor.id and not actor.is_admin:
|
||||
raise AuthorizationError(own)
|
||||
item, version = _resolve(db, req)
|
||||
if version.created_by == actor.id and not actor.is_admin:
|
||||
raise AuthorizationError(own)
|
||||
if approve:
|
||||
if item.status == CatalogStatus.archived:
|
||||
raise ConflictError("An archived item cannot be published.")
|
||||
current = db.get(type(version), item.current_version_id) if item.current_version_id else None
|
||||
if refuses_older(item, current.n if current else None, version):
|
||||
raise ConflictError("A newer version is already published; decline this one.")
|
||||
if req.kind == PublishKind.agent:
|
||||
# Asked for while the pins were checked; asked again, because approving is what exposes them.
|
||||
_check_pins(db, actor, SkillScope.firm, _pinned_ids(db, version.id))
|
||||
_make_current(item, version)
|
||||
req.status = (PublishRequestStatus.approved if approve else PublishRequestStatus.declined).value
|
||||
req.decided_by = actor.id
|
||||
req.decided_at = dt.datetime.now(dt.UTC)
|
||||
req.note = _clean_note(note)
|
||||
db.flush()
|
||||
audit.record(db, action=f"{req.kind}.publish_{'approve' if approve else 'decline'}",
|
||||
entity_type=req.kind, entity_id=item.id, actor_id=actor.id,
|
||||
detail=f"{getattr(item, 'slug', item.name)} v{version.n}", ip=ip)
|
||||
return _request_out(db, req)
|
||||
|
||||
|
||||
def _request_out(db: DbSession, req: PublishRequest) -> dict:
|
||||
"""A request with both sides of the diff: what is asked for, and what the firm has now."""
|
||||
item, version = _resolve(db, req)
|
||||
requester = db.get(AppUser, req.requested_by)
|
||||
base = None
|
||||
if item.scope == SkillScope.firm and item.current_version_id not in (None, version.id):
|
||||
base = _full_version(db, req.kind, db.get(type(version), item.current_version_id))
|
||||
return {"id": req.id, "kind": req.kind, "status": req.status, "note": req.note,
|
||||
"created_at": req.created_at, "decided_at": req.decided_at,
|
||||
"requested_by": {"id": requester.id, "email": requester.email,
|
||||
"full_name": requester.full_name},
|
||||
"item": {"id": item.id, "slug": getattr(item, "slug", None), "name": item.name,
|
||||
"scope": item.scope, "status": item.status},
|
||||
"version": _full_version(db, req.kind, version), "base": base}
|
||||
|
||||
|
||||
def _full_version(db: DbSession, kind: str, version) -> dict:
|
||||
if kind == PublishKind.skill:
|
||||
return version_out(version, _files(db, version.id))
|
||||
return agent_version_out(version, _pins(db, version.id))
|
||||
|
||||
|
||||
def pending_publish_requests(db: DbSession, actor: AppUser) -> list[dict]:
|
||||
"""Every pending request, oldest first: the one place an approver sees somebody else's personal
|
||||
skill, and only the version put forward (which `_readable_version` lets them read as well)."""
|
||||
_require_approver(db, actor)
|
||||
rows = db.scalars(select(PublishRequest).where(
|
||||
PublishRequest.status == PublishRequestStatus.pending).order_by(PublishRequest.created_at))
|
||||
return [_request_out(db, r) for r in rows]
|
||||
|
||||
|
||||
# ---- import and export -------------------------------------------------------------------------
|
||||
|
||||
def free_slug(taken, slug: str) -> str:
|
||||
"""`slug`, or the first of `slug-2`, `slug-3`… nobody in `taken` has — trimmed to stay ≤ 64."""
|
||||
n, candidate = 1, slug
|
||||
while candidate in taken:
|
||||
n += 1
|
||||
suffix = f"-{n}"
|
||||
candidate = slug[: skill_pack.MAX_NAME - len(suffix)].rstrip("-") + suffix
|
||||
return candidate
|
||||
|
||||
|
||||
def _sha(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def _already_have(db: DbSession, actor: AppUser, sha: str) -> SkillVersion | None:
|
||||
"""A version of one of `actor`'s active skills with this content — stored as it was imported
|
||||
(`provenance`), or exported from here and coming back (`content_sha256`)."""
|
||||
return db.scalar(
|
||||
select(SkillVersion).join(Skill, Skill.id == SkillVersion.skill_id)
|
||||
.where(Skill.owner_id == actor.id, Skill.status == CatalogStatus.active,
|
||||
or_(SkillVersion.content_sha256 == sha,
|
||||
SkillVersion.provenance["content_sha256"].astext == sha))
|
||||
.order_by(SkillVersion.created_at.desc()).limit(1))
|
||||
|
||||
|
||||
def _import_one(db: DbSession, actor: AppUser, doc, content: SkillContent, sha: str,
|
||||
match: SkillVersion | None, taken: set, *, filename: str | None, pack_sha: str,
|
||||
ip: str | None) -> tuple[Skill, SkillVersion]:
|
||||
"""One SKILL.md of a pack: a new version of `match`'s skill, or a new personal skill."""
|
||||
provenance = {"filename": filename, "path": doc.path, "pack_sha256": pack_sha,
|
||||
"content_sha256": sha}
|
||||
fields = dict(description=doc.description, body=doc.body,
|
||||
license=str(doc.frontmatter.get("license") or DEFAULT_LICENSE),
|
||||
meta={k: v for k, v in doc.frontmatter.items() if k not in _OWN_KEYS},
|
||||
files=content.files, provenance=provenance)
|
||||
if match is not None:
|
||||
skill = db.get(Skill, match.skill_id)
|
||||
latest = db.scalar(select(SkillVersion.n).where(SkillVersion.skill_id == skill.id)
|
||||
.order_by(SkillVersion.n.desc()).limit(1))
|
||||
version = _add_version(db, actor, skill, next_n(latest), **fields)
|
||||
else:
|
||||
slug = free_slug(taken, doc.name)
|
||||
taken.add(slug)
|
||||
skill = Skill(slug=slug, name=doc.name, owner_id=actor.id, scope=SkillScope.personal,
|
||||
status=CatalogStatus.active, origin=SkillOrigin.imported)
|
||||
db.add(skill)
|
||||
db.flush()
|
||||
version = _add_version(db, actor, skill, 1, **fields)
|
||||
# The pack's own sum, so the audit row names the file that came in; never its content.
|
||||
audit.record(db, action="skill.import", entity_type="skill", entity_id=skill.id,
|
||||
actor_id=actor.id, ip=ip,
|
||||
detail=f"{skill.slug} v{version.n} {version.content_sha256} pack {pack_sha}")
|
||||
return skill, version
|
||||
|
||||
|
||||
def import_skills(db: DbSession, actor: AppUser, data: bytes, filename: str | None = None, *,
|
||||
add_version: bool = False, ip: str | None) -> dict:
|
||||
"""Every SKILL.md of an uploaded pack becomes a personal copy of `actor`'s: `origin=imported`,
|
||||
version 1, a free slug (`x`, `x-2`…). Nothing updates itself: if `actor` already has one of
|
||||
them (same `content_sha256`), nothing is written and the answer is `duplicate` — call again
|
||||
with `add_version=True` to add those as a new version of the skill they match.
|
||||
|
||||
-> {"status": "imported" | "duplicate", "skills": [one per SKILL.md: path, its sum, the match
|
||||
or the skill written, and `info_only` — what it asked for and was not given (D3)], "ignored":
|
||||
files of the pack that belong to no skill (a plugin's commands/, agents/…)}"""
|
||||
pack = skill_pack.read_pack(data)
|
||||
if pack.agent is not None or pack.kind == "agent":
|
||||
raise PackRejected("pack_is_agent", [skill_pack.AGENT_DOC])
|
||||
if not pack.skills:
|
||||
raise PackRejected("pack_no_skill")
|
||||
pack_sha = _sha(data)
|
||||
found = []
|
||||
for doc in pack.skills:
|
||||
content = skill_pack.skill_content(pack, doc)
|
||||
found.append((doc, content, skill_pack.content_sha256(content)))
|
||||
matches = {sha: _already_have(db, actor, sha) for _, _, sha in found}
|
||||
used = {doc.path[: -len("SKILL.md")] for doc in pack.skills}
|
||||
ignored = sorted(p for p in pack.files
|
||||
if p != skill_pack.AGENT_DOC and not any(p.startswith(u) for u in used))
|
||||
if any(matches.values()) and not add_version:
|
||||
return {"status": "duplicate", "ignored": ignored, "skills": [
|
||||
{"path": doc.path, "content_sha256": sha, "info_only": doc.info_only,
|
||||
"match": ({**skill_out(actor, db.get(Skill, matches[sha].skill_id)),
|
||||
"n": matches[sha].n} if matches[sha] else None)}
|
||||
for doc, _, sha in found]}
|
||||
|
||||
taken = set(db.scalars(select(Skill.slug).where(Skill.owner_id == actor.id)))
|
||||
out = []
|
||||
for doc, content, sha in found:
|
||||
skill, version = _import_one(db, actor, doc, content, sha, matches[sha], taken,
|
||||
filename=filename, pack_sha=pack_sha, ip=ip)
|
||||
out.append({"path": doc.path, "content_sha256": version.content_sha256,
|
||||
"info_only": doc.info_only, "skill": skill_out(actor, skill), "n": version.n})
|
||||
return {"status": "imported", "ignored": ignored, "skills": out}
|
||||
|
||||
|
||||
def may_export(user: AppUser, item, firm_export: str) -> bool:
|
||||
"""T2. One's own: always. A firm one: an administrator, or everybody under `everyone`."""
|
||||
return (item.owner_id == user.id or bool(user.is_admin) or firm_export == "everyone")
|
||||
|
||||
|
||||
def export_skill(db: DbSession, actor: AppUser, skill_id: uuid.UUID, n: int | None = None, *,
|
||||
ip: str | None) -> tuple[str, bytes]:
|
||||
"""The pack of version `n` (default: the current one) -> (file name, ZIP bytes)."""
|
||||
skill = _get(db, actor, skill_id) # somebody else's personal one is a 404 before T2 is asked
|
||||
if not may_export(actor, skill, settings.get(db, "skills_firm_export")):
|
||||
raise AuthorizationError("Only an administrator may export the firm's skills.")
|
||||
query = select(SkillVersion).where(SkillVersion.skill_id == skill.id)
|
||||
query = (query.where(SkillVersion.n == n) if n is not None
|
||||
else query.where(SkillVersion.id == skill.current_version_id))
|
||||
version = db.scalar(query)
|
||||
if version is None or not readable_version_ids(actor, skill, [version]):
|
||||
raise NotFoundError("Version not found.")
|
||||
data = skill_pack.build_pack([version_content(skill, version, _files(db, version.id))])
|
||||
audit.record(db, action="skill.export", entity_type="skill", entity_id=skill.id,
|
||||
actor_id=actor.id, ip=ip,
|
||||
detail=f"{skill.slug} v{version.n} {version.content_sha256} pack {_sha(data)}")
|
||||
return f"{skill.slug}-v{version.n}.zip", data
|
||||
|
||||
|
||||
# ---- agents --------------------------------------------------------------------------------------
|
||||
# The same rules as skills — visibility (`can_see`/`can_edit`), frozen versions, publication through
|
||||
# `_publish`, T2 through `may_export` — plus one of their own: what a version may pin (`may_pin`).
|
||||
# ponytail: an agent has no description column; an exported agent.md carries its name there and an
|
||||
# imported one's description is not kept. Add a column (own revision) when the console needs one.
|
||||
|
||||
def may_pin(user: AppUser, agent_scope: str, skill: Skill | None, version: SkillVersion | None) -> bool:
|
||||
"""THE pinning rule. A firm agent pins only the firm's published skill versions (what everybody
|
||||
already reads), a personal one any skill version its author may read. Anything else would let
|
||||
an agent show people what they may not see."""
|
||||
if skill is None or version is None or version.skill_id != skill.id:
|
||||
return False
|
||||
if agent_scope == SkillScope.firm:
|
||||
# ponytail: only the CURRENT published version — an older approved one is refused too;
|
||||
# remembering which versions were approved would lift that, if repinning annoys.
|
||||
return skill.scope == SkillScope.firm and version.id == skill.current_version_id
|
||||
return can_see(user, skill) and bool(readable_version_ids(user, skill, [version]))
|
||||
|
||||
|
||||
def _check_pins(db: DbSession, user: AppUser, agent_scope: str, ids) -> list[SkillVersion]:
|
||||
"""`ids` as versions, in order, or a ValidationError naming every one `may_pin` refuses."""
|
||||
ids = list(ids)
|
||||
if len(set(ids)) != len(ids):
|
||||
raise ValidationError("A skill version is pinned twice.")
|
||||
versions = [db.get(SkillVersion, i) for i in ids]
|
||||
refused = [str(i) for i, v in zip(ids, versions, strict=True)
|
||||
if not may_pin(user, agent_scope, v and db.get(Skill, v.skill_id), v)]
|
||||
if refused:
|
||||
pl, en = (("Agent firmowy przypina tylko opublikowane wersje firmowych skilli.",
|
||||
"A firm agent pins only the firm's published skill versions.")
|
||||
if agent_scope == SkillScope.firm
|
||||
else ("Nie znaleziono wersji skilla.", "Skill version not found."))
|
||||
raise ValidationError(pl, extra={"code": "agent_pin_refused", "en": en,
|
||||
"skill_version_ids": refused})
|
||||
return versions
|
||||
|
||||
|
||||
def _pinned_ids(db: DbSession, agent_version_id: uuid.UUID) -> list[uuid.UUID]:
|
||||
return list(db.scalars(select(AgentVersionSkill.skill_version_id)
|
||||
.where(AgentVersionSkill.agent_version_id == agent_version_id)
|
||||
.order_by(AgentVersionSkill.position)))
|
||||
|
||||
|
||||
def _pins(db: DbSession, agent_version_id: uuid.UUID) -> list[tuple[Skill, SkillVersion]]:
|
||||
out = []
|
||||
for vid in _pinned_ids(db, agent_version_id):
|
||||
version = db.get(SkillVersion, vid)
|
||||
out.append((db.get(Skill, version.skill_id), version))
|
||||
return out
|
||||
|
||||
|
||||
def agent_out(user: AppUser, agent: Agent) -> dict[str, Any]:
|
||||
return {"id": agent.id, "name": agent.name, "owner_id": agent.owner_id, "scope": agent.scope,
|
||||
"status": agent.status, "kind": agent.kind,
|
||||
"current_version_id": agent.current_version_id, "mine": agent.owner_id == user.id,
|
||||
"editable": can_edit(user, agent)}
|
||||
|
||||
|
||||
def agent_version_out(version: AgentVersion, pins: list[tuple[Skill, SkillVersion]]) -> dict:
|
||||
"""A version with its pins named; an archived skill stays pinned, and says so."""
|
||||
return {"id": version.id, "n": version.n, "instructions": version.instructions_md,
|
||||
"model_policy": version.model_policy, "tools_requested": list(version.tools_requested),
|
||||
"created_at": version.created_at, "created_by": version.created_by,
|
||||
"skills": [{"skill_id": s.id, "slug": s.slug, "name": s.name, "scope": s.scope,
|
||||
"status": s.status, "skill_version_id": v.id, "n": v.n,
|
||||
"description": v.description} for s, v in pins]}
|
||||
|
||||
|
||||
def _get_agent(db: DbSession, user: AppUser, agent_id: uuid.UUID) -> Agent:
|
||||
agent = db.get(Agent, agent_id)
|
||||
if agent is None or not can_see(user, agent):
|
||||
raise NotFoundError("Agent not found.")
|
||||
return agent
|
||||
|
||||
|
||||
def _get_agent_editable(db: DbSession, user: AppUser, agent_id: uuid.UUID) -> Agent:
|
||||
agent = _get_agent(db, user, agent_id)
|
||||
if not can_edit(user, agent):
|
||||
raise AuthorizationError("Only the owner or an administrator may change a firm agent.")
|
||||
return agent
|
||||
|
||||
|
||||
def _agent_version(db: DbSession, agent: Agent, n: int | None) -> AgentVersion | None:
|
||||
query = select(AgentVersion).where(AgentVersion.agent_id == agent.id)
|
||||
return db.scalar(query.where(AgentVersion.n == n) if n is not None
|
||||
else query.order_by(AgentVersion.n.desc()).limit(1))
|
||||
|
||||
|
||||
def _audit_agent(db: DbSession, actor: AppUser, action: str, agent: Agent,
|
||||
version: AgentVersion | None = None, extra: str = "", *, ip: str | None) -> None:
|
||||
detail = agent.name if version is None else f"{agent.name} v{version.n}"
|
||||
audit.record(db, action=action, entity_type="agent", entity_id=agent.id, actor_id=actor.id,
|
||||
detail=f"{detail} {extra}".strip(), ip=ip)
|
||||
|
||||
|
||||
def _add_agent_version(db: DbSession, actor: AppUser, agent: Agent, n: int, *, instructions: str,
|
||||
model_policy: dict | None, tools, skill_version_ids) -> AgentVersion:
|
||||
pinned = _check_pins(db, actor, agent.scope, skill_version_ids)
|
||||
version = AgentVersion(agent_id=agent.id, n=n, instructions_md=instructions,
|
||||
model_policy=model_policy, tools_requested=list(tools),
|
||||
created_by=actor.id)
|
||||
db.add(version)
|
||||
db.flush()
|
||||
for position, sv in enumerate(pinned):
|
||||
db.add(AgentVersionSkill(agent_version_id=version.id, skill_version_id=sv.id,
|
||||
position=position))
|
||||
if agent.scope == SkillScope.personal:
|
||||
agent.current_version_id = version.id
|
||||
# A firm agent's current version moves only through publication, as a firm skill's does.
|
||||
db.flush()
|
||||
return version
|
||||
|
||||
|
||||
def list_agents(db: DbSession, user: AppUser) -> list[dict]:
|
||||
"""Own agents and firm ones — `can_see` as SQL, the same rule `visible_to` applies to skills."""
|
||||
rows = db.scalars(select(Agent).where(or_(Agent.owner_id == user.id,
|
||||
Agent.scope == SkillScope.firm))
|
||||
.order_by(Agent.name, Agent.id))
|
||||
return [agent_out(user, a) for a in rows]
|
||||
|
||||
|
||||
def get_agent(db: DbSession, user: AppUser, agent_id: uuid.UUID) -> dict:
|
||||
"""The agent, its versions (an editor sees all, anybody else the current one) and the current
|
||||
one in full."""
|
||||
agent = _get_agent(db, user, agent_id)
|
||||
versions = list(db.scalars(select(AgentVersion).where(AgentVersion.agent_id == agent.id)
|
||||
.order_by(AgentVersion.n.desc())))
|
||||
if not can_edit(user, agent):
|
||||
versions = [v for v in versions if v.id == agent.current_version_id]
|
||||
current = next((v for v in versions if v.id == agent.current_version_id), None)
|
||||
return {**agent_out(user, agent),
|
||||
"versions": [{"n": v.n, "id": v.id, "created_at": v.created_at} for v in versions],
|
||||
"current": agent_version_out(current, _pins(db, current.id)) if current else None}
|
||||
|
||||
|
||||
def create_agent(db: DbSession, actor: AppUser, fields: Mapping, *, ip: str | None) -> dict:
|
||||
"""A personal agent with its version 1. `fields`: name, instructions, and optionally
|
||||
model_policy (a hint), tools (requested, never granted — D3) and skill_version_ids."""
|
||||
agent = Agent(name=fields["name"], owner_id=actor.id, scope=SkillScope.personal,
|
||||
status=CatalogStatus.active, kind=AgentKind.assistant)
|
||||
db.add(agent)
|
||||
db.flush()
|
||||
version = _add_agent_version(db, actor, agent, 1, instructions=fields["instructions"],
|
||||
model_policy=fields.get("model_policy"),
|
||||
tools=fields.get("tools") or [],
|
||||
skill_version_ids=fields.get("skill_version_ids") or [])
|
||||
_audit_agent(db, actor, "agent.create", agent, version, ip=ip)
|
||||
return agent_out(actor, agent)
|
||||
|
||||
|
||||
def new_agent_version(db: DbSession, actor: AppUser, agent_id: uuid.UUID, fields: Mapping, *,
|
||||
ip: str | None) -> dict:
|
||||
"""Version `n + 1`; a field that is None is carried over from the newest version, the pins
|
||||
included (`[]` unpins everything). Carried-over pins are checked again: what a firm agent may
|
||||
pin is decided now, not when the list was first made."""
|
||||
agent = _get_agent_editable(db, actor, agent_id)
|
||||
if agent.status == CatalogStatus.archived:
|
||||
raise ConflictError("An archived agent takes no new versions.")
|
||||
latest = _agent_version(db, agent, None)
|
||||
if fields.get("name"):
|
||||
agent.name = fields["name"]
|
||||
pins = fields.get("skill_version_ids")
|
||||
version = _add_agent_version(
|
||||
db, actor, agent, next_n(latest.n),
|
||||
instructions=(fields["instructions"] if fields.get("instructions") is not None
|
||||
else latest.instructions_md),
|
||||
model_policy=(fields["model_policy"] if fields.get("model_policy") is not None
|
||||
else latest.model_policy),
|
||||
tools=fields["tools"] if fields.get("tools") is not None else latest.tools_requested,
|
||||
skill_version_ids=pins if pins is not None else _pinned_ids(db, latest.id))
|
||||
_audit_agent(db, actor, "agent.version", agent, version, ip=ip)
|
||||
return agent_version_out(version, _pins(db, version.id))
|
||||
|
||||
|
||||
def archive_agent(db: DbSession, actor: AppUser, agent_id: uuid.UUID, *, ip: str | None) -> dict:
|
||||
"""Archived, not deleted — like a skill."""
|
||||
agent = _get_agent_editable(db, actor, agent_id)
|
||||
if agent.status != CatalogStatus.archived:
|
||||
agent.status = CatalogStatus.archived
|
||||
db.flush()
|
||||
_audit_agent(db, actor, "agent.archive", agent, ip=ip)
|
||||
return agent_out(actor, agent)
|
||||
|
||||
|
||||
def publish_agent(db: DbSession, actor: AppUser, agent_id: uuid.UUID, n: int | None = None, *,
|
||||
ip: str | None) -> dict:
|
||||
"""Version `n` (default: the newest) to the firm, through the same T1 path as a skill. Its pins
|
||||
must already be the firm's: a firm agent never carries somebody's personal skill."""
|
||||
agent = _get_agent_editable(db, actor, agent_id)
|
||||
version = _agent_version(db, agent, n)
|
||||
if version is None:
|
||||
raise NotFoundError("Version not found.")
|
||||
_check_pins(db, actor, SkillScope.firm, _pinned_ids(db, version.id))
|
||||
return {**_publish(db, actor, PublishKind.agent, agent, version, ip=ip),
|
||||
"agent": agent_out(actor, agent)}
|
||||
|
||||
|
||||
def _slugish(name: str) -> str:
|
||||
"""A file name out of an agent's free-text name."""
|
||||
plain = unicodedata.normalize("NFKD", name.lower().replace("ł", "l")) # ó -> o, ł has no NFKD
|
||||
out = "-".join("".join(c if c.isascii() and c.isalnum() else " " if not unicodedata.combining(c)
|
||||
else "" for c in plain).split())
|
||||
return out[: skill_pack.MAX_NAME] or "agent"
|
||||
|
||||
|
||||
def export_agent(db: DbSession, actor: AppUser, agent_id: uuid.UUID, n: int | None = None, *,
|
||||
ip: str | None) -> tuple[str, bytes]:
|
||||
"""agent.md and every pinned skill version in one pack. T2 covers the pinned skills too: a
|
||||
personal agent pinning a firm skill exports only where that skill would."""
|
||||
agent = _get_agent(db, actor, agent_id)
|
||||
version = (_agent_version(db, agent, n) if n is not None else
|
||||
db.get(AgentVersion, agent.current_version_id) if agent.current_version_id else None)
|
||||
if version is None or (not can_edit(actor, agent) and version.id != agent.current_version_id):
|
||||
raise NotFoundError("Version not found.")
|
||||
pins = _pins(db, version.id)
|
||||
firm_export = settings.get(db, "skills_firm_export")
|
||||
if not all(may_export(actor, item, firm_export) for item in [agent, *(s for s, _ in pins)]):
|
||||
raise AuthorizationError("Only an administrator may export the firm's skills and agents.")
|
||||
folders: set[str] = set()
|
||||
contents = []
|
||||
for skill, sv in pins:
|
||||
folder = free_slug(folders, skill.slug) # two owners' `nda` side by side
|
||||
folders.add(folder)
|
||||
contents.append(dataclasses.replace(version_content(skill, sv, _files(db, sv.id)),
|
||||
folder=folder))
|
||||
head = {"name": agent.name, "description": agent.name, "kind": agent.kind}
|
||||
if version.tools_requested:
|
||||
head["tools"] = list(version.tools_requested)
|
||||
if (version.model_policy or {}).get("model"):
|
||||
head["model"] = version.model_policy["model"]
|
||||
data = skill_pack.build_pack(contents, skill_pack.AgentDoc(
|
||||
name=agent.name, description=agent.name, body=version.instructions_md, frontmatter=head))
|
||||
_audit_agent(db, actor, "agent.export", agent, version, f"pack {_sha(data)}", ip=ip)
|
||||
return f"{_slugish(agent.name)}-v{version.n}.zip", data
|
||||
|
||||
|
||||
def import_agent(db: DbSession, actor: AppUser, data: bytes, filename: str | None = None, *,
|
||||
ip: str | None) -> dict:
|
||||
"""An agent pack becomes a personal agent of `actor`'s, version 1, pinning its skills: a skill
|
||||
`actor` already has (same sum) is pinned as it is, every other one is imported as a personal
|
||||
copy first. `tools` and `model` are kept as a request and a hint, never granted (D3)."""
|
||||
pack = skill_pack.read_pack(data)
|
||||
if pack.agent is None:
|
||||
raise PackRejected("pack_not_agent")
|
||||
head = pack.agent.frontmatter
|
||||
if head.get("kind", AgentKind.assistant) != AgentKind.assistant:
|
||||
raise PackRejected("pack_agent_kind", [skill_pack.AGENT_DOC])
|
||||
pack_sha = _sha(data)
|
||||
taken = set(db.scalars(select(Skill.slug).where(Skill.owner_id == actor.id)))
|
||||
pinned, skills_out = [], []
|
||||
for doc in pack.skills:
|
||||
content = skill_pack.skill_content(pack, doc)
|
||||
sha = skill_pack.content_sha256(content)
|
||||
version = _already_have(db, actor, sha)
|
||||
if version is None:
|
||||
skill, version = _import_one(db, actor, doc, content, sha, None, taken,
|
||||
filename=filename, pack_sha=pack_sha, ip=ip)
|
||||
else:
|
||||
skill = db.get(Skill, version.skill_id)
|
||||
if version.id not in pinned: # two folders of one pack with the same content
|
||||
pinned.append(version.id)
|
||||
skills_out.append({"path": doc.path, "content_sha256": sha, "info_only": doc.info_only,
|
||||
"skill": skill_out(actor, skill), "n": version.n})
|
||||
tools = head.get("tools")
|
||||
model = head.get("model")
|
||||
agent = Agent(name=pack.agent.name, owner_id=actor.id, scope=SkillScope.personal,
|
||||
status=CatalogStatus.active, kind=AgentKind.assistant)
|
||||
db.add(agent)
|
||||
db.flush()
|
||||
version = _add_agent_version(
|
||||
db, actor, agent, 1, instructions=pack.agent.body,
|
||||
model_policy={"model": str(model)} if model else None,
|
||||
tools=[str(t) for t in tools] if isinstance(tools, list) else [],
|
||||
skill_version_ids=pinned)
|
||||
_audit_agent(db, actor, "agent.import", agent, version, f"pack {pack_sha}", ip=ip)
|
||||
return {"status": "imported", "agent": agent_out(actor, agent), "skills": skills_out,
|
||||
"info_only": {k: head[k] for k in ("tools", "model") if k in head}}
|
||||
@@ -0,0 +1,175 @@
|
||||
"""History and trends on the home page: aggregates over the platform's event log (`module_event`).
|
||||
|
||||
Current numbers still come from each module's own stats, which the console asks directly; history
|
||||
and trends come from the event log, which carries identifiers and numbers only - never a title, a
|
||||
name or a sentence (`dredd_core.events.check_payload`). Nothing here returns an id or a list of
|
||||
documents: events per day and kind, and how long documents took between two kinds of event.
|
||||
|
||||
**Where the log is.** Atrium is the hub: on the platform the log is its own (`dredd.module_event`,
|
||||
revision 0011), reached through the `search_path`. Standalone nobody writes events into this schema,
|
||||
so the charts say there is no log; nothing fails. A lightweight `table()` construct reads it, so this
|
||||
file adds nothing to the metadata.
|
||||
|
||||
Events are not filtered per person (the log has no notion of who may read the subject), so the route
|
||||
keeps these charts to platform administrators (`routers/marketplace.home_trends`).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import statistics
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import DateTime, Text, column, func, literal_column, select, table, text
|
||||
from sqlalchemy.dialects.postgresql import JSONB
|
||||
from sqlalchemy.orm import Session as DbSession
|
||||
|
||||
#: The platform's working day: a day on a chart is a day in Poland.
|
||||
ZONE = "Europe/Warsaw"
|
||||
#: The history the activity chart shows, today included.
|
||||
DAYS = 30
|
||||
#: How far back the durations look for the events that start a measurement.
|
||||
DURATION_YEARS = 2
|
||||
|
||||
_EVENT = table(
|
||||
"module_event",
|
||||
column("kind", Text),
|
||||
column("source_module", Text),
|
||||
column("payload", JSONB),
|
||||
column("created_at", DateTime(timezone=True)),
|
||||
)
|
||||
|
||||
#: The kinds the platform emits today (`dredd_core.events.FIRST_EVENTS`) in the console's words.
|
||||
#: A kind not listed is still counted, under its own code.
|
||||
KIND_LABELS: dict[str, str] = {
|
||||
"document.version_added": "Nowe wersje dokumentów",
|
||||
"workflow.approved": "Zatwierdzone obiegi",
|
||||
"document.signed": "Podpisane dokumenty",
|
||||
"negotiation.round_received": "Rundy negocjacji",
|
||||
"analysis.accepted": "Zaakceptowane analizy",
|
||||
}
|
||||
|
||||
#: The milestones a document passes, each the FIRST event of its kind naming that document
|
||||
#: (`payload.document_id`), in order. A new event kind adds a milestone here, not a table.
|
||||
MILESTONES: tuple[tuple[str, str], ...] = (
|
||||
("created", "document.version_added"),
|
||||
("approved", "workflow.approved"),
|
||||
("signed", "document.signed"),
|
||||
)
|
||||
#: The stages a duration spans: from the first milestone to the last.
|
||||
SEGMENTS = ("przygotowanie", "podpisanie")
|
||||
#: The distribution's bands in days, both ends included; `None` = no upper end.
|
||||
BANDS = ((0, 7), (8, 30), (31, 90), (91, None))
|
||||
|
||||
|
||||
def log_status(db: DbSession) -> str:
|
||||
"""`ok` when the event log is reachable and readable by this role, `absent` when this database
|
||||
has none (standalone), `no_grant` when it exists but this role may not read it. Catalog reads
|
||||
only, so a missing grant is a status rather than a failed statement."""
|
||||
row = db.execute(text(
|
||||
"SELECT to_regclass('module_event') IS NOT NULL AS present, "
|
||||
"CASE WHEN to_regclass('module_event') IS NULL THEN false "
|
||||
"ELSE has_table_privilege(to_regclass('module_event'), 'SELECT') END AS readable"
|
||||
)).one()
|
||||
if not row.present:
|
||||
return "absent"
|
||||
return "ok" if row.readable else "no_grant"
|
||||
|
||||
|
||||
def _day(column_):
|
||||
# The zone as a literal, not a bind parameter: each bind is its own placeholder, so the GROUP BY
|
||||
# expression would not be the select-list one and PostgreSQL refuses the query.
|
||||
return func.date(func.timezone(literal_column(f"'{ZONE}'"), column_))
|
||||
|
||||
|
||||
def activity(db: DbSession, status: str, *, today: dt.date | None = None) -> dict[str, Any]:
|
||||
"""Events per day and kind over the last DAYS days (today included, the oldest first), every
|
||||
day present with zeros, and the kinds ordered by their total."""
|
||||
if status != "ok":
|
||||
return {"status": status, "days": [], "kinds": [], "total": 0}
|
||||
today = today or dt.datetime.now(dt.timezone.utc).date()
|
||||
first = today - dt.timedelta(days=DAYS - 1)
|
||||
rows = db.execute(activity_statement(first, today)).all()
|
||||
per_day: dict[dt.date, dict[str, int]] = defaultdict(dict)
|
||||
totals: dict[str, int] = defaultdict(int)
|
||||
for when, kind, n in rows:
|
||||
per_day[when][kind] = n
|
||||
totals[kind] += n
|
||||
kinds = sorted(totals, key=lambda k: (-totals[k], k))
|
||||
return {
|
||||
"status": "ok",
|
||||
"days": [{"date": (first + dt.timedelta(days=i)).isoformat(),
|
||||
"counts": per_day.get(first + dt.timedelta(days=i), {})} for i in range(DAYS)],
|
||||
"kinds": [{"kind": k, "label": KIND_LABELS.get(k, k), "total": totals[k]} for k in kinds],
|
||||
"total": sum(totals.values()),
|
||||
}
|
||||
|
||||
|
||||
def activity_statement(first: dt.date, today: dt.date):
|
||||
day = _day(_EVENT.c.created_at)
|
||||
return (select(day.label("day"), _EVENT.c.kind, func.count().label("n"))
|
||||
.where(day >= first, day <= today)
|
||||
.group_by(day, _EVENT.c.kind))
|
||||
|
||||
|
||||
# -- durations ------------------------------------------------------------------
|
||||
|
||||
|
||||
def measure(m: dict[str, dt.date | None]) -> int | str:
|
||||
"""One document's days from its first milestone to its last, or why it has none: `missing` when
|
||||
an end is unknown, `order` when it ends before it starts. Pure."""
|
||||
start, end = m.get(MILESTONES[0][0]), m.get(MILESTONES[-1][0])
|
||||
if start is None or end is None:
|
||||
return "missing"
|
||||
if end < start:
|
||||
return "order"
|
||||
return (end - start).days
|
||||
|
||||
|
||||
def milestones_statement(since: dt.date):
|
||||
# `->>` with a literal key, for the GROUP BY reason `_day` gives.
|
||||
doc = _EVENT.c.payload.op("->>")(literal_column("'document_id'"))
|
||||
kinds = [kind for _, kind in MILESTONES]
|
||||
return (select(doc.label("doc"), _EVENT.c.kind, func.min(_day(_EVENT.c.created_at)).label("day"))
|
||||
.where(_EVENT.c.kind.in_(kinds), doc.isnot(None),
|
||||
_EVENT.c.created_at >= dt.datetime.combine(since, dt.time(), dt.timezone.utc))
|
||||
.group_by(doc, _EVENT.c.kind))
|
||||
|
||||
|
||||
def milestones(db: DbSession, *, today: dt.date | None = None) -> list[dict[str, dt.date | None]]:
|
||||
"""Each document's milestone days, from the first event of each milestone kind that names it.
|
||||
Only documents whose first milestone falls in the last DURATION_YEARS years are measured, and
|
||||
older events are never read."""
|
||||
today = today or dt.datetime.now(dt.timezone.utc).date()
|
||||
since = today - dt.timedelta(days=365 * DURATION_YEARS)
|
||||
by_doc: dict[str, dict[str, dt.date]] = defaultdict(dict)
|
||||
name_of = {kind: name for name, kind in MILESTONES}
|
||||
for document, kind, day in db.execute(milestones_statement(since)).all():
|
||||
by_doc[document][name_of[kind]] = day
|
||||
first = MILESTONES[0][0]
|
||||
return [m for m in by_doc.values() if m.get(first) and m[first] >= since]
|
||||
|
||||
|
||||
def durations(db: DbSession, status: str, *, today: dt.date | None = None) -> dict[str, Any]:
|
||||
"""How long documents took from their first version to signature: how many were measured, the
|
||||
median, the bands, and how many were left out and why. Aggregates only, no document is named."""
|
||||
measured, skipped = [], {"missing": 0, "order": 0}
|
||||
if status == "ok":
|
||||
for m in milestones(db, today=today):
|
||||
days = measure(m)
|
||||
if isinstance(days, str):
|
||||
skipped[days] += 1
|
||||
else:
|
||||
measured.append(days)
|
||||
return {"status": status, "segments": list(SEGMENTS), "measured": len(measured),
|
||||
"median_days": statistics.median(measured) if measured else None,
|
||||
"bands": [{"from": lo, "to": hi,
|
||||
"count": sum(lo <= d and (hi is None or d <= hi) for d in measured)}
|
||||
for lo, hi in BANDS],
|
||||
"skipped": skipped}
|
||||
|
||||
|
||||
def home(db: DbSession) -> dict[str, Any]:
|
||||
"""Both charts, with the log's status read once."""
|
||||
status = log_status(db)
|
||||
return {"activity": activity(db, status), "durations": durations(db, status)}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
pytest==8.3.4
|
||||
pytest-cov==6.0.0
|
||||
pytest-xdist==3.8.0 # MIT — the deploy kit's tests over every core (ci.yml deploy-kit-tests)
|
||||
httpx==0.28.1 # the TestClient transport (the probe uses stdlib http.client)
|
||||
pip-licenses==5.0.0 # the license gate reads this
|
||||
ruff==0.8.4
|
||||
|
||||
@@ -11,8 +11,8 @@
|
||||
# alembic revision for whatever tables or columns the bump brings (never edit 0001).
|
||||
#
|
||||
# The repo is PRIVATE, so pip needs credentials to fetch it:
|
||||
# local — a GitHub PAT in your git credential helper (or an SSH `insteadOf` rewrite)
|
||||
# CI — the DREDD_CORE_TOKEN repo secret; see the auth step in .github/workflows/ci.yml
|
||||
# local — a read-only Gitea access token in your git credential helper (or an SSH `insteadOf` rewrite)
|
||||
# CI — the Haski org secret DREDD_CORE_TOKEN; see the workflow-level `env:` in .github/workflows/
|
||||
#
|
||||
# v0.10.0 is what makes ONE ACCOUNT possible: the shared identity schema (`ModuleModerator`,
|
||||
# `SHARED_IDENTITY_TABLES`, `shared_identity_grants_sql`, `create_identity_tables`,
|
||||
@@ -49,7 +49,14 @@
|
||||
# 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
|
||||
#
|
||||
# v0.19.0 (document_ref, plain_files, module_client) needs nothing here: no schema or grant change.
|
||||
# v0.20.0 adds the module events: the shared `module_event` log the hub creates and grants in its
|
||||
# identity schema (`alembic/versions/0011_module_events.py`, re-applied by `app.identity_grants`).
|
||||
# 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+http://77.216.148.202:3000/Haski/dredd-core.git@v0.26.1
|
||||
|
||||
# Web framework
|
||||
fastapi==0.115.6
|
||||
@@ -73,8 +80,11 @@ argon2-cffi==23.1.0 # Argon2id password hashing (MIT). dredd-core depe
|
||||
# this is now a re-pin rather than the only source — kept explicit so
|
||||
# the version is visible here and the license gate sees it named.
|
||||
# AES-256-GCM for model-provider API keys (app/provider_keys.py). Apache-2.0 OR BSD-3-Clause. Same
|
||||
# pin as Compass, whose analyses decrypt the keys the hub writes.
|
||||
# pin as Arbiter, whose runs decrypt the keys the hub writes.
|
||||
cryptography==46.0.3
|
||||
# SKILL.md frontmatter in skill packs (app/services/skill_pack.py) — `yaml.safe_load` only, never the
|
||||
# full loader. MIT.
|
||||
PyYAML==6.0.3
|
||||
|
||||
|
||||
# OpenTelemetry (OTLP → OTel Collector) — optional, import-guarded in observability.py
|
||||
|
||||
@@ -120,8 +120,8 @@ check("USER app" in dockerfile, "container runs as root",
|
||||
|
||||
# ── the image can install the private core ────────────────────────────────────
|
||||
requirements = read("backend/requirements.txt")
|
||||
if "git+https://github.com/Alpaq92/dredd-core" in requirements:
|
||||
# Not `"git" in dockerfile` — the secret-mount RUN names github.com, so that could never fail.
|
||||
if "dredd-core @ git+" in requirements:
|
||||
# Not `"git" in dockerfile` — the secret-mount RUN names git in its URL rewrite, so that could never fail.
|
||||
# Look for git as a package of an apt/apk install (comments dropped, `\` continuations joined as
|
||||
# BuildKit joins them: whitespace may follow the backslash, and blank lines inside are skipped).
|
||||
run_text = re.sub(r"\\[ \t]*\n(?:[ \t]*\n)*", " ", re.sub(r"(?m)^\s*#.*\n", "", dockerfile))
|
||||
|
||||
@@ -173,7 +173,7 @@ test('module prefixes match only at a segment boundary', () => {
|
||||
test('a malformed module hash shows "not found" instead of throwing', async () => {
|
||||
const calls = [];
|
||||
const env = { state: { user: {}, stale: false }, location: { hash: '#/m/%zz/x' },
|
||||
closeWaffle() {}, refreshShared() {}, showFrame: (...a) => calls.push(a) };
|
||||
closeWaffle() {}, refreshShared() {}, leavingDraft: () => false, showFrame: (...a) => calls.push(a) };
|
||||
const router = new Function(...Object.keys(env), fnBody('async function router() {') + '\nreturn router;')(...Object.values(env));
|
||||
await router();
|
||||
assert.deepEqual(calls, [['', 'x']]);
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
// Run by test_skills_console.py: `node trial_loop.mjs <app.js>`. It lifts the Próba tab's section out
|
||||
// of the console and drives `runVersionLoop` against a scripted `arbiter()`, so the rule "after a 504,
|
||||
// never a POST beside the step still running" is asserted by behaviour, not by grepping for strings.
|
||||
// Time is faked: `setTimeout` fires at once and `Date.now()` is a clock the script moves.
|
||||
import { readFileSync } from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
const SRC = readFileSync(process.argv[2], 'utf8');
|
||||
const START = "/* ── a skill version's trial and standards check (Próba) ──";
|
||||
const i = SRC.indexOf(START);
|
||||
assert.ok(i >= 0, 'the Próba section is not in app.js');
|
||||
const SECTION = SRC.slice(i, SRC.indexOf('/* ── import ──', i));
|
||||
|
||||
const http = (status, detail) => Object.assign(new Error(detail), { status, problem: { detail } });
|
||||
const trialState = (contracts, extra = {}) => ({
|
||||
version_n: 2, ran_at: 'r' + contracts, contracts, of: 15, complete: contracts === 15,
|
||||
rules: contracts * 4, agree: contracts * 4, differ: 0,
|
||||
results: Array.from({ length: contracts }, (_, k) => ({ contract: 'c' + k, status: 'answered' })),
|
||||
...extra,
|
||||
});
|
||||
const agentWith = (st) => ({ id: 'A', skill_trials: { AV: st } });
|
||||
|
||||
/* One run of the loop over `script`: a list of [expected call, reply]. A call off the script is
|
||||
recorded and refused, so the run ends with it in `calls` and in `t.runErr`. */
|
||||
async function run(script, { clock = { now: 0 }, onGet = () => {}, start = trialState(3) } = {}) {
|
||||
const calls = [];
|
||||
const t = { version: 'V1', loading: false, status: { trial: start }, err: null, running: null, stop: false, runErr: null };
|
||||
const state = { _skillView: { s: { id: 'S' }, shown: { id: 'V1', n: 2 } }, _trials: { V1: t }, _trial: t };
|
||||
const arbiter = async (method, path) => {
|
||||
const call = method + ' ' + path;
|
||||
calls.push(call);
|
||||
const next = script.shift();
|
||||
if (!next || next[0] !== call) throw new Error('unexpected call: ' + call);
|
||||
if (method === 'GET') { clock.now += 16 * 60 * 1000; onGet(t, calls, state); }
|
||||
if (next[1] instanceof Error) throw next[1];
|
||||
return next[1];
|
||||
};
|
||||
const env = {
|
||||
state, arbiter, enc: encodeURIComponent, _tr: (x) => x,
|
||||
renderSkillBody() {}, setTimeout: (fn) => fn(), Date: { now: () => clock.now },
|
||||
};
|
||||
const fns = new Function(...Object.keys(env), SECTION + '\nreturn { runVersionLoop };')(...Object.values(env));
|
||||
await fns.runVersionLoop('trial');
|
||||
return { calls, t, script };
|
||||
}
|
||||
|
||||
const SYNC = ['POST skills/S/versions/2/sync', { agent_id: 'A', agent_version_id: 'AV', n: 2, approved_for_firm: false }];
|
||||
const STEP = 'POST agents/A/trial?agent_version_id=AV';
|
||||
const READ = 'GET agents/A';
|
||||
|
||||
const tests = [];
|
||||
const test = (name, fn) => tests.push([name, fn]);
|
||||
|
||||
test('after a 504 the next step waits until a re-read shows the cut-off step landed', async () => {
|
||||
const { calls, t, script } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
[READ, agentWith(trialState(3))], // the cut-off step still running: nothing new yet
|
||||
[READ, agentWith(trialState(4))], // it landed
|
||||
[STEP, agentWith(trialState(15))],
|
||||
], { clock: { now: 0 } });
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, READ, READ, STEP]);
|
||||
assert.equal(script.length, 0);
|
||||
assert.equal(t.runErr, null, 'no error is shown');
|
||||
assert.equal(t.running, null);
|
||||
assert.equal(t.status.trial.complete, true);
|
||||
});
|
||||
|
||||
test('a contract judged again (no new row, a new ran_at) counts as landed', async () => {
|
||||
const { calls, t } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
[READ, agentWith(trialState(3, { ran_at: 'later' }))],
|
||||
[STEP, agentWith(trialState(15))],
|
||||
]);
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, READ, STEP]);
|
||||
assert.equal(t.runErr, null);
|
||||
});
|
||||
|
||||
test('"Zatrzymaj" during the wait still waits for the step, then posts nothing more', async () => {
|
||||
const { calls, t } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
[READ, agentWith(trialState(3))],
|
||||
[READ, agentWith(trialState(4))],
|
||||
], { onGet: (tr, cs) => { if (cs.length === 3) tr.stop = true; } });
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, READ, READ]);
|
||||
assert.equal(t.runErr, null);
|
||||
assert.equal(t.running, null);
|
||||
assert.equal(t.status.trial.contracts, 4);
|
||||
});
|
||||
|
||||
test('a step that never lands is waited for at most the cap, then one POST shows the refusal', async () => {
|
||||
// Each read moves the clock 16 minutes; the cap is 125, so the eighth read is past it.
|
||||
const reads = Array.from({ length: 8 }, () => [READ, agentWith(trialState(3))]);
|
||||
const { calls, t } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
...reads,
|
||||
[STEP, http(409, 'The model is busy with another step.')],
|
||||
]);
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, ...reads.map((r) => r[0]), STEP]);
|
||||
assert.equal(t.runErr.status, 409);
|
||||
assert.equal(t.running, null);
|
||||
});
|
||||
|
||||
test('signing out during the wait ends the loop without another POST', async () => {
|
||||
const { calls, t } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
[READ, agentWith(trialState(3))],
|
||||
], { onGet: (tr, cs, st) => { st._trials = {}; } }); // what showLogin() does
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, READ]);
|
||||
assert.equal(t.runErr, null);
|
||||
});
|
||||
|
||||
test('a retry that is cut off again and never lands stops with a message, not a third POST', async () => {
|
||||
// Each wait runs out the cap (8 reads of 16 minutes); a model server that never answers would
|
||||
// otherwise get a paid call every 125 minutes for ever.
|
||||
const reads = Array.from({ length: 8 }, () => [READ, agentWith(trialState(3))]);
|
||||
const running = [];
|
||||
const { calls, t, script } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
...reads,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
...reads.map((r) => [...r]),
|
||||
], { onGet: (tr) => running.push(tr.running) });
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, ...reads.map((r) => r[0]), STEP, ...reads.map((r) => r[0])]);
|
||||
assert.equal(script.length, 0);
|
||||
assert.ok(t.runErr && t.runErr.slow, 'the "taking too long" message is shown');
|
||||
assert.equal(t.runErr.message, 'Ten krok trwa zbyt długo. Sprawdź serwer modelu i spróbuj ponownie.');
|
||||
assert.ok(running.every((r) => r === 'trial'), 'the button stays disabled through both waits');
|
||||
assert.equal(t.running, null);
|
||||
});
|
||||
|
||||
test('a capped retry that lands carries on as usual', async () => {
|
||||
const reads = Array.from({ length: 8 }, () => [READ, agentWith(trialState(3))]);
|
||||
const { calls, t } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
...reads,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
[READ, agentWith(trialState(4))],
|
||||
[STEP, agentWith(trialState(15))],
|
||||
]);
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, ...reads.map((r) => r[0]), STEP, READ, STEP]);
|
||||
assert.equal(t.runErr, null);
|
||||
assert.equal(t.status.trial.complete, true);
|
||||
});
|
||||
|
||||
test('a read that fails during the wait (502, network) keeps waiting, the button disabled', async () => {
|
||||
const running = [];
|
||||
const { calls, t, script } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
[READ, http(502, 'Bad Gateway')],
|
||||
[READ, new TypeError('Failed to fetch')],
|
||||
[READ, agentWith(trialState(3))],
|
||||
[READ, agentWith(trialState(4))],
|
||||
[STEP, agentWith(trialState(15))],
|
||||
], { clock: { now: 0 }, onGet: (tr) => running.push(tr.running) });
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, READ, READ, READ, READ, STEP]);
|
||||
assert.equal(script.length, 0);
|
||||
assert.equal(t.runErr, null, 'a failed read is not the run\'s error');
|
||||
assert.ok(running.every((r) => r === 'trial'));
|
||||
assert.equal(t.status.trial.complete, true);
|
||||
});
|
||||
|
||||
test('reads that keep failing still end at the cap, then one POST', async () => {
|
||||
const reads = Array.from({ length: 8 }, () => [READ, http(502, 'Bad Gateway')]);
|
||||
const { calls, t } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
...reads,
|
||||
[STEP, agentWith(trialState(15))],
|
||||
]);
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, ...reads.map((r) => r[0]), STEP]);
|
||||
assert.equal(t.runErr, null);
|
||||
assert.equal(t.status.trial.complete, true);
|
||||
});
|
||||
|
||||
test('a 4xx during the wait ends the run: the next POST would be refused just the same', async () => {
|
||||
const { calls, t } = await run([
|
||||
SYNC,
|
||||
[STEP, http(504, 'Gateway Timeout')],
|
||||
[READ, http(401, 'Not authenticated.')],
|
||||
]);
|
||||
assert.deepEqual(calls, [SYNC[0], STEP, READ]);
|
||||
assert.equal(t.runErr.status, 401);
|
||||
assert.equal(t.running, null);
|
||||
});
|
||||
|
||||
let failed = 0;
|
||||
for (const [name, fn] of tests) {
|
||||
try { await fn(); console.log('ok ' + name); } catch (e) { failed++; console.log('FAIL ' + name + '\n' + e.stack); }
|
||||
}
|
||||
process.exit(failed ? 1 : 0);
|
||||
@@ -6,6 +6,7 @@ main._ConsoleUnlessApi it swallowed every method mismatch: `GET /api/v1/auth/log
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from dredd_core.routes import iter_routes
|
||||
from fastapi.routing import APIRoute
|
||||
from fastapi.testclient import TestClient
|
||||
from starlette.routing import Match
|
||||
@@ -18,8 +19,8 @@ _ALL = {"GET", "HEAD", "POST", "PUT", "PATCH", "DELETE"}
|
||||
|
||||
def _bound() -> dict[str, set[str]]:
|
||||
out: dict[str, set[str]] = {}
|
||||
for r in app.routes:
|
||||
if isinstance(r, APIRoute) and "{" not in r.path:
|
||||
for orig, r in iter_routes(app.routes):
|
||||
if isinstance(orig, APIRoute) and "{" not in r.path:
|
||||
out.setdefault(r.path, set()).update(r.methods)
|
||||
return out
|
||||
|
||||
@@ -27,7 +28,8 @@ def _bound() -> dict[str, set[str]]:
|
||||
def _claimed(method: str, path: str) -> bool:
|
||||
"""True when some route (a parameterised one, e.g. `/{id}` catching `/policy`) takes it."""
|
||||
scope = {"type": "http", "method": method, "path": path, "root_path": ""}
|
||||
return any(isinstance(r, APIRoute) and r.matches(scope)[0] is Match.FULL for r in app.routes)
|
||||
return any(isinstance(orig, APIRoute) and r.matches(scope)[0] is Match.FULL
|
||||
for orig, r in iter_routes(app.routes))
|
||||
|
||||
|
||||
def _is_problem(r, status):
|
||||
|
||||
@@ -64,13 +64,17 @@ class TestTheScreenExistsAtAll:
|
||||
assert "'#/tokens'" in console
|
||||
|
||||
def test_it_is_everybodys_screen_not_an_administrators(self, console):
|
||||
"""A credential belongs to the person holding it. Putting the entry in ADMIN_NAV would hide
|
||||
it from every user who is not an administrator — which is most of the people who hold a
|
||||
desktop client — and `GET /me/tokens` is guarded by `get_current_user`, not by the tier."""
|
||||
nav = _block(console, "const NAV = [", "];")
|
||||
"""A credential belongs to the person holding it. Putting the entry in ADMIN_NAV, or marking
|
||||
it `admin: true` under Ustawienia, would hide it from every user who is not an administrator —
|
||||
which is most of the people who hold a desktop client — and `GET /me/tokens` is guarded by
|
||||
`get_current_user`, not by the tier."""
|
||||
settings = _block(console, "const SETTINGS_NAV = [", "];")
|
||||
admin_nav = _block(console, "const ADMIN_NAV = [", "];")
|
||||
assert "'#/tokens'" in nav
|
||||
line = next(ln for ln in settings.splitlines() if "'#/tokens'" in ln)
|
||||
assert "admin: true" not in line
|
||||
assert "tokens" not in admin_nav
|
||||
section = next(ln for ln in _block(console, "const SECTIONS = [", "];").splitlines() if "key: 'settings'" in ln)
|
||||
assert "admin: true" not in section, "Ustawienia itself must be everybody's"
|
||||
|
||||
def test_the_routes_it_calls_are_the_ones_that_exist(self, console, users_router):
|
||||
"""The console invents no endpoint: each path it posts to or deletes is declared in the
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
"""DB-free tests of the Archive's technical account (Atrium#53, step 4)."""
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app.config import get_settings
|
||||
from app.services import accounts, archive_reader, audit, moderation
|
||||
|
||||
|
||||
class _Db:
|
||||
def __init__(self, user=None):
|
||||
self.user, self.added = user, []
|
||||
|
||||
def get(self, model, key):
|
||||
return self.user
|
||||
|
||||
def add(self, row):
|
||||
self.added.append(row)
|
||||
|
||||
def flush(self):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def platform(monkeypatch):
|
||||
grants, audited = [], []
|
||||
monkeypatch.setattr(type(get_settings()), "shares_identity", property(lambda s: True))
|
||||
monkeypatch.setattr(moderation, "module_roles", lambda db, uid: {"parafa": "user"})
|
||||
monkeypatch.setattr(moderation, "grant",
|
||||
lambda db, actor, **kw: grants.append(kw) or {})
|
||||
monkeypatch.setattr(audit, "record", lambda db, **kw: audited.append(kw))
|
||||
return grants, audited
|
||||
|
||||
|
||||
def test_creates_a_passwordless_account_under_the_fixed_id(platform):
|
||||
grants, audited = platform
|
||||
db = _Db()
|
||||
user = archive_reader.ensure(db)
|
||||
assert db.added == [user]
|
||||
assert user.id == get_settings().archive_reader_id and user.password_hash is None
|
||||
assert not user.is_admin
|
||||
assert audited[0]["action"] == "archive_reader.created"
|
||||
# Only the modules it does not hold yet, and only as `user`.
|
||||
assert sorted(g["module_slug"] for g in grants) == ["agora", "arbiter", "workflow"]
|
||||
assert {g["role"] for g in grants} == {moderation.USER}
|
||||
|
||||
|
||||
def test_idempotent_when_it_exists(platform, monkeypatch):
|
||||
grants, audited = platform
|
||||
monkeypatch.setattr(moderation, "module_roles",
|
||||
lambda db, uid: dict.fromkeys(archive_reader.MODULES, "user"))
|
||||
db = _Db(SimpleNamespace(id=get_settings().archive_reader_id, is_active=True))
|
||||
archive_reader.ensure(db)
|
||||
assert db.added == [] and grants == [] and audited == []
|
||||
|
||||
|
||||
def test_a_deactivated_account_gets_no_grants_back(platform):
|
||||
grants, _ = platform
|
||||
archive_reader.ensure(_Db(SimpleNamespace(id=get_settings().archive_reader_id,
|
||||
is_active=False)))
|
||||
assert grants == []
|
||||
|
||||
|
||||
def test_mint_is_read_only(platform, monkeypatch):
|
||||
seen = {}
|
||||
|
||||
def create(db, user, **kw):
|
||||
seen.update(kw)
|
||||
return SimpleNamespace(id="s", token_prefix="galena_pat_ab"), "galena_pat_secret"
|
||||
|
||||
monkeypatch.setattr(accounts, "create_module_token", create)
|
||||
user = SimpleNamespace(id=get_settings().archive_reader_id, is_active=True)
|
||||
monkeypatch.setattr(moderation, "module_roles",
|
||||
lambda db, uid: dict.fromkeys(archive_reader.MODULES, "user"))
|
||||
_row, raw = archive_reader.mint(_Db(user))
|
||||
assert raw == "galena_pat_secret"
|
||||
assert seen["scope"] == "read" and seen["module_slug"] == "galena"
|
||||
assert seen["idle_days"] == get_settings().app_token_max_idle_days
|
||||
|
||||
|
||||
def test_the_reconciliation_leaves_it_out():
|
||||
"""`_active_ids` excludes it, so `everyone` never admits it and no sweep revokes its grants."""
|
||||
import inspect
|
||||
|
||||
from app.services import marketplace
|
||||
assert "archive_reader_id" in inspect.getsource(marketplace._active_ids)
|
||||
@@ -35,10 +35,10 @@ ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
BACKEND = ROOT / "backend"
|
||||
DEPLOY = ROOT / "deploy"
|
||||
#: Where a module's application sits inside its checkout — push.sh's SUBDIR and
|
||||
#: preflight.sh's. Compass's repository is the analysis engine's and carries the app in a
|
||||
#: subdirectory; every other module's repository IS the app. Without this the Compass case below
|
||||
#: looked for `deploy/modules/compass/backend`, never found it, and skipped on every machine.
|
||||
SUBDIR = {"compass": "apps/compass"}
|
||||
#: preflight.sh's. Arbiter's repository also carries the analysis engine and holds the app in a
|
||||
#: subdirectory; every other module's repository IS the app. Without this the Arbiter case below
|
||||
#: would look for `deploy/modules/arbiter/backend`, never find it, and skip on every machine.
|
||||
SUBDIR = {"arbiter": "apps/arbiter"}
|
||||
|
||||
def _hub_slug() -> str:
|
||||
"""Atrium's own slug, read from the field's default rather than written out again here — the
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
"""What a named contract says: `chatClauses` reads the contract's text from
|
||||
Galena and picks the paragraphs that share the question's words. Run under Node with the module
|
||||
calls stubbed; skipped where no `node`."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
NODE = shutil.which("node")
|
||||
SRC = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _between(start: str, end: str) -> str:
|
||||
i = SRC.index(start)
|
||||
return SRC[i:SRC.index(end, i)]
|
||||
|
||||
|
||||
BLOCK = "\n".join([
|
||||
_between("const chatStems = ", "\n") + "\n",
|
||||
_between("const reviewFiles = ", "const reviewWords"),
|
||||
_between("const CHAT_CLAUSE = ", "/* The panel beside the chat"),
|
||||
])
|
||||
C = {"id": "c1", "project_id": "p1", "number": "UM-2026-0017", "name": "Najem biura"}
|
||||
PARAS = ["§ 1. Przedmiotem umowy jest najem lokalu.",
|
||||
"§ 2. Czynsz płatny do 10. dnia miesiąca.",
|
||||
"§ 5. Za zwłokę najemca zapłaci karę umowną 0,5% czynszu dziennie.",
|
||||
"§ 6. Umowę można wypowiedzieć z trzymiesięcznym okresem wypowiedzenia."]
|
||||
|
||||
|
||||
def _run(question: str, files=("umowa.docx",), named=True) -> list:
|
||||
case = {"question": question, "named": [{"contract": C}] if named else [],
|
||||
"tree": {"entries": [{"type": "file", "path": f} for f in files]}, "paras": PARAS}
|
||||
script = f"""
|
||||
const CASE = {json.dumps(case)};
|
||||
const chat = {{}};
|
||||
const askerGet = async (slug, path) => path.includes('/tree') ? CASE.tree : {{ paragraphs: CASE.paras }};
|
||||
{BLOCK}
|
||||
chatClauses(CASE.question, CASE.named).then((out) => console.log(JSON.stringify(out)))
|
||||
.catch((e) => {{ console.error(e); process.exit(1); }});
|
||||
"""
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60,
|
||||
encoding="utf-8")
|
||||
assert r.returncode == 0, r.stderr
|
||||
return json.loads(r.stdout)
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_a_content_question_gets_the_matching_paragraphs_in_document_order() -> None:
|
||||
out = _run("Jaka kara umowna za zwłokę jest w UM-2026-0017?")
|
||||
assert out and out[0]["key"] == "galena:zapis:c1:2"
|
||||
assert "karę umowną" in out[0]["text"] and "UM-2026-0017" in out[0]["text"]
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
@pytest.mark.parametrize("question, kw", [
|
||||
("Kiedy kończy się UM-2026-0017?", {}), # not about content
|
||||
("Jaka kara umowna w UM-2026-0017?", {"named": False}), # no contract named
|
||||
("Jaka kara umowna w UM-2026-0017?", {"files": ("a.docx", "b.pdf")}), # which file?
|
||||
])
|
||||
def test_otherwise_nothing_is_read(question, kw) -> None:
|
||||
assert _run(question, **kw) == []
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_a_follow_up_reuses_the_text_read_earlier_in_the_conversation() -> None:
|
||||
case = {"named": [{"contract": C}], "paras": PARAS,
|
||||
"tree": {"entries": [{"type": "file", "path": "umowa.docx"}]}}
|
||||
script = f"""
|
||||
const CASE = {json.dumps(case)};
|
||||
const chat = {{}};
|
||||
const reads = [];
|
||||
const askerGet = async (slug, path) => {{ reads.push(path); return path.includes('/tree') ? CASE.tree : {{ paragraphs: CASE.paras }}; }};
|
||||
{BLOCK}
|
||||
(async () => {{
|
||||
const a = await chatClauses('Jaka kara umowna w UM-2026-0017?', CASE.named);
|
||||
const b = await chatClauses('A jak wypowiedzieć UM-2026-0017?', CASE.named);
|
||||
console.log(JSON.stringify({{ reads: reads.length, a: a.length, b: b.length }}));
|
||||
}})().catch((e) => {{ console.error(e); process.exit(1); }});
|
||||
"""
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60,
|
||||
encoding="utf-8")
|
||||
assert r.returncode == 0, r.stderr
|
||||
out = json.loads(r.stdout)
|
||||
assert out["reads"] == 2 and out["a"] and out["b"]
|
||||
@@ -0,0 +1,132 @@
|
||||
"""Home chat's urgent list: the next step it offers per deadline, and the links under each row.
|
||||
|
||||
`chatStep` is lifted out of `frontend/app.js` and run under Node, so the behaviour is asserted, not the
|
||||
source text. DB-free; skipped only where no `node` binary exists.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
NODE = shutil.which("node")
|
||||
SRC = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _line(head: str) -> str:
|
||||
i = SRC.index(head)
|
||||
return SRC[i:SRC.index("\n", i) + 1]
|
||||
|
||||
|
||||
def _fn(head: str) -> str:
|
||||
i = SRC.index(head)
|
||||
return SRC[i:SRC.index("\n}\n", i) + 3]
|
||||
|
||||
|
||||
def _steps(cases: list[dict], en: bool = False) -> list[str]:
|
||||
script = "\n".join([_line("const chatCivil = "), _fn("const CHAT_STEPS_EN = {").split("\nconst CHAT_KINDS_EN")[0],
|
||||
_fn("function chatStep(")])
|
||||
script += f"\nconsole.log(JSON.stringify({json.dumps(cases)}.map((d) => chatStep(d, {json.dumps(en)}))));"
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60, encoding="utf-8")
|
||||
assert r.returncode == 0, r.stderr
|
||||
return json.loads(r.stdout)
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_the_kpc_restore_motion_is_offered_in_civil_procedure_only() -> None:
|
||||
civil_statute, court, uodo = _steps([
|
||||
{"kind": "procedural", "source": "statute", "basis": "Art. 369 § 1 k.p.c.", "days_left": -1, "due_date": "2026-11-05"},
|
||||
{"kind": "procedural", "source": "court", "basis": None, "days_left": -2, "due_date": "2026-11-04"},
|
||||
{"kind": "procedural", "source": "statute", "basis": "Art. 33 ust. 4 RODO", "days_left": -1, "due_date": "2026-11-05"},
|
||||
])
|
||||
assert "168" in civil_statute and "168" in court
|
||||
# A late RODO breach notification to UODO is not civil procedure (Tobiasz, 2026-11-06).
|
||||
assert "168" not in uodo and "KPC" not in uodo and "skutki uchybienia" in uodo
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_a_hearing_is_attended_not_filed() -> None:
|
||||
ahead, past = _steps([{"kind": "hearing", "source": "court", "days_left": 4, "due_date": "2026-11-10"},
|
||||
{"kind": "hearing", "source": "court", "days_left": -1, "due_date": "2026-11-05"}])
|
||||
assert "złożyć" not in ahead and "rozprawy" in ahead and "2026-11-10" in ahead
|
||||
assert "odbyła" in past
|
||||
en_ahead, = _steps([{"kind": "hearing", "source": "court", "days_left": 4, "due_date": "2026-11-10"}], en=True)
|
||||
assert "file" not in en_ahead and "hearing" in en_ahead
|
||||
|
||||
|
||||
def test_each_urgent_row_links_to_its_record_and_the_list_to_sygna() -> None:
|
||||
pick = _fn("function chatPick(")
|
||||
assert "moduleHref(r.slug, r.inner)" in pick and "linkCol: 5" in pick
|
||||
assert "rec: { slug: 'sygna', kind: 'zestawienie', key: 'atrium:pilne'" in pick
|
||||
table = _fn("function chatTableEl(")
|
||||
# A link only to this origin or an in-app hash, and the cell text set as text, never as markup.
|
||||
assert "href.startsWith('#') || sameOrigin(href)" in table and "const a = el('a', null, r[i])" in table
|
||||
assert "innerHTML" not in table
|
||||
|
||||
|
||||
def test_no_two_top_level_functions_share_a_name() -> None:
|
||||
# `node --check` accepts a second `function f()`; the later one silently replaces the first. PR #31's
|
||||
# chatRefusal(problem) replaced chatRefusal(index, question) and every chat question answered "Error".
|
||||
import collections
|
||||
import re
|
||||
|
||||
names = collections.Counter(re.findall(r"^(?:async\s+)?function\s+(\w+)\s*\(", SRC, re.M))
|
||||
assert [n for n, k in names.items() if k > 1] == []
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_quotes_come_from_the_models_words_once_not_from_the_appended_table() -> None:
|
||||
# The urgent list's answer listed 12 "quotes" for 3: every matter name in the table, and repeats.
|
||||
script = "\n".join([_line("const chatEsc = ") if "const chatEsc = " in SRC else _fn("function chatEsc("),
|
||||
_line("const norm = "), _fn("const chatQuoteRe = ").split("\nconst chatQuoteIn")[0],
|
||||
_line("const chatQuoteIn = "), _fn("const chatQuotes = ").split("\n\nconst chatCitedNs")[0]])
|
||||
a = "sprawa „Konstrukta-Bud — zapłata” [1], potem „Remedium — kontrola UODO” [1] i znów „Konstrukta-Bud — zapłata” [1]."
|
||||
t = {"content": a + "\n\n| Lp. | Sprawa |\n| 1 | „Zielona Energia — dzierżawa PV” |", "table": {"rows": [[]]},
|
||||
"refs": [{"n": 1, "text": "Konstrukta-Bud — zapłata; Remedium — kontrola UODO; Zielona Energia — dzierżawa PV"}]}
|
||||
script += f"\nconsole.log(JSON.stringify(chatQuotes({json.dumps(t, ensure_ascii=False)})));"
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60, encoding="utf-8")
|
||||
assert r.returncode == 0, r.stderr
|
||||
assert [x["q"] for x in json.loads(r.stdout)] == ["Konstrukta-Bud — zapłata", "Remedium — kontrola UODO"]
|
||||
|
||||
|
||||
# The smallest DOM chatTableEl needs: elements that keep their children, text and class.
|
||||
_DOM = """
|
||||
const mk = (tag) => ({ tag, children: [], dataset: {}, className: '', textContent: '',
|
||||
appendChild(c) { this.children.push(c); return c; }, append(...c) { this.children.push(...c); } });
|
||||
const document = { createElement: mk };
|
||||
const sameOrigin = () => false;
|
||||
const text = (e) => [e.textContent, ...e.children.map(text)].filter(Boolean).join('/');
|
||||
"""
|
||||
|
||||
|
||||
def _draw(table: dict, view: dict) -> dict:
|
||||
script = _DOM + _fn("function chatTableEl(") + f"""
|
||||
const w = chatTableEl({{ ...{json.dumps(table, ensure_ascii=False)}, view: {json.dumps(view)} }});
|
||||
const [th, tb] = w.children[0].children;
|
||||
const cells = tb.children[0].children;
|
||||
const a = cells.map((c) => c.children[0]).find((x) => x && x.tag === 'a');
|
||||
console.log(JSON.stringify({{ head: th.children[0].children.map((c) => c.textContent), first: cells.map(text), link: a && a.href }}));"""
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60, encoding="utf-8")
|
||||
assert r.returncode == 0, r.stderr
|
||||
return json.loads(r.stdout)
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_the_urgent_table_draws_five_columns_with_kind_and_state_underneath() -> None:
|
||||
view = {"sub": {"1": 2, "3": 4}, "head": {"3": "Termin"}, "dropSame": [6]}
|
||||
head = ["Lp.", "Pozycja", "Rodzaj", "Data", "Stan", "Sprawa / umowa", "Odpowiada", "Następny krok"]
|
||||
rows = [["1", "Odpowiedź na pozew", "procesowy", "2026-11-04", "po terminie od 2 dni", "sprawa 2026/0001", "Ala", "sprawdzić"],
|
||||
["2", "Rozprawa", "rozprawa", "2026-11-10", "za 4 dni", "sprawa 2026/0002", "Ala", "przygotować się"]]
|
||||
t = {"head": head, "rows": rows, "links": ["#/m/sygna/a", "#/m/sygna/b"], "linkCol": 5}
|
||||
compact = _draw(t, view)
|
||||
assert compact["head"] == ["Lp.", "Pozycja", "Termin", "Sprawa / umowa", "Następny krok"]
|
||||
assert compact["first"][1:3] == ["Odpowiedź na pozew/procesowy", "2026-11-04/po terminie od 2 dni"]
|
||||
assert compact["link"] == "#/m/sygna/a"
|
||||
assert _draw(t, {})["head"] == head # no view: drawn as it is
|
||||
# Different owners stay: the column is left out only when it says nothing.
|
||||
rows[1][6] = "Ola"
|
||||
assert "Odpowiada" in _draw(t, view)["head"]
|
||||
@@ -0,0 +1,159 @@
|
||||
"""Contract review from the chat: `chatReview` decides by code what to order in
|
||||
Arbiter, or what to ask back. Lifted out of `frontend/app.js` and run under Node with the modules'
|
||||
APIs stubbed, so the behaviour is asserted, not the source text. DB-free; skipped where no `node`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
NODE = shutil.which("node")
|
||||
SRC = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8")
|
||||
CSS = (ROOT / "frontend" / "app.css").read_text(encoding="utf-8")
|
||||
|
||||
BLOCK = SRC[SRC.index("const CHAT_REVIEW = "):SRC.index("/* The panel beside the chat")]
|
||||
|
||||
C1 = {"id": "c1", "project_id": "p1", "number": "UM-2026-0017", "name": "Najem biura"}
|
||||
C2 = {"id": "c2", "project_id": "p2", "number": "UM-2026-0018", "name": "Dostawa"}
|
||||
SKILL = {"id": "s1", "name": "Umowy najmu", "scope": "firm", "status": "published",
|
||||
"current_version_id": "v3"}
|
||||
|
||||
|
||||
def _run(case: dict) -> dict:
|
||||
"""One `chatReview` call; returns its [text, extra] and every call it made to Arbiter."""
|
||||
stubs = f"""
|
||||
const CASE = {json.dumps(case)};
|
||||
const calls = [];
|
||||
const askerGet = async (slug, path) => (CASE.trees || {{}})[path] ?? null;
|
||||
const api = async (method, path) => path === '/skills' ? CASE.skills : {{ versions: [{{ id: 'v3', n: 3 }}] }};
|
||||
const arbiter = async (method, path, body) => {{
|
||||
calls.push([method, path, body]);
|
||||
if (CASE.refuse) {{ const e = new Error('nope'); e.status = CASE.refuse; throw e; }}
|
||||
return path === 'subjects/document' ? {{ id: 'sub1' }} : {{ id: 'run1' }};
|
||||
}};
|
||||
let opened = null;
|
||||
const reviewOpen = (a) => {{ opened = a; }};
|
||||
"""
|
||||
named = [{"contract": c} for c in case.get("named", [])]
|
||||
prev = {"mentioned": [f"galena:umowa:{c['id']}" for c in case.get("prev", [])]}
|
||||
index = "{ byKey: new Map(" + json.dumps(
|
||||
[[f"galena:umowa:{c['id']}", {"contract": c}] for c in case.get("prev", [])]) + ") }"
|
||||
script = stubs + BLOCK + f"""
|
||||
chatReview({{ question: CASE.question, named: {json.dumps(named)}, prev: {json.dumps(prev)},
|
||||
index: {index}, en: false }})
|
||||
.then((out) => console.log(JSON.stringify({{ out, calls, opened }})))
|
||||
.catch((e) => {{ console.error(e); process.exit(1); }});
|
||||
"""
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60,
|
||||
encoding="utf-8")
|
||||
assert r.returncode == 0, r.stderr
|
||||
return json.loads(r.stdout)
|
||||
|
||||
|
||||
def _case(**kw) -> dict:
|
||||
base = {"question": "Sprawdź umowę UM-2026-0017", "skills": [SKILL], "named": [C1],
|
||||
"trees": {"projects/p1/tree?recursive=true": {"entries": [
|
||||
{"type": "dir", "path": "podpisane"},
|
||||
{"type": "file", "path": "podpisane/skan.pdf"},
|
||||
{"type": "file", "path": ".galena/meta"},
|
||||
{"type": "file", "path": "umowa.docx"}]}}}
|
||||
base.update(kw)
|
||||
return base
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_a_named_contract_is_ordered_by_the_only_skill_and_the_panel_opens() -> None:
|
||||
r = _run(_case())
|
||||
text, extra = r["out"]
|
||||
assert r["calls"] == [
|
||||
["POST", "subjects/document", {"document_id": "p1", "path": "umowa.docx",
|
||||
"title": "UM-2026-0017 Najem biura"}],
|
||||
["POST", "analyses", {"subject_id": "sub1", "mode": "agent", "skill_id": "s1", "skill_n": 3}]]
|
||||
assert extra["analysis"] == {"id": "run1", "number": "UM-2026-0017", "name": "Najem biura",
|
||||
"skill": "Umowy najmu", "n": 3}
|
||||
assert r["opened"] == extra["analysis"]
|
||||
assert "UM-2026-0017" in text and "umowa.docx" in text and "zaakceptować" in text
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_the_contract_of_the_last_answer_is_this_one() -> None:
|
||||
r = _run(_case(question="Sprawdź tę umowę", named=[], prev=[C1]))
|
||||
assert r["out"][1]["analysis"]["number"] == "UM-2026-0017"
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
@pytest.mark.parametrize("kw, words", [
|
||||
({"named": [C1, C2]}, "Którą umowę"),
|
||||
({"named": []}, "Którą umowę"),
|
||||
({"trees": {}}, "nie ma w Galenie pliku"),
|
||||
({"trees": {"projects/p1/tree?recursive=true": [{"type": "file", "path": "a.docx"},
|
||||
{"type": "file", "path": "b.pdf"}]}}, "2 plików"),
|
||||
({"skills": []}, "Nie ma jeszcze opublikowanego skilla"),
|
||||
({"skills": [SKILL, {**SKILL, "id": "s2", "name": "Umowy dostawy"}]}, "Według którego skilla"),
|
||||
])
|
||||
def test_anything_missing_is_asked_back_and_nothing_is_ordered(kw, words) -> None:
|
||||
r = _run(_case(**kw))
|
||||
assert words in r["out"][0]
|
||||
assert r["calls"] == [] and r["opened"] is None
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_the_skill_named_in_the_question_is_the_one() -> None:
|
||||
other = {**SKILL, "id": "s2", "name": "Umowy dostawy"}
|
||||
r = _run(_case(question="Sprawdź umowę UM-2026-0017 skillem dostawy", skills=[SKILL, other]))
|
||||
assert r["calls"][1][2]["skill_id"] == "s2"
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_a_refused_order_is_a_sentence_not_a_throw() -> None:
|
||||
r = _run(_case(refuse=422))
|
||||
text, extra = r["out"]
|
||||
assert text.startswith("Arbiter nie przyjął zlecenia") and extra["failed"] is True
|
||||
assert r["opened"] is None
|
||||
|
||||
|
||||
def test_the_trigger_wants_a_verb_and_a_contract() -> None:
|
||||
pattern = re.search(r"const CHAT_REVIEW = /(.*)/iu;", SRC).group(1)
|
||||
assert "sprawdź" in pattern and "umow" in pattern
|
||||
# The route also wants a register contract (named, or "tę umowę"): a law question stays the law's.
|
||||
assert "named.some((r) => r && r.contract) || chatAnaphora(question).demonstrative" in SRC
|
||||
|
||||
|
||||
def test_the_report_is_framed_with_no_rights_and_the_panel_never_transitions_visibility() -> None:
|
||||
assert 'class="rp-report" sandbox=""' in SRC
|
||||
assert "/acceptance'" in SRC
|
||||
panel = CSS[CSS.index(".review-panel {"):]
|
||||
assert "transition: transform" in panel and "transition: visibility" not in panel
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_no_access_is_arbiters_answer_not_the_catalogues() -> None:
|
||||
"""A service module is missing from `/marketplace` for a non-administrator: the catalogue says
|
||||
nothing about access, so the order is tried and Arbiter's 403 is the refusal."""
|
||||
r = _run(_case(refuse=403))
|
||||
assert "nie masz do niego dostępu" in r["out"][0] and r["opened"] is None
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_only_a_verb_taking_the_contract_as_its_object_is_an_order() -> None:
|
||||
line = SRC[SRC.index("const CHAT_REVIEW = "):SRC.index("\n", SRC.index("const CHAT_REVIEW = "))]
|
||||
asks = ["Sprawdź umowę UM-2026-0017", "przeanalizuj tę umowę", "Check the contract UM-2026-0017",
|
||||
"Sprawdź, kiedy kończy się umowa UM-2026-0017", "Sprawdź czy umowa UM-2026-0017 ma kontrahenta",
|
||||
"Kiedy kończy się umowa UM-2026-0017?"]
|
||||
script = line + f"\nconsole.log(JSON.stringify({json.dumps(asks)}.map((q) => CHAT_REVIEW.test(q))));"
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60, encoding="utf-8")
|
||||
assert r.returncode == 0, r.stderr
|
||||
assert json.loads(r.stdout) == [True, True, True, False, False, False]
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_a_personal_skill_is_never_ordered() -> None:
|
||||
"""A personal skill's current version follows its newest, unapproved one: only firm skills judge."""
|
||||
r = _run(_case(skills=[{**SKILL, "scope": "personal"}]))
|
||||
assert "Nie ma jeszcze opublikowanego skilla" in r["out"][0] and r["calls"] == []
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Scribe and Lexicon lost their consoles (Atrium#53): the chat reads their templates, drafts,
|
||||
sources and library, and creates a draft in Scribe by code. Lifted out of `frontend/app.js` and run
|
||||
under Node with the modules' APIs stubbed. DB-free; skipped where no `node`."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
NODE = shutil.which("node")
|
||||
SRC = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _between(start: str, end: str) -> str:
|
||||
i = SRC.index(start)
|
||||
return SRC[i:SRC.index(end, i)]
|
||||
|
||||
|
||||
BLOCK = "\n".join([
|
||||
_between("const chatStems = ", "\n") + "\n",
|
||||
_between("const reviewWords = ", "\n") + "\n",
|
||||
_between("const CHAT_CLAUSE_TOP = ", "async function chatClauses"),
|
||||
_between("const chatWho = ", "// The calendar week"),
|
||||
_between("/* Scribe and Lexicon have no console", "// What Insider's resolve takes"),
|
||||
])
|
||||
TPL = [{"id": "t1", "name": "Najem lokalu", "description": "Umowa najmu", "field_count": 3, "slot_count": 1},
|
||||
{"id": "t2", "name": "Dostawa towaru", "description": None, "field_count": 2, "slot_count": 0}]
|
||||
DRAFTS = [{"id": "d1", "title": "Najem Kraków", "template_id": "t1", "template_name": "Najem lokalu",
|
||||
"from_scratch": False, "status": "draft", "owner_id": "u1", "created_at": "2026-11-20T10:00:00"}]
|
||||
SOURCES = [{"id": "s1", "title": "Wzór NDA", "kind": "file", "name": "nda.docx", "shared": True,
|
||||
"note": None, "library": {"count": 7}}]
|
||||
|
||||
|
||||
def _run(call: str, case: dict) -> dict:
|
||||
script = f"""
|
||||
const CASE = {json.dumps(case)};
|
||||
const gets = [], posts = [];
|
||||
const askerGet = async (slug, path) => {{ gets.push(slug + ':' + path); return (CASE.gets || {{}})[slug + ':' + path] ?? null; }};
|
||||
const jsonOf = (t) => JSON.parse(t);
|
||||
const httpError = (r, d) => Object.assign(new Error('HTTP ' + r.status), {{ status: r.status, problem: d }});
|
||||
const document = {{ baseURI: 'http://x/atrium/' }};
|
||||
const fetch = async (url, opt) => {{ posts.push([String(url), opt.method, JSON.parse(opt.body)]);
|
||||
const st = CASE.refuse || 201; return {{ ok: st < 300, status: st, text: async () => JSON.stringify({{ id: 'd9', title: JSON.parse(opt.body).title, detail: 'nie' }}) }}; }};
|
||||
{BLOCK}
|
||||
({call}).then((out) => console.log(JSON.stringify({{ out, gets, posts }})))
|
||||
.catch((e) => {{ console.error(e); process.exit(1); }});
|
||||
"""
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60,
|
||||
encoding="utf-8")
|
||||
assert r.returncode == 0, r.stderr
|
||||
return json.loads(r.stdout)
|
||||
|
||||
|
||||
GETS = {"scribe:templates": TPL, "scribe:drafts": DRAFTS, "lexicon:sources?status=active": SOURCES,
|
||||
"lexicon:library/shelves": [{"type": "poufnosc", "label": "Poufność", "count": 4},
|
||||
{"type": None, "label": None, "count": 0}]}
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_scribe_templates_and_drafts_become_records() -> None:
|
||||
out = _run("chatScribe({ u1: 'Anna Nowak' })", {"gets": GETS})["out"]
|
||||
keys = [r["key"] for r in out]
|
||||
assert keys == ["scribe:szablon:t1", "scribe:szablon:t2", "scribe:szkic:d1"]
|
||||
assert "Najem lokalu" in out[2]["text"] and "Anna Nowak" in out[2]["text"]
|
||||
assert out[2]["members"] == ["scribe:szablon:t1"]
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
@pytest.mark.parametrize("call", ["chatScribe({})", "chatLexicon()"])
|
||||
def test_no_access_is_null(call) -> None:
|
||||
assert _run(call, {"gets": {}})["out"] is None
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_lexicon_sources_and_shelves() -> None:
|
||||
out = _run("chatLexicon()", {"gets": GETS})["out"]
|
||||
assert out[0]["key"] == "lexicon:zrodlo:s1" and "7" in out[0]["text"]
|
||||
assert out[1]["key"] == "lexicon:polki" and "Poufność 4" in out[1]["text"]
|
||||
assert "bez typu" not in out[1]["text"]
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_library_clauses_are_searched_only_for_a_library_question() -> None:
|
||||
path = "lexicon:library/clauses?q=poufn"
|
||||
hit = [{"source_id": "s1", "source_title": "Wzór NDA", "position": 2, "label": "§ 3",
|
||||
"numbering": "§ 3", "text": "Strony zachowają poufność.", "types": ["poufnosc"]}]
|
||||
got = _run("chatLibrary('Jaką klauzulę poufności mamy w bibliotece?')", {"gets": {path: hit}})
|
||||
assert got["gets"] == [path]
|
||||
assert got["out"][0]["key"] == "lexicon:klauzula:s1:2" and "poufność" in got["out"][0]["text"]
|
||||
assert _run("chatLibrary('Jaka kara umowna w UM-1?')", {"gets": {}})["out"] == []
|
||||
|
||||
|
||||
def _index() -> str:
|
||||
return "{ records: " + json.dumps([{"kind": "szablon", "key": "scribe:szablon:" + t["id"],
|
||||
"template": t} for t in TPL]) + " }"
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_a_draft_is_created_from_the_one_named_template() -> None:
|
||||
got = _run(f"chatDraft({{ question: 'Utwórz projekt pisma z szablonu najem „Najem Gdańsk”', index: {_index()}, en: false }})", {})
|
||||
assert got["posts"] == [["http://x/scribe/api/v1/drafts", "POST", {"template_id": "t1", "title": "Najem Gdańsk"}]]
|
||||
assert got["out"][1]["mentioned"] == ["scribe:szkic:d9"]
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_from_scratch_and_unclear_template() -> None:
|
||||
got = _run(f"chatDraft({{ question: 'Załóż szkic od zera', index: {_index()}, en: false }})", {})
|
||||
assert got["posts"][0][2] == {"template_id": None, "title": ""}
|
||||
asked = _run(f"chatDraft({{ question: 'Utwórz szkic', index: {_index()}, en: false }})", {})
|
||||
assert asked["posts"] == [] and asked["out"][1]["coded"] == "ask"
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_a_refusal_is_a_sentence() -> None:
|
||||
got = _run(f"chatDraft({{ question: 'Załóż szkic od zera', index: {_index()}, en: false }})", {"refuse": 404})
|
||||
assert "nie masz do niego dostępu" in got["out"][0]
|
||||
@@ -0,0 +1,359 @@
|
||||
"""Home chat's traps for small models (P1-P9, audit 2026-11-13): what code decides before the model reads.
|
||||
|
||||
The whole chat block of `frontend/app.js` (from "Code finds, the model reads" to "A module's screen") is
|
||||
built under Node, as `lw-platform/testy/czat-graf/test-graf.mjs` does, over a small in-memory world of
|
||||
the four modules and a stub of the model that answers with fixed text. So the behaviour is asserted, not
|
||||
the source text. DB-free and network-free; skipped only where no `node` binary exists.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
NODE = shutil.which("node")
|
||||
APP = ROOT / "frontend" / "app.js"
|
||||
|
||||
pytestmark = pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
|
||||
# The world, as the modules' APIs answer it, on a frozen day (Thursday 2026-11-12; its week is 9-15 Nov).
|
||||
_PRELUDE = r"""
|
||||
const fs = require('fs');
|
||||
const src = fs.readFileSync(APP, 'utf8');
|
||||
const block = src.slice(src.indexOf('// Code finds, the model reads'), src.indexOf("// A module's screen"));
|
||||
const TODAY = '2026-11-12';
|
||||
const NOW = Date.parse(TODAY + 'T12:00:00Z');
|
||||
class FixedDate extends Date { constructor(...a) { super(...(a.length ? a : [NOW])); } static now() { return NOW; } }
|
||||
const NAMES = ['chatIndex', 'chatTurn', 'chatPick', 'chatStep', 'chatVerify', 'chatRound', 'chatCarry'];
|
||||
const load = new Function('fetch', 'document', 'state', 'chat', '_tr', 'moduleHref', 'coreRefusal', 'Date',
|
||||
block + `\nreturn { ${NAMES.map((n) => `...(typeof ${n} === 'undefined' ? {} : { ${n} })`).join(', ')} };`);
|
||||
const dl = (id, title, kind, due, days, extra = {}) => ({ id, title, kind, due_date: due, days_left: days, completed_at: null,
|
||||
matter_id: 'm1', matter_reference: '2026/0001', matter_name: 'Spór z Alfą', basis: null, owner_id: 'u1', source: 'internal', ...extra });
|
||||
const con = (id, number, name, counterparty, status, value, ends, created) => ({ id, project_id: 'p-' + id, number, name, counterparty, status,
|
||||
value_amount: value, value_currency: value ? 'PLN' : null, concluded_on: status === 'szkic' ? null : '2026-01-02', ends_on: ends, created_at: created });
|
||||
const WORLD = {
|
||||
'sygna/users': [{ id: 'u1', full_name: 'Anna Nowak' }],
|
||||
'sygna/matters': [
|
||||
{ id: 'm1', reference: '2026/0001', name: 'Spór z Alfą', client_name: 'Alfa sp. z o.o.', practice_area: null, status: 'open',
|
||||
responsible_lawyer_id: 'u1', opened_at: '2026-01-10', closed_at: null, description: '', client_party_id: 'p1' },
|
||||
{ id: 'm2', reference: '2026/0002', name: 'Opinia dla Bety', client_name: 'Beta S.A.', practice_area: 'cywilne', status: 'closed',
|
||||
responsible_lawyer_id: 'u1', opened_at: '2026-02-01', closed_at: '2026-11-10', description: '', client_party_id: null }],
|
||||
'sygna/deadlines?days=365': [
|
||||
dl('d1', 'Zebranie dokumentów od klienta', 'internal', '2026-11-07', -5),
|
||||
dl('d2', 'Zgłoszenie naruszenia do UODO', 'procedural', '2026-11-11', -1, { source: 'statute', basis: 'Art. 33 ust. 4 RODO' }),
|
||||
dl('d3', 'Przekazanie projektu umowy', 'contractual', '2026-11-10', -2),
|
||||
dl('d4', 'Odpowiedź na pozew', 'procedural', '2026-11-14', 2, { source: 'court' }),
|
||||
dl('d5', 'Notatka dla zarządu', 'internal', '2026-11-16', 4),
|
||||
dl('d6', 'Telefon do klienta', 'internal', '2026-11-12', 0),
|
||||
dl('d7', 'Apelacja', 'procedural', '2026-12-02', 20, { source: 'court' })],
|
||||
'sygna/parties': [{ id: 'p1', name: 'Alfa sp. z o.o.', nip: null, address: null }],
|
||||
'galena/cards?limit=200&offset=0': [
|
||||
con('c1', 'UM-2026-0001', 'Najem biura', 'Alfa sp. z o.o.', 'obowiazuje', 120000, '2026-12-27', '2026-11-11T09:00:00Z'),
|
||||
con('c2', 'UM-2026-0002', 'Dostawa pomp', 'Kalinowy Dwór sp. z o.o.', 'obowiazuje', 80000.5, '2027-03-01', '2026-11-10T09:00:00Z'),
|
||||
con('c3', 'UM-2026-0003', 'Serwis IT', 'Beta S.A.', 'obowiazuje', null, '2027-06-30', '2026-01-05T09:00:00Z'),
|
||||
con('c4', 'UM-2026-0004', 'Umowa ramowa', null, 'szkic', null, null, '2026-01-06T09:00:00Z'),
|
||||
con('c5', 'UM-2026-0005', 'Licencja', 'Gamma sp. z o.o.', 'szkic', null, null, '2026-01-07T09:00:00Z'),
|
||||
con('c6', 'UM-2026-0006', 'Ochrona obiektu', 'Delta sp. z o.o.', 'obowiazuje', 5000, '2026-11-17', '2026-01-08T09:00:00Z')],
|
||||
'counsel/firms': [1, 2, 3].map((i) => ({ id: 'f' + i, name: ['Lis i Wspólnicy', 'Kowal Legal', 'Nowicki Kancelaria'][i - 1],
|
||||
legal_name: 'Kancelaria ' + i, status: i === 3 ? 'inactive' : 'active', contact_person: null, notes: '' })),
|
||||
'counsel/matters': [{ id: 'o1', firm_id: 'f1', reference: 'ZK/2026/001', title: 'Opinia podatkowa', status: 'in_progress',
|
||||
budget_estimate: 10000, budget_currency: 'PLN', created_at: '2026-11-12T08:00:00Z' }],
|
||||
'counsel/review-cycles': [{ id: 'cy1', name: 'Q3 2026', status: 'closed' }],
|
||||
'counsel/review-cycles/cy1/snapshots': [{ firm_id: 'f1', composite_score: 91.5, evaluation_count: 4 },
|
||||
{ firm_id: 'f2', composite_score: 77, evaluation_count: 3 }, { firm_id: 'f3', composite_score: 52.25, evaluation_count: 2 }],
|
||||
'galena/drive/home': { workspaces: [] },
|
||||
'galena/drive/shared': [],
|
||||
};
|
||||
// One chat session: the block over the world, a model stub answering `replies` in turn (a function gets the request).
|
||||
function session(replies = [], { chat = {}, failOnce = false, breakMid = false } = {}) {
|
||||
const asked = [];
|
||||
let i = 0;
|
||||
let broke = false;
|
||||
const fetch = async (url, o = {}) => {
|
||||
const u = new URL(String(url));
|
||||
if (u.pathname === '/atrium/api/v1/models/ask') {
|
||||
if (failOnce && !broke) { broke = true; throw new TypeError('terminated'); }
|
||||
// A break after the first words: the stream gives one chunk, then the connection dies.
|
||||
if (breakMid && !broke) {
|
||||
broke = true; asked.push(JSON.parse(o.body));
|
||||
const enc = new TextEncoder();
|
||||
return new Response(new ReadableStream({ start(c) {
|
||||
c.enqueue(enc.encode('data: ' + JSON.stringify({ choices: [{ delta: { content: 'Najpierw ' } }] }) + '\n\n'));
|
||||
setTimeout(() => c.error(new TypeError('terminated')), 0); } }), { status: 200, headers: { 'Content-Type': 'text/event-stream' } });
|
||||
}
|
||||
const body = JSON.parse(o.body);
|
||||
asked.push(body);
|
||||
const r = replies[Math.min(i++, replies.length - 1)];
|
||||
const content = typeof r === 'function' ? r(body) : r;
|
||||
return new Response('data: ' + JSON.stringify({ choices: [{ delta: { content } }] }) + '\n\ndata: [DONE]\n\n',
|
||||
{ status: 200, headers: { 'Content-Type': 'text/event-stream' } });
|
||||
}
|
||||
const m = /^\/([^/]+)\/api\/v1\/(.*)$/.exec(u.pathname);
|
||||
const body = m && WORLD[m[1] + '/' + m[2] + u.search];
|
||||
return body === undefined ? new Response('{}', { status: 404 }) : new Response(JSON.stringify(body), { status: 200 });
|
||||
};
|
||||
const f = load(fetch, { baseURI: 'http://t.local/atrium/' }, { user: { id: 'u1' }, launcher: [] }, { ctl: new AbortController(), ...chat },
|
||||
(s) => s, (slug, inner) => slug + '/#/' + inner, (p) => p.detail, FixedDate);
|
||||
const turns = [];
|
||||
let index = null;
|
||||
return { f, asked, turns, async ask(question, args = {}) {
|
||||
index = index || await f.chatIndex();
|
||||
const answer = await f.chatTurn({ model: 'm', question, turns: [...turns], index, graf: false, ja: false, prawo: false, ...args });
|
||||
turns.push({ role: 'user', content: question }, answer);
|
||||
return answer;
|
||||
}, index: async () => (index = index || await f.chatIndex()) };
|
||||
}
|
||||
const lastUser = (body) => body.messages.filter((m) => m.role === 'user').at(-1).content;
|
||||
// The [n] this turn gave the source whose text contains `needle`.
|
||||
const nOf = (body, needle) => { const l = lastUser(body).split('\n').find((x) => x.includes(needle)); return l ? Number(l.match(/^\[(\d+)\]/)[1]) : 0; };
|
||||
"""
|
||||
|
||||
|
||||
def _run(js: str) -> object:
|
||||
script = f"const APP = {json.dumps(str(APP))};\n" + _PRELUDE + \
|
||||
f"\n(async () => {{ const out = await (async () => {{ {js} }})(); console.log(JSON.stringify(out)); }})()" \
|
||||
".catch((e) => { console.error(e && e.stack || e); process.exit(1); });"
|
||||
r = subprocess.run([NODE, "-"], input=script, capture_output=True, text=True, timeout=120, encoding="utf-8")
|
||||
assert r.returncode == 0, r.stderr
|
||||
return json.loads(r.stdout)
|
||||
|
||||
|
||||
def test_p1_activity_and_totals_are_counted_by_code() -> None:
|
||||
# Qwen read "Zestawienie obejmuje … zamknięcie sprawy, wykonanie terminu" as things that happened, and the
|
||||
# register split "obowiązuje" over two lines, so Bielik said 5 where there were 7 (test 9.11).
|
||||
got = _run("""const s = session(); const ix = await s.index();
|
||||
const t = (k) => ix.byKey.get(k).text;
|
||||
return { act: t('atrium:aktywnosc'), reg: t('galena:zestawienie'), rank: t('counsel:ranking:cy1') };""")
|
||||
assert "Zestawienie obejmuje" not in got["act"] and "W ostatnich dniu" not in got["act"]
|
||||
assert "W ostatnich 3 dniach: 4 zmiany: 2 umowy dodane do rejestru, 1 sprawa zamknięta, 1 zlecenie" in got["act"]
|
||||
assert "Status obowiązuje: 4 umowy" in got["reg"]
|
||||
assert "205 000,50 PLN" in got["reg"]
|
||||
assert "Nowicki Kancelaria (ostatnie, 3. miejsce z 3)" in got["rank"]
|
||||
|
||||
|
||||
def test_p2_overdue_items_head_the_urgent_list_also_this_week() -> None:
|
||||
# "Na ten tydzień" dropped the overdue items from the table and named them in one closing sentence ("Poza
|
||||
# tym 4 pozycje są już po terminie"), which 15 of 16 answers then lost (user-ii-thread, 9.11).
|
||||
got = _run("""const s = session(['Najpierw Zebranie dokumentów od klienta [1].']); const ix = await s.index();
|
||||
const p = s.f.chatPick('jakie są najpilniejsze zadania na ten tydzień?', ix);
|
||||
await s.ask('jakie są najpilniejsze zadania na ten tydzień?');
|
||||
return { rows: p.table.rows, text: p.rec.text, hint: lastUser(s.asked[0]) };""")
|
||||
states = [r[4] for r in got["rows"]]
|
||||
assert [s.startswith("po terminie") for s in states] == [True, True, True, False, False, False, False]
|
||||
assert [r[3] for r in got["rows"]][:3] == ["2026-11-07", "2026-11-10", "2026-11-11"] # oldest first
|
||||
assert "Poza tym" not in got["text"]
|
||||
assert "krótko" in got["hint"] and "1-4 zdania" not in got["hint"]
|
||||
|
||||
|
||||
def test_p3_only_the_window_asked_about_goes_to_the_model() -> None:
|
||||
# Given the 30-, 60- and 90-day windows at once for "w ciągu 60 dni", both models answered from the wrong
|
||||
# one (q-60-dni, 14 of 16, 9.11).
|
||||
got = _run("""const s = session(['W ciągu 60 dni kończą się 2 umowy [1].']);
|
||||
const a = await s.ask('Które umowy wygasają w ciągu najbliższych 60 dni?');
|
||||
return a.refs.map((r) => r.key);""")
|
||||
assert "galena:wygasajace:60" in got
|
||||
assert "galena:wygasajace:30" not in got and "galena:wygasajace:90" not in got
|
||||
|
||||
|
||||
def test_p4_the_earliest_end_is_asked_for_only_when_there_are_end_dates() -> None:
|
||||
# Told "która kończy się najwcześniej" of two drafts with no end date, 10 of 16 answers made one up (q-szkic).
|
||||
got = _run("""const s = session(['W statusie szkic są 2 umowy [1].', 'Umowy obowiązujące [1].']);
|
||||
await s.ask('Ile umów jest w statusie szkic i jakie to umowy?');
|
||||
await s.ask('Ile umów jest w statusie obowiązuje i jakie to umowy?');
|
||||
return s.asked.map((b) => lastUser(b).split('Pytanie: ')[1]);""")
|
||||
drafts, in_force = got
|
||||
assert "najwcześniej" not in drafts and "żadna z nich nie ma wpisanej daty końca" in drafts
|
||||
assert "najwcześniej kończy się UM-2026-0006 (2026-11-17)" in in_force
|
||||
|
||||
|
||||
def test_p5_records_say_statuses_and_empty_fields_in_words() -> None:
|
||||
# "kontrahent brak" was read as a firm called Brak (Qwen, 5 of 6), "zawarta brak daty" as concluded, and
|
||||
# answers copied "obowiazuje", "open", "closed" (9.11).
|
||||
got = _run("""const s = session(); const ix = await s.index();
|
||||
const t = (k) => ix.byKey.get(k).text;
|
||||
return { draft: t('galena:umowa:c4'), matter: t('sygna:sprawa:m2'), firm: t('counsel:kancelaria:f3'),
|
||||
cycle: t('counsel:ranking:cy1'), party: t('sygna:strona:p1') };""")
|
||||
assert not any(x in got["draft"] for x in ("brak", "status szkic,", "obowiazuje"))
|
||||
assert "kontrahent nie wpisany" in got["draft"] and "szkic (umowa niezawarta)" in got["draft"]
|
||||
assert "data zawarcia nie wpisana" in got["draft"] and "wartość nie wpisana" in got["draft"]
|
||||
assert "status closed" not in got["matter"] and "status zamknięta" in got["matter"] and "dziedzina cywilne" in got["matter"]
|
||||
assert "inactive" not in got["firm"] and "nieaktywna" in got["firm"] and "osoba kontaktowa nie wpisana" in got["firm"]
|
||||
assert "(closed)" not in got["cycle"]
|
||||
assert "NIP nie wpisany" in got["party"]
|
||||
|
||||
|
||||
def test_p6_the_check_and_the_refusals_follow_the_data_not_the_words() -> None:
|
||||
got = _run("""const s = session([
|
||||
'Przepraszam, ale nie piszę wierszy.',
|
||||
(b) => `Łączna wartość umów w PLN to 999 999,00 PLN [${nOf(b, 'Rejestr umów')}].`, 'Przepraszam, nie mogę w tym pomóc.']);
|
||||
const ix = await s.index(); const f = s.f;
|
||||
const src = (text) => [{ slug: 'x', kind: 'x', key: 'x:1', text }];
|
||||
const bad = (v) => v.issues.filter((x) => x.level === 'bad').map((x) => x.raw);
|
||||
const run = async (q) => { try { const a = await s.ask(q); return { coded: a.coded || null, content: a.content }; } catch (e) { return { err: String(e) }; } };
|
||||
return {
|
||||
// 6.3 straight quotes in an English answer are not a quotation
|
||||
straight: bad(f.chatVerify('The "pomp" contract and the "lease" one are both in force [1].', src('Umowa UM-2026-0002 „Dostawa pomp”, status obowiązuje.'))),
|
||||
// 6.4 "§ 1 pkt 1" stands in the statute as "§ 1." and "1)"
|
||||
point: bad(f.chatVerify('Zgodnie z art. 53 § 1 pkt 1 pracodawca może rozwiązać umowę [1].',
|
||||
src('Art. 53. § 1. Pracodawca może rozwiązać umowę o pracę bez wypowiedzenia: 1) jeżeli niezdolność pracownika do pracy wskutek choroby trwa dłużej niż 3 miesiące; 2) w razie usprawiedliwionej nieobecności.'))),
|
||||
// 6.5 today's date frames the answer
|
||||
today: bad(f.chatVerify('Na dziś, 12 listopada 2026 (2026-11-12), najpilniejsza jest Apelacja [1].', src('Apelacja, termin 2026-12-02.'))),
|
||||
// 6.6 the calendar week is in the sources
|
||||
week: f.chatPick('co mam pilnego w tym tygodniu?', ix).rec.text, terminy: ix.byKey.get('sygna:terminy').text,
|
||||
// 6.1 a refusal in other words, naming no data
|
||||
poem: await run('Napisz krótki wiersz o pracy w kancelarii.'),
|
||||
// 6.2 refused after a wrong cited answer: what code assembled
|
||||
total: await run('Jaka jest łączna wartość umów w PLN?'),
|
||||
};""")
|
||||
assert got["straight"] == [] and got["point"] == [] and got["today"] == []
|
||||
assert "tydzień kalendarzowy od 2026-11-09 do 2026-11-15" in got["week"]
|
||||
assert "tydzień kalendarzowy od 2026-11-09 do 2026-11-15" in got["terminy"]
|
||||
assert got["poem"].get("coded") == "refusal", got["poem"]
|
||||
assert got["total"].get("coded") == "fallback" and "205 000,50 PLN" in got["total"]["content"], got["total"]
|
||||
|
||||
|
||||
def test_p7_a_second_of_one_is_asked_and_a_bare_citation_is_no_reference() -> None:
|
||||
# After a one-item list "a ta druga?" was searched as a new question and answered about another record
|
||||
# (q-ta-druga, 9.11); and "nie znalazłem odpowiedzi [1]" made [1] what the next "ta umowa" meant.
|
||||
got = _run("""const s = session([(b) => `W ciągu 30 dni kończy się jedna umowa: UM-2026-0006 Ochrona obiektu [${nOf(b, 'okno 30 dni')}].`]);
|
||||
await s.ask('Które umowy wygasają w ciągu 30 dni?');
|
||||
const second = await s.ask('a ta druga?');
|
||||
const t = session(['W danych, do których masz dostęp, nie znalazłem odpowiedzi [1].']);
|
||||
const bare = await t.ask('Jaki jest NIP firmy Kalinowy Dwór?');
|
||||
return { calls: s.asked.length, coded: second.coded, content: second.content, mentioned: bare.mentioned };""")
|
||||
assert got["calls"] == 1 and got["coded"] == "ask"
|
||||
assert "tylko jedna" in got["content"] and "UM-2026-0006" in got["content"]
|
||||
assert got["mentioned"] == []
|
||||
|
||||
|
||||
def test_p7_an_english_follow_up_is_asked_back_in_english() -> None:
|
||||
# The questions back are said by code; asked in English they were Polish (i18n pass, 20.11).
|
||||
got = _run("""const s = session([(b) => `W ciągu 30 dni kończy się jedna umowa: UM-2026-0006 Ochrona obiektu [${nOf(b, 'okno 30 dni')}].`]);
|
||||
await s.ask('Które umowy wygasają w ciągu 30 dni?');
|
||||
const a = await s.ask('the second contract?');
|
||||
return { coded: a.coded, content: a.content };""")
|
||||
assert got["coded"] == "ask", got
|
||||
assert got["content"].startswith("The previous answer had only one item") and "UM-2026-0006" in got["content"], got
|
||||
|
||||
|
||||
def test_p8_a_broken_stream_is_retried_and_the_code_table_is_marked() -> None:
|
||||
# A connection cut before the first word ended the turn as a failure (2 turns, 9.11); "przed 2026-11-12" on
|
||||
# that very day read as too late; the harness could not tell a turn with code's table from a plain one.
|
||||
got = _run("""const s = session(['Najpierw Telefon do klienta [1].'], { failOnce: true });
|
||||
const a = await s.ask('co jest najpilniejsze?');
|
||||
return { failed: !!a.failed, content: a.content, from: a.tableFrom || null, coded: a.coded || null,
|
||||
today: s.f.chatStep({ kind: 'internal', days_left: 0, due_date: '2026-11-12' }, false),
|
||||
later: s.f.chatStep({ kind: 'procedural', source: 'court', days_left: 2, due_date: '2026-11-14' }, false) };""")
|
||||
assert not got["failed"] and got["content"].startswith("Najpierw")
|
||||
assert got["from"] == "pick" and got["coded"] is None
|
||||
assert got["today"] == "wykonać dziś" and got["later"] == "przygotować i złożyć do 2026-11-14"
|
||||
|
||||
|
||||
def test_p9_a_name_no_visible_record_carries_is_said_by_code_behind_the_switch() -> None:
|
||||
# Today a firm we do not have is refused by the model alone, on rule 3; softening that rule without a code
|
||||
# check broke the refusals (Bielik 30%, experiment 9.11). Off by default until measured.
|
||||
got = _run("""const keys = async (q, chat) => { const s = session(['Nie znalazłem [1].']);
|
||||
const a = await s.ask(q, chat); return a.refs.map((r) => [r.key, r.text]); };
|
||||
return { zygzak: await keys('Jakie umowy mamy z firmą Zygzak sp. z o.o.?', { istnienie: true }),
|
||||
inflected: await keys('Jakie sprawy prowadzimy dla Kalinowego Dworu?', { istnienie: true }),
|
||||
exact: await keys('Jaką umowę mamy z Kalinowy Dwór?', { istnienie: true }),
|
||||
off: await keys('Jakie umowy mamy z firmą Zygzak sp. z o.o.?') };""")
|
||||
hit = [t for k, t in got["zygzak"] if k == "atrium:istnienie"]
|
||||
assert len(hit) == 1 and "„Zygzak”" in hit[0] and "nie ma " not in hit[0]
|
||||
for case in ("inflected", "exact", "off"):
|
||||
assert all(k != "atrium:istnienie" for k, _ in got[case]), case
|
||||
|
||||
|
||||
def test_step0_the_english_urgent_table_speaks_english_and_uodo_is_no_court() -> None:
|
||||
# Step-0 defects: Polish "Koniec umowy … kontrahent …" under an English answer, a UODO breach notice called
|
||||
# "court", "overdue by 1 days".
|
||||
got = _run("""const s = session(); const ix = await s.index();
|
||||
return { rows: s.f.chatPick('What are the most urgent deadlines this week?', ix).table.rows,
|
||||
uodo: ix.byKey.get('sygna:termin:d2').text, court: ix.byKey.get('sygna:termin:d4').text };""")
|
||||
rows = {r[1]: r for r in got["rows"]}
|
||||
uodo = rows["Zgłoszenie naruszenia do UODO"]
|
||||
assert uodo[2] != "court" and uodo[4] == "overdue by 1 day"
|
||||
assert rows["Odpowiedź na pozew"][2] == "court" and rows["Odpowiedź na pozew"][4] == "in 2 days"
|
||||
end = next(r for r in got["rows"] if "UM-2026-0006" in r[1])
|
||||
assert "Koniec umowy" not in end[1] and "kontrahent" not in end[5] and end[1].startswith("End of contract")
|
||||
assert "(sąd)" not in got["uodo"] and "(sąd)" in got["court"]
|
||||
|
||||
|
||||
def test_review_people_and_dates_said_as_they_are() -> None:
|
||||
# chatWho: an id the list lacks is "spoza listy"; no list at all (the account cannot read it) is not.
|
||||
# An end date already past is not "najbliższa"/"najwcześniej kończy się".
|
||||
got = _run("""WORLD['sygna/matters'][1].responsible_lawyer_id = 'u9';
|
||||
WORLD['galena/cards?limit=200&offset=0'][2].ends_on = '2026-10-13';
|
||||
const ix = await session().index();
|
||||
delete WORLD['sygna/users'];
|
||||
const blind = await session().index();
|
||||
return { stranger: ix.byKey.get('sygna:sprawa:m2').text, nolist: blind.byKey.get('sygna:sprawa:m1').text,
|
||||
reg: ix.byKey.get('galena:zestawienie').text };""")
|
||||
assert "prowadzi osoba spoza listy użytkowników" in got["stranger"]
|
||||
assert "spoza listy" not in got["nolist"] and "osoba prowadząca nie wpisana" not in got["nolist"] and "prowadzi osoba" in got["nolist"]
|
||||
assert "najbliższa data końca: UM-2026-0006 (2026-11-17)" in got["reg"]
|
||||
assert "data końca już minęła: UM-2026-0003 (2026-10-13)" in got["reg"]
|
||||
|
||||
|
||||
def test_review_refusals_fallbacks_and_retries_keep_the_answer() -> None:
|
||||
got = _run("""let reg = 0; const run = async (replies, q, o) => { const s = session(replies, o);
|
||||
try { const a = await s.ask(q); return { coded: a.coded || null, content: a.content, table: !!a.table, failed: !!a.failed, calls: s.asked.length,
|
||||
refs: a.refs.map((r) => r.key) }; } catch (e) { return { err: String(e), calls: s.asked.length }; } };
|
||||
return {
|
||||
// an English refusal of an off-topic ask is said by code in English
|
||||
en: await run(['Sorry, I do not write poems.'], 'Write a short poem about the weather.'),
|
||||
// an uncited answer to the urgent question keeps the urgent table, it is no "nie znalazłem nic"
|
||||
urgent: await run(['Najpierw zajmij się zaległymi zadaniami.'], 'co jest najpilniejsze?'),
|
||||
// a retry that passes with its [n] is the answer, not the raw data
|
||||
// (the retry's last message is the correction, so the [n] is kept from the first request)
|
||||
retry: await run([(b) => `Łączna wartość umów w PLN to 999 999,00 PLN [${(reg = nOf(b, 'Rejestr umów'))}].`,
|
||||
() => `Łączna wartość umów w PLN to 205 000,50 PLN [${reg}].`], 'Jaka jest łączna wartość umów w PLN?'),
|
||||
// a break after the first words is not retried
|
||||
mid: await run(['Najpierw Telefon do klienta [1].'], 'co jest najpilniejsze?', { breakMid: true }),
|
||||
// with the existence check on, the urgent list stays [1]
|
||||
exist: await run(['Najpierw Telefon do klienta [1].'], 'Co jest najpilniejsze dla Zygzaka?', { chat: {} }),
|
||||
};""")
|
||||
assert got["en"].get("coded") == "refusal" and got["en"]["content"].startswith("I found nothing"), got["en"]
|
||||
assert got["urgent"].get("coded") != "refusal" and got["urgent"].get("table"), got["urgent"]
|
||||
assert got["retry"].get("coded") is None and "205 000,50 PLN" in got["retry"]["content"], got["retry"]
|
||||
assert got["mid"]["calls"] == 1 and (got["mid"].get("failed") or "err" in got["mid"]), got["mid"]
|
||||
exist = _run("""const s = session(['Najpierw Telefon do klienta [1].']);
|
||||
const a = await s.ask('Co jest najpilniejsze dla Zygzaka?', { istnienie: true }); return a.refs.map((r) => r.key);""")
|
||||
assert exist[0] == "atrium:pilne" and "atrium:istnienie" not in exist
|
||||
|
||||
|
||||
def test_review_references_survive_abbreviations_and_lists_go_on() -> None:
|
||||
got = _run("""const ix = await session().index();
|
||||
const ref = (n, key) => ({ n, key });
|
||||
const carry = (content, key) => s0.f.chatCarry({ content, refs: [ref(1, key)] }, ix).map((r) => r.key);
|
||||
const s0 = session();
|
||||
const s = session([(b) => `Tak, ta umowa najmu biura nadal obowiązuje [${nOf(b, 'UM-2026-0001 „Najem')}].`]);
|
||||
const a = await s.ask('Czy umowa UM-2026-0001 obowiązuje?');
|
||||
// a one-item answer citing a longer list: "a drugi termin?" is looked up, not asked back
|
||||
const t = session([(b) => `Najbliższy termin to Odpowiedź na pozew, 2026-11-14 [${nOf(b, 'Stan na 2026-11-12 (tydzień')}].`, 'Drugi to Notatka dla zarządu [1].']);
|
||||
await t.ask('Jaki jest najbliższy termin w sprawie 2026/0001?');
|
||||
const second = await t.ask('A drugi termin?');
|
||||
return { mentioned: a.mentioned,
|
||||
sa: carry('Kontrahentem jest Beta S.A. [1]', 'galena:umowa:c3'),
|
||||
year: carry('Umowa kończy się 30 czerwca 2027. [1]', 'galena:umowa:c3'),
|
||||
bare: carry('W danych, do których masz dostęp, nie znalazłem odpowiedzi [1].', 'galena:umowa:c3'),
|
||||
secondCalls: t.asked.length, secondCoded: second.coded || null };""")
|
||||
assert "galena:umowa:c1" in got["mentioned"]
|
||||
assert got["sa"] == ["galena:umowa:c3"] and got["year"] == ["galena:umowa:c3"] and got["bare"] == []
|
||||
assert got["secondCalls"] == 2 and got["secondCoded"] != "ask"
|
||||
|
||||
|
||||
def test_review_today_is_exempt_only_as_a_frame_and_en_refs_have_no_polish() -> None:
|
||||
got = _run("""const s = session(); const f = s.f;
|
||||
const src = [{ slug: 'x', kind: 'x', key: 'x:1', text: 'Apelacja, termin 2026-12-02.' }];
|
||||
const bad = (t) => f.chatVerify(t, src).issues.filter((x) => x.level === 'bad').map((x) => x.raw);
|
||||
WORLD['galena/cards?limit=200&offset=0'][5].counterparty = null;
|
||||
const ix = await s.index();
|
||||
const row = f.chatPick('What are the most urgent deadlines this week?', ix).table.rows.find((r) => r[1].includes('UM-2026-0006'));
|
||||
return { framed: bad('Stan na 2026-11-12: najpilniejsza jest Apelacja [1].'), wrong: bad('Apelacja ma termin 2026-11-12 [1].'), row };""")
|
||||
assert got["framed"] == [] and "2026-11-12" in got["wrong"]
|
||||
assert got["row"][5] == "contract UM-2026-0006, counterparty not entered"
|
||||
@@ -26,7 +26,8 @@ def _block(console: str, start: str, end: str) -> str:
|
||||
|
||||
|
||||
def _menus(console: str) -> str:
|
||||
return _block(console, "const NAV = [", "];") + _block(console, "const ADMIN_NAV = [", "];")
|
||||
return (_block(console, "const NAV = [", "];") + _block(console, "const SETTINGS_NAV = [", "];")
|
||||
+ _block(console, "const ADMIN_NAV = [", "];"))
|
||||
|
||||
|
||||
def _i18n(console: str) -> set[str]:
|
||||
@@ -37,7 +38,8 @@ def _i18n(console: str) -> set[str]:
|
||||
def test_every_admin_screen_is_in_the_menu(console):
|
||||
"""A screen the router serves and no menu reaches is a screen only a bookmark finds."""
|
||||
routed = set(re.findall(r"if \(page === '([a-z]+)'", _block(console, "async function adminRoute(", "\n}\n")))
|
||||
listed = set(re.findall(r"hash: '#/admin/([a-z]+)'", _block(console, "const ADMIN_NAV = [", "];")))
|
||||
listed = set(re.findall(r"hash: '#/admin/([a-z]+)'", _block(console, "const ADMIN_NAV = [", "];")
|
||||
+ _block(console, "const SETTINGS_NAV = [", "];")))
|
||||
# Module administration is a tab of the catalogue ("Moduły"), lit by its menu entry.
|
||||
tabbed = set(re.findall(r"'#/admin/([a-z]+)'", _block(console, "function catalogTabs(", "\n}\n")))
|
||||
assert "'#/admin/modules'" in _block(console, "const NAV = [", "];")
|
||||
@@ -63,7 +65,7 @@ def test_the_screens_that_left_the_menu_still_route(console):
|
||||
def test_every_label_the_menu_shows_is_translated(console):
|
||||
labels = re.findall(r"label: '([^']+)'", _menus(console))
|
||||
heads = re.findall(r"sep: '([^']+)'", _block(console, "const ADMIN_NAV = [", "];"))
|
||||
heads += re.findall(r'<div class="nav-sep">([^<$]+)</div>', _block(console, "function renderNav(", "\n}\n"))
|
||||
heads += re.findall(r"label: '([^']+)', (?:admin|groups)", _block(console, "const SECTIONS = [", "];"))
|
||||
tabs = re.findall(r"'#/[a-z/]+', '([^']+)'\)", _block(console, "function catalogTabs(", "\n}\n"))
|
||||
shown = labels + heads + tabs
|
||||
assert labels and heads and len(tabs) == 3
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
"""deploy/push.sh checks Arbiter's database with exactly the lists Arbiter itself declares (M1d).
|
||||
|
||||
Arbiter lives in the arbiter submodule (`apps/arbiter`; the repository also carries the engine). Its evidence lists are
|
||||
`app.models.APPEND_ONLY_TABLES` / `NO_DELETE_TABLES`, which its 0002, 0005 and 0006 grant from, so
|
||||
push.sh's CHECK_EXTRA for arbiter is compared with them: an evidence table Arbiter adds later must not
|
||||
deploy unchecked. Arbiter calls the models itself, so it is a model-provider KEY reader, and its
|
||||
migrator references the hub's model_provider; the hub's templates list both roles.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
PUSH = ROOT / "deploy" / "push.sh"
|
||||
MODELS = (ROOT / "deploy" / "modules" / "arbiter" / "apps" / "arbiter" / "backend" / "app" / "models"
|
||||
/ "__init__.py")
|
||||
|
||||
|
||||
def _tuple(src: str, name: str) -> list[str]:
|
||||
body = re.search(rf"^{name}(?:: [^=]+)? = \(([^)]*)\)", src, re.M)
|
||||
assert body, name
|
||||
return re.findall(r'"([a-z_]+)"', body.group(1))
|
||||
|
||||
|
||||
def _check_extra() -> str:
|
||||
actual = re.search(r'arbiter\) UP=ARBITER;.*?CHECK_EXTRA="([^"]*)"',
|
||||
PUSH.read_text(encoding="utf-8"), re.S)
|
||||
assert actual, "push.sh has no arbiter branch in app_setup"
|
||||
return actual.group(1)
|
||||
|
||||
|
||||
def test_push_checks_arbiter_with_arbiter_own_lists():
|
||||
if not MODELS.exists():
|
||||
pytest.skip("deploy/modules/arbiter (apps/arbiter) is not checked out")
|
||||
models = MODELS.read_text(encoding="utf-8")
|
||||
append_only, no_delete = _tuple(models, "APPEND_ONLY_TABLES"), _tuple(models, "NO_DELETE_TABLES")
|
||||
expected = " ".join([f"--append-only {' '.join(append_only)}",
|
||||
*([f"--no-delete {' '.join(no_delete)}"] if no_delete else [])])
|
||||
assert _check_extra() == expected
|
||||
|
||||
|
||||
def test_arbiter_reads_model_provider_keys_and_references_providers():
|
||||
push = PUSH.read_text(encoding="utf-8")
|
||||
assert "case $slug in arbiter) IDENTITY_CHECK_ARGS=\"$IDENTITY_CHECK_ARGS --model-provider-keys\"" in push
|
||||
atrium = (ROOT / "deploy" / "env" / "atrium.env.example").read_text(encoding="utf-8")
|
||||
keys = re.search(r"^MODEL_PROVIDER_KEY_READER_ROLES=(.*)$", atrium, re.M).group(1).split(",")
|
||||
migrators = re.search(r"^MODEL_PROVIDER_MIGRATOR_ROLES=(.*)$", atrium, re.M).group(1).split(",")
|
||||
assert "arbiter_app" in keys
|
||||
assert migrators == ["arbiter_migrator"]
|
||||
@@ -1,50 +0,0 @@
|
||||
"""deploy/push.sh checks Compass's database with exactly the lists Compass itself declares.
|
||||
|
||||
Compass's evidence is more than its audit log, and it grows: `app/db_grants.py` says which tables the
|
||||
runtime role may never update or delete (`MANAGED_CHECK_ARGS`). push.sh's step 4 hands
|
||||
`dredd_core.managed check` its own copy of that string, so a Compass that adds an evidence table
|
||||
while push.sh keeps the old string deploys a database whose new evidence nobody checks — the check
|
||||
still passes. Compared here wherever the Compass checkout is present (it is a submodule).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
PUSH = ROOT / "deploy" / "push.sh"
|
||||
GRANTS = ROOT / "deploy" / "modules" / "compass" / "apps" / "compass" / "backend" / "app" / "db_grants.py"
|
||||
|
||||
|
||||
def _tuple(src: str, name: str) -> list[str]:
|
||||
body = re.search(rf"^{name} = \(([^)]*)\)", src, re.M)
|
||||
assert body, name
|
||||
return re.findall(r'"([a-z_]+)"', body.group(1))
|
||||
|
||||
|
||||
def test_push_checks_compass_with_compass_own_lists():
|
||||
if not GRANTS.exists():
|
||||
pytest.skip("deploy/modules/compass is not checked out")
|
||||
grants = GRANTS.read_text(encoding="utf-8")
|
||||
expected = (f"--append-only {' '.join(_tuple(grants, 'APPEND_ONLY'))} "
|
||||
f"--no-delete {' '.join(_tuple(grants, 'NO_DELETE'))} "
|
||||
f"--read-only {' '.join(_tuple(grants, 'READ_ONLY'))}")
|
||||
actual = re.search(r'compass\) UP=COMPASS;.*?CHECK_EXTRA="([^"]*)"',
|
||||
PUSH.read_text(encoding="utf-8"), re.S)
|
||||
assert actual and actual.group(1) == expected
|
||||
|
||||
|
||||
def test_push_checks_compass_opted_in_to_the_model_provider_keys():
|
||||
"""dredd-core 0.15.0: Compass is the one module in MODEL_PROVIDER_KEY_READER_ROLES, so its
|
||||
platform check carries Compass's own `MODEL_PROVIDER_CHECK_ARGS` and no other module's does."""
|
||||
push = PUSH.read_text(encoding="utf-8")
|
||||
flag = '[ "$slug" != compass ] || IDENTITY_CHECK_ARGS="$IDENTITY_CHECK_ARGS --model-provider-keys"'
|
||||
assert flag in push
|
||||
if not GRANTS.exists():
|
||||
pytest.skip("deploy/modules/compass is not checked out")
|
||||
declared = re.search(r'^MODEL_PROVIDER_CHECK_ARGS = "([^"]*)"', GRANTS.read_text(encoding="utf-8"),
|
||||
re.M)
|
||||
assert declared, "Compass's db_grants declares no MODEL_PROVIDER_CHECK_ARGS: repin the submodule"
|
||||
assert flag.endswith(f' {declared.group(1)}"')
|
||||
@@ -1,37 +0,0 @@
|
||||
"""deploy/compose.yaml: Compass's backend can reach a model server on this box.
|
||||
|
||||
A `local` model provider in Compass is accepted only at a loopback name or at host.docker.internal
|
||||
(Compass's services/providers.py LOCAL_HOSTS), which is what keeps a contract on the machine it was
|
||||
uploaded to. On Linux, Docker defines host.docker.internal only for a service that asks with
|
||||
`extra_hosts: host-gateway` — without it the provider saves, and every analysis fails to resolve the
|
||||
name. Only compass-backend runs the engine, so only it asks; no other service gets a route to the host.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pathlib
|
||||
|
||||
import yaml
|
||||
|
||||
COMPOSE = pathlib.Path(__file__).resolve().parents[2] / "deploy" / "compose.yaml"
|
||||
|
||||
|
||||
class _Loader(yaml.SafeLoader):
|
||||
pass
|
||||
|
||||
|
||||
# compose.yaml carries Compose-only tags (`!reset`, `!override`) in places; their values do not matter here.
|
||||
_Loader.add_multi_constructor("!", lambda loader, suffix, node: None)
|
||||
|
||||
|
||||
def _services() -> dict:
|
||||
return yaml.load(COMPOSE.read_text(encoding="utf-8"), Loader=_Loader)["services"]
|
||||
|
||||
|
||||
def test_compass_backend_resolves_the_host_for_a_local_model():
|
||||
assert "host.docker.internal:host-gateway" in (_services()["compass-backend"].get("extra_hosts") or [])
|
||||
|
||||
|
||||
def test_no_other_service_is_given_the_host():
|
||||
asking = sorted(name for name, svc in _services().items()
|
||||
if name != "compass-backend" and svc.get("extra_hosts"))
|
||||
assert asking == []
|
||||
@@ -1,24 +0,0 @@
|
||||
"""deploy/env/compass.migrate.env.example: the line that gives the platform its Compass demo set.
|
||||
|
||||
Compass's own default for SEED_DEMO is false, because the twenty synthetic contracts it places are
|
||||
permanent. So on the platform this template's line is the only thing that turns the set on: an edit
|
||||
that dropped or commented it would leave the platform's demo empty, and the only trace would be one INFO
|
||||
line in a migrate log ("SEED_DEMO is off") that nobody reads on a routine deploy.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
TEMPLATE = pathlib.Path(__file__).resolve().parents[2] / "deploy" / "env" / "compass.migrate.env.example"
|
||||
|
||||
|
||||
def test_the_platform_template_turns_the_demo_set_on():
|
||||
active = re.findall(r"(?m)^SEED_DEMO=(.*)$", TEMPLATE.read_text(encoding="utf-8"))
|
||||
assert active == ["true"]
|
||||
|
||||
|
||||
def test_it_says_the_set_is_permanent_and_where_the_log_explains_a_missing_one():
|
||||
text = TEMPLATE.read_text(encoding="utf-8")
|
||||
assert "PERMANENT" in text
|
||||
assert "not seeded" in text
|
||||
@@ -25,8 +25,8 @@ yaml = pytest.importorskip("yaml")
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
DEPLOY = ROOT / "deploy"
|
||||
MODULES = ("galena", "sygna", "counsel", "compass", "insider")
|
||||
SUBDIR = {"compass": "apps/compass"}
|
||||
MODULES = ("galena", "sygna", "counsel", "insider", "arbiter")
|
||||
SUBDIR = {"arbiter": "apps/arbiter"}
|
||||
|
||||
|
||||
def _checks():
|
||||
@@ -105,8 +105,8 @@ def _broken(model, change):
|
||||
lambda s, n: s["sygna-backend"]["environment"].__setitem__("FORWARDED_ALLOW_IPS", "172.30.11.0/24"),
|
||||
"expected its own `sygna` subnet"),
|
||||
("a module trusts everyone",
|
||||
lambda s, n: s["compass-backend"]["environment"].__setitem__("FORWARDED_ALLOW_IPS", "*"),
|
||||
"expected its own `compass` subnet"),
|
||||
lambda s, n: s["arbiter-backend"]["environment"].__setitem__("FORWARDED_ALLOW_IPS", "*"),
|
||||
"expected its own `arbiter` subnet"),
|
||||
("a module refuses framing",
|
||||
lambda s, n: s["counsel-backend"]["environment"].__setitem__("FRAME_ANCESTORS", "'none'"), "FRAME_ANCESTORS"),
|
||||
("a module loses its console context",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""deploy/init.sh --add: one app joins a deployment that already exists.
|
||||
|
||||
`init.sh --add compass` is how Compass reaches a box that is already running. The only other ways
|
||||
`init.sh --add insider` is how Insider reaches a box that is already running. The only other ways
|
||||
were copying a scratch init's secrets across by hand, or --force, which regenerates every secret on
|
||||
the box — Galena's unrecoverable ENCRYPTION_MASTER_KEY among them.
|
||||
|
||||
@@ -38,21 +38,21 @@ def _init(*args: str) -> subprocess.CompletedProcess:
|
||||
|
||||
@pytest.fixture
|
||||
def box(tmp_path):
|
||||
"""A deployment that went live before Compass was in the kit and has since cut over to one
|
||||
account: init.sh's own output with every Compass line taken out, the hub on the shared schema,
|
||||
"""A deployment that went live before Insider was in the kit and has since cut over to one
|
||||
account: init.sh's own output with every Insider line taken out, the hub on the shared schema,
|
||||
and db.env ending without a newline (the cutover added its last line by hand — which is why the
|
||||
PLATFORM_IDENTITY_SCHEMA line init.sh now writes itself is taken out first and put back last)."""
|
||||
done = _init("--ip", "203.0.113.7", "--into", str(tmp_path))
|
||||
assert done.returncode == 0, done.stderr
|
||||
for name in ("compass.env", "compass.migrate.env"):
|
||||
for name in ("insider.env", "insider.migrate.env"):
|
||||
(tmp_path / "env" / name).unlink()
|
||||
db_env = tmp_path / "db.env"
|
||||
kept = [line for line in db_env.read_text(encoding="utf-8").splitlines()
|
||||
if not re.match(r"^(# )?(COMPASS_|PLATFORM_IDENTITY_SCHEMA=)", line)]
|
||||
if not re.match(r"^(# )?(INSIDER_|PLATFORM_IDENTITY_SCHEMA=)", line)]
|
||||
db_env.write_text("\n".join(kept) + "\nPLATFORM_IDENTITY_SCHEMA=dredd", encoding="utf-8", newline="\n")
|
||||
dot_env = tmp_path / ".env"
|
||||
dot_env.write_text("".join(line for line in dot_env.read_text(encoding="utf-8").splitlines(True)
|
||||
if not re.match(r"^(# )?(COMPASS_DOMAIN|COMPOSE_PROFILES)=", line)),
|
||||
if not re.match(r"^(# )?(INSIDER_DOMAIN|COMPOSE_PROFILES)=", line)),
|
||||
encoding="utf-8", newline="\n")
|
||||
atrium = tmp_path / "env" / "atrium.env"
|
||||
text = atrium.read_text(encoding="utf-8")
|
||||
@@ -64,22 +64,22 @@ def box(tmp_path):
|
||||
return tmp_path
|
||||
|
||||
|
||||
def test_it_writes_compass_and_touches_no_other_app(box):
|
||||
def test_it_writes_insider_and_touches_no_other_app(box):
|
||||
before = {p.name: p.read_bytes() for p in (box / "env").glob("*.env") if p.name != "atrium.env"}
|
||||
done = _init("--add", "compass", "--into", str(box))
|
||||
done = _init("--add", "insider", "--into", str(box))
|
||||
assert done.returncode == 0, done.stdout + done.stderr
|
||||
after = {p.name: p.read_bytes() for p in (box / "env").glob("*.env")
|
||||
if p.name not in ("atrium.env", "compass.env", "compass.migrate.env")}
|
||||
if p.name not in ("atrium.env", "insider.env", "insider.migrate.env")}
|
||||
assert after == before
|
||||
|
||||
|
||||
def test_its_urls_carry_the_passwords_db_env_now_holds(box):
|
||||
assert _init("--add", "compass", "--into", str(box)).returncode == 0
|
||||
assert _init("--add", "insider", "--into", str(box)).returncode == 0
|
||||
db = _env_values(box / "db.env")
|
||||
runtime = _env_values(box / "env" / "compass.env")
|
||||
migrate = _env_values(box / "env" / "compass.migrate.env")
|
||||
assert f"compass_app:{db['COMPASS_APP_PASSWORD']}@postgres:5432/dredd" in runtime["DATABASE_URL"]
|
||||
assert f"compass_migrator:{db['COMPASS_MIGRATOR_PASSWORD']}@postgres:5432/dredd" \
|
||||
runtime = _env_values(box / "env" / "insider.env")
|
||||
migrate = _env_values(box / "env" / "insider.migrate.env")
|
||||
assert f"insider_app:{db['INSIDER_APP_PASSWORD']}@postgres:5432/dredd" in runtime["DATABASE_URL"]
|
||||
assert f"insider_migrator:{db['INSIDER_MIGRATOR_PASSWORD']}@postgres:5432/dredd" \
|
||||
in migrate["MIGRATION_DATABASE_URL"]
|
||||
# The unterminated last line was ended, not glued to the first appended key.
|
||||
assert db["PLATFORM_IDENTITY_SCHEMA"] == "dredd"
|
||||
@@ -88,39 +88,39 @@ def test_its_urls_carry_the_passwords_db_env_now_holds(box):
|
||||
|
||||
|
||||
def test_the_site_comes_from_the_deployment(box):
|
||||
assert _init("--add", "compass", "--into", str(box)).returncode == 0
|
||||
assert _init("--add", "insider", "--into", str(box)).returncode == 0
|
||||
site = _env_values(box / ".env")["ATRIUM_DOMAIN"]
|
||||
# There are no per-app *_DOMAIN keys: --add must not write one.
|
||||
assert "COMPASS_DOMAIN" not in _env_values(box / ".env")
|
||||
assert _env_values(box / "env" / "compass.env")["APP_BASE_URL"] == f"{site}/compass"
|
||||
assert "INSIDER_DOMAIN" not in _env_values(box / ".env")
|
||||
assert _env_values(box / "env" / "insider.env")["APP_BASE_URL"] == f"{site}/insider"
|
||||
|
||||
|
||||
def test_on_the_platform_it_joins_the_one_account(box):
|
||||
assert _init("--add", "compass", "--into", str(box)).returncode == 0
|
||||
runtime = _env_values(box / "env" / "compass.env")
|
||||
assert _init("--add", "insider", "--into", str(box)).returncode == 0
|
||||
runtime = _env_values(box / "env" / "insider.env")
|
||||
atrium = _env_values(box / "env" / "atrium.env")
|
||||
assert runtime["IDENTITY_SCHEMA"] == "dredd"
|
||||
assert runtime["SESSION_COOKIE_NAME"] == "dredd_session"
|
||||
assert atrium["IDENTITY_READER_ROLES"] == "galena_app,sygna_app,counsel_app,compass_app"
|
||||
assert atrium["IDENTITY_MIGRATOR_ROLES"] == "galena_migrator,sygna_migrator,counsel_migrator,compass_migrator"
|
||||
# Atrium's grants now name compass's roles, so the next push must provision them: it does only
|
||||
assert atrium["IDENTITY_READER_ROLES"] == "galena_app,sygna_app,counsel_app,insider_app"
|
||||
assert atrium["IDENTITY_MIGRATOR_ROLES"] == "galena_migrator,sygna_migrator,counsel_migrator,insider_migrator"
|
||||
# Atrium's grants now name insider's roles, so the next push must provision them: it does only
|
||||
# for an app that is switched on.
|
||||
assert "compass" in _env_values(box / ".env")["COMPOSE_PROFILES"].split(",")
|
||||
assert "insider" in _env_values(box / ".env")["COMPOSE_PROFILES"].split(",")
|
||||
|
||||
|
||||
def test_a_second_run_refuses_rather_than_minting_new_passwords(box):
|
||||
assert _init("--add", "compass", "--into", str(box)).returncode == 0
|
||||
assert _init("--add", "insider", "--into", str(box)).returncode == 0
|
||||
snapshot = {p: p.read_bytes() for p in box.rglob("*") if p.is_file()}
|
||||
again = _init("--add", "compass", "--into", str(box))
|
||||
again = _init("--add", "insider", "--into", str(box))
|
||||
assert again.returncode == 2
|
||||
assert {p: p.read_bytes() for p in box.rglob("*") if p.is_file()} == snapshot
|
||||
|
||||
|
||||
@pytest.mark.parametrize("extra", [("--force",), ("--ip", "203.0.113.8")])
|
||||
def test_it_takes_nothing_that_would_regenerate_or_relocate(box, extra):
|
||||
done = _init("--add", "compass", *extra, "--into", str(box))
|
||||
done = _init("--add", "insider", *extra, "--into", str(box))
|
||||
assert done.returncode == 2
|
||||
assert not (box / "env" / "compass.env").exists()
|
||||
assert not (box / "env" / "insider.env").exists()
|
||||
|
||||
|
||||
def test_the_hub_cannot_be_added(box):
|
||||
@@ -133,8 +133,8 @@ def test_half_a_cutover_is_refused(box):
|
||||
atrium = box / "env" / "atrium.env"
|
||||
atrium.write_text(re.sub(r"(?m)^IDENTITY_SCHEMA=.*$", "IDENTITY_SCHEMA=", atrium.read_text(encoding="utf-8")),
|
||||
encoding="utf-8", newline="\n")
|
||||
assert _init("--add", "compass", "--into", str(box)).returncode == 2
|
||||
assert not (box / "env" / "compass.env").exists()
|
||||
assert _init("--add", "insider", "--into", str(box)).returncode == 2
|
||||
assert not (box / "env" / "insider.env").exists()
|
||||
|
||||
|
||||
def _standalone(box: pathlib.Path) -> None:
|
||||
@@ -153,14 +153,14 @@ def _standalone(box: pathlib.Path) -> None:
|
||||
|
||||
def test_a_standalone_deployment_gets_no_identity(box):
|
||||
"""The module templates carry the one-account lines ACTIVE now (a fresh install is one account),
|
||||
so --add on a standalone box has to comment them back out — or Compass would read a schema
|
||||
so --add on a standalone box has to comment them back out — or Insider would read a schema
|
||||
nobody serves, under a cookie name no other app of that box uses."""
|
||||
_standalone(box)
|
||||
atrium_before = (box / "env" / "atrium.env").read_bytes()
|
||||
assert _init("--add", "compass", "--into", str(box)).returncode == 0
|
||||
runtime = _env_values(box / "env" / "compass.env")
|
||||
assert _init("--add", "insider", "--into", str(box)).returncode == 0
|
||||
runtime = _env_values(box / "env" / "insider.env")
|
||||
assert "IDENTITY_SCHEMA" not in runtime and "SESSION_COOKIE_NAME" not in runtime
|
||||
text = (box / "env" / "compass.env").read_text(encoding="utf-8")
|
||||
text = (box / "env" / "insider.env").read_text(encoding="utf-8")
|
||||
assert "\n# IDENTITY_SCHEMA=dredd\n" in text and "\n# SESSION_COOKIE_NAME=dredd_session\n" in text
|
||||
assert (box / "env" / "atrium.env").read_bytes() == atrium_before
|
||||
|
||||
@@ -171,17 +171,17 @@ def test_a_hub_on_a_schema_db_env_does_not_know_is_refused(box):
|
||||
db_env = box / "db.env"
|
||||
db_env.write_text(db_env.read_text(encoding="utf-8").replace("PLATFORM_IDENTITY_SCHEMA=dredd", ""),
|
||||
encoding="utf-8", newline="\n")
|
||||
done = _init("--add", "compass", "--into", str(box))
|
||||
done = _init("--add", "insider", "--into", str(box))
|
||||
assert done.returncode == 2
|
||||
assert "sets no PLATFORM_IDENTITY_SCHEMA" in done.stderr
|
||||
assert not (box / "env" / "compass.env").exists()
|
||||
assert not (box / "env" / "insider.env").exists()
|
||||
|
||||
|
||||
def test_standalone_is_not_an_add_option(box):
|
||||
"""--add follows the deployment it joins; one account or not is that deployment's answer."""
|
||||
done = _init("--add", "compass", "--standalone", "--into", str(box))
|
||||
done = _init("--add", "insider", "--standalone", "--into", str(box))
|
||||
assert done.returncode == 2
|
||||
assert not (box / "env" / "compass.env").exists()
|
||||
assert not (box / "env" / "insider.env").exists()
|
||||
|
||||
|
||||
def _append(path: pathlib.Path, line: str) -> None:
|
||||
@@ -198,8 +198,8 @@ def _append(path: pathlib.Path, line: str) -> None:
|
||||
def test_a_key_it_would_write_twice_is_refused(box, file, lines):
|
||||
for line in lines:
|
||||
_append(box / file, line)
|
||||
assert _init("--add", "compass", "--into", str(box)).returncode == 2
|
||||
assert not (box / "env" / "compass.env").exists()
|
||||
assert _init("--add", "insider", "--into", str(box)).returncode == 2
|
||||
assert not (box / "env" / "insider.env").exists()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("line", ["MANAGED_DB_HOST=db.example.net",
|
||||
@@ -207,12 +207,12 @@ def test_a_key_it_would_write_twice_is_refused(box, file, lines):
|
||||
def test_a_managed_database_is_refused(box, line):
|
||||
"""--add writes this box's own PostgreSQL URLs; on a provider's database they would be wrong."""
|
||||
_append(box / "db.env", line)
|
||||
assert _init("--add", "compass", "--into", str(box)).returncode == 2
|
||||
assert _init("--add", "insider", "--into", str(box)).returncode == 2
|
||||
|
||||
|
||||
def test_leftover_files_are_refused_without_suggesting_force(box):
|
||||
(box / "env" / "compass.env").write_text("# a leftover\n", encoding="utf-8")
|
||||
done = _init("--add", "compass", "--into", str(box))
|
||||
(box / "env" / "insider.env").write_text("# a leftover\n", encoding="utf-8")
|
||||
done = _init("--add", "insider", "--into", str(box))
|
||||
assert done.returncode == 2
|
||||
assert "--force" not in done.stderr and "never overwrites" in done.stderr
|
||||
|
||||
@@ -221,56 +221,58 @@ def test_a_role_prefix_reaches_db_env_as_the_main_path_writes_it(tmp_path):
|
||||
"""push.sh provisions <APP>_APP_ROLE / <APP>_MIGRATOR_ROLE from db.env and falls back to the
|
||||
plain names: without them a prefixed deployment would provision roles nothing connects as."""
|
||||
assert _init("--ip", "203.0.113.7", "--role-prefix", "t1_", "--into", str(tmp_path)).returncode == 0
|
||||
for name in ("compass.env", "compass.migrate.env"):
|
||||
for name in ("insider.env", "insider.migrate.env"):
|
||||
(tmp_path / "env" / name).unlink()
|
||||
db_env = tmp_path / "db.env"
|
||||
db_env.write_text("".join(line for line in db_env.read_text(encoding="utf-8").splitlines(True)
|
||||
if not line.startswith("COMPASS_")), encoding="utf-8", newline="\n")
|
||||
assert _init("--add", "compass", "--into", str(tmp_path)).returncode == 0
|
||||
if not line.startswith("INSIDER_")), encoding="utf-8", newline="\n")
|
||||
assert _init("--add", "insider", "--into", str(tmp_path)).returncode == 0
|
||||
db = _env_values(db_env)
|
||||
assert db["COMPASS_APP_ROLE"] == "t1_compass_app" and db["COMPASS_MIGRATOR_ROLE"] == "t1_compass_migrator"
|
||||
assert "t1_compass_app:" in _env_values(tmp_path / "env" / "compass.env")["DATABASE_URL"]
|
||||
assert db["INSIDER_APP_ROLE"] == "t1_insider_app" and db["INSIDER_MIGRATOR_ROLE"] == "t1_insider_migrator"
|
||||
assert "t1_insider_app:" in _env_values(tmp_path / "env" / "insider.env")["DATABASE_URL"]
|
||||
|
||||
|
||||
# ── the model-provider secret (dredd-core 0.15.0) ────────────────────────────
|
||||
|
||||
def test_compass_gets_the_hubs_model_provider_secret(box):
|
||||
hub = _env_values(box / "env" / "atrium.env")["MODEL_PROVIDER_SECRET"]
|
||||
assert len(hub) >= 32
|
||||
done = _init("--add", "compass", "--into", str(box))
|
||||
assert done.returncode == 0, done.stdout + done.stderr
|
||||
assert _env_values(box / "env" / "compass.env")["MODEL_PROVIDER_SECRET"] == hub
|
||||
assert _env_values(box / "env" / "atrium.env")["MODEL_PROVIDER_SECRET"] == hub
|
||||
assert hub not in done.stdout + done.stderr
|
||||
|
||||
|
||||
def test_a_hub_from_before_the_secret_gets_one_and_compass_the_same(box):
|
||||
atrium = box / "env" / "atrium.env"
|
||||
atrium.write_text("".join(line for line in atrium.read_text(encoding="utf-8").splitlines(True)
|
||||
if not line.startswith("MODEL_PROVIDER_SECRET=")),
|
||||
encoding="utf-8", newline="\n")
|
||||
done = _init("--add", "compass", "--into", str(box))
|
||||
assert done.returncode == 0, done.stdout + done.stderr
|
||||
hub = _env_values(atrium)["MODEL_PROVIDER_SECRET"]
|
||||
assert len(hub) >= 32
|
||||
assert _env_values(box / "env" / "compass.env")["MODEL_PROVIDER_SECRET"] == hub
|
||||
assert "MODEL_PROVIDER_SECRET" in done.stdout and hub not in done.stdout + done.stderr
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def insider_box(box):
|
||||
"""The same box, from before Insider was in the kit too: its files and passwords taken out."""
|
||||
for name in ("insider.env", "insider.migrate.env"):
|
||||
def arbiter_box(box):
|
||||
"""The same box, from before Arbiter was in the kit too: Arbiter, a key reader of the shared
|
||||
model providers, is the module that carries the hub's MODEL_PROVIDER_SECRET."""
|
||||
for name in ("arbiter.env", "arbiter.migrate.env"):
|
||||
(box / "env" / name).unlink()
|
||||
db_env = box / "db.env"
|
||||
db_env.write_text("\n".join(line for line in db_env.read_text(encoding="utf-8").splitlines()
|
||||
if not re.match(r"^(# )?INSIDER_", line)),
|
||||
if not re.match(r"^(# )?ARBITER_", line)),
|
||||
encoding="utf-8", newline="\n")
|
||||
return box
|
||||
|
||||
|
||||
def test_insider_joins_as_a_reader_switched_on_with_its_own_cursor_secret(insider_box):
|
||||
box = insider_box
|
||||
def test_arbiter_gets_the_hubs_model_provider_secret(arbiter_box):
|
||||
box = arbiter_box
|
||||
hub = _env_values(box / "env" / "atrium.env")["MODEL_PROVIDER_SECRET"]
|
||||
assert len(hub) >= 32
|
||||
done = _init("--add", "arbiter", "--into", str(box))
|
||||
assert done.returncode == 0, done.stdout + done.stderr
|
||||
assert _env_values(box / "env" / "arbiter.env")["MODEL_PROVIDER_SECRET"] == hub
|
||||
assert _env_values(box / "env" / "atrium.env")["MODEL_PROVIDER_SECRET"] == hub
|
||||
assert hub not in done.stdout + done.stderr
|
||||
|
||||
|
||||
def test_a_hub_from_before_the_secret_gets_one_and_arbiter_the_same(arbiter_box):
|
||||
box = arbiter_box
|
||||
atrium = box / "env" / "atrium.env"
|
||||
atrium.write_text("".join(line for line in atrium.read_text(encoding="utf-8").splitlines(True)
|
||||
if not line.startswith("MODEL_PROVIDER_SECRET=")),
|
||||
encoding="utf-8", newline="\n")
|
||||
done = _init("--add", "arbiter", "--into", str(box))
|
||||
assert done.returncode == 0, done.stdout + done.stderr
|
||||
hub = _env_values(atrium)["MODEL_PROVIDER_SECRET"]
|
||||
assert len(hub) >= 32
|
||||
assert _env_values(box / "env" / "arbiter.env")["MODEL_PROVIDER_SECRET"] == hub
|
||||
assert "MODEL_PROVIDER_SECRET" in done.stdout and hub not in done.stdout + done.stderr
|
||||
|
||||
|
||||
def test_insider_joins_as_a_reader_switched_on_with_its_own_cursor_secret(box):
|
||||
done = _init("--add", "insider", "--into", str(box))
|
||||
assert done.returncode == 0, done.stdout + done.stderr
|
||||
runtime = _env_values(box / "env" / "insider.env")
|
||||
|
||||
@@ -31,10 +31,10 @@ import yaml
|
||||
DEPLOY = pathlib.Path(__file__).resolve().parents[2] / "deploy"
|
||||
INIT = DEPLOY / "init.sh"
|
||||
PUSH = DEPLOY / "push.sh"
|
||||
FAMILY = ("atrium", "galena", "sygna", "counsel", "compass")
|
||||
FAMILY = ("atrium", "galena", "sygna", "counsel", "arbiter")
|
||||
MODULES = FAMILY[1:]
|
||||
#: Where a module's app sits inside its checkout (push.sh's SUBDIR): Compass's repository is the engine's.
|
||||
SUBDIR = {"compass": "apps/compass"}
|
||||
#: Where a module's app sits inside its checkout (push.sh's SUBDIR): Arbiter's repository also carries the engine.
|
||||
SUBDIR = {"arbiter": "apps/arbiter"}
|
||||
BASH = shutil.which("bash")
|
||||
needs_bash = pytest.mark.skipif(BASH is None, reason="bash is needed to run deploy/init.sh and push.sh")
|
||||
|
||||
@@ -65,7 +65,7 @@ _Loader.add_multi_constructor("!", lambda loader, suffix, node: None)
|
||||
|
||||
def _switched_on_by_default() -> list[str]:
|
||||
"""The modules `docker compose up -d` starts on a fresh box: those whose backend sits behind no
|
||||
profile, since .env.example names none (Compass's is the `compass` profile)."""
|
||||
profile, since .env.example names none (Arbiter's is the `arbiter` profile)."""
|
||||
services = yaml.load((DEPLOY / "compose.yaml").read_text(encoding="utf-8"), Loader=_Loader)["services"]
|
||||
assert "COMPOSE_PROFILES" not in _active(DEPLOY / ".env.example"), \
|
||||
".env.example switches a profile on: the hub's default role lists must follow it"
|
||||
@@ -90,7 +90,7 @@ class TestTheTemplatesAgree:
|
||||
role that does not exist, so a module that ships OFF must not be listed (its roles are not
|
||||
provisioned), and every module that ships ON must be (or its migration is refused)."""
|
||||
on = _switched_on_by_default()
|
||||
assert "compass" not in on and on == ["galena", "sygna", "counsel"]
|
||||
assert "arbiter" not in on and on == ["galena", "sygna", "counsel"]
|
||||
hub = DEPLOY / "env" / "atrium.env.example"
|
||||
assert _one(hub, "IDENTITY_READER_ROLES") == ",".join(f"{m}_app" for m in on)
|
||||
assert _one(hub, "IDENTITY_MIGRATOR_ROLES") == ",".join(f"{m}_migrator" for m in on)
|
||||
@@ -134,19 +134,28 @@ class TestAFreshInitIsOneAccount:
|
||||
assert module["IDENTITY_SCHEMA"] == "dredd", app
|
||||
assert module["SESSION_COOKIE_NAME"] == "dredd_session", app
|
||||
|
||||
def test_one_model_provider_secret_for_the_hub_and_compass(self, fresh):
|
||||
"""dredd-core 0.15.0: both derive the provider-key cipher from it, so it is ONE value; and
|
||||
it is nobody else's secret (not Compass's SECRET_KEY, which decrypts its pre-0.15 keys)."""
|
||||
def test_one_model_provider_secret_for_the_hub_and_the_model_callers(self, fresh):
|
||||
"""dredd-core 0.15.0: the hub and every module that calls the models derive the provider-key
|
||||
cipher from it, so it is ONE value; and it is nobody's own SECRET_KEY."""
|
||||
hub = _values(fresh / "env" / "atrium.env")
|
||||
compass = _values(fresh / "env" / "compass.env")
|
||||
assert len(hub["MODEL_PROVIDER_SECRET"]) >= 32
|
||||
assert compass["MODEL_PROVIDER_SECRET"] == hub["MODEL_PROVIDER_SECRET"]
|
||||
assert compass["SECRET_KEY"] != hub["MODEL_PROVIDER_SECRET"]
|
||||
assert hub["MODEL_PROVIDER_KEY_READER_ROLES"] == "compass_app"
|
||||
assert hub["MODEL_PROVIDER_MIGRATOR_ROLES"] == "compass_migrator"
|
||||
assert hub["MODEL_PROVIDER_KEY_READER_ROLES"] == "arbiter_app,lexicon_app"
|
||||
assert hub["MODEL_PROVIDER_MIGRATOR_ROLES"] == "arbiter_migrator"
|
||||
arbiter = _values(fresh / "env" / "arbiter.env")
|
||||
lexicon = _values(fresh / "env" / "lexicon.env")
|
||||
assert arbiter["MODEL_PROVIDER_SECRET"] == lexicon["MODEL_PROVIDER_SECRET"] == hub["MODEL_PROVIDER_SECRET"]
|
||||
assert arbiter["SECRET_KEY"] != hub["MODEL_PROVIDER_SECRET"]
|
||||
assert not (fresh / "env" / "compass.env").exists()
|
||||
for app in ("galena", "sygna", "counsel"):
|
||||
assert "MODEL_PROVIDER_SECRET" not in _values(fresh / "env" / f"{app}.env"), app
|
||||
|
||||
def test_arbiter_reads_skills_from_the_hubs_public_address(self, fresh):
|
||||
"""A skill version is read through Atrium's API (the same hairpin as Galena's): the example's
|
||||
`<site>` placeholder must never reach a fresh env file."""
|
||||
arbiter = _values(fresh / "env" / "arbiter.env")
|
||||
assert arbiter["ATRIUM_BASE_URL"] == arbiter["GALENA_BASE_URL"].removesuffix("/galena") + "/atrium"
|
||||
assert "<site>" not in arbiter["ATRIUM_BASE_URL"]
|
||||
|
||||
def test_one_first_administrator_for_the_platform(self, fresh):
|
||||
"""The modules' seeds look the hub's account up by this address, so all five must agree."""
|
||||
emails = {app: _values(fresh / "env" / f"{app}.migrate.env")["BOOTSTRAP_ADMIN_EMAIL"] for app in FAMILY}
|
||||
@@ -159,6 +168,12 @@ class TestAFreshInitIsOneAccount:
|
||||
hub = _values(tmp_path / "env" / "atrium.env")
|
||||
assert hub["IDENTITY_READER_ROLES"] == "t1_galena_app,t1_sygna_app,t1_counsel_app"
|
||||
assert hub["IDENTITY_MIGRATOR_ROLES"] == "t1_galena_migrator,t1_sygna_migrator,t1_counsel_migrator"
|
||||
# Galena trusts the event senders by their REAL role names too, or it refuses every event.
|
||||
galena = _values(tmp_path / "env" / "galena.env")
|
||||
assert (galena["WORKFLOW_EVENT_ROLES"], galena["SIGNING_EVENT_ROLES"],
|
||||
galena["NEGOTIATION_EVENT_ROLES"], galena["ANALYSIS_EVENT_ROLES"]) == (
|
||||
"t1_workflow_app", "t1_parafa_app", "t1_agora_app", "t1_arbiter_app")
|
||||
assert _values(tmp_path / "env" / "agora.env")["WORKFLOW_EVENT_ROLES"] == "t1_workflow_app"
|
||||
|
||||
def test_standalone_is_the_whole_opt_out_at_once(self, tmp_path):
|
||||
"""Never half: the push refuses every half-done combination, so the opt-out writes all of it.
|
||||
@@ -241,7 +256,7 @@ class TestThePushAcceptsWhatInitWrote:
|
||||
assert drift and "--identity-schema dredd --identity-owner atrium_migrator" in drift[0], app
|
||||
assert run and "--identity-schema dredd --identity-owner atrium_migrator" in run[0], app
|
||||
assert len(checks) == 2 and all(f"--identity-tier {tier}" in c for c in checks), app
|
||||
assert "--schema compass " not in trace # switched off, as it ships
|
||||
assert "--schema arbiter " not in trace # switched off, as it ships
|
||||
|
||||
def test_standalone_passes_too_and_carries_no_identity(self, tmp_path):
|
||||
modules = _stand_in_modules(tmp_path)
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
"""deploy/push.sh checks Insider's database with exactly the lists Insider itself declares.
|
||||
|
||||
Insider has no `db_grants.MANAGED_CHECK_ARGS` string the way Compass does: its evidence lists are
|
||||
Insider has no `db_grants.MANAGED_CHECK_ARGS` string the way Compass did: its evidence lists are
|
||||
`app.models.APPEND_ONLY_TABLES` and `NO_DELETE_TABLES`, which its revision 0002 grants from and its
|
||||
own CI hands to `dredd_core.managed check` (`--append-only $append_only --no-delete $no_delete`). So
|
||||
push.sh's CHECK_EXTRA for insider is compared with those two tuples, wherever the submodule is checked
|
||||
out: an evidence table Insider adds later must not deploy unchecked while the check still passes.
|
||||
And Insider is a READER of the shared model providers like every module, never a key reader: the
|
||||
`--model-provider-keys` flag stays Compass's alone.
|
||||
`--model-provider-keys` flag stays Arbiter's (and Lexicon's).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -46,7 +46,7 @@ def test_push_checks_insider_with_insider_own_lists():
|
||||
def test_insider_is_never_a_model_provider_key_reader():
|
||||
push = PUSH.read_text(encoding="utf-8")
|
||||
assert "--model-provider-keys" not in _check_extra()
|
||||
assert '[ "$slug" != compass ] || IDENTITY_CHECK_ARGS="$IDENTITY_CHECK_ARGS --model-provider-keys"' in push
|
||||
assert 'case $slug in arbiter) IDENTITY_CHECK_ARGS="$IDENTITY_CHECK_ARGS --model-provider-keys" ;; esac' in push
|
||||
atrium = (ROOT / "deploy" / "env" / "atrium.env.example").read_text(encoding="utf-8")
|
||||
keys = re.search(r"^MODEL_PROVIDER_KEY_READER_ROLES=(.*)$", atrium, re.M)
|
||||
assert keys and "insider_app" not in keys.group(1)
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
"""deploy/push.sh checks Lexicon and Agora (the split plan's M2-M3) with exactly the lists each
|
||||
declares, and with the platform tier each is granted.
|
||||
|
||||
Each module's evidence lists are `app.models.APPEND_ONLY_TABLES` / `NO_DELETE_TABLES`, which its 0002
|
||||
grants from and its CI's managed check passes, so push.sh's CHECK_EXTRA is compared with them wherever
|
||||
the submodule is checked out: an evidence table a module adds later must not deploy unchecked.
|
||||
|
||||
The tiers: Lexicon calls the models (a model-provider KEY reader), Agora writes the event log (an
|
||||
EMITTER). The hub's template and init.sh list each in exactly its own tier. Panorama (M4), the one
|
||||
module of the READER tier, left the platform: the tier stays, and nothing is listed in it.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
PUSH = ROOT / "deploy" / "push.sh"
|
||||
INIT = ROOT / "deploy" / "init.sh"
|
||||
ATRIUM_ENV = ROOT / "deploy" / "env" / "atrium.env.example"
|
||||
MODULES = ("lexicon", "agora")
|
||||
|
||||
|
||||
def _tuple(src: str, name: str) -> list[str]:
|
||||
body = re.search(rf"^{name}(?:: [^=]+)? = \(([^)]*)\)", src, re.M)
|
||||
assert body, name
|
||||
return re.findall(r'"([a-z_]+)"', body.group(1))
|
||||
|
||||
|
||||
def _check_extra(slug: str) -> str:
|
||||
actual = re.search(rf'^ {slug}\)\s+UP={slug.upper()};.*?CHECK_EXTRA="([^"]*)"',
|
||||
PUSH.read_text(encoding="utf-8"), re.S | re.M)
|
||||
assert actual, f"push.sh has no {slug} branch in app_setup"
|
||||
return actual.group(1)
|
||||
|
||||
|
||||
def _list(key: str) -> list[str]:
|
||||
found = re.search(rf"^{key}=(.*)$", ATRIUM_ENV.read_text(encoding="utf-8"), re.M)
|
||||
assert found, key
|
||||
return [r.strip() for r in found.group(1).split(",") if r.strip()]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("slug", MODULES)
|
||||
def test_push_checks_each_module_with_its_own_lists(slug):
|
||||
models = ROOT / "deploy" / "modules" / slug / "backend" / "app" / "models" / "__init__.py"
|
||||
if not models.exists():
|
||||
pytest.skip(f"deploy/modules/{slug} is not checked out")
|
||||
src = models.read_text(encoding="utf-8")
|
||||
append_only, no_delete = _tuple(src, "APPEND_ONLY_TABLES"), _tuple(src, "NO_DELETE_TABLES")
|
||||
expected = " ".join([f"--append-only {' '.join(append_only)}",
|
||||
*([f"--no-delete {' '.join(no_delete)}"] if no_delete else [])])
|
||||
assert _check_extra(slug) == expected
|
||||
|
||||
|
||||
def test_each_module_is_checked_in_its_own_tier():
|
||||
push = PUSH.read_text(encoding="utf-8")
|
||||
assert 'case $slug in lexicon) IDENTITY_CHECK_ARGS="$IDENTITY_CHECK_ARGS --model-provider-keys" ;; esac' in push
|
||||
assert "case $slug in galena|agora|parafa|workflow|arbiter)" in push
|
||||
assert "case $slug in panorama)" not in push and "--events-reader\" ;;" not in push
|
||||
|
||||
|
||||
def test_the_hub_template_lists_each_in_exactly_its_tier():
|
||||
keys, emitters, readers = (_list("MODEL_PROVIDER_KEY_READER_ROLES"), _list("MODULE_EVENT_EMITTER_ROLES"),
|
||||
_list("MODULE_EVENT_READER_ROLES"))
|
||||
assert "lexicon_app" in keys and "lexicon_migrator" not in _list("MODEL_PROVIDER_MIGRATOR_ROLES")
|
||||
assert "agora_app" in emitters and "agora_app" not in readers
|
||||
assert readers == [] and "panorama_app" not in emitters
|
||||
assert _list("MODEL_PROVIDER_MIGRATOR_ROLES") == ["arbiter_migrator"]
|
||||
|
||||
|
||||
def test_init_add_puts_each_module_in_its_tier():
|
||||
init = INIT.read_text(encoding="utf-8")
|
||||
assert "case $ADD in galena|agora|parafa|workflow|arbiter)" in init
|
||||
assert '"env/atrium.env:MODULE_EVENT_READER_ROLES"' in init
|
||||
|
||||
|
||||
def test_atrium_pins_the_core_with_the_event_reader_tier():
|
||||
"""event_grants_sql(reader_roles=...) and `managed check --events-reader` are dredd-core 0.23.0."""
|
||||
req = (ROOT / "backend" / "requirements.txt").read_text(encoding="utf-8")
|
||||
pin = re.search(r"^dredd-core @ .*@v(\d+)\.(\d+)\.(\d+)", req, re.M)
|
||||
assert pin and tuple(int(p) for p in pin.groups()) >= (0, 23, 0)
|
||||
@@ -0,0 +1,80 @@
|
||||
"""deploy/push.sh checks Parafa and Scribe (the split plan's M6, M7) with exactly the lists each declares,
|
||||
and with the platform tier each is granted.
|
||||
|
||||
Each module's evidence lists are `app.models.APPEND_ONLY_TABLES` / `NO_DELETE_TABLES`, which its 0002
|
||||
grants from and its CI's managed check passes, so push.sh's CHECK_EXTRA is compared with them wherever
|
||||
the submodule is checked out (skipped where it is not).
|
||||
|
||||
The tiers: Parafa writes the event log (`document.signed`, an EMITTER, like Agora); Scribe takes no
|
||||
part in it and calls no model, so it is in no opt-in list at all.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
PUSH = ROOT / "deploy" / "push.sh"
|
||||
INIT = ROOT / "deploy" / "init.sh"
|
||||
COMPOSE = ROOT / "deploy" / "compose.yaml"
|
||||
ATRIUM_ENV = ROOT / "deploy" / "env" / "atrium.env.example"
|
||||
MODULES = ("parafa", "scribe")
|
||||
OPT_INS = ("MODEL_PROVIDER_KEY_READER_ROLES", "MODEL_PROVIDER_MIGRATOR_ROLES", "MODULE_EVENT_EMITTER_ROLES",
|
||||
"MODULE_EVENT_READER_ROLES", "COUNTERPARTY_WRITER_ROLES", "COUNTERPARTY_READER_ROLES",
|
||||
"COUNTERPARTY_MIGRATOR_ROLES")
|
||||
|
||||
|
||||
def _tuple(src: str, name: str) -> list[str]:
|
||||
body = re.search(rf"^{name}(?:: [^=]+)? = \(([^)]*)\)", src, re.M)
|
||||
assert body, name
|
||||
return re.findall(r'"([a-z_]+)"', body.group(1))
|
||||
|
||||
|
||||
def _check_extra(slug: str) -> str:
|
||||
actual = re.search(rf'^ {slug}\)\s+UP={slug.upper()};.*?CHECK_EXTRA="([^"]*)"',
|
||||
PUSH.read_text(encoding="utf-8"), re.S | re.M)
|
||||
assert actual, f"push.sh has no {slug} branch in app_setup"
|
||||
return actual.group(1)
|
||||
|
||||
|
||||
def _list(key: str) -> list[str]:
|
||||
found = re.search(rf"^{key}=(.*)$", ATRIUM_ENV.read_text(encoding="utf-8"), re.M)
|
||||
assert found, key
|
||||
return [r.strip() for r in found.group(1).split(",") if r.strip()]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("slug", MODULES)
|
||||
def test_push_checks_each_module_with_its_own_lists(slug):
|
||||
models = ROOT / "deploy" / "modules" / slug / "backend" / "app" / "models" / "__init__.py"
|
||||
if not models.exists():
|
||||
pytest.skip(f"deploy/modules/{slug} is not checked out")
|
||||
src = models.read_text(encoding="utf-8")
|
||||
append_only, no_delete = _tuple(src, "APPEND_ONLY_TABLES"), _tuple(src, "NO_DELETE_TABLES")
|
||||
expected = " ".join([f"--append-only {' '.join(append_only)}",
|
||||
*([f"--no-delete {' '.join(no_delete)}"] if no_delete else [])])
|
||||
assert _check_extra(slug) == expected
|
||||
|
||||
|
||||
def test_the_evidence_lists_as_shipped():
|
||||
"""Without the submodules (CI), at least the lists the modules shipped with at their first pin."""
|
||||
assert _check_extra("parafa") == ("--append-only audit_log module_event module_event_receipt "
|
||||
"--no-delete signing_request")
|
||||
assert _check_extra("scribe") == "--append-only audit_log --no-delete draft_export"
|
||||
|
||||
|
||||
def test_parafa_is_an_emitter_and_scribe_is_in_no_tier():
|
||||
push, init = PUSH.read_text(encoding="utf-8"), INIT.read_text(encoding="utf-8")
|
||||
assert "case $slug in galena|agora|parafa|workflow|arbiter)" in push
|
||||
assert "case $ADD in galena|agora|parafa|workflow|arbiter)" in init
|
||||
assert "parafa_app" in _list("MODULE_EVENT_EMITTER_ROLES")
|
||||
assert "parafa_app" not in _list("MODULE_EVENT_READER_ROLES")
|
||||
for key in OPT_INS:
|
||||
assert not any(r.startswith("scribe_") for r in _list(key)), key
|
||||
|
||||
|
||||
def test_parafa_mounts_its_signer_read_only():
|
||||
compose = COMPOSE.read_text(encoding="utf-8")
|
||||
assert "- ${PARAFA_SIGNER_DIR:-./parafa-signer}:/run/parafa-signer:ro" in compose
|
||||
assert "PARAFA_SIGNER_DIR" in (ROOT / "deploy" / "lib" / "envfile.sh").read_text(encoding="utf-8")
|
||||
@@ -40,12 +40,15 @@ ATRIUM = pathlib.Path(__file__).resolve().parents[2]
|
||||
PUSH = DEPLOY / "push.sh"
|
||||
PREFLIGHT = DEPLOY / "preflight.sh"
|
||||
ENVFILE_LIB = DEPLOY / "lib" / "envfile.sh"
|
||||
FAMILY = ("atrium", "galena", "sygna", "counsel", "compass", "insider")
|
||||
#: Where an app's tree sits inside its checkout — push.sh's SUBDIR and preflight.sh's. Compass's
|
||||
#: repository is the analysis engine's and carries the application in a subdirectory; every other
|
||||
FAMILY = ("atrium", "galena", "sygna", "counsel", "insider", "arbiter", "lexicon", "agora",
|
||||
"parafa", "scribe", "workflow")
|
||||
#: Where an app's tree sits inside its checkout — push.sh's SUBDIR and preflight.sh's. Arbiter's
|
||||
#: repository also carries the analysis engine and holds the application in a subdirectory; every other
|
||||
#: app's repository is the application. The fixture has to lay the scratch tree out the same way, or
|
||||
#: it would be testing a shape no deployment has.
|
||||
SUBDIR = {"compass": "apps/compass"}
|
||||
SUBDIR = {"arbiter": "apps/arbiter"}
|
||||
#: Every app has a checkout of its own, named after it (Arbiter included since its own repository).
|
||||
CHECKOUT: dict[str, str] = {}
|
||||
#: The flags each app's own repository renders `db/managed/provision.sql` with on this platform, and
|
||||
#: the ones push.sh must therefore both check against and provision with.
|
||||
IDENTITY_FLAGS = "--identity-schema dredd --identity-owner atrium_migrator"
|
||||
@@ -135,13 +138,13 @@ def rig(tmp_path_factory):
|
||||
_write(root / "env" / f"{app}.migrate.env",
|
||||
f"MIGRATION_DATABASE_URL=postgresql+pg8000://{app}_migrator:x@postgres:5432/dredd\n")
|
||||
for app in FAMILY[1:]:
|
||||
app_root = root / "modules" / app / SUBDIR.get(app, "")
|
||||
app_root = root / "modules" / CHECKOUT.get(app, app) / SUBDIR.get(app, "")
|
||||
(app_root / "backend").mkdir(parents=True)
|
||||
_write(app_root / "db" / "managed" / "provision.sql", "-- not read by these tests\n")
|
||||
base_env = f"MODULES_DIR={root / 'modules'}\nDEPLOY_ENV_DIR={root / 'env'}\n"
|
||||
# The rig is a box with every module deployed, Compass and Insider included, so the tests above mean
|
||||
# The rig is a box with every module deployed, the switched-off ones included, so the tests above mean
|
||||
# "all of them" without each having to say so. .env.off is the same box before either was switched on.
|
||||
_write(root / ".env", base_env + "COMPOSE_PROFILES=compass,insider\n")
|
||||
_write(root / ".env", base_env + "COMPOSE_PROFILES=insider,arbiter,lexicon,agora,parafa,scribe,workflow\n")
|
||||
_write(root / ".env.off", base_env)
|
||||
# Records the command line and succeeds, so the push walks all five steps without a database.
|
||||
_write(root / "recorder.sh", '#!/usr/bin/env bash\nprintf \'%s\\n\' "$*" >> "$PUSH_TRACE"\nexit 0\n')
|
||||
@@ -156,6 +159,17 @@ HUB_ON_THE_PLATFORM = {
|
||||
"SESSION_COOKIE_NAME": "dredd_session",
|
||||
"IDENTITY_READER_ROLES": ",".join(f"{app}_app" for app in FAMILY[1:]),
|
||||
"IDENTITY_MIGRATOR_ROLES": ",".join(f"{app}_migrator" for app in FAMILY[1:]),
|
||||
# The modules taking part in the shared event log (dredd-core 0.20.0), init.sh's default.
|
||||
"MODULE_EVENT_EMITTER_ROLES": "galena_app,agora_app,parafa_app,workflow_app,arbiter_app",
|
||||
# The event log's reader tier (dredd-core 0.23.0; empty since Panorama left) and the key readers.
|
||||
"MODULE_EVENT_READER_ROLES": "",
|
||||
"MODEL_PROVIDER_KEY_READER_ROLES": "arbiter_app,lexicon_app",
|
||||
# The shared counterparty register (dredd-core 0.21.0), init.sh's default: Sygna writes and its
|
||||
# migrator moves its own rows in through the hub's import door; Galena writes too, Agora and
|
||||
# Parafa read, and every one's migrator holds REFERENCES (spec 2026-11-25 part A).
|
||||
"COUNTERPARTY_WRITER_ROLES": "sygna_app,galena_app",
|
||||
"COUNTERPARTY_READER_ROLES": "agora_app,parafa_app",
|
||||
"COUNTERPARTY_MIGRATOR_ROLES": "sygna_migrator,galena_migrator,agora_migrator,parafa_migrator",
|
||||
}
|
||||
|
||||
|
||||
@@ -297,17 +311,74 @@ class TestTheHalfDoneShapesOfOneAccountAreRefused:
|
||||
done, trace = _push(rig, platform=True, trace="unlisted", settings={"atrium": {
|
||||
"IDENTITY_READER_ROLES": "galena_app,sygna_app,counsel_app"}})
|
||||
assert done.returncode == 2, done.stdout + done.stderr
|
||||
assert "compass: " in done.stderr
|
||||
assert "does not list compass_app in IDENTITY_READER_ROLES:" in done.stderr # and only that one
|
||||
assert "insider: " in done.stderr
|
||||
assert "does not list insider_app in IDENTITY_READER_ROLES:" in done.stderr
|
||||
assert "app.identity_grants" in done.stderr # the late-joiner fix is named too
|
||||
assert "0007_compass_joins" not in done.stderr # no revision needed any more
|
||||
assert trace == ""
|
||||
|
||||
def test_a_module_taking_part_in_events_the_hub_would_not_grant_is_refused(self, rig):
|
||||
"""Galena, Agora and Parafa are checked with --events; a hub that does not list them in
|
||||
MODULE_EVENT_EMITTER_ROLES grants them nothing on the log, and the check would fail late."""
|
||||
done, trace = _push(rig, platform=True, trace="no-emitters", settings={"atrium": {
|
||||
"MODULE_EVENT_EMITTER_ROLES": "galena_app"}})
|
||||
assert done.returncode == 2, done.stdout + done.stderr
|
||||
assert "does not list agora_app in MODULE_EVENT_EMITTER_ROLES" in done.stderr
|
||||
assert "galena_app in MODULE_EVENT_EMITTER_ROLES" not in done.stderr
|
||||
assert trace == ""
|
||||
|
||||
def test_a_module_needing_the_counterparty_register_the_hub_would_not_grant_is_refused(self, rig):
|
||||
"""Sygna (on dredd-core 0.21.0+) moves its counterparties into the shared register: a hub
|
||||
that lists neither tier for it, or not its migrator, is refused up front."""
|
||||
done, trace = _push(rig, platform=True, trace="no-counterparties", settings={"atrium": {
|
||||
"COUNTERPARTY_WRITER_ROLES": "galena_app",
|
||||
"COUNTERPARTY_MIGRATOR_ROLES": "galena_migrator,agora_migrator,parafa_migrator"}})
|
||||
assert done.returncode == 2, done.stdout + done.stderr
|
||||
assert ("lists sygna_app in neither COUNTERPARTY_WRITER_ROLES nor "
|
||||
"COUNTERPARTY_READER_ROLES") in done.stderr
|
||||
assert "does not list sygna_migrator in COUNTERPARTY_MIGRATOR_ROLES" in done.stderr
|
||||
assert trace == ""
|
||||
|
||||
def test_each_module_is_checked_with_the_counterparty_tier_the_hub_grants_it(self, rig):
|
||||
done, trace = _push(rig, platform=True, trace="cp-tiers", settings={"atrium": {
|
||||
# Galena, Agora and Parafa point foreign keys at the register (CP_NEEDED), so the hub has to
|
||||
# list all three; Galena as a reader here, to prove the check follows the listed tier.
|
||||
"COUNTERPARTY_WRITER_ROLES": "sygna_app",
|
||||
"COUNTERPARTY_READER_ROLES": "galena_app,agora_app,parafa_app"}})
|
||||
assert done.returncode == 0, done.stdout + done.stderr
|
||||
checks = {app: [line for line in trace.splitlines()
|
||||
if "managed check" in line and f"--app-role {app}_app" in line]
|
||||
for app in FAMILY}
|
||||
assert all(checks.values()), checks
|
||||
assert all("--counterparties writer" in line for line in checks["sygna"])
|
||||
assert all("--counterparties reader" in line for line in checks["galena"])
|
||||
assert all("--counterparties" not in line
|
||||
for app in ("atrium", "counsel", "insider") for line in checks[app])
|
||||
|
||||
def test_a_module_on_an_older_core_is_not_checked_with_the_counterparty_flag(self, rig):
|
||||
"""A module held on an older dredd-core (here Sygna on 0.18.1): its `managed check` has no
|
||||
--counterparties flag, and its revisions move nothing, so the preflight asks nothing of it."""
|
||||
reqs = rig / "modules" / "sygna" / "backend" / "requirements.txt"
|
||||
reqs.write_text("dredd-core @ git+http://77.216.148.202:3000/Haski/dredd-core.git@v0.18.1\n",
|
||||
encoding="utf-8")
|
||||
try:
|
||||
done, trace = _push(rig, platform=True, trace="cp-old", settings={"atrium": {
|
||||
"COUNTERPARTY_WRITER_ROLES": "galena_app",
|
||||
"COUNTERPARTY_MIGRATOR_ROLES": "galena_migrator,agora_migrator,parafa_migrator"}})
|
||||
finally:
|
||||
reqs.unlink()
|
||||
assert done.returncode == 0, done.stdout + done.stderr
|
||||
sygna = [line for line in trace.splitlines()
|
||||
if "managed check" in line and "--app-role sygna_app" in line]
|
||||
assert sygna and all("--counterparties" not in line for line in sygna)
|
||||
|
||||
def test_the_lists_are_read_the_way_atrium_reads_them(self, rig):
|
||||
"""Atrium strips each comma-separated name, so a space after a comma is a valid list there
|
||||
and must not be a refusal here."""
|
||||
done, _ = _push(rig, platform=True, trace="spaces", settings={"atrium": {
|
||||
"IDENTITY_READER_ROLES": "galena_app, sygna_app, counsel_app, compass_app, insider_app"}})
|
||||
"IDENTITY_READER_ROLES": "galena_app, sygna_app, counsel_app, insider_app, arbiter_app, "
|
||||
"lexicon_app, agora_app, parafa_app, scribe_app, "
|
||||
"workflow_app"}})
|
||||
assert done.returncode == 0, done.stdout + done.stderr
|
||||
|
||||
@pytest.mark.parametrize("cookie, shown", [("galena_session", "galena_session"),
|
||||
@@ -329,13 +400,13 @@ class TestTheHalfDoneShapesOfOneAccountAreRefused:
|
||||
assert trace.count("--identity-schema dredd --identity-tier") == 2 * len(FAMILY)
|
||||
|
||||
def test_a_listed_role_this_push_does_not_provision_is_a_note_not_a_refusal(self, rig):
|
||||
"""Compass listed but switched off. Harmless where Atrium is at its head; fatal on a fresh
|
||||
"""Insider listed but switched off. Harmless where Atrium is at its head; fatal on a fresh
|
||||
database, where its grant refuses a role that does not exist. Only the database knows which,
|
||||
so the plan says it and the push goes on."""
|
||||
done, _ = _push(rig, platform=True, trace="listed-off", compose_env=".env.off")
|
||||
assert done.returncode == 0, done.stdout + done.stderr
|
||||
assert "lists compass_app, which this push does not provision" in done.stdout
|
||||
assert "lists compass_migrator, which this push does not provision" in done.stdout
|
||||
assert "lists insider_app, which this push does not provision" in done.stdout
|
||||
assert "lists insider_migrator, which this push does not provision" in done.stdout
|
||||
|
||||
def test_a_standalone_push_checks_a_one_account_rendering_as_one(self, rig):
|
||||
"""Standalone is the opt-out, and every repository's committed provision.sql is the one-account
|
||||
@@ -491,14 +562,14 @@ class TestTheCommittedSqlMatchesTheFlagsThePushUses:
|
||||
assert "STALE" in without.stderr
|
||||
|
||||
@pytest.mark.parametrize("slug,extension", [("galena", "pgcrypto"), ("sygna", None),
|
||||
("counsel", "pg_trgm"), ("compass", "pgcrypto"),
|
||||
("insider", None)])
|
||||
("counsel", "pg_trgm"), ("insider", None),
|
||||
("arbiter", None)])
|
||||
def test_each_module_checkout_matches_when_it_is_present(self, render, slug, extension):
|
||||
"""The module checkouts are submodules and may not be fetched (CI does not need them), so
|
||||
this skips rather than fails — but where they ARE present it is the same assertion against
|
||||
the real committed file, which is what a deploy compares."""
|
||||
# SUBDIR: Compass's app is apps/compass inside its checkout. Without it this looked for
|
||||
# deploy/modules/compass/db/... and skipped Compass on every machine, checkout or not.
|
||||
# SUBDIR: Arbiter's app is apps/arbiter inside its checkout. Without it this would look for
|
||||
# deploy/modules/arbiter/db/... and skip Arbiter on every machine, checkout or not.
|
||||
target = DEPLOY / "modules" / slug / SUBDIR.get(slug, "") / "db" / "managed" / "provision.sql"
|
||||
if not target.exists():
|
||||
pytest.skip(f"no {slug} checkout at {target.parent}")
|
||||
@@ -509,8 +580,8 @@ class TestTheCommittedSqlMatchesTheFlagsThePushUses:
|
||||
assert done.returncode == 0, done.stdout + done.stderr
|
||||
|
||||
|
||||
class TestCompassShipsSwitchedOff:
|
||||
"""Compass is in the kit before it is deployed anywhere, and a box that has not deployed it must
|
||||
class TestArbiterShipsSwitchedOff:
|
||||
"""Arbiter is in the kit before it is deployed anywhere, and a box that has not deployed it must
|
||||
notice nothing: no refusal over env files nobody has written, no push held up, no service started.
|
||||
|
||||
compose.yaml carries the same switch as a profile; preflight.sh step 2c proves that half with a
|
||||
@@ -528,13 +599,13 @@ class TestCompassShipsSwitchedOff:
|
||||
done, trace = _push(rig, platform=False, trace="off", compose_env=".env.off")
|
||||
assert done.returncode == 0, done.stdout + done.stderr
|
||||
assert self._schemas(trace) == {"atrium", "galena", "sygna", "counsel"}
|
||||
assert "compass is switched off" in done.stdout
|
||||
assert "arbiter is switched off" in done.stdout
|
||||
|
||||
def test_naming_it_pushes_it_anyway_and_warns_that_up_will_not_start_it(self, rig):
|
||||
done, trace = _push(rig, "compass", platform=False, trace="named", compose_env=".env.off")
|
||||
done, trace = _push(rig, "arbiter", platform=False, trace="named", compose_env=".env.off")
|
||||
assert done.returncode == 0, done.stdout + done.stderr
|
||||
assert self._schemas(trace) == {"compass"}
|
||||
assert "will not start compass-backend" in done.stdout
|
||||
assert self._schemas(trace) == {"arbiter"}
|
||||
assert "will not start arbiter-backend" in done.stdout
|
||||
|
||||
def test_switched_on_the_default_is_all_of_them(self, rig):
|
||||
done, trace = _push(rig, platform=False, trace="on")
|
||||
@@ -544,7 +615,7 @@ class TestCompassShipsSwitchedOff:
|
||||
|
||||
def test_insider_follows_its_own_profile(self, rig):
|
||||
"""Insider ships switched off the same way, under its own profile: off, a push with no app
|
||||
named leaves it out and says so; named, it is pushed with the same warning as Compass."""
|
||||
named leaves it out and says so; named, it is pushed with the same warning as Arbiter."""
|
||||
done, trace = _push(rig, platform=False, trace="insider-off", compose_env=".env.off")
|
||||
assert done.returncode == 0, done.stdout + done.stderr
|
||||
assert "insider" not in self._schemas(trace)
|
||||
@@ -561,7 +632,7 @@ class TestCompassShipsSwitchedOff:
|
||||
trace_file = rig / "shell.txt"
|
||||
trace_file.write_text("", encoding="utf-8")
|
||||
env = {
|
||||
"PATH": os.environ["PATH"], "PUSH_TRACE": str(trace_file), "COMPOSE_PROFILES": "compass",
|
||||
"PATH": os.environ["PATH"], "PUSH_TRACE": str(trace_file), "COMPOSE_PROFILES": "arbiter",
|
||||
**{f"{app.upper()}_PYTHON": str(rig / "recorder.sh") for app in FAMILY},
|
||||
}
|
||||
done = subprocess.run(
|
||||
@@ -569,7 +640,7 @@ class TestCompassShipsSwitchedOff:
|
||||
capture_output=True, text=True, env=env, stdin=subprocess.DEVNULL, cwd=str(DEPLOY),
|
||||
)
|
||||
assert done.returncode == 0, done.stdout + done.stderr
|
||||
assert "compass" in self._schemas(trace_file.read_text(encoding="utf-8"))
|
||||
assert "arbiter" in self._schemas(trace_file.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
@needs_bash
|
||||
@@ -595,23 +666,22 @@ class TestEveryAppIsProvisionedBeforeAnyMigrates:
|
||||
assert done.returncode == 0, done.stdout + done.stderr
|
||||
assert "every app is provisioned before any migrates" in done.stdout
|
||||
|
||||
def test_the_budget_counts_compass_only_when_it_runs(self, rig):
|
||||
def test_the_budget_counts_a_module_only_when_it_runs(self, rig):
|
||||
on, _ = _push(rig, "--dry-run", platform=False, trace="budget-on")
|
||||
off, _ = _push(rig, "--dry-run", platform=False, trace="budget-off", compose_env=".env.off")
|
||||
assert re.search(r"budget\s+6 apps x", on.stdout), on.stdout
|
||||
assert re.search(r"budget\s+11 apps x", on.stdout), on.stdout # Panorama left
|
||||
assert re.search(r"budget\s+4 apps x", off.stdout), off.stdout
|
||||
|
||||
|
||||
@needs_bash
|
||||
class TestALocalPushLeavesFileWritingSeedsToTheServer:
|
||||
"""--local runs each app's Python on this machine against the server's database. A seed that writes
|
||||
files would put its rows on the server and its files here: Galena's demo repository, and since its
|
||||
demo set Compass's contracts. Both seeds wait for the server's own <app>-migrate."""
|
||||
files would put its rows on the server and its files here: Galena's demo repository. That seed waits
|
||||
for the server's own galena-migrate."""
|
||||
|
||||
def test_galena_and_compass_migrate_without_their_seed(self, rig):
|
||||
def test_galena_migrates_without_its_seed(self, rig):
|
||||
done, trace = _push(rig, platform=True, trace="local-seeds")
|
||||
assert done.returncode == 0, done.stdout + done.stderr
|
||||
for slug in ("galena", "compass"):
|
||||
assert f"seed skipped: {slug}'s seed writes files" in done.stdout, done.stdout
|
||||
assert "seed skipped: galena's seed writes files" in done.stdout, done.stdout
|
||||
seeded = [line for line in trace.splitlines() if "app.seed" in line]
|
||||
assert len(seeded) == len(FAMILY) - 2, trace # atrium, sygna and counsel still seed from here
|
||||
assert len(seeded) == len(FAMILY) - 1, trace # every app but galena still seeds from here
|
||||
|
||||
@@ -306,6 +306,6 @@ def test_init_refuses_a_tls_it_cannot_serve(tmp_path, args, expected):
|
||||
@needs_bash
|
||||
def test_add_takes_no_tls_flags(tmp_path):
|
||||
assert _init(tmp_path, "--domain", "dredd.example.org").returncode == 0
|
||||
done = subprocess.run([BASH, str(DEPLOY / "init.sh"), "--into", str(tmp_path / "out"), "--add", "compass",
|
||||
done = subprocess.run([BASH, str(DEPLOY / "init.sh"), "--into", str(tmp_path / "out"), "--add", "insider",
|
||||
"--tls"], capture_output=True, text=True, timeout=300)
|
||||
assert done.returncode == 2 and "takes no option but --into" in done.stderr
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
"""deploy/push.sh checks Workflow with exactly the lists it declares, and with the platform tier it is granted.
|
||||
|
||||
Its evidence lists are `app.models.APPEND_ONLY_TABLES` / `NO_DELETE_TABLES`, which its revisions grant
|
||||
from, so push.sh's CHECK_EXTRA is compared with them wherever the submodule is checked out (skipped
|
||||
where it is not).
|
||||
|
||||
The tier: every step of a run writes the event log (dredd_core.workflow_contract), so Workflow is an
|
||||
EMITTER, like Agora and Parafa; it calls no model and keeps no counterparties.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import pathlib
|
||||
|
||||
import pytest
|
||||
|
||||
from test_deploy_m6_m7_check_args import OPT_INS, _check_extra, _list, _tuple
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
SHIPPED = ("--append-only audit_log module_event module_event_receipt workflow_event "
|
||||
"--no-delete workflow_run request workflow_template request_type approver_group")
|
||||
|
||||
|
||||
def test_push_checks_workflow_with_its_own_lists():
|
||||
models = ROOT / "deploy" / "modules" / "workflow" / "backend" / "app" / "models" / "__init__.py"
|
||||
if not models.exists():
|
||||
pytest.skip("deploy/modules/workflow is not checked out")
|
||||
src = models.read_text(encoding="utf-8")
|
||||
expected = (f"--append-only {' '.join(_tuple(src, 'APPEND_ONLY_TABLES'))} "
|
||||
f"--no-delete {' '.join(_tuple(src, 'NO_DELETE_TABLES'))}")
|
||||
assert _check_extra("workflow") == expected
|
||||
|
||||
|
||||
def test_the_evidence_lists_as_shipped():
|
||||
"""Without the submodule (CI), at least the lists Workflow shipped with at its first pin."""
|
||||
assert _check_extra("workflow") == SHIPPED
|
||||
|
||||
|
||||
def test_workflow_is_an_emitter_and_in_no_other_tier():
|
||||
assert "workflow_app" in _list("MODULE_EVENT_EMITTER_ROLES")
|
||||
for key in OPT_INS:
|
||||
if key != "MODULE_EVENT_EMITTER_ROLES":
|
||||
assert not any(r.startswith("workflow_") for r in _list(key)), key
|
||||
|
||||
|
||||
def test_workflow_is_offered_to_an_instance_seeded_before_it():
|
||||
from app import frontdoor
|
||||
from app.seed import ADDED_AFTER_FIRST_SEED, FAMILY
|
||||
|
||||
entry = next(e for e in FAMILY if e["slug"] == "workflow")
|
||||
assert "workflow" in ADDED_AFTER_FIRST_SEED and "workflow" in frontdoor.MODULES
|
||||
assert (entry["hue"], entry["glyph"]) == ("gray", "clock")
|
||||
@@ -145,7 +145,7 @@ def test_root_redirects_to_atrium():
|
||||
assert r.header(b"x-content-type-options") == b"nosniff"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("slug", ["atrium", "galena", "sygna", "counsel", "compass", "insider"])
|
||||
@pytest.mark.parametrize("slug", ["atrium", "galena", "sygna", "counsel", "insider", "arbiter"])
|
||||
def test_bare_slug_gets_its_slash(slug):
|
||||
fd, up = door()
|
||||
r = run(call(fd, "POST", f"/{slug}".encode(), query=b"a=1"))
|
||||
@@ -154,7 +154,7 @@ def test_bare_slug_gets_its_slash(slug):
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", [b"/nope", b"/nope/x", b"/galenax/", b"/counsel/x", b"/favicon.ico",
|
||||
b"/compass/", b"/insider/"])
|
||||
b"/compass/", b"/compass", b"/insider/"])
|
||||
def test_unknown_or_unconfigured_is_the_plain_404(path):
|
||||
fd, up = door()
|
||||
r = run(call(fd, "GET", path))
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Trends on Atrium's home. DB-free: the pure parts, the compiled SQL, and the guard."""
|
||||
from __future__ import annotations
|
||||
|
||||
import datetime as dt
|
||||
import types
|
||||
import uuid
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
from app import deps
|
||||
from app.db import get_db
|
||||
from app.services import trends
|
||||
|
||||
D = dt.date(2026, 11, 1)
|
||||
|
||||
|
||||
def _sql(stmt) -> str:
|
||||
return str(stmt.compile(dialect=postgresql.dialect()))
|
||||
|
||||
|
||||
def test_a_document_is_measured_from_its_first_version_to_its_signature():
|
||||
m = {"created": D, "approved": D + dt.timedelta(days=3), "signed": D + dt.timedelta(days=10)}
|
||||
assert trends.measure(m) == 10
|
||||
|
||||
|
||||
def test_a_document_without_a_milestone_or_out_of_order_is_left_out():
|
||||
assert trends.measure({"created": D, "approved": D, "signed": None}) == "missing"
|
||||
assert trends.measure({"created": None, "approved": D, "signed": D}) == "missing"
|
||||
assert trends.measure({"created": D, "signed": D - dt.timedelta(days=1)}) == "order"
|
||||
|
||||
|
||||
def test_the_new_kinds_have_labels():
|
||||
assert {"analysis.accepted", "negotiation.round_received"} <= set(trends.KIND_LABELS)
|
||||
|
||||
|
||||
def test_the_activity_groups_by_the_very_day_expression_it_selects():
|
||||
sql = _sql(trends.activity_statement(D - dt.timedelta(days=29), D))
|
||||
day = "date(timezone('Europe/Warsaw', module_event.created_at))"
|
||||
select_part, group_part = sql.split("GROUP BY")
|
||||
assert select_part.startswith(f"SELECT {day} AS day")
|
||||
assert group_part.strip().startswith(day)
|
||||
assert group_part.count(day) == 1
|
||||
|
||||
|
||||
def test_milestones_read_only_the_recent_events():
|
||||
sql = _sql(trends.milestones_statement(D))
|
||||
where = sql.split("WHERE")[1].split("GROUP BY")[0]
|
||||
assert "module_event.created_at >= %(created_at_1)s" in where
|
||||
|
||||
|
||||
def test_without_a_log_nothing_is_read():
|
||||
db = types.SimpleNamespace(execute=lambda *a, **k: (_ for _ in ()).throw(AssertionError))
|
||||
assert trends.activity(db, "absent")["days"] == []
|
||||
assert trends.durations(db, "no_grant")["measured"] == 0
|
||||
|
||||
|
||||
def test_trends_are_refused_to_a_non_administrator():
|
||||
from app.main import app
|
||||
|
||||
person = types.SimpleNamespace(id=uuid.uuid4(), is_admin=False, is_active=True)
|
||||
app.dependency_overrides[deps.get_current_user] = lambda: person
|
||||
app.dependency_overrides[get_db] = lambda: types.SimpleNamespace(
|
||||
execute=lambda *a, **k: (_ for _ in ()).throw(AssertionError("no query for a refusal")))
|
||||
try:
|
||||
r = TestClient(app).get("/api/v1/home/trends")
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
assert r.status_code == 403, r.text
|
||||
@@ -23,7 +23,13 @@ import types
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from dredd_core.identity import MODEL_PROVIDER_TABLES, SHARED_IDENTITY_TABLES
|
||||
from dredd_core.identity import (
|
||||
COUNTERPARTY_TABLES,
|
||||
EVENT_TABLES,
|
||||
MODEL_PROVIDER_TABLES,
|
||||
SHARED_IDENTITY_TABLES,
|
||||
)
|
||||
from dredd_core.routes import iter_routes
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.routing import APIRoute
|
||||
from fastapi.testclient import TestClient
|
||||
@@ -143,8 +149,8 @@ class TestOnlyASignInMints:
|
||||
yield from calls(d)
|
||||
|
||||
out = set()
|
||||
for route in app.routes:
|
||||
if isinstance(route, APIRoute) and deps.require_session_credential in set(calls(route.dependant)):
|
||||
for orig, route in iter_routes(app.routes):
|
||||
if isinstance(orig, APIRoute) and deps.require_session_credential in set(calls(route.dependant)):
|
||||
out |= {(m, route.path) for m in route.methods}
|
||||
return out
|
||||
|
||||
@@ -477,9 +483,11 @@ class TestTheLifespanAssertsTheIdentitySchema:
|
||||
monkeypatch.setattr(app_main, "assert_identity_schema",
|
||||
lambda c, **kw: calls.append((c, kw)))
|
||||
self._boot(app_main)
|
||||
# The model providers too (dredd-core 0.15.0, revision 0009): a local copy is a shadow.
|
||||
# The model providers too (dredd-core 0.15.0, revision 0009), and the event log (0.20.0,
|
||||
# revision 0011): a local copy of either is a shadow.
|
||||
assert calls == [(conn, {"own_schema": "atrium", "identity_schema": "dredd",
|
||||
"tables": SHARED_IDENTITY_TABLES | MODEL_PROVIDER_TABLES})]
|
||||
"tables": SHARED_IDENTITY_TABLES | MODEL_PROVIDER_TABLES
|
||||
| EVENT_TABLES | COUNTERPARTY_TABLES})]
|
||||
|
||||
def test_a_failing_guard_stops_the_boot(self, monkeypatch):
|
||||
from app import main as app_main
|
||||
|
||||
@@ -16,6 +16,8 @@ from app import identity_grants
|
||||
from app.config import Settings
|
||||
|
||||
_AMBIENT = ("IDENTITY_SCHEMA", "IDENTITY_READER_ROLES", "IDENTITY_MIGRATOR_ROLES", "DB_APP_ROLE",
|
||||
"MODULE_EVENT_EMITTER_ROLES", "MODULE_EVENT_READER_ROLES", "COUNTERPARTY_WRITER_ROLES", "COUNTERPARTY_READER_ROLES",
|
||||
"COUNTERPARTY_MIGRATOR_ROLES",
|
||||
"DATABASE_URL", "MIGRATION_DATABASE_URL")
|
||||
|
||||
|
||||
@@ -266,3 +268,206 @@ def test_revision_0009_carries_no_bind_parameter_lookalikes():
|
||||
assert "%" not in sql
|
||||
assert not re.search(r"(?<!:):[A-Za-z_]", sql), sql
|
||||
assert s.shares_identity
|
||||
|
||||
|
||||
def test_revision_0010_runs_cores_three_steps_in_order_with_no_bind_parameter_lookalikes():
|
||||
"""dredd-core 0.18.0's hub revision: key_mode column, then the tables, then the grant block
|
||||
(through `model_provider_statements`, i.e. 0009's arguments) — in that order, in both shapes."""
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from dredd_core import model_providers as mp
|
||||
|
||||
sql = mp.model_provider_key_mode_sql("dredd")
|
||||
assert "%" not in sql and not re.search(r"(?<!:):[A-Za-z_]", sql), sql
|
||||
source = (Path(__file__).resolve().parents[1] / "alembic" / "versions"
|
||||
/ "0010_model_provider_user_keys.py").read_text(encoding="utf-8")
|
||||
platform = source.split("identity = settings.identity_schema", 1)[1]
|
||||
steps = ["model_provider_key_mode_sql(identity)", "create_model_provider_tables(bind, identity)",
|
||||
"model_provider_statements(settings, owner, bind)"]
|
||||
assert [platform.index(s) for s in steps] == sorted(platform.index(s) for s in steps)
|
||||
standalone = source.split("if not settings.shares_identity:", 1)[1].split("return", 1)[0]
|
||||
assert standalone.index("model_provider_key_mode_sql(own)") < standalone.index(
|
||||
"create_model_provider_tables(bind, own)") < standalone.index("runtime_grants_sql(")
|
||||
assert 'down_revision = "0009"' in source
|
||||
|
||||
|
||||
# ── the module events (dredd-core 0.20.0, revision 0011) ───────────────────────
|
||||
|
||||
class TestEventEmitters:
|
||||
def test_the_hub_always_and_the_listed_modules_once_joined(self):
|
||||
tiers = identity_grants.event_emitters(_platform(
|
||||
identity_reader_roles="galena_app",
|
||||
module_event_emitter_roles="galena_app, compass_app"))
|
||||
assert tiers == {"emitters": ["atrium_app", "galena_app"], "readers": [], "pending": ["compass_app"]}
|
||||
|
||||
def test_a_reader_not_listed_reaches_nothing(self):
|
||||
tiers = identity_grants.event_emitters(_platform(
|
||||
identity_reader_roles="galena_app,sygna_app,compass_app",
|
||||
module_event_emitter_roles="galena_app,compass_app"))
|
||||
assert "sygna_app" not in tiers["emitters"]
|
||||
assert tiers["emitters"] == ["atrium_app", "galena_app", "compass_app"]
|
||||
|
||||
def test_the_hub_listed_again_is_not_a_second_grantee(self):
|
||||
tiers = identity_grants.event_emitters(_platform(module_event_emitter_roles="atrium_app"))
|
||||
assert tiers == {"emitters": ["atrium_app"], "readers": [], "pending": []}
|
||||
|
||||
def test_the_reader_tier_once_joined(self):
|
||||
"""dredd-core 0.23.0: MODULE_EVENT_READER_ROLES is SELECT only, joined like an
|
||||
emitter, and never added to the emitters. No module uses it since Panorama
|
||||
left the platform, so the role here is a stand-in."""
|
||||
tiers = identity_grants.event_emitters(_platform(
|
||||
identity_reader_roles="galena_app,agora_app,reporter_app",
|
||||
module_event_emitter_roles="galena_app,agora_app",
|
||||
module_event_reader_roles="reporter_app, lexicon_app"))
|
||||
assert tiers == {"emitters": ["atrium_app", "galena_app", "agora_app"],
|
||||
"readers": ["reporter_app"], "pending": ["lexicon_app"]}
|
||||
|
||||
def test_the_readers_reach_the_grant_block(self, monkeypatch):
|
||||
monkeypatch.setattr(identity_grants, "event_table_exists", lambda conn, s: True)
|
||||
sql = identity_grants.event_statements(_platform(
|
||||
identity_reader_roles="reporter_app", module_event_reader_roles="reporter_app"),
|
||||
"atrium_migrator", object())
|
||||
assert len(sql) == 2 and "reporter_app" in sql[1]
|
||||
|
||||
def test_a_role_in_both_tiers_is_refused(self, monkeypatch):
|
||||
monkeypatch.setattr(identity_grants, "event_table_exists", lambda conn, s: True)
|
||||
with pytest.raises(identity_grants.GrantsRefused, match="MODULE_EVENT_READER_ROLES"):
|
||||
identity_grants.event_statements(_platform(
|
||||
identity_reader_roles="reporter_app", module_event_emitter_roles="reporter_app",
|
||||
module_event_reader_roles="reporter_app"), "atrium_migrator", object())
|
||||
|
||||
def test_standalone_renders_nothing(self):
|
||||
assert identity_grants.event_statements(_settings(), "atrium_migrator", None) == []
|
||||
|
||||
def test_nothing_before_0011_created_the_table(self, monkeypatch):
|
||||
monkeypatch.setattr(identity_grants, "event_table_exists", lambda conn, s: False)
|
||||
assert identity_grants.event_statements(_platform(), "atrium_migrator", object()) == []
|
||||
|
||||
def test_the_policies_then_the_grant_block(self, monkeypatch):
|
||||
from dredd_core import events
|
||||
|
||||
monkeypatch.setattr(identity_grants, "event_table_exists", lambda conn, s: True)
|
||||
s = _platform(module_event_emitter_roles="galena_app,compass_app")
|
||||
out = identity_grants.event_statements(s, "atrium_migrator", object())
|
||||
assert out == [events.event_policies_sql("dredd"),
|
||||
events.event_grants_sql("dredd", owner_role="atrium_migrator",
|
||||
emitter_roles=["atrium_app", "galena_app",
|
||||
"compass_app"])]
|
||||
|
||||
def test_a_bad_name_is_refused_before_anything_connects(self, monkeypatch):
|
||||
monkeypatch.setattr(identity_grants, "event_table_exists", lambda conn, s: True)
|
||||
s = _platform(identity_reader_roles="galena-app", module_event_emitter_roles="galena-app")
|
||||
with pytest.raises(identity_grants.GrantsRefused, match="MODULE_EVENT_EMITTER_ROLES"):
|
||||
identity_grants.event_statements(s, "atrium_migrator", object())
|
||||
|
||||
|
||||
def test_revision_0011_runs_the_hubs_three_steps_in_order_with_no_bind_parameter_lookalikes():
|
||||
"""dredd-core 0.20.0's hub revision: the table, then (via `event_statements`) the policies and
|
||||
the grant block — in that order; standalone the log is Atrium's own, append-only in the sweep."""
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from dredd_core import events
|
||||
|
||||
for sql in (events.event_policies_sql("dredd"), events.event_policies_sql(),
|
||||
events.event_grants_sql("dredd", owner_role="atrium_migrator",
|
||||
emitter_roles=["atrium_app", "galena_app"])):
|
||||
assert "%" not in sql and not re.search(r"(?<!:):[A-Za-z_]", sql), sql
|
||||
source = (Path(__file__).resolve().parents[1] / "alembic" / "versions"
|
||||
/ "0011_module_events.py").read_text(encoding="utf-8")
|
||||
fstrings = re.findall(r'f?"((?:SELECT|DROP|WHERE|AND)[^"]*)"', source)
|
||||
for sql in fstrings:
|
||||
assert "%" not in sql and not re.search(r"(?<!:):[A-Za-z_]", sql), sql
|
||||
platform = source.split("identity = settings.identity_schema", 1)[1]
|
||||
steps = ["create_event_tables(bind, identity)", "DROP TABLE",
|
||||
"event_statements(settings, owner, bind)"]
|
||||
assert [platform.index(s) for s in steps] == sorted(platform.index(s) for s in steps)
|
||||
standalone = source.split("if not settings.shares_identity:", 1)[1].split("return", 1)[0]
|
||||
assert standalone.index("create_event_tables(bind, own)") < standalone.index(
|
||||
"event_policies_sql()") < standalone.index("runtime_grants_sql(")
|
||||
assert 'APPEND_ONLY = ("audit_log", "module_event")' in source
|
||||
assert 'down_revision = "0010"' in source
|
||||
# Lazily imported: a module-level import would register the event models before 0001's
|
||||
# create_all ran on a fresh database, and build local shadows of them.
|
||||
assert not re.search(r"^from dredd_core(\.events)? import .*events", source, re.M)
|
||||
|
||||
|
||||
# ── the counterparty register (dredd-core 0.21.0, revision 0012) ───────────────
|
||||
|
||||
class TestCounterpartyTiers:
|
||||
def test_writers_readers_and_migrators_once_joined(self):
|
||||
tiers = identity_grants.counterparty_tiers(_platform(
|
||||
identity_reader_roles="sygna_app,galena_app",
|
||||
identity_migrator_roles="sygna_migrator",
|
||||
counterparty_writer_roles="sygna_app",
|
||||
counterparty_reader_roles="galena_app, compass_app",
|
||||
counterparty_migrator_roles="sygna_migrator,compass_migrator"))
|
||||
assert tiers == {"writers": ["sygna_app"], "readers": ["galena_app"],
|
||||
"migrators": ["sygna_migrator"],
|
||||
"pending": ["compass_app", "compass_migrator"]}
|
||||
|
||||
def test_a_role_in_both_lists_is_a_writer_and_the_hub_is_never_a_grantee(self):
|
||||
tiers = identity_grants.counterparty_tiers(_platform(
|
||||
identity_reader_roles="compass_app",
|
||||
counterparty_writer_roles="compass_app,atrium_app",
|
||||
counterparty_reader_roles="compass_app,atrium_app"))
|
||||
assert tiers["writers"] == ["compass_app"] and tiers["readers"] == []
|
||||
|
||||
def test_standalone_renders_nothing(self):
|
||||
assert identity_grants.counterparty_statements(_settings(), "atrium_migrator", None) == []
|
||||
|
||||
def test_nothing_before_0012_created_the_tables(self, monkeypatch):
|
||||
monkeypatch.setattr(identity_grants, "counterparty_tables_exist", lambda conn, s: False)
|
||||
assert identity_grants.counterparty_statements(_platform(), "atrium_migrator", object()) == []
|
||||
|
||||
def test_the_grant_block_then_the_door(self, monkeypatch):
|
||||
from dredd_core import counterparties as cp
|
||||
|
||||
monkeypatch.setattr(identity_grants, "counterparty_tables_exist", lambda conn, s: True)
|
||||
s = _platform(identity_reader_roles="sygna_app,compass_app",
|
||||
identity_migrator_roles="compass_migrator",
|
||||
counterparty_writer_roles="sygna_app", counterparty_reader_roles="compass_app",
|
||||
counterparty_migrator_roles="compass_migrator")
|
||||
grants = cp.counterparty_grants_sql("dredd", owner_role="atrium_migrator",
|
||||
writer_roles=["sygna_app"], reader_roles=["compass_app"],
|
||||
migrator_roles=["compass_migrator"])
|
||||
monkeypatch.setattr(identity_grants, "counterparty_door_wanted", lambda c, s, i: True)
|
||||
assert identity_grants.counterparty_statements(s, "atrium_migrator", object()) == [
|
||||
grants, *cp.counterparty_import_sql("dredd", owner_role="atrium_migrator",
|
||||
importer_roles=["compass_migrator"])]
|
||||
monkeypatch.setattr(identity_grants, "counterparty_door_wanted", lambda c, s, i: False)
|
||||
assert identity_grants.counterparty_statements(s, "atrium_migrator", object()) == [
|
||||
grants, cp.drop_counterparty_import_sql("dredd")]
|
||||
|
||||
def test_no_importer_no_door(self):
|
||||
assert identity_grants.counterparty_door_wanted(None, "dredd", []) is False
|
||||
|
||||
def test_a_bad_name_is_refused_before_anything_connects(self, monkeypatch):
|
||||
monkeypatch.setattr(identity_grants, "counterparty_tables_exist", lambda conn, s: True)
|
||||
s = _platform(identity_reader_roles="sygna-app", counterparty_writer_roles="sygna-app")
|
||||
with pytest.raises(identity_grants.GrantsRefused, match="COUNTERPARTY_WRITER_ROLES"):
|
||||
identity_grants.counterparty_statements(s, "atrium_migrator", object())
|
||||
|
||||
|
||||
def test_revision_0012_creates_then_grants_with_no_bind_parameter_lookalikes():
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from dredd_core import counterparties as cp
|
||||
|
||||
for sql in (cp.counterparty_grants_sql("dredd", owner_role="atrium_migrator",
|
||||
writer_roles=["sygna_app"]),
|
||||
*cp.counterparty_import_sql("dredd", owner_role="atrium_migrator",
|
||||
importer_roles=["compass_migrator"])):
|
||||
assert "%" not in sql and not re.search(r"(?<!:):[A-Za-z_]", sql), sql
|
||||
source = (Path(__file__).resolve().parents[1] / "alembic" / "versions"
|
||||
/ "0012_counterparties.py").read_text(encoding="utf-8")
|
||||
for sql in re.findall(r'f?"((?:SELECT|DROP|WHERE|AND)[^"]*)"', source):
|
||||
assert "%" not in sql and not re.search(r"(?<!:):[A-Za-z_]", sql), sql
|
||||
platform = source.split("identity = settings.identity_schema", 1)[1]
|
||||
steps = ["create_counterparty_tables(bind, identity)", "DROP TABLE",
|
||||
"counterparty_statements(settings, owner, bind)"]
|
||||
assert [platform.index(s) for s in steps] == sorted(platform.index(s) for s in steps)
|
||||
assert 'down_revision = "0011"' in source
|
||||
assert not re.search(r"^from dredd_core(\.counterparties)? import .*counterparties", source, re.M)
|
||||
|
||||
@@ -390,6 +390,31 @@ class TestTheTwoTiers:
|
||||
out = UserOut(id="x", email="a@b.test", full_name="A", is_admin=False, is_active=True)
|
||||
assert out.modules == {} # always a mapping, never absent
|
||||
|
||||
def test_only_an_administrator_is_told_who_holds_which_tier(self):
|
||||
"""`GET /users` answers any credential, a read-only app token included, and the tiers are
|
||||
the map of whose account is worth taking over. Everybody else gets a row with no tier in
|
||||
it at all: absent, never `false` or empty, which would be a lie about an administrator."""
|
||||
from pydantic import TypeAdapter
|
||||
|
||||
from app.schemas import UserBriefOut, UserOut
|
||||
|
||||
assert set(UserBriefOut.model_fields) == {"id", "email", "full_name", "is_active"}
|
||||
# The route's own response type, fed what the handler returns for somebody who is not an
|
||||
# administrator: nothing in the reply may put a tier back.
|
||||
reply = TypeAdapter(list[UserOut] | list[UserBriefOut])
|
||||
brief = UserBriefOut(id="x", email="a@b.test", full_name="A", is_active=True)
|
||||
assert reply.dump_python(reply.validate_python([brief])) == [
|
||||
{"id": "x", "email": "a@b.test", "full_name": "A", "is_active": True}]
|
||||
full = UserOut(id="x", email="a@b.test", full_name="A", is_admin=True, is_active=True,
|
||||
modules={"galena": "moderator"})
|
||||
assert reply.dump_python(reply.validate_python([full]))[0]["modules"] == {
|
||||
"galena": "moderator"}
|
||||
|
||||
source = (BACKEND / "app" / "routers" / "users.py").read_text(encoding="utf-8")
|
||||
body = source.split("def list_users", 1)[1].split("@router.post", 1)[0]
|
||||
assert "response_model=list[UserOut] | list[UserBriefOut]" in source
|
||||
assert body.index("if not user.is_admin") < body.index("module_roles_by_user")
|
||||
|
||||
def test_a_new_account_gets_no_tier_and_no_module_by_default(self):
|
||||
"""The default is an account that can sign in and open nothing. Before `module_permission`
|
||||
there was no way to express that: everybody could open everything."""
|
||||
@@ -433,9 +458,11 @@ class TestTheTwoTiers:
|
||||
other two quote it in their docs — so renaming it here alone breaks another app's tests and
|
||||
leaves three sets of documentation wrong. Rename it in four repositories at once, or not at
|
||||
all."""
|
||||
from dredd_core.routes import iter_routes
|
||||
|
||||
from app.main import app
|
||||
|
||||
paths = {r.path for r in app.routes if hasattr(r, "path")}
|
||||
paths = {r.path for _, r in iter_routes(app.routes) if hasattr(r, "path")}
|
||||
assert "/api/v1/admin/modules/{slug}/moderators" in paths
|
||||
assert "/api/v1/admin/modules/{slug}/moderators/{user_id}" in paths
|
||||
|
||||
@@ -476,6 +503,20 @@ class TestTheLastAdministratorGuard:
|
||||
body = source.split("def count_administrators", 1)[1].split("def _assert", 1)[0]
|
||||
assert "is_active.is_(True)" in body
|
||||
|
||||
def test_the_count_is_taken_under_a_lock_on_the_administrators(self):
|
||||
"""A check followed by a write, with nothing in between, is passed by two requests at once:
|
||||
"demote A" and "demote B" each count the other and both go through. So the guard locks the
|
||||
administrators' rows first and counts after — FOR NO KEY UPDATE (a plain FOR UPDATE would
|
||||
make every foreign-key insert that names an administrator wait), in a fixed order."""
|
||||
source = (BACKEND / "app" / "services" / "accounts.py").read_text(encoding="utf-8")
|
||||
lock = source.split("def _lock_administrators", 1)[1].split("def _assert", 1)[0]
|
||||
assert "with_for_update(key_share=True)" in lock
|
||||
assert "order_by(AppUser.id)" in lock
|
||||
assert "is_admin.is_(True)" in lock and "is_active.is_(True)" in lock
|
||||
guard = source.split("def _assert_not_last_administrator", 1)[1].split(
|
||||
"def set_administrator", 1)[0]
|
||||
assert guard.index("_lock_administrators(db)") < guard.index("count_administrators(db")
|
||||
|
||||
def test_the_routers_do_not_reimplement_it(self):
|
||||
"""Layering: routers never build SQL, and a second copy of a guard is a guard that will
|
||||
disagree with the first one."""
|
||||
|
||||
@@ -80,7 +80,7 @@ def test_the_seeded_family_is_in_the_catalog(admin_client):
|
||||
# `counsel`, not `counsel-scorecard`: a slug is the name the MODULE answers to, because a
|
||||
# moderator grant and an app token are both addressed by it and both fail silently on a name it
|
||||
# does not use (revision 0005, tests/test_catalog_slugs.py).
|
||||
assert {"galena", "sygna", "counsel", "compass", "insider"} <= set(catalog)
|
||||
assert {"galena", "sygna", "counsel", "insider"} <= set(catalog) and "compass" not in catalog
|
||||
assert "counsel-scorecard" not in catalog, "revision 0005 did not correct the catalogue row"
|
||||
for entry in FAMILY:
|
||||
seeded = catalog[entry["slug"]]
|
||||
@@ -98,6 +98,23 @@ def test_admin_endpoints_refuse_ordinary_users(client, make_user):
|
||||
assert r.status_code == 403, (path, r.status_code)
|
||||
|
||||
|
||||
def test_the_user_list_tells_only_an_administrator_who_holds_which_tier(admin_client, client,
|
||||
make_user):
|
||||
"""Anybody signed in may list people (a picker needs names). Who is an administrator and who
|
||||
may open which module is told to an administrator only: for everybody else those fields are
|
||||
absent, on every row, their own and the administrators' included."""
|
||||
alice = make_user("brief")
|
||||
rows = client.get("/api/v1/users", headers=bearer(alice["token"]))
|
||||
assert rows.status_code == 200, rows.text
|
||||
assert rows.json() and all(set(row) == {"id", "email", "full_name", "is_active"}
|
||||
for row in rows.json())
|
||||
assert any(row["id"] == alice["id"] for row in rows.json())
|
||||
|
||||
full = admin_client.get("/api/v1/users").json()
|
||||
assert all({"is_admin", "modules"} <= set(row) for row in full)
|
||||
assert any(row["is_admin"] for row in full)
|
||||
|
||||
|
||||
# ── people: the way back in ───────────────────────────────────────────────────
|
||||
# A forgotten password had no answer on this platform: `POST /me/password` needs the password that
|
||||
# is missing, a module's own reset 409s because no module may write `app_user`, and there is no
|
||||
|
||||
@@ -9,6 +9,7 @@ OpenAPI, /healthz and the problem responses (401/404/405/422/500).
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from dredd_core.routes import iter_routes
|
||||
from fastapi.routing import APIRoute
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
@@ -32,8 +33,8 @@ def _declares_utf8(r) -> None:
|
||||
|
||||
|
||||
def test_every_parameter_free_get_route_declares_utf8():
|
||||
paths = sorted({r.path for r in app.routes
|
||||
if isinstance(r, APIRoute) and "GET" in r.methods and "{" not in r.path})
|
||||
paths = sorted({r.path for orig, r in iter_routes(app.routes)
|
||||
if isinstance(orig, APIRoute) and "GET" in r.methods and "{" not in r.path})
|
||||
if app.openapi_url:
|
||||
paths.append(app.openapi_url)
|
||||
assert "/healthz" in paths
|
||||
@@ -53,7 +54,7 @@ def test_unknown_api_path_404():
|
||||
|
||||
|
||||
def test_wrong_method_and_bad_body():
|
||||
post_only = sorted(r.path for r in app.routes if isinstance(r, APIRoute)
|
||||
post_only = sorted(r.path for orig, r in iter_routes(app.routes) if isinstance(orig, APIRoute)
|
||||
and r.methods == {"POST"} and "{" not in r.path)
|
||||
assert post_only
|
||||
wrong = client.get(post_only[0])
|
||||
@@ -78,7 +79,7 @@ def broken_identity():
|
||||
|
||||
|
||||
def test_401_and_500_problems(broken_identity):
|
||||
authed = next(r.path for r in app.routes if isinstance(r, APIRoute) and "GET" in r.methods
|
||||
authed = next(r.path for orig, r in iter_routes(app.routes) if isinstance(orig, APIRoute) and "GET" in r.methods
|
||||
and "{" not in r.path and _uses_current_user(r))
|
||||
r = client.get(authed)
|
||||
assert r.status_code == 500
|
||||
|
||||
@@ -215,6 +215,46 @@ class TestFields:
|
||||
with pytest.raises(ValidationError):
|
||||
marketplace._clean_field("category", "x" * 41)
|
||||
|
||||
def test_in_menu_is_a_real_bool(self):
|
||||
assert marketplace._clean_field("in_menu", False) is False
|
||||
assert marketplace._clean_field("in_menu", True) is True
|
||||
for bad in ("false", 0, 1, "no"):
|
||||
with pytest.raises(ValidationError):
|
||||
marketplace._clean_field("in_menu", bad)
|
||||
|
||||
|
||||
class TestServiceModules:
|
||||
"""A service module (`in_menu` false, as Galena) loses its menu entry and its
|
||||
catalogue card, and nothing else: launcher, deep links, stats tiles and access stay."""
|
||||
|
||||
def test_galena_is_seeded_as_a_service(self):
|
||||
from app.seed import FAMILY
|
||||
flags = {e["slug"]: e.get("in_menu", True) for e in FAMILY}
|
||||
assert flags["galena"] is False and flags["arbiter"] is False
|
||||
# Issue #53: the three contract modules are services, shown as one „Umowy” entry.
|
||||
assert flags["lexicon"] is False and flags["scribe"] is False
|
||||
# Panorama left the platform: no longer seeded; 0018 hides an existing row.
|
||||
assert "panorama" not in flags
|
||||
assert all(flags[s] for s in flags if s not in ("galena", "arbiter", "lexicon", "scribe"))
|
||||
|
||||
def test_the_catalogue_hides_it_from_people_not_administrators(self):
|
||||
body = inspect.getsource(marketplace.browse)
|
||||
assert "Module.in_menu.is_(True)" in body
|
||||
assert body.index("user.is_admin") < body.index("Module.in_menu")
|
||||
|
||||
def test_the_launcher_keeps_it(self):
|
||||
# Hiding it here would break every "open in Galena" link, the frame and the Home tiles.
|
||||
assert "in_menu" not in inspect.getsource(marketplace.launcher)
|
||||
|
||||
def test_the_console_drops_only_the_menu_entry(self):
|
||||
console = (FRONTEND / "app.js").read_text(encoding="utf-8")
|
||||
nav = re.search(r"const navModules = \(\) =>.*?;\n", console, re.S).group(0)
|
||||
assert "inMenu(m)" in nav and "m.slug === frame.slug" in nav
|
||||
prefs = console.split("function openNavPrefs()", 1)[1].split("\n}\n", 1)[0]
|
||||
assert "inMenu(m)" in prefs
|
||||
stats = console.split("async function loadModuleStats()", 1)[1].split("\n}\n", 1)[0]
|
||||
assert "inMenu" not in stats
|
||||
|
||||
|
||||
class TestMembership:
|
||||
"""An assignment on a unit reaches its members and the members of every unit below it — and
|
||||
@@ -254,6 +294,15 @@ class TestSettings:
|
||||
settings._normalize("support_contact", "ring\x07")
|
||||
assert settings._normalize("welcome_message", " line one\nline two ") == "line one\nline two"
|
||||
|
||||
def test_skills_settings_default_closed_and_refuse_other_values(self):
|
||||
assert settings.SPECS["skills_firm_publish"].default == "approval"
|
||||
assert settings.SPECS["skills_firm_export"].default == "administrator"
|
||||
assert settings._normalize("skills_firm_publish", "direct") == "direct"
|
||||
assert settings._normalize("skills_firm_export", "everyone") == "everyone"
|
||||
for key, bad in (("skills_firm_publish", "auto"), ("skills_firm_export", "owner")):
|
||||
with pytest.raises(ValidationError):
|
||||
settings._normalize(key, bad)
|
||||
|
||||
def test_the_catalog_marker_key_never_changes(self):
|
||||
"""Persisted in every instance: renamed, an instance whose administrator deleted every
|
||||
module loses its marker and gets the catalog back on the next deploy."""
|
||||
|
||||
@@ -28,9 +28,14 @@ def test_core_tables_are_registered():
|
||||
assert {"app_user", "session", "app_setting", "audit_log"} <= set(_metadata().tables)
|
||||
|
||||
|
||||
SKILL_TABLES = ("skill", "skill_version", "skill_file", "agent", "agent_version",
|
||||
"agent_version_skill", "publish_request")
|
||||
|
||||
|
||||
def test_the_apps_own_tables_are_registered():
|
||||
"""A model missing from `app/models/__init__.py` silently gets no table."""
|
||||
assert {"module", "module_assignment", "access_request"} <= set(_metadata().tables)
|
||||
assert set(SKILL_TABLES) <= set(_metadata().tables)
|
||||
assert "record" not in _metadata().tables
|
||||
|
||||
|
||||
@@ -52,14 +57,30 @@ def test_marketplace_vocabularies_are_check_constraints_not_enum_types():
|
||||
and each CHECK lists exactly the StrEnum's values, so the code and the database agree."""
|
||||
from sqlalchemy import CheckConstraint
|
||||
|
||||
from app.enums import AccessRequestStatus, Availability, ModuleStatus
|
||||
from app.enums import (
|
||||
AccessRequestStatus,
|
||||
AgentKind,
|
||||
Availability,
|
||||
CatalogStatus,
|
||||
ModuleStatus,
|
||||
PublishKind,
|
||||
PublishRequestStatus,
|
||||
SkillOrigin,
|
||||
SkillScope,
|
||||
)
|
||||
|
||||
tables = _metadata().tables
|
||||
for name in ("module", "module_assignment", "access_request"):
|
||||
for name in ("module", "module_assignment", "access_request", *SKILL_TABLES):
|
||||
assert not [c for c in tables[name].columns if isinstance(c.type, PGEnum)], name
|
||||
assert "record_status" not in enum_types(_metadata())
|
||||
expected = {("module", "status"): ModuleStatus, ("module", "availability"): Availability,
|
||||
("access_request", "status"): AccessRequestStatus}
|
||||
("access_request", "status"): AccessRequestStatus,
|
||||
("skill", "scope"): SkillScope, ("skill", "status"): CatalogStatus,
|
||||
("skill", "origin"): SkillOrigin,
|
||||
("agent", "scope"): SkillScope, ("agent", "status"): CatalogStatus,
|
||||
("agent", "kind"): AgentKind,
|
||||
("publish_request", "kind"): PublishKind,
|
||||
("publish_request", "status"): PublishRequestStatus}
|
||||
for (table, column), enum in expected.items():
|
||||
sql = [str(c.sqltext) for c in tables[table].constraints
|
||||
if isinstance(c, CheckConstraint) and str(c.sqltext).startswith(f"{column} IN")]
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Home's model picker: how a model id is shown and which family's mark it wears.
|
||||
|
||||
`prettyModel` and `modelFamily` are lifted out of `frontend/app.js` and run under Node, so the
|
||||
behaviour is asserted, not the source text. DB-free; skipped only where no `node` binary exists.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
NODE = shutil.which("node")
|
||||
SRC = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _fn(head: str) -> str:
|
||||
i = SRC.index(head)
|
||||
return SRC[i:SRC.index("\n}\n", i) + 3]
|
||||
|
||||
|
||||
def _run(fn: str, args: list[str]) -> list[str]:
|
||||
script = _fn(f"function {fn}(") + f"\nconsole.log(JSON.stringify({json.dumps(args)}.map({fn})));"
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60)
|
||||
assert r.returncode == 0, r.stderr
|
||||
return json.loads(r.stdout)
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_pretty_model_reads_like_a_name() -> None:
|
||||
assert _run("prettyModel", ["claude-opus-5-5", "qwen/qwen3.5-9b", "claude-sonnet-4-5-20250929"]) == [
|
||||
"Claude Opus 5.5", "Qwen3.5 9B", "Claude Sonnet 4.5 20250929"]
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_model_family_by_id() -> None:
|
||||
cases = {
|
||||
"claude-opus-5-5": "anthropic", "anthropic/claude-haiku-5-5": "anthropic",
|
||||
"gpt-5": "openai", "o3-mini": "openai", "openai/o4": "openai",
|
||||
"gemini-2.5-pro": "google", "google/gemma-3-27b": "google",
|
||||
"qwen/qwen3.5-9b": "qwen", "speakleash/bielik-11b-v2.6": "bielik",
|
||||
"meta-llama/llama-3.3-70b": "meta", "mistral-large": "mistral", "mixtral-8x7b": "mistral",
|
||||
"deepseek-r1": "D", "phi-4": "P",
|
||||
}
|
||||
assert _run("modelFamily", list(cases)) == list(cases.values())
|
||||
|
||||
|
||||
def test_picker_groups_by_provider_and_escapes() -> None:
|
||||
body = _fn("function modelOptions(")
|
||||
assert "<optgroup label=\"${esc(g.provider)}\" data-no-i18n>" in body
|
||||
assert "${esc(prettyModel(m.id))}" in body and 'title="${esc(m.id)}"' in body
|
||||
assert "modelLabel" not in SRC
|
||||
|
||||
|
||||
def test_pick_is_remembered_and_the_icon_follows_it() -> None:
|
||||
change = _fn("function homeModelChange(")
|
||||
assert "saveModelPick(sel.value)" in change
|
||||
assert "$('homeModelIcon').innerHTML = familyIcon(sel.value)" in change
|
||||
assert "savedModelPick()" in SRC and "localStorage.setItem(modelPickKey()" in SRC
|
||||
assert '<span id="homeModelIcon">${familyIcon(picked)}</span>' in SRC
|
||||
assert "markSvg(fam, letter)" in _fn("function familyIcon(")
|
||||
assert "${esc(letter)}" in _fn("function markSvg(")
|
||||
|
||||
|
||||
def test_every_vendored_logotype_is_credited() -> None:
|
||||
import re
|
||||
|
||||
brand = SRC[SRC.index("const BRAND = {"):]
|
||||
brand = brand[:brand.index("\n};")]
|
||||
keys = re.findall(r"^ (\w+): '", brand, re.M)
|
||||
assert keys, "BRAND map is empty"
|
||||
credits = (ROOT / "CREDITS.md").read_text(encoding="utf-8")
|
||||
assert "Simple Icons" in credits and "CC0" in credits
|
||||
for key in keys:
|
||||
assert f"`{key}`" in credits, key
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_a_model_two_providers_offer_is_listed_once_under_the_one_that_answers() -> None:
|
||||
# The server routes an id to the FIRST provider offering it; a second option for the same id
|
||||
# would show one provider and send the question to another.
|
||||
start = SRC.index("const esc = ")
|
||||
esc = SRC[start:SRC.index("}[c]));", start) + len("}[c]));")]
|
||||
script = "\n".join([esc, _fn("function prettyModel("), _fn("function modelOptions(")]) + (
|
||||
"\nconsole.log(modelOptions([{id:'qwen3',provider:'Lokalny'},{id:'qwen3',provider:'OpenRouter'},"
|
||||
"{id:'gpt-5',provider:'OpenRouter'}], 'qwen3', 'Tylko szukaj'));")
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60)
|
||||
assert r.returncode == 0, r.stderr
|
||||
html = r.stdout
|
||||
assert html.count('value="qwen3"') == 1 and html.count(" selected") == 1
|
||||
assert html.index('value="qwen3"') < html.index('label="OpenRouter"')
|
||||
@@ -0,0 +1,183 @@
|
||||
"""`model_server.list_models` on a mocked transport: what counts as a chat model, the outbound limits
|
||||
(no redirects, 2 MB), the refusal codes, and that the key never appears in an error."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from app.errors import ValidationError
|
||||
from app.integrations import model_server
|
||||
|
||||
KEY = "sk-secret-value-123"
|
||||
|
||||
|
||||
def _resp(status, json_=None, content=b"", headers=None):
|
||||
"""A STREAMED response, as the network gives one (`content=` would arrive already read)."""
|
||||
body = json.dumps(json_).encode() if json_ is not None else content
|
||||
return httpx.Response(status, headers=headers, stream=httpx.ByteStream(body))
|
||||
|
||||
|
||||
def _run(handler, base="http://gpu.example:8000/v1", key=KEY, vendor=None):
|
||||
return asyncio.run(model_server.list_models(base, key, vendor, transport=httpx.MockTransport(handler)))
|
||||
|
||||
|
||||
def _refused(handler, code, **kw):
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
_run(handler, **kw)
|
||||
assert exc.value.extra["code"] == code
|
||||
assert KEY not in exc.value.detail and KEY not in json.dumps(exc.value.extra)
|
||||
return exc.value
|
||||
|
||||
|
||||
def test_vllm_max_model_len_becomes_the_context_window_and_the_key_is_a_bearer():
|
||||
seen = []
|
||||
|
||||
def handler(req):
|
||||
seen.append(req)
|
||||
if req.url.path == "/v1/models":
|
||||
return _resp(200, json_={"data": [{"id": "qwen/qwen3.5-9b", "max_model_len": 32768},
|
||||
{"id": "bielik-11b"}]})
|
||||
return _resp(404)
|
||||
assert _run(handler) == [{"id": "qwen/qwen3.5-9b", "dialect": "openai", "context_window": 32768},
|
||||
{"id": "bielik-11b", "dialect": "openai"}]
|
||||
assert seen[0].headers["authorization"] == f"Bearer {KEY}"
|
||||
|
||||
|
||||
def test_lm_studio_drops_embeddings_and_keeps_models_not_loaded():
|
||||
def handler(req):
|
||||
if req.url.path == "/v1/models":
|
||||
return _resp(200, json_={"data": [{"id": "qwen3"}, {"id": "nomic-text-v1"}, {"id": "gemma"}]})
|
||||
return _resp(200, json_={"data": [
|
||||
{"id": "qwen3", "type": "llm", "state": "loaded"},
|
||||
{"id": "nomic-text-v1", "type": "embeddings", "state": "not-loaded"},
|
||||
{"id": "gemma", "type": "vlm", "state": "not-loaded"}]})
|
||||
assert [m["id"] for m in _run(handler, base="http://localhost:1234", key=None)] == ["qwen3", "gemma"]
|
||||
|
||||
|
||||
def test_non_chat_ids_are_dropped_by_pattern():
|
||||
def handler(req):
|
||||
return _resp(200, json_={"data": [{"id": "gpt-5"}, {"id": "text-embedding-3-large"},
|
||||
{"id": "whisper-1"}, {"id": "gpt-image-1"}]})
|
||||
assert [m["id"] for m in _run(handler, vendor="openai")] == ["gpt-5"]
|
||||
|
||||
|
||||
def test_a_redirect_is_refused():
|
||||
_refused(lambda req: _resp(302, headers={"Location": "http://169.254.169.254/"}),
|
||||
"provider_unreachable")
|
||||
|
||||
|
||||
def test_an_answer_over_2_mb_is_cut_and_refused():
|
||||
big = b'{"data": [' + b" " * (model_server.LIST_MAX_BYTES + 1) + b"]}"
|
||||
_refused(lambda req: _resp(200, content=big), "provider_unreachable")
|
||||
|
||||
|
||||
def test_401_is_a_refused_key():
|
||||
_refused(lambda req: _resp(401, json_={"error": f"bad key {KEY}"}), "provider_key_refused")
|
||||
|
||||
|
||||
def test_no_answer_is_unreachable():
|
||||
def handler(req):
|
||||
raise httpx.ConnectError(f"cannot connect with {KEY}")
|
||||
_refused(handler, "provider_unreachable")
|
||||
|
||||
|
||||
def test_an_empty_list_after_the_filter_is_no_models():
|
||||
_refused(lambda req: _resp(200, json_={"data": [{"id": "text-embedding-3-small"}]}),
|
||||
"provider_no_models", vendor="openai")
|
||||
|
||||
|
||||
def test_a_compressed_answer_is_refused_and_identity_is_asked_for():
|
||||
seen = []
|
||||
|
||||
def handler(req):
|
||||
seen.append(req.headers["accept-encoding"])
|
||||
return _resp(200, headers={"Content-Encoding": "gzip"}, content=b"\x1f\x8b")
|
||||
_refused(handler, "provider_unreachable")
|
||||
assert seen == ["identity"]
|
||||
|
||||
|
||||
ANTHROPIC = "https://api.anthropic.com/v1"
|
||||
|
||||
|
||||
def _anthropic(handler):
|
||||
return _run(handler, base=ANTHROPIC, vendor="anthropic")
|
||||
|
||||
|
||||
def test_anthropic_keeps_active_models_and_sends_its_own_headers():
|
||||
seen = []
|
||||
|
||||
def handler(req):
|
||||
seen.append(req)
|
||||
return _resp(200, json_={"data": [
|
||||
{"id": "claude-opus-5-5", "lifecycle": "active", "max_input_tokens": 1000000},
|
||||
{"id": "claude-old-3", "lifecycle": "deprecated", "max_input_tokens": 200000},
|
||||
{"id": "claude-haiku-5-5", "lifecycle": "active", "max_input_tokens": 0}]})
|
||||
assert _anthropic(handler) == [
|
||||
{"id": "claude-opus-5-5", "dialect": "openai", "context_window": 1000000},
|
||||
{"id": "claude-haiku-5-5", "dialect": "openai"}]
|
||||
req, = seen
|
||||
assert req.url.path == "/v1/models" and req.url.params["limit"] == "1000"
|
||||
assert req.headers["x-api-key"] == KEY
|
||||
assert req.headers["anthropic-version"] == model_server.ANTHROPIC_VERSION
|
||||
assert "authorization" not in req.headers
|
||||
|
||||
|
||||
def test_anthropic_refusals_never_carry_the_key():
|
||||
_refused(lambda req: _resp(401, json_={"error": f"bad key {KEY}"}), "provider_key_refused",
|
||||
base=ANTHROPIC, vendor="anthropic")
|
||||
_refused(lambda req: _resp(302, headers={"Location": "http://169.254.169.254/"}),
|
||||
"provider_unreachable", base=ANTHROPIC, vendor="anthropic")
|
||||
_refused(lambda req: _resp(200, json_={"data": [{"id": "claude-old-3", "lifecycle": "deprecated"}]}),
|
||||
"provider_no_models", base=ANTHROPIC, vendor="anthropic")
|
||||
|
||||
|
||||
def test_a_redirect_is_not_followed_one_request_and_no_second_host():
|
||||
seen = []
|
||||
|
||||
def handler(req):
|
||||
seen.append(str(req.url))
|
||||
return _resp(302, headers={"Location": "http://169.254.169.254/latest/meta-data/"})
|
||||
_refused(handler, "provider_unreachable")
|
||||
assert len(seen) == 1 and "169.254" not in seen[0]
|
||||
|
||||
|
||||
def test_one_deadline_covers_the_whole_exchange_not_each_read(monkeypatch):
|
||||
"""A body trickled slower than the deadline in total, but each chunk fast enough for a per-read
|
||||
timeout, must still end at the deadline."""
|
||||
import time
|
||||
|
||||
class Trickle(httpx.AsyncByteStream):
|
||||
async def __aiter__(self):
|
||||
yield b'{"data": ['
|
||||
for _ in range(50):
|
||||
await asyncio.sleep(0.05)
|
||||
yield b" "
|
||||
yield b"]}"
|
||||
monkeypatch.setattr(model_server, "LIST_DEADLINE", 0.5)
|
||||
started = time.monotonic()
|
||||
_refused(lambda req: httpx.Response(200, stream=Trickle()), "provider_unreachable")
|
||||
assert time.monotonic() - started < 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize("answer", [
|
||||
lambda: _resp(302, headers={"Location": "/login"}),
|
||||
lambda: _resp(200, content=b"<html>login</html>"),
|
||||
lambda: _resp(401),
|
||||
], ids=["redirect", "html", "401"])
|
||||
def test_a_broken_optional_lm_studio_listing_does_not_sink_the_discovery(answer):
|
||||
def handler(req):
|
||||
if req.url.path == "/v1/models":
|
||||
return _resp(200, json_={"data": [{"id": "qwen3"}]})
|
||||
return answer()
|
||||
assert [m["id"] for m in _run(handler, key=None)] == ["qwen3"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("body", [b"[]", b"null", b'"x"', b'{"data": null}', b'{"data": "x"}',
|
||||
b"[" * 100_000 + b"]" * 100_000],
|
||||
ids=["list", "null", "string", "data-null", "data-string", "deep-nesting"])
|
||||
@pytest.mark.parametrize("vendor", [None, "anthropic"])
|
||||
def test_an_unexpected_json_shape_is_a_422_not_a_500(body, vendor):
|
||||
_refused(lambda req: _resp(200, content=body), "provider_unreachable", vendor=vendor)
|
||||
@@ -0,0 +1,393 @@
|
||||
"""Home's "ask the model", DB-free: where a call may go (provider rows only), what counts toward the
|
||||
question cap, the limit, the sampling knobs, and that the old module door is gone."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import uuid
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from dredd_core.routes import iter_routes
|
||||
from fastapi.testclient import TestClient
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app import db as db_module
|
||||
from app import deps
|
||||
from app.errors import ConflictError, NotFoundError
|
||||
from app.integrations import model_server
|
||||
from app.main import app
|
||||
from app.routers import models
|
||||
from app.services import providers
|
||||
|
||||
ADMIN = SimpleNamespace(is_admin=True, id=uuid.uuid4())
|
||||
PERSON = SimpleNamespace(is_admin=False, id=uuid.uuid4())
|
||||
|
||||
|
||||
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 _offering(monkeypatch, found):
|
||||
calls = []
|
||||
|
||||
def offering(db, model_id, *, is_admin):
|
||||
calls.append(is_admin)
|
||||
return found
|
||||
monkeypatch.setattr(providers.core, "offering", offering)
|
||||
# core's real `key_for` runs; only the policy filter (a DB read) is opened up.
|
||||
monkeypatch.setattr(providers.core, "_use_filter", lambda db, *, is_admin: lambda provider: True)
|
||||
return calls
|
||||
|
||||
|
||||
class _UserKeys:
|
||||
"""Just enough of a session for core's `key_for` / `user_key_prefix`: `get` by primary key."""
|
||||
|
||||
def __init__(self, rows=None):
|
||||
self.rows = rows or {}
|
||||
|
||||
def get(self, model, pk):
|
||||
return self.rows.get(pk)
|
||||
|
||||
|
||||
# ── where a call may go ─────────────────────────────────────────────────
|
||||
|
||||
def test_a_model_nobody_offers_is_a_404(monkeypatch):
|
||||
_offering(monkeypatch, None)
|
||||
with pytest.raises(NotFoundError):
|
||||
providers.call_target(None, PERSON, "qwen")
|
||||
|
||||
|
||||
def test_a_model_in_another_dialect_is_not_offered(monkeypatch):
|
||||
p = _provider(models_=[{"id": "qwen", "dialect": "chatml"}])
|
||||
_offering(monkeypatch, (p, p.models[0]))
|
||||
with pytest.raises(NotFoundError):
|
||||
providers.call_target(None, PERSON, "qwen")
|
||||
|
||||
|
||||
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]))
|
||||
target = providers.call_target(_UserKeys(), PERSON, "qwen")
|
||||
assert target == {"base_url": p.base_url, "key": None, "provider": "LM Studio", "kind": "local",
|
||||
"key_source": "none"}
|
||||
providers.call_target(_UserKeys(), ADMIN, "qwen")
|
||||
assert calls == [False, True]
|
||||
|
||||
|
||||
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")
|
||||
target = providers.call_target(None, PERSON, "qwen")
|
||||
assert (target["key"], target["key_source"]) == ("sk-abcdef", "firm")
|
||||
|
||||
|
||||
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):
|
||||
providers.call_target(None, PERSON, "qwen")
|
||||
|
||||
|
||||
def test_a_personal_key_provider_without_the_askers_key_says_add_your_key(monkeypatch):
|
||||
"""dredd-core 0.18.0: `(None, "user")` from `key_for` is the caller's refusal, never a keyless call."""
|
||||
p = _provider(kind="api", key_mode="user", name="Claude")
|
||||
_offering(monkeypatch, (p, p.models[0]))
|
||||
with pytest.raises(ConflictError) as err:
|
||||
providers.call_target(_UserKeys(), PERSON, "qwen")
|
||||
assert err.value.extra["code"] == providers.USER_KEY_MISSING
|
||||
assert "Dodaj swój klucz" in str(err.value) and "Add your key" in err.value.extra["en"]
|
||||
|
||||
|
||||
def test_the_askers_own_key_goes_with_the_call_and_is_audited_as_theirs(monkeypatch):
|
||||
p = _provider(kind="api", key_mode="user", name="Claude")
|
||||
_offering(monkeypatch, (p, p.models[0]))
|
||||
row = SimpleNamespace(api_key_encrypted="v1.cipher", key_prefix="sk-own")
|
||||
monkeypatch.setattr(providers, "decrypt", lambda stored: "sk-own-123" if stored == "v1.cipher" else None)
|
||||
db = _UserKeys({(p.id, PERSON.id): row})
|
||||
target = providers.call_target(db, PERSON, "qwen")
|
||||
assert (target["key"], target["key_source"]) == ("sk-own-123", "user")
|
||||
# Somebody else's key is never borrowed: the administrator has none stored here.
|
||||
with pytest.raises(ConflictError) as err:
|
||||
providers.call_target(db, ADMIN, "qwen")
|
||||
assert err.value.extra["code"] == providers.USER_KEY_MISSING
|
||||
|
||||
|
||||
def test_an_unreadable_personal_key_refuses_and_asks_to_store_it_again(monkeypatch):
|
||||
p = _provider(kind="api", key_mode="user", name="Claude")
|
||||
_offering(monkeypatch, (p, p.models[0]))
|
||||
monkeypatch.setattr(providers, "decrypt", lambda stored: None)
|
||||
db = _UserKeys({(p.id, PERSON.id): SimpleNamespace(api_key_encrypted="v1.x", key_prefix="sk-own")})
|
||||
with pytest.raises(ConflictError) as err:
|
||||
providers.call_target(db, PERSON, "qwen")
|
||||
assert err.value.extra["code"] == providers.USER_KEY_UNREADABLE
|
||||
|
||||
|
||||
def test_a_none_provider_calls_without_a_key_even_if_one_was_stored_once(monkeypatch):
|
||||
p = _provider(kind="api", key_mode="none", key_prefix="sk-old")
|
||||
_offering(monkeypatch, (p, p.models[0]))
|
||||
monkeypatch.setattr(providers.core, "api_key", lambda db, provider, decrypt: pytest.fail("read"))
|
||||
target = providers.call_target(None, PERSON, "qwen")
|
||||
assert (target["key"], target["key_source"]) == (None, "none")
|
||||
|
||||
|
||||
def test_key_for_is_the_only_door_out(monkeypatch):
|
||||
"""The call path never reads a key past `key_for` (dredd-core 0.18.0)."""
|
||||
import inspect
|
||||
|
||||
source = inspect.getsource(providers.call_target)
|
||||
assert "core.key_for(" in source and "core.api_key(" not in source
|
||||
|
||||
|
||||
def test_the_list_shows_chat_models_only_and_never_an_address(monkeypatch):
|
||||
p = _provider(models_=[{"id": "qwen"}, {"id": "old", "dialect": "chatml"}])
|
||||
monkeypatch.setattr(providers.core, "usable_providers", lambda db, *, is_admin: [p])
|
||||
monkeypatch.setattr(providers.core, "stays_in_the_eu", lambda provider: True)
|
||||
listed = providers.usable_models(None, PERSON)
|
||||
assert [m["id"] for m in listed] == ["qwen"]
|
||||
assert all("base_url" not in m and "key" not in m for m in listed)
|
||||
|
||||
|
||||
def test_the_server_root_reads_v1_like_compass():
|
||||
assert model_server.server_root("http://h:1234/v1/") == "http://h:1234"
|
||||
assert model_server.server_root("http://h:1234") == "http://h:1234"
|
||||
|
||||
|
||||
def test_a_server_without_lm_studios_listing_is_never_loaded_by_hand(monkeypatch):
|
||||
async def refuse(*_a, **_k):
|
||||
raise model_server.GatewayError("HTTP 404")
|
||||
monkeypatch.setattr(model_server, "_json", refuse)
|
||||
assert asyncio.run(model_server.loaded_models("http://h:11434", None)) is None
|
||||
|
||||
|
||||
# ── one model on the card: who may switch it, and what a switch unloads ─
|
||||
|
||||
class _LmStudio:
|
||||
"""The two listings and the two writes of LM Studio, recording the writes."""
|
||||
|
||||
def __init__(self, loaded):
|
||||
self.loaded = dict(loaded) # {id: type}
|
||||
self.writes = []
|
||||
|
||||
async def __call__(self, _client, method, url, _key, body=None):
|
||||
if method == "POST":
|
||||
self.writes.append((url.rsplit("/", 1)[1], body))
|
||||
if url.endswith("/unload"):
|
||||
del self.loaded[body["instance_id"]]
|
||||
else:
|
||||
self.loaded[body["model"]] = "llm"
|
||||
return {}
|
||||
if "/api/v0/" in url:
|
||||
return {"data": [{"id": m, "type": t, "state": "loaded"} for m, t in self.loaded.items()]
|
||||
+ [{"id": "cold", "type": "llm", "state": "not-loaded"}]}
|
||||
return {"models": [{"key": m, "loaded_instances": [{"id": m}]} for m in self.loaded]}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def asker(monkeypatch):
|
||||
"""`asker(server, admin=...)` gives POST /models/ask with the row, session and audit stubbed."""
|
||||
audited = []
|
||||
target = {"base_url": "http://h:1234/v1", "key": None, "provider": "LM Studio", "kind": "local",
|
||||
"key_source": "none"}
|
||||
|
||||
async def chat(*_a, **_k):
|
||||
yield b"data: [DONE]\n\n"
|
||||
|
||||
def build(server, *, admin):
|
||||
user = SimpleNamespace(id=uuid.uuid4(), is_admin=admin)
|
||||
monkeypatch.setattr(model_server, "_json", server)
|
||||
monkeypatch.setattr(model_server, "stream_chat", chat)
|
||||
monkeypatch.setattr(providers, "call_target", lambda db, u, m: target)
|
||||
monkeypatch.setattr(models.audit, "record", lambda *a, **k: audited.append(k))
|
||||
app.dependency_overrides[deps.get_current_user] = lambda: user
|
||||
app.dependency_overrides[db_module.get_db] = lambda: SimpleNamespace(commit=lambda: None)
|
||||
|
||||
def ask(model):
|
||||
return TestClient(app).post("/api/v1/models/ask",
|
||||
json={"model": model, "messages": [{"role": "user", "content": "?"}]})
|
||||
return ask, audited
|
||||
yield build
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def test_a_user_asking_for_another_model_gets_409_and_the_loaded_model_stays(asker):
|
||||
server = _LmStudio({"qwen": "llm"})
|
||||
ask, audited = asker(server, admin=False)
|
||||
resp = ask("cold")
|
||||
assert resp.status_code == 409
|
||||
problem = resp.json()
|
||||
assert "Teraz działa model qwen" in problem["detail"]
|
||||
assert (problem["code"], problem["running"]) == ("model_busy", "qwen")
|
||||
assert server.writes == [] and server.loaded == {"qwen": "llm"} and audited == []
|
||||
|
||||
|
||||
def test_a_user_may_ask_with_the_loaded_model(asker):
|
||||
server = _LmStudio({"qwen": "llm"})
|
||||
ask, audited = asker(server, admin=False)
|
||||
assert ask("qwen").status_code == 200
|
||||
assert server.writes == [] and len(audited) == 1
|
||||
|
||||
|
||||
def test_a_user_may_load_the_first_model(asker):
|
||||
server = _LmStudio({})
|
||||
ask, _ = asker(server, admin=False)
|
||||
assert ask("cold").status_code == 200
|
||||
assert [w[0] for w in server.writes] == ["load"] and "cold" in server.loaded
|
||||
|
||||
|
||||
def test_an_embedding_model_alone_does_not_count_as_running(asker):
|
||||
server = _LmStudio({"nomic": "embeddings"})
|
||||
ask, _ = asker(server, admin=False)
|
||||
assert ask("cold").status_code == 200
|
||||
assert set(server.loaded) == {"nomic", "cold"}
|
||||
|
||||
|
||||
def test_an_administrator_switches_and_the_embeddings_survive(asker):
|
||||
server = _LmStudio({"qwen": "llm", "picture": "vlm", "nomic": "embeddings"})
|
||||
ask, _ = asker(server, admin=True)
|
||||
assert ask("cold").status_code == 200
|
||||
assert set(server.loaded) == {"nomic", "cold"}
|
||||
assert server.writes[-1] == ("load", {"model": "cold", "context_length": model_server.DEFAULT_CONTEXT})
|
||||
|
||||
|
||||
def test_the_lock_decides_again_when_someone_ahead_loaded_another_model(monkeypatch):
|
||||
server = _LmStudio({"qwen": "llm"})
|
||||
monkeypatch.setattr(model_server, "_json", server)
|
||||
with pytest.raises(model_server.ModelBusy) as refused:
|
||||
asyncio.run(model_server.ensure_loaded("http://h", None, "cold", may_switch=False))
|
||||
assert refused.value.running == "qwen" and server.writes == []
|
||||
|
||||
|
||||
def test_losing_that_race_reaches_the_console_as_the_same_refusal(asker, monkeypatch):
|
||||
server = _LmStudio({})
|
||||
ask, _ = asker(server, admin=False)
|
||||
|
||||
async def lost(*_a, **_k):
|
||||
raise model_server.ModelBusy("qwen")
|
||||
monkeypatch.setattr(model_server, "ensure_loaded", lost)
|
||||
resp = ask("cold")
|
||||
assert '"code": "model_busy"' in resp.text and "Teraz działa model qwen" in resp.text
|
||||
|
||||
|
||||
def test_a_model_loaded_ahead_in_the_queue_is_not_loaded_twice(monkeypatch):
|
||||
server = _LmStudio({"qwen": "llm"})
|
||||
monkeypatch.setattr(model_server, "_json", server)
|
||||
asyncio.run(model_server.ensure_loaded("http://h", None, "qwen", may_switch=False))
|
||||
assert server.writes == []
|
||||
|
||||
|
||||
def test_an_instance_the_typed_listing_does_not_report_is_not_unloaded(monkeypatch):
|
||||
server = _LmStudio({"qwen": "llm", "nomic": "embeddings"})
|
||||
|
||||
async def v0_without_nomic(client, method, url, key, body=None):
|
||||
got = await server(client, method, url, key, body)
|
||||
if "/api/v0/" in url:
|
||||
got["data"] = [m for m in got["data"] if m["id"] != "nomic"]
|
||||
return got
|
||||
monkeypatch.setattr(model_server, "_json", v0_without_nomic)
|
||||
asyncio.run(model_server.ensure_loaded("http://h", None, "cold", may_switch=True))
|
||||
assert set(server.loaded) == {"nomic", "cold"}
|
||||
|
||||
|
||||
# ── the question ────────────────────────────────────────────────────────
|
||||
|
||||
def _ask(**fields) -> models.AskIn:
|
||||
return models.AskIn(model="m", **{"messages": [{"role": "user", "content": "?"}], **fields})
|
||||
|
||||
|
||||
def test_tools_and_tool_calls_count_toward_the_cap():
|
||||
plain = models.prompt_size(_ask())
|
||||
big = {"type": "function", "function": {"name": "f", "description": "x" * 50_000}}
|
||||
assert models.prompt_size(_ask(tools=[big])) > plain + 50_000
|
||||
call = {"role": "assistant", "tool_calls": [{"id": "1", "function": {"arguments": "y" * 50_000}}]}
|
||||
assert models.prompt_size(_ask(messages=[{"role": "user", "content": "?"}, call])) > plain + 50_000
|
||||
|
||||
|
||||
def test_the_ask_limit_counts_per_person():
|
||||
a, b = uuid.uuid4(), uuid.uuid4()
|
||||
for _ in range(models.ASKS_PER_MINUTE):
|
||||
models._rate_limit(a)
|
||||
with pytest.raises(ConflictError):
|
||||
models._rate_limit(a)
|
||||
models._rate_limit(b)
|
||||
|
||||
|
||||
def test_unset_knobs_leave_the_models_defaults():
|
||||
assert models._sampling(_ask()) == {}
|
||||
assert models._sampling(_ask(thinking=True)) == {}
|
||||
|
||||
|
||||
def test_set_knobs_reach_the_server_and_thinking_off_is_reasoning_effort_none():
|
||||
sent = models._sampling(_ask(temperature=0.2, top_p=0.9, top_k=40, presence_penalty=1.5,
|
||||
thinking=False, max_tokens=512))
|
||||
assert sent == {"temperature": 0.2, "top_p": 0.9, "top_k": 40, "presence_penalty": 1.5,
|
||||
"reasoning_effort": "none"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("knob, ok, bad", [
|
||||
("temperature", (0, 2), (-0.1, 2.1)),
|
||||
("top_p", (0, 1), (-0.1, 1.1)),
|
||||
("top_k", (1, 200), (0, 201)),
|
||||
("presence_penalty", (-2, 2), (-2.1, 2.1)),
|
||||
("max_tokens", (64, 16384), (63, 16385)),
|
||||
])
|
||||
def test_knobs_outside_their_range_are_refused(knob, ok, bad):
|
||||
for value in ok:
|
||||
_ask(**{knob: value})
|
||||
for value in bad:
|
||||
with pytest.raises(ValidationError):
|
||||
_ask(**{knob: value})
|
||||
|
||||
|
||||
# ── what is gone ────────────────────────────────────────────────────────
|
||||
|
||||
def test_there_is_no_door_for_modules_and_no_stored_choice():
|
||||
paths = {getattr(r, "path", "") for _, r in iter_routes(app.routes)}
|
||||
assert "/api/v1/models" in paths and "/api/v1/models/ask" in paths
|
||||
assert not any(p.startswith("/api/v1/gateway") or p == "/api/v1/models/choice" for p in paths)
|
||||
|
||||
|
||||
def test_claude_is_not_sent_the_knobs_it_refuses():
|
||||
# claude-opus-5-5 answered 400 "`temperature` is deprecated for this model" (2026-11-06).
|
||||
sent = models._sampling(_ask(temperature=0.2, top_p=0.9, top_k=40, presence_penalty=1.5, thinking=False),
|
||||
"anthropic")
|
||||
assert sent == {"presence_penalty": 1.5, "reasoning_effort": "none"}
|
||||
|
||||
|
||||
def test_a_refused_call_says_why(monkeypatch):
|
||||
import httpx
|
||||
|
||||
def handler(req):
|
||||
body = b'{"error": {"message": "`temperature` is deprecated for this model."}}'
|
||||
return httpx.Response(400, stream=httpx.ByteStream(body)) # streamed, as the network gives it
|
||||
real = httpx.AsyncClient
|
||||
monkeypatch.setattr(model_server.httpx, "AsyncClient",
|
||||
lambda **kw: real(transport=httpx.MockTransport(handler), **kw))
|
||||
|
||||
async def run():
|
||||
async for _ in model_server.stream_chat("http://h", "k", "m", [], 64):
|
||||
pass
|
||||
with pytest.raises(model_server.GatewayError, match="temperature"):
|
||||
asyncio.run(run())
|
||||
|
||||
|
||||
def test_the_answer_is_asked_for_uncompressed(monkeypatch):
|
||||
# The bytes are passed through raw with no Content-Encoding: a gzipped stream reached the chat
|
||||
# as garbage (api.anthropic.com, 2026-11-06).
|
||||
import httpx
|
||||
seen = []
|
||||
|
||||
def handler(req):
|
||||
seen.append(req.headers.get("accept-encoding"))
|
||||
return httpx.Response(200, stream=httpx.ByteStream(b"data: [DONE]\n\n"))
|
||||
real = httpx.AsyncClient
|
||||
monkeypatch.setattr(model_server.httpx, "AsyncClient",
|
||||
lambda **kw: real(transport=httpx.MockTransport(handler), **kw))
|
||||
|
||||
async def run():
|
||||
return [c async for c in model_server.stream_chat("http://h", "k", "m", [], 64)]
|
||||
assert asyncio.run(run()) == [b"data: [DONE]\n\n"] and seen == ["identity"]
|
||||
@@ -0,0 +1,25 @@
|
||||
"""A module the front door serves opens at its own path when no administrator typed an address."""
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services import marketplace
|
||||
|
||||
|
||||
def _m(slug, url=None):
|
||||
return SimpleNamespace(slug=slug, url=url)
|
||||
|
||||
|
||||
def test_admin_address_wins(monkeypatch):
|
||||
monkeypatch.setattr(marketplace, "served_here", lambda slug: True)
|
||||
assert marketplace.module_url(_m("lexicon", "https://x.example/lexicon")) == "https://x.example/lexicon"
|
||||
|
||||
|
||||
def test_served_module_defaults_to_its_path(monkeypatch):
|
||||
monkeypatch.setattr(marketplace, "served_here", lambda slug: slug == "lexicon")
|
||||
assert marketplace.module_url(_m("lexicon")) == "../lexicon/"
|
||||
assert marketplace.module_url(_m("galena")) is None
|
||||
|
||||
|
||||
def test_standalone_has_no_default(monkeypatch):
|
||||
monkeypatch.setattr(marketplace.get_settings(), "frontdoor_upstreams", "")
|
||||
assert marketplace.served_here("lexicon") is False
|
||||
assert marketplace.module_url(_m("lexicon")) is None
|
||||
@@ -1,10 +1,10 @@
|
||||
"""The hub's provider-key cipher against Compass's own code, in both directions. DB-free.
|
||||
"""The hub's provider-key cipher against Arbiter's own code, in both directions. DB-free.
|
||||
|
||||
Compass's analyses decrypt the keys Atrium writes, and Atrium reads the keys Compass imported, so the
|
||||
two copies of the cipher (`app/provider_keys.py` here, `apps/compass/backend/app/provider_keys.py`
|
||||
Arbiter's runs decrypt the keys Atrium writes (Compass, retired, did the same before it), so the
|
||||
two copies of the cipher (`app/provider_keys.py` here, `apps/arbiter/backend/app/provider_keys.py`
|
||||
there) must agree byte for byte: the same Argon2id-derived key, the same salt, the same
|
||||
`v1.<nonce>.<ct>` packing. Compass's file is loaded straight from the vendored
|
||||
`deploy/modules/compass` checkout, by path, so this tests the code that actually ships there.
|
||||
`v1.<nonce>.<ct>` packing. Arbiter's file is loaded straight from the vendored
|
||||
`deploy/modules/arbiter` checkout, by path, so this tests the code that actually ships there.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -17,50 +17,50 @@ import pytest
|
||||
|
||||
from app import provider_keys
|
||||
|
||||
_COMPASS = (Path(__file__).resolve().parents[2] / "deploy" / "modules" / "compass" / "apps"
|
||||
/ "compass" / "backend" / "app" / "provider_keys.py")
|
||||
_ARBITER = (Path(__file__).resolve().parents[2] / "deploy" / "modules" / "arbiter" / "apps"
|
||||
/ "arbiter" / "backend" / "app" / "provider_keys.py")
|
||||
SECRET = "a-platform-secret-for-the-tests-0123456789"
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def compass():
|
||||
if not _COMPASS.exists():
|
||||
pytest.skip("the vendored Compass checkout is not present")
|
||||
spec = importlib.util.spec_from_file_location("compass_provider_keys", _COMPASS)
|
||||
def arbiter():
|
||||
if not _ARBITER.exists():
|
||||
pytest.skip("the vendored Arbiter checkout is not present")
|
||||
spec = importlib.util.spec_from_file_location("arbiter_provider_keys", _ARBITER)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def test_the_salt_is_the_platforms(compass):
|
||||
assert provider_keys.SALT == compass.SALT == b"dredd.model_provider.v1"
|
||||
def test_the_salt_is_the_platforms(arbiter):
|
||||
assert provider_keys.SALT == arbiter.SALT == b"dredd.model_provider.v1"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", ["sk-abc123def456", "zażółć-gęślą-🔑", "x" * 400])
|
||||
def test_atrium_writes_and_compass_reads(compass, key):
|
||||
def test_atrium_writes_and_compass_reads(arbiter, key):
|
||||
stored = provider_keys.encrypt(key, SECRET)
|
||||
assert stored.startswith("v1.") and stored.count(".") == 2
|
||||
assert key not in stored
|
||||
assert compass.decrypt(stored, SECRET) == key
|
||||
assert arbiter.decrypt(stored, SECRET) == key
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", ["sk-abc123def456", "zażółć-gęślą-🔑"])
|
||||
def test_compass_writes_and_atrium_reads(compass, key):
|
||||
assert provider_keys.decrypt(compass.encrypt(key, SECRET), SECRET) == key
|
||||
def test_compass_writes_and_atrium_reads(arbiter, key):
|
||||
assert provider_keys.decrypt(arbiter.encrypt(key, SECRET), SECRET) == key
|
||||
|
||||
|
||||
def test_compass_derives_the_secret_atrium_uses_on_the_platform(compass):
|
||||
"""On the platform Compass encrypts under MODEL_PROVIDER_SECRET and nothing else — the value the
|
||||
def test_compass_derives_the_secret_atrium_uses_on_the_platform(arbiter):
|
||||
"""On the platform Arbiter encrypts under MODEL_PROVIDER_SECRET and nothing else — the value the
|
||||
hub's `services/providers.py` reads — so the two settings files hold one value."""
|
||||
settings = SimpleNamespace(model_provider_secret=f" {SECRET} ", shares_identity=True,
|
||||
secret_key="compass-only")
|
||||
assert compass.secret(settings) == SECRET
|
||||
secret_key="arbiter-only")
|
||||
assert arbiter.secret(settings) == SECRET
|
||||
|
||||
|
||||
def test_a_wrong_secret_or_a_tampered_row_reads_as_none(compass):
|
||||
def test_a_wrong_secret_or_a_tampered_row_reads_as_none(arbiter):
|
||||
stored = provider_keys.encrypt("sk-secret", SECRET)
|
||||
assert provider_keys.decrypt(stored, "another-secret") is None
|
||||
assert compass.decrypt(stored, "another-secret") is None
|
||||
assert arbiter.decrypt(stored, "another-secret") is None
|
||||
version, nonce, blob = stored.split(".")
|
||||
tampered = ".".join((version, nonce, ("A" if blob[0] != "A" else "B") + blob[1:]))
|
||||
assert provider_keys.decrypt(tampered, SECRET) is None
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""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, offers nothing that fetches a
|
||||
provider, and is in both languages. That the routes really behave is
|
||||
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
|
||||
@@ -36,8 +36,9 @@ def _i18n(console: str) -> set[str]:
|
||||
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
|
||||
admin_nav = console.split("const ADMIN_NAV = [", 1)[1].split("];", 1)[0]
|
||||
assert "'#/admin/providers'" in admin_nav
|
||||
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
|
||||
|
||||
@@ -65,23 +66,68 @@ def test_the_key_is_write_only_in_the_console_too(screen):
|
||||
assert "{ clear: ['api_key'] }" in screen
|
||||
|
||||
|
||||
def test_nothing_on_it_reaches_a_provider(screen):
|
||||
"""These endpoints store configuration; a "test connection" would make the hub fetch an
|
||||
administrator-typed URL."""
|
||||
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
|
||||
# The header comment says why there is none; no control may offer one.
|
||||
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(", "kindChip",
|
||||
"euChip", "keyCell", "p ?", "p &&", "writable", "rows.map",
|
||||
"p.is_active", "v.trains_on_data", "v.is_active",
|
||||
"policy.eu_only", "esc(")):
|
||||
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}}}")
|
||||
|
||||
@@ -91,16 +137,17 @@ def test_the_look_is_marked_as_replaceable(screen):
|
||||
|
||||
|
||||
@pytest.mark.parametrize("phrase", [
|
||||
"Dostawcy modeli", "Nowy dostawca", "Edytuj dostawcę", "Polityka użycia", "Kto może używać modeli",
|
||||
"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.",
|
||||
"Jeden model w wierszu: identyfikator | okno kontekstu | dialekt (openai albo chatml).",
|
||||
"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
|
||||
@@ -111,6 +158,84 @@ 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
|
||||
assert "throw httpError(res, data)" in api # the refusal is worded in one place for api() and arbiter()
|
||||
refused = console.split("function httpError(", 1)[1].split("\n}\n", 1)[0]
|
||||
assert "coreRefusal(data)" in refused
|
||||
body = console.split("function coreRefusal(", 1)[1].split("\n}\n", 1)[0]
|
||||
assert "problem.en" in body and "LANG === SRC_LANG" in body
|
||||
|
||||
|
||||
@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
|
||||
|
||||
|
||||
# ── 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]
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
"""`providers.discover` with `list_models` replaced: the key-prefix table, address vs key, local vs
|
||||
external host, a non-http scheme refused, and an audit row that names the host and never the key."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import types
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
|
||||
from app.errors import ValidationError
|
||||
from app.services import providers
|
||||
|
||||
MODELS = [{"id": "m-1", "dialect": "openai"}]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def calls(monkeypatch):
|
||||
seen = {"list": [], "audit": []}
|
||||
|
||||
async def fake_list(base_url, key, vendor):
|
||||
seen["list"].append((base_url, key, vendor))
|
||||
return MODELS
|
||||
|
||||
monkeypatch.setattr(providers.model_server, "list_models", fake_list)
|
||||
monkeypatch.setattr(providers.audit, "record", lambda db, **kw: seen["audit"].append(kw))
|
||||
return seen
|
||||
|
||||
|
||||
def _discover(text, key=None):
|
||||
actor = types.SimpleNamespace(id=uuid.uuid4())
|
||||
return asyncio.run(providers.discover(object(), actor, text, key, ip="10.0.0.1"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key, vendor, name, base", [
|
||||
("sk-ant-api03-abc", "anthropic", "Anthropic", "https://api.anthropic.com/v1"),
|
||||
("sk-or-v1-abc", "openrouter", "OpenRouter", "https://openrouter.ai/api/v1"),
|
||||
("sk-proj-abc", "openai", "OpenAI", "https://api.openai.com/v1"),
|
||||
])
|
||||
def test_each_key_prefix_names_its_vendor(calls, key, vendor, name, base):
|
||||
out = _discover(f" {key} ")
|
||||
assert out == {"vendor": vendor, "name": name, "kind": "api", "base_url": base, "models": MODELS}
|
||||
assert calls["list"] == [(base, key, vendor)]
|
||||
|
||||
|
||||
def test_an_unknown_key_asks_for_an_address(calls):
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
_discover("xai-abcdef")
|
||||
assert exc.value.extra["code"] == "provider_unknown_key"
|
||||
assert calls["list"] == [] and calls["audit"] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url, kind, host", [
|
||||
("http://localhost:1234/v1", "local", "localhost"),
|
||||
("http://127.0.0.1:1234", "local", "127.0.0.1"),
|
||||
("http://[::1]:8080", "local", "::1"),
|
||||
("http://host.docker.internal:1234/", "local", "host.docker.internal"),
|
||||
("https://gpu.example.com:8000/v1", "api", "gpu.example.com"),
|
||||
("http://localhost.evil.example", "api", "localhost.evil.example"),
|
||||
])
|
||||
def test_an_address_is_local_only_on_this_machine(calls, url, kind, host):
|
||||
out = _discover(url, key=" srv-key ")
|
||||
assert (out["vendor"], out["name"], out["kind"]) == (None, host, kind)
|
||||
assert out["base_url"] == url.rstrip("/")
|
||||
assert calls["list"] == [(url.rstrip("/"), "srv-key", None)]
|
||||
|
||||
|
||||
def test_an_address_without_a_key_sends_none(calls):
|
||||
_discover("http://localhost:1234")
|
||||
assert calls["list"][0][1] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("url", ["ftp://gpu.example.com", "file:///etc/passwd",
|
||||
"http://user:pw@gpu.example.com"])
|
||||
def test_a_non_http_address_or_one_with_credentials_is_refused(calls, url):
|
||||
with pytest.raises(ValidationError):
|
||||
_discover(url)
|
||||
assert calls["list"] == []
|
||||
|
||||
|
||||
def test_the_audit_names_the_host_and_never_the_key(calls):
|
||||
key = "sk-ant-api03-very-secret"
|
||||
_discover(key)
|
||||
(row,) = calls["audit"]
|
||||
assert row["action"] == "model_provider.discover"
|
||||
assert row["detail"] == "api.anthropic.com"
|
||||
assert key not in json.dumps(row, default=str)
|
||||
|
||||
|
||||
def test_a_refused_listing_propagates_and_writes_no_audit(monkeypatch, calls):
|
||||
async def refuse(*_a):
|
||||
raise ValidationError("x", {"code": "provider_key_refused"})
|
||||
|
||||
monkeypatch.setattr(providers.model_server, "list_models", refuse)
|
||||
with pytest.raises(ValidationError):
|
||||
_discover("sk-proj-abc")
|
||||
assert calls["audit"] == []
|
||||
|
||||
|
||||
# ── refresh: a stored provider's models re-read, through `update` ────────────
|
||||
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"}])
|
||||
seen = {"list": [], "update": [], "commits": 0, "listing": MODELS}
|
||||
|
||||
async def fake_list(base_url, key, vendor):
|
||||
seen["list"].append((base_url, key, vendor))
|
||||
if isinstance(seen["listing"], Exception):
|
||||
raise seen["listing"]
|
||||
return seen["listing"]
|
||||
|
||||
def fake_update(db, actor, provider_id, fields, *, ip):
|
||||
seen["update"].append(fields)
|
||||
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)
|
||||
monkeypatch.setattr(providers.core, "api_key", lambda _db, _p, _decrypt: KEY)
|
||||
monkeypatch.setattr(providers.model_server, "list_models", fake_list)
|
||||
monkeypatch.setattr(providers, "update", fake_update)
|
||||
return row, seen, db
|
||||
|
||||
|
||||
def _refresh(row, db):
|
||||
actor = types.SimpleNamespace(id=uuid.uuid4())
|
||||
return asyncio.run(providers.refresh(db, actor, row.id, ip="10.0.0.1"))
|
||||
|
||||
|
||||
def test_refresh_replaces_the_models_and_ends_the_read_first(stored):
|
||||
row, seen, db = stored
|
||||
out = _refresh(row, db)
|
||||
assert out["models"] == MODELS and row.models == MODELS
|
||||
assert seen["list"] == [("https://api.anthropic.com/v1", KEY, "anthropic")]
|
||||
assert seen["commits"] == 1
|
||||
# Only the models go to `update`: its audit diff can never carry the key.
|
||||
assert seen["update"] == [{"models": MODELS}]
|
||||
assert KEY not in json.dumps(seen["update"])
|
||||
|
||||
|
||||
def test_a_refused_listing_keeps_the_old_models(stored):
|
||||
row, seen, db = stored
|
||||
seen["listing"] = ValidationError("Brak modeli.", {"code": "provider_no_models", "en": "No models."})
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
_refresh(row, db)
|
||||
assert exc.value.extra["code"] == "provider_no_models"
|
||||
assert seen["update"] == [] and row.models == [{"id": "old", "dialect": "openai"}]
|
||||
|
||||
|
||||
def test_refresh_of_a_keyless_local_server_sends_no_key(stored):
|
||||
row, seen, db = stored
|
||||
row.base_url, row.key_prefix = "http://localhost:1234", None
|
||||
_refresh(row, db)
|
||||
assert seen["list"] == [("http://localhost:1234", None, None)]
|
||||
|
||||
|
||||
def test_an_unreadable_key_refuses_before_calling(stored, monkeypatch):
|
||||
row, seen, db = stored
|
||||
monkeypatch.setattr(providers.core, "api_key", lambda *_: None)
|
||||
with pytest.raises(providers.ConflictError) as exc:
|
||||
_refresh(row, db)
|
||||
assert exc.value.extra["code"] == providers.KEY_UNREADABLE
|
||||
assert seen["list"] == [] and seen["update"] == []
|
||||
|
||||
|
||||
@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):
|
||||
out = _discover(url, key="k")
|
||||
assert out["vendor"] == vendor and calls["list"][0][2] == vendor
|
||||
|
||||
|
||||
def test_a_provider_with_hundreds_of_models_can_be_added():
|
||||
from app.schemas import ProviderCreateIn, ProviderUpdateIn
|
||||
models = [{"id": f"m-{i}", "dialect": "openai"} for i in range(400)]
|
||||
ProviderCreateIn(name="OpenRouter", kind="api", base_url="https://openrouter.ai/api/v1",
|
||||
models=models, trains_on_data=False)
|
||||
ProviderUpdateIn(models=models)
|
||||
@@ -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
|
||||
|
||||
@@ -25,8 +25,8 @@ 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")
|
||||
_COMPASS = (Path(__file__).resolve().parents[2] / "deploy" / "modules" / "compass" / "apps"
|
||||
/ "compass" / "backend" / "app" / "provider_keys.py")
|
||||
_ARBITER = (Path(__file__).resolve().parents[2] / "deploy" / "modules" / "arbiter" / "apps"
|
||||
/ "arbiter" / "backend" / "app" / "provider_keys.py")
|
||||
|
||||
|
||||
def _body(**over) -> dict:
|
||||
@@ -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():
|
||||
@@ -153,11 +155,11 @@ def test_the_key_is_write_only_and_compass_reads_it(admin_client):
|
||||
|
||||
from app.models import ModelProvider
|
||||
|
||||
if not _COMPASS.exists():
|
||||
pytest.skip("the vendored Compass checkout is not present")
|
||||
spec = importlib.util.spec_from_file_location("compass_provider_keys", _COMPASS)
|
||||
compass = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(compass)
|
||||
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"
|
||||
@@ -171,7 +173,7 @@ def test_the_key_is_write_only_and_compass_reads_it(admin_client):
|
||||
def read_back():
|
||||
with _db() as db:
|
||||
return core.api_key(db, db.get(ModelProvider, uuid.UUID(pid)),
|
||||
lambda stored: compass.decrypt(stored, secret))
|
||||
lambda stored: arbiter.decrypt(stored, secret))
|
||||
assert read_back() == key
|
||||
|
||||
# Leaving the key out keeps it; sending one replaces it; clearing it removes it.
|
||||
@@ -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})
|
||||
@@ -234,3 +262,78 @@ 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"]
|
||||
|
||||
|
||||
# ── 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
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
"""The two routes that call a provider: administrator-only, routed before `/{provider_id}`, and
|
||||
SQL-free (the router validates and calls the service, nothing else)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import pathlib
|
||||
import re
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services import providers
|
||||
from tests.test_hub_gates_unit import _person, api # noqa: F401 (fixture)
|
||||
|
||||
ROUTER = pathlib.Path(__file__).resolve().parents[1] / "app" / "routers" / "admin_providers.py"
|
||||
BASE = "/api/v1/admin/model-providers"
|
||||
|
||||
|
||||
def test_both_routes_are_in_the_openapi_document():
|
||||
from app.main import app
|
||||
paths = app.openapi()["paths"]
|
||||
assert "post" in paths[f"{BASE}/discover"]
|
||||
assert "post" in paths[f"{BASE}/{{provider_id}}/refresh"]
|
||||
|
||||
|
||||
def test_the_router_holds_no_sql():
|
||||
assert not re.search(r"select\(|db\.execute|db\.add", ROUTER.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path, body", [
|
||||
(f"{BASE}/discover", {"input": "sk-ant-secret"}),
|
||||
(f"{BASE}/{uuid.uuid4()}/refresh", None),
|
||||
])
|
||||
def test_a_plain_user_gets_what_other_admin_routes_answer(api, monkeypatch, path, body): # noqa: F811
|
||||
called = []
|
||||
monkeypatch.setattr(providers, "discover", lambda *a, **k: called.append(a))
|
||||
monkeypatch.setattr(providers, "refresh", lambda *a, **k: called.append(a))
|
||||
api.who(_person())
|
||||
reference = api.client.get(f"{BASE}/policy")
|
||||
r = api.client.post(path, json=body)
|
||||
assert r.status_code == reference.status_code and r.status_code in (403, 404)
|
||||
assert not called
|
||||
|
||||
|
||||
def test_discover_is_not_parsed_as_an_id(api, monkeypatch): # noqa: F811
|
||||
async def fake(db, actor, text, key, *, ip):
|
||||
return {"vendor": "anthropic", "name": "Anthropic", "kind": "api",
|
||||
"base_url": "https://api.anthropic.com/v1", "models": [{"id": "claude-x"}]}
|
||||
monkeypatch.setattr(providers, "discover", fake)
|
||||
api.who(_person(admin=True))
|
||||
r = api.client.post(f"{BASE}/discover", json={"input": "sk-ant-secret"})
|
||||
assert r.status_code == 200, r.text
|
||||
assert r.json()["vendor"] == "anthropic"
|
||||
assert api.db.calls == ["commit", "commit"]
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Workflow (slug `compass`) is retired: the seed no longer offers it, revision 0014 removes it."""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
from app import frontdoor
|
||||
from app.seed import ADDED_AFTER_FIRST_SEED, FAMILY
|
||||
|
||||
REV = Path(__file__).resolve().parents[1] / "alembic" / "versions" / "0014_retire_workflow.py"
|
||||
|
||||
|
||||
def _revision():
|
||||
spec = importlib.util.spec_from_file_location("rev0014", REV)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(mod)
|
||||
return mod
|
||||
|
||||
|
||||
def test_the_catalogue_and_the_front_door_no_longer_know_compass():
|
||||
assert "compass" not in {e["slug"] for e in FAMILY}
|
||||
assert "compass" not in ADDED_AFTER_FIRST_SEED
|
||||
assert "compass" not in frontdoor.MODULES
|
||||
assert b"/compass" not in frontdoor.NOT_FOUND
|
||||
|
||||
|
||||
def test_revision_0014_follows_0013_and_targets_the_compass_slug():
|
||||
rev = _revision()
|
||||
assert (rev.revision, rev.down_revision) == ("0014", "0013")
|
||||
assert rev.SLUG == "compass"
|
||||
|
||||
|
||||
def test_revision_0014_carries_no_bind_parameter_text():
|
||||
"""op.execute/text() scan a statement for `:name`; the one text() here must carry none."""
|
||||
source = REV.read_text(encoding="utf-8")
|
||||
statement = source.split('sa.text("', 1)[1].split('")', 1)[0]
|
||||
assert ":" not in statement
|
||||
@@ -0,0 +1,113 @@
|
||||
"""The review panel's polling and acceptance, and the home page's ways into Galena, run under Node
|
||||
with the DOM and the modules stubbed. DB-free; skipped where no `node`."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
NODE = shutil.which("node")
|
||||
SRC = (ROOT / "frontend" / "app.js").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _between(start: str, end: str) -> str:
|
||||
i = SRC.index(start)
|
||||
return SRC[i:SRC.index(end, i)]
|
||||
|
||||
|
||||
CONSTS = _between("const CHAT_REVIEW_POLL_MS = ", "// A Galena project's document file")
|
||||
PANEL = _between("const reviewPanel = ", "/* An Atrium GET answered as text")
|
||||
LINKS = _between("function homeGalenaLinks()", "async function loadHomeStats()")
|
||||
|
||||
DOM = """
|
||||
const els = {};
|
||||
const mk = (id) => ({ id, innerHTML: '', textContent: '', value: '', attrs: {},
|
||||
classList: { add() {}, remove() {} }, setAttribute(k, v) { this.attrs[k] = v; } });
|
||||
const $ = (id) => els[id] || null;
|
||||
const document = { baseURI: 'http://x/atrium/', body: { appendChild(el) { els[el.id] = el; } },
|
||||
createElement: () => mk(null) };
|
||||
const esc = (s) => String(s); const svg = () => ''; const ICN = { x: 'x', check: 'c' };
|
||||
const _tr = (s) => s; const localize = () => {}; const toasts = []; const toast = (t) => toasts.push(t);
|
||||
const timers = []; const setTimeout = (f, ms) => { timers.push(ms); return timers.length; };
|
||||
const clearTimeout = () => {};
|
||||
const pending = [];
|
||||
const arbiter = (method, path, body) => new Promise((ok, no) => pending.push({ method, path, ok, no }));
|
||||
const tick = () => new Promise((r) => setImmediate(r));
|
||||
"""
|
||||
|
||||
|
||||
def _node(body: str) -> dict:
|
||||
script = DOM + CONSTS + PANEL + "\n(async () => {\n" + body + "\n})().catch((e) => { console.error(e); process.exit(1); });"
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60, encoding="utf-8")
|
||||
assert r.returncode == 0, r.stderr
|
||||
return json.loads(r.stdout)
|
||||
|
||||
|
||||
A = "{ id: 'a1', number: 'UM-1', name: 'Najem', skill: 'S', n: 1 }"
|
||||
B = "{ id: 'b2', number: 'UM-2', name: 'Dostawa', skill: 'S', n: 1 }"
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_a_late_answer_for_a_replaced_run_draws_nothing() -> None:
|
||||
out = _node(f"""
|
||||
reviewOpen({A});
|
||||
reviewOpen({B});
|
||||
pending[0].ok({{ status: 'running' }}); // the first run's answer comes last
|
||||
await tick();
|
||||
pending[1].ok({{ status: 'running' }});
|
||||
await tick();
|
||||
console.log(JSON.stringify({{ html: els.reviewPanel.innerHTML, timers }}));
|
||||
""")
|
||||
assert "UM-2" in out["html"] and "UM-1" not in out["html"]
|
||||
assert out["timers"] == [3000]
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_polling_backs_off_and_gives_up() -> None:
|
||||
out = _node(f"""
|
||||
reviewOpen({A});
|
||||
for (let i = 0; i < 6; i++) {{ pending[i].ok({{ status: 'running' }}); await tick(); reviewPoll(); }}
|
||||
reviewPanel.analysis.since -= CHAT_REVIEW_GIVE_UP_MS + 1;
|
||||
const before = timers.length;
|
||||
pending[6].ok({{ status: 'running' }}); await tick();
|
||||
console.log(JSON.stringify({{ timers, stopped: timers.length === before, html: els.reviewPanel.innerHTML }}));
|
||||
""")
|
||||
assert out["timers"][:6] == [3000, 6000, 12000, 24000, 30000, 30000]
|
||||
assert out["stopped"] and "dłużej niż zwykle" in out["html"]
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_an_acceptance_answered_after_the_panel_closed_touches_nothing() -> None:
|
||||
out = _node(f"""
|
||||
reviewOpen({A});
|
||||
pending[0].ok({{ status: 'done' }}); await tick();
|
||||
els.rpErr = mk('rpErr');
|
||||
reviewAccept();
|
||||
reviewClose();
|
||||
pending[1].no(new Error('late refusal')); await tick();
|
||||
console.log(JSON.stringify({{ err: els.rpErr.textContent, accepted: pending[1].path, polls: pending.length }}));
|
||||
""")
|
||||
assert out["accepted"] == "analyses/a1/acceptance"
|
||||
assert out["err"] == "" and out["polls"] == 2
|
||||
|
||||
|
||||
def _links(launcher) -> str:
|
||||
script = (f"const state = {{ launcher: {json.dumps(launcher)} }};\n"
|
||||
"const esc = (s) => String(s); const moduleIcon = () => '<i></i>';\n"
|
||||
"const frameHash = (slug, inner) => '#/m/' + slug + '/' + inner;\n"
|
||||
+ LINKS + "\nconsole.log(JSON.stringify(homeGalenaLinks()));")
|
||||
r = subprocess.run([NODE, "-e", script], capture_output=True, text=True, timeout=60, encoding="utf-8")
|
||||
assert r.returncode == 0, r.stderr
|
||||
return json.loads(r.stdout)
|
||||
|
||||
|
||||
@pytest.mark.skipif(NODE is None, reason="needs node on PATH")
|
||||
def test_the_ways_into_galena_are_shown_only_with_access() -> None:
|
||||
html = _links([{"slug": "galena", "has_access": True}])
|
||||
assert 'href="#/m/galena/"' in html and 'href="#/m/galena/cards"' in html
|
||||
assert _links([{"slug": "galena", "has_access": False}]) == ""
|
||||
assert _links([{"slug": "sygna", "has_access": True}]) == ""
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Revision 0016: `module.in_menu`, and Galena becomes a service module (DB-free)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
BACKEND = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def revision():
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"revision_0016", BACKEND / "alembic" / "versions" / "0016_service_modules.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
class _Recorder:
|
||||
def __init__(self) -> None:
|
||||
self.sql: list[str] = []
|
||||
|
||||
def execute(self, stmt):
|
||||
self.sql.append(stmt if isinstance(stmt, str) else str(stmt.compile(
|
||||
dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True})))
|
||||
|
||||
def get_bind(self):
|
||||
return self
|
||||
|
||||
|
||||
def _run(revision, monkeypatch, fn: str) -> list[str]:
|
||||
rec = _Recorder()
|
||||
monkeypatch.setattr(revision, "op", rec)
|
||||
getattr(revision, fn)()
|
||||
return rec.sql
|
||||
|
||||
|
||||
def test_it_follows_the_skills_revision(revision):
|
||||
assert (revision.revision, revision.down_revision) == ("0016", "0015")
|
||||
|
||||
|
||||
def test_upgrade_is_idempotent_and_touches_only_galena(revision, monkeypatch):
|
||||
add, switch = _run(revision, monkeypatch, "upgrade")
|
||||
# 0001 builds `module` from the live metadata on a fresh database, so the column may exist.
|
||||
assert "ADD COLUMN IF NOT EXISTS in_menu boolean NOT NULL DEFAULT true" in add
|
||||
assert switch.startswith("UPDATE module SET in_menu=false")
|
||||
assert "WHERE module.slug = 'galena'" in switch
|
||||
|
||||
|
||||
def test_downgrade_drops_only_the_column(revision, monkeypatch):
|
||||
assert _run(revision, monkeypatch, "downgrade") == [
|
||||
"ALTER TABLE module DROP COLUMN IF EXISTS in_menu"]
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def arbiter_revision():
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"revision_0017", BACKEND / "alembic" / "versions" / "0017_arbiter_service.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def test_0017_makes_only_arbiter_a_service_and_back(arbiter_revision, monkeypatch):
|
||||
"""Contracts are checked from the chat, Arbiter has no console of its own."""
|
||||
assert (arbiter_revision.revision, arbiter_revision.down_revision) == ("0017", "0016")
|
||||
up, = _run(arbiter_revision, monkeypatch, "upgrade")
|
||||
assert up.startswith("UPDATE module SET in_menu=false") and "module.slug = 'arbiter'" in up
|
||||
down, = _run(arbiter_revision, monkeypatch, "downgrade")
|
||||
assert down.startswith("UPDATE module SET in_menu=true") and "module.slug = 'arbiter'" in down
|
||||
|
||||
|
||||
def test_0018_retires_only_panorama_from_the_menu(monkeypatch):
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"revision_0018", BACKEND / "alembic" / "versions" / "0018_panorama_retired.py")
|
||||
rev = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(rev)
|
||||
assert (rev.revision, rev.down_revision) == ("0018", "0017")
|
||||
up, = _run(rev, monkeypatch, "upgrade")
|
||||
assert up.startswith("UPDATE module SET in_menu=false") and "module.slug = 'panorama'" in up
|
||||
|
||||
|
||||
def test_panorama_is_off_the_platform():
|
||||
"""The seed no longer offers Panorama and the front door no longer routes it; an
|
||||
existing row stays, hidden from the menu by 0018 (above)."""
|
||||
from app import frontdoor
|
||||
from app.seed import ADDED_AFTER_FIRST_SEED, FAMILY
|
||||
|
||||
assert "panorama" not in {e["slug"] for e in FAMILY}
|
||||
assert "panorama" not in ADDED_AFTER_FIRST_SEED
|
||||
assert "panorama" not in frontdoor.MODULES
|
||||
assert b"/panorama" not in frontdoor.NOT_FOUND
|
||||
|
||||
|
||||
def test_0019_makes_lexicon_and_scribe_services_and_back(monkeypatch):
|
||||
"""Issue #53: no console of their own; the catalogue shows one „Umowy” entry for the three."""
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"revision_0019", BACKEND / "alembic" / "versions" / "0019_contracts_one_entry.py")
|
||||
rev = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(rev)
|
||||
assert (rev.revision, rev.down_revision) == ("0019", "0018")
|
||||
up, = _run(rev, monkeypatch, "upgrade")
|
||||
assert up.startswith("UPDATE module SET in_menu=false")
|
||||
assert "module.slug IN ('lexicon', 'scribe')" in up
|
||||
down, = _run(rev, monkeypatch, "downgrade")
|
||||
assert down.startswith("UPDATE module SET in_menu=true") and "('lexicon', 'scribe')" in down
|
||||
|
||||
|
||||
def test_the_console_shows_one_contracts_entry():
|
||||
console = (BACKEND.parent / "frontend" / "app.js").read_text(encoding="utf-8")
|
||||
assert "const CONTRACTS = ['arbiter', 'lexicon', 'scribe'];" in console
|
||||
assert "contractsNavItem(cur) + mods.map(modItem)" in console
|
||||
assert "d.modules.filter((m) => !CONTRACTS.includes(m.slug))" in console
|
||||
@@ -0,0 +1,470 @@
|
||||
"""`skill_pack.read_pack`: one test per archive rule, on ZIPs built in memory (DB-free)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import os
|
||||
import stat
|
||||
import warnings
|
||||
import zipfile
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services import skill_pack
|
||||
from app.services.skill_pack import PackRejected, read_pack
|
||||
|
||||
|
||||
def _zip(entries, *, compression=zipfile.ZIP_DEFLATED) -> bytes:
|
||||
"""`entries`: (name or ZipInfo, bytes). Names are written raw — see `_raw`."""
|
||||
buf = io.BytesIO()
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore") # the duplicate-name test writes one twice on purpose
|
||||
with zipfile.ZipFile(buf, "w", compression) as zf:
|
||||
for name, data in entries:
|
||||
zf.writestr(name, data)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def _raw(name: str) -> zipfile.ZipInfo:
|
||||
# On Windows the ZipInfo constructor rewrites `\` to `/`; setting the attribute afterwards keeps
|
||||
# the name exactly as an attacker's archive would carry it.
|
||||
info = zipfile.ZipInfo("placeholder")
|
||||
info.filename = name
|
||||
return info
|
||||
|
||||
|
||||
def _code(data: bytes) -> str:
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
read_pack(data)
|
||||
return caught.value.code
|
||||
|
||||
|
||||
SKILL = b"---\nname: nda\ndescription: Przeglad NDA\n---\n# NDA\n"
|
||||
|
||||
|
||||
def _lying_size(data: bytes, declared: int) -> bytes:
|
||||
"""Rewrite every header's uncompressed size to `declared` — a bomb's header lies about it."""
|
||||
out = bytearray(data)
|
||||
for sig, off in ((b"PK\x03\x04", 22), (b"PK\x01\x02", 24)):
|
||||
at = out.find(sig)
|
||||
while at != -1:
|
||||
out[at + off:at + off + 4] = declared.to_bytes(4, "little")
|
||||
at = out.find(sig, at + 4)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def test_a_member_lying_about_its_size_is_refused_without_inflating_it():
|
||||
import tracemalloc
|
||||
bomb = _lying_size(_zip([("s/notes.txt", b"\0" * (40 * 1024 * 1024))]), 1000)
|
||||
tracemalloc.start()
|
||||
try:
|
||||
assert _code(bomb) == "pack_not_zip"
|
||||
peak = tracemalloc.get_traced_memory()[1]
|
||||
finally:
|
||||
tracemalloc.stop()
|
||||
# An unbounded `zf.read` inflates all 40 MB before trimming to the declared 1000 bytes.
|
||||
assert peak < 5 * 1024 * 1024, peak
|
||||
|
||||
|
||||
def test_a_clean_pack_is_read():
|
||||
pack = read_pack(_zip([("nda/SKILL.md", SKILL), ("nda/resources/a.txt", b"x")]))
|
||||
assert pack.files == {"nda/SKILL.md": SKILL, "nda/resources/a.txt": b"x"}
|
||||
(skill,) = pack.skills
|
||||
assert (skill.path, skill.name, skill.description, skill.body, skill.info_only) \
|
||||
== ("nda/SKILL.md", "nda", "Przeglad NDA", "# NDA\n", {})
|
||||
|
||||
|
||||
def test_every_code_has_both_languages_and_rides_in_problem_details():
|
||||
err = PackRejected("pack_link", ["b", "a"])
|
||||
# Polish detail + English `en`, the shape the console's coreRefusal words in either language.
|
||||
assert err.extra == {"code": "pack_link", "files": ["a", "b"], "en": "The pack contains a link."}
|
||||
assert err.detail == "Paczka zawiera dowiązanie."
|
||||
assert err.status_code == 422
|
||||
for pl, en in skill_pack.MESSAGES.values():
|
||||
assert pl and en and pl != en
|
||||
|
||||
|
||||
def test_more_than_10_mb_is_refused():
|
||||
assert _code(b"\0" * (skill_pack.MAX_PACK_BYTES + 1)) == "pack_too_large"
|
||||
|
||||
|
||||
def test_not_a_zip_is_refused():
|
||||
assert _code(b"plain text, not an archive") == "pack_not_zip"
|
||||
|
||||
|
||||
def test_more_than_200_files_is_refused():
|
||||
data = _zip([(f"s/{i}.md", b"x") for i in range(skill_pack.MAX_FILES + 1)])
|
||||
assert _code(data) == "pack_too_many_files"
|
||||
|
||||
|
||||
def test_200_files_is_accepted():
|
||||
assert len(read_pack(_zip([(f"s/{i}.md", b"x") for i in range(200)])).files) == 200
|
||||
|
||||
|
||||
def test_more_than_50_mb_unpacked_is_refused():
|
||||
data = _zip([("s/big.txt", b"\0" * (skill_pack.MAX_UNPACKED_BYTES + 1))])
|
||||
assert len(data) < skill_pack.MAX_PACK_BYTES
|
||||
assert _code(data) == "pack_unpacked_too_large"
|
||||
|
||||
|
||||
def test_a_file_compressed_over_100_to_1_is_refused():
|
||||
assert _code(_zip([("s/bomb.txt", b"\0" * 1_000_000)])) == "pack_compression_ratio"
|
||||
|
||||
|
||||
def test_zip64_is_refused():
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w") as zf, zf.open("s/SKILL.md", "w", force_zip64=True) as f:
|
||||
f.write(b"# x")
|
||||
assert _code(buf.getvalue()) == "pack_zip64"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["s/../SKILL.md", "../SKILL.md"])
|
||||
def test_a_dot_dot_segment_is_refused(name):
|
||||
assert _code(_zip([(_raw(name), b"x")])) == "pack_bad_path"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["/etc/SKILL.md", "C:/SKILL.md"])
|
||||
def test_an_absolute_path_is_refused(name):
|
||||
assert _code(_zip([(_raw(name), b"x")])) == "pack_bad_path"
|
||||
|
||||
|
||||
def test_a_backslash_is_refused():
|
||||
assert _code(_zip([(_raw("s\\SKILL.md"), b"x")])) == "pack_bad_path"
|
||||
|
||||
|
||||
def test_a_symlink_is_refused():
|
||||
info = zipfile.ZipInfo("s/link.md")
|
||||
info.external_attr = (stat.S_IFLNK | 0o777) << 16
|
||||
assert _code(_zip([(info, b"/etc/passwd")])) == "pack_link"
|
||||
|
||||
|
||||
def test_a_duplicate_name_is_refused():
|
||||
assert _code(_zip([("s/SKILL.md", b"a"), ("s/SKILL.md", b"b")])) == "pack_duplicate_name"
|
||||
|
||||
|
||||
def test_names_differing_only_in_case_are_refused():
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
read_pack(_zip([("s/Notes.md", b"a"), ("s/notes.md", b"b")]))
|
||||
assert caught.value.code == "pack_case_collision"
|
||||
assert caught.value.files == ["s/Notes.md", "s/notes.md"]
|
||||
|
||||
|
||||
# --- file rules (2.2) ---------------------------------------------------------------------------
|
||||
|
||||
def _office(*parts: str, content_types: bool = True) -> bytes:
|
||||
names = (["[Content_Types].xml"] if content_types else []) + list(parts)
|
||||
return _zip([(n, b"<x/>") for n in names])
|
||||
|
||||
|
||||
def _files_code(path: str, data: bytes) -> tuple[str, list[str]]:
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
read_pack(_zip([("s/SKILL.md", b"# x"), (path, data)]))
|
||||
return caught.value.code, caught.value.files
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ext", sorted(skill_pack.ALLOWED_TYPES))
|
||||
def test_every_allowed_extension_is_accepted(ext):
|
||||
data = {".pdf": b"%PDF-1.7\n", ".docx": _office("word/document.xml"),
|
||||
".xlsx": _office("xl/workbook.xml")}.get(ext, "zażółć;gęślą".encode("cp1250"))
|
||||
assert read_pack(_zip([(f"s/r/a{ext}", data)])).files[f"s/r/a{ext}"] == data
|
||||
|
||||
|
||||
def test_the_extension_is_matched_case_insensitively():
|
||||
assert read_pack(_zip([("s/r/A.PDF", b"%PDF-1.4")]))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["s/run.sh", "s/tool.py", "s/LICENSE", "s/inner.zip"])
|
||||
def test_an_extension_off_the_list_is_refused(path):
|
||||
assert _files_code(path, b"x") == ("pack_file_type", [path])
|
||||
|
||||
|
||||
def test_a_pdf_without_the_pdf_signature_is_refused():
|
||||
assert _files_code("s/r/a.pdf", b"MZ\x90\x00")[0] == "pack_signature_mismatch"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ext", [".docx", ".xlsx"])
|
||||
def test_an_office_file_that_is_not_a_zip_is_refused(ext):
|
||||
assert _files_code(f"s/r/a{ext}", b"%PDF-1.7")[0] == "pack_signature_mismatch"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ext", [".docx", ".xlsx"])
|
||||
def test_an_office_zip_without_content_types_is_refused(ext):
|
||||
assert _files_code(f"s/r/a{ext}", _office("x.xml", content_types=False))[0] \
|
||||
== "pack_signature_mismatch"
|
||||
|
||||
|
||||
def test_binary_content_under_a_text_extension_is_refused():
|
||||
assert _files_code("s/r/notes.txt", b"\x7fELF\x02\x01\x00")[0] == "pack_signature_mismatch"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path, part", [("s/r/a.docx", "word/vbaProject.bin"),
|
||||
("s/r/a.xlsx", "xl/VBAProject.bin")])
|
||||
def test_an_office_file_with_macros_is_refused(path, part):
|
||||
assert _files_code(path, _office(part)) == ("pack_macros", [path])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["s/r/a.txt", "s/r/a.json", "s/r/a.md"])
|
||||
def test_a_zip_under_a_text_extension_is_refused(path):
|
||||
assert _files_code(path, _zip([("x.txt", b"x")])) == ("pack_nested_zip", [path])
|
||||
|
||||
|
||||
def test_the_inside_of_an_office_file_obeys_the_compression_limit():
|
||||
data = _zip([("[Content_Types].xml", b"<x/>"), ("word/bomb.xml", b"\0" * 1_000_000)])
|
||||
assert _files_code("s/r/a.docx", data) == ("pack_compression_ratio", ["s/r/a.docx"])
|
||||
|
||||
|
||||
def test_the_inside_of_an_office_file_obeys_the_path_rules():
|
||||
data = _zip([("[Content_Types].xml", b"<x/>"), (_raw("../evil.xml"), b"x")])
|
||||
assert _files_code("s/r/a.xlsx", data) == ("pack_bad_path", ["s/r/a.xlsx"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("types", [
|
||||
b'<Default Extension="bin" ContentType="application/vnd.ms-office.vbaProject"/>',
|
||||
b'<Override PartName="/word/document.xml" ContentType="application/vnd.ms-word.document.'
|
||||
b'macroEnabled.main+xml"/>',
|
||||
b'<Override PartName="/word/activeX/a.xml" ContentType="application/vnd.ms-office.activeX+xml"/>',
|
||||
])
|
||||
def test_macros_declared_only_in_the_content_types_are_refused(types):
|
||||
data = _zip([("[Content_Types].xml", b"<Types>" + types + b"</Types>"),
|
||||
("word/renamed.dat", b"code")])
|
||||
assert _files_code("s/r/a.docx", data) == ("pack_macros", ["s/r/a.docx"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("manifest", [
|
||||
b'<Default Extension="bin" ContentType="application/vnd.ms-office.vbaProject"/>',
|
||||
'<Default ContentType="application/vnd.ms-office.vbaProject"/>'.encode("utf-16"),
|
||||
b"<Types>\xff\xfe</Types>",
|
||||
])
|
||||
def test_a_content_types_part_a_substring_search_could_misread_is_refused(manifest):
|
||||
data = _zip([("[Content_Types].xml", manifest)])
|
||||
assert _files_code("s/r/a.docx", data)[0] == "pack_signature_mismatch"
|
||||
|
||||
|
||||
def test_an_oversized_content_types_part_is_refused():
|
||||
data = _zip([("[Content_Types].xml", os.urandom(skill_pack.MAX_MANIFEST_BYTES + 1))],
|
||||
compression=zipfile.ZIP_STORED)
|
||||
assert _files_code("s/r/a.docx", data)[0] == "pack_signature_mismatch"
|
||||
|
||||
|
||||
def test_only_the_content_types_of_an_office_file_are_inflated(monkeypatch):
|
||||
calls = []
|
||||
pack = _zip([("s/r/a.docx", _office("word/document.xml"))]) # built before the spy: writes open too
|
||||
real = zipfile.ZipFile.open # every inflating read goes through `open` (`_bounded_read`)
|
||||
monkeypatch.setattr(zipfile.ZipFile, "open", lambda self, name, *a, **k: calls.append(name)
|
||||
or real(self, name, *a, **k))
|
||||
read_pack(pack)
|
||||
assert [getattr(c, "filename", c) for c in calls] == ["s/r/a.docx", "[Content_Types].xml"]
|
||||
|
||||
|
||||
# --- SKILL.md (2.3) -----------------------------------------------------------------------------
|
||||
|
||||
def _skill(text: str, path: str = "s/SKILL.md") -> tuple[str, list[str]]:
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
read_pack(_zip([(path, text.encode("utf-8"))], compression=zipfile.ZIP_STORED))
|
||||
return caught.value.code, caught.value.files
|
||||
|
||||
|
||||
def _fm(**fields) -> str:
|
||||
return "---\n" + "".join(f"{k}: {v}\n" for k, v in fields.items()) + "---\nbody\n"
|
||||
|
||||
|
||||
def test_crlf_and_a_bom_are_read_like_lf():
|
||||
pack = read_pack(_zip([("s/SKILL.md", b"\xef\xbb\xbf" + SKILL.replace(b"\n", b"\r\n"))]))
|
||||
assert pack.skills[0].name == "nda" and pack.skills[0].body == "# NDA\n"
|
||||
|
||||
|
||||
def test_a_skill_md_that_is_not_utf8_is_refused():
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
read_pack(_zip([("s/SKILL.md", "---\nname: zażółć\n---\n".encode("cp1250"))]))
|
||||
assert caught.value.code == "skill_not_utf8"
|
||||
|
||||
|
||||
def test_a_frontmatter_over_8_kb_is_refused():
|
||||
big = "x" * (skill_pack.MAX_FRONTMATTER_BYTES + 1)
|
||||
assert _skill(_fm(name="a", description=big)) == ("skill_frontmatter_too_large", ["s/SKILL.md"])
|
||||
|
||||
|
||||
def test_a_date_in_the_frontmatter_stays_a_string_jsonb_can_store():
|
||||
import json
|
||||
pack = read_pack(_zip([("s/SKILL.md", _fm(name="a", description="d", updated="2025-01-01").encode())]))
|
||||
assert pack.skills[0].frontmatter["updated"] == "2025-01-01"
|
||||
json.dumps(pack.skills[0].frontmatter, allow_nan=False)
|
||||
|
||||
|
||||
def test_a_claude_code_style_description_with_colons_is_read_as_one_string():
|
||||
# Strict YAML refuses the second `: `; Claude Code (and most real SKILL.md files) do not.
|
||||
doc = ("---\nname: tworzenie-skilli\ndescription: Use when X — `a: b`. SKIP: literówka\n"
|
||||
" ciąg dalszy\nallowed-tools: Read, Glob\n---\n# Body\n")
|
||||
s = read_pack(_zip([("s/SKILL.md", doc.encode())])).skills[0]
|
||||
assert s.description == "Use when X — `a: b`. SKIP: literówka ciąg dalszy"
|
||||
assert s.frontmatter["allowed-tools"] == "Read, Glob"
|
||||
|
||||
|
||||
def test_in_flat_text_a_quoted_or_list_value_is_still_read_as_yaml():
|
||||
doc = '---\nname: a\ndescription: d. SKIP: x\npaths: ["**/*.gs", "*.json"]\nargument-hint: "[review]"\n---\nb'
|
||||
fm = read_pack(_zip([("s/SKILL.md", doc.encode())])).skills[0].frontmatter
|
||||
assert fm["paths"] == ["**/*.gs", "*.json"] and fm["argument-hint"] == "[review]"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("head", ["name: a\ndescription: d: e\n- list item", "name: a\n orphan\nx: [unclosed",
|
||||
"name: a\ndescription: d: e\nx: !!python/object:os.system ls",
|
||||
"name: a\ndescription: d: e\nx: *undefined"])
|
||||
def test_a_broken_frontmatter_that_is_not_flat_text_is_still_refused(head):
|
||||
assert _skill(f"---\n{head}\n---\nbody")[0] == "skill_frontmatter_invalid"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value", ["!!binary aGVsbG8=", "!!set {a: null}", ".nan", "!!timestamp 2025-01-01"])
|
||||
def test_frontmatter_values_json_cannot_carry_are_refused(value):
|
||||
assert _skill(_fm(name="a", description="d", x=value))[0] == "skill_frontmatter_invalid"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("yaml_text", [
|
||||
"name: &n a\ndescription: *n\n", # anchor + alias
|
||||
"name: a\ndescription: d\nx: &anchor 1\n", # an anchor alone is refused too
|
||||
])
|
||||
def test_yaml_anchors_and_aliases_are_refused(yaml_text):
|
||||
assert _skill(f"---\n{yaml_text}---\n")[0] == "skill_frontmatter_alias"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("yaml_text", ["name: [unclosed\n", "x: !!python/object:os.system ls\n",
|
||||
"[" * 5000 + "\n"])
|
||||
def test_a_frontmatter_that_is_not_safe_yaml_is_refused(yaml_text):
|
||||
assert _skill(f"---\n{yaml_text}---\n")[0] == "skill_frontmatter_invalid"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("yaml_text", ["- a\n- b\n", "just a string\n"])
|
||||
def test_a_frontmatter_that_is_not_a_mapping_is_refused(yaml_text):
|
||||
assert _skill(f"---\n{yaml_text}---\n")[0] == "skill_frontmatter_not_mapping"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["# no frontmatter at all\n", _fm(name="a"), _fm(description="d"),
|
||||
_fm(name="a", description='""'), _fm(name=1, description="d")])
|
||||
def test_a_missing_name_or_description_is_refused(text):
|
||||
assert _skill(text)[0] == "skill_missing_field"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["Nda", "nda_review", "nda--x", "-nda", "przegląd", "a" * 65])
|
||||
def test_a_name_that_is_not_kebab_up_to_64_is_refused(name):
|
||||
assert _skill(_fm(name=name, description="d"))[0] == "skill_bad_name"
|
||||
|
||||
|
||||
def test_a_64_character_name_is_accepted():
|
||||
assert read_pack(_zip([("s/SKILL.md", _fm(name="a" * 64, description="d").encode())]))
|
||||
|
||||
|
||||
def test_a_description_over_1024_characters_is_refused():
|
||||
assert _skill(_fm(name="a", description="d" * 1025))[0] == "skill_description_too_long"
|
||||
|
||||
|
||||
def test_a_body_over_30000_characters_is_refused():
|
||||
text = "---\nname: a\ndescription: d\n---\n" + "ż" * (skill_pack.MAX_BODY + 1)
|
||||
assert _skill(text)[0] == "skill_body_too_long"
|
||||
|
||||
|
||||
def test_permission_fields_are_kept_as_information_only():
|
||||
text = ("---\nname: a\ndescription: d\nallowed-tools: [Bash, WebFetch]\nmodel: opus\n"
|
||||
"permissionMode: bypassPermissions\nlicense: MIT\n---\n")
|
||||
(skill,) = read_pack(_zip([("s/SKILL.md", text.encode())])).skills
|
||||
assert skill.info_only == {"allowed-tools": ["Bash", "WebFetch"], "model": "opus",
|
||||
"permissionMode": "bypassPermissions"}
|
||||
assert skill.frontmatter["license"] == "MIT"
|
||||
|
||||
|
||||
def _plugin(*extra) -> bytes:
|
||||
return _zip([("p/.claude-plugin/plugin.json", b'{"name": "p"}'),
|
||||
("p/skills/nda/SKILL.md", SKILL), ("p/commands/review.md", b"# c"), *extra])
|
||||
|
||||
|
||||
def test_a_plugin_contributes_its_skills():
|
||||
assert [s.path for s in read_pack(_plugin()).skills] == ["p/skills/nda/SKILL.md"]
|
||||
|
||||
|
||||
def test_a_plugin_with_a_script_is_refused_with_the_list():
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
read_pack(_plugin(("p/scripts/run.sh", b"rm -rf /"), ("p/skills/nda/helper.py", b"x")))
|
||||
assert caught.value.code == "pack_plugin_code"
|
||||
assert caught.value.files == ["p/scripts/run.sh", "p/skills/nda/helper.py"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path", ["p/hooks/hooks.json", "p/.mcp.json", "p/bin/tool.md"])
|
||||
def test_a_plugin_with_hooks_or_mcp_servers_is_refused(path):
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
read_pack(_plugin((path, b"{}")))
|
||||
assert (caught.value.code, caught.value.files) == ("pack_plugin_code", [path])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("key", ["hooks", "mcpServers"])
|
||||
def test_a_plugin_manifest_declaring_code_inline_is_refused(key):
|
||||
data = _zip([("p/.claude-plugin/plugin.json", f'{{"name": "p", "{key}": {{}}}}'.encode()),
|
||||
("p/skills/nda/SKILL.md", SKILL)])
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
read_pack(data)
|
||||
assert (caught.value.code, caught.value.files) == ("pack_plugin_code",
|
||||
["p/.claude-plugin/plugin.json"])
|
||||
|
||||
|
||||
def test_a_plugin_nested_in_another_is_judged_against_its_own_root():
|
||||
data = _zip([(".claude-plugin/plugin.json", b'{"name": "outer"}'),
|
||||
("inner/.claude-plugin/plugin.json", b'{"name": "inner"}'),
|
||||
("inner/hooks/hooks.json", b"{}")])
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
read_pack(data)
|
||||
assert (caught.value.code, caught.value.files) == ("pack_plugin_code", ["inner/hooks/hooks.json"])
|
||||
|
||||
|
||||
# --- content sum, build_pack, agent packs (2.4) ------------------------------------------------
|
||||
|
||||
_ORIGINAL = ("---\r\nname: nda\r\nmetadata: {version: 2, author: Zespół}\r\ndescription: Przeglăd\r\n"
|
||||
"license: proprietary\r\n---\r\n# Przeglăd NDA\r\n").encode()
|
||||
_DOCX = _office("word/document.xml")
|
||||
|
||||
|
||||
def _sum(pack, i=0):
|
||||
return skill_pack.content_sha256(skill_pack.skill_content(pack, pack.skills[i]))
|
||||
|
||||
|
||||
def test_a_skill_with_a_docx_hashes_the_same_after_export_and_import():
|
||||
original = read_pack(_zip([("nda/SKILL.md", _ORIGINAL), ("nda/resources/playbook.docx", _DOCX)]))
|
||||
content = skill_pack.skill_content(original, original.skills[0])
|
||||
assert content.folder == "nda" and content.files == {"resources/playbook.docx": _DOCX}
|
||||
again = read_pack(skill_pack.build_pack([content]))
|
||||
assert again.kind == "skill" and "atrium-pack.json" not in again.files
|
||||
assert _sum(again) == _sum(original)
|
||||
# Only spelling is normalised away: a changed file is a changed skill.
|
||||
other = read_pack(_zip([("nda/SKILL.md", _ORIGINAL), ("nda/resources/playbook.docx",
|
||||
_office("word/other.xml"))]))
|
||||
assert _sum(other) != _sum(original)
|
||||
|
||||
|
||||
def test_an_agent_pack_round_trips_with_its_skills():
|
||||
skills = [skill_pack.SkillContent("nda", {"name": "nda", "description": "d"}, "# a\n",
|
||||
{"r/a.txt": b"x"}),
|
||||
skill_pack.SkillContent("dpa", {"name": "dpa", "description": "e"}, "# b\n", {})]
|
||||
agent = skill_pack.AgentDoc(name="Asystent umów", description="Przegląda umowy", body="Bądź zwięzły.\n",
|
||||
frontmatter={"name": "Asystent umów", "description": "Przegląda umowy",
|
||||
"kind": "assistant", "tools": ["search"], "model": "sonnet"})
|
||||
pack = read_pack(skill_pack.build_pack(skills, agent))
|
||||
assert pack.kind == "agent" and pack.agent == agent
|
||||
assert [skill_pack.skill_content(pack, s) for s in pack.skills] == sorted(skills, key=lambda s: s.folder)
|
||||
|
||||
|
||||
def _tampered(change) -> tuple[str, list[str]]:
|
||||
content = skill_pack.SkillContent("nda", {"name": "nda", "description": "d"}, "# a\n", {"a.txt": b"x"})
|
||||
with zipfile.ZipFile(io.BytesIO(skill_pack.build_pack([content]))) as zf:
|
||||
entries = {n: zf.read(n) for n in zf.namelist()}
|
||||
change(entries)
|
||||
with pytest.raises(PackRejected) as caught:
|
||||
read_pack(_zip(entries.items()))
|
||||
return caught.value.code, caught.value.files
|
||||
|
||||
|
||||
def test_a_file_whose_sum_differs_from_the_manifest_is_refused():
|
||||
assert _tampered(lambda e: e.update({"nda/a.txt": b"y"})) == ("pack_manifest_mismatch", ["nda/a.txt"])
|
||||
|
||||
|
||||
def test_a_file_missing_from_the_manifest_is_refused():
|
||||
assert _tampered(lambda e: e.update({"nda/b.txt": b"y"})) == ("pack_manifest_mismatch", ["nda/b.txt"])
|
||||
|
||||
|
||||
def test_a_malformed_manifest_is_refused():
|
||||
assert _tampered(lambda e: e.update({"atrium-pack.json": b'{"format": 1}'}))[0] \
|
||||
== "pack_manifest_invalid"
|
||||
@@ -0,0 +1,215 @@
|
||||
"""The skills HTTP surface, DB-free: the routes exist under /api/v1, and what the router itself
|
||||
decides — the streamed 10 MB ceiling on an import, base64 files, the ZIP response — reaches the
|
||||
service the way the service expects. The rules behind the routes are `test_skills_unit.py`'s."""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import types
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from fastapi.routing import APIRoute
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import deps
|
||||
from app.db import get_db
|
||||
from app.main import app
|
||||
from app.services import skills as service
|
||||
from app.routers.skills import MAX_JSON_BODY_BYTES
|
||||
from app.services.skill_pack import MAX_PACK_BYTES
|
||||
|
||||
API = "/api/v1"
|
||||
SKILL_ID = uuid.uuid4()
|
||||
|
||||
|
||||
def test_every_skills_route_is_registered_under_the_api_prefix():
|
||||
bound = {(m, r.path) for r in app.routes if isinstance(r, APIRoute) for m in r.methods}
|
||||
for method, path in [
|
||||
("GET", "/skills"), ("POST", "/skills"), ("GET", "/skills/{skill_id}"),
|
||||
("POST", "/skills/{skill_id}/versions"), ("GET", "/skills/{skill_id}/versions/{n}"),
|
||||
("GET", "/skills/{skill_id}/versions/{n}/files/{path:path}"),
|
||||
("POST", "/skills/{skill_id}/archive"), ("POST", "/skills/{skill_id}/publish"),
|
||||
("GET", "/skills/{skill_id}/export"), ("POST", "/skills/import"),
|
||||
]:
|
||||
assert (method, API + path) in bound, (method, path)
|
||||
|
||||
|
||||
class _Db:
|
||||
def commit(self):
|
||||
pass
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def api(monkeypatch):
|
||||
"""`calls` records what reached the service; nothing touches a database."""
|
||||
calls: dict = {}
|
||||
user = types.SimpleNamespace(id=uuid.uuid4(), is_admin=False)
|
||||
app.dependency_overrides[get_db] = _Db
|
||||
app.dependency_overrides[deps.get_current_user] = lambda: user
|
||||
|
||||
def fake(name, result):
|
||||
def _f(db, actor, *args, **kwargs):
|
||||
calls[name] = (args, kwargs)
|
||||
return result
|
||||
monkeypatch.setattr(service, name, _f)
|
||||
|
||||
fake("import_skills", {"status": "imported", "skills": [], "ignored": []})
|
||||
fake("new_version", {"n": 2})
|
||||
fake("export_skill", ("nda-v3.zip", b"PK\x05\x06" + bytes(18)))
|
||||
try:
|
||||
yield types.SimpleNamespace(client=TestClient(app), calls=calls)
|
||||
finally:
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def test_import_passes_the_raw_body_and_its_name_to_the_service(api):
|
||||
r = api.client.post(f"{API}/skills/import?filename=nda.zip&add_version=true", content=b"PK-bytes",
|
||||
headers={"Content-Type": "application/zip"})
|
||||
assert r.status_code == 200, r.text
|
||||
args, kwargs = api.calls["import_skills"]
|
||||
assert args == (b"PK-bytes", "nda.zip") and kwargs["add_version"] is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("chunked", [False, True])
|
||||
def test_an_import_over_10_mb_is_refused_before_the_service(api, chunked):
|
||||
big = b"x" * (MAX_PACK_BYTES + 1)
|
||||
# A generator body goes out chunked, with no Content-Length: only the streamed count catches it.
|
||||
content = (big[i:i + 65536] for i in range(0, len(big), 65536)) if chunked else big
|
||||
r = api.client.post(f"{API}/skills/import", content=content,
|
||||
headers={"Content-Type": "application/zip"})
|
||||
assert r.status_code == 422 and r.json()["code"] == "pack_too_large"
|
||||
assert "import_skills" not in api.calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize("path, cap", [
|
||||
("/skills/import", MAX_PACK_BYTES), # zip_body
|
||||
(f"/skills/{SKILL_ID}/versions", MAX_JSON_BODY_BYTES), # CappedBodyRoute
|
||||
])
|
||||
def test_an_oversized_body_stops_being_read_at_the_cap(api, path, cap):
|
||||
"""Not only refused: reading STOPS at the cap. Buffering the whole body first and measuring it
|
||||
afterwards answers the same 422, so the result alone cannot tell the two apart. ASGI-level,
|
||||
because TestClient reads the whole request body before the app sees a byte."""
|
||||
import asyncio
|
||||
chunk, received, status = b"x" * 65536, [0], []
|
||||
ctype = b"application/zip" if path.endswith("import") else b"application/json"
|
||||
scope = {"type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "POST",
|
||||
"scheme": "http", "path": f"{API}{path}", "raw_path": f"{API}{path}".encode(),
|
||||
"root_path": "", "query_string": b"", "server": ("testserver", 80),
|
||||
"client": ("127.0.0.1", 1), "headers": [(b"host", b"testserver"), (b"content-type", ctype)]}
|
||||
|
||||
async def receive():
|
||||
received[0] += len(chunk)
|
||||
return {"type": "http.request", "body": chunk, "more_body": received[0] < 10 * cap}
|
||||
|
||||
async def send(message):
|
||||
if message["type"] == "http.response.start":
|
||||
status.append(message["status"])
|
||||
|
||||
asyncio.run(app(scope, receive, send))
|
||||
assert status == [422]
|
||||
assert received[0] < cap + 4 * len(chunk), received[0]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field", ["metadata", "model_policy"])
|
||||
def test_free_form_json_over_8_kb_is_a_422(api, field):
|
||||
path = f"/skills/{SKILL_ID}/versions" if field == "metadata" else f"/agents/{SKILL_ID}/versions"
|
||||
r = api.client.post(f"{API}{path}", json={field: {"x": "y" * 9000}})
|
||||
assert r.status_code == 422
|
||||
|
||||
|
||||
def test_a_new_version_decodes_files_and_leaves_absent_fields_none(api):
|
||||
r = api.client.post(f"{API}/skills/{SKILL_ID}/versions",
|
||||
json={"body": "# v2", "files": {"a.txt": base64.b64encode(b"hi").decode()}})
|
||||
assert r.status_code == 201, r.text
|
||||
(skill_id, fields), _ = api.calls["new_version"]
|
||||
assert skill_id == SKILL_ID
|
||||
assert fields["files"] == {"a.txt": b"hi"} and fields["body"] == "# v2"
|
||||
assert fields["description"] is None and fields["metadata"] is None # None = carry over
|
||||
|
||||
|
||||
def test_a_new_version_passes_base_n_and_refuses_one_below_1(api):
|
||||
r = api.client.post(f"{API}/skills/{SKILL_ID}/versions", json={"base_n": 3})
|
||||
assert r.status_code == 201, r.text
|
||||
(_, fields), _ = api.calls["new_version"]
|
||||
assert fields["base_n"] == 3
|
||||
del api.calls["new_version"]
|
||||
assert api.client.post(f"{API}/skills/{SKILL_ID}/versions", json={"base_n": 0}).status_code == 422
|
||||
assert "new_version" not in api.calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize("files", [
|
||||
{"a.txt": "not base64!"},
|
||||
["a.txt"],
|
||||
{"a.txt": base64.b64encode(b"x" * (MAX_PACK_BYTES // 2 + 1)).decode(),
|
||||
"b.txt": base64.b64encode(b"x" * (MAX_PACK_BYTES // 2 + 1)).decode()},
|
||||
])
|
||||
def test_bad_or_oversized_files_are_a_422(api, files):
|
||||
r = api.client.post(f"{API}/skills/{SKILL_ID}/versions", json={"files": files})
|
||||
assert r.status_code == 422
|
||||
assert "new_version" not in api.calls
|
||||
|
||||
|
||||
def test_export_answers_a_zip_attachment(api):
|
||||
r = api.client.get(f"{API}/skills/{SKILL_ID}/export?n=3")
|
||||
assert r.status_code == 200
|
||||
assert r.headers["content-type"] == "application/zip"
|
||||
assert r.headers["content-disposition"] == 'attachment; filename="nda-v3.zip"'
|
||||
assert api.calls["export_skill"][0] == (SKILL_ID, 3)
|
||||
|
||||
|
||||
def test_every_agent_and_publish_request_route_is_registered_under_the_api_prefix():
|
||||
bound = {(m, r.path) for r in app.routes if isinstance(r, APIRoute) for m in r.methods}
|
||||
for method, path in [
|
||||
("GET", "/agents"), ("POST", "/agents"), ("GET", "/agents/{agent_id}"),
|
||||
("POST", "/agents/{agent_id}/versions"), ("POST", "/agents/{agent_id}/archive"),
|
||||
("POST", "/agents/{agent_id}/publish"), ("GET", "/agents/{agent_id}/export"),
|
||||
("POST", "/agents/import"), ("GET", "/skills/permissions"),
|
||||
("GET", "/admin/publish-requests"),
|
||||
("POST", "/admin/publish-requests/{request_id}/approve"),
|
||||
("POST", "/admin/publish-requests/{request_id}/decline"),
|
||||
]:
|
||||
assert (method, API + path) in bound, (method, path)
|
||||
|
||||
|
||||
def _calls(dependant):
|
||||
for d in dependant.dependencies:
|
||||
yield d.call
|
||||
yield from _calls(d)
|
||||
|
||||
|
||||
def test_every_publish_request_route_depends_on_require_skill_approver():
|
||||
routes = [r for r in app.routes
|
||||
if isinstance(r, APIRoute) and r.path.startswith(API + "/admin/publish-requests")]
|
||||
assert len(routes) == 3
|
||||
for r in routes:
|
||||
assert deps.require_skill_approver in set(_calls(r.dependant)), r.path
|
||||
assert deps.require_administrator not in set(_calls(r.dependant)), r.path
|
||||
|
||||
|
||||
def test_somebody_who_may_not_approve_is_refused_the_publish_queue(api, monkeypatch):
|
||||
monkeypatch.setattr(service, "may_approve", lambda _db, _user: False)
|
||||
r = api.client.get(f"{API}/admin/publish-requests")
|
||||
assert r.status_code == 403
|
||||
|
||||
|
||||
def test_a_new_agent_version_passes_pins_and_leaves_absent_fields_none(api, monkeypatch):
|
||||
pin = uuid.uuid4()
|
||||
seen = {}
|
||||
monkeypatch.setattr(service, "new_agent_version",
|
||||
lambda db, actor, agent_id, fields, ip: seen.update(fields) or {"n": 2})
|
||||
r = api.client.post(f"{API}/agents/{SKILL_ID}/versions", json={"skill_version_ids": [str(pin)]})
|
||||
assert r.status_code == 201, r.text
|
||||
assert seen["skill_version_ids"] == [pin] and seen["instructions"] is None
|
||||
|
||||
|
||||
def test_an_approver_who_is_not_an_administrator_reaches_the_publish_queue(api, monkeypatch):
|
||||
monkeypatch.setattr(service, "may_approve", lambda _db, _user: True)
|
||||
monkeypatch.setattr(service, "pending_publish_requests", lambda _db, _actor: [])
|
||||
r = api.client.get(f"{API}/admin/publish-requests")
|
||||
assert r.status_code == 200 and r.json() == []
|
||||
|
||||
|
||||
def test_permissions_route_is_not_swallowed_by_skill_id(api, monkeypatch):
|
||||
monkeypatch.setattr(service, "may_approve", lambda _db, _user: True)
|
||||
r = api.client.get(f"{API}/skills/permissions")
|
||||
assert r.status_code == 200 and r.json() == {"approve": True}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user