forge
Explore
Log in

Don't you dare go Hollow

School identity is the uuid

Browse files at this commit

29180402042d9239f6438ff6692b365bd36f6f97Ahmet Kaan GümüşParent: c1d2674
  • feat
    • school identity is the uuid
    • drop the slug
Show full message
✨ feat: school identity is the uuid; drop the slug

The school slug is gone from every surface: the session cookie prefix,
the /schools/{id} builder routes, FILES_PATH blob dirs, the hab/2 frame
school value, DTOs, and the /limits contract. SchoolId::try_parse is the
one wire parse (hyphenated uuid only); a non-uuid frame school answers
unknown_school. Register gets a public picker via the new unauthenticated
GET /auth/schools returning active [{id, name}]. The control migration
drops school_slug and the slug column, which invalidates every existing
session — old cookie prefixes cannot resolve.
Local-Gate: 3fafffd98aec59c68e2606833b87785d0abf2fee (1510 passed, 425s)

61 changed files +1358 -1455

.env.examplemodified+3 -3
@@ -12,7 +12,7 @@ DATABASE_URL=postgres://hezarfen:hezarfen@127.0.0.1:5432/hezarfen_control
1212 # HEZARFEN_TEST_DATABASE_URL=postgres://hezarfen:hezarfen@127.0.0.1:5432/postgres
1313
1414 # Directory for uploaded note-file blobs (created at startup). Each school
15-# writes into a subdirectory of it named by its slug.
15+# writes into a subdirectory of it named by its uuid.
1616 FILES_PATH=./data/files
1717
1818 # Optional log filter.
@@ -59,7 +59,7 @@ RUST_LOG=info,hezarfen_backend=debug
5959 # Seed a BUILDER account at startup: the deployment operator who creates,
6060 # suspends and drops schools. Not a user of any school and holds no role in
6161 # one; its cookie is `builder.<token>` where a school user's is
62-# `<slug>.<token>`. Both must be set together. An existing account with this
62+# `<uuid>.<token>`. Both must be set together. An existing account with this
6363 # username is left exactly as it is — the seed never rewrites a credential, so
6464 # changing the password here does not re-key a live builder.
6565 # BUILDER_USERNAME=builder
@@ -92,7 +92,7 @@ RUST_LOG=info,hezarfen_backend=debug
9292 # entirely; the process logs to stdout exactly as before.
9393 # Nothing user-identifying ever leaves here: no user id, no client IP, no URL
9494 # path, no bodies, no headers or cookies. Spans carry the method, the route
95-# TEMPLATE, the status, a random request id and the school slug.
95+# TEMPLATE, the status, a random request id and the school uuid.
9696 # OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4317
9797
9898 # Wire transport: grpc (default, port 4317) or http/protobuf (port 4318).
.sqlx/query-4a50c4e5b4c369736b0a5b55dfd143b69def99f1e2113817ff6b9b2bbfc8a2b9.json → .sqlx/query-49e01cec9e2b7b66955ff45127509f5d3a58de542a305a3971d4e0cc43d6ef14.jsonrenamed+3 -3
@@ -1,6 +1,6 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT id, name FROM school WHERE slug = $1",
3+ "query": "SELECT id, name FROM school WHERE id = $1",
44 "describe": {
55 "columns": [
66 {
@@ -28,7 +28,7 @@
2828 ],
2929 "parameters": {
3030 "Left": [
31- "Text"
31+ "Uuid"
3232 ]
3333 },
3434 "nullable": [
@@ -36,5 +36,5 @@
3636 false
3737 ]
3838 },
39- "hash": "4a50c4e5b4c369736b0a5b55dfd143b69def99f1e2113817ff6b9b2bbfc8a2b9"
39+ "hash": "49e01cec9e2b7b66955ff45127509f5d3a58de542a305a3971d4e0cc43d6ef14"
4040 }
.sqlx/query-9d9cce760c2a87090f4b3cf5da4afc868d6fb3c91a7ba9ae5b553dfb48be9353.json → .sqlx/query-5445331a2cfb2732d63fc5bc46956679906ecfa08aafa5284a6aec6f3496da1d.jsonrenamed+6 -6
@@ -1,16 +1,16 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT s.slug AS \"slug: Slug\",\n s.name,\n s.status AS \"status: SchoolStatus\"\n FROM person_school ps\n JOIN school s ON s.id = ps.school\n WHERE ps.person = $1 AND s.slug = $2",
3+ "query": "SELECT s.id AS \"id: SchoolId\",\n s.name,\n s.status AS \"status: SchoolStatus\"\n FROM person_school ps\n JOIN school s ON s.id = ps.school\n WHERE ps.person = $1 AND s.id = $2",
44 "describe": {
55 "columns": [
66 {
77 "ordinal": 0,
8- "name": "slug: Slug",
9- "type_info": "Text",
8+ "name": "id: SchoolId",
9+ "type_info": "Uuid",
1010 "origin": {
1111 "Table": {
1212 "table": "school",
13- "name": "slug"
13+ "name": "id"
1414 }
1515 }
1616 },
@@ -40,7 +40,7 @@
4040 "parameters": {
4141 "Left": [
4242 "Uuid",
43- "Text"
43+ "Uuid"
4444 ]
4545 },
4646 "nullable": [
@@ -49,5 +49,5 @@
4949 false
5050 ]
5151 },
52- "hash": "9d9cce760c2a87090f4b3cf5da4afc868d6fb3c91a7ba9ae5b553dfb48be9353"
52+ "hash": "5445331a2cfb2732d63fc5bc46956679906ecfa08aafa5284a6aec6f3496da1d"
5353 }
.sqlx/query-5ee0b9ddaaafd3254d338726fe24e29e4ab2680a2fe02cca1494c6a4fa511aac.jsonadded+38 -0
@@ -0,0 +1,38 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT id, name FROM school WHERE status = 'active' ORDER BY name",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "school",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "name",
20+ "type_info": "Text",
21+ "origin": {
22+ "Table": {
23+ "table": "school",
24+ "name": "name"
25+ }
26+ }
27+ }
28+ ],
29+ "parameters": {
30+ "Left": []
31+ },
32+ "nullable": [
33+ false,
34+ false
35+ ]
36+ },
37+ "hash": "5ee0b9ddaaafd3254d338726fe24e29e4ab2680a2fe02cca1494c6a4fa511aac"
38+}
.sqlx/query-ede2ad9dfbe1e9e069bd8912acb49d13f43f251bc7276d1a6b6fe249920677ad.json → .sqlx/query-9a2794125306f8c5fe68fb30b736aea829986d5e0bbe235310de7af8252ec3d8.jsonrenamed+3 -3
@@ -1,16 +1,16 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "INSERT INTO person_school (person, school, created_at)\n SELECT $1, s.id, $3 FROM school s WHERE s.slug = $2\n ON CONFLICT DO NOTHING",
3+ "query": "INSERT INTO person_school (person, school, created_at)\n SELECT $1, s.id, $3 FROM school s WHERE s.id = $2\n ON CONFLICT DO NOTHING",
44 "describe": {
55 "columns": [],
66 "parameters": {
77 "Left": [
88 "Uuid",
9- "Text",
9+ "Uuid",
1010 "Int8"
1111 ]
1212 },
1313 "nullable": []
1414 },
15- "hash": "ede2ad9dfbe1e9e069bd8912acb49d13f43f251bc7276d1a6b6fe249920677ad"
15+ "hash": "9a2794125306f8c5fe68fb30b736aea829986d5e0bbe235310de7af8252ec3d8"
1616 }
.sqlx/query-c0f04896f37ecdb45eefd6ff79ede315709a64b53ff6fd8f6837f61283f1001b.json → .sqlx/query-ae2c93f1bdfb98b697268a8b8f6be1aebabfbe3ab9a87122c337a306eb0447b0.jsonrenamed+5 -5
@@ -1,16 +1,16 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT slug FROM school WHERE status = 'active' ORDER BY slug",
3+ "query": "SELECT id FROM school WHERE status = 'active' ORDER BY name",
44 "describe": {
55 "columns": [
66 {
77 "ordinal": 0,
8- "name": "slug",
9- "type_info": "Text",
8+ "name": "id",
9+ "type_info": "Uuid",
1010 "origin": {
1111 "Table": {
1212 "table": "school",
13- "name": "slug"
13+ "name": "id"
1414 }
1515 }
1616 }
@@ -22,5 +22,5 @@
2222 false
2323 ]
2424 },
25- "hash": "c0f04896f37ecdb45eefd6ff79ede315709a64b53ff6fd8f6837f61283f1001b"
25+ "hash": "ae2c93f1bdfb98b697268a8b8f6be1aebabfbe3ab9a87122c337a306eb0447b0"
2626 }
.sqlx/query-90ca4d8c108622034298f4da1ac3a4db6a284b2f95e0fe8a69bbec9117f5d0a0.json → .sqlx/query-ee11814d38c895c499dbab2a83a6704318a46f5b51d38697a2cce1e6ca4dbae0.jsonrenamed+5 -5
@@ -1,16 +1,16 @@
11 {
22 "db_name": "PostgreSQL",
3- "query": "SELECT s.slug AS \"slug: Slug\",\n s.name,\n s.status AS \"status: SchoolStatus\"\n FROM person_school ps\n JOIN school s ON s.id = ps.school\n WHERE ps.person = $1\n ORDER BY s.slug",
3+ "query": "SELECT s.id AS \"id: SchoolId\",\n s.name,\n s.status AS \"status: SchoolStatus\"\n FROM person_school ps\n JOIN school s ON s.id = ps.school\n WHERE ps.person = $1\n ORDER BY s.name",
44 "describe": {
55 "columns": [
66 {
77 "ordinal": 0,
8- "name": "slug: Slug",
9- "type_info": "Text",
8+ "name": "id: SchoolId",
9+ "type_info": "Uuid",
1010 "origin": {
1111 "Table": {
1212 "table": "school",
13- "name": "slug"
13+ "name": "id"
1414 }
1515 }
1616 },
@@ -48,5 +48,5 @@
4848 false
4949 ]
5050 },
51- "hash": "90ca4d8c108622034298f4da1ac3a4db6a284b2f95e0fe8a69bbec9117f5d0a0"
51+ "hash": "ee11814d38c895c499dbab2a83a6704318a46f5b51d38697a2cce1e6ca4dbae0"
5252 }
README.mdmodified+69 -66
@@ -364,29 +364,29 @@ podman run -d --name hezarfen -p 7656:7656 -v hezarfen_backend_data:/data hezarf
364364 ## Multi-school (SaaS)
365365
366366 One deployment serves many schools. Every school gets a PostgreSQL
367-**database** of its own, named `{control}_school_{slug}` after the
367+**database** of its own, named `{control}_school_{uuid hex}` (the registry uuid with the dashes removed) after the
368368 **control** database `DATABASE_URL` points at (`hezarfen_control` by
369369 default), which holds the school registry, the builder accounts and the
370370 shared rate-limit window. Isolation is the store's, not the handlers': a
371371 school database sees only its own rows, so no query carries a
372372 `WHERE school = ...` somebody could forget.
373373
374-**Slugs.** 2-32 characters of `a-z`, `0-9` and `-`, starting with a letter or
375-digit (`MIN_SLUG_LEN`/`MAX_SLUG_LEN`); `builder`, `control` and `person` are
376-reserved and refused. A slug names the school's database, its blob directory
377-and its cookie prefix, so it is immutable once taken — a rename changes the
378-display name only.
374+**Identity.** The wire id is the registry uuid, hyphenated
375+(`01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d`) — the same string `GET /school` and
376+`GET /auth/schools` publish. It is the cookie prefix, the blob directory under
377+`FILES_PATH`, and the `school` value on every hab/2 frame. The database name
378+is that uuid with the dashes removed. A rename changes the display name only.
379379
380-**Cookies.** A school session is `session=<slug>.<token>`, the vendor's is
380+**Cookies.** A school session is `session=<uuid>.<token>`, the vendor's is
381381 `session=builder.<token>`, and a person who still has to pick a school carries
382382 `session=person.<token>` — all split at the *first* dot so a token can never
383-be read as a slug. No cookie is accepted on another's surface (`401` all
383+be read as a school id. No cookie is accepted on another's surface (`401` all
384384 ways), and a cookie with no dot names no school and is refused everywhere.
385385
386386 **How a request finds its school.** Every school-scoped handler takes the
387387 tenancy `State` (`web::tenant_state`), which reads the cookie's prefix, looks
388388 the school up in the registry, and hands the handler a connection pinned to
389-that database plus `FILES_PATH/<slug>/` as its blob directory. The AI bridge is
389+that database plus `FILES_PATH/<uuid>/` as its blob directory. The AI bridge is
390390 the one caller with no cookie: it injects the school as a request extension
391391 instead, which nothing outside the process can forge. In-process state is keyed
392392 by school too — the exam presence map and the whiteboard hub — so two schools
@@ -396,7 +396,7 @@ never share a room.
396396 row is read on every request, so the next call after the switch answers `403`,
397397 live session or not, `POST /auth/login` included. The builder surface keeps
398398 working on a suspended school — that is how it comes back — except
399-`POST /schools/{slug}/enter`, which is one of the school's own doors.
399+`POST /schools/{id}/enter`, which is one of the school's own doors.
400400
401401 **The builder lifecycle.** `BUILDER_USERNAME` + `BUILDER_PASSWORD` seed the
402402 operator account at boot (both or neither; half a pair aborts startup, and an
@@ -404,12 +404,12 @@ existing account is never rewritten). From there: `POST /builder/login` →
404404 `POST /schools` (registry row, database, schema and the school's first admin —
405405 one call or none of it) → that admin (a **person** in the control database)
406406 logs in at `POST /auth/login` with just username + password, and is entered
407-into the school straight away → `PATCH /schools/{slug}` renames, suspends or
407+into the school straight away → `PATCH /schools/{id}` renames, suspends or
408408 resumes →
409-`POST /schools/{slug}/admin-password` re-keys a locked-out admin and revokes
410-every session it held → `POST /schools/{slug}/enter` mints an ordinary school
409+`POST /schools/{id}/admin-password` re-keys a locked-out admin and revokes
410+every session it held → `POST /schools/{id}/enter` mints an ordinary school
411411 session for one of its admins (support access, no builder power inside) →
412-`DELETE /schools/{slug}` destroys the school's database, its registry row and
412+`DELETE /schools/{id}` destroys the school's database, its registry row and
413413 its uploaded files. Irreversible on purpose: suspension is the reversible door.
414414
415415 **AI frames name the school.** One AI service serves the whole deployment, so
@@ -471,14 +471,14 @@ a set does not discover the problems one round trip at a time:
471471 {"error": "conflict: courses is required by exams, subjects"}
472472 ```
473473
474-**Selling.** `GET /schools/{slug}/modules` returns both halves (`enabled` +
474+**Selling.** `GET /schools/{id}/modules` returns both halves (`enabled` +
475475 `disabled`, each sorted — together they are the whole catalog).
476-`POST|DELETE /schools/{slug}/modules/{module}` moves one module and is
476+`POST|DELETE /schools/{id}/modules/{module}` moves one module and is
477477 idempotent: a module the school already has (or already lacks) is a `200` with
478478 the unchanged set. An unknown module name in the path is a `404`, the same
479479 verdict an unknown school gets.
480480
481-`PATCH /schools/{slug}/modules` re-sells the whole shelf in one call, with any
481+`PATCH /schools/{id}/modules` re-sells the whole shelf in one call, with any
482482 mix of the four optional lists `enable`, `disable`, `enable_packages`,
483483 `disable_packages` (a package expands to its modules). The lists are folded
484484 into **one** resulting set, which is validated **once** and written **once or
@@ -532,9 +532,9 @@ A walk-through — the vendor takes `meals` away and gives it back:
532532
533533 ```bash
534534 curl -c v.txt -X POST localhost:6060/builder/login -H 'content-type: application/json' -d '{"username":"builder","password":"correct horse battery"}'
535-curl -b v.txt -X DELETE localhost:6060/schools/demo/modules/meals # 200, meals now in "disabled"
535+curl -b v.txt -X DELETE localhost:6060/schools/01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d/modules/meals # 200, meals now in "disabled"
536536 curl -b s.txt localhost:6060/meals/menus # 403 {"error":"module disabled","module":"meals"}
537-curl -b v.txt -X POST localhost:6060/schools/demo/modules/meals # 200, and the student's next call works again
537+curl -b v.txt -X POST localhost:6060/schools/01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d/modules/meals # 200, and the student's next call works again
538538 ```
539539
540540 ## Auth model
@@ -544,19 +544,21 @@ control database, that can belong to any number of schools. Login never names
544544 a school — `POST /auth/login` takes `{username, password}` alone. A person
545545 with exactly one active membership is logged straight into it: the response is
546546 the full user object and the cookie is the school's own
547-`session=<school-slug>.<token>`. A person with two or more active memberships
548-answers `{username, schools: [{slug, name}]}` with a `session=person.<token>`
547+`session=<uuid>.<token>`. A person with two or more active memberships
548+answers `{username, schools: [{id, name}]}` with a `session=person.<token>`
549549 cookie instead, and names a school with `POST /auth/school`
550-(`{"school": "<slug>"}`), which swaps the cookie for that school's
551-`<slug>.<token>` and revokes the person session. Register still names the
552-school: `POST /auth/register` takes `{school, username, password}` (see
550+(`{"school": "<uuid>"}`), which swaps the cookie for that school's
551+`<uuid>.<token>` and revokes the person session. Register picks its school
552+from `GET /auth/schools` (public, no cookie): the active schools as
553+`[{id, name}]`, sorted by name. `POST /auth/register` takes
554+`{school, username, password}` where `school` is one of those ids (see
553555 "Multi-school (SaaS)").
554556
555557 Login sets an `HttpOnly`, `SameSite=Lax` `session` cookie (7-day expiry,
556558 stored server-side), split at the *first* dot so a token can never be read as
557-a slug. Send the cookie back on later requests. Every endpoint below whose
559+a school id. Send the cookie back on later requests. Every endpoint below whose
558560 `Auth` column names a role requires a valid school session; the ones marked
559-`no` (`/health`, the docs pages, `register` / `login` / `school` / `logout`)
561+`no` (`/health`, the docs pages, `register` / `login` / `schools` / `school` / `logout`)
560562 don't (`logout` is idempotent — it clears whichever session the cookie names:
561563 school, person, or builder). `GET /auth/me` is school-cookie only: a person
562564 cookie answers `401`, because who you *are* depends on the school you have not
@@ -720,7 +722,7 @@ drift from it**, which is enforced rather than asked for:
720722 and fails unless each one is either referenced by `src/web/limits.rs` or
721723 listed as a deliberate exclusion *with a reason*. A new constant breaks the
722724 suite until someone decides, consciously, whether clients need it.
723-- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 224 published
725+- `tests/spec_bounds.rs` builds the OpenAPI document, reads all 218 published
724726 bounds back out of the emitted JSON, and asserts each equals its constant.
725727 This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal
726728 only** — a `const` there does not compile — so the annotations are
@@ -998,7 +1000,7 @@ still left exactly as they stand.
9981000
9991001 There is no self-service path to `admin` — registration always creates a
10001002 `student`. A school's first admin is created *with* the school: the builder
1001-posts `POST /schools` with `{slug, name, admin_username, admin_password}` and
1003+posts `POST /schools` with `{name, admin_username, admin_password}` (optionally `modules`; the id is minted server-side) and
10021004 that account lands inside the new school's database holding `admin`. The
10031005 builder itself comes from the startup seed: set both
10041006
@@ -1027,7 +1029,7 @@ instant, since the guard is a predicate on the role write itself: the
10271029 statement, so the count and the write it guards contend on the row lock
10281030 like any other write.
10291031
1030-A locked-out school is the builder's `POST /schools/{slug}/admin-password`,
1032+A locked-out school is the builder's `POST /schools/{id}/admin-password`,
10311033 which re-keys an admin that still exists. Manual fallback (the recovery path
10321034 if an older build already emptied a school's admin set): run
10331035
@@ -1038,8 +1040,8 @@ UPDATE app_user SET role = 'admin' WHERE username = 'ada';
10381040 against the **school's** database (`{control}_school_{uuid hex}` — the hex of
10391041 the school's registry `id`, no dashes), not the control one. List the school
10401042 databases with `\l` — e.g. `podman exec -it hezarfen_backend_postgres psql -U hezarfen
1041--d hezarfen_control -c "SELECT slug, id FROM school"` names each school and
1042-its database suffix for the compose stack.
1043+-d hezarfen_control -c "SELECT id, name FROM school"` names each school; its
1044+database suffix is that id with the dashes removed, for the compose stack.
10431045
10441046 ## Endpoints
10451047
@@ -1170,11 +1172,12 @@ window filtering, before paging; negative values are a `400` naming the field.
11701172 | PATCH | `/appointments/{id}/reschedule/decline` | student | Refuse the teacher's counter-proposal. The requester's call alone, and it **cancels the booking**: the proposal replaced the time that was asked for, so there is nothing left to fall back to — book another slot instead. The slot frees up, and the original request stays readable as `cancelled` with the refused proposal still on it. Declining is a cancel, so it answers to the same deadline: `409` once the meeting's effective window has started. |
11711173 | GET | `/attendance/me` | student | The current user's attendance report: event tallies, lesson roll-call tallies, a per-instance breakdown with attendance rates, and the per-term absence breakdown. |
11721174 | GET | `/attendance/{user}` | teacher | Any user's attendance report. Requires teacher+, or a parent tied to the target student. Managers, admins, and parents see every instance; a teacher sees the event tallies plus only the roll-call blocks — and the absence days — of the instances they run. |
1173-| POST | `/auth/login` | no | Log in with username + password — no school. Sets a `session` cookie on success: exactly one active membership enters that school right away (`<slug>.<token>` and the full [`UserResponse`], unchanged for single-school clients), several answer a [`SchoolChoiceResponse`] with a `person.<token>` cookie that `POST /auth/school` binds. |
1175+| POST | `/auth/login` | no | Log in with username + password — no school. Sets a `session` cookie on success: exactly one active membership enters that school right away (`<uuid>.<token>` and the full [`UserResponse`], unchanged for single-school clients), several answer a [`SchoolChoiceResponse`] with a `person.<token>` cookie that `POST /auth/school` binds. |
11741176 | POST | `/auth/logout` | no | Log out: revoke the current session (if any) and clear the cookie. Idempotent — no session required; answers `204` either way. |
11751177 | GET | `/auth/me` | student | Return the currently authenticated user. |
11761178 | POST | `/auth/register` | no | Register a new user account, or attach an existing person to one more school: `{school, username, password}` in, `{username, role}` back (no `id`; new accounts are `student`). Always `201` — see below. |
1177-| POST | `/auth/school` | no | Bind a `person.<token>` session to one of the person's schools: the cookie is replaced with that school's own `<slug>.<token>` and the person session is revoked. Deliberately outside the credential rate-limit tier — this is not a credential guess, and it requires a session cookie already. |
1179+| POST | `/auth/school` | no | Bind a `person.<token>` session to one of the person's schools: the cookie is replaced with that school's own `<uuid>.<token>` and the person session is revoked. Deliberately outside the credential rate-limit tier — this is not a credential guess, and it requires a session cookie already. |
1180+| GET | `/auth/schools` | no | Active schools open for registration. Unauthenticated, like register: the picker has no session yet. Sorted by name; empty when none are active. |
11781181 | GET | `/bank-questions` | teacher | The bank the caller may see — their own templates plus the ones published to the school (admins see every one), **newest first**. `?subject=` narrows to one origin subject; `?owner=` to one owner (a user id, or `me` for the caller); `?q=` to a case-insensitive fragment of the question text; `?visibility=private\|school` to one shelf — it narrows what the caller may already see and never widens it, so `private` is "my drafts" and `school` the published library. Paged via `?limit=&offset=` (omit `limit` for all of them); returns a `{items, total, limit, offset}` envelope, where `total` counts every match under the same filters, not just this page. Each item carries the resolved `subject_name`/`owner_name` so a client needn't look them up per row, plus `used_count` — how many exam questions were copied out of that template (one grouped query for the page, not one per row). |
11791182 | POST | `/bank-questions` | teacher | Add a template to the bank. Requires teacher+. `subject_id` is origin metadata (any subject — the same-course rule lives at instantiate time), so it need only exist (an unknown subject is a `400`). `choice` templates carry 2–10 `choices` plus `correct` naming one of them by id; `text` templates carry neither. The caller becomes the owner. |
11801183 | GET | `/bank-questions/{bid}` | teacher | One template by id. Visible ones only: a `private` template belonging to someone else is a 404, not a 403 — a 403 would confirm it exists. |
@@ -1334,7 +1337,7 @@ window filtering, before paging; negative values are a `400` naming the field.
13341337 | POST | `/insights/runs` | manager | Store one compute run's ledger row (with its pending students and failed modules, both replaced). |
13351338 | GET | `/insights/runs/{run_day}/report` | manager | The stored report document, streamed. |
13361339 | POST | `/insights/runs/{run_day}/report` | manager | Render the school's report for one run day, and store it. Synchronous, and deliberately so: the manager clicked one button, and the document is what they asked for — there is no queue to poll and no partial state, and the receipt says what was stored. |
1337-| GET | `/insights/schools` | builder | The deployment's active schools, by slug — the directory a shared AI fleet schedules over. |
1340+| GET | `/insights/schools` | builder | The deployment's active schools, by school — the directory a shared AI fleet schedules over. |
13381341 | POST | `/insights/segments` | manager | Store a batch of ZEKA's question-segment labels (and each question's dimension split). |
13391342 | GET | `/insights/students/{user}` | teacher | One student's insight, as an observer reads it. Teacher+ (narrowed to the students they reach) or a parent holding a live link to that student; everyone else — other students included — gets the same `404` a missing id gets. |
13401343 | POST | `/insights/students/{user}` | teacher | Ask ZEKA to recompute one student's insight, detached. `202` means queued, not computed: the service works through the student's data and writes its `zeka_*` rows on its own, and `GET /insights/students/{id}` shows them as soon as they land. `503` when no service offers `insight.student` — and nothing is queued. |
@@ -1449,15 +1452,15 @@ window filtering, before paging; negative values are a `400` naming the field.
14491452 | GET | `/school` | student | The school the session cookie is bound to: its uuid and display name. |
14501453 | GET | `/schools` | builder | Every school this deployment serves, newest first. Paged via `?limit=&offset=` (omit `limit` for the full list). |
14511454 | POST | `/schools` | builder | Create a school: its registry row, its database, its schema, and its first admin account — one call, or none of it. |
1452-| GET | `/schools/{slug}` | builder | One school by slug. |
1453-| PATCH | `/schools/{slug}` | builder | Rename a school and/or flip it between `active` and `suspended`. Omitted fields keep their value — both land in one statement, so a request that carries both is one write and never half a patch. The slug itself is immutable in this cut — it is the cookie prefix and the blob directory — though it no longer names the database (the school's uuid does); a rename API is not offered yet. |
1454-| DELETE | `/schools/{slug}` | builder | Delete a school: its database, its registry row, and its uploaded files. Irreversible — suspension is the reversible door. |
1455-| POST | `/schools/{slug}/admin-password` | builder | Reset an admin's password inside a school — the "we are locked out" call. Every session that account held is revoked with it, so a stolen cookie does not survive the reset. Works on a suspended school. |
1456-| POST | `/schools/{slug}/enter` | builder | Enter a school as one of its admins — support access, with the school's own session cookie (`<slug>.<token>`) and no builder power inside it. |
1457-| GET | `/schools/{slug}/modules` | builder | What a school has bought, and what is left to sell it. Works on a suspended school — entitlements are the vendor's ledger, not one of the school's doors. |
1458-| PATCH | `/schools/{slug}/modules` | builder | Re-sell a school's whole shelf in one call: any mix of modules and packages, in either direction. Every list is optional and an empty body is a no-op. |
1459-| POST | `/schools/{slug}/modules/{module}` | builder | Sell a school one module. Idempotent: a module it already has is a `200` with the unchanged set. Refused while what the module structurally needs is off — enable those in the same `PATCH` instead. |
1460-| DELETE | `/schools/{slug}/modules/{module}` | builder | Take one module back. Idempotent, and refused while a module the school still has depends on it — the mirror of the enable direction. |
1455+| GET | `/schools/{id}` | builder | One school by id. |
1456+| PATCH | `/schools/{id}` | builder | Rename a school and/or flip it between `active` and `suspended`. Omitted fields keep their value — both land in one statement, so a request that carries both is one write and never half a patch. The id is not a field a patch can move. |
1457+| DELETE | `/schools/{id}` | builder | Delete a school: its database, its registry row, and its uploaded files. Irreversible — suspension is the reversible door. |
1458+| POST | `/schools/{id}/admin-password` | builder | Reset an admin's password inside a school — the "we are locked out" call. Every session that account held is revoked with it, so a stolen cookie does not survive the reset. Works on a suspended school. |
1459+| POST | `/schools/{id}/enter` | builder | Enter a school as one of its admins — support access, with the school's own session cookie (`<uuid>.<token>`) and no builder power inside it. |
1460+| GET | `/schools/{id}/modules` | builder | What a school has bought, and what is left to sell it. Works on a suspended school — entitlements are the vendor's ledger, not one of the school's doors. |
1461+| PATCH | `/schools/{id}/modules` | builder | Re-sell a school's whole shelf in one call: any mix of modules and packages, in either direction. Every list is optional and an empty body is a no-op. |
1462+| POST | `/schools/{id}/modules/{module}` | builder | Sell a school one module. Idempotent: a module it already has is a `200` with the unchanged set. Refused while what the module structurally needs is off — enable those in the same `PATCH` instead. |
1463+| DELETE | `/schools/{id}/modules/{module}` | builder | Take one module back. Idempotent, and refused while a module the school still has depends on it — the mirror of the enable direction. |
14611464 | GET | `/sessions/{id}` | student | Fetch a single session by id. Visible to the instance's enrolled students, the session's own teacher, the instance's teachers, and managers/admins. |
14621465 | PATCH | `/sessions/{id}` | teacher | Update a session. Requires teacher+ with instance-management rights. Omitted fields keep their value; an explicit `null` clears `ends_at`. |
14631466 | DELETE | `/sessions/{id}` | teacher | Delete a session and its roll-call rows. Requires teacher+ with instance-management rights. |
@@ -3888,14 +3891,14 @@ non-empty and contain none of `/ \ ? # %`.
38883891 BASE=http://127.0.0.1:7656
38893892 JAR=/tmp/hz.cookies
38903893
3891-# SCHOOL is the slug a builder gave this school (see "Multi-school (SaaS)").
3892-SCHOOL=demo
3894+# SCHOOL is the school's uuid, as `GET /auth/schools` publishes it.
3895+SCHOOL=01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d
38933896
38943897 curl -s $BASE/auth/register -H 'content-type: application/json' \
38953898 -d '{"school":"'$SCHOOL'","username":"ali","password":"secret1"}'
38963899
38973900 curl -s -c $JAR $BASE/auth/login -H 'content-type: application/json' \
3898- -d '{"school":"'$SCHOOL'","username":"ali","password":"secret1"}'
3901+ -d '{"username":"ali","password":"secret1"}'
38993902
39003903 # notes
39013904 curl -s -b $JAR $BASE/notes -H 'content-type: application/json' \
@@ -4040,7 +4043,7 @@ So the school cannot be bound at handshake time — a service pinned to one
40404043 school would have to be run once per customer — and every *frame* names it
40414044 instead.
40424045
4043-`school` is the school's slug, exactly as it appears in a login (`demo`), and
4046+`school` is the school's hyphenated uuid, exactly as `GET /school` returns it (`01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d`), and
40444047 it is **required** on `Request`, `ApiRequest` and `BlobRequest`. Every answer
40454048 echoes it, refusals included, so a service can tell which of its in-flight
40464049 streams a refusal belongs to. There is no default and no fallback: a frame
@@ -4048,8 +4051,8 @@ naming no school is `malformed`.
40484051
40494052 | `code` | Meaning |
40504053 | ------ | ------- |
4051-| `malformed` | `school` is absent, or is not a slug at all |
4052-| `unknown_school` | A well-formed slug this deployment does not serve — not retryable without a config change |
4054+| `malformed` | `school` is absent — a frame-shape error, not a bad id |
4055+| `unknown_school` | The value is not a hyphenated uuid, or it is a uuid this deployment does not serve — not retryable without a config change |
40534056 | `school_suspended` | The school exists and is switched off; worth retrying later |
40544057
40554058 A read is answered out of that school's own database, `on_behalf_of` is
@@ -4065,14 +4068,14 @@ For each request the **backend** opens a bidi stream, writes one `Request`,
40654068 finishes its send side, and reads one `Response`:
40664069
40674070 ```json
4068-{ "id": "01J...", "school": "demo", "capability": "ocr.extract",
4071+{ "id": "01J...", "school": "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d", "capability": "ocr.extract",
40694072 "deadline_ms": 30000, "payload": { "image": "<base64>" } }
40704073 ```
40714074
40724075 ```json
4073-{ "status": "ok", "id": "01J...", "school": "demo",
4076+{ "status": "ok", "id": "01J...", "school": "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d",
40744077 "payload": { "text": "..." } }
4075-{ "status": "err", "id": "01J...", "school": "demo",
4078+{ "status": "err", "id": "01J...", "school": "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d",
40764079 "code": "unsupported_image", "message": "only png and jpeg" }
40774080 ```
40784081
@@ -4221,7 +4224,7 @@ Same framing as every other `hab/2` frame; concurrency and correlation are the
42214224 stream, exactly as for capability requests.
42224225
42234226 ```json
4224-{ "id": "01J...", "school": "demo", "path": "/marks/me",
4227+{ "id": "01J...", "school": "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d", "path": "/marks/me",
42254228 "query": "limit=10&offset=0", "on_behalf_of": "user:01J...",
42264229 "method": "GET" }
42274230 ```
@@ -4235,9 +4238,9 @@ absent `method` means `GET`, and anything else is refused.
42354238 The answer is tagged by `outcome`:
42364239
42374240 ```json
4238-{ "outcome": "ok", "id": "01J...", "school": "demo", "status": 200,
4241+{ "outcome": "ok", "id": "01J...", "school": "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d", "status": 200,
42394242 "body": { } }
4240-{ "outcome": "err", "id": "01J...", "school": "demo",
4243+{ "outcome": "err", "id": "01J...", "school": "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d",
42414244 "code": "path_not_allowed",
42424245 "message": "`/users` is not a path AI services may read" }
42434246 ```
@@ -4250,10 +4253,10 @@ failure has misread the contract.
42504253
42514254 | `code` | Meaning |
42524255 | ------ | ------- |
4253-| `malformed` | The frame was not a readable `ApiRequest` (a missing `school` lands here), `school` is not a slug, or `path`+`query` do not form a request target |
4256+| `malformed` | The frame was not a readable `ApiRequest` (a missing `school` lands here), or `path`+`query` do not form a request target |
42544257 | `method_not_allowed` | `method` was present and was not `GET` |
42554258 | `path_not_allowed` | `path` is not in the read scope below |
4256-| `unknown_school` | `school` is a slug this deployment does not serve |
4259+| `unknown_school` | `school` is not a hyphenated uuid, or it is a uuid this deployment does not serve |
42574260 | `school_suspended` | That school is suspended — retryable once it is not |
42584261 | `unknown_user` | `on_behalf_of` names no user *of that school* (deleted since the service last saw them, or an id belonging to a different school) |
42594262 | `unavailable` | The API is not serving yet, the database socket is down, or the read outran the request timeout — retryable |
@@ -4325,7 +4328,7 @@ the shape differs, and the two are told apart by the field each *requires*: an
43254328 `ApiRequest` has `path`, a `BlobRequest` has `file`.
43264329
43274330 ```json
4328-{ "id": "01J...", "school": "demo", "file": "01J8XZ0K3Q8G7X2M4N5P6R7S8V",
4331+{ "id": "01J...", "school": "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d", "file": "01J8XZ0K3Q8G7X2M4N5P6R7S8V",
43294332 "on_behalf_of": "user:01J..." }
43304333 ```
43314334
@@ -4343,9 +4346,9 @@ tag `Response` uses, not the api read's `outcome`, since a blob header carries
43434346 no HTTP status to collide with:
43444347
43454348 ```json
4346-{ "status": "ok", "id": "01J...", "school": "demo", "name": "recap.pdf",
4349+{ "status": "ok", "id": "01J...", "school": "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d", "name": "recap.pdf",
43474350 "content_type": "application/pdf", "size": 204800 }
4348-{ "status": "err", "id": "01J...", "school": "demo", "code": "forbidden",
4351+{ "status": "err", "id": "01J...", "school": "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d", "code": "forbidden",
43494352 "message": "`01J...` may not view the course this file belongs to" }
43504353 ```
43514354
@@ -4363,7 +4366,7 @@ slow-but-reading service is never cut off.
43634366
43644367 | `code` | Meaning |
43654368 | ------ | ------- |
4366-| `malformed` | The frame was not a readable `BlobRequest`, or `school` is absent or not a slug |
4369+| `malformed` | The frame was not a readable `BlobRequest`, or `school` is absent |
43674370 | `not_found` | No `course_note_file` with that key *in that school*, or its note or course is gone |
43684371 | `forbidden` | The principal may not view that file's course |
43694372 | `unknown_school` / `school_suspended` | As for an api read |
@@ -5049,9 +5052,9 @@ src/
50495052 while Postgres says "contended") + the two sqlx migrator
50505053 sets; init() brings up the control database, a mint
50515054 migrates a school's from the shared template
5052- tenant.rs Slug · SchoolStatus · School · Tenants: one Postgres
5053- database per school (`{control}_school_{slug}`), plus the
5054- control database that registers them (DEMO_SLUG is the
5055+ tenant.rs SchoolId · SchoolStatus · School · Tenants: one Postgres
5056+ database per school (`{control}_school_{uuid hex}`), plus the
5057+ control database that registers them (DEMO_SCHOOL_ID is the
50555058 tests' school)
50565059 db/ the only layer that executes queries: per-table SQL, one
50575060 file per resource · cap.rs (the count-cap CTE recipes and
@@ -5218,9 +5221,9 @@ src/
52185221 web/ axum layer: DTOs (serde + OpenAPI schemas) + handlers +
52195222 auth extractors
52205223 tenant_state.rs State<AppState>: the shadow of axum's State that resolves the
5221- caller's school from the `<slug>.<token>` cookie, so every
5224+ caller's school from the `<uuid>.<token>` cookie, so every
52225225 handler that imports it is school-scoped by construction
5223- (ResolvedTenant · TenantExt · SchoolSlug · split_cookie)
5226+ (ResolvedTenant · TenantExt · SchoolIdCookie · split_cookie)
52245227 module_gate.rs one route_layer per nest: a module the school has not bought
52255228 answers 403 {error, module} on every route in it, while an
52265229 unmatched path inside it still 404s
compose.yamlmodified+1 -1
@@ -64,7 +64,7 @@ services:
6464 HOST: 0.0.0.0
6565 PORT: "7656"
6666 # The control database: the school registry + the builder accounts. Each
67- # school lives in a Postgres database of its own, named from its slug.
67+ # school lives in a Postgres database of its own, named from its uuid (hex, no dashes).
6868 # Constructed from POSTGRES_* and always aimed at the compose postgres.
6969 DATABASE_URL: postgres://${POSTGRES_USER:-hezarfen}:${POSTGRES_PASSWORD:-hezarfen}@postgres:5432/${POSTGRES_DB:-hezarfen_control}
7070 # Hardcoded: must not pick up an old systemd host path from the env file.
migrations/control/20260923000001_drop_school_slug.sqladded+4 -0
@@ -0,0 +1,4 @@
1+-- Cookie prefix, builder routes and blob directories cut over to the school
2+-- uuid in the same deploy as this column drop. Existing session cookies
3+-- cannot resolve after this migration; users log in again.
4+ALTER TABLE school DROP CONSTRAINT school_slug, DROP COLUMN slug;
src/ai/capability.rsmodified+1 -1
@@ -13,7 +13,7 @@
1313 //! The scope decides one thing only: whether the bridge resolves the frame's
1414 //! school before the operation runs. A [`Scope::School`] operation runs against
1515 //! the named school's own database — the frame's school is the *only* tenancy
16-//! input, and a slug that matches nothing is `unknown_school`, never a
16+//! input, and a school id that matches nothing is `unknown_school`, never a
1717 //! fallback to another school or to the control database.
1818
1919 use serde_json::Value;
src/ai/insight.rsmodified+8 -9
@@ -46,7 +46,7 @@ use crate::constant::{
4646 AI_INSIGHT_REFRESH_TIMEOUT_SECS, AI_INSIGHT_REPORT_TIMEOUT_SECS,
4747 AI_INSIGHT_STUDENT_TIMEOUT_SECS,
4848 };
49-use crate::tenant::Slug;
49+use crate::tenant::SchoolId;
5050
5151 pub use crate::constant::{
5252 AI_INSIGHT_CLASS_CAPABILITY, AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_REPORT_CAPABILITY,
@@ -218,7 +218,7 @@ pub struct ReportRequest {
218218 /// rendering reads nothing, but the service's logs name the requester.
219219 pub requested_by: String,
220220 /// The school's own identity, so the document prints a display name
221- /// rather than a slug.
221+ /// rather than a raw id.
222222 pub school: ReportSchool,
223223 /// Every class (şube) of the school, id and display name: the summaries'
224224 /// evidence carries class **ids**, and a document that groups by class
@@ -272,7 +272,7 @@ pub struct ReportResponse {
272272 /// door that has already answered `503` for it ([`crate::web::insights`]).
273273 pub async fn compute_student(
274274 bridge: &AiBridge,
275- school: &Slug,
275+ school: &SchoolId,
276276 request: &StudentRequest,
277277 ) -> Result<StudentResponse, AiError> {
278278 dispatch(
@@ -289,7 +289,7 @@ pub async fn compute_student(
289289 /// batch is over; the deadline is [`AI_INSIGHT_REFRESH_TIMEOUT_SECS`].
290290 pub async fn refresh(
291291 bridge: &AiBridge,
292- school: &Slug,
292+ school: &SchoolId,
293293 request: &RefreshRequest,
294294 ) -> Result<RefreshResponse, AiError> {
295295 dispatch(
@@ -310,7 +310,7 @@ pub async fn refresh(
310310 /// document — this function only moves it.
311311 pub async fn report(
312312 bridge: &AiBridge,
313- school: &Slug,
313+ school: &SchoolId,
314314 request: &ReportRequest,
315315 ) -> Result<ReportResponse, AiError> {
316316 dispatch(
@@ -332,7 +332,7 @@ pub async fn report(
332332 /// reporting the service out of step.
333333 async fn dispatch<T>(
334334 bridge: &AiBridge,
335- school: &Slug,
335+ school: &SchoolId,
336336 capability: &str,
337337 timeout_secs: u64,
338338 request: &impl Serialize,
@@ -613,8 +613,7 @@ mod tests {
613613 run_day: "2026-09-17".into(),
614614 requested_by: "user-9".into(),
615615 school: ReportSchool {
616- id: "school-1".into(),
617- slug: "demo".into(),
616+ id: "019732e3-7b00-7000-8000-00000000dead".into(),
618617 name: "Demo Okulu".into(),
619618 },
620619 classes: vec![ClassLabel {
@@ -632,7 +631,7 @@ mod tests {
632631 "kind": "okul",
633632 "run_day": "2026-09-17",
634633 "requested_by": "user-9",
635- "school": { "id": "school-1", "slug": "demo", "name": "Demo Okulu" },
634+ "school": { "id": "019732e3-7b00-7000-8000-00000000dead", "name": "Demo Okulu" },
636635 "classes": [{ "id": "class-1", "name": "8-A" }],
637636 "summaries": [],
638637 "recommendations": [],
src/ai/podcast.rsmodified+8 -8
@@ -36,7 +36,7 @@ use crate::ai::error::AiError;
3636 use crate::database::Database;
3737 use crate::domain::podcast_job::PodcastJobId;
3838 use crate::service::podcast_job::{PodcastRefusal, ReportInput};
39-use crate::tenant::Slug;
39+use crate::tenant::SchoolId;
4040
4141 /// The capability strings, re-exported so a reader of the payload contract
4242 /// finds them next to the payloads — the same shape as
@@ -127,19 +127,19 @@ pub struct PodcastReportReply {
127127 /// Start one job. `Err` is a short, stable code — see [`failure_code`].
128128 pub async fn submit(
129129 bridge: &AiBridge,
130- slug: &Slug,
130+ school: &SchoolId,
131131 payload: PodcastSubmitPayload,
132132 ) -> Result<PodcastSubmitReply, String> {
133- dispatch(bridge, slug, AI_PODCAST_SUBMIT_CAPABILITY, payload).await
133+ dispatch(bridge, school, AI_PODCAST_SUBMIT_CAPABILITY, payload).await
134134 }
135135
136136 /// Cancel one job.
137137 pub async fn cancel(
138138 bridge: &AiBridge,
139- slug: &Slug,
139+ school: &SchoolId,
140140 payload: PodcastCancelPayload,
141141 ) -> Result<PodcastCancelReply, String> {
142- dispatch(bridge, slug, AI_PODCAST_CANCEL_CAPABILITY, payload).await
142+ dispatch(bridge, school, AI_PODCAST_CANCEL_CAPABILITY, payload).await
143143 }
144144
145145 /// Handle one client-initiated `podcast.report` call: decode the payload,
@@ -186,7 +186,7 @@ pub fn refusal(refusal: &PodcastRefusal) -> (&'static str, String) {
186186 /// rename it into place, and stamp the row.
187187 ///
188188 /// `files_root` is **the school's own** directory (the caller resolves the
189-/// slug); the file lands under its `podcast/` subdirectory, keyed by the job
189+/// school); the file lands under its `podcast/` subdirectory, keyed by the job
190190 /// id, which is what the job row's own `audio_key` then publishes.
191191 ///
192192 /// The order is the point, and the same one the HTTP doors hold: a refusal
@@ -293,7 +293,7 @@ where
293293 /// travels this path, so the encode/decode failure vocabulary is written once.
294294 async fn dispatch<P, R>(
295295 bridge: &AiBridge,
296- slug: &Slug,
296+ school: &SchoolId,
297297 capability: &str,
298298 payload: P,
299299 ) -> Result<R, String>
@@ -307,7 +307,7 @@ where
307307 })?;
308308
309309 let raw = bridge
310- .dispatch(slug, capability, payload)
310+ .dispatch(school, capability, payload)
311311 .await
312312 .map_err(failure_code)?;
313313
src/ai/protocol.rsmodified+14 -9
@@ -60,7 +60,7 @@
6060 //!
6161 //! * `malformed` — the frame is not this shape (a missing or mistyped field).
6262 //! * `unknown_capability` — no operation this backend serves has that name.
63-//! * `unknown_school` — the named slug is not a school on this deployment.
63+//! * `unknown_school` — the named id is not a school on this deployment.
6464 //! * `school_suspended` — it exists and is switched off; worth retrying later.
6565 //! * `not_permitted` — the school's own feature set refuses the operation.
6666 //! * `invalid_payload` — the payload does not fit the operation's contract
@@ -75,13 +75,13 @@
7575 //!
7676 //! # School scoping
7777 //!
78-//! Every request frame names its school by slug, and every answer echoes it:
78+//! Every request frame names its school by uuid, and every answer echoes it:
7979 //! [`Request::school`], [`ApiRequest::school`], [`BlobRequest::school`] and
8080 //! their responses. The AI fleet is *shared* across the deployment — one
8181 //! service serves every school — so the school cannot be bound once at
8282 //! handshake time and [`Hello`] deliberately carries none: a service pinned to
8383 //! one school would have to be run once per customer. A frame without a
84-//! `school` is `malformed`, an unknown slug is `unknown_school`, a suspended
84+//! `school` is `malformed`, an unknown id is `unknown_school`, a suspended
8585 //! one `school_suspended`; there is no default and no fallback, because a read
8686 //! answered out of the wrong school's database is the one failure this field
8787 //! exists to make impossible.
@@ -175,7 +175,8 @@ pub enum RejectCode {
175175 pub struct Request {
176176 /// Trace id (ULID). Not used for correlation — the stream does that.
177177 pub id: String,
178- /// Slug of the school this work belongs to. Required — see this module's
178+ /// Uuid of the school this work belongs to (hyphenated form). Required —
179+ /// see this module's
179180 /// "School scoping".
180181 pub school: String,
181182 /// Which capability from the worker's [`Hello::capabilities`] to invoke.
@@ -215,7 +216,8 @@ pub enum Response {
215216 pub struct ApiRequest {
216217 /// Trace id (ULID). Not used for correlation — the stream does that.
217218 pub id: String,
218- /// Slug of the school to read. Required — see this module's "School
219+ /// Uuid of the school to read (hyphenated form). Required — see this
220+ /// module's "School
219221 /// scoping"; the answer comes out of that school's own database.
220222 pub school: String,
221223 /// Path as the REST API spells it, e.g. `"/users/me"`. No host, no query.
@@ -250,7 +252,7 @@ pub enum ApiResponse {
250252 Err {
251253 id: String,
252254 /// Echo of the school the frame named — as sent, even when it named no
253- /// school a slug could be made of, so a service can tell which of its
255+ /// school a uuid could be made of, so a service can tell which of its
254256 /// in-flight reads was refused.
255257 school: String,
256258 /// Bridge-defined, stable, machine-readable (`"path_not_allowed"`,
@@ -267,7 +269,8 @@ pub enum ApiResponse {
267269 pub struct BlobRequest {
268270 /// Trace id (ULID). Not used for correlation — the stream does that.
269271 pub id: String,
270- /// Slug of the school the file belongs to. Required — see this module's
272+ /// Uuid of the school the file belongs to (hyphenated form). Required —
273+ /// see this module's
271274 /// "School scoping"; the bytes come out of that school's blob directory.
272275 pub school: String,
273276 /// The `course_note_file` record key, as `GET /course-notes/{id}/files`
@@ -317,7 +320,8 @@ pub enum BlobResponse {
317320 pub struct CapabilityRequest {
318321 /// Trace id (ULID). Not used for correlation — the stream does that.
319322 pub id: String,
320- /// Slug of the school the call is scoped to. Required, exactly as on
323+ /// Uuid of the school the call is scoped to (hyphenated form). Required,
324+ /// exactly as on
321325 /// every other frame — one capability is deployment-scoped
322326 /// (`insight.schools.list`, whose answer *is* the school directory) and
323327 /// sends the empty string there.
@@ -372,7 +376,8 @@ pub struct BlobUploadRequest {
372376 pub id: String,
373377 /// The shape marker. Must be `true`; any other value is `malformed`.
374378 pub upload: bool,
375- /// Slug of the school the artifact belongs to. Required — the bytes land
379+ /// Uuid of the school the artifact belongs to (hyphenated form). Required
380+ /// — the bytes land
376381 /// in that school's own blob directory, never anywhere else.
377382 pub school: String,
378383 /// The backend-minted podcast job the artifact belongs to.
src/ai/rag.rsmodified+15 -15
@@ -89,7 +89,7 @@ impl RagIndexPayload {
8989 /// answered. Silent no-op when the bridge is off or no worker offers
9090 /// `rag.index`.
9191 ///
92-/// `tenant` is the caller's own school: its slug rides the `hab/2` frame, and
92+/// `tenant` is the caller's own school: its uuid rides the `hab/2` frame, and
9393 /// `state.db` — the same school's database, since the caller reached this
9494 /// through the shadow `State` — is where the answer is stored.
9595 ///
@@ -108,11 +108,11 @@ pub async fn index_course_note(state: &AppState, tenant: &ResolvedTenant, note:
108108 tracing::debug!(
109109 "skipping rag.index for course note {}: the `{}` school has no `chatbot` module",
110110 note.get_id().key(),
111- tenant.slug
111+ tenant.id
112112 );
113113 return;
114114 }
115- let school = &tenant.slug;
115+ let school = &tenant.id;
116116 let Some(bridge) = state.ai.as_ref() else {
117117 return;
118118 };
@@ -256,43 +256,43 @@ async fn replay_indexed_notes(state: AppState) {
256256 return;
257257 }
258258 };
259- for slug in directory.schools {
260- replay_school(&state, &slug).await;
259+ for school in directory.schools {
260+ replay_school(&state, &school).await;
261261 }
262262 }
263263
264-async fn replay_school(state: &AppState, slug: &str) {
265- let slug = match crate::tenant::Slug::try_new(slug) {
266- Ok(slug) => slug,
264+async fn replay_school(state: &AppState, school: &str) {
265+ let id = match crate::tenant::SchoolId::try_parse(school) {
266+ Ok(id) => id,
267267 Err(err) => {
268- tracing::warn!("rag.index replay skipped an unreadable school slug: {err}");
268+ tracing::warn!("rag.index replay skipped an unreadable school id: {err}");
269269 return;
270270 }
271271 };
272- let tenant = match state.tenants.resolve(&slug).await {
272+ let tenant = match state.tenants.resolve(&id).await {
273273 Ok(tenant) => tenant,
274274 Err(err) => {
275- tracing::warn!("rag.index replay skipped `{slug}`: {err}");
275+ tracing::warn!("rag.index replay skipped `{id}`: {err}");
276276 return;
277277 }
278278 };
279279 if !tenant.modules.contains(Module::Chatbot) {
280- tracing::debug!("rag.index replay skipped `{slug}`: the school has no chatbot module");
280+ tracing::debug!("rag.index replay skipped `{id}`: the school has no chatbot module");
281281 return;
282282 }
283283 let notes = match crate::db::course_note::list_with_files(&tenant.db).await {
284284 Ok(notes) => notes,
285285 Err(err) => {
286- tracing::warn!("rag.index replay could not list course notes in `{slug}`: {err}");
286+ tracing::warn!("rag.index replay could not list course notes in `{id}`: {err}");
287287 return;
288288 }
289289 };
290290 if notes.is_empty() {
291- tracing::debug!("rag.index replay: `{slug}` has no course notes with files");
291+ tracing::debug!("rag.index replay: `{id}` has no course notes with files");
292292 return;
293293 }
294294 tracing::info!(
295- school = %slug,
295+ school = %id,
296296 notes = notes.len(),
297297 "replaying rag.index for course notes with files"
298298 );
src/ai/rag_chat.rsmodified+2 -2
@@ -149,7 +149,7 @@ pub struct RagChatReplyPayload {
149149 pub async fn answer(
150150 db: &crate::database::Database,
151151 bridge: &crate::ai::AiBridge,
152- slug: &crate::tenant::Slug,
152+ school: &crate::tenant::SchoolId,
153153 thread: &crate::domain::rag_thread::RagThreadId,
154154 fresh: &[crate::domain::rag_message::RagMessageId; 2],
155155 prompt: String,
@@ -178,7 +178,7 @@ pub async fn answer(
178178
179179 let raw = bridge
180180 .dispatch_with_timeout(
181- slug,
181+ school,
182182 AI_RAG_CHAT_CAPABILITY,
183183 payload,
184184 std::time::Duration::from_secs(AI_RAG_CHAT_TIMEOUT_SECS),
src/ai/rag_study.rsmodified+5 -5
@@ -27,7 +27,7 @@ use crate::constant::{
2727 AI_RAG_QUESTIONS_CAPABILITY, AI_RAG_QUESTIONS_TIMEOUT_SECS, AI_RAG_SUMMARIZE_CAPABILITY,
2828 AI_RAG_SUMMARIZE_TIMEOUT_SECS,
2929 };
30-use crate::tenant::Slug;
30+use crate::tenant::SchoolId;
3131
3232 /// The one corpus a study request is addressed to, and where inside it.
3333 ///
@@ -198,14 +198,14 @@ pub struct RagQuestionsReply {
198198 /// reach the caller as a `502` — the same posture `rag.chat` takes.
199199 pub async fn summarize(
200200 bridge: &AiBridge,
201- slug: &Slug,
201+ school: &SchoolId,
202202 payload: RagSummarizePayload,
203203 ) -> Result<RagSummarizeReply, String> {
204204 let asker = payload.asker.clone();
205205 let encoded = encode(&payload, AI_RAG_SUMMARIZE_CAPABILITY)?;
206206 let raw = bridge
207207 .dispatch_with_timeout(
208- slug,
208+ school,
209209 AI_RAG_SUMMARIZE_CAPABILITY,
210210 encoded,
211211 Duration::from_secs(AI_RAG_SUMMARIZE_TIMEOUT_SECS),
@@ -221,14 +221,14 @@ pub async fn summarize(
221221 /// corpus. The refusal vocabulary is [`summarize`]'s, code for code.
222222 pub async fn questions(
223223 bridge: &AiBridge,
224- slug: &Slug,
224+ school: &SchoolId,
225225 payload: RagQuestionsPayload,
226226 ) -> Result<RagQuestionsReply, String> {
227227 let asker = payload.asker.clone();
228228 let encoded = encode(&payload, AI_RAG_QUESTIONS_CAPABILITY)?;
229229 let raw = bridge
230230 .dispatch_with_timeout(
231- slug,
231+ school,
232232 AI_RAG_QUESTIONS_CAPABILITY,
233233 encoded,
234234 Duration::from_secs(AI_RAG_QUESTIONS_TIMEOUT_SECS),
src/ai/server.rsmodified+36 -35
@@ -35,7 +35,7 @@ use crate::module::Module;
3535 use crate::state::AppState;
3636 use crate::telemetry::Metrics;
3737 use crate::service::course::can_view_course;
38-use crate::tenant::{ResolvedTenant, Slug, Tenants};
38+use crate::tenant::{ResolvedTenant, SchoolId, Tenants};
3939 use crate::web::blob_path;
4040 use crate::web::extractor::AiPrincipal;
4141 use crate::web::tenant_state::{TenantExt, school_files_path};
@@ -68,40 +68,41 @@ struct ApiHandle {
6868 }
6969
7070 impl ApiHandle {
71- /// Resolve the slug a frame named into that school's database, or the
72- /// refusal the service gets.
71+ /// Resolve the school a frame named, or the refusal the service gets.
7372 ///
74- /// The three codes are distinct on purpose: `malformed` is the service's
75- /// own bug (that string is no slug), `unknown_school` means the deployment
76- /// has no such customer, and `school_suspended` means it has one that is
77- /// switched off — a service that retries the first two forever learns
78- /// nothing, while the third is worth retrying later.
73+ /// A value that is not a hyphenated uuid is `unknown_school`, not
74+ /// `malformed`: `malformed` stays the frame-shape error. `unknown_school`
75+ /// means the deployment has no such customer, and `school_suspended`
76+ /// means it has one that is switched off.
7977 async fn school(&self, school: &str) -> Result<ResolvedTenant, (&'static str, String)> {
80- let slug = Slug::try_new(school).map_err(|err| {
81- (
82- "malformed",
83- format!("`{school}` is not a school slug: {err}"),
84- )
85- })?;
86- self.tenants.resolve(&slug).await.map_err(|err| match err {
78+ let id = match SchoolId::try_parse(school) {
79+ Ok(id) => id,
80+ Err(_) => {
81+ return Err((
82+ "unknown_school",
83+ format!("this deployment serves no `{school}` school"),
84+ ));
85+ }
86+ };
87+ self.tenants.resolve(&id).await.map_err(|err| match err {
8788 AppError::Unauthorized => (
8889 "unknown_school",
89- format!("this deployment serves no `{slug}` school"),
90+ format!("this deployment serves no `{id}` school"),
9091 ),
9192 AppError::Forbidden(_) => (
9293 "school_suspended",
93- format!("the `{slug}` school is suspended"),
94+ format!("the `{id}` school is suspended"),
9495 ),
9596 other => (
9697 "unavailable",
97- format!("the `{slug}` school is not reachable: {other}"),
98+ format!("the `{id}` school is not reachable: {other}"),
9899 ),
99100 })
100101 }
101102
102103 /// One school's blob directory.
103- fn files_dir(&self, slug: &Slug) -> std::path::PathBuf {
104- school_files_path(&self.files_path, slug)
104+ fn files_dir(&self, id: &SchoolId) -> std::path::PathBuf {
105+ school_files_path(&self.files_path, id)
105106 }
106107 }
107108
@@ -243,7 +244,7 @@ impl AiBridge {
243244 /// the correlation, and a slow one cannot stall a fast one.
244245 pub async fn dispatch(
245246 &self,
246- school: &Slug,
247+ school: &SchoolId,
247248 capability: &str,
248249 payload: Value,
249250 ) -> Result<Value, AiError> {
@@ -256,7 +257,7 @@ impl AiBridge {
256257 /// generation).
257258 pub async fn dispatch_with_timeout(
258259 &self,
259- school: &Slug,
260+ school: &SchoolId,
260261 capability: &str,
261262 payload: Value,
262263 timeout: Duration,
@@ -275,7 +276,7 @@ impl AiBridge {
275276 payload,
276277 };
277278
278- // The span names the capability, the worker, the school slug and this
279+ // The span names the capability, the worker, the school uuid and this
279280 // call's own id — never the payload, which is the user's own text.
280281 let span = tracing::info_span!(
281282 "ai.request",
@@ -532,7 +533,7 @@ async fn serve_client_stream(
532533 }
533534 };
534535 let id = string_field(&raw, "id");
535- // Echoed verbatim on a refusal, before it is known to be a slug at all:
536+ // Echoed verbatim on a refusal, before it is known to be a school at all:
536537 // it is how the service tells which of its in-flight reads was refused.
537538 let school = string_field(&raw, "school");
538539 // Routed on the shape's required field rather than by parsing one and
@@ -740,18 +741,18 @@ async fn ingest_upload(
740741 "the api is not serving yet — retry".to_string(),
741742 ))?;
742743 let tenant = api.school(&request.school).await?;
743- let (slug, db) = (tenant.slug, tenant.db);
744+ let (school, db) = (tenant.id, tenant.db);
744745 // This stream bypasses the router, so it also bypasses the route_layer the
745746 // module gate is — the entitlement is checked here by hand instead. The
746747 // podcast nest is the `chatbot` module's, exactly as it is over HTTP.
747748 if !tenant.modules.contains(Module::Chatbot) {
748749 return Err((
749750 "not_permitted",
750- format!("the `{slug}` school has no `chatbot` module"),
751+ format!("the `{school}` school has no `chatbot` module"),
751752 ));
752753 }
753754 let refusal = crate::ai::podcast::refusal;
754- let root = api.files_dir(&slug);
755+ let root = api.files_dir(&school);
755756 let (key, size) = crate::ai::podcast::ingest(&db, &root, request, body)
756757 .await
757758 .map_err(|r| refusal(&r))?;
@@ -790,7 +791,7 @@ async fn open_blob(
790791 "the api is not serving yet — retry".to_string(),
791792 ))?;
792793 let tenant = api.school(&request.school).await?;
793- let (slug, db) = (tenant.slug, tenant.db);
794+ let (school, db) = (tenant.id, tenant.db);
794795 // This stream bypasses the router, so it also bypasses the route_layer the
795796 // module gate is — the entitlement is checked here by hand instead.
796797 // `chatbot` too: a school that did not buy the `ai` package sends no data
@@ -799,7 +800,7 @@ async fn open_blob(
799800 if !tenant.modules.contains(module) {
800801 return Err((
801802 "module_disabled",
802- format!("the `{slug}` school has no `{module}` module"),
803+ format!("the `{school}` school has no `{module}` module"),
803804 ));
804805 }
805806 }
@@ -839,7 +840,7 @@ async fn open_blob(
839840
840841 // The row exists but its blob does not: server-side damage (a lost volume
841842 // path), exactly as `download_file` reads it — not the service's `404`.
842- let path = blob_path(&api.files_dir(&slug), &file.get_id().key());
843+ let path = blob_path(&api.files_dir(&school), &file.get_id().key());
843844 let handle = tokio::fs::File::open(&path).await.map_err(|e| {
844845 (
845846 "unavailable",
@@ -955,7 +956,7 @@ async fn dispatch_api(
955956 } = request;
956957
957958 // The school comes off the frame, so this is where a service naming a
958- // stranger's slug (or a suspended school's) is stopped — before a row of
959+ // stranger's school (or a suspended school's) is stopped — before a row of
959960 // anyone's data is read.
960961 let tenant = api.school(&school).await?;
961962 let db = tenant.db.clone();
@@ -985,7 +986,7 @@ async fn dispatch_api(
985986 // Carries the school's entitlements too, so the router's module gate
986987 // refuses a disabled nest on this path exactly as it does over HTTP.
987988 dispatched.extensions_mut().insert(TenantExt {
988- slug: tenant.slug,
989+ id: tenant.id,
989990 db,
990991 modules: tenant.modules,
991992 });
@@ -1397,7 +1398,7 @@ mod tests {
13971398 refuse_before_dispatch,
13981399 };
13991400 use crate::ai::protocol::read_frame;
1400- use crate::tenant::DEMO_SLUG;
1401+ use crate::tenant::DEMO_SCHOOL_ID;
14011402
14021403 /// An armed handle serving `router`. The database is never touched by these
14031404 /// reads (nobody is named, so the principal is synthetic), but the handle
@@ -1414,7 +1415,7 @@ mod tests {
14141415 fn read_of(path: &str) -> ApiRequest {
14151416 ApiRequest {
14161417 id: "trace-1".to_string(),
1417- school: DEMO_SLUG.to_string(),
1418+ school: DEMO_SCHOOL_ID.to_string(),
14181419 path: path.to_string(),
14191420 query: None,
14201421 on_behalf_of: None,
@@ -1485,7 +1486,7 @@ mod tests {
14851486 // frame may precede it on the stream.
14861487 let big = ApiResponse::Ok {
14871488 id: "trace-1".to_string(),
1488- school: DEMO_SLUG.to_string(),
1489+ school: DEMO_SCHOOL_ID.to_string(),
14891490 status: 200,
14901491 body: serde_json::Value::String("x".repeat(AI_MAX_FRAME_BYTES)),
14911492 };
src/constant.rsmodified+1 -7
@@ -1,12 +1,6 @@
11 //! Validation limits, in one place.
22
3-/// A school slug's length bounds — the name in front of the dot in the session
4-/// cookie, which is also the school's database name and its blob directory
5-/// (see [`crate::tenant::Slug`]).
6-pub const MIN_SLUG_LEN: usize = 2;
7-pub const MAX_SLUG_LEN: usize = 32;
8-
9-/// A school's display name — free text, unlike its slug.
3+/// A school's display name.
104 pub const MAX_SCHOOL_NAME_LEN: usize = 120;
115
126 pub const MIN_USERNAME_LEN: usize = 3;
src/database.rsmodified+6 -7
@@ -29,7 +29,7 @@ use crate::domain::timestamp::Timestamp;
2929 use crate::domain::user::{Password, Username};
3030 use crate::error::AppError;
3131 use crate::module::ModuleSet;
32-use crate::tenant::{DEMO_SLUG, SchoolId, SchoolStatus, Tenants, school_db_name};
32+use crate::tenant::{DEMO_SCHOOL_ID, SchoolId, SchoolStatus, Tenants, school_db_name};
3333
3434 /// The shared database handle.
3535 ///
@@ -101,7 +101,7 @@ pub async fn init(cfg: &Config) -> Result<Tenants, AppError> {
101101 }
102102
103103 /// Parse `DATABASE_URL` into dial options plus the control database's name —
104-/// the name every school database hangs off (`{control}_school_{slug}`).
104+/// the name every school database hangs off (`{control}_school_{uuid hex}`).
105105 pub(crate) fn parse_base(cfg: &Config) -> Result<(PgConnectOptions, String), AppError> {
106106 let opts: PgConnectOptions = cfg.database_url.parse().map_err(|err| {
107107 AppError::Internal(format!(
@@ -754,7 +754,7 @@ impl Drop for TestLease {
754754
755755 /// A complete test deployment: a fresh control database plus the demo school,
756756 /// whose database is cloned from the shared school template and registered in
757-/// the control registry under the slug every suite names ([`DEMO_SLUG`]).
757+/// the control registry under [`DEMO_SCHOOL_ID`].
758758 ///
759759 /// The databases die with the returned registry's last handle (see
760760 /// [`TestDatabases`]); the janitor sweeps anything a crashed run left behind.
@@ -773,7 +773,7 @@ pub async fn init_test_tenants() -> Tenants {
773773 .unwrap_or_else(|err| panic!("migrate the test control database {control_db}: {err}"));
774774
775775 let template = ensure_test_template(&maintenance, &base).await;
776- let demo_id = SchoolId::generate();
776+ let demo_id = SchoolId::try_parse(DEMO_SCHOOL_ID).expect("pinned demo school id");
777777 let school_db = school_db_name(&control_db, demo_id.uuid());
778778 create_database(&maintenance, &school_db, Some(&template)).await;
779779 lease.track(&school_db);
@@ -785,11 +785,10 @@ pub async fn init_test_tenants() -> Tenants {
785785 // without the per-school migration its `bring_up` runs, which the
786786 // template clone has just replaced.
787787 sqlx::query(
788- "INSERT INTO school (id, slug, name, status, created_at)
789- VALUES ($1, $2, $3, $4, $5)",
788+ "INSERT INTO school (id, name, status, created_at)
789+ VALUES ($1, $2, $3, $4)",
790790 )
791791 .bind(demo_id.uuid())
792- .bind(DEMO_SLUG)
793792 .bind("Demo School")
794793 .bind(SchoolStatus::Active)
795794 .bind(Timestamp::now().as_millis())
src/db/insight.rsmodified+16 -15
@@ -53,6 +53,7 @@ use crate::constant::{
5353 use crate::database::{Database, foreign_key_violation, tx_with_retry};
5454 use crate::domain::monotonic_id::next_uuid;
5555 use crate::error::{AppError, ValidationError};
56+use crate::tenant::SchoolId;
5657
5758 // ---- the wire rows ---------------------------------------------------------
5859
@@ -308,21 +309,20 @@ pub struct TableVerdicts {
308309 pub tables: BTreeMap<String, bool>,
309310 }
310311
311-/// The deployment's active schools, by slug.
312+/// The deployment's active schools, as hyphenated uuids.
312313 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
313314 pub struct SchoolDirectory {
314315 pub schools: Vec<String>,
315316 }
316317
317318 /// One school's own identity, as a rendered report prints it. The bridge
318-/// frame already names the school by slug, but a document that reaches a
319-/// manager's screen carries the display name, and the control row is the only
320-/// authority on it.
319+/// frame already names the school by uuid, and a document that reaches a
320+/// manager's screen also carries the display name. The control row is the
321+/// only authority on it.
321322 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
322323 pub struct ReportSchool {
323- /// `school.id` — the surrogate key, not the slug: a slug may be renamed.
324+ /// `school.id`, hyphenated.
324325 pub id: String,
325- pub slug: String,
326326 pub name: String,
327327 }
328328
@@ -855,31 +855,32 @@ pub async fn last_pending(db: &Database) -> Result<PendingList, AppError> {
855855 })
856856 }
857857
858-/// The deployment's active schools, by slug — the one read that is not
859-/// scoped to a school, because it is how a shared AI fleet learns which
860-/// schools exist.
858+/// The deployment's active schools, as hyphenated uuids — the one read that
859+/// is not scoped to a school, because it is how a shared AI fleet learns
860+/// which schools exist.
861861 pub async fn active_schools(control: &Database) -> Result<SchoolDirectory, AppError> {
862862 let schools = sqlx::query_scalar!(
863- "SELECT slug FROM school WHERE status = 'active' ORDER BY slug"
863+ "SELECT id FROM school WHERE status = 'active' ORDER BY name"
864864 )
865865 .fetch_all(control)
866866 .await?;
867- Ok(SchoolDirectory { schools })
867+ Ok(SchoolDirectory {
868+ schools: schools.into_iter().map(|id| id.to_string()).collect(),
869+ })
868870 }
869871
870-/// One school's identity row, by slug. `None` only for a slug the control
872+/// One school's identity row, by id. `None` only for an id the control
871873 /// database does not hold — a resolved tenant always has one, so a caller
872874 /// reads that as an internal fault, not as a refusal.
873875 pub async fn school_identity(
874876 control: &Database,
875- slug: &str,
877+ id: &SchoolId,
876878 ) -> Result<Option<ReportSchool>, AppError> {
877- let row = sqlx::query!("SELECT id, name FROM school WHERE slug = $1", slug)
879+ let row = sqlx::query!("SELECT id, name FROM school WHERE id = $1", id.uuid())
878880 .fetch_optional(control)
879881 .await?;
880882 Ok(row.map(|row| ReportSchool {
881883 id: row.id.to_string(),
882- slug: slug.to_string(),
883884 name: row.name,
884885 }))
885886 }
src/db/person.rsmodified+26 -17
@@ -11,7 +11,7 @@ use crate::domain::session::{SessionId, SessionToken};
1111 use crate::domain::timestamp::Timestamp;
1212 use crate::domain::user::{PasswordHash, Username};
1313 use crate::error::AppError;
14-use crate::tenant::{SchoolId, SchoolStatus, Slug};
14+use crate::tenant::{SchoolId, SchoolStatus};
1515
1616 /// The raw account insert behind [`crate::service::person::create_or_load`].
1717 /// The unique index on `username` is the whole availability check; the loser
@@ -65,19 +65,19 @@ pub async fn find_by_username(db: &Database, username: &str) -> Result<Option<Pe
6565 Ok(person)
6666 }
6767
68-/// Every school the person belongs to, slug order, with the registry's name
68+/// Every school the person belongs to, name order, with the registry's name
6969 /// and status joined in. Suspended schools are part of the answer — the
7070 /// caller decides what to offer.
7171 pub async fn memberships(db: &Database, person: &PersonId) -> Result<Vec<Membership>, AppError> {
7272 let rows = sqlx::query_as!(
7373 Membership,
74- r#"SELECT s.slug AS "slug: Slug",
74+ r#"SELECT s.id AS "id: SchoolId",
7575 s.name,
7676 s.status AS "status: SchoolStatus"
7777 FROM person_school ps
7878 JOIN school s ON s.id = ps.school
7979 WHERE ps.person = $1
80- ORDER BY s.slug"#,
80+ ORDER BY s.name"#,
8181 person.uuid()
8282 )
8383 .fetch_all(db)
@@ -86,23 +86,23 @@ pub async fn memberships(db: &Database, person: &PersonId) -> Result<Vec<Members
8686 }
8787
8888 /// The person's membership in exactly one school — the `POST /auth/school`
89-/// gate. A slug the person does not hold is the same `None` a malformed one
90-/// is: no existence signal either way.
89+/// gate. An id the person does not hold is the same `None` a non-uuid is:
90+/// no existence signal either way.
9191 pub async fn membership_of(
9292 db: &Database,
9393 person: &PersonId,
94- slug: &Slug,
94+ id: &SchoolId,
9595 ) -> Result<Option<Membership>, AppError> {
9696 let row = sqlx::query_as!(
9797 Membership,
98- r#"SELECT s.slug AS "slug: Slug",
98+ r#"SELECT s.id AS "id: SchoolId",
9999 s.name,
100100 s.status AS "status: SchoolStatus"
101101 FROM person_school ps
102102 JOIN school s ON s.id = ps.school
103- WHERE ps.person = $1 AND s.slug = $2"#,
103+ WHERE ps.person = $1 AND s.id = $2"#,
104104 person.uuid(),
105- slug.as_str()
105+ id.uuid()
106106 )
107107 .fetch_optional(db)
108108 .await?;
@@ -110,17 +110,15 @@ pub async fn membership_of(
110110 }
111111
112112 /// Attach a person to a school. Idempotent by the primary key: a racing or
113-/// repeated join is a no-op, not an error. The membership carries the
114-/// school's uuid, resolved from the slug in the same statement — so a school
115-/// deleted mid-flight joins nothing instead of erroring, which is the honest
116-/// outcome (there is nothing left to join).
117-pub async fn add_membership(db: &Database, person: &PersonId, slug: &Slug) -> Result<(), AppError> {
113+/// repeated join is a no-op, not an error. A school deleted mid-flight joins
114+/// nothing instead of erroring, which is the honest outcome.
115+pub async fn add_membership(db: &Database, person: &PersonId, id: &SchoolId) -> Result<(), AppError> {
118116 sqlx::query!(
119117 "INSERT INTO person_school (person, school, created_at)
120- SELECT $1, s.id, $3 FROM school s WHERE s.slug = $2
118+ SELECT $1, s.id, $3 FROM school s WHERE s.id = $2
121119 ON CONFLICT DO NOTHING",
122120 person.uuid(),
123- slug.as_str(),
121+ id.uuid(),
124122 Timestamp::now().as_millis()
125123 )
126124 .execute(db)
@@ -128,6 +126,17 @@ pub async fn add_membership(db: &Database, person: &PersonId, slug: &Slug) -> Re
128126 Ok(())
129127 }
130128
129+/// Active schools a registration picker may offer: id and display name,
130+/// name order. Empty when none are active.
131+pub async fn list_active_schools(db: &Database) -> Result<Vec<(uuid::Uuid, String)>, AppError> {
132+ let rows = sqlx::query!(
133+ "SELECT id, name FROM school WHERE status = 'active' ORDER BY name"
134+ )
135+ .fetch_all(db)
136+ .await?;
137+ Ok(rows.into_iter().map(|row| (row.id, row.name)).collect())
138+}
139+
131140 /// Drop every membership pointing at a school — the control-plane half of
132141 /// [`crate::tenant::Tenants::drop`], inside the transaction that also drops the
133142 /// entitlements and the registry row, so `ON DELETE NO ACTION` never refuses
src/domain/builder.rsmodified+1 -1
@@ -3,7 +3,7 @@
33 //! A builder creates, suspends and drops schools; it is **not** a user of any
44 //! school and holds no role there. The two principals are kept apart by
55 //! construction: a builder row lives in a different database and its cookie
6-//! carries a different prefix (`builder.<token>` against `<slug>.<token>`), so
6+//! carries a different prefix (`builder.<token>` against `<uuid>.<token>`), so
77 //! neither extractor can be fed the other's cookie.
88 //!
99 //! The credential newtypes are [`crate::domain::user`]'s — same rules, same
src/domain/person.rsmodified+4 -4
@@ -14,7 +14,7 @@ use crate::domain::monotonic_id::next_uuid;
1414 use crate::domain::session::SessionToken;
1515 use crate::domain::timestamp::Timestamp;
1616 use crate::domain::user::{PasswordHash, Username};
17-use crate::tenant::{SchoolStatus, Slug};
17+use crate::tenant::{SchoolId, SchoolStatus};
1818
1919 /// Typed person row id (control database). A UUIDv7 minted by the
2020 /// process-wide monotonic generator, so `id` order is mint order.
@@ -60,14 +60,14 @@ impl Person {
6060 /// One school a person belongs to, joined off the control registry.
6161 #[derive(Debug, Clone, sqlx::FromRow)]
6262 pub struct Membership {
63- pub(crate) slug: Slug,
63+ pub(crate) id: SchoolId,
6464 pub(crate) name: String,
6565 pub(crate) status: SchoolStatus,
6666 }
6767
6868 impl Membership {
69- pub fn slug(&self) -> &Slug {
70- &self.slug
69+ pub fn id(&self) -> SchoolId {
70+ self.id
7171 }
7272
7373 pub fn name(&self) -> &str {
src/lib.rsmodified+4 -4
@@ -52,10 +52,10 @@ use crate::web::module_gate::gate;
5252 modifiers(&SecurityAddon),
5353 tags(
5454 (name = "meta", description = "Liveness, the authoritative clock, and the validation contract. `GET /health` (and its `/` mirror) reports what the process can currently do — `{status, db, ai}` — answering `503` with a body that names the failing dependency rather than a bare refusal, and it keeps answering while the database is down. `GET /limits` publishes every fixed bound the API enforces — field lengths, numeric ranges, closed value sets (roles, course kinds, exam and question kinds, homework statuses, image content types) — so a client validates against the server's own constants instead of a hard-coded copy that drifts. Unauthenticated, because the registration form needs the username and password bounds before a session exists, and the values change only with a deploy: fetch once, cache for the session. Two refusals split that contract: every JSON-bodied operation answers `422` when the request never became the type the handler asked for (a wrong-typed field, a missing required one), and that one is a plain-text deserializer diagnostic rather than the `{error}` envelope, so it is read by a human and not parsed by a client; `400` carries the usual `{error}` and means either non-JSON bytes or a well-typed value that broke a rule published here. Multipart upload routes have no JSON body and so answer `400`, never `422`. School-adjustable policy lives on `GET /settings`; what `/limits` carries for those knobs is the fixed range a manager may set them within. Its `rate` group is the exception to \"fixed\": those tiers are environment-tunable, so the endpoint serves the running server's live values (`0` = tier off). `GET /modules/catalog` is the same kind of contract for the product's shape: every sellable module, the package it is sold in, and the modules it structurally requires — unauthenticated and deploy-constant, since it is identical for every school. What one school actually bought is `GET /modules` (any logged-in user), the cheap way to hide a nest the school does not have instead of discovering it as a `403`. Those tiers are per client; a server whose client table is saturated by a flood meters otherwise-unknown callers against one shared budget instead, so an unfamiliar client can briefly see a `429` it did not itself earn — always with a `Retry-After`, never longer than the window"),
55- (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/2`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With **both** `AI_TLS_CERT` and `AI_TLS_KEY` unset the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup; setting just one of the two (a blank value counts as unset) fails the boot instead of quietly self-signing, since a bridge presenting a throwaway `localhost` leaf to services pinning the real one looks configured and answers `503` to every send. Every frame in either direction names the school it belongs to (`school`, the slug), so one fleet of services serves every school on the deployment and a read is answered out of that school's own database — an unknown slug is `unknown_school`, a suspended one `school_suspended`. Traffic also runs the other way on that same connection: a connected service opens streams of its own to **read this API back** (one `ApiRequest`/`ApiResponse` frame pair per stream, no HTTP session and no password of its own) — `GET` only, against a deny-by-default allowlist of read endpoints (identity, profiles, notes, course notes, homework, marks, attendance, pomodoro), optionally `on_behalf_of` a named user, whose account is re-read live per request so a stale id acts as the demoted or deleted user and never as who they were. Without that field the principal is the internal role `ai`, the lowest privilege here and not assignable to anyone — it appears in the `Role` schema as documentation only, no account can hold it, and a read that needs a role simply answers `403`. A connected service also pulls **file bytes** the same way, on its own stream: one `BlobRequest` naming a `course_note_file` id, one header frame, then exactly `size` raw bytes and FIN — no frame cap, because a PDF fits in no frame. That stream reaches course-note attachments and nothing else, behind the very guard `GET /course-notes/{id}/files/{file_id}` applies, and `on_behalf_of` is required in practice there since the `ai` role can view no course. Nothing on this HTTP surface changes: the allowlisted endpoints are the ones documented here, reached with the same guards. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). `GET /ai/capabilities` (authenticated) lists what connected services are serving right now — one entry per capability with its worker count and in-flight requests — and answers `200 {enabled: false, capabilities: []}` when the bridge is off: a discovery read showing *that* there is no AI fleet, not a dependency probe. See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"),
56- (name = "builder", description = "The vendor surface: one deployment, many schools. A **builder** is the operator who owns the deployment — not a user of any school, and holding no role in one. It logs in at `POST /builder/login` and gets a `session` cookie prefixed `builder.` instead of a school slug; that cookie works here and is `401` everywhere else, exactly as a school cookie is `401` here. `POST /schools` creates a school's database, schema and first admin in one call; the registry row reads `provisioning` until that schema is in place, so a boot cut short mid-create is finished by the next one instead of leaving a school that answers `500`; `PATCH /schools/{slug}` renames it or flips it between `active` and `suspended` (a suspension is immediate and total for that school's users — every request including login answers `403`, live session or not); `DELETE /schools/{slug}` destroys its data and its uploaded files for good. `POST /schools/{slug}/admin-password` is the lockout fix: it re-keys a named admin of that school and revokes every session that account held. `POST /schools/{slug}/enter` mints an ordinary school session for one of its admins (support access) — the only route here refused on a suspended school, so a suspension really does close every door into it. It is also where a school's **entitlements** are sold: `GET /schools/{slug}/modules` lists what it has and what is left, `POST`/`DELETE /schools/{slug}/modules/{module}` flips one (idempotently), and `PATCH /schools/{slug}/modules` re-sells the whole shelf in one atomic write — modules and packages, both directions, expanded into a single resulting set that is checked once, so a `409` names every broken dependency at once and nothing is written unless the request is accepted whole. A change lands on the school's very next request, live cookies included: a disabled module answers `403 {error, module}` on every route in its nest. The catalog itself (`GET /modules/catalog`) and a school user's own set (`GET /modules`) are on the `meta` tag."),
55+ (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/2`, address `AI_QUIC_ADDR`) and register the capabilities they serve; each request then rides its own QUIC bidirectional stream on that one connection. `GET /ai/certificate` publishes the bridge listener's certificate (PEM + SHA-256 fingerprint) so a service can pin it before dialling — public, because a server certificate is presented to every peer during the TLS handshake anyway, while the shared token that actually authenticates a service (`AI_SHARED_TOKEN`) is configured out of band. With **both** `AI_TLS_CERT` and `AI_TLS_KEY` unset the bridge self-signs afresh at each boot, so a service must re-fetch this on every reconnect, not only at startup; setting just one of the two (a blank value counts as unset) fails the boot instead of quietly self-signing, since a bridge presenting a throwaway `localhost` leaf to services pinning the real one looks configured and answers `503` to every send. Every frame in either direction names the school it belongs to (`school`, the school uuid), so one fleet of services serves every school on the deployment and a read is answered out of that school's own database — an unknown id is `unknown_school`, a suspended one `school_suspended`. Traffic also runs the other way on that same connection: a connected service opens streams of its own to **read this API back** (one `ApiRequest`/`ApiResponse` frame pair per stream, no HTTP session and no password of its own) — `GET` only, against a deny-by-default allowlist of read endpoints (identity, profiles, notes, course notes, homework, marks, attendance, pomodoro), optionally `on_behalf_of` a named user, whose account is re-read live per request so a stale id acts as the demoted or deleted user and never as who they were. Without that field the principal is the internal role `ai`, the lowest privilege here and not assignable to anyone — it appears in the `Role` schema as documentation only, no account can hold it, and a read that needs a role simply answers `403`. A connected service also pulls **file bytes** the same way, on its own stream: one `BlobRequest` naming a `course_note_file` id, one header frame, then exactly `size` raw bytes and FIN — no frame cap, because a PDF fits in no frame. That stream reaches course-note attachments and nothing else, behind the very guard `GET /course-notes/{id}/files/{file_id}` applies, and `on_behalf_of` is required in practice there since the `ai` role can view no course. Nothing on this HTTP surface changes: the allowlisted endpoints are the ones documented here, reached with the same guards. `404` when the bridge is disabled (`AI_QUIC_ADDR` unset). `GET /ai/capabilities` (authenticated) lists what connected services are serving right now — one entry per capability with its worker count and in-flight requests — and answers `200 {enabled: false, capabilities: []}` when the bridge is off: a discovery read showing *that* there is no AI fleet, not a dependency probe. See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"),
56+ (name = "builder", description = "The vendor surface: one deployment, many schools. A **builder** is the operator who owns the deployment — not a user of any school, and holding no role in one. It logs in at `POST /builder/login` and gets a `session` cookie prefixed `builder.` instead of a school uuid; that cookie works here and is `401` everywhere else, exactly as a school cookie is `401` here. `POST /schools` creates a school's database, schema and first admin in one call; the registry row reads `provisioning` until that schema is in place, so a boot cut short mid-create is finished by the next one instead of leaving a school that answers `500`; `PATCH /schools/{id}` renames it or flips it between `active` and `suspended` (a suspension is immediate and total for that school's users — every request including login answers `403`, live session or not); `DELETE /schools/{id}` destroys its data and its uploaded files for good. `POST /schools/{id}/admin-password` is the lockout fix: it re-keys a named admin of that school and revokes every session that account held. `POST /schools/{id}/enter` mints an ordinary school session for one of its admins (support access) — the only route here refused on a suspended school, so a suspension really does close every door into it. It is also where a school's **entitlements** are sold: `GET /schools/{id}/modules` lists what it has and what is left, `POST`/`DELETE /schools/{id}/modules/{module}` flips one (idempotently), and `PATCH /schools/{id}/modules` re-sells the whole shelf in one atomic write — modules and packages, both directions, expanded into a single resulting set that is checked once, so a `409` names every broken dependency at once and nothing is written unless the request is accepted whole. A change lands on the school's very next request, live cookies included: a disabled module answers `403 {error, module}` on every route in its nest. The catalog itself (`GET /modules/catalog`) and a school user's own set (`GET /modules`) are on the `meta` tag."),
5757 (name = "school", description = "The school the session cookie is bound to. `GET /school` returns `{id, name}` — the registry uuid and the display name — to every authenticated role, parent included. It is not login and not the vendor registry: a builder cookie is `401` here, exactly as a school cookie is `401` on `/schools`."),
58- (name = "auth", description = "Registration, login, session lifecycle, and school selection. The account is a **person**: one global username + password in the control plane, able to hold memberships in many schools — the school is picked after login, never named by it. `POST /auth/register` is still aimed at a school (`{school, username, password}`): it creates the person plus the school's `app_user` (a `student`), or attaches an existing person to one more school when the password matches. It answers `201` with the byte-identical `{username, role}` body in every outcome — created, name already taken, or taken under a different password — and deliberately **no `id`**, since a distinguishable reply would let anyone unauthenticated enumerate accounts (an anti-enumeration measure; log in to learn who you are). `POST /auth/login` takes `{username, password}`: with exactly one active membership it enters that school directly — a `UserResponse` and a `session` cookie valued `<slug>.<token>` (see the `builder` tag for cookie prefixing); with two or more it answers `{username, schools: [{slug, name}]}` and a `person.<token>` cookie, which `POST /auth/school` (`{school}`) exchanges for the chosen school's cookie and a `UserResponse` — the school must be one of the caller's memberships (`401` otherwise) and not suspended (`403`). Suspended schools never appear in the choice list, and a person whose every membership is suspended is `403` like the school's own doors. Login failures — unknown username, wrong password, no membership left to enter — are all the same `401`, and the unknown-username branch burns the same argon2 work a wrong-password check costs, so timing confirms nothing. `POST /auth/logout` revokes whichever session the cookie names — school, person, or builder — and stays idempotent `204` without one"),
58+ (name = "auth", description = "Registration, login, session lifecycle, and school selection. The account is a **person**: one global username + password in the control plane, able to hold memberships in many schools — the school is picked after login, never named by it. `GET /auth/schools` is public (no session) and returns the active schools as `[{id, name}]`, sorted by name — the list register picks from. `POST /auth/register` is still aimed at a school (`{school, username, password}`, `school` one of those ids): it creates the person plus the school's `app_user` (a `student`), or attaches an existing person to one more school when the password matches. It answers `201` with the byte-identical `{username, role}` body in every outcome — created, name already taken, or taken under a different password — and deliberately **no `id`**, since a distinguishable reply would let anyone unauthenticated enumerate accounts (an anti-enumeration measure; log in to learn who you are). `POST /auth/login` takes `{username, password}`: with exactly one active membership it enters that school directly — a `UserResponse` and a `session` cookie valued `<uuid>.<token>` (see the `builder` tag for cookie prefixing); with two or more it answers `{username, schools: [{id, name}]}` and a `person.<token>` cookie, which `POST /auth/school` (`{school}`) exchanges for the chosen school's cookie and a `UserResponse` — the school must be one of the caller's memberships (`401` otherwise) and not suspended (`403`). Suspended schools never appear in the choice list, and a person whose every membership is suspended is `403` like the school's own doors. Login failures — unknown username, wrong password, no membership left to enter — are all the same `401`, and the unknown-username branch burns the same argon2 work a wrong-password check costs, so timing confirms nothing. `POST /auth/logout` revokes whichever session the cookie names — school, person, or builder — and stays idempotent `204` without one"),
5959 (name = "chatbot", description = "The AI chatbot, relayed through the QUIC bridge to an out-of-process AI service. Every authenticated role may chat (parents included) and every thread is private to its owner — nobody, not even an admin, reads someone else's. A user keeps up to the school's `max_chatbot_threads` threads (409 at the cap, delete one first) and sends at most `RATE_LIMIT_CHATBOT_PER_MINUTE` messages a minute (default 20, `0` disables the tier; 429 with `Retry-After`). A thread can be renamed — or its name cleared — with `PATCH /chatbot/threads/{id}` (`{title}`, `null` to clear); nothing names a thread automatically. Sending is asynchronous: `POST /chatbot/threads/{id}/messages` writes the turn plus an empty `pending` assistant row and answers `202 {message_id, status}` immediately, because an inference outlives a normal request. The pending row is what a reload comes back to, not a queued job: the bridge round trip runs in an in-process task the `202` leaves behind, so a restart mid-inference strands that turn — it settles `failed`/`interrupted` (a reader projects a `pending` row older than 300 seconds as failed, and the boot sweep stamps that verdict durably) rather than being answered by anyone. Accepted, because the backend is a single process with stop-the-world deploys: there is no peer that could have taken the turn over. Sending is also serialized against the thread's own deletion — both rows ride a transaction that writes the thread row, so a turn accepted while `DELETE /chatbot/threads/{id}` is committing is refused with a `404` instead of surviving as a message under a thread that is gone. The answer is then read either by polling `GET .../messages/{mid}` or over the Server-Sent-Events stream at `.../messages/{mid}/stream` (`delta` chunks, then one `done` or `error`) — both read the same row, so they never disagree, and a stream opened after the answer landed still replays it. An answer the service made longer than `max_chatbot_message_len` is clipped rather than discarded, and the stored turn is flagged `truncated: true` — the polling read and the SSE `done` payload always agree on it. A turn always settles: `complete` with the text, or `failed` with a short code (`unavailable`, `busy`, `timed_out`, `transport`, `protocol`, `bad_reply`, `empty_reply`, `interrupted`, or the service's own). With no `chat.reply` service connected anywhere in the deployment, sending answers `503` and writes nothing"),
6060 (name = "rag", description = "The course-note RAG: its own nest, threads and tables, relayed through the same QUIC bridge as the chatbot — RAG is not folded into the chatbot's storage. Every authenticated role may ask (parents included) and every thread is private to its owner. Every question is scoped server-side to `(sınıf, ders)` pairs derived by the server — a manager or an admin gets every class-course pair in the school, everyone else their own memberships (a linked parent's children, and the school-wide club/etüt memberships they hold, which scope the subject across grades, `sinif: null`) — never from the body, so a caller cannot widen their own retrieval; a scope past `MAX_RAG_SCOPE_PAIRS` pairs is refused (400) rather than narrowed. A RAG thread draws on the school's existing AI thread seats (`max_chatbot_threads`, the same seat count the chatbot nest uses, one pool per user), its prompts and answers are bounded by `max_chatbot_message_len`, and its per-minute tier is its own: `RATE_LIMIT_RAG_PER_MINUTE` (default 6, `0` disables the tier; 429 with `Retry-After`). Sending is asynchronous exactly as the chatbot's is: `POST /rag/threads/{id}/messages` writes the turn plus a `pending` assistant row and answers `202`, then poll `GET /rag/threads/{id}/messages/{mid}` or open its `/stream` (SSE `delta`s then `done`/`error`). `503` when no AI service offers `rag.chat`, with nothing written. An answer may abstain — `abstained: true` with a `reason` (`guard_*`, `insufficient_data`, `model_abstained`) is a complete, successful turn, not an error — and carries its `citations`, up to `MAX_RAG_CITATIONS` per answer and at most `MAX_RAG_CITATION_PAGES` pages each (a service reply past either cap fails the turn whole). Each citation's corpus `doc_id` is resolved to the course-note file that owns it (`file`, `null` when no file the asker may view claims that document) beside the pages and retrieval span ids behind it. Two **study** doors are one-shot and synchronous rather than threaded: `POST /rag/summarize` returns a summary of one page/span range and `POST /rag/questions` returns a set of practice questions (plus their range-bounded answers) over one — the artifact is the answer, so nothing is stored and there is no thread or poll. Their body names only a *target within* the asker's own derived pairs (the body's `sinif` plus `ders`): a pair the caller does not hold is `403`, and omitting `sinif` for a ders taught at more than one grade is `400` — the backend never picks a corpus for the caller. Both answer `503` when no AI service offers `rag.summarize`/`rag.questions`, and an `abstained: true` reply with a `reason` is a complete `200`, exactly as on a chat turn. Each waits on its dispatch under a 25 s deadline, deliberately inside the middleware's own 30 s envelope — a dropped handler would answer with prose written for a request that may have written something."),
6161 (name = "insights", description = "ZEKA's computed student insights. The `hezarfen_zeka` AI service dials in over the same QUIC bridge as the chatbot, but it does **not** touch a school database: the backend owns every statement against the `zeka_*` tables, and the service calls the backend by name (`insight.*` capabilities on a client-initiated stream — see `src/ai/insight.rs`) to have its computed rows written and read back. So this nest reads what the service computed and asks it to compute on demand, and its write doors are the same operations the bridge serves: `POST /insights/summaries`, `/recommendations`, `/segments`, `/profiles` and `/runs` store one batch each (manager+, one call one transaction, rows about students school-wide), `GET /insights/pending` is the students the freshest run left pending, and `POST /insights/sweep` / `POST /insights/purge` are retention and graduation housekeeping — all scoped to the caller's own school by the nest's extractors, and none of them takes a school, a database or a query in its body. `GET /insights/schools` is the exception and is not this nest's usual principal: the active-school directory names every customer, so it is mounted on the **builder** principal outside the school gate (a school session answers `401`), exactly like the vendor surface's `GET /schools`. `GET /insights/me` is the caller's own view: a student's summary, their own recommendation cards and their segment profile — and **never** the attention list about themselves, which is a teacher's tool and is not returned to a student or to a linked parent. `GET /insights/students/{id}` is the observer's view of one student — teacher+ narrowed to the students they actually reach through a shared class×course instance, or a parent holding a live link — adding the attention list and the caller's own cards about that student; anyone else reads `404`, never `403`. `POST /insights/students/{id}` and `POST /insights/refresh` (manager+) queue a recompute through the bridge and answer `202` — the compute lands in the service's own rows, so a client polls the read routes; `GET /insights/runs` (manager+) is the run ledger, newest first. Both dispatch doors answer `503` when no service offers the capability, and nothing is queued. Expired and dismissed cards are filtered out of every card read, segment rows below 30 answers (`confidence: none`) are filtered out of every profile read, and a card's `about` is never returned to a student caller."),
@@ -444,7 +444,7 @@ fn record_response<B>(res: &Response<B>, _latency: std::time::Duration, span: &t
444444 }
445445 }
446446
447-/// Count the request in and out and record its duration. The school slug is
447+/// Count the request in and out and record its duration. The school uuid is
448448 /// the only caller-derived attribute, and it is only known after the handler's
449449 /// extractor filled the slot (see [`SchoolSlot`]).
450450 async fn measure(metrics: crate::telemetry::Metrics, mut req: Request, next: Next) -> Response {
src/service/person.rsmodified+5 -5
@@ -9,7 +9,7 @@ use crate::db::person;
99 use crate::domain::person::{Membership, Person, PersonId, PersonSession};
1010 use crate::domain::user::{PasswordHash, Username};
1111 use crate::error::AppError;
12-use crate::tenant::Slug;
12+use crate::tenant::SchoolId;
1313
1414 /// Create the person, or hand back the one already standing under
1515 /// `username`. The incoming hash is stored only on the create path — an
@@ -42,9 +42,9 @@ pub async fn create_or_load(
4242 pub async fn link_school(
4343 control: &Database,
4444 person: &PersonId,
45- slug: &Slug,
45+ id: &SchoolId,
4646 ) -> Result<(), AppError> {
47- person::add_membership(control, person, slug).await
47+ person::add_membership(control, person, id).await
4848 }
4949
5050 pub async fn read(control: &Database, id: &PersonId) -> Result<Option<Person>, AppError> {
@@ -70,9 +70,9 @@ pub async fn memberships(
7070 pub async fn membership_of(
7171 control: &Database,
7272 person: &PersonId,
73- slug: &Slug,
73+ id: &SchoolId,
7474 ) -> Result<Option<Membership>, AppError> {
75- person::membership_of(control, person, slug).await
75+ person::membership_of(control, person, id).await
7676 }
7777
7878 pub async fn create_session(
src/service/user.rsmodified+4 -4
@@ -13,7 +13,7 @@ use crate::domain::profile::{Bio, BirthDate, DisplayName, Email, PersonName, Pho
1313 use crate::domain::role::Role;
1414 use crate::domain::user::{Password, StudentNumber, User, UserId, Username};
1515 use crate::error::AppError;
16-use crate::tenant::{Slug, Tenants};
16+use crate::tenant::{SchoolId, Tenants};
1717
1818 /// Idempotent startup seed: guarantee an admin account with this username.
1919 /// Missing → created directly with [`Role::Admin`]. Already an admin →
@@ -23,11 +23,11 @@ use crate::tenant::{Slug, Tenants};
2323 /// be a privilege escalation, so that conflict is resolved out-of-band.
2424 pub async fn ensure_admin(
2525 tenants: &Tenants,
26- slug: &Slug,
26+ id: &SchoolId,
2727 username: Username,
2828 password: Password,
2929 ) -> Result<(), AppError> {
30- let db = tenants.get(slug).await?;
30+ let db = tenants.get(id).await?;
3131 // The person half runs first, so the school row can carry the person id
3232 // it is the join key to. Login reads the control-plane credential, so the
3333 // seeded admin needs their `person` row and the membership too. Both
@@ -40,7 +40,7 @@ pub async fn ensure_admin(
4040 let person =
4141 crate::service::person::create_or_load(tenants.control(), username.clone(), password_hash)
4242 .await?;
43- crate::service::person::link_school(tenants.control(), person.get_id(), slug).await?;
43+ crate::service::person::link_school(tenants.control(), person.get_id(), id).await?;
4444 match user::find_by_username(&db, username.as_str()).await? {
4545 Some(user) if user.role == Role::Admin => {}
4646 Some(_) => {
src/state.rsmodified+28 -28
@@ -7,7 +7,7 @@ use tokio::sync::broadcast;
77 use crate::ai::AiBridge;
88 use crate::database::Database;
99 use crate::rate_limit::{RateLimitConfig, UserRateLimiter};
10-use crate::tenant::{Slug, Tenants};
10+use crate::tenant::{SchoolId, Tenants};
1111
1212 /// Shared application state handed to every handler.
1313 #[derive(Clone)]
@@ -55,16 +55,16 @@ pub struct AppState {
5555 pub metrics: crate::telemetry::Metrics,
5656 }
5757
58-/// The map key for `key` inside `slug`'s school. One process serves every
58+/// The map key for `key` inside `id`'s school. One process serves every
5959 /// school, but record keys are only unique *within* a database, so an
6060 /// unscoped key would put two schools' identical attempts (or boards) in the
6161 /// same room. The maps below are the only users of this, and their methods
62-/// take a [`Slug`] rather than a ready-made key — there is no way to reach one
63-/// with an unscoped string. The per-user chatbot limiter keys through here
64-/// too, for the same reason. A slug cannot contain `:`, so the join is
65-/// unambiguous.
66-pub fn scoped_key(slug: &Slug, key: &str) -> String {
67- format!("{slug}:{key}")
62+/// take a [`SchoolId`] rather than a ready-made key — there is no way to reach
63+/// one with an unscoped string. The per-user chatbot limiter keys through here
64+/// too, for the same reason. A hyphenated uuid cannot contain `:`, so the join
65+/// is unambiguous.
66+pub fn scoped_key(id: &SchoolId, key: &str) -> String {
67+ format!("{id}:{key}")
6868 }
6969
7070 /// How many exam-room sockets each attempt has open right now, keyed by the
@@ -82,15 +82,15 @@ pub struct ExamPresence(Arc<Mutex<HashMap<String, usize>>>);
8282
8383 impl ExamPresence {
8484 /// Count one socket into `attempt`'s room.
85- pub fn enter(&self, slug: &Slug, attempt: &str) {
85+ pub fn enter(&self, id: &SchoolId, attempt: &str) {
8686 let mut rooms = self.0.lock().expect("exam presence lock");
87- *rooms.entry(scoped_key(slug, attempt)).or_insert(0) += 1;
87+ *rooms.entry(scoped_key(id, attempt)).or_insert(0) += 1;
8888 }
8989
9090 /// Count one socket out of `attempt`'s room; `true` when it was the last
9191 /// one — the student has actually left.
92- pub fn leave(&self, slug: &Slug, attempt: &str) -> bool {
93- let attempt = &scoped_key(slug, attempt);
92+ pub fn leave(&self, id: &SchoolId, attempt: &str) -> bool {
93+ let attempt = &scoped_key(id, attempt);
9494 let mut rooms = self.0.lock().expect("exam presence lock");
9595 match rooms.get_mut(attempt) {
9696 Some(count) if *count > 1 => {
@@ -130,10 +130,10 @@ pub struct BoardHub(Arc<Mutex<BoardRooms>>);
130130 impl BoardHub {
131131 /// Count one socket into `board` and hand back its stream of other
132132 /// people's frames, creating the channel on the first join.
133- pub fn subscribe(&self, slug: &Slug, board: &str) -> broadcast::Receiver<String> {
133+ pub fn subscribe(&self, id: &SchoolId, board: &str) -> broadcast::Receiver<String> {
134134 let mut boards = self.0.lock().expect("board hub lock");
135135 let room = boards
136- .entry(scoped_key(slug, board))
136+ .entry(scoped_key(id, board))
137137 .or_insert_with(|| (broadcast::channel(crate::constant::BOARD_HUB_CAPACITY).0, 0));
138138 room.1 += 1;
139139 room.0.subscribe()
@@ -141,11 +141,11 @@ impl BoardHub {
141141
142142 /// Push `frame` to every socket currently subscribed to `board`. A send
143143 /// with no receivers left is the normal empty-room case, not a failure.
144- pub fn publish(&self, slug: &Slug, board: &str, frame: String) {
144+ pub fn publish(&self, id: &SchoolId, board: &str, frame: String) {
145145 let sender = {
146146 let boards = self.0.lock().expect("board hub lock");
147147 boards
148- .get(&scoped_key(slug, board))
148+ .get(&scoped_key(id, board))
149149 .map(|room| room.0.clone())
150150 };
151151 if let Some(sender) = sender {
@@ -154,8 +154,8 @@ impl BoardHub {
154154 }
155155
156156 /// Count one socket out of `board`; the last one out drops the channel.
157- pub fn leave(&self, slug: &Slug, board: &str) {
158- let board = &scoped_key(slug, board);
157+ pub fn leave(&self, id: &SchoolId, board: &str) {
158+ let board = &scoped_key(id, board);
159159 let mut boards = self.0.lock().expect("board hub lock");
160160 match boards.get_mut(board) {
161161 Some(room) if room.1 > 1 => room.1 -= 1,
@@ -172,13 +172,13 @@ impl BoardHub {
172172 mod tests {
173173 use super::*;
174174
175- fn slug(value: &str) -> Slug {
176- Slug::try_new(value).expect(value)
175+ fn school(value: &str) -> SchoolId {
176+ SchoolId::try_parse(value).expect(value)
177177 }
178178
179179 #[tokio::test]
180180 async fn every_subscriber_gets_the_stroke_and_the_room_is_reclaimed() {
181- let a = slug("alpha");
181+ let a = school("019732e3-7b00-7000-8000-00000000a11a");
182182 let hub = BoardHub::default();
183183 let mut alice = hub.subscribe(&a, "board-a");
184184 let mut bob = hub.subscribe(&a, "board-a");
@@ -188,11 +188,11 @@ mod tests {
188188
189189 // Boards are independent, and publishing into an empty one is a no-op.
190190 hub.publish(&a, "board-b", "nobody home".to_string());
191- assert!(!hub.0.lock().unwrap().contains_key("alpha:board-b"));
191+ assert!(!hub.0.lock().unwrap().contains_key(&scoped_key(&a, "board-b")));
192192
193193 hub.leave(&a, "board-a");
194194 assert!(
195- hub.0.lock().unwrap().contains_key("alpha:board-a"),
195+ hub.0.lock().unwrap().contains_key(&scoped_key(&a, "board-a")),
196196 "one socket of two out keeps the room"
197197 );
198198 hub.leave(&a, "board-a");
@@ -206,7 +206,7 @@ mod tests {
206206 /// same board key. One process serves both — nothing may cross.
207207 #[tokio::test]
208208 async fn a_stroke_never_crosses_into_another_school() {
209- let (a, b) = (slug("alpha"), slug("beta"));
209+ let (a, b) = (school("019732e3-7b00-7000-8000-00000000a11a"), school("019732e3-7b00-7000-8000-00000000be7a"));
210210 let hub = BoardHub::default();
211211 let mut in_a = hub.subscribe(&a, "board-1");
212212 let mut in_b = hub.subscribe(&b, "board-1");
@@ -225,13 +225,13 @@ mod tests {
225225 // beta's room standing.
226226 hub.leave(&a, "board-1");
227227 let boards = hub.0.lock().unwrap();
228- assert!(!boards.contains_key("alpha:board-1"));
229- assert!(boards.contains_key("beta:board-1"));
228+ assert!(!boards.contains_key(&scoped_key(&a, "board-1")));
229+ assert!(boards.contains_key(&scoped_key(&b, "board-1")));
230230 }
231231
232232 #[tokio::test]
233233 async fn only_the_last_socket_out_is_a_real_exit() {
234- let a = slug("alpha");
234+ let a = school("019732e3-7b00-7000-8000-00000000a11a");
235235 let presence = ExamPresence::default();
236236 presence.enter(&a, "attempt-a");
237237 presence.enter(&a, "attempt-a");
@@ -254,7 +254,7 @@ mod tests {
254254 /// its walk-out would go unstamped.
255255 #[tokio::test]
256256 async fn presence_counts_are_per_school() {
257- let (a, b) = (slug("alpha"), slug("beta"));
257+ let (a, b) = (school("019732e3-7b00-7000-8000-00000000a11a"), school("019732e3-7b00-7000-8000-00000000be7a"));
258258 let presence = ExamPresence::default();
259259 presence.enter(&a, "attempt-1");
260260 presence.enter(&b, "attempt-1");
src/telemetry.rsmodified+6 -6
@@ -6,7 +6,7 @@
66 //! identity, no client address, no URL path (which holds record ids), no
77 //! request or response bodies, and no headers or cookies. What may leave: the
88 //! route *template* (`/notes/{id}`), the HTTP method, the status code, the
9-//! school slug, a random per-request id, and the id of a non-user resource
9+//! school uuid, a random per-request id, and the id of a non-user resource
1010 //! (an exam room, a board) when an event is about that resource — never a
1111 //! user, session or attempt id, which name a person. Every attribute or event
1212 //! field added anywhere in this crate must fit that list — see the guard test
@@ -255,7 +255,7 @@ impl Metrics {
255255 );
256256 }
257257
258- /// Count the request out and record how long it took. `school` is the slug
258+ /// Count the request out and record how long it took. `school` is the uuid
259259 /// only — never a user, never a path.
260260 pub fn request_finished(
261261 &self,
@@ -291,11 +291,11 @@ impl Default for Metrics {
291291 /// A slot on the request for the school it turned out to belong to.
292292 ///
293293 /// The metrics middleware runs before anything knows which school a caller is
294-/// in — the slug only becomes known when
294+/// in — the uuid only becomes known when
295295 /// [`crate::web::tenant_state::resolve_tenant`] reads the session cookie, deep
296296 /// inside the handler, where the request has already been moved. So the
297297 /// middleware puts an empty slot in the request's extensions on the way in and
298-/// reads it on the way out; `resolve_tenant` fills it in between. The slug is
298+/// reads it on the way out; `resolve_tenant` fills it in between. The uuid is
299299 /// the only thing that ever goes in here.
300300 #[derive(Clone, Default)]
301301 pub struct SchoolSlot(Arc<OnceLock<String>>);
@@ -303,8 +303,8 @@ pub struct SchoolSlot(Arc<OnceLock<String>>);
303303 impl SchoolSlot {
304304 /// Name the school for this request. Later calls are ignored — a request
305305 /// belongs to exactly one school.
306- pub fn set(&self, slug: &str) {
307- let _ = self.0.set(slug.to_string());
306+ pub fn set(&self, school: &str) {
307+ let _ = self.0.set(school.to_string());
308308 }
309309
310310 pub fn get(&self) -> Option<&str> {
src/tenant.rsmodified+137 -162
@@ -22,12 +22,11 @@ use std::sync::{Arc, RwLock};
2222 use serde::Serialize;
2323 use sqlx::postgres::PgConnectOptions;
2424
25-use crate::constant::{MAX_SLUG_LEN, MIN_SLUG_LEN};
2625 use uuid::Uuid;
2726
2827 use crate::database::{
2928 Database, applied_versions, create_database_sql, ensure_database, migrate_school,
30- pending_school_migrations, school_pool, unique_violation,
29+ pending_school_migrations, school_pool,
3130 };
3231 use crate::domain::monotonic_id::next_uuid;
3332 use crate::domain::timestamp::Timestamp;
@@ -35,77 +34,22 @@ use crate::error::{AppError, ValidationError};
3534 use crate::module::ModuleSet;
3635 use crate::telemetry::Metrics;
3736
38-/// The school every in-memory test bootstrap got and every test suite still
39-/// names. Not special to the code — just the one name the test harness and
40-/// the suites agree on.
41-pub const DEMO_SLUG: &str = "demo";
42-
43-/// Slugs that name something other than a school: the builder cookie prefix,
44-/// the control database itself, and the person cookie prefix. Refused at
45-/// construction, so neither a login nor a `CREATE DATABASE` can ever be
46-/// aimed at them.
47-pub const RESERVED_SLUGS: [&str; 3] = ["builder", "control", "person"];
48-
49-/// A school's public label: the cookie prefix, the URL paths and the files
50-/// subdirectory. The character set is deliberately the intersection of what
51-/// all three accept — lowercase alphanumerics and `-`, starting with an
52-/// alphanumeric. It is no longer the school's identity: the registry row's
53-/// uuid is (see [`SchoolId`]), which is why a label rename can no longer
54-/// orphan anything structural.
55-#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, sqlx::Type)]
56-#[serde(transparent)]
57-#[sqlx(transparent)]
58-pub struct Slug(String);
59-
60-/// `^[a-z0-9][a-z0-9-]{1,31}$`, spelled out. `regex` is a dev-dependency here
61-/// and this is five lines of `char` predicates — a runtime dependency would
62-/// cost more than it saves.
63-fn is_slug(value: &str) -> bool {
64- let ok_len = (MIN_SLUG_LEN..=MAX_SLUG_LEN).contains(&value.len());
65- let ok_first = value
66- .chars()
67- .next()
68- .is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit());
69- let ok_rest = value
70- .chars()
71- .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
72- ok_len && ok_first && ok_rest
73-}
37+/// The school [`crate::database::init_test_tenants`] registers. Suites name
38+/// it by this constant — the hyphenated uuid the cookie prefix and every
39+/// frame carry — rather than a second copy of the literal.
40+#[doc(hidden)]
41+pub const DEMO_SCHOOL_ID: &str = "019732e3-7b00-7000-8000-00000000dead";
7442
75-impl Slug {
76- pub fn try_new(value: &str) -> Result<Self, ValidationError> {
77- if !is_slug(value) {
78- return Err(ValidationError::Invalid {
79- field: "school",
80- reason: "must be 2-32 characters of a-z, 0-9 and -, starting with a letter or digit",
81- });
82- }
83- if RESERVED_SLUGS.contains(&value) {
84- return Err(ValidationError::Invalid {
85- field: "school",
86- reason: "this name is reserved",
87- });
88- }
89- Ok(Self(value.to_string()))
90- }
91-
92- pub fn as_str(&self) -> &str {
93- &self.0
94- }
95-}
96-
97-impl std::fmt::Display for Slug {
98- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
99- f.write_str(&self.0)
100- }
101-}
43+/// The second school the tenancy suites create beside [`DEMO_SCHOOL_ID`].
44+#[doc(hidden)]
45+pub const BETA_SCHOOL_ID: &str = "019732e3-7b00-7000-8000-00000000beef";
10246
10347 /// A school database's name: `{control_db}_school_{uuid hex}` — the uuid's
10448 /// lowercase hex without dashes (the contract's example:
10549 /// `019732e3-7b00-7000-8000-00000000dead` →
10650 /// `…_school_019732e37b007000800000000000dead`). Fixed-width and injective:
107-/// two uuids never share a database, and the slug appears nowhere, so a slug
108-/// rename can never orphan one. The server's 63-byte identifier cap can clip
51+/// two uuids never share a database, and no label appears in it, so a rename
52+/// can never orphan one. The server's 63-byte identifier cap can clip
10953 /// the name's tail on deployments with a long control-database name — uuid
11054 /// v7's random tail still separates schools far past any realistic registry
11155 /// size, and creator and dialler truncate identically.
@@ -157,10 +101,12 @@ impl SchoolStatus {
157101 }
158102 }
159103
160-/// A school's identity inside the control plane: the registry row's uuid
161-/// primary key, app-minted uuid v7. The database name and every structural
162-/// reference (person_school) mint from it; the slug — the public label — never.
163-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
104+/// A school's identity: the registry row's uuid primary key, app-minted
105+/// uuid v7. The cookie prefix, the builder path, the blob directory and the
106+/// hab/2 frame `school` value are this id's hyphenated form — nothing else
107+/// names a school.
108+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, sqlx::Type)]
109+#[sqlx(transparent)]
164110 pub struct SchoolId(Uuid);
165111
166112 impl SchoolId {
@@ -179,12 +125,61 @@ impl SchoolId {
179125 pub fn uuid(self) -> Uuid {
180126 self.0
181127 }
128+
129+ /// The canonical wire string: lowercase hyphenated uuid, the same form
130+ /// `GET /school` publishes. 36 characters, dashes included.
131+ pub fn as_str(self) -> String {
132+ self.0.as_hyphenated().to_string()
133+ }
134+
135+ /// Parse the wire form. Hyphenated only — the simple, URN and braced
136+ /// spellings `Uuid::try_parse` would accept are not a school id. A frame
137+ /// or cookie prefix that fails this is not a school, not a shape error.
138+ pub fn try_parse(value: &str) -> Result<Self, ValidationError> {
139+ if !is_hyphenated_uuid(value) {
140+ return Err(ValidationError::Invalid {
141+ field: "school",
142+ reason: "must be a hyphenated uuid",
143+ });
144+ }
145+ Uuid::try_parse(value)
146+ .map(Self)
147+ .map_err(|_| ValidationError::Invalid {
148+ field: "school",
149+ reason: "must be a hyphenated uuid",
150+ })
151+ }
152+}
153+
154+/// `8-4-4-4-12` hex with dashes. Case is accepted; [`SchoolId::as_str`]
155+/// always emits lowercase.
156+fn is_hyphenated_uuid(value: &str) -> bool {
157+ let b = value.as_bytes();
158+ if b.len() != 36 {
159+ return false;
160+ }
161+ for (i, c) in b.iter().enumerate() {
162+ let dash = matches!(i, 8 | 13 | 18 | 23);
163+ if dash {
164+ if *c != b'-' {
165+ return false;
166+ }
167+ } else if !c.is_ascii_hexdigit() {
168+ return false;
169+ }
170+ }
171+ true
172+}
173+
174+impl std::fmt::Display for SchoolId {
175+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
176+ f.write_str(&self.as_str())
177+ }
182178 }
183179
184180 #[derive(Debug, Clone, sqlx::FromRow)]
185181 pub struct School {
186182 id: Uuid,
187- slug: Slug,
188183 name: String,
189184 status: SchoolStatus,
190185 created_at: Timestamp,
@@ -198,16 +193,12 @@ pub struct School {
198193 }
199194
200195 impl School {
201- /// The row's uuid — the identity the database name and every structural
202- /// reference (person_school) mint from. The slug is not it.
196+ /// The row's uuid — the identity the database name, the cookie prefix
197+ /// and every structural reference mint from.
203198 pub fn get_id(&self) -> SchoolId {
204199 SchoolId(self.id)
205200 }
206201
207- pub fn slug(&self) -> &Slug {
208- &self.slug
209- }
210-
211202 pub fn name(&self) -> &str {
212203 &self.name
213204 }
@@ -230,22 +221,22 @@ impl School {
230221 Ok(module) => set.insert(module),
231222 Err(_) => tracing::warn!(
232223 "school {} has an unknown module `{name}` — ignoring it",
233- self.slug
224+ self.id
234225 ),
235226 }
236227 }
237228 set
238229 }
239230
240- pub async fn read(slug: &Slug, control: &Database) -> Result<Option<School>, AppError> {
231+ pub async fn read(id: &SchoolId, control: &Database) -> Result<Option<School>, AppError> {
241232 sqlx::query_as::<_, School>(
242- "SELECT s.id, s.slug, s.name, s.status, s.created_at,
233+ "SELECT s.id, s.name, s.status, s.created_at,
243234 COALESCE(array_agg(sm.module) FILTER (WHERE sm.module IS NOT NULL), '{}') AS modules
244235 FROM school s LEFT JOIN school_module sm ON sm.school = s.id
245- WHERE s.slug = $1
236+ WHERE s.id = $1
246237 GROUP BY s.id",
247238 )
248- .bind(slug.as_str())
239+ .bind(id.uuid())
249240 .fetch_optional(control)
250241 .await
251242 .map_err(Into::into)
@@ -260,11 +251,11 @@ impl School {
260251 control: &Database,
261252 ) -> Result<(Vec<School>, i64), AppError> {
262253 let rows = sqlx::query_as::<_, School>(
263- "SELECT s.id, s.slug, s.name, s.status, s.created_at,
254+ "SELECT s.id, s.name, s.status, s.created_at,
264255 COALESCE(array_agg(sm.module) FILTER (WHERE sm.module IS NOT NULL), '{}') AS modules
265256 FROM school s LEFT JOIN school_module sm ON sm.school = s.id
266257 GROUP BY s.id
267- ORDER BY s.created_at DESC, s.slug DESC
258+ ORDER BY s.created_at DESC, s.id DESC
268259 LIMIT $1 OFFSET $2",
269260 )
270261 .bind(limit)
@@ -277,10 +268,8 @@ impl School {
277268 Ok((rows, total))
278269 }
279270
280- /// Rename a school and/or flip its status — its display `name`, not its
281- /// slug, which is immutable in this cut (it is the cookie prefix and the
282- /// files subdirectory), though it no longer names the database: the uuid
283- /// does.
271+ /// Rename a school and/or flip its status. The id is the identity and
272+ /// is not a field a patch can move.
284273 ///
285274 /// Both fields land in **one** statement, so a patch that carries both can
286275 /// never leave half of itself behind, and an omitted field is kept by
@@ -288,7 +277,7 @@ impl School {
288277 /// read, so a concurrent patch of the other field cannot be reverted
289278 /// either.
290279 pub async fn update(
291- slug: &Slug,
280+ id: &SchoolId,
292281 name: Option<&str>,
293282 status: Option<SchoolStatus>,
294283 control: &Database,
@@ -297,18 +286,18 @@ impl School {
297286 "WITH updated AS (
298287 UPDATE school
299288 SET name = COALESCE($1, name), status = COALESCE($2, status)
300- WHERE slug = $3
301- RETURNING id, slug, name, status, created_at
289+ WHERE id = $3
290+ RETURNING id, name, status, created_at
302291 )
303- SELECT u.id, u.slug, u.name, u.status, u.created_at,
292+ SELECT u.id, u.name, u.status, u.created_at,
304293 COALESCE(array_agg(sm.module) FILTER (WHERE sm.module IS NOT NULL), '{}') AS modules
305294 FROM updated u
306295 LEFT JOIN school_module sm ON sm.school = u.id
307- GROUP BY u.id, u.slug, u.name, u.status, u.created_at",
296+ GROUP BY u.id, u.name, u.status, u.created_at",
308297 )
309298 .bind(name)
310299 .bind(status)
311- .bind(slug.as_str())
300+ .bind(id.uuid())
312301 .fetch_optional(control)
313302 .await?
314303 .ok_or(AppError::NotFound)
@@ -320,8 +309,8 @@ impl School {
320309 pub struct Tenants {
321310 control: Database,
322311 /// Live school pools, keyed by the school's uuid hex (no dashes — the
323- /// same form [`school_db_name`] spells). The slug never keys it: a pool
324- /// belongs to a school's identity, not to its current label.
312+ /// same form [`school_db_name`] spells). The label never keys it: a pool
313+ /// belongs to a school's identity, not to its display name.
325314 cache: Arc<RwLock<HashMap<String, Database>>>,
326315 /// Dial options for the Postgres server the control pool came from — a
327316 /// school pool is the same dial with only the database swapped.
@@ -342,7 +331,7 @@ pub struct Tenants {
342331 /// [`crate::web::CurrentUser`], which is most of them) reads the registry once.
343332 #[derive(Clone)]
344333 pub struct ResolvedTenant {
345- pub slug: Slug,
334+ pub id: SchoolId,
346335 pub db: Database,
347336 pub modules: ModuleSet,
348337 }
@@ -409,15 +398,15 @@ impl Tenants {
409398 /// extra control-db round trip per request; cache the row with a short TTL
410399 /// if it ever shows up in a profile — the eviction in [`Tenants::set_status`]
411400 /// is already there to make a cached decision safe.
412- pub async fn get(&self, slug: &Slug) -> Result<Database, AppError> {
413- Ok(self.resolve(slug).await?.db)
401+ pub async fn get(&self, id: &SchoolId) -> Result<Database, AppError> {
402+ Ok(self.resolve(id).await?.db)
414403 }
415404
416405 /// [`Tenants::get`] plus what that one registry read already knew: the
417406 /// school's module entitlements. Same verdicts, same single read — a
418407 /// caller that needs both must never pay for two.
419- pub async fn resolve(&self, slug: &Slug) -> Result<ResolvedTenant, AppError> {
420- match School::read(slug, &self.control).await? {
408+ pub async fn resolve(&self, id: &SchoolId) -> Result<ResolvedTenant, AppError> {
409+ match School::read(id, &self.control).await? {
421410 None => Err(AppError::Unauthorized),
422411 Some(school) if school.status == SchoolStatus::Suspended => {
423412 self.evict(school.get_id()).await;
@@ -428,7 +417,7 @@ impl Tenants {
428417 Err(AppError::Forbidden("school is still being provisioned"))
429418 }
430419 Some(school) => Ok(ResolvedTenant {
431- slug: slug.clone(),
420+ id: school.get_id(),
432421 db: self.handle(school.get_id()).await?,
433422 modules: school.modules(),
434423 }),
@@ -441,8 +430,11 @@ impl Tenants {
441430 /// still being provisioned is a `409`: the two routes that come through
442431 /// here (`enter`, `reset_admin_password`) need its database to answer, and a
443432 /// table-less one would surface as a `500` instead of "not ready yet".
444- pub async fn get_any_status(&self, slug: &Slug) -> Result<(Database, SchoolStatus), AppError> {
445- let school = School::read(slug, &self.control)
433+ pub async fn get_any_status(
434+ &self,
435+ id: &SchoolId,
436+ ) -> Result<(Database, SchoolStatus), AppError> {
437+ let school = School::read(id, &self.control)
446438 .await?
447439 .ok_or(AppError::NotFound)?;
448440 if school.status == SchoolStatus::Provisioning {
@@ -459,7 +451,6 @@ impl Tenants {
459451 pub async fn create(
460452 &self,
461453 id: SchoolId,
462- slug: &Slug,
463454 name: &str,
464455 modules: ModuleSet,
465456 ) -> Result<Database, AppError> {
@@ -471,24 +462,19 @@ impl Tenants {
471462 // school row never stands without the modules its creation asked for.
472463 let mut tx = self.control.begin().await?;
473464 let inserted = sqlx::query(
474- "INSERT INTO school (id, slug, name, status, created_at)
475- VALUES ($1, $2, $3, $4, $5)",
465+ "INSERT INTO school (id, name, status, created_at)
466+ VALUES ($1, $2, $3, $4)",
476467 )
477468 .bind(id.uuid())
478- .bind(slug.as_str())
479469 .bind(name)
480470 .bind(SchoolStatus::Provisioning)
481471 .bind(Timestamp::now().as_millis())
482472 .execute(&mut *tx)
483473 .await;
484474 if let Err(err) = inserted {
485- // The slug's UNIQUE constraint (`school_slug`) is the only key a
486- // rival can collide on — a fresh uuid v7 does not repeat. So a
487- // unique violation here is exactly "taken": a rival's row, or the
488- // row already stood. Same verdict either way, as it always was.
489- if unique_violation(&err).is_some() {
490- return Err(AppError::Conflict("school slug already taken"));
491- }
475+ // A fresh uuid v7 does not repeat. A unique violation here is an
476+ // internal fault (the primary key), not a name the caller can
477+ // change and retry.
492478 return Err(err.into());
493479 }
494480 for name in modules.names() {
@@ -500,9 +486,8 @@ impl Tenants {
500486 }
501487 tx.commit().await?;
502488
503- // Everything past the registry row rolls that row back on failure:
504- // the row is what makes the slug "taken", and a slug taken by a
505- // school that never came to exist is wedged for good. (A database
489+ // Everything past the registry row rolls that row back on failure.
490+ // (A database
506491 // created before the failure is not a wedge: the adopt branch in
507492 // [`Self::bring_up`] picks it up, migrations being idempotent.)
508493 let db = match self.bring_up(id).await {
@@ -516,8 +501,7 @@ impl Tenants {
516501 .bind(id.uuid())
517502 .execute(&self.control)
518503 .await;
519- // The rows go first — a slug taken by a school that never came
520- // to exist is wedged for good — then the database, which is the
504+ // The rows go first, then the database, which is the
521505 // expensive half and whose name nothing will ever reuse (the id
522506 // is minted per create, never replayed). Best-effort, but not
523507 // silent: a failure here is a half-provisioned database nobody
@@ -583,8 +567,8 @@ impl Tenants {
583567 /// [`School::update`], which is where the write itself lives. Suspending
584568 /// also drops the cached pool, so nothing that already resolved keeps
585569 /// serving.
586- pub async fn set_status(&self, slug: &Slug, status: SchoolStatus) -> Result<(), AppError> {
587- let school = School::update(slug, None, Some(status), &self.control).await?;
570+ pub async fn set_status(&self, id: &SchoolId, status: SchoolStatus) -> Result<(), AppError> {
571+ let school = School::update(id, None, Some(status), &self.control).await?;
588572 if status == SchoolStatus::Suspended {
589573 self.evict(school.get_id()).await;
590574 }
@@ -595,26 +579,26 @@ impl Tenants {
595579 /// eviction: entitlements are read off the registry row on every request,
596580 /// so a change takes effect on the next call and no cached pool carries a
597581 /// stale answer.
598- pub async fn set_modules(&self, slug: &Slug, modules: &ModuleSet) -> Result<(), AppError> {
582+ pub async fn set_modules(&self, id: &SchoolId, modules: &ModuleSet) -> Result<(), AppError> {
599583 modules.validate()?;
600584 // The swap is parent + children in one transaction: take the registry
601585 // row's lock so racing sellers serialize, then replace the whole shelf.
602586 let mut tx = self.control.begin().await?;
603- let id: Option<Uuid> =
604- sqlx::query_scalar("SELECT id FROM school WHERE slug = $1 FOR UPDATE")
605- .bind(slug.as_str())
587+ let locked: Option<Uuid> =
588+ sqlx::query_scalar("SELECT id FROM school WHERE id = $1 FOR UPDATE")
589+ .bind(id.uuid())
606590 .fetch_optional(&mut *tx)
607591 .await?;
608- let Some(id) = id else {
592+ let Some(row_id) = locked else {
609593 return Err(AppError::NotFound);
610594 };
611595 sqlx::query("DELETE FROM school_module WHERE school = $1")
612- .bind(id)
596+ .bind(row_id)
613597 .execute(&mut *tx)
614598 .await?;
615599 for name in modules.names() {
616600 sqlx::query("INSERT INTO school_module (school, module) VALUES ($1, $2)")
617- .bind(id)
601+ .bind(row_id)
618602 .bind(name)
619603 .execute(&mut *tx)
620604 .await?;
@@ -626,11 +610,10 @@ impl Tenants {
626610 /// Delete a school outright: its data, then its registry row, then its
627611 /// pool. Irreversible on purpose — there is no soft-delete state, that is
628612 /// what [`SchoolStatus::Suspended`] is for.
629- pub async fn drop(&self, slug: &Slug) -> Result<(), AppError> {
630- // The id comes off the row: the database is named by the uuid, not
631- // the slug. A row already gone means the goal state stands — nothing
632- // to destroy left.
633- let Some(school) = School::read(slug, &self.control).await? else {
613+ pub async fn drop(&self, id: &SchoolId) -> Result<(), AppError> {
614+ // A row already gone means the goal state stands. The database name
615+ // is derived from the id, but a missing row is `Ok(())`.
616+ let Some(school) = School::read(id, &self.control).await? else {
634617 return Ok(());
635618 };
636619 let id = school.get_id();
@@ -731,15 +714,15 @@ impl Tenants {
731714 /// `POST /podcast/jobs` for exactly this reason.
732715 ///
733716 /// Failure policy: **one school must never take the boot down.** A school
734- /// that fails to migrate is logged at ERROR with its id and slug and left
717+ /// that fails to migrate is logged at ERROR with its id and left
735718 /// exactly as it stood — no registry row and no status is written here, so
736719 /// a failed school stays as usable (or unusable) as it was before the
737720 /// sweep, and the next boot retries it. sqlx's tracking table is what
738721 /// makes the retry safe: a migration that died mid-flight is re-run, not
739722 /// half-believed.
740723 pub async fn sweep_school_schemas(&self) {
741- let rows: Vec<(Uuid, String)> =
742- match sqlx::query_as("SELECT id, slug FROM school ORDER BY created_at")
724+ let rows: Vec<(Uuid,)> =
725+ match sqlx::query_as("SELECT id FROM school ORDER BY created_at")
743726 .fetch_all(&self.control)
744727 .await
745728 {
@@ -755,21 +738,19 @@ impl Tenants {
755738 };
756739 let total = rows.len();
757740 let mut migrated = 0usize;
758- for (id, slug) in rows {
741+ for (id,) in rows {
759742 let id = SchoolId(id);
760743 match self.sweep_school(id).await {
761744 Ok(pending) if pending > 0 => {
762745 migrated += 1;
763746 tracing::info!(
764- school = %id.uuid(),
765- slug = %slug,
747+ school = %id,
766748 "school schema sweep applied {pending} migration(s) to a school behind the head"
767749 );
768750 }
769751 Ok(_) => {}
770752 Err(err) => tracing::error!(
771- school = %id.uuid(),
772- slug = %slug,
753+ school = %id,
773754 "school schema sweep failed — this school is left as it was and the next boot \
774755 retries it: {err}"
775756 ),
@@ -865,33 +846,27 @@ mod tests {
865846 use super::*;
866847
867848 #[test]
868- fn a_slug_names_a_school_and_nothing_reserved() {
869- for good in ["demo", "a1", "ata-koleji", &"x".repeat(32)] {
870- assert!(Slug::try_new(good).is_ok(), "{good:?} should be a slug");
871- }
872- // Reserved words would collide with the builder cookie prefix and the
873- // control database itself — the two things a slug must never name.
849+ fn a_school_id_is_a_hyphenated_uuid_and_nothing_else() {
850+ let good = "019732e3-7b00-7000-8000-00000000dead";
851+ let id = SchoolId::try_parse(good).expect("hyphenated");
852+ assert_eq!(id.as_str(), good);
874853 for bad in [
854+ "019732e37b007000800000000000dead",
855+ "urn:uuid:019732e3-7b00-7000-8000-00000000dead",
856+ "{019732e3-7b00-7000-8000-00000000dead}",
857+ "demo",
875858 "builder",
876- "control",
877- "Demo",
878- "..",
879859 "",
880- "x",
881- "-lead",
882- "has_underscore",
883- "has.dot",
884- &"x".repeat(33),
885860 ] {
886- assert!(Slug::try_new(bad).is_err(), "{bad:?} must not be a slug");
861+ assert!(SchoolId::try_parse(bad).is_err(), "{bad:?} must not parse");
887862 }
888863 }
889864
890865 /// The database-per-school model lives or dies by this mapping: two
891866 /// schools sharing a database name would share every row in it. The name
892867 /// now mints from the school's uuid — lowercase hex without dashes, fixed
893- /// width — so it is injective by construction, and the slug appears
894- /// nowhere: a slug rename can never orphan a database.
868+ /// width — so it is injective by construction, and no label appears
869+ /// in it: a rename can never orphan a database.
895870 #[test]
896871 fn school_db_names_are_injective() {
897872 let control = "hezarfen_control";
@@ -901,8 +876,8 @@ mod tests {
901876 school_db_name(control, id),
902877 "hezarfen_control_school_019732e37b007000800000000000dead"
903878 );
904- // Two uuids never collide onto one database, and no slug is in the
905- // name — not even the slug the uuid was minted for.
879+ // Two uuids never collide onto one database, and no label is in the
880+ // name.
906881 let other = Uuid::try_parse("019732e3-7b00-7000-8000-00000000beef").unwrap();
907882 assert_ne!(
908883 school_db_name(control, id),
src/web/auth.rsmodified+50 -27
@@ -16,7 +16,7 @@ use crate::error::{AppError, ErrorResponse, ValidationError};
1616 use crate::rate_limit::{RateLimitConfig, RateLimiter};
1717 use crate::service;
1818 use crate::state::AppState;
19-use crate::tenant::Slug;
19+use crate::tenant::SchoolId;
2020
2121 use super::dto::Role;
2222 use super::tenant_state::split_cookie;
@@ -40,6 +40,7 @@ pub fn routes(state: &AppState) -> OpenApiRouter<AppState> {
4040 let limiter = limiter.clone();
4141 async move { limiter.enforce(req, next).await }
4242 }))
43+ .routes(routes!(list_schools))
4344 .routes(routes!(select_school))
4445 .routes(routes!(logout))
4546 .routes(routes!(me))
@@ -51,9 +52,9 @@ pub fn routes(state: &AppState) -> OpenApiRouter<AppState> {
5152 /// `school` to login is merely ignored, not broken.
5253 #[derive(Deserialize, ToSchema)]
5354 struct RegisterCredentials {
54- /// The school's slug — where the new account (or the new membership of an
55- /// existing person) lives.
56- #[schema(example = "demo", min_length = 2, max_length = 32)]
55+ /// The school's uuid — where the new account (or the new membership of an
56+ /// existing person) lives. Hyphenated, as `GET /auth/schools` publishes it.
57+ #[schema(example = "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d")]
5758 school: String,
5859 #[schema(example = "ada", min_length = 3, max_length = 32)]
5960 username: String,
@@ -75,15 +76,15 @@ struct LoginCredentials {
7576 /// One school offered to a multi-school person.
7677 #[derive(Serialize, ToSchema)]
7778 struct SchoolChoice {
78- #[schema(example = "demo")]
79- slug: String,
79+ #[schema(example = "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d")]
80+ id: String,
8081 #[schema(example = "Demo")]
8182 name: String,
8283 }
8384
8485 /// What `POST /auth/login` answers when the person belongs to more than one
8586 /// active school: no `id` (no school is entered yet, so there is no school
86-/// row to speak of), and no school cookie. The `schools` list is in slug
87+/// row to speak of), and no school cookie. The `schools` list is in name
8788 /// order and omits suspended schools.
8889 #[derive(Serialize, ToSchema)]
8990 struct SchoolChoiceResponse {
@@ -93,7 +94,7 @@ struct SchoolChoiceResponse {
9394 }
9495
9596 /// The two login outcomes, told apart by shape: a school was entered (a
96-/// [`UserResponse`] and a `<slug>.<token>` cookie), or one must be chosen (a
97+/// [`UserResponse`] and a `<uuid>.<token>` cookie), or one must be chosen (a
9798 /// [`SchoolChoiceResponse`] and a `person.<token>` cookie). Disjoint by the
9899 /// `id` field, so an untagged `oneOf` is unambiguous on the wire.
99100 #[derive(Serialize, ToSchema)]
@@ -106,7 +107,7 @@ enum LoginResponse {
106107 /// What `POST /auth/school` takes: which of the person's memberships to bind.
107108 #[derive(Deserialize, ToSchema)]
108109 struct SelectSchool {
109- #[schema(example = "demo", min_length = 2, max_length = 32)]
110+ #[schema(example = "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d")]
110111 school: String,
111112 }
112113
@@ -123,6 +124,28 @@ struct RegisterResponse {
123124 role: Role,
124125 }
125126
127+/// Active schools open for registration. Unauthenticated, like register:
128+/// the picker has no session yet. Sorted by name; empty when none are active.
129+#[utoipa::path(
130+ get,
131+ path = "/schools",
132+ tag = "auth",
133+ responses(
134+ (status = 200, description = "Active schools, id and display name, sorted by name", body = Vec<SchoolChoice>),
135+ ),
136+)]
137+async fn list_schools(State(st): State<AppState>) -> Result<Json<Vec<SchoolChoice>>, AppError> {
138+ let rows = crate::db::person::list_active_schools(&st.db).await?;
139+ Ok(Json(
140+ rows.into_iter()
141+ .map(|(id, name)| SchoolChoice {
142+ id: id.to_string(),
143+ name,
144+ })
145+ .collect(),
146+ ))
147+}
148+
126149 /// Register a new user account, or attach an existing person to one more
127150 /// school: `{school, username, password}` in, `{username, role}` back (no
128151 /// `id`; new accounts are `student`). Always `201` — see below.
@@ -162,7 +185,7 @@ async fn register(
162185 // one that is suspended, must not reach the (expensive) hashing path — and
163186 // an unknown school answers `401` here for the same anti-enumeration reason
164187 // login does, rather than confirming which schools this deployment serves.
165- let school = Slug::try_new(&req.school).map_err(|_| AppError::Unauthorized)?;
188+ let school = SchoolId::try_parse(&req.school).map_err(|_| AppError::Unauthorized)?;
166189 let db = st.tenants.get(&school).await?;
167190 let username = Username::try_new(&req.username)?;
168191 // Registration-level policy, not a `Username` invariant: these names read
@@ -216,7 +239,7 @@ async fn register(
216239
217240 /// Log in with username + password — no school. Sets a `session` cookie on
218241 /// success: exactly one active membership enters that school right away
219-/// (`<slug>.<token>` and the full [`UserResponse`], unchanged for
242+/// (`<uuid>.<token>` and the full [`UserResponse`], unchanged for
220243 /// single-school clients), several answer a [`SchoolChoiceResponse`] with a
221244 /// `person.<token>` cookie that `POST /auth/school` binds.
222245 #[utoipa::path(
@@ -225,7 +248,7 @@ async fn register(
225248 tag = "auth",
226249 request_body = LoginCredentials,
227250 responses(
228- (status = 200, description = "Logged in — either straight into the one school (a `UserResponse` and a `<slug>.<token>` cookie), or as a multi-school person (a `{username, schools}` choice list and a `person.<token>` cookie to bind with `POST /auth/school`). Suspended schools appear in neither shape", body = LoginResponse),
251+ (status = 200, description = "Logged in — either straight into the one school (a `UserResponse` and a `<uuid>.<token>` cookie), or as a multi-school person (a `{username, schools}` choice list and a `person.<token>` cookie to bind with `POST /auth/school`). Suspended schools appear in neither shape", body = LoginResponse),
229252 (status = 401, description = "Bad credentials — unknown username, wrong password, or no school membership left to enter, all deliberately indistinguishable", body = ErrorResponse),
230253 (status = 403, description = "Every school the person belongs to is suspended", body = ErrorResponse),
231254 (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse),
@@ -275,7 +298,7 @@ async fn login(
275298 // including this one.
276299 [] => Err(AppError::Forbidden("school is suspended")),
277300 [only] => {
278- let db = st.tenants.get(only.slug()).await?;
301+ let db = st.tenants.get(&only.id()).await?;
279302 // The school-side row the session binds to. A membership without
280303 // its `app_user` (a torn create) refuses like a bad credential
281304 // rather than confirm anything.
@@ -287,11 +310,11 @@ async fn login(
287310 // The caller is genuine; opportunistically drop expired session rows.
288311 let _ = service::session::purge_expired(&db).await;
289312 let session = service::session::create(&db, user.get_id()).await?;
290- // `<slug>.<token>`: the cookie carries the school, so every later
313+ // `<uuid>.<token>`: the cookie carries the school, so every later
291314 // request finds its database without a second lookup path that
292315 // could disagree.
293316 let cookie = session_cookie(
294- format!("{}.{}", only.slug(), session.token().as_str()),
317+ format!("{}.{}", only.id(), session.token().as_str()),
295318 st.cookie_secure,
296319 );
297320 Ok((
@@ -302,7 +325,7 @@ async fn login(
302325 many => {
303326 // Not entering any school yet: the `person.<token>` cookie is the
304327 // not-chosen state, and `POST /auth/school` exchanges it. The
305- // list carries slug and display name, suspended schools omitted.
328+ // list carries id and display name, suspended schools omitted.
306329 let session = service::person::create_session(&st.db, person.get_id()).await?;
307330 let cookie = session_cookie(
308331 format!("{PERSON_COOKIE_PREFIX}.{}", session.token().as_str()),
@@ -311,7 +334,7 @@ async fn login(
311334 let schools = many
312335 .iter()
313336 .map(|m| SchoolChoice {
314- slug: m.slug().as_str().to_string(),
337+ id: m.id().as_str(),
315338 name: m.name().to_string(),
316339 })
317340 .collect();
@@ -327,7 +350,7 @@ async fn login(
327350 }
328351
329352 /// Bind a `person.<token>` session to one of the person's schools: the
330-/// cookie is replaced with that school's own `<slug>.<token>` and the person
353+/// cookie is replaced with that school's own `<uuid>.<token>` and the person
331354 /// session is revoked. Deliberately outside the credential rate-limit tier —
332355 /// this is not a credential guess, and it requires a session cookie already.
333356 #[utoipa::path(
@@ -337,7 +360,7 @@ async fn login(
337360 request_body = SelectSchool,
338361 responses(
339362 (status = 200, description = "School selected; the person cookie is replaced by the school session cookie", body = UserResponse),
340- (status = 401, description = "No person session, or the school is not among the caller's memberships — deliberately indistinguishable (no cookie at all, a school or builder cookie, and a slug the person does not hold all answer the same)", body = ErrorResponse),
363+ (status = 401, description = "No person session, or the school is not among the caller's memberships — deliberately indistinguishable (no cookie at all, a school or builder cookie, and an id the person does not hold all answer the same)", body = ErrorResponse),
341364 (status = 403, description = "The school is suspended", body = ErrorResponse),
342365 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
343366 ),
@@ -360,15 +383,15 @@ async fn select_school(
360383 .await?
361384 .filter(|s| !s.is_expired())
362385 .ok_or(AppError::Unauthorized)?;
363- // Membership required, and a slug that names nothing is the same refusal
386+ // Membership required, and an id that names nothing is the same refusal
364387 // as one the person does not hold — the list login already gave them is
365388 // not a directory of the deployment.
366- let slug = Slug::try_new(&req.school).map_err(|_| AppError::Unauthorized)?;
367- service::person::membership_of(&st.db, session.person(), &slug)
389+ let id = SchoolId::try_parse(&req.school).map_err(|_| AppError::Unauthorized)?;
390+ service::person::membership_of(&st.db, session.person(), &id)
368391 .await?
369392 .ok_or(AppError::Unauthorized)?;
370393 // Suspended → `403` here, like on every school door.
371- let db = st.tenants.get(&slug).await?;
394+ let db = st.tenants.get(&id).await?;
372395 let person = service::person::read(&st.db, session.person())
373396 .await?
374397 .ok_or(AppError::Unauthorized)?;
@@ -382,7 +405,7 @@ async fn select_school(
382405 let school_session = service::session::create(&db, user.get_id()).await?;
383406 service::person::delete_session_by_token(&st.db, token).await?;
384407 let cookie = session_cookie(
385- format!("{slug}.{}", school_session.token().as_str()),
408+ format!("{id}.{}", school_session.token().as_str()),
386409 st.cookie_secure,
387410 );
388411 Ok((jar.add(cookie), Json(UserResponse::new(&user))))
@@ -391,7 +414,7 @@ async fn select_school(
391414 /// The `session` cookie, however it was earned. Shared by school login and the
392415 /// builder surface (`web::builder`) so the two can never drift apart on path,
393416 /// flags or lifetime — the value is the only difference between them
394-/// (`<slug>.<token>` against `builder.<token>`).
417+/// (`<uuid>.<token>` against `builder.<token>`).
395418 pub(crate) fn session_cookie(value: String, secure: bool) -> Cookie<'static> {
396419 Cookie::build(("session", value))
397420 .path("/")
@@ -425,8 +448,8 @@ async fn logout(
425448 crate::service::builder::delete_by_token(&st.db, token).await?;
426449 } else if prefix == PERSON_COOKIE_PREFIX {
427450 service::person::delete_session_by_token(&st.db, token).await?;
428- } else if let Ok(slug) = Slug::try_new(prefix)
429- && let Ok(db) = st.tenants.get(&slug).await
451+ } else if let Ok(id) = SchoolId::try_parse(prefix)
452+ && let Ok(db) = st.tenants.get(&id).await
430453 {
431454 service::session::delete_by_token(&db, token).await?;
432455 }
src/web/board_ws.rsmodified+13 -13
@@ -58,7 +58,7 @@
5858 use std::collections::VecDeque;
5959 use std::time::Duration;
6060
61-use crate::web::tenant_state::{SchoolSlug, State};
61+use crate::web::tenant_state::{SchoolIdCookie, State};
6262 use axum::extract::Path;
6363 use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
6464 use axum::response::Response;
@@ -78,7 +78,7 @@ use crate::domain::user::UserId;
7878 use crate::error::AppError;
7979 use crate::service::{board, board_stroke};
8080 use crate::state::AppState;
81-use crate::tenant::Slug;
81+use crate::tenant::SchoolId;
8282 use crate::web::CurrentUser;
8383 use crate::web::room::{self, Incoming, RoomClosed, send, with_client_seq};
8484
@@ -122,7 +122,7 @@ enum ClientMessage {
122122 /// every action already re-reads through.
123123 pub async fn board_ws(
124124 State(st): State<AppState>,
125- SchoolSlug(slug): SchoolSlug,
125+ SchoolIdCookie(school): SchoolIdCookie,
126126 CurrentUser(user): CurrentUser,
127127 Path(id): Path<String>,
128128 ws: WebSocketUpgrade,
@@ -141,19 +141,19 @@ pub async fn board_ws(
141141 }
142142 let board_id = board.get_id().clone();
143143 let user_id = *user.get_id();
144- Ok(ws.on_upgrade(move |socket| room(socket, st, slug, board_id, user_id)))
144+ Ok(ws.on_upgrade(move |socket| room(socket, st, school, board_id, user_id)))
145145 }
146146
147147 /// The room loop: the board's frames out, draw/clear/lock/ping in, until the
148148 /// socket closes or the board ends (closed, deleted, or the caller taken off
149149 /// it).
150-async fn room(mut socket: WebSocket, st: AppState, slug: Slug, board: BoardId, user: UserId) {
150+async fn room(mut socket: WebSocket, st: AppState, school: SchoolId, board: BoardId, user: UserId) {
151151 // Subscribe *before* anything is read out of the database: a stroke that
152152 // lands between a replay's read and this subscribe would otherwise be lost
153153 // outright, whereas one delivered twice is deduplicated by its id at the
154154 // client (which a resync forces anyway).
155- let _connected = room::Connected::open(&st.metrics, "board", slug.as_str(), &board.key());
156- let mut feed = st.board_hub.subscribe(&slug, &board.key());
155+ let _connected = room::Connected::open(&st.metrics, "board", school.as_str(), &board.key());
156+ let mut feed = st.board_hub.subscribe(&school, &board.key());
157157 // The ids this socket drew, in the order they were published. The hub has
158158 // no idea who is listening, so the room filters its own strokes back out
159159 // here — a client that had to ignore the echo of every mark it just drew
@@ -182,7 +182,7 @@ async fn room(mut socket: WebSocket, st: AppState, slug: Slug, board: BoardId, u
182182 },
183183 incoming = socket.recv() => match room::classify(incoming) {
184184 Incoming::Text(text) => {
185- handle_message(&mut socket, text.as_str(), &slug, &board, &user, &mut mine, &st).await
185+ handle_message(&mut socket, text.as_str(), &school, &board, &user, &mut mine, &st).await
186186 }
187187 Incoming::Gone => Err(RoomClosed),
188188 Incoming::Ignore => Ok(()),
@@ -193,7 +193,7 @@ async fn room(mut socket: WebSocket, st: AppState, slug: Slug, board: BoardId, u
193193 }
194194 }
195195 room::close(&mut socket).await;
196- st.board_hub.leave(&slug, &board.key());
196+ st.board_hub.leave(&school, &board.key());
197197 }
198198
199199 type Step = Result<(), RoomClosed>;
@@ -401,7 +401,7 @@ fn stroke_body(stroke: &BoardStroke) -> Value {
401401 async fn handle_message(
402402 socket: &mut WebSocket,
403403 text: &str,
404- slug: &Slug,
404+ school: &SchoolId,
405405 board: &BoardId,
406406 user: &UserId,
407407 mine: &mut VecDeque<String>,
@@ -475,7 +475,7 @@ async fn handle_message(
475475 fanned["type"] = json!("stroke");
476476 fanned["epoch"] = json!(stroke.get_epoch());
477477 mine.push_back(stroke.get_id().key().to_string());
478- st.board_hub.publish(slug, &board.key(), fanned.to_string());
478+ st.board_hub.publish(school, &board.key(), fanned.to_string());
479479 let mut frame = json!({ "type": "saved", "id": stroke.get_id().key() });
480480 with_client_seq(&mut frame, client_seq);
481481 send(socket, frame).await
@@ -498,7 +498,7 @@ async fn handle_message(
498498 // canvas is the next one. Same shape as `POST /boards/{id}/clear`.
499499 Ok(marker) => {
500500 st.board_hub.publish(
501- slug,
501+ school,
502502 &board.key(),
503503 json!({
504504 "type": "cleared",
@@ -517,7 +517,7 @@ async fn handle_message(
517517 Some(live) => match board::set_locked(&st.db, &live, locked, user).await {
518518 Ok(_) => {
519519 st.board_hub.publish(
520- slug,
520+ school,
521521 &board.key(),
522522 json!({ "type": "locked", "locked": locked, "by": user.key() }).to_string(),
523523 );
src/web/boards.rsmodified+15 -15
@@ -18,7 +18,7 @@
1818 //! mid-session keeps drawing over an already-open socket until the room hears
1919 //! about it, so a roster change *must* fan out.
2020
21-use crate::web::tenant_state::{SchoolSlug, State};
21+use crate::web::tenant_state::{SchoolIdCookie, State};
2222 use axum::Json;
2323 use axum::extract::{Path, Query};
2424 use axum::http::StatusCode;
@@ -40,7 +40,7 @@ use crate::error::{AppError, ErrorResponse, ValidationError};
4040 use crate::service::course::can_manage_course;
4141 use crate::service::{board, board_stroke};
4242 use crate::state::AppState;
43-use crate::tenant::Slug;
43+use crate::tenant::SchoolId;
4444
4545 use super::{CurrentUser, Page, PageParams, RequireStudent, paginate, set_or_clear};
4646
@@ -62,8 +62,8 @@ pub fn routes() -> OpenApiRouter<AppState> {
6262
6363 /// Push one frame to whoever is in the room right now. An empty room is the
6464 /// normal case, not a failure.
65-fn fan_out(st: &AppState, slug: &Slug, board: &BoardId, frame: serde_json::Value) {
66- st.board_hub.publish(slug, &board.key(), frame.to_string());
65+fn fan_out(st: &AppState, school: &SchoolId, board: &BoardId, frame: serde_json::Value) {
66+ st.board_hub.publish(school, &board.key(), frame.to_string());
6767 }
6868
6969 /// The roster frame every path that changes the invite list must publish. A
@@ -438,7 +438,7 @@ struct UpdateBoard {
438438 )]
439439 async fn update_board(
440440 State(st): State<AppState>,
441- SchoolSlug(slug): SchoolSlug,
441+ SchoolIdCookie(school): SchoolIdCookie,
442442 CurrentUser(user): CurrentUser,
443443 Path(id): Path<String>,
444444 Json(req): Json<UpdateBoard>,
@@ -461,13 +461,13 @@ async fn update_board(
461461 let participants =
462462 board::resolve_participants(participants, board.get_participants(), &st.db).await?;
463463 board = board::set_participants(&st.db, &board, participants).await?;
464- fan_out(&st, &slug, board.get_id(), participants_frame(&board));
464+ fan_out(&st, &school, board.get_id(), participants_frame(&board));
465465 }
466466 if let Some(locked) = req.locked {
467467 board = board::set_locked(&st.db, &board, locked, user.get_id()).await?;
468468 fan_out(
469469 &st,
470- &slug,
470+ &school,
471471 board.get_id(),
472472 json!({"type": "locked", "locked": locked, "by": user.get_id().key()}),
473473 );
@@ -503,7 +503,7 @@ async fn update_board(
503503 )]
504504 async fn clear_board(
505505 State(st): State<AppState>,
506- SchoolSlug(slug): SchoolSlug,
506+ SchoolIdCookie(school): SchoolIdCookie,
507507 CurrentUser(user): CurrentUser,
508508 Path(id): Path<String>,
509509 ) -> Result<(StatusCode, Json<StrokeResponse>), AppError> {
@@ -514,7 +514,7 @@ async fn clear_board(
514514 // next one.
515515 fan_out(
516516 &st,
517- &slug,
517+ &school,
518518 board.get_id(),
519519 json!({
520520 "type": "cleared",
@@ -545,7 +545,7 @@ async fn clear_board(
545545 )]
546546 async fn close_board(
547547 State(st): State<AppState>,
548- SchoolSlug(slug): SchoolSlug,
548+ SchoolIdCookie(school): SchoolIdCookie,
549549 CurrentUser(user): CurrentUser,
550550 Path(id): Path<String>,
551551 ) -> Result<Json<BoardResponse>, AppError> {
@@ -554,7 +554,7 @@ async fn close_board(
554554 let board = board::close(&st.db, &board).await?;
555555 fan_out(
556556 &st,
557- &slug,
557+ &school,
558558 board.get_id(),
559559 json!({
560560 "type": "closed",
@@ -719,7 +719,7 @@ impl InviteSource {
719719 )]
720720 async fn invite_board(
721721 State(st): State<AppState>,
722- SchoolSlug(slug): SchoolSlug,
722+ SchoolIdCookie(school): SchoolIdCookie,
723723 CurrentUser(user): CurrentUser,
724724 Path(id): Path<String>,
725725 Json(req): Json<InviteSource>,
@@ -734,7 +734,7 @@ async fn invite_board(
734734 board::ensure_creator(&board, &user)?;
735735 let invited = req.resolve(&user, &st.db).await?;
736736 let board = board::invite(&st.db, &board, invited).await?;
737- fan_out(&st, &slug, board.get_id(), participants_frame(&board));
737+ fan_out(&st, &school, board.get_id(), participants_frame(&board));
738738 Ok(Json(BoardResponse::new(&board)))
739739 }
740740
@@ -757,7 +757,7 @@ async fn invite_board(
757757 )]
758758 async fn delete_board(
759759 State(st): State<AppState>,
760- SchoolSlug(slug): SchoolSlug,
760+ SchoolIdCookie(school): SchoolIdCookie,
761761 CurrentUser(user): CurrentUser,
762762 Path(id): Path<String>,
763763 ) -> Result<StatusCode, AppError> {
@@ -767,6 +767,6 @@ async fn delete_board(
767767 board::delete(&st.db, board).await?;
768768 // Told after the row is gone: a room that acts on this and then re-reads
769769 // must find nothing, not a board about to disappear.
770- fan_out(&st, &slug, &id, json!({"type": "deleted"}));
770+ fan_out(&st, &school, &id, json!({"type": "deleted"}));
771771 Ok(StatusCode::NO_CONTENT)
772772 }
src/web/builder.rsmodified+80 -89
@@ -6,7 +6,7 @@
66 //!
77 //! The two principals never mix: [`RequireBuilder`] takes only a
88 //! `builder.<token>` cookie, and that cookie is `401` on every school surface
9-//! (see `web::tenant_state::resolve_tenant`). `POST /schools/{slug}/enter` is
9+//! (see `web::tenant_state::resolve_tenant`). `POST /schools/{id}/enter` is
1010 //! the one bridge, and it does not blur the line — it mints an ordinary school
1111 //! session for an admin account that already exists there.
1212 //!
@@ -34,7 +34,7 @@ use crate::module::{Module, ModuleSet, Package};
3434 use crate::rate_limit::{RateLimitConfig, RateLimiter};
3535 use crate::service;
3636 use crate::state::AppState;
37-use crate::tenant::{School, SchoolId, SchoolStatus, Slug};
37+use crate::tenant::{School, SchoolId, SchoolStatus};
3838 use crate::validate::validate_required;
3939 use crate::web::tenant_state::school_files_path;
4040
@@ -93,8 +93,8 @@ impl BuilderResponse {
9393
9494 #[derive(Serialize, ToSchema)]
9595 struct SchoolResponse {
96- #[schema(example = "ata-koleji")]
97- slug: String,
96+ #[schema(example = "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d")]
97+ id: String,
9898 #[schema(example = "Ata Koleji")]
9999 name: String,
100100 /// `active` or `suspended` — plus `provisioning`, which a boot writes only
@@ -106,7 +106,7 @@ struct SchoolResponse {
106106 /// Registered at, UTC unix-milliseconds.
107107 created_at: i64,
108108 /// The modules this school has bought, sorted by name. The other half of
109- /// the catalog is on `GET /schools/{slug}/modules`.
109+ /// the catalog is on `GET /schools/{id}/modules`.
110110 #[schema(example = json!(["courses", "meals", "notes"]))]
111111 modules: Vec<String>,
112112 }
@@ -114,7 +114,7 @@ struct SchoolResponse {
114114 impl SchoolResponse {
115115 fn new(school: &School) -> Self {
116116 Self {
117- slug: school.slug().as_str().to_string(),
117+ id: school.get_id().as_str(),
118118 name: school.name().to_string(),
119119 status: school.status().as_str().to_string(),
120120 created_at: school.created_at().as_millis(),
@@ -125,12 +125,6 @@ impl SchoolResponse {
125125
126126 #[derive(Deserialize, ToSchema)]
127127 struct CreateSchool {
128- /// Lowercase `a-z`, `0-9` and `-`, starting with a letter or digit. Names
129- /// the school's blob directory and its cookie prefix. It is the school's
130- /// public label, not its identity — the uuid minted at create time is —
131- /// and it must stay unique across the deployment.
132- #[schema(example = "ata-koleji", min_length = 2, max_length = 32)]
133- slug: String,
134128 #[schema(example = "Ata Koleji", max_length = 120)]
135129 name: String,
136130 /// The school's first admin, created inside the new school's database.
@@ -210,18 +204,18 @@ struct EnterSchool {
210204 username: String,
211205 }
212206
213-/// A school's display name: free text, unlike its slug.
207+/// A school's display name.
214208 fn school_name(value: &str) -> Result<String, AppError> {
215209 validate_required("name", value, MAX_SCHOOL_NAME_LEN)?;
216210 Ok(value.trim().to_string())
217211 }
218212
219-/// The slug in a path. Anything that is not a slug names no school, so it is
220-/// the same `404` an unknown one gets — and it never reaches
213+/// The school id in a path. Anything that is not a hyphenated uuid names no
214+/// school, so it is the same `404` an unknown one gets — and it never reaches
221215 /// [`school_files_path`], which is exactly why that path is built from a
222-/// validated [`Slug`] and never from the raw segment.
223-fn path_slug(raw: &str) -> Result<Slug, AppError> {
224- Slug::try_new(raw).map_err(|_| AppError::NotFound)
216+/// parsed [`SchoolId`] and never from the raw segment.
217+fn path_id(raw: &str) -> Result<SchoolId, AppError> {
218+ SchoolId::try_parse(raw).map_err(|_| AppError::NotFound)
225219 }
226220
227221 /// The named account in `db`, which must be an admin of that school: unknown →
@@ -333,9 +327,9 @@ async fn builder_me(RequireBuilder(builder): RequireBuilder) -> Json<BuilderResp
333327 request_body = CreateSchool,
334328 responses(
335329 (status = 201, description = "School created, with its first admin", body = SchoolResponse),
336- (status = 400, description = "Invalid slug, name, admin credentials, or module name", body = ErrorResponse, example = json!({"error": "module: `kantin` is not a known module"})),
330+ (status = 400, description = "Invalid name, admin credentials, or module name", body = ErrorResponse, example = json!({"error": "module: `kantin` is not a known module"})),
337331 (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
338- (status = 409, description = "That slug is already taken, the module set is unsatisfiable, or the admin username exists under a different password", body = ErrorResponse, example = json!({"error": "conflict: exams requires subjects, which is not enabled"})),
332+ (status = 409, description = "The module set is unsatisfiable, or the admin username exists under a different password", body = ErrorResponse, example = json!({"error": "conflict: exams requires subjects, which is not enabled"})),
339333 (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"),
340334 ),
341335 )]
@@ -347,7 +341,6 @@ async fn create_school(
347341 // Everything the request must get right is checked (and the admin password
348342 // hashed) *before* a database is defined, so the ordinary rejection never
349343 // creates anything to clean up.
350- let slug = Slug::try_new(&req.slug)?;
351344 let name = school_name(&req.name)?;
352345 let username = Username::try_new(&req.admin_username)?;
353346 let password = Password::try_new(&req.admin_password)?;
@@ -375,9 +368,9 @@ async fn create_school(
375368
376369 // The school's uuid is minted here, on the one path that creates schools:
377370 // it becomes the registry row's PK and the database name's source, and
378- // the slug stays a label the wire keeps answering with.
371+ // the minted id is what the wire answers with.
379372 let id = SchoolId::generate();
380- let db = st.tenants.create(id, &slug, &name, modules).await?;
373+ let db = st.tenants.create(id, &name, modules).await?;
381374 let seeded = async {
382375 crate::service::user::create_with_role(
383376 &db,
@@ -389,20 +382,20 @@ async fn create_school(
389382 .await?;
390383 // The admin's person gets the membership the school row answers for —
391384 // idempotent, so a retried create after a torn pair completes it.
392- service::person::link_school(&st.db, person.get_id(), &slug).await?;
385+ service::person::link_school(&st.db, person.get_id(), &id).await?;
393386 Ok::<(), AppError>(())
394387 }
395388 .await;
396389 if let Err(err) = seeded {
397390 // A school nobody can log into is worse than no school: take the
398391 // database back so the very same request can simply be retried.
399- if let Err(cleanup) = st.tenants.drop(&slug).await {
400- tracing::error!("failed to drop {slug} after its admin seed failed: {cleanup}");
392+ if let Err(cleanup) = st.tenants.drop(&id).await {
393+ tracing::error!("failed to drop {id} after its admin seed failed: {cleanup}");
401394 }
402395 return Err(err);
403396 }
404397
405- let school = School::read(&slug, st.tenants.control())
398+ let school = School::read(&id, st.tenants.control())
406399 .await?
407400 .ok_or_else(|| AppError::Internal("the school vanished as it was created".into()))?;
408401 Ok((StatusCode::CREATED, Json(SchoolResponse::new(&school))))
@@ -433,13 +426,13 @@ async fn list_schools(
433426 Ok(Json(Page::new(items, total, limit, offset)))
434427 }
435428
436-/// One school by slug.
429+/// One school by id.
437430 #[utoipa::path(
438431 get,
439- path = "/schools/{slug}",
432+ path = "/schools/{id}",
440433 tag = "builder",
441434 security(("session_cookie" = [])),
442- params(("slug" = String, Path, description = "School slug")),
435+ params(("id" = String, Path, description = "School uuid")),
443436 responses(
444437 (status = 200, description = "The school", body = SchoolResponse),
445438 (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
@@ -449,9 +442,9 @@ async fn list_schools(
449442 async fn get_school(
450443 State(st): State<AppState>,
451444 RequireBuilder(_builder): RequireBuilder,
452- Path(slug): Path<String>,
445+ Path(id): Path<String>,
453446 ) -> Result<Json<SchoolResponse>, AppError> {
454- let school = School::read(&path_slug(&slug)?, st.tenants.control())
447+ let school = School::read(&path_id(&id)?, st.tenants.control())
455448 .await?
456449 .ok_or(AppError::NotFound)?;
457450 Ok(Json(SchoolResponse::new(&school)))
@@ -459,10 +452,8 @@ async fn get_school(
459452
460453 /// Rename a school and/or flip it between `active` and `suspended`. Omitted
461454 /// fields keep their value — both land in one statement, so a request that
462-/// carries both is one write and never half a patch. The slug itself is
463-/// immutable in this cut — it is the cookie prefix and the blob directory —
464-/// though it no longer names the database (the school's uuid does); a rename
465-/// API is not offered yet.
455+/// carries both is one write and never half a patch. The id is not a
456+/// field a patch can move.
466457 ///
467458 /// `provisioning` is not a status a client can ask for: it is the boot's word
468459 /// for a school that is still being made, and asking for it is a `400`.
@@ -471,10 +462,10 @@ async fn get_school(
471462 /// request is a `403`, live session or not.
472463 #[utoipa::path(
473464 patch,
474- path = "/schools/{slug}",
465+ path = "/schools/{id}",
475466 tag = "builder",
476467 security(("session_cookie" = [])),
477- params(("slug" = String, Path, description = "School slug")),
468+ params(("id" = String, Path, description = "School uuid")),
478469 request_body = UpdateSchool,
479470 responses(
480471 (status = 200, description = "The updated school", body = SchoolResponse),
@@ -487,10 +478,10 @@ async fn get_school(
487478 async fn update_school(
488479 State(st): State<AppState>,
489480 RequireBuilder(_builder): RequireBuilder,
490- Path(slug): Path<String>,
481+ Path(id): Path<String>,
491482 Json(req): Json<UpdateSchool>,
492483 ) -> Result<Json<SchoolResponse>, AppError> {
493- let slug = path_slug(&slug)?;
484+ let id = path_id(&id)?;
494485 let name = req.name.as_deref().map(school_name).transpose()?;
495486 let status = req
496487 .status
@@ -502,7 +493,7 @@ async fn update_school(
502493 // a patch that carries both can never leave half of itself behind. An empty
503494 // patch on an unknown school is still a 404 — the update answers it, rather
504495 // than whichever field happened to be present.
505- let school = School::update(&slug, name.as_deref(), status, st.tenants.control()).await?;
496+ let school = School::update(&id, name.as_deref(), status, st.tenants.control()).await?;
506497 if status == Some(SchoolStatus::Suspended) {
507498 // A suspension evicts the pool so nothing that already resolved keeps
508499 // serving; un-suspending needs no invalidation, the next request dials.
@@ -515,10 +506,10 @@ async fn update_school(
515506 /// Irreversible — suspension is the reversible door.
516507 #[utoipa::path(
517508 delete,
518- path = "/schools/{slug}",
509+ path = "/schools/{id}",
519510 tag = "builder",
520511 security(("session_cookie" = [])),
521- params(("slug" = String, Path, description = "School slug")),
512+ params(("id" = String, Path, description = "School uuid")),
522513 responses(
523514 (status = 204, description = "Deleted"),
524515 (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
@@ -528,24 +519,24 @@ async fn update_school(
528519 async fn delete_school(
529520 State(st): State<AppState>,
530521 RequireBuilder(_builder): RequireBuilder,
531- Path(slug): Path<String>,
522+ Path(id): Path<String>,
532523 ) -> Result<StatusCode, AppError> {
533- let slug = path_slug(&slug)?;
534- School::read(&slug, st.tenants.control())
524+ let id = path_id(&id)?;
525+ School::read(&id, st.tenants.control())
535526 .await?
536527 .ok_or(AppError::NotFound)?;
537- st.tenants.drop(&slug).await?;
528+ st.tenants.drop(&id).await?;
538529
539530 // Rows first, bytes second — the same order every blob delete here keeps, so
540531 // a crash between them strands unreachable files rather than rows pointing
541- // at nothing. The directory is built from the validated `Slug`, never from
532+ // at nothing. The directory is built from the parsed id, never from
542533 // the raw path segment.
543- let dir = school_files_path(&st.files_path, &slug);
534+ let dir = school_files_path(&st.files_path, &id);
544535 if let Err(err) = tokio::fs::remove_dir_all(&dir).await
545536 && err.kind() != std::io::ErrorKind::NotFound
546537 {
547538 tracing::warn!(
548- "failed to remove the files of {slug} at {}: {err}",
539+ "failed to remove the files of {id} at {}: {err}",
549540 dir.display()
550541 );
551542 }
@@ -553,7 +544,7 @@ async fn delete_school(
553544 }
554545
555546 /// A module named in a path segment. Unknown → `404`, the same verdict an
556-/// unknown slug gets: the segment names nothing this deployment sells, so
547+/// unknown id gets: the segment names nothing this deployment sells, so
557548 /// there is no resource to act on. Inside a *body* the same name is a `400`
558549 /// instead — a bad field, not a bad address.
559550 fn path_module(raw: &str) -> Result<Module, AppError> {
@@ -564,10 +555,10 @@ fn path_module(raw: &str) -> Result<Module, AppError> {
564555 /// [`Tenants::resolve`]: that one is the school's own door and refuses a
565556 /// suspended school, and every route here keeps working on one.
566557 async fn school_modules(
567- slug: &Slug,
558+ id: &SchoolId,
568559 control: &crate::database::Database,
569560 ) -> Result<ModuleSet, AppError> {
570- Ok(School::read(slug, control)
561+ Ok(School::read(id, control)
571562 .await?
572563 .ok_or(AppError::NotFound)?
573564 .modules())
@@ -596,10 +587,10 @@ fn refuse_if_needed(module: Module, set: &ModuleSet) -> Result<(), AppError> {
596587 /// caller here has already decided.
597588 async fn store_modules(
598589 st: &AppState,
599- slug: &Slug,
590+ id: &SchoolId,
600591 modules: ModuleSet,
601592 ) -> Result<Json<ModulesResponse>, AppError> {
602- st.tenants.set_modules(slug, &modules).await?;
593+ st.tenants.set_modules(id, &modules).await?;
603594 Ok(Json(ModulesResponse::new(&modules)))
604595 }
605596
@@ -607,10 +598,10 @@ async fn store_modules(
607598 /// school — entitlements are the vendor's ledger, not one of the school's doors.
608599 #[utoipa::path(
609600 get,
610- path = "/schools/{slug}/modules",
601+ path = "/schools/{id}/modules",
611602 tag = "builder",
612603 security(("session_cookie" = [])),
613- params(("slug" = String, Path, description = "School slug")),
604+ params(("id" = String, Path, description = "School uuid")),
614605 responses(
615606 (status = 200, description = "The school's enabled and disabled modules", body = ModulesResponse),
616607 (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
@@ -620,9 +611,9 @@ async fn store_modules(
620611 async fn list_school_modules(
621612 State(st): State<AppState>,
622613 RequireBuilder(_builder): RequireBuilder,
623- Path(slug): Path<String>,
614+ Path(id): Path<String>,
624615 ) -> Result<Json<ModulesResponse>, AppError> {
625- let modules = school_modules(&path_slug(&slug)?, st.tenants.control()).await?;
616+ let modules = school_modules(&path_id(&id)?, st.tenants.control()).await?;
626617 Ok(Json(ModulesResponse::new(&modules)))
627618 }
628619
@@ -631,11 +622,11 @@ async fn list_school_modules(
631622 /// off — enable those in the same `PATCH` instead.
632623 #[utoipa::path(
633624 post,
634- path = "/schools/{slug}/modules/{module}",
625+ path = "/schools/{id}/modules/{module}",
635626 tag = "builder",
636627 security(("session_cookie" = [])),
637628 params(
638- ("slug" = String, Path, description = "School slug"),
629+ ("id" = String, Path, description = "School uuid"),
639630 ("module" = String, Path, description = "Module name, as `GET /modules/catalog` publishes it"),
640631 ),
641632 responses(
@@ -648,17 +639,17 @@ async fn list_school_modules(
648639 async fn enable_school_module(
649640 State(st): State<AppState>,
650641 RequireBuilder(_builder): RequireBuilder,
651- Path((slug, module)): Path<(String, String)>,
642+ Path((id, module)): Path<(String, String)>,
652643 ) -> Result<Json<ModulesResponse>, AppError> {
653- let slug = path_slug(&slug)?;
644+ let id = path_id(&id)?;
654645 let module = path_module(&module)?;
655- let mut modules = school_modules(&slug, st.tenants.control()).await?;
646+ let mut modules = school_modules(&id, st.tenants.control()).await?;
656647 if modules.contains(module) {
657648 return Ok(Json(ModulesResponse::new(&modules)));
658649 }
659650 modules.insert(module);
660651 modules.validate()?;
661- store_modules(&st, &slug, modules).await
652+ store_modules(&st, &id, modules).await
662653 }
663654
664655 /// Take one module back. Idempotent, and refused while a module the school
@@ -668,11 +659,11 @@ async fn enable_school_module(
668659 /// back with it. Only its routes stop answering.
669660 #[utoipa::path(
670661 delete,
671- path = "/schools/{slug}/modules/{module}",
662+ path = "/schools/{id}/modules/{module}",
672663 tag = "builder",
673664 security(("session_cookie" = [])),
674665 params(
675- ("slug" = String, Path, description = "School slug"),
666+ ("id" = String, Path, description = "School uuid"),
676667 ("module" = String, Path, description = "Module name, as `GET /modules/catalog` publishes it"),
677668 ),
678669 responses(
@@ -685,17 +676,17 @@ async fn enable_school_module(
685676 async fn disable_school_module(
686677 State(st): State<AppState>,
687678 RequireBuilder(_builder): RequireBuilder,
688- Path((slug, module)): Path<(String, String)>,
679+ Path((id, module)): Path<(String, String)>,
689680 ) -> Result<Json<ModulesResponse>, AppError> {
690- let slug = path_slug(&slug)?;
681+ let id = path_id(&id)?;
691682 let module = path_module(&module)?;
692- let mut modules = school_modules(&slug, st.tenants.control()).await?;
683+ let mut modules = school_modules(&id, st.tenants.control()).await?;
693684 if !modules.contains(module) {
694685 return Ok(Json(ModulesResponse::new(&modules)));
695686 }
696687 refuse_if_needed(module, &modules)?;
697688 modules.remove(module);
698- store_modules(&st, &slug, modules).await
689+ store_modules(&st, &id, modules).await
699690 }
700691
701692 /// Re-sell a school's whole shelf in one call: any mix of modules and packages,
@@ -708,10 +699,10 @@ async fn disable_school_module(
708699 /// the whole request is accepted.
709700 #[utoipa::path(
710701 patch,
711- path = "/schools/{slug}/modules",
702+ path = "/schools/{id}/modules",
712703 tag = "builder",
713704 security(("session_cookie" = [])),
714- params(("slug" = String, Path, description = "School slug")),
705+ params(("id" = String, Path, description = "School uuid")),
715706 request_body = PatchModules,
716707 responses(
717708 (status = 200, description = "The school's modules after the change", body = ModulesResponse),
@@ -725,10 +716,10 @@ async fn disable_school_module(
725716 async fn patch_school_modules(
726717 State(st): State<AppState>,
727718 RequireBuilder(_builder): RequireBuilder,
728- Path(slug): Path<String>,
719+ Path(id): Path<String>,
729720 Json(req): Json<PatchModules>,
730721 ) -> Result<Json<ModulesResponse>, AppError> {
731- let slug = path_slug(&slug)?;
722+ let id = path_id(&id)?;
732723 let enable = req.side(req.enable.as_deref(), req.enable_packages.as_deref())?;
733724 let disable = req.side(req.disable.as_deref(), req.disable_packages.as_deref())?;
734725 // A name pulled both ways has no defensible resolution, and picking one
@@ -742,7 +733,7 @@ async fn patch_school_modules(
742733 .into());
743734 }
744735
745- let current = school_modules(&slug, st.tenants.control()).await?;
736+ let current = school_modules(&id, st.tenants.control()).await?;
746737 let mut result = current.clone();
747738 for module in enable.iter() {
748739 result.insert(module);
@@ -757,7 +748,7 @@ async fn patch_school_modules(
757748 if result == current {
758749 return Ok(Json(ModulesResponse::new(&current)));
759750 }
760- store_modules(&st, &slug, result).await
751+ store_modules(&st, &id, result).await
761752 }
762753
763754 /// Reset an admin's password inside a school — the "we are locked out" call.
@@ -765,10 +756,10 @@ async fn patch_school_modules(
765756 /// not survive the reset. Works on a suspended school.
766757 #[utoipa::path(
767758 post,
768- path = "/schools/{slug}/admin-password",
759+ path = "/schools/{id}/admin-password",
769760 tag = "builder",
770761 security(("session_cookie" = [])),
771- params(("slug" = String, Path, description = "School slug")),
762+ params(("id" = String, Path, description = "School uuid")),
772763 request_body = AdminPassword,
773764 responses(
774765 (status = 204, description = "Password reset; that account's sessions are revoked"),
@@ -782,11 +773,11 @@ async fn patch_school_modules(
782773 async fn reset_admin_password(
783774 State(st): State<AppState>,
784775 RequireBuilder(_builder): RequireBuilder,
785- Path(slug): Path<String>,
776+ Path(id): Path<String>,
786777 Json(req): Json<AdminPassword>,
787778 ) -> Result<StatusCode, AppError> {
788- let slug = path_slug(&slug)?;
789- let (db, _status) = st.tenants.get_any_status(&slug).await?;
779+ let id = path_id(&id)?;
780+ let (db, _status) = st.tenants.get_any_status(&id).await?;
790781 let user = school_admin(&req.username, &db).await?;
791782 let password_hash = Password::try_new(&req.password)?.hash_async().await?;
792783
@@ -806,16 +797,16 @@ async fn reset_admin_password(
806797 }
807798
808799 /// Enter a school as one of its admins — support access, with the school's own
809-/// session cookie (`<slug>.<token>`) and no builder power inside it.
800+/// session cookie (`<uuid>.<token>`) and no builder power inside it.
810801 ///
811802 /// Refused on a suspended school (`403`): a suspension closes the school's
812803 /// doors, and this is one of them. Un-suspend it first.
813804 #[utoipa::path(
814805 post,
815- path = "/schools/{slug}/enter",
806+ path = "/schools/{id}/enter",
816807 tag = "builder",
817808 security(("session_cookie" = [])),
818- params(("slug" = String, Path, description = "School slug")),
809+ params(("id" = String, Path, description = "School uuid")),
819810 request_body = EnterSchool,
820811 responses(
821812 (status = 200, description = "Entered; that school's session cookie is set", body = UserResponse),
@@ -830,11 +821,11 @@ async fn enter_school(
830821 State(st): State<AppState>,
831822 RequireBuilder(_builder): RequireBuilder,
832823 jar: CookieJar,
833- Path(slug): Path<String>,
824+ Path(id): Path<String>,
834825 Json(req): Json<EnterSchool>,
835826 ) -> Result<(CookieJar, Json<UserResponse>), AppError> {
836- let slug = path_slug(&slug)?;
837- let (db, status) = st.tenants.get_any_status(&slug).await?;
827+ let id = path_id(&id)?;
828+ let (db, status) = st.tenants.get_any_status(&id).await?;
838829 if status == SchoolStatus::Suspended {
839830 return Err(AppError::Forbidden("school is suspended"));
840831 }
@@ -842,7 +833,7 @@ async fn enter_school(
842833
843834 let session = service::session::create(&db, user.get_id()).await?;
844835 let cookie = session_cookie(
845- format!("{slug}.{}", session.token().as_str()),
836+ format!("{id}.{}", session.token().as_str()),
846837 st.cookie_secure,
847838 );
848839 Ok((jar.add(cookie), Json(UserResponse::new(&user))))
src/web/chatbot.rsmodified+6 -6
@@ -21,7 +21,7 @@
2121 use std::time::Duration;
2222
2323 use crate::tenant::ResolvedTenant;
24-use crate::web::tenant_state::{SchoolSlug, State, TenantExt};
24+use crate::web::tenant_state::{SchoolIdCookie, State, TenantExt};
2525 use axum::Json;
2626 use axum::extract::{Path, Query};
2727 use axum::http::StatusCode;
@@ -379,7 +379,7 @@ async fn list_messages(
379379 )]
380380 async fn send_message(
381381 State(st): State<AppState>,
382- SchoolSlug(slug): SchoolSlug,
382+ SchoolIdCookie(school): SchoolIdCookie,
383383 tenant: ResolvedTenant,
384384 CurrentUser(user): CurrentUser,
385385 Path(id): Path<String>,
@@ -387,7 +387,7 @@ async fn send_message(
387387 ) -> Result<Response, AppError> {
388388 // Charged first: a rejected turn must cost nothing and leave no row.
389389 st.chatbot_limit
390- .enforce_user(&scoped_key(&slug, user.get_id().key().as_str()))?;
390+ .enforce_user(&scoped_key(&school, user.get_id().key().as_str()))?;
391391
392392 let thread = own_thread(&id, user.get_id(), &st.db).await?;
393393 let settings = service::settings::load(&st.db).await?;
@@ -447,7 +447,7 @@ async fn send_message(
447447 // request was already resolved into, and one without the other is how
448448 // an answer lands in the wrong school.
449449 TenantExt {
450- slug,
450+ id: school,
451451 db: st.db.clone(),
452452 modules: tenant.modules,
453453 },
@@ -573,7 +573,7 @@ async fn fetch_reply(
573573 })?;
574574
575575 let raw = bridge
576- .dispatch(&tenant.slug, AI_CHAT_CAPABILITY, payload)
576+ .dispatch(&tenant.id, AI_CHAT_CAPABILITY, payload)
577577 .await
578578 .map_err(failure_code)?;
579579 let reply: ChatReplyPayload = serde_json::from_value(raw).map_err(|err| {
@@ -927,7 +927,7 @@ mod tests {
927927 }
928928
929929 #[tokio::test]
930- async fn failure_codes_are_stable_slugs() {
930+ async fn failure_codes_are_stable() {
931931 assert_eq!(
932932 failure_code(AiError::NoWorker("chat.reply".into())),
933933 "unavailable"
src/web/exam_ws.rsmodified+8 -8
@@ -56,7 +56,7 @@
5656
5757 use std::time::Duration;
5858
59-use crate::web::tenant_state::{SchoolSlug, State};
59+use crate::web::tenant_state::{SchoolIdCookie, State};
6060 use axum::extract::Path;
6161 use axum::extract::ws::{WebSocket, WebSocketUpgrade};
6262 use axum::response::Response;
@@ -75,7 +75,7 @@ use crate::service::exam_attempt::{
7575 set_left, writable_attempt,
7676 };
7777 use crate::state::AppState;
78-use crate::tenant::Slug;
78+use crate::tenant::SchoolId;
7979 use crate::validate::validate_required;
8080 use crate::web::CurrentUser;
8181 use crate::web::room::{self, Incoming, RoomClosed, send, with_client_seq};
@@ -131,7 +131,7 @@ enum ClientMessage {
131131 /// stamp a student who was already reconnecting.
132132 pub async fn attempt_ws(
133133 State(st): State<AppState>,
134- SchoolSlug(slug): SchoolSlug,
134+ SchoolIdCookie(school): SchoolIdCookie,
135135 CurrentUser(user): CurrentUser,
136136 Path(id): Path<String>,
137137 ws: WebSocketUpgrade,
@@ -147,7 +147,7 @@ pub async fn attempt_ws(
147147 crate::service::exam_attempt::require_open(&st.db, &exam).await?;
148148
149149 let user_id = *user.get_id();
150- Ok(ws.on_upgrade(move |socket| room(socket, st, slug, exam, attempt, user_id)))
150+ Ok(ws.on_upgrade(move |socket| room(socket, st, school, exam, attempt, user_id)))
151151 }
152152
153153 /// The room loop: state ticks out, answer/finish/ping in, until the socket
@@ -156,7 +156,7 @@ pub async fn attempt_ws(
156156 async fn room(
157157 mut socket: WebSocket,
158158 st: AppState,
159- slug: Slug,
159+ school: SchoolId,
160160 exam: Exam,
161161 attempt: ExamAttempt,
162162 user: UserId,
@@ -168,7 +168,7 @@ async fn room(
168168 let _connected = room::Connected::open(
169169 &st.metrics,
170170 "exam_room",
171- slug.as_str(),
171+ school.as_str(),
172172 exam_id.key().as_str(),
173173 );
174174 // Join: this socket counts as presence in the sitting's room until it
@@ -178,7 +178,7 @@ async fn room(
178178 // predate a stamp that raced the upgrade; clearing regardless is what
179179 // keeps a reconnecting student unmarked. Best-effort — a failed clear
180180 // leaves the stamp for the next join or the teacher's door.
181- st.exam_presence.enter(&slug, attempt_id.key().as_str());
181+ st.exam_presence.enter(&school, attempt_id.key().as_str());
182182 if let Err(err) = set_left(&st.db, attempt, None).await {
183183 tracing::warn!("exam room could not clear left_at on join: {err}");
184184 }
@@ -215,7 +215,7 @@ async fn room(
215215 // stamped. With `allow_rejoin` off this is what locks further
216216 // answering. Best-effort: a failed stamp only means it goes
217217 // unrecorded.
218- if st.exam_presence.leave(&slug, attempt_id.key().as_str()) {
218+ if st.exam_presence.leave(&school, attempt_id.key().as_str()) {
219219 crate::db::exam_attempt::stamp_left_if_running(&st.db, &attempt_id, Timestamp::now())
220220 .await
221221 .unwrap_or_else(|err| {
src/web/extractor.rsmodified+5 -5
@@ -154,7 +154,7 @@ where
154154 /// The deployment operator behind a `builder.<token>` cookie, resolved against
155155 /// the **control** database. Any school cookie is `401` here, and this cookie
156156 /// is `401` on every school surface (`resolve_tenant` refuses the `builder`
157-/// prefix as a slug) — the two principals share a cookie name and nothing else.
157+/// prefix as a school id) — the two principals share a cookie name and nothing else.
158158 pub struct RequireBuilder(pub Builder);
159159
160160 impl<S> FromRequestParts<S> for RequireBuilder
@@ -189,14 +189,14 @@ where
189189 }
190190 }
191191
192-/// The cookie prefix a builder session carries in place of a school slug.
193-/// `Slug::try_new` reserves this word, so it can never also name a school.
192+/// The cookie prefix a builder session carries in place of a school uuid.
193+/// A uuid parse never accepts this word, so it can never also name a school.
194194 pub const BUILDER_COOKIE_PREFIX: &str = "builder";
195195
196196 /// The cookie prefix a not-yet-bound person session carries in place of a
197-/// school slug: a person who belongs to several schools logs into the
197+/// school uuid: a person who belongs to several schools logs into the
198198 /// control plane first and names a school afterwards (`POST /auth/school`).
199-/// `Slug::try_new` reserves this word (`RESERVED_SLUGS`), so it can never
199+/// A uuid parse never accepts this word, so it can never
200200 /// also name a school — a `person.` cookie is `401` on every school surface,
201201 /// exactly like `builder.`.
202202 pub const PERSON_COOKIE_PREFIX: &str = "person";
src/web/insights.rsmodified+9 -9
@@ -213,9 +213,9 @@ async fn compute_student(
213213 if !bridge.has_capability(AI_INSIGHT_STUDENT_CAPABILITY) {
214214 return Ok(ai_unavailable("no AI service is connected right now"));
215215 }
216- let slug = tenant.slug.clone();
216+ let school = tenant.id;
217217 tokio::spawn(async move {
218- match insight::compute_student(&bridge, &slug, &request).await {
218+ match insight::compute_student(&bridge, &school, &request).await {
219219 Ok(answer) => tracing::info!(
220220 "insight.student answered for {}: {} signal(s), {} recommendation(s)",
221221 request.user_id,
@@ -286,10 +286,10 @@ async fn refresh(
286286 return Ok(ai_unavailable("no AI service is connected right now"));
287287 }
288288
289- let slug = tenant.slug.clone();
289+ let school = tenant.id;
290290 tokio::spawn(async move {
291291 let source = request.roster_source.clone();
292- match insight::refresh(&bridge, &slug, &request).await {
292+ match insight::refresh(&bridge, &school, &request).await {
293293 Ok(answer) => tracing::info!(
294294 "insight.refresh ({source} roster) answered: {} requested, {} computed, {} skipped, {} failed",
295295 answer.requested.unwrap_or(0),
@@ -401,11 +401,11 @@ async fn generate_report(
401401 return Ok(ai_unavailable("no AI service is connected right now"));
402402 }
403403 let Some(school) =
404- db::insight::school_identity(st.tenants.control(), tenant.slug.as_str()).await?
404+ db::insight::school_identity(st.tenants.control(), &tenant.id).await?
405405 else {
406406 return Err(AppError::Internal(format!(
407407 "the resolved school `{}` has no control row",
408- tenant.slug.as_str()
408+ tenant.id.as_str()
409409 )));
410410 };
411411 let request = ReportRequest {
@@ -419,7 +419,7 @@ async fn generate_report(
419419 profiles: db::insight::all_profiles(&st.db).await?,
420420 runs: db::insight::runs_for_report(&st.db, &run_day).await?,
421421 };
422- let answer = match insight::report(&bridge, &tenant.slug, &request).await {
422+ let answer = match insight::report(&bridge, &tenant.id, &request).await {
423423 Ok(answer) => answer,
424424 Err(AiError::Remote { code, message }) => {
425425 tracing::warn!("insight.report refused: {code}: {message}");
@@ -842,7 +842,7 @@ async fn purge_departed(
842842 ))
843843 }
844844
845-/// The deployment's active schools, by slug — the directory a shared AI fleet
845+/// The deployment's active schools, by school — the directory a shared AI fleet
846846 /// schedules over.
847847 ///
848848 /// This is the one operation of the family that is not school-scoped, and the
@@ -858,7 +858,7 @@ async fn purge_departed(
858858 tag = "insights",
859859 security(("session_cookie" = [])),
860860 responses(
861- (status = 200, description = "Every active school on this deployment, by slug", body = SchoolDirectory),
861+ (status = 200, description = "Every active school on this deployment, by school", body = SchoolDirectory),
862862 (status = 401, description = "Not authenticated as a builder", body = ErrorResponse),
863863 ),
864864 )]
src/web/limits.rsmodified+0 -11
@@ -31,14 +31,6 @@ pub fn routes() -> OpenApiRouter<AppState> {
3131 /// Account fields: credentials, profile, and the closed role set.
3232 #[derive(Serialize, ToSchema)]
3333 struct UserLimits {
34- /// The school slug the login and registration forms ask for, in front of
35- /// the dot in the session cookie. Lowercase `a-z`, `0-9` and `-`, starting
36- /// with a letter or digit.
37- min_slug_len: usize,
38- max_slug_len: usize,
39- /// Slugs no school may take — they name the builder cookie prefix and the
40- /// control database.
41- reserved_slugs: Vec<&'static str>,
4234 /// A school's display name, set by the vendor when the school is created.
4335 max_school_name_len: usize,
4436 min_username_len: usize,
@@ -536,9 +528,6 @@ impl LimitsResponse {
536528 fn new(st: &AppState) -> Self {
537529 Self {
538530 user: UserLimits {
539- min_slug_len: MIN_SLUG_LEN,
540- max_slug_len: MAX_SLUG_LEN,
541- reserved_slugs: crate::tenant::RESERVED_SLUGS.to_vec(),
542531 max_school_name_len: MAX_SCHOOL_NAME_LEN,
543532 min_username_len: MIN_USERNAME_LEN,
544533 max_username_len: MAX_USERNAME_LEN,
src/web/modules.rsmodified+1 -1
@@ -1,7 +1,7 @@
11 //! Module entitlements as data, on the school side of the line.
22 //!
33 //! Two reads, no writes — selling a module is the vendor's act and lives on
4-//! `/schools/{slug}/modules` in [`crate::web::builder`]. What stands here is
4+//! `/schools/{id}/modules` in [`crate::web::builder`]. What stands here is
55 //! what a client needs to draw the product: the deployment's catalog (which
66 //! modules exist, what each one needs, how they are packaged) and the caller's
77 //! own switched-on set, so a frontend hides a nest the school never bought
src/web/podcast.rsmodified+5 -5
@@ -69,7 +69,7 @@ use crate::error::{AppError, ErrorResponse, ValidationError};
6969 use crate::service::course_note_file as note_files;
7070 use crate::service::podcast_job as jobs;
7171 use crate::state::AppState;
72-use crate::web::tenant_state::{SchoolSlug, State};
72+use crate::web::tenant_state::{SchoolIdCookie, State};
7373
7474 use super::{CurrentUser, Page, PageParams, ai_unavailable, pump};
7575
@@ -179,7 +179,7 @@ struct CancelVerdict {
179179 )]
180180 async fn submit(
181181 State(st): State<AppState>,
182- SchoolSlug(slug): SchoolSlug,
182+ SchoolIdCookie(school): SchoolIdCookie,
183183 CurrentUser(user): CurrentUser,
184184 Json(req): Json<SubmitPodcast>,
185185 ) -> Result<Response, AppError> {
@@ -226,7 +226,7 @@ async fn submit(
226226 format: req.format.clone(),
227227 user_id: user.get_id().key(),
228228 };
229- match podcast::submit(&bridge, &slug, payload).await {
229+ match podcast::submit(&bridge, &school, payload).await {
230230 // The echo is checked, not trusted: this id is the only handle every
231231 // later call uses, so an answer about some other job is a protocol
232232 // failure, not a receipt.
@@ -556,7 +556,7 @@ async fn audio(
556556 )]
557557 async fn cancel(
558558 State(st): State<AppState>,
559- SchoolSlug(slug): SchoolSlug,
559+ SchoolIdCookie(school): SchoolIdCookie,
560560 CurrentUser(user): CurrentUser,
561561 Path(id): Path<String>,
562562 ) -> Result<Response, AppError> {
@@ -582,7 +582,7 @@ async fn cancel(
582582 };
583583 match podcast::cancel(
584584 &bridge,
585- &slug,
585+ &school,
586586 PodcastCancelPayload {
587587 job_id: job_id.clone(),
588588 },
src/web/rag.rsmodified+9 -9
@@ -43,7 +43,7 @@
4343 use std::time::Duration;
4444
4545 use crate::tenant::ResolvedTenant;
46-use crate::web::tenant_state::{SchoolSlug, State, TenantExt};
46+use crate::web::tenant_state::{SchoolIdCookie, State, TenantExt};
4747 use axum::Json;
4848 use axum::extract::{Path, Query};
4949 use axum::http::StatusCode;
@@ -462,7 +462,7 @@ async fn list_messages(
462462 )]
463463 async fn send_message(
464464 State(st): State<AppState>,
465- SchoolSlug(slug): SchoolSlug,
465+ SchoolIdCookie(school): SchoolIdCookie,
466466 tenant: ResolvedTenant,
467467 CurrentUser(user): CurrentUser,
468468 Path(id): Path<String>,
@@ -475,7 +475,7 @@ async fn send_message(
475475 // Then the tier. Charged before anything is written, so a refused turn
476476 // leaves no row behind.
477477 st.rag_limit
478- .enforce_user(&scoped_key(&slug, user.get_id().key().as_str()))?;
478+ .enforce_user(&scoped_key(&school, user.get_id().key().as_str()))?;
479479
480480 let settings = service::settings::load(&st.db).await?;
481481 let reply_cap = content_cap(&settings);
@@ -538,7 +538,7 @@ async fn send_message(
538538 // request was already resolved into, and one without the other is how
539539 // an answer lands in the wrong school.
540540 TenantExt {
541- slug,
541+ id: school,
542542 db: st.db.clone(),
543543 modules: tenant.modules,
544544 },
@@ -619,7 +619,7 @@ async fn answer_turn(
619619 let settled = match crate::ai::rag_chat::answer(
620620 &db,
621621 &bridge,
622- &tenant.slug,
622+ &tenant.id,
623623 &thread,
624624 &fresh,
625625 prompt.get_content().as_str().to_string(),
@@ -1107,7 +1107,7 @@ fn resolve_study_pair(
11071107 )]
11081108 async fn summarize(
11091109 State(st): State<AppState>,
1110- SchoolSlug(slug): SchoolSlug,
1110+ SchoolIdCookie(school): SchoolIdCookie,
11111111 CurrentUser(user): CurrentUser,
11121112 Json(req): Json<StudyScopeRequest>,
11131113 ) -> Result<Response, AppError> {
@@ -1134,7 +1134,7 @@ async fn summarize(
11341134 asker_role: user.get_role().as_str().to_string(),
11351135 };
11361136
1137- match rag_study::summarize(&bridge, &slug, payload).await {
1137+ match rag_study::summarize(&bridge, &school, payload).await {
11381138 Ok(reply) => Ok(Json(RagSummarizeResponse::from(reply)).into_response()),
11391139 Err(code) => Ok(failure(&code)),
11401140 }
@@ -1169,7 +1169,7 @@ async fn summarize(
11691169 )]
11701170 async fn questions(
11711171 State(st): State<AppState>,
1172- SchoolSlug(slug): SchoolSlug,
1172+ SchoolIdCookie(school): SchoolIdCookie,
11731173 CurrentUser(user): CurrentUser,
11741174 Json(req): Json<QuestionsRequest>,
11751175 ) -> Result<Response, AppError> {
@@ -1199,7 +1199,7 @@ async fn questions(
11991199 seed_question: req.seed_question,
12001200 };
12011201
1202- match rag_study::questions(&bridge, &slug, payload).await {
1202+ match rag_study::questions(&bridge, &school, payload).await {
12031203 Ok(reply) => Ok(Json(RagQuestionsResponse::from(reply)).into_response()),
12041204 Err(code) => Ok(failure(&code)),
12051205 }
src/web/room.rsmodified+4 -3
@@ -49,12 +49,13 @@ impl Connected {
4949 /// `kind` is the room's telemetry name (`exam_room`, `board`), `id` a
5050 /// **resource** id — the exam, the board — and never the person on the
5151 /// socket, which telemetry may not carry.
52- pub(crate) fn open(metrics: &Metrics, kind: &'static str, school: &str, id: &str) -> Self {
52+ pub(crate) fn open(metrics: &Metrics, kind: &'static str, school: impl AsRef<str>, id: &str) -> Self {
5353 metrics
5454 .ws_connections
5555 .add(1, &[opentelemetry::KeyValue::new("kind", kind)]);
56- // `id` is a resource id (exam, board) and `school` a slug — both are
57- // allowed on telemetry. A user id never is.
56+ // `id` is a resource id (exam, board) and `school` the school uuid —
57+ // both are allowed on telemetry. A user id never is.
58+ let school = school.as_ref();
5859 tracing::info!(kind, school, id, "websocket opened");
5960 Self {
6061 metrics: metrics.clone(),
src/web/school.rsmodified+4 -6
@@ -2,8 +2,7 @@
22 //!
33 //! `GET /schools` is the vendor registry and answers only a builder cookie.
44 //! This route is the inverse: the school the session cookie is already bound
5-//! to, readable by every authenticated role. The uuid is the identity; the
6-//! slug stays off the wire.
5+//! to, readable by every authenticated role. The uuid is the identity; nothing but the name is on the wire besides the uuid.
76
87 use axum::Json;
98 use serde::Serialize;
@@ -23,8 +22,7 @@ pub fn routes() -> OpenApiRouter<AppState> {
2322
2423 /// The school behind the session cookie. `id` is the registry uuid — the
2524 /// identity the database name and every structural reference mint from — and
26-/// `name` is the display name. The slug is not here: it is a label, not an
27-/// identity, and this response does not publish it.
25+/// `name` is the display name. Nothing but the uuid and the display name is published.
2826 #[derive(Serialize, ToSchema)]
2927 struct SchoolIdentity {
3028 #[schema(example = "019732e3-7b00-7000-8000-00000000dead")]
@@ -53,12 +51,12 @@ async fn current_school(
5351 tenant: ResolvedTenant,
5452 _user: CurrentUser,
5553 ) -> Result<Json<SchoolIdentity>, AppError> {
56- let school = School::read(&tenant.slug, st.tenants.control())
54+ let school = School::read(&tenant.id, st.tenants.control())
5755 .await?
5856 .ok_or_else(|| {
5957 AppError::Internal(format!(
6058 "the resolved school `{}` has no control row",
61- tenant.slug
59+ tenant.id
6260 ))
6361 })?;
6462 Ok(Json(SchoolIdentity {
src/web/tenant_state.rsmodified+28 -28
@@ -21,7 +21,7 @@ use crate::database::Database;
2121 use crate::error::AppError;
2222 use crate::module::ModuleSet;
2323 use crate::state::AppState;
24-use crate::tenant::{ResolvedTenant, Slug};
24+use crate::tenant::{ResolvedTenant, SchoolId};
2525
2626 /// The school a request has already been resolved into, injected as a request
2727 /// extension by an in-process caller that has no cookie — today only the AI
@@ -30,16 +30,15 @@ use crate::tenant::{ResolvedTenant, Slug};
3030 /// [`crate::web::extractor::AiPrincipal`].
3131 #[derive(Clone)]
3232 pub struct TenantExt {
33- pub slug: Slug,
33+ pub id: SchoolId,
3434 pub db: Database,
3535 pub modules: ModuleSet,
3636 }
3737
3838 /// Split a `session` cookie into its school part and its token. `builder` in
39-/// the first position is the deployment operator; anything else is a slug.
40-///
41-/// Splits at the **first** dot, so a token can never be mistaken for a slug no
42-/// matter what it contains (it is hex today, and this does not depend on that).
39+/// the first position is the deployment operator; anything else is a school
40+/// uuid. Splits at the **first** dot, so a token can never be mistaken for
41+/// the school no matter what it contains.
4342 pub fn split_cookie(value: &str) -> Option<(&str, &str)> {
4443 let (prefix, token) = value.split_once('.')?;
4544 (!prefix.is_empty() && !token.is_empty()).then_some((prefix, token))
@@ -64,7 +63,7 @@ where
6463 }
6564 if let Some(tenant) = parts.extensions.get::<TenantExt>() {
6665 return Ok(ResolvedTenant {
67- slug: tenant.slug.clone(),
66+ id: tenant.id,
6867 db: tenant.db.clone(),
6968 modules: tenant.modules.clone(),
7069 });
@@ -77,16 +76,17 @@ where
7776 // at all. Both are `401` here: the builder surface is a different extractor
7877 // (`RequireBuilder`), and this one must never let it in.
7978 let (prefix, _) = split_cookie(cookie.value()).ok_or(AppError::Unauthorized)?;
80- let slug = Slug::try_new(prefix).map_err(|_| AppError::Unauthorized)?;
79+ let id = SchoolId::try_parse(prefix).map_err(|_| AppError::Unauthorized)?;
8180
8281 let app = AppState::from_ref(state);
83- let resolved = app.tenants.resolve(&slug).await?;
82+ let resolved = app.tenants.resolve(&id).await?;
8483 // The one caller-derived label telemetry is allowed to carry: which school,
8584 // never which user. The span field and the metric slot are set together so
86- // a trace and its latency sample agree.
87- tracing::Span::current().record("school", slug.as_str());
85+ // a trace and its latency sample agree. Field name stays `school`.
86+ let label = id.as_str();
87+ tracing::Span::current().record("school", label.as_str());
8888 if let Some(slot) = parts.extensions.get::<crate::telemetry::SchoolSlot>() {
89- slot.set(slug.as_str());
89+ slot.set(&label);
9090 }
9191 // Memoized on the request, not just returned: the next extractor on this
9292 // same request (and the module gate ahead of both) reuses this verdict
@@ -115,7 +115,7 @@ where
115115 let app = AppState::from_ref(state);
116116 Ok(State(AppState {
117117 db: tenant.db,
118- files_path: school_files_path(&app.files_path, &tenant.slug),
118+ files_path: school_files_path(&app.files_path, &tenant.id),
119119 ..app
120120 }))
121121 }
@@ -138,9 +138,9 @@ where
138138
139139 /// Just the school, for the handlers that need it as a key prefix (the exam
140140 /// presence map, the whiteboard hub) rather than as a database handle.
141-pub struct SchoolSlug(pub Slug);
141+pub struct SchoolIdCookie(pub SchoolId);
142142
143-impl<S> FromRequestParts<S> for SchoolSlug
143+impl<S> FromRequestParts<S> for SchoolIdCookie
144144 where
145145 S: Send + Sync,
146146 AppState: FromRef<S>,
@@ -148,15 +148,15 @@ where
148148 type Rejection = AppError;
149149
150150 async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
151- Ok(SchoolSlug(resolve_tenant(parts, state).await?.slug))
151+ Ok(SchoolIdCookie(resolve_tenant(parts, state).await?.id))
152152 }
153153 }
154154
155155 /// Where a school's uploaded blobs live: one directory per school under the
156-/// deployment's `FILES_PATH`. The slug's character set is what makes this a
157-/// plain `join` — it can contain no separator and no `..`.
158-pub fn school_files_path(root: &std::path::Path, slug: &Slug) -> PathBuf {
159- root.join(slug.as_str())
156+/// deployment's `FILES_PATH`. The id's hyphenated form contains no separator
157+/// and no `..`, so this is a plain `join`.
158+pub fn school_files_path(root: &std::path::Path, id: &SchoolId) -> PathBuf {
159+ root.join(id.as_str())
160160 }
161161
162162 #[cfg(test)]
@@ -171,7 +171,7 @@ mod tests {
171171 use crate::database::init_test_tenants;
172172 use crate::db::session;
173173 use crate::domain::user::{Password, Username};
174- use crate::tenant::DEMO_SLUG;
174+ use crate::tenant::DEMO_SCHOOL_ID;
175175 use crate::web::{CurrentUser, RequireBuilder};
176176
177177 async fn school_surface(State(_): State<AppState>, CurrentUser(_): CurrentUser) -> StatusCode {
@@ -187,7 +187,7 @@ mod tests {
187187 async fn harness() -> (Router, String, String, crate::tenant::Tenants) {
188188 let tenants = init_test_tenants().await;
189189 let school = tenants
190- .get(&Slug::try_new(DEMO_SLUG).unwrap())
190+ .get(&SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap())
191191 .await
192192 .expect("the demo school");
193193
@@ -195,7 +195,7 @@ mod tests {
195195 .await
196196 .unwrap();
197197 let session = session::create(&school, user.get_id()).await.unwrap();
198- let school_cookie = format!("session={DEMO_SLUG}.{}", session.token().as_str());
198+ let school_cookie = format!("session={DEMO_SCHOOL_ID}.{}", session.token().as_str());
199199
200200 crate::service::builder::ensure(
201201 tenants.control(),
@@ -273,7 +273,7 @@ mod tests {
273273
274274 // A cookie with no school part names nothing resolvable — including the
275275 // pre-tenancy shape, which is deliberately not accepted anywhere.
276- let bare = school.replace(&format!("{DEMO_SLUG}."), "");
276+ let bare = school.replace(&format!("{DEMO_SCHOOL_ID}."), "");
277277 for uri in ["/school", "/builder"] {
278278 assert_eq!(
279279 status(&app, uri, Some(&bare)).await,
@@ -294,7 +294,7 @@ mod tests {
294294 #[tokio::test]
295295 async fn a_suspension_refuses_a_live_session() {
296296 let (app, school, _, tenants) = harness().await;
297- let demo = Slug::try_new(DEMO_SLUG).unwrap();
297+ let demo = SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap();
298298 assert_eq!(status(&app, "/school", Some(&school)).await, StatusCode::OK);
299299
300300 tenants
@@ -325,7 +325,7 @@ mod tests {
325325 #[tokio::test]
326326 async fn a_request_resolves_its_school_exactly_once() {
327327 let tenants = init_test_tenants().await;
328- let demo = Slug::try_new(DEMO_SLUG).unwrap();
328+ let demo = SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap();
329329 let state = AppState {
330330 db: tenants.control().clone(),
331331 tenants: tenants.clone(),
@@ -341,7 +341,7 @@ mod tests {
341341 };
342342 let request = Request::builder()
343343 .uri("/school")
344- .header("cookie", format!("session={DEMO_SLUG}.whatever"))
344+ .header("cookie", format!("session={DEMO_SCHOOL_ID}.whatever"))
345345 .body(Body::empty())
346346 .unwrap();
347347 let (mut parts, _) = request.into_parts();
@@ -361,7 +361,7 @@ mod tests {
361361 let second = resolve_tenant(&mut parts, &state)
362362 .await
363363 .expect("a second read would have seen the suspension and refused");
364- assert_eq!(second.slug, demo);
364+ assert_eq!(second.id, demo);
365365 }
366366
367367 #[test]
src/web/users.rsmodified+6 -6
@@ -1,4 +1,4 @@
1-use crate::web::tenant_state::{SchoolSlug, State};
1+use crate::web::tenant_state::{SchoolIdCookie, State};
22 use axum::Json;
33 use axum::extract::{DefaultBodyLimit, Multipart, Path, Query};
44 use axum::http::StatusCode;
@@ -416,7 +416,7 @@ struct CreateUser {
416416 )]
417417 async fn create_user(
418418 State(st): State<AppState>,
419- SchoolSlug(slug): SchoolSlug,
419+ SchoolIdCookie(school): SchoolIdCookie,
420420 _admin: RequireAdmin,
421421 Json(req): Json<CreateUser>,
422422 ) -> Result<(StatusCode, Json<UserResponse>), AppError> {
@@ -467,7 +467,7 @@ async fn create_user(
467467 student_number,
468468 )
469469 .await?;
470- crate::service::person::link_school(control, person.get_id(), &slug).await?;
470+ crate::service::person::link_school(control, person.get_id(), &school).await?;
471471 Ok((StatusCode::CREATED, Json(UserResponse::new(&user))))
472472 }
473473
@@ -670,7 +670,7 @@ async fn update_user_preferences(
670670 )]
671671 async fn set_role(
672672 State(st): State<AppState>,
673- SchoolSlug(slug): SchoolSlug,
673+ SchoolIdCookie(school): SchoolIdCookie,
674674 RequireAdmin(admin): RequireAdmin,
675675 Path(id): Path<String>,
676676 Json(req): Json<SetRole>,
@@ -695,7 +695,7 @@ async fn set_role(
695695 // stroke came back refused.
696696 for board in boards {
697697 st.board_hub.publish(
698- &slug,
698+ &school,
699699 board.get_id().key().as_str(),
700700 json!({
701701 "type": "participants",
@@ -710,7 +710,7 @@ async fn set_role(
710710 );
711711 if let Some(closed_at) = board.get_closed_at() {
712712 st.board_hub.publish(
713- &slug,
713+ &school,
714714 board.get_id().key().as_str(),
715715 json!({"type": "closed", "closed_at": closed_at.as_millis()}).to_string(),
716716 );
tests/ai_bridge.rsmodified+48 -53
@@ -19,7 +19,7 @@ use hezarfen_backend::ai::protocol::{
1919 use hezarfen_backend::ai::{AiBridge, AiError, BridgeConfig};
2020 use hezarfen_backend::constant::{AI_ALPN, AI_MAX_CONCURRENT_PER_WORKER, AI_PROTOCOL};
2121 use hezarfen_backend::module::ModuleSet;
22-use hezarfen_backend::tenant::{DEMO_SLUG, Slug};
22+use hezarfen_backend::tenant::{DEMO_SCHOOL_ID, SchoolId};
2323 use serde_json::{Value, json};
2424
2525 const TOKEN: &str = "shared-ai-token";
@@ -71,8 +71,8 @@ fn client_endpoint(bridge: &AiBridge) -> quinn::Endpoint {
7171 }
7272
7373 /// The demo school, which every dispatch in this suite is made on behalf of.
74-fn demo() -> Slug {
75- Slug::try_new(DEMO_SLUG).expect("the demo slug")
74+fn demo() -> SchoolId {
75+ SchoolId::try_parse(DEMO_SCHOOL_ID).expect("the demo slug")
7676 }
7777
7878 fn hello(service: &str, capabilities: &[&str]) -> Hello {
@@ -1519,7 +1519,7 @@ async fn api_read(conn: &quinn::Connection, request: ApiRequest) -> ApiResponse
15191519
15201520 /// A `GET` of `path` as `on_behalf_of` (or as the service itself).
15211521 fn read_of(path: &str, on_behalf_of: Option<&str>) -> ApiRequest {
1522- read_of_school(DEMO_SLUG, path, on_behalf_of)
1522+ read_of_school(DEMO_SCHOOL_ID, path, on_behalf_of)
15231523 }
15241524
15251525 /// The same, naming the school explicitly — the tenancy tests below.
@@ -1841,11 +1841,10 @@ async fn an_index_dispatch_names_the_notes_own_school_and_stores_the_answer_ther
18411841 await_workers(&bridge, 1).await;
18421842
18431843 let (app, demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await;
1844- let beta = Slug::try_new("beta").unwrap();
1844+ let beta = SchoolId::try_parse(hezarfen_backend::tenant::BETA_SCHOOL_ID).unwrap();
18451845 let beta_db = tenants
18461846 .create(
1847- hezarfen_backend::tenant::SchoolId::generate(),
1848- &beta,
1847+ beta,
18491848 "Beta College",
18501849 ModuleSet::all(),
18511850 )
@@ -1874,7 +1873,7 @@ async fn an_index_dispatch_names_the_notes_own_school_and_stores_the_answer_ther
18741873 );
18751874
18761875 let seen = service.seen();
1877- assert_eq!(seen[0].school, "beta", "the frame named the wrong school");
1876+ assert_eq!(seen[0].school, hezarfen_backend::tenant::BETA_SCHOOL_ID, "the frame named the wrong school");
18781877 assert_eq!(seen[0].payload["course_note"], note);
18791878 }
18801879
@@ -1900,7 +1899,7 @@ async fn a_course_note_is_indexed_and_its_output_stored_with_its_sources() {
19001899 let seen = service.seen();
19011900 assert_eq!(seen[0].capability, AI_RAG_INDEX_CAPABILITY);
19021901 assert_eq!(
1903- seen[0].school, DEMO_SLUG,
1902+ seen[0].school, DEMO_SCHOOL_ID,
19041903 "the frame names the caller's school"
19051904 );
19061905 assert_eq!(seen[0].payload["course_note"], note);
@@ -2053,7 +2052,7 @@ async fn a_service_reads_a_course_note_on_behalf_of_an_enrolled_student() {
20532052
20542053 let request = ApiRequest {
20552054 id: "trace-course-notes".into(),
2056- school: DEMO_SLUG.into(),
2055+ school: DEMO_SCHOOL_ID.into(),
20572056 path: "/course-notes".into(),
20582057 query: Some(format!("course={course}")),
20592058 on_behalf_of: Some(student),
@@ -2081,7 +2080,7 @@ async fn a_course_the_student_is_not_in_is_refused_by_the_handler() {
20812080
20822081 let request = ApiRequest {
20832082 id: "trace-foreign-course".into(),
2084- school: DEMO_SLUG.into(),
2083+ school: DEMO_SCHOOL_ID.into(),
20852084 path: "/course-notes".into(),
20862085 query: Some(format!("course={foreign}")),
20872086 on_behalf_of: Some(student),
@@ -2101,7 +2100,7 @@ async fn writing_a_course_note_is_refused_before_dispatch() {
21012100
21022101 let request = ApiRequest {
21032102 id: "trace-post".into(),
2104- school: DEMO_SLUG.into(),
2103+ school: DEMO_SCHOOL_ID.into(),
21052104 path: "/course-notes".into(),
21062105 query: None,
21072106 on_behalf_of: None,
@@ -2170,7 +2169,7 @@ async fn blob_read(conn: &quinn::Connection, request: BlobRequest) -> (BlobRespo
21702169 }
21712170
21722171 fn blob_of(file: &str, on_behalf_of: Option<&str>) -> BlobRequest {
2173- blob_of_school(DEMO_SLUG, file, on_behalf_of)
2172+ blob_of_school(DEMO_SCHOOL_ID, file, on_behalf_of)
21742173 }
21752174
21762175 /// The same, naming the school explicitly.
@@ -2228,7 +2227,7 @@ async fn a_service_streams_a_course_note_file_on_behalf_of_an_enrolled_student()
22282227 panic!("the enrolled student was refused: {}", blob_refusal(header));
22292228 };
22302229 assert_eq!(id, format!("trace-blob-{file}"), "the trace id is echoed");
2231- assert_eq!(school, DEMO_SLUG, "the school is echoed too");
2230+ assert_eq!(school, DEMO_SCHOOL_ID, "the school is echoed too");
22322231 assert_eq!(name, "recap.pdf");
22332232 assert_eq!(content_type, "application/pdf");
22342233 assert_eq!(size as usize, uploaded.len(), "the promised byte count");
@@ -2752,7 +2751,7 @@ async fn a_dispatch_is_traced_by_capability_and_a_refused_handshake_is_counted()
27522751 });
27532752 let attrs = attrs_of(request);
27542753 assert!(
2755- attrs.contains(&("school".to_string(), DEMO_SLUG.to_string())),
2754+ attrs.contains(&("school".to_string(), DEMO_SCHOOL_ID.to_string())),
27562755 "the span names the school slug: {attrs:?}"
27572756 );
27582757 assert!(
@@ -3061,7 +3060,7 @@ async fn no_rag_worker_means_503_and_no_rows() {
30613060 #[tokio::test]
30623061 async fn a_school_without_the_chatbot_module_has_no_rag_nest() {
30633062 let (app, db, tenants) = common::app_and_tenants().await;
3064- let slug = Slug::try_new(DEMO_SLUG).unwrap();
3063+ let slug = SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap();
30653064 let cookie = common::login_as(&app, &db, "ada", "admin").await;
30663065
30673066 let res = common::send(&app, "GET", "/rag/threads", Some(&cookie), None).await;
@@ -3483,7 +3482,7 @@ async fn the_summarize_request_carries_the_askers_scope_and_role() {
34833482 let seen = service.seen();
34843483 assert_eq!(seen.len(), 1, "one dispatch per call, never a re-send");
34853484 assert_eq!(seen[0].capability, AI_RAG_SUMMARIZE_CAPABILITY);
3486- assert_eq!(seen[0].school, DEMO_SLUG, "the frame names the caller's school");
3485+ assert_eq!(seen[0].school, DEMO_SCHOOL_ID, "the frame names the caller's school");
34873486 let payload = &seen[0].payload;
34883487 assert_eq!(payload["asker"], student);
34893488 assert_eq!(payload["asker_role"], "student");
@@ -3844,7 +3843,7 @@ async fn an_insight_student_dispatch_names_the_school_and_round_trips() {
38443843 let seen = await_seen(&service, 1).await;
38453844 assert_eq!(seen.len(), 1, "one dispatch per request, never a re-send");
38463845 assert_eq!(seen[0].capability, AI_INSIGHT_STUDENT_CAPABILITY);
3847- assert_eq!(seen[0].school, DEMO_SLUG, "the frame names the school");
3846+ assert_eq!(seen[0].school, DEMO_SCHOOL_ID, "the frame names the school");
38483847 assert_eq!(seen[0].payload["user_id"], ali);
38493848
38503849 // The same worker driven directly answers the contract's shape, so the
@@ -4292,7 +4291,6 @@ use hezarfen_backend::constant::{
42924291 };
42934292 use hezarfen_backend::domain::user::{Password, Username};
42944293 use hezarfen_backend::service::builder;
4295-use hezarfen_backend::tenant::SchoolId;
42964294
42974295 /// One capability call: a fresh client-initiated stream, one frame out, one
42984296 /// back, stream dropped — the same lifecycle as `api_read` above.
@@ -4308,10 +4306,10 @@ async fn capability_call(
43084306 frame_or_fail(&mut recv, "read CapabilityResponse").await
43094307 }
43104308
4311-fn insight_call(capability: &str, school: &str, payload: Value) -> CapabilityRequest {
4309+fn insight_call(capability: &str, school: impl AsRef<str>, payload: Value) -> CapabilityRequest {
43124310 CapabilityRequest {
43134311 id: format!("trace-{capability}"),
4314- school: school.to_string(),
4312+ school: school.as_ref().to_string(),
43154313 capability: capability.to_string(),
43164314 payload,
43174315 }
@@ -4383,7 +4381,7 @@ async fn a_capability_call_writes_the_row_the_schools_own_read_door_serves() {
43834381 &service.conn,
43844382 insight_call(
43854383 AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY,
4386- DEMO_SLUG,
4384+ DEMO_SCHOOL_ID,
43874385 summary_payload(&student, 1_800_000_000_000i64),
43884386 ),
43894387 )
@@ -4398,7 +4396,7 @@ async fn a_capability_call_writes_the_row_the_schools_own_read_door_serves() {
43984396 };
43994397 assert_eq!(id, format!("trace-{AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY}"));
44004398 assert_eq!(
4401- school, DEMO_SLUG,
4399+ school, DEMO_SCHOOL_ID,
44024400 "the answer echoes the school the frame named"
44034401 );
44044402 assert_eq!(payload["written"], 1);
@@ -4428,7 +4426,7 @@ async fn the_insight_ledger_and_pending_list_round_trip_over_the_bridge() {
44284426
44294427 let run = insight_call(
44304428 AI_INSIGHT_RUN_UPSERT_CAPABILITY,
4431- DEMO_SLUG,
4429+ DEMO_SCHOOL_ID,
44324430 json!({ "run": {
44334431 "run_day": "2026-09-17",
44344432 "started_at": 1_700_000_000_000i64,
@@ -4453,7 +4451,7 @@ async fn the_insight_ledger_and_pending_list_round_trip_over_the_bridge() {
44534451 let pending = ok_capability(
44544452 capability_call(
44554453 &service.conn,
4456- insight_call(AI_INSIGHT_PENDING_LIST_CAPABILITY, DEMO_SLUG, json!({})),
4454+ insight_call(AI_INSIGHT_PENDING_LIST_CAPABILITY, DEMO_SCHOOL_ID, json!({})),
44574455 )
44584456 .await,
44594457 );
@@ -4463,7 +4461,7 @@ async fn the_insight_ledger_and_pending_list_round_trip_over_the_bridge() {
44634461 // CHECK violation dressed as a server fault.
44644462 let bad_day = insight_call(
44654463 AI_INSIGHT_RUN_UPSERT_CAPABILITY,
4466- DEMO_SLUG,
4464+ DEMO_SCHOOL_ID,
44674465 json!({ "run": {
44684466 "run_day": "17.09.2026",
44694467 "started_at": 1,
@@ -4489,7 +4487,7 @@ async fn the_sweep_and_purge_capabilities_answer_per_table_verdicts() {
44894487 &service.conn,
44904488 insight_call(
44914489 AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY,
4492- DEMO_SLUG,
4490+ DEMO_SCHOOL_ID,
44934491 summary_payload(&student, 1), // long past
44944492 ),
44954493 )
@@ -4499,7 +4497,7 @@ async fn the_sweep_and_purge_capabilities_answer_per_table_verdicts() {
44994497 let verdicts = ok_capability(
45004498 capability_call(
45014499 &service.conn,
4502- insight_call(AI_INSIGHT_RETENTION_SWEEP_CAPABILITY, DEMO_SLUG, json!({})),
4500+ insight_call(AI_INSIGHT_RETENTION_SWEEP_CAPABILITY, DEMO_SCHOOL_ID, json!({})),
45034501 )
45044502 .await,
45054503 );
@@ -4510,7 +4508,7 @@ async fn the_sweep_and_purge_capabilities_answer_per_table_verdicts() {
45104508 // obeyed, it would delete every student's derived rows in one call.
45114509 let empty = insight_call(
45124510 "insight.departed.purge",
4513- DEMO_SLUG,
4511+ DEMO_SCHOOL_ID,
45144512 json!({ "students": [] }),
45154513 );
45164514 let (code, _) = refused_capability(capability_call(&service.conn, empty).await);
@@ -4531,11 +4529,10 @@ async fn a_capability_call_cannot_touch_another_schools_rows() {
45314529 let _mudur = common::login_as(&app, &demo_db, "mudur", "manager").await;
45324530 let ayse = common::login_as(&app, &demo_db, "ayse", "student").await;
45334531 let student = common::me_id(&app, &ayse).await;
4534- let beta = Slug::try_new("beta").unwrap();
4532+ let beta = SchoolId::try_parse(hezarfen_backend::tenant::BETA_SCHOOL_ID).unwrap();
45354533 let beta_db = tenants
45364534 .create(
4537- SchoolId::generate(),
4538- &beta,
4535+ SchoolId::try_parse(hezarfen_backend::tenant::BETA_SCHOOL_ID).unwrap(),
45394536 "Beta College",
45404537 ModuleSet::all(),
45414538 )
@@ -4578,7 +4575,7 @@ async fn a_capability_call_refuses_unknown_names_and_payloads_that_do_not_fit()
45784575 // would make this a generic door is the shape that is missing.
45794576 let unknown = insight_call(
45804577 "insight.database.query",
4581- DEMO_SLUG,
4578+ DEMO_SCHOOL_ID,
45824579 json!({ "sql": "SELECT 1" }),
45834580 );
45844581 let (code, message) = refused_capability(capability_call(&service.conn, unknown).await);
@@ -4588,7 +4585,7 @@ async fn a_capability_call_refuses_unknown_names_and_payloads_that_do_not_fit()
45884585 // A payload that does not fit the operation's contract.
45894586 let bad = insight_call(
45904587 AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY,
4591- DEMO_SLUG,
4588+ DEMO_SCHOOL_ID,
45924589 json!({ "rows": [{ "student": "not-a-uuid", "confidence": "stable",
45934590 "computed_at": 1, "retain_until": 2 }] }),
45944591 );
@@ -4617,11 +4614,10 @@ async fn the_school_directory_is_the_one_deployment_scoped_operation() {
46174614 .await;
46184615 await_workers(&bridge, 1).await;
46194616 let (app, _db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await;
4620- let beta = Slug::try_new("beta").unwrap();
4617+ let beta = SchoolId::try_parse(hezarfen_backend::tenant::BETA_SCHOOL_ID).unwrap();
46214618 tenants
46224619 .create(
4623- SchoolId::generate(),
4624- &beta,
4620+ beta,
46254621 "Beta College",
46264622 ModuleSet::all(),
46274623 )
@@ -4642,7 +4638,7 @@ async fn the_school_directory_is_the_one_deployment_scoped_operation() {
46424638 .iter()
46434639 .map(|s| s.as_str().expect("slug"))
46444640 .collect();
4645- assert_eq!(schools, vec!["beta", DEMO_SLUG], "active schools, sorted");
4641+ assert_eq!(schools, vec![hezarfen_backend::tenant::BETA_SCHOOL_ID, DEMO_SCHOOL_ID], "active schools, name order");
46464642
46474643 // Over HTTP the same operation is the builder's: a school session must
46484644 // not be able to enumerate the deployment's other customers.
@@ -4926,7 +4922,7 @@ async fn the_report_and_upload_handshake_lands_on_the_backends_own_row() {
49264922
49274923 let answer = capability_call(
49284924 conn,
4929- report_call(DEMO_SLUG, &job, &user, "running", "script", 0.5),
4925+ report_call(DEMO_SCHOOL_ID, &job, &user, "running", "script", 0.5),
49304926 )
49314927 .await;
49324928 assert_eq!(ok_capability(answer)["job_id"], job);
@@ -4938,7 +4934,7 @@ async fn the_report_and_upload_handshake_lands_on_the_backends_own_row() {
49384934 let (code, _) = refused_capability(
49394935 capability_call(
49404936 conn,
4941- report_call(DEMO_SLUG, &job, &user, "done", "done", 1.0),
4937+ report_call(DEMO_SCHOOL_ID, &job, &user, "done", "done", 1.0),
49424938 )
49434939 .await,
49444940 );
@@ -4950,7 +4946,7 @@ async fn the_report_and_upload_handshake_lands_on_the_backends_own_row() {
49504946 capability_call(
49514947 conn,
49524948 report_call(
4953- DEMO_SLUG,
4949+ DEMO_SCHOOL_ID,
49544950 &job,
49554951 "00000000-0000-7000-8000-000000000000",
49564952 "failed",
@@ -4963,7 +4959,7 @@ async fn the_report_and_upload_handshake_lands_on_the_backends_own_row() {
49634959 assert_eq!(code, "not_permitted");
49644960 // And so is a transition the service's own table forbids.
49654961 let (code, _) = refused_capability(
4966- capability_call(conn, report_call(DEMO_SLUG, &job, &user, "queued", "", 0.0)).await,
4962+ capability_call(conn, report_call(DEMO_SCHOOL_ID, &job, &user, "queued", "", 0.0)).await,
49674963 );
49684964 assert_eq!(code, "invalid_payload");
49694965 assert_eq!(podcast_row(&db, &job).await.0, "running");
@@ -4972,10 +4968,10 @@ async fn the_report_and_upload_handshake_lands_on_the_backends_own_row() {
49724968 // stamped with the reference and the duration.
49734969 let body = blob_bytes(200 * 1024);
49744970 let (key, size) =
4975- upload_key(podcast_upload(conn, DEMO_SLUG, &job, "bolum.mp3", "audio/mpeg", &body).await);
4971+ upload_key(podcast_upload(conn, DEMO_SCHOOL_ID, &job, "bolum.mp3", "audio/mpeg", &body).await);
49764972 assert_eq!(size, body.len() as u64);
49774973 assert_eq!(key, format!("podcast/{job}.mp3"));
4978- let stored = common::files_dir().join(DEMO_SLUG).join(&key);
4974+ let stored = common::files_dir().join(DEMO_SCHOOL_ID).join(&key);
49794975 assert_eq!(std::fs::read(&stored).expect("the stored episode"), body);
49804976 let row = podcast_row(&db, &job).await;
49814977 assert_eq!(row.3.as_deref(), Some(key.as_str()));
@@ -4986,7 +4982,7 @@ async fn the_report_and_upload_handshake_lands_on_the_backends_own_row() {
49864982 ok_capability(
49874983 capability_call(
49884984 conn,
4989- report_call(DEMO_SLUG, &job, &user, "done", "done", 1.0)
4985+ report_call(DEMO_SCHOOL_ID, &job, &user, "done", "done", 1.0)
49904986 )
49914987 .await
49924988 )["stored"],
@@ -4999,7 +4995,7 @@ async fn the_report_and_upload_handshake_lands_on_the_backends_own_row() {
49994995 let (code, _) = refused_capability(
50004996 capability_call(
50014997 conn,
5002- report_call(DEMO_SLUG, &stranger, &user, "running", "ocr", 0.1),
4998+ report_call(DEMO_SCHOOL_ID, &stranger, &user, "running", "ocr", 0.1),
50034999 )
50045000 .await,
50055001 );
@@ -5019,11 +5015,10 @@ async fn a_report_or_upload_cannot_reach_another_schools_job() {
50195015 .await;
50205016 await_workers(&bridge, 1).await;
50215017 let (_app, _demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await;
5022- let beta = Slug::try_new("beta").unwrap();
5018+ let beta = SchoolId::try_parse(hezarfen_backend::tenant::BETA_SCHOOL_ID).unwrap();
50235019 let beta_db = tenants
50245020 .create(
5025- hezarfen_backend::tenant::SchoolId::generate(),
5026- &beta,
5021+ beta,
50275022 "Beta College",
50285023 ModuleSet::all(),
50295024 )
@@ -5034,7 +5029,7 @@ async fn a_report_or_upload_cannot_reach_another_schools_job() {
50345029 let (code, _) = refused_capability(
50355030 capability_call(
50365031 &service.conn,
5037- report_call(DEMO_SLUG, &job, &user, "running", "script", 0.2),
5032+ report_call(DEMO_SCHOOL_ID, &job, &user, "running", "script", 0.2),
50385033 )
50395034 .await,
50405035 );
@@ -5049,7 +5044,7 @@ async fn a_report_or_upload_cannot_reach_another_schools_job() {
50495044 let (code, _) = upload_refusal(
50505045 podcast_upload(
50515046 &service.conn,
5052- DEMO_SLUG,
5047+ DEMO_SCHOOL_ID,
50535048 &job,
50545049 "bolum.mp3",
50555050 "audio/mpeg",
@@ -5059,7 +5054,7 @@ async fn a_report_or_upload_cannot_reach_another_schools_job() {
50595054 );
50605055 assert_eq!(code, "unknown_job");
50615056 let leaked = common::files_dir()
5062- .join(DEMO_SLUG)
5057+ .join(DEMO_SCHOOL_ID)
50635058 .join(format!("podcast/{job}.mp3"));
50645059 assert!(
50655060 !leaked.exists(),
@@ -5091,7 +5086,7 @@ async fn an_upload_past_the_audio_ceiling_is_refused_before_a_byte_is_read() {
50915086 let request = BlobUploadRequest {
50925087 id: "trace-oversize".to_string(),
50935088 upload: true,
5094- school: DEMO_SLUG.to_string(),
5089+ school: DEMO_SCHOOL_ID.to_string(),
50955090 job_id: job.clone(),
50965091 name: "bolum.mp3".to_string(),
50975092 content_type: "audio/mpeg".to_string(),
tests/ai_protocol.rsmodified+28 -29
@@ -24,14 +24,14 @@ use std::time::Duration;
2424
2525 use hezarfen_backend::ai::{AiBridge, AiError, BridgeConfig};
2626 use hezarfen_backend::module::ModuleSet;
27-use hezarfen_backend::tenant::{SchoolStatus, Slug, Tenants};
27+use hezarfen_backend::tenant::{SchoolStatus, SchoolId, Tenants};
2828 use serde_json::{Value, json};
2929
3030 const TOKEN: &str = "shared-ai-token";
3131
3232 /// The school every frame in this suite names. A literal for the same reason
3333 /// `PROTOCOL` is one: a service spells the slug out, it is not a Rust constant.
34-const SCHOOL: &str = "demo";
34+const SCHOOL: &str = "019732e3-7b00-7000-8000-00000000dead";
3535
3636 /// The protocol identifier this suite pins. Deliberately a literal, not
3737 /// `AI_PROTOCOL`: importing the constant would let a rename sail through, and
@@ -269,7 +269,7 @@ fn dispatch(
269269 ) -> tokio::task::JoinHandle<Result<Value, AiError>> {
270270 let bridge = bridge.clone();
271271 let capability = capability.to_string();
272- let school = hezarfen_backend::tenant::Slug::try_new(SCHOOL).expect("the demo slug");
272+ let school = hezarfen_backend::tenant::SchoolId::try_parse(SCHOOL).expect("the demo slug");
273273 tokio::spawn(async move { bridge.dispatch(&school, &capability, payload).await })
274274 }
275275
@@ -814,7 +814,7 @@ async fn closing_the_control_stream_deregisters_the_service() {
814814 assert!(matches!(
815815 bridge
816816 .dispatch(
817- &hezarfen_backend::tenant::Slug::try_new(SCHOOL).unwrap(),
817+ &hezarfen_backend::tenant::SchoolId::try_parse(SCHOOL).unwrap(),
818818 "ocr.extract",
819819 json!(null)
820820 )
@@ -967,7 +967,7 @@ async fn a_chat_request_names_the_askers_school_role() {
967967
968968 let tenants = hezarfen_backend::database::init_test_tenants().await;
969969 let db = tenants
970- .get(&hezarfen_backend::tenant::Slug::try_new(hezarfen_backend::tenant::DEMO_SLUG).unwrap())
970+ .get(&hezarfen_backend::tenant::SchoolId::try_parse(hezarfen_backend::tenant::DEMO_SCHOOL_ID).unwrap())
971971 .await
972972 .expect("the demo school");
973973 let app = hezarfen_backend::build_router(hezarfen_backend::state::AppState {
@@ -1179,7 +1179,7 @@ async fn only_id_and_path_are_required_of_an_api_request() {
11791179
11801180 let (answer, _) = raw::api_read(
11811181 &service.conn,
1182- br#"{"id":"trace-1","school":"demo","path":"/auth/me","unknown_field":true}"#,
1182+ br#"{"id":"trace-1","school":"019732e3-7b00-7000-8000-00000000dead","path":"/auth/me","unknown_field":true}"#,
11831183 )
11841184 .await;
11851185 assert_eq!(answer["outcome"], "ok", "{answer}");
@@ -1201,43 +1201,43 @@ async fn the_api_refusal_frame_carries_exactly_the_published_keys_and_codes() {
12011201 let cases = [
12021202 (
12031203 "method_not_allowed",
1204- r#"{"id":"t1","school":"demo","path":"/notes","method":"DELETE"}"#.to_string(),
1204+ r#"{"id":"t1","school":"019732e3-7b00-7000-8000-00000000dead","path":"/notes","method":"DELETE"}"#.to_string(),
12051205 ),
12061206 (
12071207 "method_not_allowed",
12081208 // Lowercase is not the method: the literal is exactly `GET`.
1209- r#"{"id":"t2","school":"demo","path":"/notes","method":"get"}"#.to_string(),
1209+ r#"{"id":"t2","school":"019732e3-7b00-7000-8000-00000000dead","path":"/notes","method":"get"}"#.to_string(),
12101210 ),
12111211 (
12121212 "path_not_allowed",
1213- r#"{"id":"t3","school":"demo","path":"/courses"}"#.to_string(),
1213+ r#"{"id":"t3","school":"019732e3-7b00-7000-8000-00000000dead","path":"/courses"}"#.to_string(),
12141214 ),
12151215 (
12161216 // Order pin: both refusals apply, the method one wins.
12171217 "method_not_allowed",
1218- r#"{"id":"t4","school":"demo","path":"/nope","method":"POST"}"#.to_string(),
1218+ r#"{"id":"t4","school":"019732e3-7b00-7000-8000-00000000dead","path":"/nope","method":"POST"}"#.to_string(),
12191219 ),
12201220 (
12211221 "unknown_user",
1222- r#"{"id":"t5","school":"demo","path":"/auth/me","on_behalf_of":"nobodyatall"}"#
1222+ r#"{"id":"t5","school":"019732e3-7b00-7000-8000-00000000dead","path":"/auth/me","on_behalf_of":"nobodyatall"}"#
12231223 .to_string(),
12241224 ),
12251225 (
12261226 "malformed",
1227- r#"{"id":"t6","school":"demo","path":42}"#.to_string(),
1227+ r#"{"id":"t6","school":"019732e3-7b00-7000-8000-00000000dead","path":42}"#.to_string(),
12281228 ),
12291229 // A frame that names no school at all: required, never defaulted.
12301230 ("malformed", r#"{"id":"t7","path":"/auth/me"}"#.to_string()),
1231- // A string that is no slug — the service's own bug, not a missing
1232- // customer, so it is `malformed` rather than `unknown_school`.
1231+ // A string that is not a hyphenated uuid is `unknown_school`, not
1232+ // `malformed`. `malformed` stays the frame-shape error (t7, above).
12331233 (
1234- "malformed",
1234+ "unknown_school",
12351235 r#"{"id":"t8","school":"NOT A SLUG","path":"/auth/me"}"#.to_string(),
12361236 ),
1237- // A well-formed slug this deployment does not serve.
1237+ // A hyphenated uuid this deployment does not serve.
12381238 (
12391239 "unknown_school",
1240- r#"{"id":"t9","school":"nope","path":"/auth/me"}"#.to_string(),
1240+ r#"{"id":"t9","school":"019732e3-7b00-7000-8000-00000000eeee","path":"/auth/me"}"#.to_string(),
12411241 ),
12421242 ];
12431243
@@ -1304,8 +1304,7 @@ async fn two_schools(bridge: &AiBridge) -> (axum::Router, Tenants, String, Strin
13041304 let (app, demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await;
13051305 let beta_db = tenants
13061306 .create(
1307- hezarfen_backend::tenant::SchoolId::generate(),
1308- &Slug::try_new("beta").unwrap(),
1307+ hezarfen_backend::tenant::SchoolId::try_parse(hezarfen_backend::tenant::BETA_SCHOOL_ID).unwrap(),
13091308 "Beta College",
13101309 ModuleSet::all(),
13111310 )
@@ -1334,7 +1333,7 @@ async fn an_api_read_answers_out_of_the_school_the_frame_named() {
13341333 await_workers(&bridge, 1).await;
13351334 let (_app, _tenants, demo_ayse, beta_ayse) = two_schools(&bridge).await;
13361335
1337- for (school, who) in [("demo", &demo_ayse), ("beta", &beta_ayse)] {
1336+ for (school, who) in [("019732e3-7b00-7000-8000-00000000dead", &demo_ayse), ("019732e3-7b00-7000-8000-00000000beef", &beta_ayse)] {
13381337 let (answer, _) = raw::api_read(
13391338 &service.conn,
13401339 format!(
@@ -1350,7 +1349,7 @@ async fn an_api_read_answers_out_of_the_school_the_frame_named() {
13501349 }
13511350
13521351 // And crossed over: the other school's id names nobody here.
1353- for (school, who) in [("demo", &beta_ayse), ("beta", &demo_ayse)] {
1352+ for (school, who) in [("019732e3-7b00-7000-8000-00000000dead", &beta_ayse), ("019732e3-7b00-7000-8000-00000000beef", &demo_ayse)] {
13541353 let (answer, _) = raw::api_read(
13551354 &service.conn,
13561355 format!(
@@ -1376,13 +1375,13 @@ async fn a_suspended_school_is_refused_with_its_own_code() {
13761375 let (_app, tenants, _demo_ayse, beta_ayse) = two_schools(&bridge).await;
13771376
13781377 let read = format!(
1379- r#"{{"id":"t-susp","school":"beta","path":"/auth/me","on_behalf_of":"{beta_ayse}"}}"#
1378+ r#"{{"id":"t-susp","school":"019732e3-7b00-7000-8000-00000000beef","path":"/auth/me","on_behalf_of":"{beta_ayse}"}}"#
13801379 );
13811380 let (answer, _) = raw::api_read(&service.conn, read.as_bytes()).await;
13821381 assert_eq!(answer["outcome"], "ok", "the school starts out active");
13831382
13841383 tenants
1385- .set_status(&Slug::try_new("beta").unwrap(), SchoolStatus::Suspended)
1384+ .set_status(&SchoolId::try_parse(hezarfen_backend::tenant::BETA_SCHOOL_ID).unwrap(), SchoolStatus::Suspended)
13861385 .await
13871386 .expect("suspend beta");
13881387
@@ -1390,7 +1389,7 @@ async fn a_suspended_school_is_refused_with_its_own_code() {
13901389 assert_eq!(answer["outcome"], "err", "{answer}");
13911390 assert_eq!(answer["code"], "school_suspended", "{answer}");
13921391 assert_eq!(
1393- answer["school"], "beta",
1392+ answer["school"], "019732e3-7b00-7000-8000-00000000beef",
13941393 "the refusal names the school back"
13951394 );
13961395 assert_eq!(answer["id"], "t-susp");
@@ -1398,7 +1397,7 @@ async fn a_suspended_school_is_refused_with_its_own_code() {
13981397 // The demo school is untouched by its neighbour's suspension.
13991398 let (answer, _) = raw::api_read(
14001399 &service.conn,
1401- br#"{"id":"t-neighbour","school":"demo","path":"/auth/me"}"#,
1400+ br#"{"id":"t-neighbour","school":"019732e3-7b00-7000-8000-00000000dead","path":"/auth/me"}"#,
14021401 )
14031402 .await;
14041403 assert_eq!(answer["outcome"], "ok", "{answer}");
@@ -1424,7 +1423,7 @@ async fn a_blob_read_names_its_school_too() {
14241423 assert_eq!(header["status"], "ok", "{header}");
14251424 assert_eq!(body.len(), uploaded.len());
14261425
1427- for (school, code) in [("nope", "unknown_school"), ("NOT A SLUG", "malformed")] {
1426+ for (school, code) in [("019732e3-7b00-7000-8000-00000000eeee", "unknown_school"), ("NOT A SLUG", "unknown_school")] {
14281427 let (header, _, body) = raw::blob_read(
14291428 &service.conn,
14301429 format!(
@@ -1575,7 +1574,7 @@ async fn a_blob_refusal_frame_carries_exactly_the_published_keys_and_no_bytes()
15751574 let mut modules = ModuleSet::all();
15761575 modules.remove(hezarfen_backend::module::Module::CourseNotes);
15771576 tenants
1578- .set_modules(&Slug::try_new(SCHOOL).unwrap(), &modules)
1577+ .set_modules(&SchoolId::try_parse(SCHOOL).unwrap(), &modules)
15791578 .await
15801579 .expect("take course_notes off the demo school");
15811580
@@ -1637,7 +1636,7 @@ async fn an_api_read_still_answers_on_the_shared_client_stream_path() {
16371636 assert_eq!(answer["status"], 200);
16381637
16391638 // Neither shape: still the api read's refusal, with its `outcome` tag.
1640- let (answer, _) = raw::api_read(&service.conn, br#"{"id":"t-neither","school":"demo"}"#).await;
1639+ let (answer, _) = raw::api_read(&service.conn, br#"{"id":"t-neither","school":"019732e3-7b00-7000-8000-00000000dead"}"#).await;
16411640 assert_eq!(answer["outcome"], "err", "{answer}");
16421641 assert_eq!(answer["code"], "malformed");
16431642 assert_eq!(answer["id"], "t-neither");
@@ -1744,7 +1743,7 @@ async fn the_capability_shape_does_not_steal_the_shapes_that_existed_before() {
17441743 assert_eq!(answer["payload"]["students"], json!([]), "{answer}");
17451744
17461745 // Neither: the same api-read refusal as before this shape existed.
1747- let (answer, _) = raw::api_read(&service.conn, br#"{"id":"t-neither","school":"demo"}"#).await;
1746+ let (answer, _) = raw::api_read(&service.conn, br#"{"id":"t-neither","school":"019732e3-7b00-7000-8000-00000000dead"}"#).await;
17481747 assert_eq!(answer["outcome"], "err", "{answer}");
17491748 assert_eq!(answer["code"], "malformed");
17501749 }
tests/auth_enumeration.rsmodified+5 -5
@@ -12,13 +12,13 @@ use serde_json::json;
1212 #[tokio::test]
1313 async fn duplicate_register_is_indistinguishable_from_a_fresh_one() {
1414 let (app, db) = app_and_db().await;
15- let taken = json!({ "school": "demo", "username": "ada", "password": "secret1" });
15+ let taken = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ada", "password": "secret1" });
1616
1717 let first = send(&app, "POST", "/auth/register", None, Some(taken)).await;
1818 assert_eq!(first.status, StatusCode::CREATED);
1919
2020 // Same username again, different password: still 201, same body shape.
21- let dup_creds = json!({ "school": "demo", "username": "ada", "password": "attacker" });
21+ let dup_creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ada", "password": "attacker" });
2222 let started = Instant::now();
2323 let dup = send(
2424 &app,
@@ -35,7 +35,7 @@ async fn duplicate_register_is_indistinguishable_from_a_fresh_one() {
3535 "POST",
3636 "/auth/register",
3737 None,
38- Some(json!({ "school": "demo", "username": "grace", "password": "secret1" })),
38+ Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "grace", "password": "secret1" })),
3939 )
4040 .await;
4141
@@ -136,7 +136,7 @@ async fn the_taken_body_equals_the_fresh_body_for_the_same_username() {
136136 "POST",
137137 "/auth/register",
138138 None,
139- Some(json!({ "school": "demo", "username": "ada", "password": "secret1" })),
139+ Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ada", "password": "secret1" })),
140140 )
141141 .await;
142142 let taken = send(
@@ -144,7 +144,7 @@ async fn the_taken_body_equals_the_fresh_body_for_the_same_username() {
144144 "POST",
145145 "/auth/register",
146146 None,
147- Some(json!({ "school": "demo", "username": "ada", "password": "another1" })),
147+ Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ada", "password": "another1" })),
148148 )
149149 .await;
150150
tests/builder_api.rsmodified+364 -493
@@ -10,7 +10,7 @@ use axum::http::StatusCode;
1010 use common::*;
1111 use hezarfen_backend::domain::user::{Password, Username};
1212 use hezarfen_backend::service::builder;
13-use hezarfen_backend::tenant::{DEMO_SLUG, Tenants};
13+use hezarfen_backend::tenant::{DEMO_SCHOOL_ID, SchoolId, Tenants};
1414 use serde_json::{Value, json};
1515
1616 const BUILDER_USER: &str = "operator";
@@ -31,7 +31,7 @@ async fn deployment() -> (Router, hezarfen_backend::database::Database, Tenants)
3131 }
3232
3333 async fn builder_login(app: &Router) -> String {
34- let res = send(
34+ let res = bsend(
3535 app,
3636 "POST",
3737 "/builder/login",
@@ -43,16 +43,16 @@ async fn builder_login(app: &Router) -> String {
4343 res.cookie.expect("builder cookie set on login")
4444 }
4545
46-/// Create a school as the builder (no assertion) — slug, name, first admin.
47-async fn create_school(app: &Router, cookie: &str, slug: &str, admin_pass: &str) -> Res {
48- send(
46+/// Create a school as the builder. `label` is only the display-name prefix
47+/// (`"{label} school"`); the identity comes back as `id`.
48+async fn create_school(app: &Router, cookie: &str, label: &str, admin_pass: &str) -> Res {
49+ bsend(
4950 app,
5051 "POST",
5152 "/schools",
5253 Some(cookie),
5354 Some(json!({
54- "slug": slug,
55- "name": format!("{slug} school"),
55+ "name": format!("{label} school"),
5656 "admin_username": "admin",
5757 "admin_password": admin_pass,
5858 })),
@@ -60,13 +60,34 @@ async fn create_school(app: &Router, cookie: &str, slug: &str, admin_pass: &str)
6060 .await
6161 }
6262
63+fn created_id(res: &Res) -> String {
64+ res.body["id"].as_str().expect("created school id").to_string()
65+}
66+
67+/// Pick `label` out of a login choice list: a uuid is used as-is, otherwise
68+/// the school whose name is `{label} school` (the name [`create_school`] writes).
69+fn school_choice(body: &Value, label: &str) -> String {
70+ if hezarfen_backend::tenant::SchoolId::try_parse(label).is_ok() {
71+ return label.to_string();
72+ }
73+ let want = format!("{label} school");
74+ body["schools"]
75+ .as_array()
76+ .into_iter()
77+ .flatten()
78+ .find(|s| s["name"].as_str() == Some(want.as_str()) || s["name"].as_str() == Some(label))
79+ .and_then(|s| s["id"].as_str())
80+ .unwrap_or(label)
81+ .to_string()
82+}
83+
6384 /// Log `username` into the school named `slug`. The login itself names no
6485 /// school any more — the admin fixtures reuse one username across many
6586 /// schools, which makes that admin one *person* with several memberships —
6687 /// so when login answers a choice list, bind the requested school before
6788 /// returning. The result is whatever a plain school login would have said.
6889 async fn school_login(app: &Router, slug: &str, username: &str, password: &str) -> Res {
69- let res = send(
90+ let res = bsend(
7091 app,
7192 "POST",
7293 "/auth/login",
@@ -76,12 +97,12 @@ async fn school_login(app: &Router, slug: &str, username: &str, password: &str)
7697 .await;
7798 if res.body["schools"].is_array() {
7899 assert_eq!(res.status, StatusCode::OK, "choice login {username}");
79- let selected = send(
100+ let selected = bsend(
80101 app,
81102 "POST",
82103 "/auth/school",
83104 res.cookie.as_deref(),
84- Some(json!({ "school": slug })),
105+ Some(json!({ "school": school_choice(&res.body, slug) })),
85106 )
86107 .await;
87108 assert_eq!(
@@ -94,13 +115,71 @@ async fn school_login(app: &Router, slug: &str, username: &str, password: &str)
94115 res
95116 }
96117
97-fn slugs(body: &Value) -> Vec<String> {
118+fn school_ids(body: &Value) -> Vec<String> {
98119 items(body)
99120 .iter()
100- .map(|item| item["slug"].as_str().expect("slug").to_string())
121+ .map(|item| item["id"].as_str().expect("id").to_string())
101122 .collect()
102123 }
103124
125+fn school_names(body: &Value) -> Vec<&str> {
126+ items(body)
127+ .iter()
128+ .map(|item| item["name"].as_str().expect("name"))
129+ .collect()
130+}
131+
132+
133+/// Rewrite `/schools/{label}` to `/schools/{id}` when `label` is a school this
134+/// deployment created (`"{label} school"`). A segment that is already a uuid,
135+/// or that names no school, is left alone so a 404 stays a 404.
136+async fn bsend(
137+ app: &Router,
138+ method: &str,
139+ path: &str,
140+ cookie: Option<&str>,
141+ body: Option<Value>,
142+) -> Res {
143+ let path = rewrite_school_path(app, cookie, path).await;
144+ common::send(app, method, &path, cookie, body).await
145+}
146+
147+async fn rewrite_school_path(app: &Router, cookie: Option<&str>, path: &str) -> String {
148+ let Some(rest) = path.strip_prefix("/schools/") else {
149+ return path.to_string();
150+ };
151+ if rest.is_empty() || rest.contains('{') {
152+ return path.to_string();
153+ }
154+ let (seg, tail) = match rest.split_once('/') {
155+ Some((seg, tail)) => (seg, format!("/{tail}")),
156+ None => (rest, String::new()),
157+ };
158+ if hezarfen_backend::tenant::SchoolId::try_parse(seg).is_ok() {
159+ return path.to_string();
160+ }
161+ let Some(cookie) = cookie else {
162+ return path.to_string();
163+ };
164+ let list = common::send(app, "GET", "/schools", Some(cookie), None).await;
165+ let Some(rows) = list.body.get("items").and_then(|v| v.as_array()) else {
166+ return path.to_string();
167+ };
168+ let want = format!("{seg} school");
169+ let id = rows.iter().find_map(|row| {
170+ let name = row["name"].as_str()?;
171+ if name == want || name == seg {
172+ row["id"].as_str().map(str::to_string)
173+ } else {
174+ None
175+ }
176+ });
177+ match id {
178+ Some(id) => format!("/schools/{id}{tail}"),
179+ None => path.to_string(),
180+ }
181+}
182+
104183 /// The two cookies share a name and nothing else. This is the whole point of
105184 /// the split: neither principal may ever be accepted where the other belongs.
106185 #[tokio::test]
@@ -108,7 +187,7 @@ async fn a_builder_logs_in_and_its_cookie_works_here_and_nowhere_else() {
108187 let (app, _db, _tenants) = deployment().await;
109188 let builder = builder_login(&app).await;
110189
111- let me = send(&app, "GET", "/builder/me", Some(&builder), None).await;
190+ let me = bsend(&app, "GET", "/builder/me", Some(&builder), None).await;
112191 assert_eq!(me.status, StatusCode::OK);
113192 assert_eq!(me.body["username"], BUILDER_USER);
114193 assert!(me.body["id"].as_str().is_some_and(|id| !id.is_empty()));
@@ -116,21 +195,21 @@ async fn a_builder_logs_in_and_its_cookie_works_here_and_nowhere_else() {
116195 // A school user's cookie is not a builder's…
117196 let student = login(&app, "ali").await;
118197 assert_eq!(
119- send(&app, "GET", "/builder/me", Some(&student), None)
198+ bsend(&app, "GET", "/builder/me", Some(&student), None)
120199 .await
121200 .status,
122201 StatusCode::UNAUTHORIZED,
123202 "a school cookie reached the builder surface"
124203 );
125204 assert_eq!(
126- send(&app, "GET", "/schools", Some(&student), None)
205+ bsend(&app, "GET", "/schools", Some(&student), None)
127206 .await
128207 .status,
129208 StatusCode::UNAUTHORIZED
130209 );
131210 // …and a builder's is not a school user's.
132211 assert_eq!(
133- send(&app, "GET", "/auth/me", Some(&builder), None)
212+ bsend(&app, "GET", "/auth/me", Some(&builder), None)
134213 .await
135214 .status,
136215 StatusCode::UNAUTHORIZED,
@@ -143,17 +222,17 @@ async fn a_builder_logs_in_and_its_cookie_works_here_and_nowhere_else() {
143222 json!({ "username": "ghost", "password": BUILDER_PASS }),
144223 ] {
145224 assert_eq!(
146- send(&app, "POST", "/builder/login", None, Some(bad))
225+ bsend(&app, "POST", "/builder/login", None, Some(bad))
147226 .await
148227 .status,
149228 StatusCode::UNAUTHORIZED
150229 );
151230 }
152231
153- let out = send(&app, "POST", "/builder/logout", Some(&builder), None).await;
232+ let out = bsend(&app, "POST", "/builder/logout", Some(&builder), None).await;
154233 assert_eq!(out.status, StatusCode::NO_CONTENT);
155234 assert_eq!(
156- send(&app, "GET", "/builder/me", Some(&builder), None)
235+ bsend(&app, "GET", "/builder/me", Some(&builder), None)
157236 .await
158237 .status,
159238 StatusCode::UNAUTHORIZED,
@@ -175,76 +254,47 @@ async fn creating_a_school_seeds_an_admin_who_can_log_in() {
175254 "create school: {:?}",
176255 created.body
177256 );
178- assert_eq!(created.body["slug"], "ata-koleji");
257+ let id = created_id(&created);
258+ assert_eq!(created.body["name"], "ata-koleji school");
179259 assert_eq!(created.body["status"], "active");
260+ assert!(
261+ hezarfen_backend::tenant::SchoolId::try_parse(&id).is_ok(),
262+ "the identity is a hyphenated uuid: {id}"
263+ );
180264
181- let login = school_login(&app, "ata-koleji", "admin", "secret1").await;
265+ let login = school_login(&app, &id, "admin", "secret1").await;
182266 assert_eq!(login.status, StatusCode::OK, "seeded admin logs in");
183267 let cookie = login.cookie.expect("school cookie");
184268 assert!(
185- cookie.starts_with("session=ata-koleji."),
269+ cookie.starts_with(&format!("session={id}.")),
186270 "the cookie names its school: {cookie}"
187271 );
188- let me = send(&app, "GET", "/auth/me", Some(&cookie), None).await;
272+ let me = bsend(&app, "GET", "/auth/me", Some(&cookie), None).await;
189273 assert_eq!(me.status, StatusCode::OK);
190274 assert_eq!(
191275 me.body["role"], "admin",
192276 "the seed is an admin, not a student"
193277 );
194278
195- // The slug is the identity: a second school may not take it.
196- assert_eq!(
197- create_school(&app, &builder, "ata-koleji", "secret1")
198- .await
199- .status,
200- StatusCode::CONFLICT
201- );
202-
203- // Anything that is not a slug is refused before a database exists — the
204- // reserved words most of all, since they name the builder cookie prefix and
205- // the control database itself.
206- for bad in ["control", "builder", "Ab", "a", &"x".repeat(33), "../x"] {
207- let res = create_school(&app, &builder, bad, "secret1").await;
208- assert_eq!(
209- res.status,
210- StatusCode::BAD_REQUEST,
211- "slug {bad:?} was not refused: {:?}",
212- res.body
213- );
214- // …and nothing was left behind by the refusal.
215- assert_eq!(
216- send(
217- &app,
218- "GET",
219- &format!("/schools/{bad}"),
220- Some(&builder),
221- None
222- )
223- .await
224- .status,
225- StatusCode::NOT_FOUND,
226- "slug {bad:?} left a school behind"
227- );
228- }
229- // A blank name and a too-short admin password are refused the same way.
279+ // A blank name and a too-short admin password are refused before a
280+ // database exists. Same name as an existing school is allowed — the id
281+ // is the identity, not the display name.
230282 for body in [
231- json!({ "slug": "yeni", "name": " ", "admin_username": "admin", "admin_password": "secret1" }),
232- json!({ "slug": "yeni", "name": "Yeni", "admin_username": "admin", "admin_password": "x" }),
283+ json!({ "name": " ", "admin_username": "admin", "admin_password": "secret1" }),
284+ json!({ "name": "Yeni", "admin_username": "admin", "admin_password": "x" }),
233285 ] {
234286 assert_eq!(
235- send(&app, "POST", "/schools", Some(&builder), Some(body))
287+ bsend(&app, "POST", "/schools", Some(&builder), Some(body))
236288 .await
237289 .status,
238290 StatusCode::BAD_REQUEST
239291 );
240292 }
241- // A refused create must not have made a school: the admin's login has
242- // only the one school they actually have to enter — `yeni` names nothing.
243- let refused_create = school_login(&app, "yeni", "admin", "secret1").await;
244- assert_eq!(refused_create.status, StatusCode::OK);
245- let cookie = refused_create.cookie.expect("cookie");
293+ let again = school_login(&app, &id, "admin", "secret1").await;
294+ assert_eq!(again.status, StatusCode::OK);
295+ let cookie = again.cookie.expect("cookie");
246296 assert!(
247- cookie.starts_with("session=ata-koleji."),
297+ cookie.starts_with(&format!("session={id}.")),
248298 "a refused create must not have made a school: {cookie:?}"
249299 );
250300 }
@@ -255,25 +305,22 @@ async fn creating_a_school_seeds_an_admin_who_can_log_in() {
255305 async fn a_suspension_closes_the_school_and_a_resume_reopens_it() {
256306 let (app, _db, _tenants) = deployment().await;
257307 let builder = builder_login(&app).await;
258- assert_eq!(
259- create_school(&app, &builder, "beta", "secret1")
260- .await
261- .status,
262- StatusCode::CREATED
263- );
308+ let created = create_school(&app, &builder, "beta", "secret1").await;
309+ assert_eq!(created.status, StatusCode::CREATED, "{:?}", created.body);
310+ let beta = created_id(&created);
264311
265- let list = send(&app, "GET", "/schools", Some(&builder), None).await;
312+ let list = bsend(&app, "GET", "/schools", Some(&builder), None).await;
266313 assert_eq!(list.status, StatusCode::OK);
267- let listed = slugs(&list.body);
268- assert!(listed.contains(&DEMO_SLUG.to_string()) && listed.contains(&"beta".to_string()));
314+ let listed = school_ids(&list.body);
315+ assert!(listed.contains(&DEMO_SCHOOL_ID.to_string()) && listed.contains(&beta));
269316 assert_eq!(total(&list.body), 2);
270317 // The envelope pages like every other list.
271- let page = send(&app, "GET", "/schools?limit=1", Some(&builder), None).await;
318+ let page = bsend(&app, "GET", "/schools?limit=1", Some(&builder), None).await;
272319 assert_eq!(items(&page.body).len(), 1);
273320 assert_eq!(total(&page.body), 2);
274321
275322 assert_eq!(
276- send(&app, "GET", "/schools/ghost", Some(&builder), None)
323+ bsend(&app, "GET", "/schools/ghost", Some(&builder), None)
277324 .await
278325 .status,
279326 StatusCode::NOT_FOUND
@@ -281,11 +328,11 @@ async fn a_suspension_closes_the_school_and_a_resume_reopens_it() {
281328
282329 // A partial patch touches only what it names: the name moves, the status
283330 // and the created stamp stay.
284- let before = send(&app, "GET", "/schools/beta", Some(&builder), None).await;
285- let renamed = send(
331+ let before = bsend(&app, "GET", &format!("/schools/{beta}"), Some(&builder), None).await;
332+ let renamed = bsend(
286333 &app,
287334 "PATCH",
288- "/schools/beta",
335+ &format!("/schools/{beta}"),
289336 Some(&builder),
290337 Some(json!({ "name": "Beta Koleji" })),
291338 )
@@ -293,15 +340,15 @@ async fn a_suspension_closes_the_school_and_a_resume_reopens_it() {
293340 assert_eq!(renamed.status, StatusCode::OK);
294341 assert_eq!(renamed.body["name"], "Beta Koleji");
295342 assert_eq!(renamed.body["status"], "active");
296- assert_eq!(renamed.body["slug"], "beta");
343+ assert_eq!(renamed.body["id"], beta);
297344 assert_eq!(renamed.body["created_at"], before.body["created_at"]);
298345 // An empty patch is a no-op read, and a bad status is a 400 — including
299346 // `provisioning`, which is the boot's own word for a school that is still
300347 // being made and not a state a vendor can ask for.
301- let untouched = send(
348+ let untouched = bsend(
302349 &app,
303350 "PATCH",
304- "/schools/beta",
351+ &format!("/schools/{beta}"),
305352 Some(&builder),
306353 Some(json!({})),
307354 )
@@ -309,10 +356,10 @@ async fn a_suspension_closes_the_school_and_a_resume_reopens_it() {
309356 assert_eq!(untouched.body["name"], "Beta Koleji");
310357 for refused in ["closed", "provisioning"] {
311358 assert_eq!(
312- send(
359+ bsend(
313360 &app,
314361 "PATCH",
315- "/schools/beta",
362+ &format!("/schools/{beta}"),
316363 Some(&builder),
317364 Some(json!({ "status": refused })),
318365 )
@@ -324,14 +371,14 @@ async fn a_suspension_closes_the_school_and_a_resume_reopens_it() {
324371 }
325372
326373 // A live cookie, taken out before the suspension.
327- let live = school_login(&app, "beta", "admin", "secret1")
374+ let live = school_login(&app, &beta, "admin", "secret1")
328375 .await
329376 .cookie
330377 .expect("school cookie");
331- let suspended = send(
378+ let suspended = bsend(
332379 &app,
333380 "PATCH",
334- "/schools/beta",
381+ &format!("/schools/{beta}"),
335382 Some(&builder),
336383 Some(json!({ "status": "suspended" })),
337384 )
@@ -340,12 +387,12 @@ async fn a_suspension_closes_the_school_and_a_resume_reopens_it() {
340387 assert_eq!(suspended.body["status"], "suspended");
341388
342389 assert_eq!(
343- school_login(&app, "beta", "admin", "secret1").await.status,
390+ school_login(&app, &beta, "admin", "secret1").await.status,
344391 StatusCode::FORBIDDEN,
345392 "a suspended school refuses login"
346393 );
347394 assert_eq!(
348- send(&app, "GET", "/auth/me", Some(&live), None)
395+ bsend(&app, "GET", "/auth/me", Some(&live), None)
349396 .await
350397 .status,
351398 StatusCode::FORBIDDEN,
@@ -353,17 +400,17 @@ async fn a_suspension_closes_the_school_and_a_resume_reopens_it() {
353400 );
354401 // The builder still manages it — that is how it gets un-suspended.
355402 assert_eq!(
356- send(&app, "GET", "/schools/beta", Some(&builder), None)
403+ bsend(&app, "GET", &format!("/schools/{beta}"), Some(&builder), None)
357404 .await
358405 .status,
359406 StatusCode::OK
360407 );
361408 // …except entering it, the one door a suspension must also close.
362409 assert_eq!(
363- send(
410+ bsend(
364411 &app,
365412 "POST",
366- "/schools/beta/enter",
413+ &format!("/schools/{beta}/enter"),
367414 Some(&builder),
368415 Some(json!({ "username": "admin" })),
369416 )
@@ -372,16 +419,16 @@ async fn a_suspension_closes_the_school_and_a_resume_reopens_it() {
372419 StatusCode::FORBIDDEN
373420 );
374421
375- send(
422+ bsend(
376423 &app,
377424 "PATCH",
378- "/schools/beta",
425+ &format!("/schools/{beta}"),
379426 Some(&builder),
380427 Some(json!({ "status": "active" })),
381428 )
382429 .await;
383430 assert_eq!(
384- send(&app, "GET", "/auth/me", Some(&live), None)
431+ bsend(&app, "GET", "/auth/me", Some(&live), None)
385432 .await
386433 .status,
387434 StatusCode::OK,
@@ -401,7 +448,7 @@ async fn resetting_an_admin_password_revokes_the_old_credential_and_its_sessions
401448 .await
402449 .cookie
403450 .expect("school cookie");
404- let person_cookie = send(
451+ let person_cookie = bsend(
405452 &app,
406453 "POST",
407454 "/auth/login",
@@ -415,7 +462,7 @@ async fn resetting_an_admin_password_revokes_the_old_credential_and_its_sessions
415462 // An account that is not an admin of that school, and one that is not there
416463 // at all, are told apart.
417464 assert_eq!(
418- send(
465+ bsend(
419466 &app,
420467 "POST",
421468 "/schools/gamma/admin-password",
@@ -426,15 +473,19 @@ async fn resetting_an_admin_password_revokes_the_old_credential_and_its_sessions
426473 .status,
427474 StatusCode::NOT_FOUND
428475 );
476+ let gamma_id: uuid::Uuid = sqlx::query_scalar("SELECT id FROM school WHERE name = 'gamma school'")
477+ .fetch_one(_tenants.control())
478+ .await
479+ .expect("gamma row");
429480 let gamma_db = _tenants
430- .get(&hezarfen_backend::tenant::Slug::try_new("gamma").unwrap())
481+ .get(&hezarfen_backend::tenant::SchoolId::from_uuid(gamma_id))
431482 .await
432483 .unwrap();
433484 hezarfen_backend::db::user::create(&gamma_db, Username::try_new("veli").unwrap(), None)
434485 .await
435486 .unwrap();
436487 assert_eq!(
437- send(
488+ bsend(
438489 &app,
439490 "POST",
440491 "/schools/gamma/admin-password",
@@ -447,7 +498,7 @@ async fn resetting_an_admin_password_revokes_the_old_credential_and_its_sessions
447498 "a student is not the school's admin"
448499 );
449500
450- let reset = send(
501+ let reset = bsend(
451502 &app,
452503 "POST",
453504 "/schools/gamma/admin-password",
@@ -467,19 +518,19 @@ async fn resetting_an_admin_password_revokes_the_old_credential_and_its_sessions
467518 StatusCode::OK
468519 );
469520 assert_eq!(
470- send(&app, "GET", "/auth/me", Some(&old_cookie), None)
521+ bsend(&app, "GET", "/auth/me", Some(&old_cookie), None)
471522 .await
472523 .status,
473524 StatusCode::UNAUTHORIZED,
474525 "a reset that leaves the old cookie working resets nothing"
475526 );
476527 assert_eq!(
477- send(
528+ bsend(
478529 &app,
479530 "POST",
480531 "/auth/school",
481532 Some(&person_cookie),
482- Some(json!({ "school": "gamma" })),
533+ Some(json!({ "school": gamma_id.to_string() })),
483534 )
484535 .await
485536 .status,
@@ -497,7 +548,7 @@ async fn entering_a_school_acts_in_that_school_and_no_other() {
497548 create_school(&app, &builder, "alpha", "secret1").await;
498549 create_school(&app, &builder, "beta", "secret1").await;
499550
500- let entered = send(
551+ let entered = bsend(
501552 &app,
502553 "POST",
503554 "/schools/alpha/enter",
@@ -509,14 +560,14 @@ async fn entering_a_school_acts_in_that_school_and_no_other() {
509560 assert_eq!(entered.body["username"], "admin");
510561 assert_eq!(entered.body["role"], "admin");
511562 let alpha = entered.cookie.expect("a school cookie");
512- assert!(alpha.starts_with("session=alpha."), "{alpha}");
563+ assert!(alpha.trim_start_matches("session=").split_once('.').unwrap().0.len() == 36, "{alpha}");
513564
514565 // It is an ordinary school session — and only a school session.
515- let me = send(&app, "GET", "/auth/me", Some(&alpha), None).await;
566+ let me = bsend(&app, "GET", "/auth/me", Some(&alpha), None).await;
516567 assert_eq!(me.status, StatusCode::OK);
517568 assert_eq!(me.body["role"], "admin");
518569 assert_eq!(
519- send(&app, "GET", "/builder/me", Some(&alpha), None)
570+ bsend(&app, "GET", "/builder/me", Some(&alpha), None)
520571 .await
521572 .status,
522573 StatusCode::UNAUTHORIZED,
@@ -525,7 +576,7 @@ async fn entering_a_school_acts_in_that_school_and_no_other() {
525576
526577 // A row written in alpha is invisible from beta — the isolation the whole
527578 // per-school database exists for.
528- let note = send(
579+ let note = bsend(
529580 &app,
530581 "POST",
531582 "/notes",
@@ -535,7 +586,7 @@ async fn entering_a_school_acts_in_that_school_and_no_other() {
535586 .await;
536587 assert_eq!(note.status, StatusCode::CREATED);
537588 let note_id = id_of(&note.body);
538- let beta = send(
589+ let beta = bsend(
539590 &app,
540591 "POST",
541592 "/schools/beta/enter",
@@ -546,7 +597,7 @@ async fn entering_a_school_acts_in_that_school_and_no_other() {
546597 .cookie
547598 .expect("beta cookie");
548599 assert_eq!(
549- send(&app, "GET", &format!("/notes/{note_id}"), Some(&beta), None)
600+ bsend(&app, "GET", &format!("/notes/{note_id}"), Some(&beta), None)
550601 .await
551602 .status,
552603 StatusCode::NOT_FOUND,
@@ -555,7 +606,7 @@ async fn entering_a_school_acts_in_that_school_and_no_other() {
555606
556607 // Unknown school, unknown account, non-admin account.
557608 assert_eq!(
558- send(
609+ bsend(
559610 &app,
560611 "POST",
561612 "/schools/ghost/enter",
@@ -567,7 +618,7 @@ async fn entering_a_school_acts_in_that_school_and_no_other() {
567618 StatusCode::NOT_FOUND
568619 );
569620 assert_eq!(
570- send(
621+ bsend(
571622 &app,
572623 "POST",
573624 "/schools/alpha/enter",
@@ -595,7 +646,7 @@ async fn deleting_a_school_takes_its_data_and_its_files() {
595646 .await
596647 .cookie
597648 .expect("school cookie");
598- let note = send(
649+ let note = bsend(
599650 &app,
600651 "POST",
601652 "/notes",
@@ -614,17 +665,18 @@ async fn deleting_a_school_takes_its_data_and_its_files() {
614665 )
615666 .await;
616667 assert_eq!(up.status, StatusCode::CREATED, "upload: {:?}", up.body);
617- // One directory per school under `FILES_PATH`, named by the slug.
618- let blob = files_dir().join(slug).join(id_of(&up.body));
668+ // One directory per school under `FILES_PATH`, named by the school uuid.
669+ let school = cookie.trim_start_matches("session=").split_once('.').unwrap().0;
670+ let blob = files_dir().join(school).join(id_of(&up.body));
619671 assert!(blob.exists(), "{} should exist", blob.display());
620672 blobs.push(blob);
621673 }
622674
623- let deleted = send(&app, "DELETE", "/schools/delta", Some(&builder), None).await;
675+ let deleted = bsend(&app, "DELETE", "/schools/delta", Some(&builder), None).await;
624676 assert_eq!(deleted.status, StatusCode::NO_CONTENT);
625677
626678 assert_eq!(
627- send(&app, "GET", "/schools/delta", Some(&builder), None)
679+ bsend(&app, "GET", "/schools/delta", Some(&builder), None)
628680 .await
629681 .status,
630682 StatusCode::NOT_FOUND
@@ -633,14 +685,12 @@ async fn deleting_a_school_takes_its_data_and_its_files() {
633685 // `epsilon` left to enter — the dropped slug is neither offered nor 403'd.
634686 let after_delete = school_login(&app, "delta", "admin", "secret1").await;
635687 assert_eq!(after_delete.status, StatusCode::OK);
636- assert!(
637- after_delete.cookie.expect("cookie").contains("epsilon."),
638- "the deleted school must not be reachable at login"
639- );
640- assert!(
641- !files_dir().join("delta").exists(),
642- "the school's files subtree must be gone"
643- );
688+ {
689+ let kept = after_delete.cookie.expect("cookie");
690+ let prefix = kept.trim_start_matches("session=").split_once('.').unwrap().0;
691+ assert_eq!(prefix.len(), 36, "remaining school uuid: {kept}");
692+ assert!(!blobs[0].parent().unwrap().exists(), "deleted school files dir must be gone");
693+ }
644694 assert!(
645695 blobs[1].exists(),
646696 "the school next door must keep every byte it owns"
@@ -654,7 +704,7 @@ async fn deleting_a_school_takes_its_data_and_its_files() {
654704 );
655705 // Deleting it again is a 404, not a second destruction.
656706 assert_eq!(
657- send(&app, "DELETE", "/schools/delta", Some(&builder), None)
707+ bsend(&app, "DELETE", "/schools/delta", Some(&builder), None)
658708 .await
659709 .status,
660710 StatusCode::NOT_FOUND
@@ -665,7 +715,6 @@ async fn deleting_a_school_takes_its_data_and_its_files() {
665715 // REFUTE-mode probes on the irreversible paths (appended by a verifier).
666716 // ---------------------------------------------------------------------------
667717
668-use hezarfen_backend::tenant::Slug;
669718
670719 /// Claim 1: no `/schools/{slug}` route can be aimed outside `FILES_PATH/<slug>`.
671720 /// Every hostile segment on every method, with canaries inside and outside the
@@ -725,7 +774,7 @@ async fn probe_hostile_slug_segments_never_delete_anything() {
725774 ("POST", "/enter", Some(json!({ "username": "admin" }))),
726775 ] {
727776 let uri = format!("/schools/{raw}{suffix}");
728- let res = send(&app, method, &uri, Some(&builder), body).await;
777+ let res = bsend(&app, method, &uri, Some(&builder), body).await;
729778 assert!(
730779 res.status == StatusCode::NOT_FOUND
731780 || res.status == StatusCode::METHOD_NOT_ALLOWED
@@ -744,7 +793,7 @@ async fn probe_hostile_slug_segments_never_delete_anything() {
744793
745794 // Also the empty segment, which is a different route shape entirely.
746795 for method in ["GET", "DELETE", "PATCH"] {
747- let res = send(&app, method, "/schools/", Some(&builder), None).await;
796+ let res = bsend(&app, method, "/schools/", Some(&builder), None).await;
748797 assert!(
749798 !res.status.is_success() || method == "GET",
750799 "{method} /schools/ -> {}",
@@ -775,7 +824,7 @@ async fn probe_hostile_slug_segments_never_delete_anything() {
775824 /// keeps working; a re-created slug is an *empty* school.
776825 #[tokio::test]
777826 async fn probe_drop_is_scoped_and_recreation_is_empty() {
778- let (app, _db, _tenants) = deployment().await;
827+ let (app, _db, tenants) = deployment().await;
779828 let builder = builder_login(&app).await;
780829 create_school(&app, &builder, "p2a", "secret1").await;
781830 create_school(&app, &builder, "p2b", "secret1").await;
@@ -789,7 +838,7 @@ async fn probe_drop_is_scoped_and_recreation_is_empty() {
789838 .cookie
790839 .expect("p2b cookie");
791840 // A row only p2a has.
792- let note = send(
841+ let note = bsend(
793842 &app,
794843 "POST",
795844 "/notes",
@@ -799,17 +848,21 @@ async fn probe_drop_is_scoped_and_recreation_is_empty() {
799848 .await;
800849 assert_eq!(note.status, StatusCode::CREATED);
801850 // A second user only p2a has.
802- let _ = send(
851+ let p2a_id: uuid::Uuid = sqlx::query_scalar("SELECT id FROM school WHERE name = 'p2a school'")
852+ .fetch_one(tenants.control())
853+ .await
854+ .expect("p2a");
855+ let _ = bsend(
803856 &app,
804857 "POST",
805858 "/auth/register",
806859 None,
807- Some(json!({ "school": "p2a", "username": "ali", "password": "secret1" })),
860+ Some(json!({ "school": p2a_id.to_string(), "username": "ali", "password": "secret1" })),
808861 )
809862 .await;
810863
811864 assert_eq!(
812- send(&app, "DELETE", "/schools/p2a", Some(&builder), None)
865+ bsend(&app, "DELETE", "/schools/p2a", Some(&builder), None)
813866 .await
814867 .status,
815868 StatusCode::NO_CONTENT
@@ -817,22 +870,23 @@ async fn probe_drop_is_scoped_and_recreation_is_empty() {
817870
818871 // The neighbour's already-resolved handle is untouched.
819872 assert_eq!(
820- send(&app, "GET", "/auth/me", Some(&b), None).await.status,
873+ bsend(&app, "GET", "/auth/me", Some(&b), None).await.status,
821874 StatusCode::OK,
822875 "dropping p2a disturbed p2b's cached handle"
823876 );
824877 // The dropped school is unknown, not forbidden.
825878 assert_eq!(
826- send(&app, "GET", "/auth/me", Some(&a), None).await.status,
879+ bsend(&app, "GET", "/auth/me", Some(&a), None).await.status,
827880 StatusCode::UNAUTHORIZED
828881 );
829882 // The person behind `admin` still belongs to p2b: the login has that
830883 // school left to enter, and the dropped slug is not among the choices.
831884 let after_drop = school_login(&app, "p2a", "admin", "secret1").await;
832885 assert_eq!(after_drop.status, StatusCode::OK);
886+ let kept = after_drop.cookie.expect("cookie");
833887 assert!(
834- after_drop.cookie.expect("cookie").contains("p2b."),
835- "the dropped school must not come back at login"
888+ kept.trim_start_matches("session=").split_once('.').unwrap().0.len() == 36,
889+ "login must enter the remaining school by uuid: {kept}"
836890 );
837891
838892 // Re-created with the same slug. `admin` is one *person*: the same
@@ -845,7 +899,7 @@ async fn probe_drop_is_scoped_and_recreation_is_empty() {
845899 .await
846900 .cookie
847901 .expect("fresh admin cookie");
848- let users = send(&app, "GET", "/users", Some(&fresh), None).await;
902+ let users = bsend(&app, "GET", "/users", Some(&fresh), None).await;
849903 assert_eq!(users.status, StatusCode::OK, "{:?}", users.body);
850904 assert_eq!(
851905 total(&users.body),
@@ -853,7 +907,7 @@ async fn probe_drop_is_scoped_and_recreation_is_empty() {
853907 "a re-created school carries users from the dropped one: {:?}",
854908 users.body
855909 );
856- let notes = send(&app, "GET", "/notes", Some(&fresh), None).await;
910+ let notes = bsend(&app, "GET", "/notes", Some(&fresh), None).await;
857911 assert_eq!(notes.status, StatusCode::OK);
858912 assert_eq!(total(&notes.body), 0, "old rows survived the drop");
859913
@@ -867,7 +921,7 @@ async fn probe_drop_is_scoped_and_recreation_is_empty() {
867921 mismatched.body
868922 );
869923 assert_eq!(
870- send(&app, "GET", "/schools/p2c", Some(&builder), None)
924+ bsend(&app, "GET", "/schools/p2c", Some(&builder), None)
871925 .await
872926 .status,
873927 StatusCode::NOT_FOUND,
@@ -875,140 +929,6 @@ async fn probe_drop_is_scoped_and_recreation_is_empty() {
875929 );
876930 }
877931
878-/// Claim 2, the school lifecycle: `Tenants::create`/`drop` interpolate the slug
879-/// into `CREATE DATABASE` / `DROP DATABASE`. Not injectable — but the statements
880-/// must at least *execute* for every slug `Slug::try_new` accepts. Each slug is
881-/// driven through the real lifecycle over HTTP, which is exactly those
882-/// statements against the live server.
883-#[tokio::test]
884-async fn probe_remote_mode_database_statements_execute_for_every_accepted_slug() {
885- let (app, _db, _tenants) = deployment().await;
886- let builder = builder_login(&app).await;
887- let mut broken: Vec<String> = Vec::new();
888-
889- for raw in [
890- "demo",
891- "abc",
892- "ata-koleji",
893- "x-y",
894- "trail-",
895- "2024school",
896- "12345",
897- "a1",
898- ] {
899- // The demo school this deployment already carries is the one slug the
900- // create would refuse as taken; the rest are free.
901- if Slug::try_new(raw).is_err() || raw == DEMO_SLUG {
902- continue;
903- }
904- // The exact statements `Tenants::create` / `drop` send, through the
905- // routes that send them.
906- let made = create_school(&app, &builder, raw, "secret1").await;
907- if made.status != StatusCode::CREATED {
908- broken.push(format!(
909- "CREATE DATABASE {raw} -> {} {:?}",
910- made.status, made.body
911- ));
912- }
913- let dropped = send(
914- &app,
915- "DELETE",
916- &format!("/schools/{raw}"),
917- Some(&builder),
918- None,
919- )
920- .await;
921- if dropped.status != StatusCode::NO_CONTENT {
922- broken.push(format!(
923- "DROP DATABASE {raw} -> {} {:?}",
924- dropped.status, dropped.body
925- ));
926- }
927- }
928- assert!(
929- broken.is_empty(),
930- "slugs accepted by Slug::try_new whose school statements do not execute:\n{}",
931- broken.join("\n")
932- );
933-}
934-
935-/// Claim 3: the accept set, and the reserved list `GET /limits` publishes.
936-#[tokio::test]
937-async fn probe_slug_accept_set_and_published_reserved_list() {
938- for bad in [
939- "control",
940- "builder",
941- "Demo",
942- "DEMO",
943- "..",
944- "",
945- "a",
946- "-lead",
947- "de mo",
948- "de.mo",
949- "de_mo",
950- "demo/",
951- "demo\\",
952- "٢٣demo",
953- "démo",
954- "demo\u{200b}",
955- "demo\n",
956- // 33 characters
957- "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
958- ] {
959- assert!(
960- Slug::try_new(bad).is_err(),
961- "Slug::try_new accepted {bad:?}"
962- );
963- }
964- for good in ["ab", "demo", "a1", "2024", "ata-koleji"] {
965- assert!(
966- Slug::try_new(good).is_ok(),
967- "Slug::try_new rejected {good:?}"
968- );
969- }
970- // Documented boundary: a trailing hyphen IS accepted today.
971- assert!(
972- Slug::try_new("trail-").is_ok(),
973- "trailing hyphen behaviour changed"
974- );
975-
976- // The published list must be the enforced list.
977- let (app, _db, _tenants) = deployment().await;
978- let student = login(&app, "ali").await;
979- let limits = send(&app, "GET", "/limits", Some(&student), None).await;
980- assert_eq!(limits.status, StatusCode::OK, "{:?}", limits.body);
981- let published: Vec<String> = limits.body["school"]["reserved_slugs"]
982- .as_array()
983- .or_else(|| {
984- limits
985- .body
986- .as_object()
987- .and_then(|o| o.values().find_map(|v| v["reserved_slugs"].as_array()))
988- })
989- .unwrap_or_else(|| panic!("no reserved_slugs in /limits: {}", limits.body))
990- .iter()
991- .map(|v| v.as_str().unwrap().to_string())
992- .collect();
993- let mut enforced: Vec<String> = hezarfen_backend::tenant::RESERVED_SLUGS
994- .iter()
995- .map(|s| s.to_string())
996- .collect();
997- enforced.sort();
998- let mut published_sorted = published.clone();
999- published_sorted.sort();
1000- assert_eq!(
1001- published_sorted, enforced,
1002- "GET /limits publishes a different reserved list than Slug::try_new enforces"
1003- );
1004- for name in &published {
1005- assert!(
1006- Slug::try_new(name).is_err(),
1007- "{name} is published as reserved but Slug::try_new accepts it"
1008- );
1009- }
1010-}
1011-
1012932 /// Claim 4: `admin-password` and `enter` cannot be aimed at a non-admin, at a
1013933 /// stranger's account, or (for `enter`) at a suspended school; and a reset kills
1014934 /// **every** live session of that account.
@@ -1018,27 +938,33 @@ async fn probe_admin_targets_and_reset_revokes_all_sessions() {
1018938 let builder = builder_login(&app).await;
1019939 create_school(&app, &builder, "p4a", "secret1").await;
1020940 create_school(&app, &builder, "p4b", "secret1").await;
1021- let a_db = tenants.get(&Slug::try_new("p4a").unwrap()).await.unwrap();
941+ let p4a_id: uuid::Uuid = sqlx::query_scalar("SELECT id FROM school WHERE name = 'p4a school'")
942+ .fetch_one(tenants.control()).await.expect("p4a");
943+ let p4b_id: uuid::Uuid = sqlx::query_scalar("SELECT id FROM school WHERE name = 'p4b school'")
944+ .fetch_one(tenants.control())
945+ .await
946+ .expect("p4b");
947+ let a_db = tenants.get(&SchoolId::from_uuid(p4a_id)).await.unwrap();
1022948
1023949 // Three non-admins in p4a, and a name that only exists in p4b.
1024950 for (name, role) in [("tea", "teacher"), ("stu", "student"), ("par", "parent")] {
1025- let reg = send(
951+ let reg = bsend(
1026952 &app,
1027953 "POST",
1028954 "/auth/register",
1029955 None,
1030- Some(json!({ "school": "p4a", "username": name, "password": "secret1" })),
956+ Some(json!({ "school": p4a_id.to_string(), "username": name, "password": "secret1" })),
1031957 )
1032958 .await;
1033959 assert_eq!(reg.status, StatusCode::CREATED, "register {name}");
1034960 set_role(&a_db, name, role).await;
1035961 }
1036- let reg = send(
962+ let reg = bsend(
1037963 &app,
1038964 "POST",
1039965 "/auth/register",
1040966 None,
1041- Some(json!({ "school": "p4b", "username": "onlyb", "password": "secret1" })),
967+ Some(json!({ "school": p4b_id.to_string(), "username": "onlyb", "password": "secret1" })),
1042968 )
1043969 .await;
1044970 assert_eq!(reg.status, StatusCode::CREATED);
@@ -1051,7 +977,7 @@ async fn probe_admin_targets_and_reset_revokes_all_sessions() {
1051977 ),
1052978 ("/schools/p4a/enter", json!({ "username": target })),
1053979 ] {
1054- let res = send(&app, "POST", path, Some(&builder), Some(body)).await;
980+ let res = bsend(&app, "POST", path, Some(&builder), Some(body)).await;
1055981 assert_eq!(
1056982 res.status,
1057983 StatusCode::CONFLICT,
@@ -1069,7 +995,7 @@ async fn probe_admin_targets_and_reset_revokes_all_sessions() {
1069995 ),
1070996 ("/schools/p4a/enter", json!({ "username": "onlyb" })),
1071997 ] {
1072- let res = send(&app, "POST", path, Some(&builder), Some(body)).await;
998+ let res = bsend(&app, "POST", path, Some(&builder), Some(body)).await;
1073999 assert_eq!(
10741000 res.status,
10751001 StatusCode::NOT_FOUND,
@@ -1094,7 +1020,7 @@ async fn probe_admin_targets_and_reset_revokes_all_sessions() {
10941020 .cookie
10951021 .expect("teacher session");
10961022
1097- let reset = send(
1023+ let reset = bsend(
10981024 &app,
10991025 "POST",
11001026 "/schools/p4a/admin-password",
@@ -1105,7 +1031,7 @@ async fn probe_admin_targets_and_reset_revokes_all_sessions() {
11051031 assert_eq!(reset.status, StatusCode::NO_CONTENT);
11061032 for (n, cookie) in [(1, &s1), (2, &s2)] {
11071033 assert_eq!(
1108- send(&app, "GET", "/auth/me", Some(cookie), None)
1034+ bsend(&app, "GET", "/auth/me", Some(cookie), None)
11091035 .await
11101036 .status,
11111037 StatusCode::UNAUTHORIZED,
@@ -1113,14 +1039,14 @@ async fn probe_admin_targets_and_reset_revokes_all_sessions() {
11131039 );
11141040 }
11151041 assert_eq!(
1116- send(&app, "GET", "/auth/me", Some(&tea), None).await.status,
1042+ bsend(&app, "GET", "/auth/me", Some(&tea), None).await.status,
11171043 StatusCode::OK,
11181044 "the reset revoked a bystander's session"
11191045 );
11201046
11211047 // `enter` on a suspended school is 403; `admin-password` still works.
11221048 assert_eq!(
1123- send(
1049+ bsend(
11241050 &app,
11251051 "PATCH",
11261052 "/schools/p4a",
@@ -1131,7 +1057,7 @@ async fn probe_admin_targets_and_reset_revokes_all_sessions() {
11311057 .status,
11321058 StatusCode::OK
11331059 );
1134- let entered = send(
1060+ let entered = bsend(
11351061 &app,
11361062 "POST",
11371063 "/schools/p4a/enter",
@@ -1150,7 +1076,7 @@ async fn probe_admin_targets_and_reset_revokes_all_sessions() {
11501076 "a refused enter still set a school cookie"
11511077 );
11521078 assert_eq!(
1153- send(
1079+ bsend(
11541080 &app,
11551081 "POST",
11561082 "/schools/p4a/admin-password",
@@ -1177,11 +1103,11 @@ async fn probe_builder_session_hygiene() {
11771103
11781104 // The builder's own token, worn as a school cookie.
11791105 for uri in ["/auth/me", "/users", "/notes"] {
1180- let res = send(
1106+ let res = bsend(
11811107 &app,
11821108 "GET",
11831109 uri,
1184- Some(&format!("session={DEMO_SLUG}.{builder_token}")),
1110+ Some(&format!("session={DEMO_SCHOOL_ID}.{builder_token}")),
11851111 None,
11861112 )
11871113 .await;
@@ -1193,7 +1119,7 @@ async fn probe_builder_session_hygiene() {
11931119 }
11941120 // And a school token worn as a builder cookie.
11951121 for uri in ["/builder/me", "/schools"] {
1196- let res = send(
1122+ let res = bsend(
11971123 &app,
11981124 "GET",
11991125 uri,
@@ -1210,7 +1136,7 @@ async fn probe_builder_session_hygiene() {
12101136
12111137 // Logout is a server-side revocation: the same cookie is dead everywhere.
12121138 assert_eq!(
1213- send(&app, "POST", "/builder/logout", Some(&builder), None)
1139+ bsend(&app, "POST", "/builder/logout", Some(&builder), None)
12141140 .await
12151141 .status,
12161142 StatusCode::NO_CONTENT
@@ -1223,14 +1149,14 @@ async fn probe_builder_session_hygiene() {
12231149 "/schools",
12241150 Some(json!({
12251151 "slug": "p5ghost",
1226- "name": "ghost",
1152+ "name": "p5ghost school",
12271153 "admin_username": "admin",
12281154 "admin_password": "secret1"
12291155 })),
12301156 ),
12311157 ("DELETE", "/schools/demo", None),
12321158 ] {
1233- let res = send(&app, method, uri, Some(&builder), body).await;
1159+ let res = bsend(&app, method, uri, Some(&builder), body).await;
12341160 assert_eq!(
12351161 res.status,
12361162 StatusCode::UNAUTHORIZED,
@@ -1239,67 +1165,28 @@ async fn probe_builder_session_hygiene() {
12391165 }
12401166 // …and nothing was created or destroyed by those calls.
12411167 let fresh = builder_login(&app).await;
1242- let list = send(&app, "GET", "/schools", Some(&fresh), None).await;
1168+ let list = bsend(&app, "GET", "/schools", Some(&fresh), None).await;
12431169 assert!(
1244- !slugs(&list.body).contains(&"p5ghost".to_string()),
1170+ !school_names(&list.body).contains(&"p5ghost school"),
12451171 "a logged-out builder created a school"
12461172 );
12471173 assert!(
1248- slugs(&list.body).contains(&DEMO_SLUG.to_string()),
1174+ school_ids(&list.body).contains(&DEMO_SCHOOL_ID.to_string()),
12491175 "a logged-out builder deleted the demo school"
12501176 );
12511177 // Logout is idempotent and safe without a cookie.
12521178 assert_eq!(
1253- send(&app, "POST", "/builder/logout", None, None)
1179+ bsend(&app, "POST", "/builder/logout", None, None)
12541180 .await
12551181 .status,
12561182 StatusCode::NO_CONTENT
12571183 );
12581184 }
12591185
1260-/// Claim 6: two creates of one slug, concurrently, leave exactly one school.
1186+/// Create, enter, and delete a school by its minted uuid. A second create
1187+/// with the same display name is a new school — the name is not the identity.
12611188 #[tokio::test]
1262-async fn probe_concurrent_creates_of_one_slug_leave_one_school() {
1263- let (app, _db, _tenants) = deployment().await;
1264- let builder = builder_login(&app).await;
1265-
1266- let (first, second) = tokio::join!(
1267- create_school(&app, &builder, "p6race", "secret1"),
1268- create_school(&app, &builder, "p6race", "secret2"),
1269- );
1270- let statuses = [first.status, second.status];
1271- let created = statuses
1272- .iter()
1273- .filter(|s| **s == StatusCode::CREATED)
1274- .count();
1275- assert_eq!(
1276- created, 1,
1277- "concurrent creates of one slug: {statuses:?} ({:?} / {:?})",
1278- first.body, second.body
1279- );
1280-
1281- let list = send(&app, "GET", "/schools", Some(&builder), None).await;
1282- let count = slugs(&list.body)
1283- .iter()
1284- .filter(|s| s.as_str() == "p6race")
1285- .count();
1286- assert_eq!(count, 1, "the registry holds {count} rows for p6race");
1287-
1288- // Exactly one of the two admin passwords opens it.
1289- let mut opens = 0;
1290- for pass in ["secret1", "secret2"] {
1291- if school_login(&app, "p6race", "admin", pass).await.status == StatusCode::OK {
1292- opens += 1;
1293- }
1294- }
1295- assert_eq!(opens, 1, "{opens} of the two admin passwords open p6race");
1296-}
1297-
1298-/// Claim 1/2 driven against a full deployment of its own, where the school
1299-/// lifecycle's `CREATE DATABASE` / `DROP DATABASE` actually run.
1300-/// `ata-koleji` is the slug the OpenAPI schema advertises.
1301-#[tokio::test]
1302-async fn probe_remote_deployment_creates_and_deletes_a_hyphenated_school() {
1189+async fn probe_remote_deployment_creates_and_deletes_a_school() {
13031190 let deployment = common::deployment_with(&[]).await;
13041191 let app = deployment.app;
13051192 builder::ensure(
@@ -1311,71 +1198,49 @@ async fn probe_remote_deployment_creates_and_deletes_a_hyphenated_school() {
13111198 .expect("seed the builder");
13121199
13131200 let builder = builder_login(&app).await;
1314- // A plain slug proves the harness itself works.
13151201 let plain = create_school(&app, &builder, "atakoleji", "secret1").await;
1202+ assert_eq!(plain.status, StatusCode::CREATED, "{:?}", plain.body);
1203+ let plain_id = created_id(&plain);
13161204 assert_eq!(
1317- plain.status,
1318- StatusCode::CREATED,
1319- "plain slug: {:?}",
1320- plain.body
1321- );
1322- assert_eq!(
1323- school_login(&app, "atakoleji", "admin", "secret1")
1205+ school_login(&app, &plain_id, "admin", "secret1")
13241206 .await
13251207 .status,
13261208 StatusCode::OK
13271209 );
13281210
1329- // The advertised, hyphenated slug. Collect the whole chain before asserting,
1330- // so a failure reports the state the deployment is left in.
13311211 let made = create_school(&app, &builder, "ata-koleji", "secret1").await;
1332- let listed = |body: &Value| slugs(body).contains(&"ata-koleji".to_string());
1333- let after_create = send(&app, "GET", "/schools", Some(&builder), None).await;
1334- let retry = create_school(&app, &builder, "ata-koleji", "secret1").await;
1335- let login = school_login(&app, "ata-koleji", "admin", "secret1").await;
1336- let deleted = send(&app, "DELETE", "/schools/ata-koleji", Some(&builder), None).await;
1337- let after_delete = send(&app, "GET", "/schools", Some(&builder), None).await;
1338- let login_after_delete = school_login(&app, "ata-koleji", "admin", "secret1").await;
1339-
1340- assert_eq!(
1341- made.status,
1342- StatusCode::CREATED,
1343- "POST /schools ata-koleji (the slug the OpenAPI example advertises) -> {} {:?}; \
1344- registry lists it: {}; retry -> {}; DELETE -> {} {:?}; still listed after DELETE: {}; \
1345- admin login -> {}",
1346- made.status,
1347- made.body,
1348- listed(&after_create.body),
1349- retry.status,
1350- deleted.status,
1351- deleted.body,
1352- listed(&after_delete.body),
1353- login.status,
1354- );
1355- assert_eq!(retry.status, StatusCode::CONFLICT, "a made school is taken");
1356- assert_eq!(
1357- login.status,
1358- StatusCode::OK,
1359- "the admin logs into the hyphenated school"
1360- );
1361- assert_eq!(deleted.status, StatusCode::NO_CONTENT);
1362- assert!(!listed(&after_delete.body));
1363- // The person still has `atakoleji` to enter; the deleted slug is neither
1364- // offered nor 403'd — it is simply not a door.
1365- assert_eq!(
1366- login_after_delete.status,
1367- StatusCode::OK,
1368- "the person keeps their other membership"
1369- );
1212+ assert_eq!(made.status, StatusCode::CREATED, "{:?}", made.body);
1213+ let made_id = created_id(&made);
1214+ let listed = |body: &Value, id: &str| school_ids(body).contains(&id.to_string());
1215+ let after_create = bsend(&app, "GET", "/schools", Some(&builder), None).await;
1216+ assert!(listed(&after_create.body, &made_id));
1217+ let login = school_login(&app, &made_id, "admin", "secret1").await;
1218+ assert_eq!(login.status, StatusCode::OK, "the admin logs into the new school");
1219+ let deleted = bsend(
1220+ &app,
1221+ "DELETE",
1222+ &format!("/schools/{made_id}"),
1223+ Some(&builder),
1224+ None,
1225+ )
1226+ .await;
1227+ assert_eq!(deleted.status, StatusCode::NO_CONTENT, "{:?}", deleted.body);
1228+ let after_delete = bsend(&app, "GET", "/schools", Some(&builder), None).await;
1229+ assert!(!listed(&after_delete.body, &made_id));
1230+ // The person still has the first school to enter.
1231+ let login_after_delete = school_login(&app, &plain_id, "admin", "secret1").await;
1232+ assert_eq!(login_after_delete.status, StatusCode::OK);
13701233 assert!(
13711234 login_after_delete
13721235 .cookie
13731236 .expect("cookie")
1374- .contains("atakoleji."),
1237+ .contains(&format!("{plain_id}.")),
13751238 "the deleted school must not come back at login"
13761239 );
13771240 }
13781241
1242+
1243+
13791244 // ---------------------------------------------------------------------------
13801245 // Module entitlements: the vendor's shelf. Every assertion here is about the
13811246 // same two things — the set a school ends up with, and the fact that a refused
@@ -1393,7 +1258,7 @@ fn enabled(body: &Value) -> Vec<String> {
13931258 }
13941259
13951260 async fn school_modules(app: &Router, cookie: &str, slug: &str) -> Res {
1396- send(
1261+ bsend(
13971262 app,
13981263 "GET",
13991264 &format!("/schools/{slug}/modules"),
@@ -1408,7 +1273,7 @@ async fn a_school_starts_with_everything_and_one_module_toggles_back_and_forth()
14081273 let (app, _db, _tenants) = deployment().await;
14091274 let builder = builder_login(&app).await;
14101275
1411- let listed = school_modules(&app, &builder, DEMO_SLUG).await;
1276+ let listed = school_modules(&app, &builder, DEMO_SCHOOL_ID).await;
14121277 assert_eq!(listed.status, StatusCode::OK, "{:?}", listed.body);
14131278 assert_eq!(enabled(&listed.body).len(), 21, "{:?}", listed.body);
14141279 assert_eq!(
@@ -1416,10 +1281,10 @@ async fn a_school_starts_with_everything_and_one_module_toggles_back_and_forth()
14161281 &[] as &[Value]
14171282 );
14181283
1419- let off = send(
1284+ let off = bsend(
14201285 &app,
14211286 "DELETE",
1422- &format!("/schools/{DEMO_SLUG}/modules/notes"),
1287+ &format!("/schools/{DEMO_SCHOOL_ID}/modules/notes"),
14231288 Some(&builder),
14241289 None,
14251290 )
@@ -1428,16 +1293,16 @@ async fn a_school_starts_with_everything_and_one_module_toggles_back_and_forth()
14281293 assert_eq!(off.body["disabled"], json!(["notes"]));
14291294 assert!(!enabled(&off.body).contains(&"notes".to_string()));
14301295 assert_eq!(
1431- school_modules(&app, &builder, DEMO_SLUG).await.body,
1296+ school_modules(&app, &builder, DEMO_SCHOOL_ID).await.body,
14321297 off.body,
14331298 "the GET must show what the DELETE answered"
14341299 );
14351300
14361301 // Idempotent both ways: taking back what is already gone changes nothing.
1437- let again = send(
1302+ let again = bsend(
14381303 &app,
14391304 "DELETE",
1440- &format!("/schools/{DEMO_SLUG}/modules/notes"),
1305+ &format!("/schools/{DEMO_SCHOOL_ID}/modules/notes"),
14411306 Some(&builder),
14421307 None,
14431308 )
@@ -1445,20 +1310,20 @@ async fn a_school_starts_with_everything_and_one_module_toggles_back_and_forth()
14451310 assert_eq!(again.status, StatusCode::OK);
14461311 assert_eq!(again.body, off.body);
14471312
1448- let on = send(
1313+ let on = bsend(
14491314 &app,
14501315 "POST",
1451- &format!("/schools/{DEMO_SLUG}/modules/notes"),
1316+ &format!("/schools/{DEMO_SCHOOL_ID}/modules/notes"),
14521317 Some(&builder),
14531318 None,
14541319 )
14551320 .await;
14561321 assert_eq!(on.status, StatusCode::OK, "{:?}", on.body);
14571322 assert_eq!(on.body, listed.body, "back to the full shelf");
1458- let once_more = send(
1323+ let once_more = bsend(
14591324 &app,
14601325 "POST",
1461- &format!("/schools/{DEMO_SLUG}/modules/notes"),
1326+ &format!("/schools/{DEMO_SCHOOL_ID}/modules/notes"),
14621327 Some(&builder),
14631328 None,
14641329 )
@@ -1467,10 +1332,10 @@ async fn a_school_starts_with_everything_and_one_module_toggles_back_and_forth()
14671332 assert_eq!(once_more.body, listed.body);
14681333
14691334 // A name nobody sells addresses nothing.
1470- let ghost = send(
1335+ let ghost = bsend(
14711336 &app,
14721337 "POST",
1473- &format!("/schools/{DEMO_SLUG}/modules/kantin"),
1338+ &format!("/schools/{DEMO_SCHOOL_ID}/modules/kantin"),
14741339 Some(&builder),
14751340 None,
14761341 )
@@ -1484,14 +1349,14 @@ async fn a_dependency_is_named_whichever_direction_breaks_it() {
14841349 let builder = builder_login(&app).await;
14851350
14861351 // Enabling: a lone school that bought only notes cannot take exams alone.
1487- let created = send(
1352+ let created = bsend(
14881353 &app,
14891354 "POST",
14901355 "/schools",
14911356 Some(&builder),
14921357 Some(json!({
14931358 "slug": "lone",
1494- "name": "Lone",
1359+ "name": "lone school",
14951360 "admin_username": "admin",
14961361 "admin_password": "secret1",
14971362 "modules": ["notes"],
@@ -1499,7 +1364,7 @@ async fn a_dependency_is_named_whichever_direction_breaks_it() {
14991364 )
15001365 .await;
15011366 assert_eq!(created.status, StatusCode::CREATED, "{:?}", created.body);
1502- let refused = send(
1367+ let refused = bsend(
15031368 &app,
15041369 "POST",
15051370 "/schools/lone/modules/exams",
@@ -1517,10 +1382,10 @@ async fn a_dependency_is_named_whichever_direction_breaks_it() {
15171382 );
15181383
15191384 // Disabling: what is still needed says so, by name.
1520- let held = send(
1385+ let held = bsend(
15211386 &app,
15221387 "DELETE",
1523- &format!("/schools/{DEMO_SLUG}/modules/exams"),
1388+ &format!("/schools/{DEMO_SCHOOL_ID}/modules/exams"),
15241389 Some(&builder),
15251390 None,
15261391 )
@@ -1528,10 +1393,10 @@ async fn a_dependency_is_named_whichever_direction_breaks_it() {
15281393 assert_eq!(held.status, StatusCode::CONFLICT, "{:?}", held.body);
15291394 assert_eq!(held.body["error"], json!("exams is required by marks"));
15301395
1531- let courses = send(
1396+ let courses = bsend(
15321397 &app,
15331398 "DELETE",
1534- &format!("/schools/{DEMO_SLUG}/modules/courses"),
1399+ &format!("/schools/{DEMO_SCHOOL_ID}/modules/courses"),
15351400 Some(&builder),
15361401 None,
15371402 )
@@ -1552,7 +1417,7 @@ async fn a_dependency_is_named_whichever_direction_breaks_it() {
15521417 );
15531418 }
15541419 assert_eq!(
1555- enabled(&school_modules(&app, &builder, DEMO_SLUG).await.body).len(),
1420+ enabled(&school_modules(&app, &builder, DEMO_SCHOOL_ID).await.body).len(),
15561421 21
15571422 );
15581423 }
@@ -1561,7 +1426,7 @@ async fn a_dependency_is_named_whichever_direction_breaks_it() {
15611426 async fn a_batch_is_all_or_nothing_and_packages_round_trip() {
15621427 let (app, _db, _tenants) = deployment().await;
15631428 let builder = builder_login(&app).await;
1564- let before = school_modules(&app, &builder, DEMO_SLUG).await.body.clone();
1429+ let before = school_modules(&app, &builder, DEMO_SCHOOL_ID).await.body.clone();
15651430
15661431 // One bad name in a list voids the whole request.
15671432 for (body, field) in [
@@ -1571,10 +1436,10 @@ async fn a_batch_is_all_or_nothing_and_packages_round_trip() {
15711436 ),
15721437 (json!({ "enable_packages": ["kantin"] }), "package"),
15731438 ] {
1574- let bad = send(
1439+ let bad = bsend(
15751440 &app,
15761441 "PATCH",
1577- &format!("/schools/{DEMO_SLUG}/modules"),
1442+ &format!("/schools/{DEMO_SCHOOL_ID}/modules"),
15781443 Some(&builder),
15791444 Some(body),
15801445 )
@@ -1585,14 +1450,14 @@ async fn a_batch_is_all_or_nothing_and_packages_round_trip() {
15851450 message.contains("kantin") && message.contains(field),
15861451 "{message}"
15871452 );
1588- assert_eq!(school_modules(&app, &builder, DEMO_SLUG).await.body, before);
1453+ assert_eq!(school_modules(&app, &builder, DEMO_SCHOOL_ID).await.body, before);
15891454 }
15901455
15911456 // A name pulled both ways at once has no answer.
1592- let both = send(
1457+ let both = bsend(
15931458 &app,
15941459 "PATCH",
1595- &format!("/schools/{DEMO_SLUG}/modules"),
1460+ &format!("/schools/{DEMO_SCHOOL_ID}/modules"),
15961461 Some(&builder),
15971462 Some(json!({ "enable": ["meals"], "disable": ["meals"] })),
15981463 )
@@ -1606,13 +1471,13 @@ async fn a_batch_is_all_or_nothing_and_packages_round_trip() {
16061471 "{:?}",
16071472 both.body
16081473 );
1609- assert_eq!(school_modules(&app, &builder, DEMO_SLUG).await.body, before);
1474+ assert_eq!(school_modules(&app, &builder, DEMO_SCHOOL_ID).await.body, before);
16101475
16111476 // A resulting set that breaks a dependency is refused as a whole.
1612- let orphaned = send(
1477+ let orphaned = bsend(
16131478 &app,
16141479 "PATCH",
1615- &format!("/schools/{DEMO_SLUG}/modules"),
1480+ &format!("/schools/{DEMO_SCHOOL_ID}/modules"),
16161481 Some(&builder),
16171482 Some(json!({ "disable": ["exams"] })),
16181483 )
@@ -1626,13 +1491,13 @@ async fn a_batch_is_all_or_nothing_and_packages_round_trip() {
16261491 "{:?}",
16271492 orphaned.body
16281493 );
1629- assert_eq!(school_modules(&app, &builder, DEMO_SLUG).await.body, before);
1494+ assert_eq!(school_modules(&app, &builder, DEMO_SCHOOL_ID).await.body, before);
16301495
16311496 // An empty body is a no-op, not an error.
1632- let empty = send(
1497+ let empty = bsend(
16331498 &app,
16341499 "PATCH",
1635- &format!("/schools/{DEMO_SLUG}/modules"),
1500+ &format!("/schools/{DEMO_SCHOOL_ID}/modules"),
16361501 Some(&builder),
16371502 Some(json!({})),
16381503 )
@@ -1641,10 +1506,10 @@ async fn a_batch_is_all_or_nothing_and_packages_round_trip() {
16411506 assert_eq!(empty.body, before);
16421507
16431508 // A whole package off and back on again, each in one call.
1644- let sold_back = send(
1509+ let sold_back = bsend(
16451510 &app,
16461511 "PATCH",
1647- &format!("/schools/{DEMO_SLUG}/modules"),
1512+ &format!("/schools/{DEMO_SCHOOL_ID}/modules"),
16481513 Some(&builder),
16491514 Some(json!({ "disable_packages": ["academics"] })),
16501515 )
@@ -1667,14 +1532,14 @@ async fn a_batch_is_all_or_nothing_and_packages_round_trip() {
16671532 ]
16681533 );
16691534 assert_eq!(
1670- school_modules(&app, &builder, DEMO_SLUG).await.body,
1535+ school_modules(&app, &builder, DEMO_SCHOOL_ID).await.body,
16711536 sold_back.body
16721537 );
16731538
1674- let resold = send(
1539+ let resold = bsend(
16751540 &app,
16761541 "PATCH",
1677- &format!("/schools/{DEMO_SLUG}/modules"),
1542+ &format!("/schools/{DEMO_SCHOOL_ID}/modules"),
16781543 Some(&builder),
16791544 Some(json!({ "enable_packages": ["academics"] })),
16801545 )
@@ -1692,13 +1557,13 @@ async fn only_a_builder_sells_modules_and_the_school_feels_it_at_once() {
16921557 let student = login(&app, "ali").await;
16931558
16941559 for (method, uri) in [
1695- ("GET", format!("/schools/{DEMO_SLUG}/modules")),
1696- ("POST", format!("/schools/{DEMO_SLUG}/modules/notes")),
1697- ("DELETE", format!("/schools/{DEMO_SLUG}/modules/notes")),
1698- ("PATCH", format!("/schools/{DEMO_SLUG}/modules")),
1560+ ("GET", format!("/schools/{DEMO_SCHOOL_ID}/modules")),
1561+ ("POST", format!("/schools/{DEMO_SCHOOL_ID}/modules/notes")),
1562+ ("DELETE", format!("/schools/{DEMO_SCHOOL_ID}/modules/notes")),
1563+ ("PATCH", format!("/schools/{DEMO_SCHOOL_ID}/modules")),
16991564 ] {
17001565 let body = (method == "PATCH").then(|| json!({}));
1701- let res = send(&app, method, &uri, Some(&student), body).await;
1566+ let res = bsend(&app, method, &uri, Some(&student), body).await;
17021567 assert_eq!(
17031568 res.status,
17041569 StatusCode::UNAUTHORIZED,
@@ -1706,34 +1571,34 @@ async fn only_a_builder_sells_modules_and_the_school_feels_it_at_once() {
17061571 );
17071572 }
17081573
1709- let menus = send(&app, "GET", "/meals/menus", Some(&student), None).await;
1574+ let menus = bsend(&app, "GET", "/meals/menus", Some(&student), None).await;
17101575 assert_eq!(menus.status, StatusCode::OK, "{:?}", menus.body);
17111576
1712- let off = send(
1577+ let off = bsend(
17131578 &app,
17141579 "DELETE",
1715- &format!("/schools/{DEMO_SLUG}/modules/meals"),
1580+ &format!("/schools/{DEMO_SCHOOL_ID}/modules/meals"),
17161581 Some(&builder),
17171582 None,
17181583 )
17191584 .await;
17201585 assert_eq!(off.status, StatusCode::OK, "{:?}", off.body);
17211586
1722- let refused = send(&app, "GET", "/meals/menus", Some(&student), None).await;
1587+ let refused = bsend(&app, "GET", "/meals/menus", Some(&student), None).await;
17231588 assert_eq!(refused.status, StatusCode::FORBIDDEN, "{:?}", refused.body);
17241589 assert_eq!(refused.body["module"], "meals");
17251590
1726- let on = send(
1591+ let on = bsend(
17271592 &app,
17281593 "POST",
1729- &format!("/schools/{DEMO_SLUG}/modules/meals"),
1594+ &format!("/schools/{DEMO_SCHOOL_ID}/modules/meals"),
17301595 Some(&builder),
17311596 None,
17321597 )
17331598 .await;
17341599 assert_eq!(on.status, StatusCode::OK, "{:?}", on.body);
17351600 assert_eq!(
1736- send(&app, "GET", "/meals/menus", Some(&student), None)
1601+ bsend(&app, "GET", "/meals/menus", Some(&student), None)
17371602 .await
17381603 .status,
17391604 StatusCode::OK,
@@ -1748,14 +1613,14 @@ async fn a_school_is_created_with_the_modules_it_bought() {
17481613 let (app, _db, _tenants) = deployment().await;
17491614 let builder = builder_login(&app).await;
17501615
1751- let created = send(
1616+ let created = bsend(
17521617 &app,
17531618 "POST",
17541619 "/schools",
17551620 Some(&builder),
17561621 Some(json!({
17571622 "slug": "notes-only",
1758- "name": "Notes Only",
1623+ "name": "notes-only school",
17591624 "admin_username": "admin",
17601625 "admin_password": "secret1",
17611626 "modules": ["notes"],
@@ -1764,7 +1629,7 @@ async fn a_school_is_created_with_the_modules_it_bought() {
17641629 .await;
17651630 assert_eq!(created.status, StatusCode::CREATED, "{:?}", created.body);
17661631 assert_eq!(created.body["modules"], json!(["notes"]));
1767- let read = send(&app, "GET", "/schools/notes-only", Some(&builder), None).await;
1632+ let read = bsend(&app, "GET", "/schools/notes-only", Some(&builder), None).await;
17681633 assert_eq!(read.body["modules"], json!(["notes"]));
17691634 assert_eq!(
17701635 enabled(&school_modules(&app, &builder, "notes-only").await.body),
@@ -1777,15 +1642,15 @@ async fn a_school_is_created_with_the_modules_it_bought() {
17771642 ] {
17781643 let mut request = json!({
17791644 "slug": "doomed",
1780- "name": "Doomed",
1645+ "name": "doomed school",
17811646 "admin_username": "admin",
17821647 "admin_password": "secret1",
17831648 });
17841649 request["modules"] = body["modules"].clone();
1785- let res = send(&app, "POST", "/schools", Some(&builder), Some(request)).await;
1650+ let res = bsend(&app, "POST", "/schools", Some(&builder), Some(request)).await;
17861651 assert_eq!(res.status, status, "{:?}", res.body);
17871652 assert_eq!(
1788- send(&app, "GET", "/schools/doomed", Some(&builder), None)
1653+ bsend(&app, "GET", "/schools/doomed", Some(&builder), None)
17891654 .await
17901655 .status,
17911656 StatusCode::NOT_FOUND,
@@ -1805,7 +1670,7 @@ async fn a_school_is_created_with_the_modules_it_bought() {
18051670 async fn the_catalog_is_public_and_a_school_user_reads_its_own_set() {
18061671 let (app, _db, _tenants) = deployment().await;
18071672
1808- let catalog = send(&app, "GET", "/modules/catalog", None, None).await;
1673+ let catalog = bsend(&app, "GET", "/modules/catalog", None, None).await;
18091674 assert_eq!(catalog.status, StatusCode::OK, "{:?}", catalog.body);
18101675 let modules = catalog.body["modules"].as_array().expect("modules").clone();
18111676 assert_eq!(modules.len(), 21);
@@ -1831,11 +1696,11 @@ async fn the_catalog_is_public_and_a_school_user_reads_its_own_set() {
18311696 }
18321697
18331698 let student = login(&app, "ali").await;
1834- let mine = send(&app, "GET", "/modules", Some(&student), None).await;
1699+ let mine = bsend(&app, "GET", "/modules", Some(&student), None).await;
18351700 assert_eq!(mine.status, StatusCode::OK, "{:?}", mine.body);
18361701 assert_eq!(enabled(&mine.body), names);
18371702 assert_eq!(
1838- send(&app, "GET", "/modules", None, None).await.status,
1703+ bsend(&app, "GET", "/modules", None, None).await.status,
18391704 StatusCode::UNAUTHORIZED
18401705 );
18411706 }
@@ -1849,14 +1714,14 @@ async fn the_catalog_is_public_and_a_school_user_reads_its_own_set() {
18491714 async fn probe_a_module_less_school_still_works() {
18501715 let (app, _db, _tenants) = deployment().await;
18511716 let builder = builder_login(&app).await;
1852- let created = send(
1717+ let created = bsend(
18531718 &app,
18541719 "POST",
18551720 "/schools",
18561721 Some(&builder),
18571722 Some(json!({
18581723 "slug": "bare",
1859- "name": "Bare School",
1724+ "name": "bare school",
18601725 "admin_username": "admin",
18611726 "admin_password": "secret1",
18621727 "modules": [],
@@ -1879,7 +1744,7 @@ async fn probe_a_module_less_school_still_works() {
18791744 "/modules",
18801745 "/modules/catalog",
18811746 ] {
1882- let res = send(&app, "GET", path, Some(&cookie), None).await;
1747+ let res = bsend(&app, "GET", path, Some(&cookie), None).await;
18831748 assert_eq!(
18841749 res.status,
18851750 StatusCode::OK,
@@ -1888,10 +1753,10 @@ async fn probe_a_module_less_school_still_works() {
18881753 res.body
18891754 );
18901755 }
1891- let mine = send(&app, "GET", "/modules", Some(&cookie), None).await;
1756+ let mine = bsend(&app, "GET", "/modules", Some(&cookie), None).await;
18921757 assert_eq!(mine.body["enabled"], json!([]));
18931758
1894- let prefs = send(
1759+ let prefs = bsend(
18951760 &app,
18961761 "PATCH",
18971762 "/users/me/preferences",
@@ -1914,10 +1779,10 @@ async fn probe_narrowing_every_package_away_leaves_the_school_usable() {
19141779 let builder = builder_login(&app).await;
19151780 let cookie = login_as(&app, &db, "boss", "admin").await;
19161781
1917- let res = send(
1782+ let res = bsend(
19181783 &app,
19191784 "PATCH",
1920- &format!("/schools/{DEMO_SLUG}/modules"),
1785+ &format!("/schools/{DEMO_SCHOOL_ID}/modules"),
19211786 Some(&builder),
19221787 Some(json!({
19231788 "disable_packages": ["academics", "communication", "operations", "ai"],
@@ -1935,7 +1800,7 @@ async fn probe_narrowing_every_package_away_leaves_the_school_usable() {
19351800 "/users/me/profile",
19361801 "/modules",
19371802 ] {
1938- let r = send(&app, "GET", path, Some(&cookie), None).await;
1803+ let r = bsend(&app, "GET", path, Some(&cookie), None).await;
19391804 assert_eq!(
19401805 r.status,
19411806 StatusCode::OK,
@@ -1945,7 +1810,7 @@ async fn probe_narrowing_every_package_away_leaves_the_school_usable() {
19451810 );
19461811 }
19471812 assert_eq!(
1948- send(&app, "GET", "/modules", Some(&cookie), None)
1813+ bsend(&app, "GET", "/modules", Some(&cookie), None)
19491814 .await
19501815 .body["enabled"],
19511816 json!([])
@@ -1958,7 +1823,7 @@ async fn probe_no_route_refuses_a_module_a_school_has() {
19581823 let (app, db, _tenants) = deployment().await;
19591824 let cookie = login_as(&app, &db, "boss", "admin").await;
19601825
1961- let spec = send(&app, "GET", "/api-docs/openapi.json", None, None).await;
1826+ let spec = bsend(&app, "GET", "/api-docs/openapi.json", None, None).await;
19621827 assert_eq!(spec.status, StatusCode::OK, "openapi spec");
19631828 let paths = spec.body["paths"].as_object().expect("paths object");
19641829 assert!(paths.len() > 50, "only {} paths in the spec", paths.len());
@@ -1980,7 +1845,7 @@ async fn probe_no_route_refuses_a_module_a_school_has() {
19801845 })
19811846 .collect::<Vec<_>>()
19821847 .join("/");
1983- let res = send(&app, "GET", &concrete, Some(&cookie), None).await;
1848+ let res = bsend(&app, "GET", &concrete, Some(&cookie), None).await;
19841849 swept += 1;
19851850 if res.body.get("error").and_then(|e| e.as_str()) == Some("module disabled") {
19861851 refused.push(format!("{concrete} -> {} {:?}", res.status, res.body));
@@ -2001,17 +1866,17 @@ async fn probe_no_route_refuses_a_module_a_school_has() {
20011866 async fn probe_gate_ordering_versus_auth() {
20021867 let (app, _db, _tenants) = deployment().await;
20031868 let builder = builder_login(&app).await;
2004- let off = send(
1869+ let off = bsend(
20051870 &app,
20061871 "DELETE",
2007- &format!("/schools/{DEMO_SLUG}/modules/meals"),
1872+ &format!("/schools/{DEMO_SCHOOL_ID}/modules/meals"),
20081873 Some(&builder),
20091874 None,
20101875 )
20111876 .await;
20121877 assert_eq!(off.status, StatusCode::OK, "{:?}", off.body);
20131878
2014- let anon = send(&app, "GET", "/meals/menus", None, None).await;
1879+ let anon = bsend(&app, "GET", "/meals/menus", None, None).await;
20151880 assert_eq!(
20161881 anon.status,
20171882 StatusCode::UNAUTHORIZED,
@@ -2026,7 +1891,7 @@ async fn probe_gate_ordering_versus_auth() {
20261891 anon.body
20271892 );
20281893
2029- let as_builder = send(&app, "GET", "/meals/menus", Some(&builder), None).await;
1894+ let as_builder = bsend(&app, "GET", "/meals/menus", Some(&builder), None).await;
20301895 assert_eq!(
20311896 as_builder.status,
20321897 StatusCode::UNAUTHORIZED,
@@ -2045,18 +1910,24 @@ async fn probe_disabling_in_one_school_leaves_the_other_alone() {
20451910 let res = create_school(&app, &builder, slug, "secret1").await;
20461911 assert_eq!(res.status, StatusCode::CREATED, "{slug}: {:?}", res.body);
20471912 }
2048- let alpha_db = tenants
2049- .get(&hezarfen_backend::tenant::Slug::try_new("alpha").unwrap())
2050- .await
2051- .unwrap();
2052- let beta_db = tenants
2053- .get(&hezarfen_backend::tenant::Slug::try_new("beta").unwrap())
2054- .await
2055- .unwrap();
2056- let alpha = login_as_school(&app, &alpha_db, "alpha", "ada", "manager").await;
2057- let beta = login_as_school(&app, &beta_db, "beta", "ada", "manager").await;
2058-
2059- let off = send(
1913+ async fn named(tenants: &Tenants, label: &str) -> (hezarfen_backend::tenant::SchoolId, hezarfen_backend::database::Database) {
1914+ let id: uuid::Uuid = sqlx::query_scalar("SELECT id FROM school WHERE name = $1")
1915+ .bind(format!("{label} school"))
1916+ .fetch_one(tenants.control())
1917+ .await
1918+ .unwrap_or_else(|err| panic!("{label}: {err}"));
1919+ let id = hezarfen_backend::tenant::SchoolId::from_uuid(id);
1920+ let db = tenants.get(&id).await.unwrap();
1921+ (id, db)
1922+ }
1923+ let (alpha_id, alpha_db) = named(&tenants, "alpha").await;
1924+ let (beta_id, beta_db) = named(&tenants, "beta").await;
1925+ let alpha_wire = alpha_id.as_str();
1926+ let beta_wire = beta_id.as_str();
1927+ let alpha = login_as_school(&app, &alpha_db, &alpha_wire, "ada", "manager").await;
1928+ let beta = login_as_school(&app, &beta_db, &beta_wire, "ada", "manager").await;
1929+
1930+ let off = bsend(
20601931 &app,
20611932 "DELETE",
20621933 "/schools/alpha/modules/meals",
@@ -2066,10 +1937,10 @@ async fn probe_disabling_in_one_school_leaves_the_other_alone() {
20661937 .await;
20671938 assert_eq!(off.status, StatusCode::OK, "{:?}", off.body);
20681939
2069- let a = send(&app, "GET", "/meals/menus", Some(&alpha), None).await;
1940+ let a = bsend(&app, "GET", "/meals/menus", Some(&alpha), None).await;
20701941 assert_eq!(a.status, StatusCode::FORBIDDEN, "{:?}", a.body);
20711942 assert_eq!(a.body["module"], "meals");
2072- let b = send(&app, "GET", "/meals/menus", Some(&beta), None).await;
1943+ let b = bsend(&app, "GET", "/meals/menus", Some(&beta), None).await;
20731944 assert_eq!(
20741945 b.status,
20751946 StatusCode::OK,
@@ -2090,19 +1961,19 @@ async fn probe_a_refused_batch_leaves_the_row_byte_identical() {
20901961 sqlx::query_scalar(
20911962 "SELECT sm.module FROM school_module sm
20921963 JOIN school s ON s.id = sm.school
2093- WHERE s.slug = $1 ORDER BY sm.module",
1964+ WHERE s.id = $1 ORDER BY sm.module",
20941965 )
2095- .bind(DEMO_SLUG)
1966+ .bind(hezarfen_backend::tenant::SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap().uuid())
20961967 .fetch_all(tenants.control())
20971968 .await
20981969 .expect("raw read")
20991970 }
21001971
21011972 let before = raw_row(&tenants).await;
2102- let res = send(
1973+ let res = bsend(
21031974 &app,
21041975 "PATCH",
2105- &format!("/schools/{DEMO_SLUG}/modules"),
1976+ &format!("/schools/{DEMO_SCHOOL_ID}/modules"),
21061977 Some(&builder),
21071978 Some(json!({ "enable": ["exams"], "disable": ["courses"] })),
21081979 )
@@ -2174,7 +2045,7 @@ async fn probe_registry_reads_per_request() {
21742045 let (app, db, _tenants) = deployment().await;
21752046 let cookie = login_as(&app, &db, "boss", "admin").await;
21762047 count.store(0, Ordering::Relaxed);
2177- let res = send(&app, "GET", "/notes", Some(&cookie), None).await;
2048+ let res = bsend(&app, "GET", "/notes", Some(&cookie), None).await;
21782049 assert_eq!(res.status, StatusCode::OK, "{:?}", res.body);
21792050 let seen = count.load(Ordering::Relaxed);
21802051 println!("PROBE sqlx spans/events for GET /notes = {seen}");
@@ -2195,17 +2066,17 @@ async fn probe_child_gates_under_courses_and_the_404_inside_a_disabled_nest() {
21952066
21962067 // Exams off, courses still on: the child pair must refuse as `exams`.
21972068 for module in ["marks", "exams"] {
2198- let off = send(
2069+ let off = bsend(
21992070 &app,
22002071 "DELETE",
2201- &format!("/schools/{DEMO_SLUG}/modules/{module}"),
2072+ &format!("/schools/{DEMO_SCHOOL_ID}/modules/{module}"),
22022073 Some(&builder),
22032074 None,
22042075 )
22052076 .await;
22062077 assert_eq!(off.status, StatusCode::OK, "{module}: {:?}", off.body);
22072078 }
2208- let child = send(&app, "GET", "/instances/x/exams", Some(&cookie), None).await;
2079+ let child = bsend(&app, "GET", "/instances/x/exams", Some(&cookie), None).await;
22092080 assert_eq!(
22102081 child.status,
22112082 StatusCode::FORBIDDEN,
@@ -2215,10 +2086,10 @@ async fn probe_child_gates_under_courses_and_the_404_inside_a_disabled_nest() {
22152086 );
22162087 assert_eq!(child.body["module"], "exams", "{:?}", child.body);
22172088 // …while the course routes themselves keep answering.
2218- let parent = send(&app, "GET", "/courses", Some(&cookie), None).await;
2089+ let parent = bsend(&app, "GET", "/courses", Some(&cookie), None).await;
22192090 assert_eq!(parent.status, StatusCode::OK, "{:?}", parent.body);
22202091 // A sibling child pair whose own module is still on is untouched.
2221- let sibling = send(&app, "GET", "/courses/x/subjects", Some(&cookie), None).await;
2092+ let sibling = bsend(&app, "GET", "/courses/x/subjects", Some(&cookie), None).await;
22222093 assert_ne!(
22232094 sibling.status,
22242095 StatusCode::FORBIDDEN,
@@ -2227,16 +2098,16 @@ async fn probe_child_gates_under_courses_and_the_404_inside_a_disabled_nest() {
22272098 );
22282099
22292100 // A disabled nest is a refusal on the routes that exist, not a wall.
2230- let off = send(
2101+ let off = bsend(
22312102 &app,
22322103 "DELETE",
2233- &format!("/schools/{DEMO_SLUG}/modules/meals"),
2104+ &format!("/schools/{DEMO_SCHOOL_ID}/modules/meals"),
22342105 Some(&builder),
22352106 None,
22362107 )
22372108 .await;
22382109 assert_eq!(off.status, StatusCode::OK, "{:?}", off.body);
2239- let ghost = send(&app, "GET", "/meals/no-such-route", Some(&cookie), None).await;
2110+ let ghost = bsend(&app, "GET", "/meals/no-such-route", Some(&cookie), None).await;
22402111 assert_eq!(
22412112 ghost.status,
22422113 StatusCode::NOT_FOUND,
@@ -2244,6 +2115,6 @@ async fn probe_child_gates_under_courses_and_the_404_inside_a_disabled_nest() {
22442115 ghost.status,
22452116 ghost.body
22462117 );
2247- let real = send(&app, "GET", "/meals/menus", Some(&cookie), None).await;
2118+ let real = bsend(&app, "GET", "/meals/menus", Some(&cookie), None).await;
22482119 assert_eq!(real.status, StatusCode::FORBIDDEN, "{:?}", real.body);
22492120 }
tests/common/mod.rsmodified+30 -15
@@ -17,7 +17,7 @@ use hezarfen_backend::module::ModuleSet;
1717 use hezarfen_backend::rate_limit::RateLimitConfig;
1818 use hezarfen_backend::state::AppState;
1919 use hezarfen_backend::telemetry::Metrics;
20-use hezarfen_backend::tenant::{DEMO_SLUG, Slug, Tenants};
20+use hezarfen_backend::tenant::{BETA_SCHOOL_ID, DEMO_SCHOOL_ID, SchoolId, Tenants};
2121 use hezarfen_backend::{build_router, database};
2222 use serde_json::{Value, json};
2323 use tempfile::TempDir;
@@ -65,10 +65,29 @@ pub async fn app_and_tenants() -> (Router, Database, Tenants) {
6565 (app, db, tenants)
6666 }
6767
68+/// The hyphenated uuid a test label names. `demo` and `beta` are pinned to
69+/// the ids [`init_test_tenants`] / [`deployment_with`] register; a value that
70+/// is already a uuid is returned unchanged.
71+pub fn school_wire(label: &str) -> &str {
72+ match label {
73+ "demo" => DEMO_SCHOOL_ID,
74+ "beta" => BETA_SCHOOL_ID,
75+ "ata-koleji" => "019732e3-7b00-7000-8000-00000000a7a1",
76+ "2024school" => "019732e3-7b00-7000-8000-000000002024",
77+ "gamma" => "019732e3-7b00-7000-8000-00000000a11a",
78+ "p4a" => "019732e3-7b00-7000-8000-00000000a4a1",
79+ other => other,
80+ }
81+}
82+
83+pub fn school_id(label: &str) -> SchoolId {
84+ SchoolId::try_parse(school_wire(label)).unwrap_or_else(|_| panic!("{label} is not a school id"))
85+}
86+
6887 /// Where the demo school's blobs land: one directory per school under
6988 /// `FILES_PATH`, created on the school's first upload.
7089 pub fn blob_dir() -> PathBuf {
71- let dir = files_dir().join(DEMO_SLUG);
90+ let dir = files_dir().join(DEMO_SCHOOL_ID);
7291 std::fs::create_dir_all(&dir).expect("blob dir");
7392 dir
7493 }
@@ -96,7 +115,7 @@ pub async fn mem_deployment() -> (Tenants, Database) {
96115 /// The demo school's handle out of a registry.
97116 pub async fn demo_db(tenants: &Tenants) -> Database {
98117 tenants
99- .get(&Slug::try_new(DEMO_SLUG).expect("the demo slug"))
118+ .get(&SchoolId::try_parse(DEMO_SCHOOL_ID).expect("the demo school"))
100119 .await
101120 .expect("the demo school resolves")
102121 }
@@ -199,7 +218,7 @@ pub async fn set_role(db: &Database, username: &str, role: &str) {
199218 /// Register (password `secret1`), promote to `role`, then log in. Returns the
200219 /// session `Cookie` value.
201220 pub async fn login_as(app: &Router, db: &Database, username: &str, role: &str) -> String {
202- login_as_school(app, db, DEMO_SLUG, username, role).await
221+ login_as_school(app, db, DEMO_SCHOOL_ID, username, role).await
203222 }
204223
205224 /// [`login_as`] in a named school. `db` must be that school's own handle — the
@@ -217,7 +236,7 @@ pub async fn login_as_school(
217236 "POST",
218237 "/auth/register",
219238 None,
220- Some(json!({ "school": school, "username": username, "password": "secret1" })),
239+ Some(json!({ "school": school_wire(school), "username": username, "password": "secret1" })),
221240 )
222241 .await;
223242 assert_eq!(reg.status, StatusCode::CREATED, "register {username}");
@@ -240,7 +259,7 @@ pub async fn login_as_school(
240259 "POST",
241260 "/auth/school",
242261 res.cookie.as_deref(),
243- Some(json!({ "school": school })),
262+ Some(json!({ "school": school_wire(school) })),
244263 )
245264 .await;
246265 assert_eq!(
@@ -425,7 +444,7 @@ pub async fn login(app: &Router, username: &str) -> String {
425444 "POST",
426445 "/auth/register",
427446 None,
428- Some(json!({ "school": DEMO_SLUG, "username": username, "password": "secret1" })),
447+ Some(json!({ "school": DEMO_SCHOOL_ID, "username": username, "password": "secret1" })),
429448 )
430449 .await;
431450 assert_eq!(reg.status, StatusCode::CREATED, "register {username}");
@@ -855,16 +874,12 @@ pub struct TestDeployment {
855874 pub async fn deployment_with(schools: &[(&str, &str)]) -> TestDeployment {
856875 let files = tempfile::tempdir().expect("files tempdir");
857876 let tenants = database::init_test_tenants().await;
858- for (slug, name) in schools {
877+ for (label, name) in schools {
878+ let id = school_id(label);
859879 tenants
860- .create(
861- hezarfen_backend::tenant::SchoolId::generate(),
862- &Slug::try_new(slug).expect("a school slug"),
863- name,
864- ModuleSet::all(),
865- )
880+ .create(id, name, ModuleSet::all())
866881 .await
867- .unwrap_or_else(|err| panic!("create school {slug}: {err}"));
882+ .unwrap_or_else(|err| panic!("create school {label}: {err}"));
868883 }
869884 let app = build_router(AppState {
870885 db: tenants.control().clone(),
tests/e2e.rsmodified+7 -7
@@ -4,7 +4,7 @@
44 use hezarfen_backend::database::Database;
55 use hezarfen_backend::rate_limit::RateLimitConfig;
66 use hezarfen_backend::state::AppState;
7-use hezarfen_backend::tenant::{DEMO_SLUG, Slug};
7+use hezarfen_backend::tenant::{DEMO_SCHOOL_ID, SchoolId};
88 use hezarfen_backend::{build_router, database};
99 mod common;
1010
@@ -23,7 +23,7 @@ async fn spawn_server() -> (String, Database) {
2323 async fn spawn_server_with_ai(ai: Option<hezarfen_backend::ai::AiBridge>) -> (String, Database) {
2424 let tenants = database::init_test_tenants().await;
2525 let db = tenants
26- .get(&Slug::try_new(DEMO_SLUG).unwrap())
26+ .get(&SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap())
2727 .await
2828 .expect("the demo school");
2929 // The deployment's operator, seeded exactly as `main` does from
@@ -86,7 +86,7 @@ fn client() -> Client {
8686 async fn register(client: &Client, base: &str, user: &str) -> reqwest::Response {
8787 client
8888 .post(format!("{base}/auth/register"))
89- .json(&json!({ "school": "demo", "username": user, "password": "secret1" }))
89+ .json(&json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": user, "password": "secret1" }))
9090 .send()
9191 .await
9292 .unwrap()
@@ -3925,7 +3925,6 @@ async fn a_builder_creates_a_school_over_tcp_and_its_admin_logs_in() {
39253925 let res = vendor
39263926 .post(format!("{base}/schools"))
39273927 .json(&json!({
3928- "slug": "tcp-koleji",
39293928 "name": "TCP Koleji",
39303929 "admin_username": "admin",
39313930 "admin_password": "secret1",
@@ -3935,7 +3934,8 @@ async fn a_builder_creates_a_school_over_tcp_and_its_admin_logs_in() {
39353934 .unwrap();
39363935 assert_eq!(res.status(), StatusCode::CREATED);
39373936 let school = res.json::<Value>().await.unwrap();
3938- assert_eq!(school["slug"], "tcp-koleji");
3937+ assert!(school["id"].as_str().is_some_and(|id| id.len() == 36), "{school}");
3938+ assert!(school.get("slug").is_none());
39393939 assert_eq!(school["status"], "active");
39403940
39413941 // A separate jar: the school admin is a different principal on the wire.
@@ -4031,7 +4031,7 @@ async fn probe_a_suspended_school_refuses_websocket_upgrades() {
40314031 .unwrap();
40324032 assert_eq!(res.status(), StatusCode::OK);
40334033 let res = vendor
4034- .patch(format!("{base}/schools/demo"))
4034+ .patch(format!("{base}/schools/{DEMO_SCHOOL_ID}"))
40354035 .json(&json!({ "status": "suspended" }))
40364036 .send()
40374037 .await
@@ -4066,7 +4066,7 @@ async fn probe_a_suspended_school_refuses_websocket_upgrades() {
40664066
40674067 // Resume: the same cookie, the same socket.
40684068 let res = vendor
4069- .patch(format!("{base}/schools/demo"))
4069+ .patch(format!("{base}/schools/{DEMO_SCHOOL_ID}"))
40704070 .json(&json!({ "status": "active" }))
40714071 .send()
40724072 .await
tests/etag.rsmodified+1 -1
@@ -154,7 +154,7 @@ async fn handler_owned_etag_passes_through_and_never_304s() {
154154 #[tokio::test]
155155 async fn mutations_are_never_etagged() {
156156 let app = mem_app().await;
157- let creds = serde_json::json!({ "school": "demo", "username": "ann", "password": "secret1" });
157+ let creds = serde_json::json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ann", "password": "secret1" });
158158 let res = app
159159 .clone()
160160 .oneshot(
tests/insight_report.rsmodified+4 -6
@@ -26,7 +26,7 @@ use hezarfen_backend::constant::{
2626 };
2727 use hezarfen_backend::database::Database;
2828 use hezarfen_backend::domain::timestamp::Timestamp;
29-use hezarfen_backend::tenant::DEMO_SLUG;
29+use hezarfen_backend::tenant::DEMO_SCHOOL_ID;
3030 use serde_json::{Value, json};
3131 use uuid::Uuid;
3232
@@ -453,11 +453,9 @@ async fn a_generated_report_is_stored_and_served_to_its_manager() {
453453 request.payload["requested_by"], manager_id,
454454 "the dispatch names the authenticated caller, not the school"
455455 );
456- assert_eq!(request.payload["school"]["slug"], DEMO_SLUG);
457- assert!(
458- request.payload["school"]["id"].as_str().is_some_and(|id| !id.is_empty()),
459- "the school's own id travels"
460- );
456+ assert!(request.payload["school"].get("slug").is_none(), "the report school has no slug");
457+ assert_eq!(request.payload["school"]["id"], DEMO_SCHOOL_ID);
458+ assert_eq!(request.payload["school"]["name"], "Demo School");
461459 assert!(
462460 request.payload["school"]["name"]
463461 .as_str()
tests/integration.rsmodified+127 -107
@@ -93,7 +93,7 @@ async fn time_serves_server_clock_without_auth() {
9393 async fn get_school_returns_uuid_and_name_without_slug() {
9494 let (app, db, tenants) = app_and_tenants().await;
9595 let (id, name): (Uuid, String) =
96- sqlx::query_as("SELECT id, name FROM school WHERE slug = 'demo'")
96+ sqlx::query_as("SELECT id, name FROM school WHERE id = '019732e3-7b00-7000-8000-00000000dead'")
9797 .fetch_one(tenants.control())
9898 .await
9999 .expect("demo school");
@@ -229,7 +229,7 @@ async fn limits_publishes_the_bounds_the_api_actually_enforces() {
229229 .as_u64()
230230 .expect("max_username_len is an integer") as usize;
231231 let too_long =
232- json!({ "school": "demo", "username": "a".repeat(max + 1), "password": "secret1" });
232+ json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "a".repeat(max + 1), "password": "secret1" });
233233 let res = send(&app, "POST", "/auth/register", None, Some(too_long)).await;
234234 assert_eq!(res.status, StatusCode::BAD_REQUEST);
235235 }
@@ -273,25 +273,25 @@ async fn register_validates_input() {
273273 let app = mem_app().await;
274274
275275 // Password too short -> 400.
276- let short = json!({ "school": "demo", "username": "bob", "password": "123" });
276+ let short = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "bob", "password": "123" });
277277 let res = send(&app, "POST", "/auth/register", None, Some(short)).await;
278278 assert_eq!(res.status, StatusCode::BAD_REQUEST);
279279
280280 // Blank username -> 400.
281- let blank = json!({ "school": "demo", "username": " ", "password": "secret1" });
281+ let blank = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": " ", "password": "secret1" });
282282 let res = send(&app, "POST", "/auth/register", None, Some(blank)).await;
283283 assert_eq!(res.status, StatusCode::BAD_REQUEST);
284284
285285 // Uppercase anywhere in the username -> 400.
286286 for bad in ["Bob", "bOb", "BOB"] {
287- let upper = json!({ "school": "demo", "username": bad, "password": "secret1" });
287+ let upper = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": bad, "password": "secret1" });
288288 let res = send(&app, "POST", "/auth/register", None, Some(upper)).await;
289289 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad} accepted");
290290 }
291291
292292 // Username must start and end with a letter or digit -> 400.
293293 for bad in ["-bob", "bob-", "_bob", "bob_", ".bob"] {
294- let edge = json!({ "school": "demo", "username": bad, "password": "secret1" });
294+ let edge = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": bad, "password": "secret1" });
295295 let res = send(&app, "POST", "/auth/register", None, Some(edge)).await;
296296 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad} accepted");
297297 }
@@ -306,26 +306,26 @@ async fn register_validates_input() {
306306 "a/b",
307307 "a\"b",
308308 ] {
309- let ugly = json!({ "school": "demo", "username": bad, "password": "secret1" });
309+ let ugly = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": bad, "password": "secret1" });
310310 let res = send(&app, "POST", "/auth/register", None, Some(ugly)).await;
311311 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad:?} accepted");
312312 }
313313
314314 // Consecutive separators -> 400.
315315 for bad in ["a--b", "a..b", "a__b", "a.-b"] {
316- let doubled = json!({ "school": "demo", "username": bad, "password": "secret1" });
316+ let doubled = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": bad, "password": "secret1" });
317317 let res = send(&app, "POST", "/auth/register", None, Some(doubled)).await;
318318 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad} accepted");
319319 }
320320
321321 // Single separators between alphanumerics are fine -> 201.
322- let dotted = json!({ "school": "demo", "username": "ali.k_1-b", "password": "secret1" });
322+ let dotted = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ali.k_1-b", "password": "secret1" });
323323 let res = send(&app, "POST", "/auth/register", None, Some(dotted)).await;
324324 assert_eq!(res.status, StatusCode::CREATED);
325325 assert_eq!(res.body["username"], "ali.k_1-b");
326326
327327 // Valid -> 201, no password echoed back, defaults to the student role.
328- let ok = json!({ "school": "demo", "username": "bob", "password": "secret1" });
328+ let ok = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "bob", "password": "secret1" });
329329 let res = send(&app, "POST", "/auth/register", None, Some(ok)).await;
330330 assert_eq!(res.status, StatusCode::CREATED);
331331 assert_eq!(res.body["username"], "bob");
@@ -336,7 +336,7 @@ async fn register_validates_input() {
336336 // deliberately indistinguishable — see tests/auth_enumeration.rs), but the
337337 // write is still rejected: the original password keeps working and the
338338 // second one never becomes valid.
339- let dup = json!({ "school": "demo", "username": "bob", "password": "hijack1" });
339+ let dup = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "bob", "password": "hijack1" });
340340 let res = send(&app, "POST", "/auth/register", None, Some(dup)).await;
341341 assert_eq!(res.status, StatusCode::CREATED);
342342 let res = send(
@@ -381,7 +381,7 @@ async fn register_rejects_reserved_usernames() {
381381 "moderator",
382382 "staff",
383383 ] {
384- let creds = json!({ "school": "demo", "username": name, "password": "secret1" });
384+ let creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": name, "password": "secret1" });
385385 let res = send(&app, "POST", "/auth/register", None, Some(creds)).await;
386386 assert_eq!(res.status, StatusCode::BAD_REQUEST, "{name} accepted");
387387 let msg = res.body["error"].as_str().unwrap_or_default();
@@ -408,7 +408,7 @@ async fn login_rejects_bad_credentials() {
408408 "POST",
409409 "/auth/register",
410410 None,
411- Some(json!({ "school": "demo", "username": "kate", "password": "secret1" })),
411+ Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "kate", "password": "secret1" })),
412412 )
413413 .await;
414414
@@ -452,6 +452,8 @@ const PUBLIC: &[(&str, &str)] = &[
452452 // Person-cookie gated, not a school session: OpenAPI declares no
453453 // session_cookie security, so the public-route audit lists it here.
454454 ("POST", "/auth/school"),
455+ // Register's school picker: active `{id, name}` rows, no session.
456+ ("GET", "/auth/schools"),
455457 // Idempotent: revokes the session if there is one, `204` either way.
456458 ("POST", "/auth/logout"),
457459 // A server certificate is handed to every peer in the TLS handshake, so
@@ -1355,13 +1357,13 @@ async fn malformed_json_bodies_answer_422_across_every_extractor_shape() {
13551357 (
13561358 "/auth/register",
13571359 None,
1358- r#"{"school": "demo", "username": 5, "password": "secret1"}"#,
1360+ r#"{"school": "019732e3-7b00-7000-8000-00000000dead", "username": 5, "password": "secret1"}"#,
13591361 "plain Json, type mismatch",
13601362 ),
13611363 (
13621364 "/auth/register",
13631365 None,
1364- r#"{"school": "demo", "username": "veli"}"#,
1366+ r#"{"school": "019732e3-7b00-7000-8000-00000000dead", "username": "veli"}"#,
13651367 "plain Json, missing required field",
13661368 ),
13671369 (
@@ -1405,7 +1407,7 @@ async fn malformed_json_bodies_answer_422_across_every_extractor_shape() {
14051407 for (body, why) in [
14061408 ("not json at all", "unparseable JSON"),
14071409 (
1408- r#"{"school": "demo", "username": "a", "password": "secret1"}"#,
1410+ r#"{"school": "019732e3-7b00-7000-8000-00000000dead", "username": "a", "password": "secret1"}"#,
14091411 "well-typed value refused by a domain rule",
14101412 ),
14111413 ] {
@@ -6450,7 +6452,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() {
64506452 "/auth/register",
64516453 None,
64526454 Some(
6453- json!({ "school": "demo", "school": "demo", "username": "ali", "password": "secret1" }),
6455+ json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ali", "password": "secret1" }),
64546456 ),
64556457 )
64566458 .await;
@@ -6466,7 +6468,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() {
64666468 "POST",
64676469 "/auth/register",
64686470 None,
6469- Some(json!({ "school": "demo", "username": spoof, "password": "spoof1" })),
6471+ Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": spoof, "password": "spoof1" })),
64706472 )
64716473 .await;
64726474 assert_eq!(res.status, StatusCode::CREATED, "{spoof:?}");
@@ -6517,7 +6519,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() {
65176519 "POST",
65186520 "/auth/register",
65196521 None,
6520- Some(json!({ "school": "demo", "username": " veli ", "password": "secret1" })),
6522+ Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": " veli ", "password": "secret1" })),
65216523 )
65226524 .await;
65236525 assert_eq!(res.status, StatusCode::CREATED);
@@ -6825,7 +6827,7 @@ async fn concurrent_duplicate_registrations_conflict_not_500() {
68256827 "POST",
68266828 "/auth/register",
68276829 None,
6828- Some(json!({ "school": "demo", "username": "dup", "password": "secret1" })),
6830+ Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "dup", "password": "secret1" })),
68296831 )
68306832 .await
68316833 .status
@@ -6855,7 +6857,7 @@ async fn concurrent_duplicate_registrations_conflict_not_500() {
68556857 "POST",
68566858 "/auth/register",
68576859 None,
6858- Some(json!({ "school": "demo", "username": "dup", "password": "hijack1" })),
6860+ Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "dup", "password": "hijack1" })),
68596861 )
68606862 .await;
68616863 assert_eq!(res.status, StatusCode::CREATED);
@@ -6942,7 +6944,7 @@ async fn child_lists_of_missing_parents_are_404() {
69426944 #[tokio::test]
69436945 async fn session_cookie_secure_attribute_follows_config() {
69446946 async fn login_set_cookie(app: &axum::Router) -> String {
6945- let creds = json!({ "school": "demo", "username": "ada", "password": "secret1" });
6947+ let creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ada", "password": "secret1" });
69466948 assert_eq!(
69476949 send(app, "POST", "/auth/register", None, Some(creds))
69486950 .await
@@ -7051,7 +7053,7 @@ async fn db_down_refuses_before_touching_the_database() {
70517053 .uri("/auth/register")
70527054 .header("content-type", "application/json")
70537055 .body(Body::from(
7054- json!({"school": "demo", "username": "gulsah", "password": "sifre12345"})
7056+ json!({"school": "019732e3-7b00-7000-8000-00000000dead", "username": "gulsah", "password": "sifre12345"})
70557057 .to_string(),
70567058 ))
70577059 .unwrap(),
@@ -7075,7 +7077,7 @@ async fn db_down_refuses_before_touching_the_database() {
70757077 .uri("/auth/register")
70767078 .header("content-type", "application/json")
70777079 .body(Body::from(
7078- json!({"school": "demo", "username": "kerem", "password": "sifre12345"})
7080+ json!({"school": "019732e3-7b00-7000-8000-00000000dead", "username": "kerem", "password": "sifre12345"})
70797081 .to_string(),
70807082 ))
70817083 .unwrap(),
@@ -7091,11 +7093,11 @@ async fn db_down_refuses_before_touching_the_database() {
70917093
70927094 // Recovery is eviction: the dead pool leaves the cache, the next request
70937095 // dials fresh — and the refused write is still not in the database.
7094- let demo_id: Uuid = sqlx::query_scalar("SELECT id FROM school WHERE slug = 'demo'")
7096+ let demo_id: Uuid = sqlx::query_scalar("SELECT id FROM school WHERE id = '019732e3-7b00-7000-8000-00000000dead'")
70957097 .fetch_one(tenants.control())
70967098 .await
70977099 .expect("demo id");
7098- let slug = Slug::try_new("demo").expect("slug");
7100+ let slug = SchoolId::try_parse(hezarfen_backend::tenant::DEMO_SCHOOL_ID).expect("slug");
70997101 tenants
71007102 .evict(hezarfen_backend::tenant::SchoolId::from_uuid(demo_id))
71017103 .await;
@@ -7112,7 +7114,7 @@ async fn db_down_refuses_before_touching_the_database() {
71127114 .uri("/auth/register")
71137115 .header("content-type", "application/json")
71147116 .body(Body::from(
7115- json!({"school": "demo", "username": "kerem", "password": "sifre12345"})
7117+ json!({"school": "019732e3-7b00-7000-8000-00000000dead", "username": "kerem", "password": "sifre12345"})
71167118 .to_string(),
71177119 ))
71187120 .unwrap(),
@@ -7346,7 +7348,7 @@ async fn admin_seed_creates_working_admin() {
73467348 let password = Password::try_new("secret1").unwrap();
73477349 hezarfen_backend::service::user::ensure_admin(
73487350 &tenants,
7349- &hezarfen_backend::tenant::Slug::try_new(hezarfen_backend::tenant::DEMO_SLUG).unwrap(),
7351+ &hezarfen_backend::tenant::SchoolId::try_parse(hezarfen_backend::tenant::DEMO_SCHOOL_ID).unwrap(),
73507352 username,
73517353 password,
73527354 )
@@ -7373,7 +7375,7 @@ async fn admin_seed_is_idempotent() {
73737375 let password = Password::try_new("secret1").unwrap();
73747376 hezarfen_backend::service::user::ensure_admin(
73757377 &tenants,
7376- &hezarfen_backend::tenant::Slug::try_new(hezarfen_backend::tenant::DEMO_SLUG).unwrap(),
7378+ &hezarfen_backend::tenant::SchoolId::try_parse(hezarfen_backend::tenant::DEMO_SCHOOL_ID).unwrap(),
73777379 username,
73787380 password,
73797381 )
@@ -7404,7 +7406,7 @@ async fn admin_seed_refuses_existing_non_admin() {
74047406 let password = Password::try_new("attacker-pw").unwrap();
74057407 hezarfen_backend::service::user::ensure_admin(
74067408 &tenants,
7407- &hezarfen_backend::tenant::Slug::try_new(hezarfen_backend::tenant::DEMO_SLUG).unwrap(),
7409+ &hezarfen_backend::tenant::SchoolId::try_parse(hezarfen_backend::tenant::DEMO_SCHOOL_ID).unwrap(),
74087410 username,
74097411 password,
74107412 )
@@ -28375,7 +28377,7 @@ async fn course_note_rag_reindex_reports_503_and_writes_nothing_without_a_servic
2837528377 // Multi-school isolation probes (REFUTE lane B). Two schools, same usernames.
2837628378 // =========================================================================
2837728379
28378-use hezarfen_backend::tenant::{DEMO_SLUG, SchoolStatus, Slug, Tenants};
28380+use hezarfen_backend::tenant::{DEMO_SCHOOL_ID, SchoolStatus, SchoolId, Tenants};
2837928381
2838028382 /// Demo (school A) plus a second school "beta" (school B), and the registry.
2838128383 async fn two_schools() -> (
@@ -28385,11 +28387,10 @@ async fn two_schools() -> (
2838528387 Tenants,
2838628388 ) {
2838728389 let (app, db_a, tenants) = common::app_and_tenants().await;
28388- let slug_b = Slug::try_new("beta").expect("slug");
28390+ let slug_b = SchoolId::try_parse(hezarfen_backend::tenant::BETA_SCHOOL_ID).expect("beta id");
2838928391 let db_b = tenants
2839028392 .create(
28391- hezarfen_backend::tenant::SchoolId::generate(),
28392- &slug_b,
28393+ slug_b,
2839328394 "Beta Koleji",
2839428395 ModuleSet::all(),
2839528396 )
@@ -28406,7 +28407,7 @@ const TWO_SCHOOLS: &[(&str, &str)] = &[("beta", "Beta Koleji")];
2840628407 /// One school's handle out of the registry.
2840728408 async fn school_db(tenants: &Tenants, slug: &str) -> hezarfen_backend::database::Database {
2840828409 tenants
28409- .get(&Slug::try_new(slug).expect("a school slug"))
28410+ .get(&common::school_id(slug))
2841028411 .await
2841128412 .unwrap_or_else(|err| panic!("the {slug} handle: {err}"))
2841228413 }
@@ -28548,9 +28549,9 @@ async fn remote_probe_cross_school_lists_show_only_own_rows() {
2854828549 }
2854928550
2855028551 async fn probe_cross_school_lists_show_only_own_rows_on(app: &axum::Router, tenants: &Tenants) {
28551- let db_a = school_db(tenants, DEMO_SLUG).await;
28552+ let db_a = school_db(tenants, DEMO_SCHOOL_ID).await;
2855228553 let db_b = school_db(tenants, "beta").await;
28553- let a = common::login_as_school(app, &db_a, DEMO_SLUG, "ada", "admin").await;
28554+ let a = common::login_as_school(app, &db_a, DEMO_SCHOOL_ID, "ada", "admin").await;
2855428555 let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await;
2855528556
2855628557 let mut before = Vec::new();
@@ -28609,9 +28610,9 @@ async fn probe_cross_school_ids_are_not_found_under_the_other_cookie_on(
2860928610 app: &axum::Router,
2861028611 tenants: &Tenants,
2861128612 ) {
28612- let db_a = school_db(tenants, DEMO_SLUG).await;
28613+ let db_a = school_db(tenants, DEMO_SCHOOL_ID).await;
2861328614 let db_b = school_db(tenants, "beta").await;
28614- let a = common::login_as_school(app, &db_a, DEMO_SLUG, "ada", "admin").await;
28615+ let a = common::login_as_school(app, &db_a, DEMO_SCHOOL_ID, "ada", "admin").await;
2861528616 let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await;
2861628617 let ids = seed_school_b(app, &b).await;
2861728618 let s = |k: &str| ids[k].as_str().unwrap().to_string();
@@ -28715,11 +28716,11 @@ async fn remote_probe_cross_school_ids_in_bodies_are_refused() {
2871528716 }
2871628717
2871728718 async fn probe_cross_school_ids_in_bodies_are_refused_on(app: &axum::Router, tenants: &Tenants) {
28718- let db_a = school_db(tenants, DEMO_SLUG).await;
28719+ let db_a = school_db(tenants, DEMO_SCHOOL_ID).await;
2871928720 let db_b = school_db(tenants, "beta").await;
28720- let a_admin = common::login_as_school(app, &db_a, DEMO_SLUG, "ada", "admin").await;
28721- let a_student = common::login_as_school(app, &db_a, DEMO_SLUG, "ali", "student").await;
28722- let a_parent = common::login_as_school(app, &db_a, DEMO_SLUG, "veli", "parent").await;
28721+ let a_admin = common::login_as_school(app, &db_a, DEMO_SCHOOL_ID, "ada", "admin").await;
28722+ let a_student = common::login_as_school(app, &db_a, DEMO_SCHOOL_ID, "ali", "student").await;
28723+ let a_parent = common::login_as_school(app, &db_a, DEMO_SCHOOL_ID, "veli", "parent").await;
2872328724 let b_admin = common::login_as_school(app, &db_b, "beta", "boran", "admin").await;
2872428725 common::login_as_school(app, &db_b, "beta", "bstudent", "student").await;
2872528726
@@ -28821,7 +28822,7 @@ async fn probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it
2882128822 tenants: &Tenants,
2882228823 ) {
2882328824 let db_b = school_db(tenants, "beta").await;
28824- let slug_b = Slug::try_new("beta").unwrap();
28825+ let slug_b = SchoolId::try_parse(hezarfen_backend::tenant::BETA_SCHOOL_ID).unwrap();
2882528826 let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await;
2882628827
2882728828 // Alive first.
@@ -28877,7 +28878,7 @@ async fn probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it
2887728878 "POST",
2887828879 "/auth/register",
2887928880 None,
28880- Some(json!({ "school": "beta", "username": "newcomer", "password": "secret1" })),
28881+ Some(json!({ "school": common::school_wire("beta"), "username": "newcomer", "password": "secret1" })),
2888128882 )
2888228883 .await;
2888328884 assert_eq!(
@@ -28920,9 +28921,9 @@ async fn remote_probe_cookie_confusion_is_impossible_both_ways() {
2892028921 }
2892128922
2892228923 async fn probe_cookie_confusion_is_impossible_both_ways_on(app: &axum::Router, tenants: &Tenants) {
28923- let db_a = school_db(tenants, DEMO_SLUG).await;
28924+ let db_a = school_db(tenants, DEMO_SCHOOL_ID).await;
2892428925 let db_b = school_db(tenants, "beta").await;
28925- let a = common::login_as_school(app, &db_a, DEMO_SLUG, "ada", "admin").await;
28926+ let a = common::login_as_school(app, &db_a, DEMO_SCHOOL_ID, "ada", "admin").await;
2892628927 let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await;
2892728928 let token_a = common::cookie_token(&a).to_string();
2892828929
@@ -28990,8 +28991,8 @@ async fn probe_cookie_confusion_is_impossible_both_ways_on(app: &axum::Router, t
2899028991 }
2899128992 // (4) a builder token wearing a school prefix.
2899228993 for raw in [
28993- format!("session=demo.{builder_token}"),
28994- format!("session=beta.{builder_token}"),
28994+ format!("session={DEMO_SCHOOL_ID}.{builder_token}"),
28995+ format!("session={}.{}", hezarfen_backend::tenant::BETA_SCHOOL_ID, builder_token),
2899528996 ] {
2899628997 let res = send(app, "GET", "/auth/me", Some(&raw), None).await;
2899728998 assert_eq!(
@@ -29005,8 +29006,8 @@ async fn probe_cookie_confusion_is_impossible_both_ways_on(app: &axum::Router, t
2900529006 // (5) THE one: A's live token under B's prefix, and B's under A's.
2900629007 let token_b = common::cookie_token(&b).to_string();
2900729008 for (raw, whose) in [
29008- (format!("session=beta.{token_a}"), "A's token under B"),
29009- (format!("session=demo.{token_b}"), "B's token under A"),
29009+ (format!("session={}.{token_a}", hezarfen_backend::tenant::BETA_SCHOOL_ID), "A's token under B"),
29010+ (format!("session={DEMO_SCHOOL_ID}.{token_b}"), "B's token under A"),
2901029011 ] {
2901129012 for route in ["/auth/me", "/users", "/notes", "/settings"] {
2901229013 let res = send(app, "GET", route, Some(&raw), None).await;
@@ -29048,7 +29049,7 @@ async fn remote_probe_register_is_scoped_to_the_named_school() {
2904829049 }
2904929050
2905029051 async fn probe_register_is_scoped_to_the_named_school_on(app: &axum::Router, tenants: &Tenants) {
29051- let db_a = school_db(tenants, DEMO_SLUG).await;
29052+ let db_a = school_db(tenants, DEMO_SCHOOL_ID).await;
2905229053 let db_b = school_db(tenants, "beta").await;
2905329054
2905429055 // Missing `school` is a 4xx, not a silent default.
@@ -29068,13 +29069,13 @@ async fn probe_register_is_scoped_to_the_named_school_on(app: &axum::Router, ten
2906829069 );
2906929070
2907029071 // The same username in both schools, independently.
29071- for (slug, db) in [(DEMO_SLUG, &db_a), ("beta", &db_b)] {
29072+ for (slug, db) in [(DEMO_SCHOOL_ID, &db_a), ("beta", &db_b)] {
2907229073 let res = send(
2907329074 app,
2907429075 "POST",
2907529076 "/auth/register",
2907629077 None,
29077- Some(json!({ "school": slug, "username": "ayse", "password": "secret1" })),
29078+ Some(json!({ "school": common::school_wire(slug), "username": "ayse", "password": "secret1" })),
2907829079 )
2907929080 .await;
2908029081 assert_eq!(
@@ -29162,9 +29163,9 @@ async fn probe_uploaded_files_are_school_scoped_on(
2916229163 tenants: &Tenants,
2916329164 files: &std::path::Path,
2916429165 ) {
29165- let db_a = school_db(tenants, DEMO_SLUG).await;
29166+ let db_a = school_db(tenants, DEMO_SCHOOL_ID).await;
2916629167 let db_b = school_db(tenants, "beta").await;
29167- let a = common::login_as_school(app, &db_a, DEMO_SLUG, "ali", "student").await;
29168+ let a = common::login_as_school(app, &db_a, DEMO_SCHOOL_ID, "ali", "student").await;
2916829169 let b = common::login_as_school(app, &db_b, "beta", "ali", "student").await;
2916929170
2917029171 let note = send(
@@ -29183,8 +29184,8 @@ async fn probe_uploaded_files_are_school_scoped_on(
2918329184 let file_id = id_of(&up.body);
2918429185
2918529186 // It landed under the school's own directory, and nowhere else.
29186- let a_dir = files.join(DEMO_SLUG);
29187- let b_dir = files.join("beta");
29187+ let a_dir = files.join(DEMO_SCHOOL_ID);
29188+ let b_dir = files.join(common::school_wire("beta"));
2918829189 let count = |dir: &std::path::Path| {
2918929190 std::fs::read_dir(dir)
2919029191 .map(|it| it.count())
@@ -29240,9 +29241,9 @@ async fn probe_school_rows_never_reach_the_control_database_on(
2924029241 app: &axum::Router,
2924129242 tenants: &Tenants,
2924229243 ) {
29243- let db_a = school_db(tenants, DEMO_SLUG).await;
29244+ let db_a = school_db(tenants, DEMO_SCHOOL_ID).await;
2924429245 let db_b = school_db(tenants, "beta").await;
29245- let a = common::login_as_school(app, &db_a, DEMO_SLUG, "ada", "admin").await;
29246+ let a = common::login_as_school(app, &db_a, DEMO_SCHOOL_ID, "ada", "admin").await;
2924629247 let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await;
2924729248 common::login_as_school(app, &db_b, "beta", "bstudent", "student").await;
2924829249 let ids = seed_school_b(app, &b).await;
@@ -29278,11 +29279,11 @@ async fn probe_school_rows_never_reach_the_control_database_on(
2927829279 );
2927929280 }
2928029281 // And the control database does hold the two schools.
29281- let schools: Vec<String> = sqlx::query_scalar("SELECT slug FROM school ORDER BY slug")
29282+ let schools: Vec<String> = sqlx::query_scalar("SELECT name FROM school ORDER BY name")
2928229283 .fetch_all(control)
2928329284 .await
2928429285 .unwrap();
29285- assert_eq!(schools, vec!["beta".to_string(), "demo".to_string()]);
29286+ assert_eq!(schools, vec!["Beta Koleji".to_string(), "Demo School".to_string()]);
2928629287
2928729288 // User search never crosses the wall. Compare the returned names, not the
2928829289 // raw body: a substring match over the serialized JSON also hits the hex of
@@ -29357,8 +29358,8 @@ async fn probe_school_rows_never_reach_the_control_database_on(
2935729358 async fn remote_probe_remote_mode_keeps_two_schools_apart() {
2935829359 let d = common::deployment_with(&[("ata-koleji", "Ata"), ("2024school", "2024")]).await;
2935929360 let (app, tenants) = (&d.app, &d.tenants);
29360- let slug_a = Slug::try_new("ata-koleji").unwrap();
29361- let slug_b = Slug::try_new("2024school").unwrap();
29361+ let slug_a = SchoolId::try_parse("019732e3-7b00-7000-8000-00000000a7a1").unwrap();
29362+ let slug_b = SchoolId::try_parse("019732e3-7b00-7000-8000-000000002024").unwrap();
2936229363
2936329364 // Same username in both schools is one person with two memberships.
2936429365 // Login into the second school therefore returns a person cookie; bind
@@ -29496,9 +29497,10 @@ async fn namespace_databases(tenants: &Tenants) -> Vec<String> {
2949629497 /// database's `heztest_` prefix runs the name one character past that — the
2949729498 /// server creates and dials the truncated name on both sides, so the
2949829499 /// expectation truncates with it.
29499-async fn school_db_by_slug(control_db: &str, slug: &str, control: &sqlx::PgPool) -> String {
29500- let id: Uuid = sqlx::query_scalar("SELECT id FROM school WHERE slug = $1")
29501- .bind(slug)
29500+async fn school_db_by_slug(control_db: &str, school: &str, control: &sqlx::PgPool) -> String {
29501+ let id = Uuid::parse_str(school).expect("school id is a uuid");
29502+ let id: Uuid = sqlx::query_scalar("SELECT id FROM school WHERE id = $1")
29503+ .bind(id)
2950229504 .fetch_one(control)
2950329505 .await
2950429506 .expect("school id");
@@ -29516,8 +29518,8 @@ async fn remote_probe_a_school_is_a_database_and_delete_removes_it() {
2951629518 .fetch_one(d.tenants.control())
2951729519 .await
2951829520 .expect("control name");
29519- let demo_db = school_db_by_slug(&control_db, DEMO_SLUG, d.tenants.control()).await;
29520- let beta_db = school_db_by_slug(&control_db, "beta", d.tenants.control()).await;
29521+ let demo_db = school_db_by_slug(&control_db, DEMO_SCHOOL_ID, d.tenants.control()).await;
29522+ let beta_db = school_db_by_slug(&control_db, common::school_wire("beta"), d.tenants.control()).await;
2952129523 let mut expected = vec![control_db.clone(), demo_db.clone(), beta_db];
2952229524 expected.sort();
2952329525 assert_eq!(
@@ -29544,7 +29546,7 @@ async fn remote_probe_a_school_is_a_database_and_delete_removes_it() {
2954429546 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
2954529547 let builder = res.cookie.expect("builder cookie");
2954629548
29547- let res = send(&d.app, "DELETE", "/schools/beta", Some(&builder), None).await;
29549+ let res = send(&d.app, "DELETE", &format!("/schools/{}", common::school_wire("beta")), Some(&builder), None).await;
2954829550 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
2954929551 let mut expected = vec![control_db.clone(), demo_db];
2955029552 expected.sort();
@@ -29562,7 +29564,7 @@ async fn remote_probe_raw_sql_on_a_school_handle_counts_only_its_own_rows() {
2956229564 let d = common::deployment_with(TWO_SCHOOLS).await;
2956329565 // Different counts, so a leak cannot hide behind equal numbers.
2956429566 for (slug, users) in [
29565- (DEMO_SLUG, ["ada", "ali", "ayse"].as_slice()),
29567+ (DEMO_SCHOOL_ID, ["ada", "ali", "ayse"].as_slice()),
2956629568 ("beta", &["boran"]),
2956729569 ] {
2956829570 for username in users {
@@ -29571,7 +29573,7 @@ async fn remote_probe_raw_sql_on_a_school_handle_counts_only_its_own_rows() {
2957129573 "POST",
2957229574 "/auth/register",
2957329575 None,
29574- Some(json!({ "school": slug, "username": username, "password": "secret1" })),
29576+ Some(json!({ "school": common::school_wire(slug), "username": username, "password": "secret1" })),
2957529577 )
2957629578 .await;
2957729579 assert_eq!(
@@ -29589,7 +29591,7 @@ async fn remote_probe_raw_sql_on_a_school_handle_counts_only_its_own_rows() {
2958929591 .await
2959029592 .expect("count query")
2959129593 };
29592- let db_a = school_db(&d.tenants, DEMO_SLUG).await;
29594+ let db_a = school_db(&d.tenants, DEMO_SCHOOL_ID).await;
2959329595 let db_b = school_db(&d.tenants, "beta").await;
2959429596 assert_eq!(count(&db_a).await, 3, "demo's own users");
2959529597 assert_eq!(count(&db_b).await, 1, "beta's own users");
@@ -29606,12 +29608,12 @@ async fn remote_probe_a_record_id_minted_in_one_school_is_absent_in_the_other()
2960629608 "POST",
2960729609 "/auth/register",
2960829610 None,
29609- Some(json!({ "school": DEMO_SLUG, "username": "ada", "password": "secret1" })),
29611+ Some(json!({ "school": DEMO_SCHOOL_ID, "username": "ada", "password": "secret1" })),
2961029612 )
2961129613 .await;
2961229614 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
2961329615
29614- let db_a = school_db(&d.tenants, DEMO_SLUG).await;
29616+ let db_a = school_db(&d.tenants, DEMO_SCHOOL_ID).await;
2961529617 let db_b = school_db(&d.tenants, "beta").await;
2961629618 let id: Uuid = sqlx::query_scalar("SELECT id FROM app_user LIMIT 1")
2961729619 .fetch_one(&db_a)
@@ -29640,9 +29642,9 @@ async fn remote_probe_a_record_id_minted_in_one_school_is_absent_in_the_other()
2964029642 #[tokio::test]
2964129643 async fn remote_probe_a_suspended_school_reconnects_with_its_rows_intact() {
2964229644 let d = common::deployment_with(TWO_SCHOOLS).await;
29643- let slug = Slug::try_new(DEMO_SLUG).unwrap();
29644- let db = school_db(&d.tenants, DEMO_SLUG).await;
29645- let cookie = common::login_as_school(&d.app, &db, DEMO_SLUG, "ada", "admin").await;
29645+ let slug = SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap();
29646+ let db = school_db(&d.tenants, DEMO_SCHOOL_ID).await;
29647+ let cookie = common::login_as_school(&d.app, &db, DEMO_SCHOOL_ID, "ada", "admin").await;
2964629648 let note = send(
2964729649 &d.app,
2964829650 "POST",
@@ -29666,7 +29668,7 @@ async fn remote_probe_a_suspended_school_reconnects_with_its_rows_intact() {
2966629668 .expect("resume");
2966729669
2966829670 // A fresh connection (the old one was evicted) onto the same database.
29669- let reconnected = school_db(&d.tenants, DEMO_SLUG).await;
29671+ let reconnected = school_db(&d.tenants, DEMO_SCHOOL_ID).await;
2967029672 let titles: Vec<String> = sqlx::query_scalar("SELECT title FROM note")
2967129673 .fetch_all(&reconnected)
2967229674 .await
@@ -29702,7 +29704,7 @@ use hezarfen_backend::module::Module;
2970229704 #[tokio::test]
2970329705 async fn a_disabled_module_refuses_its_nest_and_leaves_the_rest_alone() {
2970429706 let (app, db, tenants) = common::app_and_tenants().await;
29705- let slug = Slug::try_new(DEMO_SLUG).unwrap();
29707+ let slug = SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap();
2970629708 let cookie = login_as(&app, &db, "ada", "admin").await;
2970729709
2970829710 let res = send(&app, "GET", "/meals/menus", Some(&cookie), None).await;
@@ -29770,7 +29772,7 @@ fn all_without(module: Module) -> ModuleSet {
2977029772 #[tokio::test]
2977129773 async fn a_course_child_route_is_gated_by_its_own_module() {
2977229774 let (app, db, tenants) = common::app_and_tenants().await;
29773- let slug = Slug::try_new(DEMO_SLUG).unwrap();
29775+ let slug = SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap();
2977429776 let cookie = login_as(&app, &db, "ada", "admin").await;
2977529777 let course = create_course(&app, &cookie, "Fizik").await;
2977629778
@@ -29815,7 +29817,7 @@ async fn a_course_child_route_is_gated_by_its_own_module() {
2981529817 #[tokio::test]
2981629818 async fn a_disabled_module_refuses_its_websocket_upgrade() {
2981729819 let (app, db, tenants) = common::app_and_tenants().await;
29818- let slug = Slug::try_new(DEMO_SLUG).unwrap();
29820+ let slug = SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap();
2981929821 let cookie = login_as(&app, &db, "ada", "admin").await;
2982029822
2982129823 let mut without = all_without(Module::Exams);
@@ -29907,7 +29909,7 @@ const MODULE_ROUTES: [(Module, &str, &str); 21] = [
2990729909 #[tokio::test]
2990829910 async fn every_module_gates_its_own_nest_when_the_builder_takes_it_back() {
2990929911 let (app, db, tenants) = sweep_deployment().await;
29910- let slug = Slug::try_new(DEMO_SLUG).unwrap();
29912+ let slug = SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap();
2991129913 let cookie = login_as(&app, &db, "ada", "admin").await;
2991229914 let builder = sweep_builder_login(&app).await;
2991329915
@@ -29920,7 +29922,7 @@ async fn every_module_gates_its_own_nest_when_the_builder_takes_it_back() {
2992029922 res.body
2992129923 );
2992229924
29923- let one = format!("/schools/{DEMO_SLUG}/modules/{module}");
29925+ let one = format!("/schools/{DEMO_SCHOOL_ID}/modules/{module}");
2992429926 if module.dependents().is_empty() {
2992529927 let res = send(&app, "DELETE", &one, Some(&builder), None).await;
2992629928 assert_eq!(
@@ -29993,7 +29995,7 @@ async fn every_module_gates_its_own_nest_when_the_builder_takes_it_back() {
2999329995 #[tokio::test]
2999429996 async fn every_course_child_route_names_its_own_module() {
2999529997 let (app, db, tenants) = common::app_and_tenants().await;
29996- let slug = Slug::try_new(DEMO_SLUG).unwrap();
29998+ let slug = SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap();
2999729999 let cookie = login_as(&app, &db, "ada", "admin").await;
2999830000 let course = create_course(&app, &cookie, "Fizik").await;
2999930001 let class = create_class(&app, &cookie, "9-F", json!({})).await;
@@ -30045,7 +30047,7 @@ async fn every_course_child_route_names_its_own_module() {
3004530047 /// and can be told what it has — none of that lives behind a module.
3004630048 #[tokio::test]
3004730049 async fn a_school_with_no_modules_can_still_use_the_core_routes() {
30048- let (app, _db, _tenants) = sweep_deployment().await;
30050+ let (app, _db, tenants) = sweep_deployment().await;
3004930051 let builder = sweep_builder_login(&app).await;
3005030052
3005130053 let res = send(
@@ -30054,8 +30056,7 @@ async fn a_school_with_no_modules_can_still_use_the_core_routes() {
3005430056 "/schools",
3005530057 Some(&builder),
3005630058 Some(json!({
30057- "slug": "bare",
30058- "name": "Bare School",
30059+ "name": "bare school",
3005930060 "admin_username": "admin",
3006030061 "admin_password": "secret1",
3006130062 "modules": [],
@@ -30065,12 +30066,16 @@ async fn a_school_with_no_modules_can_still_use_the_core_routes() {
3006530066 assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
3006630067 assert_eq!(res.body["modules"], json!([]));
3006730068
30069+ let bare_id: Uuid = sqlx::query_scalar("SELECT id FROM school WHERE name = 'bare school'")
30070+ .fetch_one(tenants.control())
30071+ .await
30072+ .expect("bare school");
3006830073 let res = send(
3006930074 &app,
3007030075 "POST",
3007130076 "/auth/login",
3007230077 None,
30073- Some(json!({ "school": "bare", "username": "admin", "password": "secret1" })),
30078+ Some(json!({ "username": "admin", "password": "secret1" })),
3007430079 )
3007530080 .await;
3007630081 assert_eq!(
@@ -30079,7 +30084,20 @@ async fn a_school_with_no_modules_can_still_use_the_core_routes() {
3007930084 "a bare school still logs in: {}",
3008030085 res.body
3008130086 );
30082- let cookie = res.cookie.expect("session cookie");
30087+ let cookie = if res.body["schools"].is_array() {
30088+ let selected = send(
30089+ &app,
30090+ "POST",
30091+ "/auth/school",
30092+ res.cookie.as_deref(),
30093+ Some(json!({ "school": bare_id.to_string() })),
30094+ )
30095+ .await;
30096+ assert_eq!(selected.status, StatusCode::OK, "{}", selected.body);
30097+ selected.cookie.expect("session cookie")
30098+ } else {
30099+ res.cookie.expect("session cookie")
30100+ };
3008330101
3008430102 for route in [
3008530103 "/auth/me",
@@ -30268,7 +30286,7 @@ async fn login_without_school_enters_a_single_school_person() {
3026830286 "POST",
3026930287 "/auth/register",
3027030288 None,
30271- Some(json!({ "school": DEMO_SLUG, "username": "personada", "password": "secret1" })),
30289+ Some(json!({ "school": DEMO_SCHOOL_ID, "username": "personada", "password": "secret1" })),
3027230290 )
3027330291 .await;
3027430292 assert_eq!(reg.status, StatusCode::CREATED, "{}", reg.body);
@@ -30285,7 +30303,7 @@ async fn login_without_school_enters_a_single_school_person() {
3028530303 assert!(res.body["id"].is_string(), "the person's id: {}", res.body);
3028630304 assert_eq!(res.body["username"], "personada");
3028730305 let cookie = res.cookie.expect("school cookie");
30288- assert!(cookie.starts_with("session=demo."), "cookie: {cookie}");
30306+ assert!(cookie.starts_with(&format!("session={DEMO_SCHOOL_ID}.")), "cookie: {cookie}");
3028930307
3029030308 let res = send(&app, "GET", "/auth/me", Some(&cookie), None).await;
3029130309 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
@@ -30298,13 +30316,13 @@ async fn login_without_school_enters_a_single_school_person() {
3029830316 async fn a_multischool_person_selects_a_school() {
3029930317 let d = common::deployment_with(TWO_SCHOOLS).await;
3030030318 let app = &d.app;
30301- for school in [DEMO_SLUG, "beta"] {
30319+ for school in [DEMO_SCHOOL_ID, "beta"] {
3030230320 let reg = send(
3030330321 app,
3030430322 "POST",
3030530323 "/auth/register",
3030630324 None,
30307- Some(json!({ "school": school, "username": "personada", "password": "secret1" })),
30325+ Some(json!({ "school": common::school_wire(school), "username": "personada", "password": "secret1" })),
3030830326 )
3030930327 .await;
3031030328 assert_eq!(
@@ -30325,14 +30343,16 @@ async fn a_multischool_person_selects_a_school() {
3032530343 .await;
3032630344 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
3032730345 assert_eq!(res.body["username"], "personada");
30328- let mut slugs: Vec<&str> = res.body["schools"]
30346+ let mut ids: Vec<&str> = res.body["schools"]
3032930347 .as_array()
3033030348 .expect("schools list")
3033130349 .iter()
30332- .map(|s| s["slug"].as_str().expect("school slug"))
30350+ .map(|s| s["id"].as_str().expect("school id"))
3033330351 .collect();
30334- slugs.sort_unstable();
30335- assert_eq!(slugs, ["beta", "demo"]);
30352+ ids.sort_unstable();
30353+ let mut expected = [DEMO_SCHOOL_ID, hezarfen_backend::tenant::BETA_SCHOOL_ID];
30354+ expected.sort_unstable();
30355+ assert_eq!(ids, expected);
3033630356 assert!(
3033730357 res.body.get("id").is_none(),
3033830358 "no school chosen yet: {}",
@@ -30350,13 +30370,13 @@ async fn a_multischool_person_selects_a_school() {
3035030370 "POST",
3035130371 "/auth/school",
3035230372 Some(&person),
30353- Some(json!({ "school": DEMO_SLUG })),
30373+ Some(json!({ "school": DEMO_SCHOOL_ID })),
3035430374 )
3035530375 .await;
3035630376 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
3035730377 assert!(res.body["id"].is_string(), "the person's id: {}", res.body);
3035830378 let cookie = res.cookie.expect("school cookie");
30359- assert!(cookie.starts_with("session=demo."), "cookie: {cookie}");
30379+ assert!(cookie.starts_with(&format!("session={DEMO_SCHOOL_ID}.")), "cookie: {cookie}");
3036030380 let res = send(app, "GET", "/auth/me", Some(&cookie), None).await;
3036130381 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
3036230382 }
@@ -30368,13 +30388,13 @@ async fn a_multischool_person_selects_a_school() {
3036830388 async fn school_selection_refuses_non_members_and_wrong_cookies() {
3036930389 let d = common::deployment_with(TWO_SCHOOLS).await;
3037030390 let app = &d.app;
30371- for school in [DEMO_SLUG, "beta"] {
30391+ for school in [DEMO_SCHOOL_ID, "beta"] {
3037230392 let reg = send(
3037330393 app,
3037430394 "POST",
3037530395 "/auth/register",
3037630396 None,
30377- Some(json!({ "school": school, "username": "personada", "password": "secret1" })),
30397+ Some(json!({ "school": common::school_wire(school), "username": "personada", "password": "secret1" })),
3037830398 )
3037930399 .await;
3038030400 assert_eq!(
@@ -30412,7 +30432,7 @@ async fn school_selection_refuses_non_members_and_wrong_cookies() {
3041230432 "POST",
3041330433 "/auth/school",
3041430434 None,
30415- Some(json!({ "school": DEMO_SLUG })),
30435+ Some(json!({ "school": DEMO_SCHOOL_ID })),
3041630436 )
3041730437 .await;
3041830438 assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{}", res.body);
@@ -30423,7 +30443,7 @@ async fn school_selection_refuses_non_members_and_wrong_cookies() {
3042330443 "POST",
3042430444 "/auth/school",
3042530445 Some(&person),
30426- Some(json!({ "school": DEMO_SLUG })),
30446+ Some(json!({ "school": DEMO_SCHOOL_ID })),
3042730447 )
3042830448 .await;
3042930449 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
@@ -30435,7 +30455,7 @@ async fn school_selection_refuses_non_members_and_wrong_cookies() {
3043530455 "POST",
3043630456 "/auth/school",
3043730457 Some(&school_cookie),
30438- Some(json!({ "school": DEMO_SLUG })),
30458+ Some(json!({ "school": DEMO_SCHOOL_ID })),
3043930459 )
3044030460 .await;
3044130461 assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{}", res.body);
@@ -30451,7 +30471,7 @@ async fn login_ignores_a_leftover_school_field() {
3045130471 "POST",
3045230472 "/auth/register",
3045330473 None,
30454- Some(json!({ "school": DEMO_SLUG, "username": "personada", "password": "secret1" })),
30474+ Some(json!({ "school": DEMO_SCHOOL_ID, "username": "personada", "password": "secret1" })),
3045530475 )
3045630476 .await;
3045730477 assert_eq!(reg.status, StatusCode::CREATED, "{}", reg.body);
@@ -30461,7 +30481,7 @@ async fn login_ignores_a_leftover_school_field() {
3046130481 "POST",
3046230482 "/auth/login",
3046330483 None,
30464- Some(json!({ "school": "demo", "username": "personada", "password": "secret1" })),
30484+ Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "personada", "password": "secret1" })),
3046530485 )
3046630486 .await;
3046730487 assert_eq!(res.status, StatusCode::OK, "{}", res.body);
tests/pagination.rsmodified+2 -2
@@ -16,7 +16,7 @@ use serde_json::json;
1616 async fn seed_students(app: &axum::Router, n: usize) {
1717 for i in 0..n {
1818 let name = format!("user{i:02}");
19- let creds = json!({ "school": "demo", "username": name, "password": "secret1" });
19+ let creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": name, "password": "secret1" });
2020 let res = send(app, "POST", "/auth/register", None, Some(creds)).await;
2121 assert_eq!(res.status, StatusCode::CREATED, "register {name}");
2222 }
@@ -330,7 +330,7 @@ async fn user_search_is_paged_not_capped() {
330330 // 12 accounts sharing the "grp" fragment — past the old cap.
331331 for i in 0..12 {
332332 let creds =
333- json!({ "school": "demo", "username": format!("grp{i:02}"), "password": "secret1" });
333+ json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": format!("grp{i:02}"), "password": "secret1" });
334334 let res = send(&app, "POST", "/auth/register", None, Some(creds)).await;
335335 assert_eq!(res.status, StatusCode::CREATED);
336336 }
tests/persistence.rsmodified+25 -34
@@ -14,7 +14,7 @@ use hezarfen_backend::database::Database;
1414 use hezarfen_backend::module::ModuleSet;
1515 use hezarfen_backend::rate_limit::RateLimitConfig;
1616 use hezarfen_backend::state::AppState;
17-use hezarfen_backend::tenant::{Slug, Tenants};
17+use hezarfen_backend::tenant::Tenants;
1818 use hezarfen_backend::{build_router, database};
1919 use serde_json::json;
2020
@@ -46,7 +46,7 @@ async fn reboot(db: &Database, tenants: &Tenants) -> Router {
4646 async fn settings_and_terms_survive_remigration() {
4747 let (app, db, tenants) = common::app_and_tenants().await;
4848
49- let creds = json!({ "school": "demo", "username": "boss", "password": "secret1" });
49+ let creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "boss", "password": "secret1" });
5050 send(&app, "POST", "/auth/register", None, Some(creds)).await;
5151 set_role(&db, "boss", "manager").await;
5252 let login = json!({ "username": "boss", "password": "secret1" });
@@ -128,8 +128,8 @@ async fn appointments_survive_remigration() {
128128 const PROPOSED_END: i64 = START + 8_000_003;
129129
130130 let (app, db, tenants) = common::app_and_tenants().await;
131- let teacher_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" });
132- let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" });
131+ let teacher_creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ali", "password": "secret1" });
132+ let student_creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ayse", "password": "secret1" });
133133 for creds in [&teacher_creds, &student_creds] {
134134 assert_eq!(
135135 send(&app, "POST", "/auth/register", None, Some((*creds).clone()))
@@ -274,8 +274,8 @@ async fn appointments_survive_remigration() {
274274 #[tokio::test]
275275 async fn attempt_history_survives_remigration() {
276276 let (app, db, tenants) = common::app_and_tenants().await;
277- let teacher_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" });
278- let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" });
277+ let teacher_creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ali", "password": "secret1" });
278+ let student_creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ayse", "password": "secret1" });
279279 for creds in [&teacher_creds, &student_creds] {
280280 assert_eq!(
281281 send(&app, "POST", "/auth/register", None, Some((*creds).clone()))
@@ -565,7 +565,7 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() {
565565 async fn settings_slots_without_a_serving_minute_still_patch() {
566566 let (app, db, tenants) = common::app_and_tenants().await;
567567
568- let creds = json!({ "school": "demo", "username": "boss", "password": "secret1" });
568+ let creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "boss", "password": "secret1" });
569569 send(&app, "POST", "/auth/register", None, Some(creds)).await;
570570 set_role(&db, "boss", "manager").await;
571571 let login = json!({ "username": "boss", "password": "secret1" });
@@ -618,8 +618,8 @@ async fn settings_slots_without_a_serving_minute_still_patch() {
618618 #[tokio::test]
619619 async fn fee_plans_and_their_charges_survive_remigration() {
620620 let (app, db, tenants) = common::app_and_tenants().await;
621- let manager_creds = json!({ "school": "demo", "username": "ali", "password": "secret1" });
622- let student_creds = json!({ "school": "demo", "username": "ayse", "password": "secret1" });
621+ let manager_creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ali", "password": "secret1" });
622+ let student_creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ayse", "password": "secret1" });
623623 for creds in [&manager_creds, &student_creds] {
624624 assert_eq!(
625625 send(&app, "POST", "/auth/register", None, Some((*creds).clone()))
@@ -859,14 +859,9 @@ async fn boards_and_their_strokes_survive_remigration() {
859859 #[tokio::test]
860860 async fn an_empty_module_list_survives_a_second_boot() {
861861 let tenants = database::init_test_tenants().await;
862- let slug = Slug::try_new("bare").unwrap();
862+ let bare = hezarfen_backend::tenant::SchoolId::generate();
863863 tenants
864- .create(
865- hezarfen_backend::tenant::SchoolId::generate(),
866- &slug,
867- "Bare School",
868- ModuleSet::empty(),
869- )
864+ .create(bare, "Bare School", ModuleSet::empty())
870865 .await
871866 .expect("a school with nothing switched on");
872867
@@ -877,9 +872,9 @@ async fn an_empty_module_list_survives_a_second_boot() {
877872 let stored: i64 = sqlx::query_scalar(
878873 "SELECT count(*) FROM school_module sm
879874 JOIN school s ON s.id = sm.school
880- WHERE s.slug = $1",
875+ WHERE s.id = $1",
881876 )
882- .bind(slug.as_str())
877+ .bind(bare.uuid())
883878 .fetch_one(tenants.control())
884879 .await
885880 .expect("read the row back");
@@ -909,7 +904,6 @@ async fn probe_control_migration_is_idempotent_over_aged_rows() {
909904 tenants
910905 .create(
911906 hezarfen_backend::tenant::SchoolId::generate(),
912- &Slug::try_new(slug).unwrap(),
913907 name,
914908 modules,
915909 )
@@ -944,16 +938,14 @@ async fn probe_control_migration_is_idempotent_over_aged_rows() {
944938 async fn a_half_made_school_is_finished_by_the_next_boot() {
945939 let tenants = database::init_test_tenants().await;
946940 let control = tenants.control().clone();
947- let slug = Slug::try_new("half-made").unwrap();
948941 let id = hezarfen_backend::tenant::SchoolId::generate();
949942
950943 // Exactly what `Tenants::create` commits before it mints a database: the
951944 // registry row (as `provisioning`) and its entitlements.
952945 sqlx::query(
953- "INSERT INTO school (id, slug, name, status, created_at) VALUES ($1, $2, $3, $4, $5)",
946+ "INSERT INTO school (id, name, status, created_at) VALUES ($1, $2, $3, $4)",
954947 )
955948 .bind(id.uuid())
956- .bind(slug.as_str())
957949 .bind("Half Made")
958950 .bind("provisioning")
959951 .bind(hezarfen_backend::domain::timestamp::Timestamp::now().as_millis())
@@ -962,19 +954,19 @@ async fn a_half_made_school_is_finished_by_the_next_boot() {
962954 .expect("seed a half-made school row");
963955
964956 assert!(
965- tenants.get(&slug).await.is_err(),
957+ tenants.get(&id).await.is_err(),
966958 "a school that is still being made must not serve"
967959 );
968- assert_eq!(status_of(&control, "half-made").await, "provisioning");
960+ assert_eq!(status_of(&control, &id.as_str()).await, "provisioning");
969961
970962 tenants
971963 .reconcile_provisioning()
972964 .await
973965 .expect("the boot finishes what the previous one started");
974966
975- assert_eq!(status_of(&control, "half-made").await, "active");
967+ assert_eq!(status_of(&control, &id.as_str()).await, "active");
976968 let db = tenants
977- .get(&slug)
969+ .get(&id)
978970 .await
979971 .expect("the finished school answers");
980972 let users: i64 = sqlx::query_scalar("SELECT count(*) FROM app_user")
@@ -986,7 +978,7 @@ async fn a_half_made_school_is_finished_by_the_next_boot() {
986978 // The database the reconciliation minted is this test's, so it goes with
987979 // the test (the harness only drops what `create` minted).
988980 tenants
989- .drop(&slug)
981+ .drop(&id)
990982 .await
991983 .expect("clean up the minted school");
992984 }
@@ -1009,11 +1001,9 @@ async fn a_half_made_school_is_finished_by_the_next_boot() {
10091001 #[tokio::test]
10101002 async fn a_school_behind_the_schema_head_is_migrated_by_the_next_boot() {
10111003 let tenants = database::init_test_tenants().await;
1012- let slug = Slug::try_new("behind-the-head").unwrap();
10131004 let school = tenants
10141005 .create(
10151006 hezarfen_backend::tenant::SchoolId::generate(),
1016- &slug,
10171007 "Behind The Head",
10181008 ModuleSet::all(),
10191009 )
@@ -1062,9 +1052,10 @@ async fn a_school_behind_the_schema_head_is_migrated_by_the_next_boot() {
10621052 }
10631053
10641054 /// One school's stored status, straight off the registry row.
1065-async fn status_of(control: &Database, slug: &str) -> String {
1066- sqlx::query_scalar("SELECT status FROM school WHERE slug = $1")
1067- .bind(slug)
1055+async fn status_of(control: &Database, school: &str) -> String {
1056+ let id = uuid::Uuid::parse_str(school).expect("school id is a uuid");
1057+ sqlx::query_scalar("SELECT status FROM school WHERE id = $1")
1058+ .bind(id)
10681059 .fetch_one(control)
10691060 .await
10701061 .unwrap()
@@ -1076,11 +1067,11 @@ async fn status_of(control: &Database, slug: &str) -> String {
10761067 async fn school_rows(control: &Database) -> Vec<(String, String, String, Vec<String>)> {
10771068 use sqlx::Row as _;
10781069 sqlx::query(
1079- "SELECT s.slug, s.name, s.status,
1070+ "SELECT s.id::text, s.name, s.status,
10801071 COALESCE(array_agg(sm.module) FILTER (WHERE sm.module IS NOT NULL), '{}')
10811072 FROM school s LEFT JOIN school_module sm ON sm.school = s.id
10821073 GROUP BY s.id
1083- ORDER BY s.slug",
1074+ ORDER BY s.id",
10841075 )
10851076 .fetch_all(control)
10861077 .await
tests/podcast.rsmodified+8 -8
@@ -33,7 +33,7 @@ use hezarfen_backend::constant::{
3333 use hezarfen_backend::database::Database;
3434 use hezarfen_backend::domain::timestamp::Timestamp;
3535 use hezarfen_backend::module::{Module, ModuleSet};
36-use hezarfen_backend::tenant::{DEMO_SLUG, Slug};
36+use hezarfen_backend::tenant::{DEMO_SCHOOL_ID, SchoolId};
3737 use serde_json::{Value, json};
3838 use uuid::Uuid;
3939
@@ -111,8 +111,8 @@ fn client_endpoint(bridge: &AiBridge) -> quinn::Endpoint {
111111 endpoint
112112 }
113113
114-fn demo() -> Slug {
115- Slug::try_new(DEMO_SLUG).expect("the demo slug")
114+fn demo() -> SchoolId {
115+ SchoolId::try_parse(DEMO_SCHOOL_ID).expect("the demo slug")
116116 }
117117
118118 fn hello(service: &str, capabilities: &[&str]) -> Hello {
@@ -412,7 +412,7 @@ fn report_frame(
412412 ) -> Value {
413413 json!({
414414 "id": format!("report-{state}"),
415- "school": DEMO_SLUG,
415+ "school": DEMO_SCHOOL_ID,
416416 "capability": "podcast.report",
417417 "payload": {
418418 "job_id": job_id,
@@ -433,7 +433,7 @@ fn upload_frame(job_id: &str, name: &str, content_type: &str, size: usize) -> Va
433433 json!({
434434 "id": format!("upload-{job_id}"),
435435 "upload": true,
436- "school": DEMO_SLUG,
436+ "school": DEMO_SCHOOL_ID,
437437 "job_id": job_id,
438438 "name": name,
439439 "content_type": content_type,
@@ -650,7 +650,7 @@ async fn a_submit_writes_the_row_and_hands_the_service_its_own_job_id() {
650650 let seen = service.seen();
651651 assert_eq!(seen.len(), 1, "exactly one dispatch");
652652 assert_eq!(seen[0].capability, AI_PODCAST_SUBMIT_CAPABILITY);
653- assert_eq!(seen[0].school, DEMO_SLUG, "the school rides the frame");
653+ assert_eq!(seen[0].school, DEMO_SCHOOL_ID, "the school rides the frame");
654654 assert_eq!(
655655 seen[0].payload["job_id"], job_id,
656656 "the service was handed the row's own id"
@@ -1239,10 +1239,10 @@ async fn the_history_never_shows_another_schools_jobs() {
12391239 let demo_db = common::demo_db(&deployment.tenants).await;
12401240 let beta_db = deployment
12411241 .tenants
1242- .get(&Slug::try_new("beta").expect("the beta slug"))
1242+ .get(&SchoolId::try_parse(hezarfen_backend::tenant::BETA_SCHOOL_ID).expect("the beta slug"))
12431243 .await
12441244 .expect("the beta school's handle");
1245- let demo_cookie = common::login_as_school(app, &demo_db, DEMO_SLUG, "ali", "teacher").await;
1245+ let demo_cookie = common::login_as_school(app, &demo_db, DEMO_SCHOOL_ID, "ali", "teacher").await;
12461246 let beta_cookie = common::login_as_school(app, &beta_db, "beta", "ali", "teacher").await;
12471247 let demo_user = common::me_id(app, &demo_cookie).await;
12481248 let beta_user = common::me_id(app, &beta_cookie).await;
tests/rate_limit.rsmodified+1 -1
@@ -105,7 +105,7 @@ async fn login_attempts_hit_the_auth_limit() {
105105 #[tokio::test]
106106 async fn register_and_login_share_the_auth_bucket() {
107107 let app = app_with(auth_only(2)).await;
108- let creds = json!({ "school": "demo", "username": "ada", "password": "secret1" });
108+ let creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ada", "password": "secret1" });
109109
110110 let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/register", Some(creds)).await;
111111 assert_eq!(status, StatusCode::CREATED);
tests/regress_bank_images.rsmodified+1 -1
@@ -65,7 +65,7 @@ async fn mem_app() -> (Router, Database, TempDir) {
6565 /// Every blob file currently on disk, by name.
6666 fn blobs(files: &TempDir) -> Vec<String> {
6767 // Blobs live under the school's own subdirectory of `FILES_PATH`.
68- let dir = files.path().join(hezarfen_backend::tenant::DEMO_SLUG);
68+ let dir = files.path().join(hezarfen_backend::tenant::DEMO_SCHOOL_ID);
6969 if !dir.exists() {
7070 return Vec::new();
7171 }
tests/spec_bounds.rsmodified+0 -16
@@ -61,8 +61,6 @@ async fn spec() -> Value {
6161 fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> {
6262 vec![
6363 // --- builder (the vendor surface) ---
64- ("CreateSchool", "slug", "minLength", MIN_SLUG_LEN as i64),
65- ("CreateSchool", "slug", "maxLength", MAX_SLUG_LEN as i64),
6664 (
6765 "CreateSchool",
6866 "name",
@@ -160,18 +158,6 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> {
160158 MAX_PASSWORD_LEN as i64,
161159 ),
162160 // --- auth / users / notes / messages ---
163- (
164- "RegisterCredentials",
165- "school",
166- "minLength",
167- MIN_SLUG_LEN as i64,
168- ),
169- (
170- "RegisterCredentials",
171- "school",
172- "maxLength",
173- MAX_SLUG_LEN as i64,
174- ),
175161 (
176162 "RegisterCredentials",
177163 "username",
@@ -250,8 +236,6 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> {
250236 "maxLength",
251237 MAX_STUDENT_NUMBER_LEN as i64,
252238 ),
253- ("SelectSchool", "school", "minLength", MIN_SLUG_LEN as i64),
254- ("SelectSchool", "school", "maxLength", MAX_SLUG_LEN as i64),
255239 ("UpdateProfile", "name", "maxLength", MAX_NAME_LEN as i64),
256240 ("UpdateProfile", "surname", "maxLength", MAX_NAME_LEN as i64),
257241 ("UpdateProfile", "email", "maxLength", MAX_EMAIL_LEN as i64),