School identity is the uuid
Browse files at this commit29180402042d9239f6438ff6692b365bd36f6f97Parent: c1d2674- feat
- school identity is the uuid
- drop the slug
61 changed files +1358 -1455
- .env.example +3 -3
- .sqlx/query-4a50c4e5b4c369736b0a5b55dfd143b69def99f1e2113817ff6b9b2bbfc8a2b9.json → .sqlx/query-49e01cec9e2b7b66955ff45127509f5d3a58de542a305a3971d4e0cc43d6ef14.json +3 -3
- .sqlx/query-9d9cce760c2a87090f4b3cf5da4afc868d6fb3c91a7ba9ae5b553dfb48be9353.json → .sqlx/query-5445331a2cfb2732d63fc5bc46956679906ecfa08aafa5284a6aec6f3496da1d.json +6 -6
- .sqlx/query-5ee0b9ddaaafd3254d338726fe24e29e4ab2680a2fe02cca1494c6a4fa511aac.json +38 -0
- .sqlx/query-ede2ad9dfbe1e9e069bd8912acb49d13f43f251bc7276d1a6b6fe249920677ad.json → .sqlx/query-9a2794125306f8c5fe68fb30b736aea829986d5e0bbe235310de7af8252ec3d8.json +3 -3
- .sqlx/query-c0f04896f37ecdb45eefd6ff79ede315709a64b53ff6fd8f6837f61283f1001b.json → .sqlx/query-ae2c93f1bdfb98b697268a8b8f6be1aebabfbe3ab9a87122c337a306eb0447b0.json +5 -5
- .sqlx/query-90ca4d8c108622034298f4da1ac3a4db6a284b2f95e0fe8a69bbec9117f5d0a0.json → .sqlx/query-ee11814d38c895c499dbab2a83a6704318a46f5b51d38697a2cce1e6ca4dbae0.json +5 -5
- README.md +69 -66
- compose.yaml +1 -1
- migrations/control/20260923000001_drop_school_slug.sql +4 -0
- src/ai/capability.rs +1 -1
- src/ai/insight.rs +8 -9
- src/ai/podcast.rs +8 -8
- src/ai/protocol.rs +14 -9
- src/ai/rag.rs +15 -15
- src/ai/rag_chat.rs +2 -2
- src/ai/rag_study.rs +5 -5
- src/ai/server.rs +36 -35
- src/constant.rs +1 -7
- src/database.rs +6 -7
- src/db/insight.rs +16 -15
- src/db/person.rs +26 -17
- src/domain/builder.rs +1 -1
- src/domain/person.rs +4 -4
- src/lib.rs +4 -4
- src/service/person.rs +5 -5
- src/service/user.rs +4 -4
- src/state.rs +28 -28
- src/telemetry.rs +6 -6
- src/tenant.rs +137 -162
- src/web/auth.rs +50 -27
- src/web/board_ws.rs +13 -13
- src/web/boards.rs +15 -15
- src/web/builder.rs +80 -89
- src/web/chatbot.rs +6 -6
- src/web/exam_ws.rs +8 -8
- src/web/extractor.rs +5 -5
- src/web/insights.rs +9 -9
- src/web/limits.rs +0 -11
- src/web/modules.rs +1 -1
- src/web/podcast.rs +5 -5
- src/web/rag.rs +9 -9
- src/web/room.rs +4 -3
- src/web/school.rs +4 -6
- src/web/tenant_state.rs +28 -28
- src/web/users.rs +6 -6
- tests/ai_bridge.rs +48 -53
- tests/ai_protocol.rs +28 -29
- tests/auth_enumeration.rs +5 -5
- tests/builder_api.rs +364 -493
- tests/common/mod.rs +30 -15
- tests/e2e.rs +7 -7
- tests/etag.rs +1 -1
- tests/insight_report.rs +4 -6
- tests/integration.rs +127 -107
- tests/pagination.rs +2 -2
- tests/persistence.rs +25 -34
- tests/podcast.rs +8 -8
- tests/rate_limit.rs +1 -1
- tests/regress_bank_images.rs +1 -1
- tests/spec_bounds.rs +0 -16
.env.examplemodified+3 -3
| @@ -12,7 +12,7 @@ DATABASE_URL=postgres://hezarfen:hezarfen@127.0.0.1:5432/hezarfen_control | ||
| 12 | 12 | # HEZARFEN_TEST_DATABASE_URL=postgres://hezarfen:hezarfen@127.0.0.1:5432/postgres |
| 13 | 13 | |
| 14 | 14 | # 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. | |
| 16 | 16 | FILES_PATH=./data/files |
| 17 | 17 | |
| 18 | 18 | # Optional log filter. |
| @@ -59,7 +59,7 @@ RUST_LOG=info,hezarfen_backend=debug | ||
| 59 | 59 | # Seed a BUILDER account at startup: the deployment operator who creates, |
| 60 | 60 | # suspends and drops schools. Not a user of any school and holds no role in |
| 61 | 61 | # 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 | |
| 63 | 63 | # username is left exactly as it is — the seed never rewrites a credential, so |
| 64 | 64 | # changing the password here does not re-key a live builder. |
| 65 | 65 | # BUILDER_USERNAME=builder |
| @@ -92,7 +92,7 @@ RUST_LOG=info,hezarfen_backend=debug | ||
| 92 | 92 | # entirely; the process logs to stdout exactly as before. |
| 93 | 93 | # Nothing user-identifying ever leaves here: no user id, no client IP, no URL |
| 94 | 94 | # 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. | |
| 96 | 96 | # OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4317 |
| 97 | 97 | |
| 98 | 98 | # 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 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "db_name": "PostgreSQL", |
| 3 | - "query": "SELECT id, name FROM school WHERE slug = $1", | |
| 3 | + "query": "SELECT id, name FROM school WHERE id = $1", | |
| 4 | 4 | "describe": { |
| 5 | 5 | "columns": [ |
| 6 | 6 | { |
| @@ -28,7 +28,7 @@ | ||
| 28 | 28 | ], |
| 29 | 29 | "parameters": { |
| 30 | 30 | "Left": [ |
| 31 | - "Text" | |
| 31 | + "Uuid" | |
| 32 | 32 | ] |
| 33 | 33 | }, |
| 34 | 34 | "nullable": [ |
| @@ -36,5 +36,5 @@ | ||
| 36 | 36 | false |
| 37 | 37 | ] |
| 38 | 38 | }, |
| 39 | - "hash": "4a50c4e5b4c369736b0a5b55dfd143b69def99f1e2113817ff6b9b2bbfc8a2b9" | |
| 39 | + "hash": "49e01cec9e2b7b66955ff45127509f5d3a58de542a305a3971d4e0cc43d6ef14" | |
| 40 | 40 | } |
.sqlx/query-9d9cce760c2a87090f4b3cf5da4afc868d6fb3c91a7ba9ae5b553dfb48be9353.json → .sqlx/query-5445331a2cfb2732d63fc5bc46956679906ecfa08aafa5284a6aec6f3496da1d.jsonrenamed+6 -6
| @@ -1,16 +1,16 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "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", | |
| 4 | 4 | "describe": { |
| 5 | 5 | "columns": [ |
| 6 | 6 | { |
| 7 | 7 | "ordinal": 0, |
| 8 | - "name": "slug: Slug", | |
| 9 | - "type_info": "Text", | |
| 8 | + "name": "id: SchoolId", | |
| 9 | + "type_info": "Uuid", | |
| 10 | 10 | "origin": { |
| 11 | 11 | "Table": { |
| 12 | 12 | "table": "school", |
| 13 | - "name": "slug" | |
| 13 | + "name": "id" | |
| 14 | 14 | } |
| 15 | 15 | } |
| 16 | 16 | }, |
| @@ -40,7 +40,7 @@ | ||
| 40 | 40 | "parameters": { |
| 41 | 41 | "Left": [ |
| 42 | 42 | "Uuid", |
| 43 | - "Text" | |
| 43 | + "Uuid" | |
| 44 | 44 | ] |
| 45 | 45 | }, |
| 46 | 46 | "nullable": [ |
| @@ -49,5 +49,5 @@ | ||
| 49 | 49 | false |
| 50 | 50 | ] |
| 51 | 51 | }, |
| 52 | - "hash": "9d9cce760c2a87090f4b3cf5da4afc868d6fb3c91a7ba9ae5b553dfb48be9353" | |
| 52 | + "hash": "5445331a2cfb2732d63fc5bc46956679906ecfa08aafa5284a6aec6f3496da1d" | |
| 53 | 53 | } |
.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 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "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", | |
| 4 | 4 | "describe": { |
| 5 | 5 | "columns": [], |
| 6 | 6 | "parameters": { |
| 7 | 7 | "Left": [ |
| 8 | 8 | "Uuid", |
| 9 | - "Text", | |
| 9 | + "Uuid", | |
| 10 | 10 | "Int8" |
| 11 | 11 | ] |
| 12 | 12 | }, |
| 13 | 13 | "nullable": [] |
| 14 | 14 | }, |
| 15 | - "hash": "ede2ad9dfbe1e9e069bd8912acb49d13f43f251bc7276d1a6b6fe249920677ad" | |
| 15 | + "hash": "9a2794125306f8c5fe68fb30b736aea829986d5e0bbe235310de7af8252ec3d8" | |
| 16 | 16 | } |
.sqlx/query-c0f04896f37ecdb45eefd6ff79ede315709a64b53ff6fd8f6837f61283f1001b.json → .sqlx/query-ae2c93f1bdfb98b697268a8b8f6be1aebabfbe3ab9a87122c337a306eb0447b0.jsonrenamed+5 -5
| @@ -1,16 +1,16 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "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", | |
| 4 | 4 | "describe": { |
| 5 | 5 | "columns": [ |
| 6 | 6 | { |
| 7 | 7 | "ordinal": 0, |
| 8 | - "name": "slug", | |
| 9 | - "type_info": "Text", | |
| 8 | + "name": "id", | |
| 9 | + "type_info": "Uuid", | |
| 10 | 10 | "origin": { |
| 11 | 11 | "Table": { |
| 12 | 12 | "table": "school", |
| 13 | - "name": "slug" | |
| 13 | + "name": "id" | |
| 14 | 14 | } |
| 15 | 15 | } |
| 16 | 16 | } |
| @@ -22,5 +22,5 @@ | ||
| 22 | 22 | false |
| 23 | 23 | ] |
| 24 | 24 | }, |
| 25 | - "hash": "c0f04896f37ecdb45eefd6ff79ede315709a64b53ff6fd8f6837f61283f1001b" | |
| 25 | + "hash": "ae2c93f1bdfb98b697268a8b8f6be1aebabfbe3ab9a87122c337a306eb0447b0" | |
| 26 | 26 | } |
.sqlx/query-90ca4d8c108622034298f4da1ac3a4db6a284b2f95e0fe8a69bbec9117f5d0a0.json → .sqlx/query-ee11814d38c895c499dbab2a83a6704318a46f5b51d38697a2cce1e6ca4dbae0.jsonrenamed+5 -5
| @@ -1,16 +1,16 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "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", | |
| 4 | 4 | "describe": { |
| 5 | 5 | "columns": [ |
| 6 | 6 | { |
| 7 | 7 | "ordinal": 0, |
| 8 | - "name": "slug: Slug", | |
| 9 | - "type_info": "Text", | |
| 8 | + "name": "id: SchoolId", | |
| 9 | + "type_info": "Uuid", | |
| 10 | 10 | "origin": { |
| 11 | 11 | "Table": { |
| 12 | 12 | "table": "school", |
| 13 | - "name": "slug" | |
| 13 | + "name": "id" | |
| 14 | 14 | } |
| 15 | 15 | } |
| 16 | 16 | }, |
| @@ -48,5 +48,5 @@ | ||
| 48 | 48 | false |
| 49 | 49 | ] |
| 50 | 50 | }, |
| 51 | - "hash": "90ca4d8c108622034298f4da1ac3a4db6a284b2f95e0fe8a69bbec9117f5d0a0" | |
| 51 | + "hash": "ee11814d38c895c499dbab2a83a6704318a46f5b51d38697a2cce1e6ca4dbae0" | |
| 52 | 52 | } |
README.mdmodified+69 -66
| @@ -364,29 +364,29 @@ podman run -d --name hezarfen -p 7656:7656 -v hezarfen_backend_data:/data hezarf | ||
| 364 | 364 | ## Multi-school (SaaS) |
| 365 | 365 | |
| 366 | 366 | 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 | |
| 368 | 368 | **control** database `DATABASE_URL` points at (`hezarfen_control` by |
| 369 | 369 | default), which holds the school registry, the builder accounts and the |
| 370 | 370 | shared rate-limit window. Isolation is the store's, not the handlers': a |
| 371 | 371 | school database sees only its own rows, so no query carries a |
| 372 | 372 | `WHERE school = ...` somebody could forget. |
| 373 | 373 | |
| 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. | |
| 379 | 379 | |
| 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 | |
| 381 | 381 | `session=builder.<token>`, and a person who still has to pick a school carries |
| 382 | 382 | `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 | |
| 384 | 384 | ways), and a cookie with no dot names no school and is refused everywhere. |
| 385 | 385 | |
| 386 | 386 | **How a request finds its school.** Every school-scoped handler takes the |
| 387 | 387 | tenancy `State` (`web::tenant_state`), which reads the cookie's prefix, looks |
| 388 | 388 | 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 | |
| 390 | 390 | the one caller with no cookie: it injects the school as a request extension |
| 391 | 391 | instead, which nothing outside the process can forge. In-process state is keyed |
| 392 | 392 | by school too — the exam presence map and the whiteboard hub — so two schools |
| @@ -396,7 +396,7 @@ never share a room. | ||
| 396 | 396 | row is read on every request, so the next call after the switch answers `403`, |
| 397 | 397 | live session or not, `POST /auth/login` included. The builder surface keeps |
| 398 | 398 | 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. | |
| 400 | 400 | |
| 401 | 401 | **The builder lifecycle.** `BUILDER_USERNAME` + `BUILDER_PASSWORD` seed the |
| 402 | 402 | 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` → | ||
| 404 | 404 | `POST /schools` (registry row, database, schema and the school's first admin — |
| 405 | 405 | one call or none of it) → that admin (a **person** in the control database) |
| 406 | 406 | 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 | |
| 408 | 408 | 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 | |
| 411 | 411 | 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 | |
| 413 | 413 | its uploaded files. Irreversible on purpose: suspension is the reversible door. |
| 414 | 414 | |
| 415 | 415 | **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: | ||
| 471 | 471 | {"error": "conflict: courses is required by exams, subjects"} |
| 472 | 472 | ``` |
| 473 | 473 | |
| 474 | -**Selling.** `GET /schools/{slug}/modules` returns both halves (`enabled` + | |
| 474 | +**Selling.** `GET /schools/{id}/modules` returns both halves (`enabled` + | |
| 475 | 475 | `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 | |
| 477 | 477 | idempotent: a module the school already has (or already lacks) is a `200` with |
| 478 | 478 | the unchanged set. An unknown module name in the path is a `404`, the same |
| 479 | 479 | verdict an unknown school gets. |
| 480 | 480 | |
| 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 | |
| 482 | 482 | mix of the four optional lists `enable`, `disable`, `enable_packages`, |
| 483 | 483 | `disable_packages` (a package expands to its modules). The lists are folded |
| 484 | 484 | 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: | ||
| 532 | 532 | |
| 533 | 533 | ```bash |
| 534 | 534 | 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" | |
| 536 | 536 | 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 | |
| 538 | 538 | ``` |
| 539 | 539 | |
| 540 | 540 | ## Auth model |
| @@ -544,19 +544,21 @@ control database, that can belong to any number of schools. Login never names | ||
| 544 | 544 | a school — `POST /auth/login` takes `{username, password}` alone. A person |
| 545 | 545 | with exactly one active membership is logged straight into it: the response is |
| 546 | 546 | 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>` | |
| 549 | 549 | 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 | |
| 553 | 555 | "Multi-school (SaaS)"). |
| 554 | 556 | |
| 555 | 557 | Login sets an `HttpOnly`, `SameSite=Lax` `session` cookie (7-day expiry, |
| 556 | 558 | 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 | |
| 558 | 560 | `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`) | |
| 560 | 562 | don't (`logout` is idempotent — it clears whichever session the cookie names: |
| 561 | 563 | school, person, or builder). `GET /auth/me` is school-cookie only: a person |
| 562 | 564 | 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: | ||
| 720 | 722 | and fails unless each one is either referenced by `src/web/limits.rs` or |
| 721 | 723 | listed as a deliberate exclusion *with a reason*. A new constant breaks the |
| 722 | 724 | 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 | |
| 724 | 726 | bounds back out of the emitted JSON, and asserts each equals its constant. |
| 725 | 727 | This exists because utoipa's `#[schema(max_length = …)]` accepts a **literal |
| 726 | 728 | only** — a `const` there does not compile — so the annotations are |
| @@ -998,7 +1000,7 @@ still left exactly as they stand. | ||
| 998 | 1000 | |
| 999 | 1001 | There is no self-service path to `admin` — registration always creates a |
| 1000 | 1002 | `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 | |
| 1002 | 1004 | that account lands inside the new school's database holding `admin`. The |
| 1003 | 1005 | builder itself comes from the startup seed: set both |
| 1004 | 1006 | |
| @@ -1027,7 +1029,7 @@ instant, since the guard is a predicate on the role write itself: the | ||
| 1027 | 1029 | statement, so the count and the write it guards contend on the row lock |
| 1028 | 1030 | like any other write. |
| 1029 | 1031 | |
| 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`, | |
| 1031 | 1033 | which re-keys an admin that still exists. Manual fallback (the recovery path |
| 1032 | 1034 | if an older build already emptied a school's admin set): run |
| 1033 | 1035 | |
| @@ -1038,8 +1040,8 @@ UPDATE app_user SET role = 'admin' WHERE username = 'ada'; | ||
| 1038 | 1040 | against the **school's** database (`{control}_school_{uuid hex}` — the hex of |
| 1039 | 1041 | the school's registry `id`, no dashes), not the control one. List the school |
| 1040 | 1042 | 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. | |
| 1043 | 1045 | |
| 1044 | 1046 | ## Endpoints |
| 1045 | 1047 | |
| @@ -1170,11 +1172,12 @@ window filtering, before paging; negative values are a `400` naming the field. | ||
| 1170 | 1172 | | 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. | |
| 1171 | 1173 | | 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. | |
| 1172 | 1174 | | 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. | | |
| 1174 | 1176 | | POST | `/auth/logout` | no | Log out: revoke the current session (if any) and clear the cookie. Idempotent — no session required; answers `204` either way. | |
| 1175 | 1177 | | GET | `/auth/me` | student | Return the currently authenticated user. | |
| 1176 | 1178 | | 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. | | |
| 1178 | 1181 | | 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). | |
| 1179 | 1182 | | 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. | |
| 1180 | 1183 | | 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. | ||
| 1334 | 1337 | | POST | `/insights/runs` | manager | Store one compute run's ledger row (with its pending students and failed modules, both replaced). | |
| 1335 | 1338 | | GET | `/insights/runs/{run_day}/report` | manager | The stored report document, streamed. | |
| 1336 | 1339 | | 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. | | |
| 1338 | 1341 | | POST | `/insights/segments` | manager | Store a batch of ZEKA's question-segment labels (and each question's dimension split). | |
| 1339 | 1342 | | 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. | |
| 1340 | 1343 | | 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. | ||
| 1449 | 1452 | | GET | `/school` | student | The school the session cookie is bound to: its uuid and display name. | |
| 1450 | 1453 | | GET | `/schools` | builder | Every school this deployment serves, newest first. Paged via `?limit=&offset=` (omit `limit` for the full list). | |
| 1451 | 1454 | | 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. | | |
| 1461 | 1464 | | 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. | |
| 1462 | 1465 | | PATCH | `/sessions/{id}` | teacher | Update a session. Requires teacher+ with instance-management rights. Omitted fields keep their value; an explicit `null` clears `ends_at`. | |
| 1463 | 1466 | | 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 `/ \ ? # %`. | ||
| 3888 | 3891 | BASE=http://127.0.0.1:7656 |
| 3889 | 3892 | JAR=/tmp/hz.cookies |
| 3890 | 3893 | |
| 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 | |
| 3893 | 3896 | |
| 3894 | 3897 | curl -s $BASE/auth/register -H 'content-type: application/json' \ |
| 3895 | 3898 | -d '{"school":"'$SCHOOL'","username":"ali","password":"secret1"}' |
| 3896 | 3899 | |
| 3897 | 3900 | 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"}' | |
| 3899 | 3902 | |
| 3900 | 3903 | # notes |
| 3901 | 3904 | 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 | ||
| 4040 | 4043 | school would have to be run once per customer — and every *frame* names it |
| 4041 | 4044 | instead. |
| 4042 | 4045 | |
| 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 | |
| 4044 | 4047 | it is **required** on `Request`, `ApiRequest` and `BlobRequest`. Every answer |
| 4045 | 4048 | echoes it, refusals included, so a service can tell which of its in-flight |
| 4046 | 4049 | streams a refusal belongs to. There is no default and no fallback: a frame |
| @@ -4048,8 +4051,8 @@ naming no school is `malformed`. | ||
| 4048 | 4051 | |
| 4049 | 4052 | | `code` | Meaning | |
| 4050 | 4053 | | ------ | ------- | |
| 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 | | |
| 4053 | 4056 | | `school_suspended` | The school exists and is switched off; worth retrying later | |
| 4054 | 4057 | |
| 4055 | 4058 | 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`, | ||
| 4065 | 4068 | finishes its send side, and reads one `Response`: |
| 4066 | 4069 | |
| 4067 | 4070 | ```json |
| 4068 | -{ "id": "01J...", "school": "demo", "capability": "ocr.extract", | |
| 4071 | +{ "id": "01J...", "school": "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d", "capability": "ocr.extract", | |
| 4069 | 4072 | "deadline_ms": 30000, "payload": { "image": "<base64>" } } |
| 4070 | 4073 | ``` |
| 4071 | 4074 | |
| 4072 | 4075 | ```json |
| 4073 | -{ "status": "ok", "id": "01J...", "school": "demo", | |
| 4076 | +{ "status": "ok", "id": "01J...", "school": "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d", | |
| 4074 | 4077 | "payload": { "text": "..." } } |
| 4075 | -{ "status": "err", "id": "01J...", "school": "demo", | |
| 4078 | +{ "status": "err", "id": "01J...", "school": "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d", | |
| 4076 | 4079 | "code": "unsupported_image", "message": "only png and jpeg" } |
| 4077 | 4080 | ``` |
| 4078 | 4081 | |
| @@ -4221,7 +4224,7 @@ Same framing as every other `hab/2` frame; concurrency and correlation are the | ||
| 4221 | 4224 | stream, exactly as for capability requests. |
| 4222 | 4225 | |
| 4223 | 4226 | ```json |
| 4224 | -{ "id": "01J...", "school": "demo", "path": "/marks/me", | |
| 4227 | +{ "id": "01J...", "school": "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d", "path": "/marks/me", | |
| 4225 | 4228 | "query": "limit=10&offset=0", "on_behalf_of": "user:01J...", |
| 4226 | 4229 | "method": "GET" } |
| 4227 | 4230 | ``` |
| @@ -4235,9 +4238,9 @@ absent `method` means `GET`, and anything else is refused. | ||
| 4235 | 4238 | The answer is tagged by `outcome`: |
| 4236 | 4239 | |
| 4237 | 4240 | ```json |
| 4238 | -{ "outcome": "ok", "id": "01J...", "school": "demo", "status": 200, | |
| 4241 | +{ "outcome": "ok", "id": "01J...", "school": "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d", "status": 200, | |
| 4239 | 4242 | "body": { } } |
| 4240 | -{ "outcome": "err", "id": "01J...", "school": "demo", | |
| 4243 | +{ "outcome": "err", "id": "01J...", "school": "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d", | |
| 4241 | 4244 | "code": "path_not_allowed", |
| 4242 | 4245 | "message": "`/users` is not a path AI services may read" } |
| 4243 | 4246 | ``` |
| @@ -4250,10 +4253,10 @@ failure has misread the contract. | ||
| 4250 | 4253 | |
| 4251 | 4254 | | `code` | Meaning | |
| 4252 | 4255 | | ------ | ------- | |
| 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 | | |
| 4254 | 4257 | | `method_not_allowed` | `method` was present and was not `GET` | |
| 4255 | 4258 | | `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 | | |
| 4257 | 4260 | | `school_suspended` | That school is suspended — retryable once it is not | |
| 4258 | 4261 | | `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) | |
| 4259 | 4262 | | `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 | ||
| 4325 | 4328 | `ApiRequest` has `path`, a `BlobRequest` has `file`. |
| 4326 | 4329 | |
| 4327 | 4330 | ```json |
| 4328 | -{ "id": "01J...", "school": "demo", "file": "01J8XZ0K3Q8G7X2M4N5P6R7S8V", | |
| 4331 | +{ "id": "01J...", "school": "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d", "file": "01J8XZ0K3Q8G7X2M4N5P6R7S8V", | |
| 4329 | 4332 | "on_behalf_of": "user:01J..." } |
| 4330 | 4333 | ``` |
| 4331 | 4334 | |
| @@ -4343,9 +4346,9 @@ tag `Response` uses, not the api read's `outcome`, since a blob header carries | ||
| 4343 | 4346 | no HTTP status to collide with: |
| 4344 | 4347 | |
| 4345 | 4348 | ```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", | |
| 4347 | 4350 | "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", | |
| 4349 | 4352 | "message": "`01J...` may not view the course this file belongs to" } |
| 4350 | 4353 | ``` |
| 4351 | 4354 | |
| @@ -4363,7 +4366,7 @@ slow-but-reading service is never cut off. | ||
| 4363 | 4366 | |
| 4364 | 4367 | | `code` | Meaning | |
| 4365 | 4368 | | ------ | ------- | |
| 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 | | |
| 4367 | 4370 | | `not_found` | No `course_note_file` with that key *in that school*, or its note or course is gone | |
| 4368 | 4371 | | `forbidden` | The principal may not view that file's course | |
| 4369 | 4372 | | `unknown_school` / `school_suspended` | As for an api read | |
| @@ -5049,9 +5052,9 @@ src/ | ||
| 5049 | 5052 | while Postgres says "contended") + the two sqlx migrator |
| 5050 | 5053 | sets; init() brings up the control database, a mint |
| 5051 | 5054 | 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 | |
| 5055 | 5058 | tests' school) |
| 5056 | 5059 | db/ the only layer that executes queries: per-table SQL, one |
| 5057 | 5060 | file per resource · cap.rs (the count-cap CTE recipes and |
| @@ -5218,9 +5221,9 @@ src/ | ||
| 5218 | 5221 | web/ axum layer: DTOs (serde + OpenAPI schemas) + handlers + |
| 5219 | 5222 | auth extractors |
| 5220 | 5223 | 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 | |
| 5222 | 5225 | handler that imports it is school-scoped by construction |
| 5223 | - (ResolvedTenant · TenantExt · SchoolSlug · split_cookie) | |
| 5226 | + (ResolvedTenant · TenantExt · SchoolIdCookie · split_cookie) | |
| 5224 | 5227 | module_gate.rs one route_layer per nest: a module the school has not bought |
| 5225 | 5228 | answers 403 {error, module} on every route in it, while an |
| 5226 | 5229 | unmatched path inside it still 404s |
compose.yamlmodified+1 -1
| @@ -64,7 +64,7 @@ services: | ||
| 64 | 64 | HOST: 0.0.0.0 |
| 65 | 65 | PORT: "7656" |
| 66 | 66 | # 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). | |
| 68 | 68 | # Constructed from POSTGRES_* and always aimed at the compose postgres. |
| 69 | 69 | DATABASE_URL: postgres://${POSTGRES_USER:-hezarfen}:${POSTGRES_PASSWORD:-hezarfen}@postgres:5432/${POSTGRES_DB:-hezarfen_control} |
| 70 | 70 | # 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 @@ | ||
| 13 | 13 | //! The scope decides one thing only: whether the bridge resolves the frame's |
| 14 | 14 | //! school before the operation runs. A [`Scope::School`] operation runs against |
| 15 | 15 | //! 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 | |
| 17 | 17 | //! fallback to another school or to the control database. |
| 18 | 18 | |
| 19 | 19 | use serde_json::Value; |
src/ai/insight.rsmodified+8 -9
| @@ -46,7 +46,7 @@ use crate::constant::{ | ||
| 46 | 46 | AI_INSIGHT_REFRESH_TIMEOUT_SECS, AI_INSIGHT_REPORT_TIMEOUT_SECS, |
| 47 | 47 | AI_INSIGHT_STUDENT_TIMEOUT_SECS, |
| 48 | 48 | }; |
| 49 | -use crate::tenant::Slug; | |
| 49 | +use crate::tenant::SchoolId; | |
| 50 | 50 | |
| 51 | 51 | pub use crate::constant::{ |
| 52 | 52 | AI_INSIGHT_CLASS_CAPABILITY, AI_INSIGHT_REFRESH_CAPABILITY, AI_INSIGHT_REPORT_CAPABILITY, |
| @@ -218,7 +218,7 @@ pub struct ReportRequest { | ||
| 218 | 218 | /// rendering reads nothing, but the service's logs name the requester. |
| 219 | 219 | pub requested_by: String, |
| 220 | 220 | /// The school's own identity, so the document prints a display name |
| 221 | - /// rather than a slug. | |
| 221 | + /// rather than a raw id. | |
| 222 | 222 | pub school: ReportSchool, |
| 223 | 223 | /// Every class (şube) of the school, id and display name: the summaries' |
| 224 | 224 | /// evidence carries class **ids**, and a document that groups by class |
| @@ -272,7 +272,7 @@ pub struct ReportResponse { | ||
| 272 | 272 | /// door that has already answered `503` for it ([`crate::web::insights`]). |
| 273 | 273 | pub async fn compute_student( |
| 274 | 274 | bridge: &AiBridge, |
| 275 | - school: &Slug, | |
| 275 | + school: &SchoolId, | |
| 276 | 276 | request: &StudentRequest, |
| 277 | 277 | ) -> Result<StudentResponse, AiError> { |
| 278 | 278 | dispatch( |
| @@ -289,7 +289,7 @@ pub async fn compute_student( | ||
| 289 | 289 | /// batch is over; the deadline is [`AI_INSIGHT_REFRESH_TIMEOUT_SECS`]. |
| 290 | 290 | pub async fn refresh( |
| 291 | 291 | bridge: &AiBridge, |
| 292 | - school: &Slug, | |
| 292 | + school: &SchoolId, | |
| 293 | 293 | request: &RefreshRequest, |
| 294 | 294 | ) -> Result<RefreshResponse, AiError> { |
| 295 | 295 | dispatch( |
| @@ -310,7 +310,7 @@ pub async fn refresh( | ||
| 310 | 310 | /// document — this function only moves it. |
| 311 | 311 | pub async fn report( |
| 312 | 312 | bridge: &AiBridge, |
| 313 | - school: &Slug, | |
| 313 | + school: &SchoolId, | |
| 314 | 314 | request: &ReportRequest, |
| 315 | 315 | ) -> Result<ReportResponse, AiError> { |
| 316 | 316 | dispatch( |
| @@ -332,7 +332,7 @@ pub async fn report( | ||
| 332 | 332 | /// reporting the service out of step. |
| 333 | 333 | async fn dispatch<T>( |
| 334 | 334 | bridge: &AiBridge, |
| 335 | - school: &Slug, | |
| 335 | + school: &SchoolId, | |
| 336 | 336 | capability: &str, |
| 337 | 337 | timeout_secs: u64, |
| 338 | 338 | request: &impl Serialize, |
| @@ -613,8 +613,7 @@ mod tests { | ||
| 613 | 613 | run_day: "2026-09-17".into(), |
| 614 | 614 | requested_by: "user-9".into(), |
| 615 | 615 | school: ReportSchool { |
| 616 | - id: "school-1".into(), | |
| 617 | - slug: "demo".into(), | |
| 616 | + id: "019732e3-7b00-7000-8000-00000000dead".into(), | |
| 618 | 617 | name: "Demo Okulu".into(), |
| 619 | 618 | }, |
| 620 | 619 | classes: vec![ClassLabel { |
| @@ -632,7 +631,7 @@ mod tests { | ||
| 632 | 631 | "kind": "okul", |
| 633 | 632 | "run_day": "2026-09-17", |
| 634 | 633 | "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" }, | |
| 636 | 635 | "classes": [{ "id": "class-1", "name": "8-A" }], |
| 637 | 636 | "summaries": [], |
| 638 | 637 | "recommendations": [], |
src/ai/podcast.rsmodified+8 -8
| @@ -36,7 +36,7 @@ use crate::ai::error::AiError; | ||
| 36 | 36 | use crate::database::Database; |
| 37 | 37 | use crate::domain::podcast_job::PodcastJobId; |
| 38 | 38 | use crate::service::podcast_job::{PodcastRefusal, ReportInput}; |
| 39 | -use crate::tenant::Slug; | |
| 39 | +use crate::tenant::SchoolId; | |
| 40 | 40 | |
| 41 | 41 | /// The capability strings, re-exported so a reader of the payload contract |
| 42 | 42 | /// finds them next to the payloads — the same shape as |
| @@ -127,19 +127,19 @@ pub struct PodcastReportReply { | ||
| 127 | 127 | /// Start one job. `Err` is a short, stable code — see [`failure_code`]. |
| 128 | 128 | pub async fn submit( |
| 129 | 129 | bridge: &AiBridge, |
| 130 | - slug: &Slug, | |
| 130 | + school: &SchoolId, | |
| 131 | 131 | payload: PodcastSubmitPayload, |
| 132 | 132 | ) -> Result<PodcastSubmitReply, String> { |
| 133 | - dispatch(bridge, slug, AI_PODCAST_SUBMIT_CAPABILITY, payload).await | |
| 133 | + dispatch(bridge, school, AI_PODCAST_SUBMIT_CAPABILITY, payload).await | |
| 134 | 134 | } |
| 135 | 135 | |
| 136 | 136 | /// Cancel one job. |
| 137 | 137 | pub async fn cancel( |
| 138 | 138 | bridge: &AiBridge, |
| 139 | - slug: &Slug, | |
| 139 | + school: &SchoolId, | |
| 140 | 140 | payload: PodcastCancelPayload, |
| 141 | 141 | ) -> Result<PodcastCancelReply, String> { |
| 142 | - dispatch(bridge, slug, AI_PODCAST_CANCEL_CAPABILITY, payload).await | |
| 142 | + dispatch(bridge, school, AI_PODCAST_CANCEL_CAPABILITY, payload).await | |
| 143 | 143 | } |
| 144 | 144 | |
| 145 | 145 | /// Handle one client-initiated `podcast.report` call: decode the payload, |
| @@ -186,7 +186,7 @@ pub fn refusal(refusal: &PodcastRefusal) -> (&'static str, String) { | ||
| 186 | 186 | /// rename it into place, and stamp the row. |
| 187 | 187 | /// |
| 188 | 188 | /// `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 | |
| 190 | 190 | /// id, which is what the job row's own `audio_key` then publishes. |
| 191 | 191 | /// |
| 192 | 192 | /// The order is the point, and the same one the HTTP doors hold: a refusal |
| @@ -293,7 +293,7 @@ where | ||
| 293 | 293 | /// travels this path, so the encode/decode failure vocabulary is written once. |
| 294 | 294 | async fn dispatch<P, R>( |
| 295 | 295 | bridge: &AiBridge, |
| 296 | - slug: &Slug, | |
| 296 | + school: &SchoolId, | |
| 297 | 297 | capability: &str, |
| 298 | 298 | payload: P, |
| 299 | 299 | ) -> Result<R, String> |
| @@ -307,7 +307,7 @@ where | ||
| 307 | 307 | })?; |
| 308 | 308 | |
| 309 | 309 | let raw = bridge |
| 310 | - .dispatch(slug, capability, payload) | |
| 310 | + .dispatch(school, capability, payload) | |
| 311 | 311 | .await |
| 312 | 312 | .map_err(failure_code)?; |
| 313 | 313 |
src/ai/protocol.rsmodified+14 -9
| @@ -60,7 +60,7 @@ | ||
| 60 | 60 | //! |
| 61 | 61 | //! * `malformed` — the frame is not this shape (a missing or mistyped field). |
| 62 | 62 | //! * `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. | |
| 64 | 64 | //! * `school_suspended` — it exists and is switched off; worth retrying later. |
| 65 | 65 | //! * `not_permitted` — the school's own feature set refuses the operation. |
| 66 | 66 | //! * `invalid_payload` — the payload does not fit the operation's contract |
| @@ -75,13 +75,13 @@ | ||
| 75 | 75 | //! |
| 76 | 76 | //! # School scoping |
| 77 | 77 | //! |
| 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: | |
| 79 | 79 | //! [`Request::school`], [`ApiRequest::school`], [`BlobRequest::school`] and |
| 80 | 80 | //! their responses. The AI fleet is *shared* across the deployment — one |
| 81 | 81 | //! service serves every school — so the school cannot be bound once at |
| 82 | 82 | //! handshake time and [`Hello`] deliberately carries none: a service pinned to |
| 83 | 83 | //! 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 | |
| 85 | 85 | //! one `school_suspended`; there is no default and no fallback, because a read |
| 86 | 86 | //! answered out of the wrong school's database is the one failure this field |
| 87 | 87 | //! exists to make impossible. |
| @@ -175,7 +175,8 @@ pub enum RejectCode { | ||
| 175 | 175 | pub struct Request { |
| 176 | 176 | /// Trace id (ULID). Not used for correlation — the stream does that. |
| 177 | 177 | 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 | |
| 179 | 180 | /// "School scoping". |
| 180 | 181 | pub school: String, |
| 181 | 182 | /// Which capability from the worker's [`Hello::capabilities`] to invoke. |
| @@ -215,7 +216,8 @@ pub enum Response { | ||
| 215 | 216 | pub struct ApiRequest { |
| 216 | 217 | /// Trace id (ULID). Not used for correlation — the stream does that. |
| 217 | 218 | 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 | |
| 219 | 221 | /// scoping"; the answer comes out of that school's own database. |
| 220 | 222 | pub school: String, |
| 221 | 223 | /// Path as the REST API spells it, e.g. `"/users/me"`. No host, no query. |
| @@ -250,7 +252,7 @@ pub enum ApiResponse { | ||
| 250 | 252 | Err { |
| 251 | 253 | id: String, |
| 252 | 254 | /// 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 | |
| 254 | 256 | /// in-flight reads was refused. |
| 255 | 257 | school: String, |
| 256 | 258 | /// Bridge-defined, stable, machine-readable (`"path_not_allowed"`, |
| @@ -267,7 +269,8 @@ pub enum ApiResponse { | ||
| 267 | 269 | pub struct BlobRequest { |
| 268 | 270 | /// Trace id (ULID). Not used for correlation — the stream does that. |
| 269 | 271 | 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 | |
| 271 | 274 | /// "School scoping"; the bytes come out of that school's blob directory. |
| 272 | 275 | pub school: String, |
| 273 | 276 | /// The `course_note_file` record key, as `GET /course-notes/{id}/files` |
| @@ -317,7 +320,8 @@ pub enum BlobResponse { | ||
| 317 | 320 | pub struct CapabilityRequest { |
| 318 | 321 | /// Trace id (ULID). Not used for correlation — the stream does that. |
| 319 | 322 | 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 | |
| 321 | 325 | /// every other frame — one capability is deployment-scoped |
| 322 | 326 | /// (`insight.schools.list`, whose answer *is* the school directory) and |
| 323 | 327 | /// sends the empty string there. |
| @@ -372,7 +376,8 @@ pub struct BlobUploadRequest { | ||
| 372 | 376 | pub id: String, |
| 373 | 377 | /// The shape marker. Must be `true`; any other value is `malformed`. |
| 374 | 378 | 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 | |
| 376 | 381 | /// in that school's own blob directory, never anywhere else. |
| 377 | 382 | pub school: String, |
| 378 | 383 | /// The backend-minted podcast job the artifact belongs to. |
src/ai/rag.rsmodified+15 -15
| @@ -89,7 +89,7 @@ impl RagIndexPayload { | ||
| 89 | 89 | /// answered. Silent no-op when the bridge is off or no worker offers |
| 90 | 90 | /// `rag.index`. |
| 91 | 91 | /// |
| 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 | |
| 93 | 93 | /// `state.db` — the same school's database, since the caller reached this |
| 94 | 94 | /// through the shadow `State` — is where the answer is stored. |
| 95 | 95 | /// |
| @@ -108,11 +108,11 @@ pub async fn index_course_note(state: &AppState, tenant: &ResolvedTenant, note: | ||
| 108 | 108 | tracing::debug!( |
| 109 | 109 | "skipping rag.index for course note {}: the `{}` school has no `chatbot` module", |
| 110 | 110 | note.get_id().key(), |
| 111 | - tenant.slug | |
| 111 | + tenant.id | |
| 112 | 112 | ); |
| 113 | 113 | return; |
| 114 | 114 | } |
| 115 | - let school = &tenant.slug; | |
| 115 | + let school = &tenant.id; | |
| 116 | 116 | let Some(bridge) = state.ai.as_ref() else { |
| 117 | 117 | return; |
| 118 | 118 | }; |
| @@ -256,43 +256,43 @@ async fn replay_indexed_notes(state: AppState) { | ||
| 256 | 256 | return; |
| 257 | 257 | } |
| 258 | 258 | }; |
| 259 | - for slug in directory.schools { | |
| 260 | - replay_school(&state, &slug).await; | |
| 259 | + for school in directory.schools { | |
| 260 | + replay_school(&state, &school).await; | |
| 261 | 261 | } |
| 262 | 262 | } |
| 263 | 263 | |
| 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, | |
| 267 | 267 | 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}"); | |
| 269 | 269 | return; |
| 270 | 270 | } |
| 271 | 271 | }; |
| 272 | - let tenant = match state.tenants.resolve(&slug).await { | |
| 272 | + let tenant = match state.tenants.resolve(&id).await { | |
| 273 | 273 | Ok(tenant) => tenant, |
| 274 | 274 | Err(err) => { |
| 275 | - tracing::warn!("rag.index replay skipped `{slug}`: {err}"); | |
| 275 | + tracing::warn!("rag.index replay skipped `{id}`: {err}"); | |
| 276 | 276 | return; |
| 277 | 277 | } |
| 278 | 278 | }; |
| 279 | 279 | 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"); | |
| 281 | 281 | return; |
| 282 | 282 | } |
| 283 | 283 | let notes = match crate::db::course_note::list_with_files(&tenant.db).await { |
| 284 | 284 | Ok(notes) => notes, |
| 285 | 285 | 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}"); | |
| 287 | 287 | return; |
| 288 | 288 | } |
| 289 | 289 | }; |
| 290 | 290 | 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"); | |
| 292 | 292 | return; |
| 293 | 293 | } |
| 294 | 294 | tracing::info!( |
| 295 | - school = %slug, | |
| 295 | + school = %id, | |
| 296 | 296 | notes = notes.len(), |
| 297 | 297 | "replaying rag.index for course notes with files" |
| 298 | 298 | ); |
src/ai/rag_chat.rsmodified+2 -2
| @@ -149,7 +149,7 @@ pub struct RagChatReplyPayload { | ||
| 149 | 149 | pub async fn answer( |
| 150 | 150 | db: &crate::database::Database, |
| 151 | 151 | bridge: &crate::ai::AiBridge, |
| 152 | - slug: &crate::tenant::Slug, | |
| 152 | + school: &crate::tenant::SchoolId, | |
| 153 | 153 | thread: &crate::domain::rag_thread::RagThreadId, |
| 154 | 154 | fresh: &[crate::domain::rag_message::RagMessageId; 2], |
| 155 | 155 | prompt: String, |
| @@ -178,7 +178,7 @@ pub async fn answer( | ||
| 178 | 178 | |
| 179 | 179 | let raw = bridge |
| 180 | 180 | .dispatch_with_timeout( |
| 181 | - slug, | |
| 181 | + school, | |
| 182 | 182 | AI_RAG_CHAT_CAPABILITY, |
| 183 | 183 | payload, |
| 184 | 184 | std::time::Duration::from_secs(AI_RAG_CHAT_TIMEOUT_SECS), |
src/ai/rag_study.rsmodified+5 -5
| @@ -27,7 +27,7 @@ use crate::constant::{ | ||
| 27 | 27 | AI_RAG_QUESTIONS_CAPABILITY, AI_RAG_QUESTIONS_TIMEOUT_SECS, AI_RAG_SUMMARIZE_CAPABILITY, |
| 28 | 28 | AI_RAG_SUMMARIZE_TIMEOUT_SECS, |
| 29 | 29 | }; |
| 30 | -use crate::tenant::Slug; | |
| 30 | +use crate::tenant::SchoolId; | |
| 31 | 31 | |
| 32 | 32 | /// The one corpus a study request is addressed to, and where inside it. |
| 33 | 33 | /// |
| @@ -198,14 +198,14 @@ pub struct RagQuestionsReply { | ||
| 198 | 198 | /// reach the caller as a `502` — the same posture `rag.chat` takes. |
| 199 | 199 | pub async fn summarize( |
| 200 | 200 | bridge: &AiBridge, |
| 201 | - slug: &Slug, | |
| 201 | + school: &SchoolId, | |
| 202 | 202 | payload: RagSummarizePayload, |
| 203 | 203 | ) -> Result<RagSummarizeReply, String> { |
| 204 | 204 | let asker = payload.asker.clone(); |
| 205 | 205 | let encoded = encode(&payload, AI_RAG_SUMMARIZE_CAPABILITY)?; |
| 206 | 206 | let raw = bridge |
| 207 | 207 | .dispatch_with_timeout( |
| 208 | - slug, | |
| 208 | + school, | |
| 209 | 209 | AI_RAG_SUMMARIZE_CAPABILITY, |
| 210 | 210 | encoded, |
| 211 | 211 | Duration::from_secs(AI_RAG_SUMMARIZE_TIMEOUT_SECS), |
| @@ -221,14 +221,14 @@ pub async fn summarize( | ||
| 221 | 221 | /// corpus. The refusal vocabulary is [`summarize`]'s, code for code. |
| 222 | 222 | pub async fn questions( |
| 223 | 223 | bridge: &AiBridge, |
| 224 | - slug: &Slug, | |
| 224 | + school: &SchoolId, | |
| 225 | 225 | payload: RagQuestionsPayload, |
| 226 | 226 | ) -> Result<RagQuestionsReply, String> { |
| 227 | 227 | let asker = payload.asker.clone(); |
| 228 | 228 | let encoded = encode(&payload, AI_RAG_QUESTIONS_CAPABILITY)?; |
| 229 | 229 | let raw = bridge |
| 230 | 230 | .dispatch_with_timeout( |
| 231 | - slug, | |
| 231 | + school, | |
| 232 | 232 | AI_RAG_QUESTIONS_CAPABILITY, |
| 233 | 233 | encoded, |
| 234 | 234 | Duration::from_secs(AI_RAG_QUESTIONS_TIMEOUT_SECS), |
src/ai/server.rsmodified+36 -35
| @@ -35,7 +35,7 @@ use crate::module::Module; | ||
| 35 | 35 | use crate::state::AppState; |
| 36 | 36 | use crate::telemetry::Metrics; |
| 37 | 37 | use crate::service::course::can_view_course; |
| 38 | -use crate::tenant::{ResolvedTenant, Slug, Tenants}; | |
| 38 | +use crate::tenant::{ResolvedTenant, SchoolId, Tenants}; | |
| 39 | 39 | use crate::web::blob_path; |
| 40 | 40 | use crate::web::extractor::AiPrincipal; |
| 41 | 41 | use crate::web::tenant_state::{TenantExt, school_files_path}; |
| @@ -68,40 +68,41 @@ struct ApiHandle { | ||
| 68 | 68 | } |
| 69 | 69 | |
| 70 | 70 | 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. | |
| 73 | 72 | /// |
| 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. | |
| 79 | 77 | 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 { | |
| 87 | 88 | AppError::Unauthorized => ( |
| 88 | 89 | "unknown_school", |
| 89 | - format!("this deployment serves no `{slug}` school"), | |
| 90 | + format!("this deployment serves no `{id}` school"), | |
| 90 | 91 | ), |
| 91 | 92 | AppError::Forbidden(_) => ( |
| 92 | 93 | "school_suspended", |
| 93 | - format!("the `{slug}` school is suspended"), | |
| 94 | + format!("the `{id}` school is suspended"), | |
| 94 | 95 | ), |
| 95 | 96 | other => ( |
| 96 | 97 | "unavailable", |
| 97 | - format!("the `{slug}` school is not reachable: {other}"), | |
| 98 | + format!("the `{id}` school is not reachable: {other}"), | |
| 98 | 99 | ), |
| 99 | 100 | }) |
| 100 | 101 | } |
| 101 | 102 | |
| 102 | 103 | /// 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) | |
| 105 | 106 | } |
| 106 | 107 | } |
| 107 | 108 | |
| @@ -243,7 +244,7 @@ impl AiBridge { | ||
| 243 | 244 | /// the correlation, and a slow one cannot stall a fast one. |
| 244 | 245 | pub async fn dispatch( |
| 245 | 246 | &self, |
| 246 | - school: &Slug, | |
| 247 | + school: &SchoolId, | |
| 247 | 248 | capability: &str, |
| 248 | 249 | payload: Value, |
| 249 | 250 | ) -> Result<Value, AiError> { |
| @@ -256,7 +257,7 @@ impl AiBridge { | ||
| 256 | 257 | /// generation). |
| 257 | 258 | pub async fn dispatch_with_timeout( |
| 258 | 259 | &self, |
| 259 | - school: &Slug, | |
| 260 | + school: &SchoolId, | |
| 260 | 261 | capability: &str, |
| 261 | 262 | payload: Value, |
| 262 | 263 | timeout: Duration, |
| @@ -275,7 +276,7 @@ impl AiBridge { | ||
| 275 | 276 | payload, |
| 276 | 277 | }; |
| 277 | 278 | |
| 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 | |
| 279 | 280 | // call's own id — never the payload, which is the user's own text. |
| 280 | 281 | let span = tracing::info_span!( |
| 281 | 282 | "ai.request", |
| @@ -532,7 +533,7 @@ async fn serve_client_stream( | ||
| 532 | 533 | } |
| 533 | 534 | }; |
| 534 | 535 | 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: | |
| 536 | 537 | // it is how the service tells which of its in-flight reads was refused. |
| 537 | 538 | let school = string_field(&raw, "school"); |
| 538 | 539 | // Routed on the shape's required field rather than by parsing one and |
| @@ -740,18 +741,18 @@ async fn ingest_upload( | ||
| 740 | 741 | "the api is not serving yet — retry".to_string(), |
| 741 | 742 | ))?; |
| 742 | 743 | let tenant = api.school(&request.school).await?; |
| 743 | - let (slug, db) = (tenant.slug, tenant.db); | |
| 744 | + let (school, db) = (tenant.id, tenant.db); | |
| 744 | 745 | // This stream bypasses the router, so it also bypasses the route_layer the |
| 745 | 746 | // module gate is — the entitlement is checked here by hand instead. The |
| 746 | 747 | // podcast nest is the `chatbot` module's, exactly as it is over HTTP. |
| 747 | 748 | if !tenant.modules.contains(Module::Chatbot) { |
| 748 | 749 | return Err(( |
| 749 | 750 | "not_permitted", |
| 750 | - format!("the `{slug}` school has no `chatbot` module"), | |
| 751 | + format!("the `{school}` school has no `chatbot` module"), | |
| 751 | 752 | )); |
| 752 | 753 | } |
| 753 | 754 | let refusal = crate::ai::podcast::refusal; |
| 754 | - let root = api.files_dir(&slug); | |
| 755 | + let root = api.files_dir(&school); | |
| 755 | 756 | let (key, size) = crate::ai::podcast::ingest(&db, &root, request, body) |
| 756 | 757 | .await |
| 757 | 758 | .map_err(|r| refusal(&r))?; |
| @@ -790,7 +791,7 @@ async fn open_blob( | ||
| 790 | 791 | "the api is not serving yet — retry".to_string(), |
| 791 | 792 | ))?; |
| 792 | 793 | let tenant = api.school(&request.school).await?; |
| 793 | - let (slug, db) = (tenant.slug, tenant.db); | |
| 794 | + let (school, db) = (tenant.id, tenant.db); | |
| 794 | 795 | // This stream bypasses the router, so it also bypasses the route_layer the |
| 795 | 796 | // module gate is — the entitlement is checked here by hand instead. |
| 796 | 797 | // `chatbot` too: a school that did not buy the `ai` package sends no data |
| @@ -799,7 +800,7 @@ async fn open_blob( | ||
| 799 | 800 | if !tenant.modules.contains(module) { |
| 800 | 801 | return Err(( |
| 801 | 802 | "module_disabled", |
| 802 | - format!("the `{slug}` school has no `{module}` module"), | |
| 803 | + format!("the `{school}` school has no `{module}` module"), | |
| 803 | 804 | )); |
| 804 | 805 | } |
| 805 | 806 | } |
| @@ -839,7 +840,7 @@ async fn open_blob( | ||
| 839 | 840 | |
| 840 | 841 | // The row exists but its blob does not: server-side damage (a lost volume |
| 841 | 842 | // 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()); | |
| 843 | 844 | let handle = tokio::fs::File::open(&path).await.map_err(|e| { |
| 844 | 845 | ( |
| 845 | 846 | "unavailable", |
| @@ -955,7 +956,7 @@ async fn dispatch_api( | ||
| 955 | 956 | } = request; |
| 956 | 957 | |
| 957 | 958 | // 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 | |
| 959 | 960 | // anyone's data is read. |
| 960 | 961 | let tenant = api.school(&school).await?; |
| 961 | 962 | let db = tenant.db.clone(); |
| @@ -985,7 +986,7 @@ async fn dispatch_api( | ||
| 985 | 986 | // Carries the school's entitlements too, so the router's module gate |
| 986 | 987 | // refuses a disabled nest on this path exactly as it does over HTTP. |
| 987 | 988 | dispatched.extensions_mut().insert(TenantExt { |
| 988 | - slug: tenant.slug, | |
| 989 | + id: tenant.id, | |
| 989 | 990 | db, |
| 990 | 991 | modules: tenant.modules, |
| 991 | 992 | }); |
| @@ -1397,7 +1398,7 @@ mod tests { | ||
| 1397 | 1398 | refuse_before_dispatch, |
| 1398 | 1399 | }; |
| 1399 | 1400 | use crate::ai::protocol::read_frame; |
| 1400 | - use crate::tenant::DEMO_SLUG; | |
| 1401 | + use crate::tenant::DEMO_SCHOOL_ID; | |
| 1401 | 1402 | |
| 1402 | 1403 | /// An armed handle serving `router`. The database is never touched by these |
| 1403 | 1404 | /// reads (nobody is named, so the principal is synthetic), but the handle |
| @@ -1414,7 +1415,7 @@ mod tests { | ||
| 1414 | 1415 | fn read_of(path: &str) -> ApiRequest { |
| 1415 | 1416 | ApiRequest { |
| 1416 | 1417 | id: "trace-1".to_string(), |
| 1417 | - school: DEMO_SLUG.to_string(), | |
| 1418 | + school: DEMO_SCHOOL_ID.to_string(), | |
| 1418 | 1419 | path: path.to_string(), |
| 1419 | 1420 | query: None, |
| 1420 | 1421 | on_behalf_of: None, |
| @@ -1485,7 +1486,7 @@ mod tests { | ||
| 1485 | 1486 | // frame may precede it on the stream. |
| 1486 | 1487 | let big = ApiResponse::Ok { |
| 1487 | 1488 | id: "trace-1".to_string(), |
| 1488 | - school: DEMO_SLUG.to_string(), | |
| 1489 | + school: DEMO_SCHOOL_ID.to_string(), | |
| 1489 | 1490 | status: 200, |
| 1490 | 1491 | body: serde_json::Value::String("x".repeat(AI_MAX_FRAME_BYTES)), |
| 1491 | 1492 | }; |
src/constant.rsmodified+1 -7
| @@ -1,12 +1,6 @@ | ||
| 1 | 1 | //! Validation limits, in one place. |
| 2 | 2 | |
| 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. | |
| 10 | 4 | pub const MAX_SCHOOL_NAME_LEN: usize = 120; |
| 11 | 5 | |
| 12 | 6 | pub const MIN_USERNAME_LEN: usize = 3; |
src/database.rsmodified+6 -7
| @@ -29,7 +29,7 @@ use crate::domain::timestamp::Timestamp; | ||
| 29 | 29 | use crate::domain::user::{Password, Username}; |
| 30 | 30 | use crate::error::AppError; |
| 31 | 31 | 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}; | |
| 33 | 33 | |
| 34 | 34 | /// The shared database handle. |
| 35 | 35 | /// |
| @@ -101,7 +101,7 @@ pub async fn init(cfg: &Config) -> Result<Tenants, AppError> { | ||
| 101 | 101 | } |
| 102 | 102 | |
| 103 | 103 | /// 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}`). | |
| 105 | 105 | pub(crate) fn parse_base(cfg: &Config) -> Result<(PgConnectOptions, String), AppError> { |
| 106 | 106 | let opts: PgConnectOptions = cfg.database_url.parse().map_err(|err| { |
| 107 | 107 | AppError::Internal(format!( |
| @@ -754,7 +754,7 @@ impl Drop for TestLease { | ||
| 754 | 754 | |
| 755 | 755 | /// A complete test deployment: a fresh control database plus the demo school, |
| 756 | 756 | /// 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`]. | |
| 758 | 758 | /// |
| 759 | 759 | /// The databases die with the returned registry's last handle (see |
| 760 | 760 | /// [`TestDatabases`]); the janitor sweeps anything a crashed run left behind. |
| @@ -773,7 +773,7 @@ pub async fn init_test_tenants() -> Tenants { | ||
| 773 | 773 | .unwrap_or_else(|err| panic!("migrate the test control database {control_db}: {err}")); |
| 774 | 774 | |
| 775 | 775 | 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"); | |
| 777 | 777 | let school_db = school_db_name(&control_db, demo_id.uuid()); |
| 778 | 778 | create_database(&maintenance, &school_db, Some(&template)).await; |
| 779 | 779 | lease.track(&school_db); |
| @@ -785,11 +785,10 @@ pub async fn init_test_tenants() -> Tenants { | ||
| 785 | 785 | // without the per-school migration its `bring_up` runs, which the |
| 786 | 786 | // template clone has just replaced. |
| 787 | 787 | 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)", | |
| 790 | 790 | ) |
| 791 | 791 | .bind(demo_id.uuid()) |
| 792 | - .bind(DEMO_SLUG) | |
| 793 | 792 | .bind("Demo School") |
| 794 | 793 | .bind(SchoolStatus::Active) |
| 795 | 794 | .bind(Timestamp::now().as_millis()) |
src/db/insight.rsmodified+16 -15
| @@ -53,6 +53,7 @@ use crate::constant::{ | ||
| 53 | 53 | use crate::database::{Database, foreign_key_violation, tx_with_retry}; |
| 54 | 54 | use crate::domain::monotonic_id::next_uuid; |
| 55 | 55 | use crate::error::{AppError, ValidationError}; |
| 56 | +use crate::tenant::SchoolId; | |
| 56 | 57 | |
| 57 | 58 | // ---- the wire rows --------------------------------------------------------- |
| 58 | 59 | |
| @@ -308,21 +309,20 @@ pub struct TableVerdicts { | ||
| 308 | 309 | pub tables: BTreeMap<String, bool>, |
| 309 | 310 | } |
| 310 | 311 | |
| 311 | -/// The deployment's active schools, by slug. | |
| 312 | +/// The deployment's active schools, as hyphenated uuids. | |
| 312 | 313 | #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] |
| 313 | 314 | pub struct SchoolDirectory { |
| 314 | 315 | pub schools: Vec<String>, |
| 315 | 316 | } |
| 316 | 317 | |
| 317 | 318 | /// 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. | |
| 321 | 322 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ToSchema)] |
| 322 | 323 | pub struct ReportSchool { |
| 323 | - /// `school.id` — the surrogate key, not the slug: a slug may be renamed. | |
| 324 | + /// `school.id`, hyphenated. | |
| 324 | 325 | pub id: String, |
| 325 | - pub slug: String, | |
| 326 | 326 | pub name: String, |
| 327 | 327 | } |
| 328 | 328 | |
| @@ -855,31 +855,32 @@ pub async fn last_pending(db: &Database) -> Result<PendingList, AppError> { | ||
| 855 | 855 | }) |
| 856 | 856 | } |
| 857 | 857 | |
| 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. | |
| 861 | 861 | pub async fn active_schools(control: &Database) -> Result<SchoolDirectory, AppError> { |
| 862 | 862 | 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" | |
| 864 | 864 | ) |
| 865 | 865 | .fetch_all(control) |
| 866 | 866 | .await?; |
| 867 | - Ok(SchoolDirectory { schools }) | |
| 867 | + Ok(SchoolDirectory { | |
| 868 | + schools: schools.into_iter().map(|id| id.to_string()).collect(), | |
| 869 | + }) | |
| 868 | 870 | } |
| 869 | 871 | |
| 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 | |
| 871 | 873 | /// database does not hold — a resolved tenant always has one, so a caller |
| 872 | 874 | /// reads that as an internal fault, not as a refusal. |
| 873 | 875 | pub async fn school_identity( |
| 874 | 876 | control: &Database, |
| 875 | - slug: &str, | |
| 877 | + id: &SchoolId, | |
| 876 | 878 | ) -> 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()) | |
| 878 | 880 | .fetch_optional(control) |
| 879 | 881 | .await?; |
| 880 | 882 | Ok(row.map(|row| ReportSchool { |
| 881 | 883 | id: row.id.to_string(), |
| 882 | - slug: slug.to_string(), | |
| 883 | 884 | name: row.name, |
| 884 | 885 | })) |
| 885 | 886 | } |
src/db/person.rsmodified+26 -17
| @@ -11,7 +11,7 @@ use crate::domain::session::{SessionId, SessionToken}; | ||
| 11 | 11 | use crate::domain::timestamp::Timestamp; |
| 12 | 12 | use crate::domain::user::{PasswordHash, Username}; |
| 13 | 13 | use crate::error::AppError; |
| 14 | -use crate::tenant::{SchoolId, SchoolStatus, Slug}; | |
| 14 | +use crate::tenant::{SchoolId, SchoolStatus}; | |
| 15 | 15 | |
| 16 | 16 | /// The raw account insert behind [`crate::service::person::create_or_load`]. |
| 17 | 17 | /// 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 | ||
| 65 | 65 | Ok(person) |
| 66 | 66 | } |
| 67 | 67 | |
| 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 | |
| 69 | 69 | /// and status joined in. Suspended schools are part of the answer — the |
| 70 | 70 | /// caller decides what to offer. |
| 71 | 71 | pub async fn memberships(db: &Database, person: &PersonId) -> Result<Vec<Membership>, AppError> { |
| 72 | 72 | let rows = sqlx::query_as!( |
| 73 | 73 | Membership, |
| 74 | - r#"SELECT s.slug AS "slug: Slug", | |
| 74 | + r#"SELECT s.id AS "id: SchoolId", | |
| 75 | 75 | s.name, |
| 76 | 76 | s.status AS "status: SchoolStatus" |
| 77 | 77 | FROM person_school ps |
| 78 | 78 | JOIN school s ON s.id = ps.school |
| 79 | 79 | WHERE ps.person = $1 |
| 80 | - ORDER BY s.slug"#, | |
| 80 | + ORDER BY s.name"#, | |
| 81 | 81 | person.uuid() |
| 82 | 82 | ) |
| 83 | 83 | .fetch_all(db) |
| @@ -86,23 +86,23 @@ pub async fn memberships(db: &Database, person: &PersonId) -> Result<Vec<Members | ||
| 86 | 86 | } |
| 87 | 87 | |
| 88 | 88 | /// 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. | |
| 91 | 91 | pub async fn membership_of( |
| 92 | 92 | db: &Database, |
| 93 | 93 | person: &PersonId, |
| 94 | - slug: &Slug, | |
| 94 | + id: &SchoolId, | |
| 95 | 95 | ) -> Result<Option<Membership>, AppError> { |
| 96 | 96 | let row = sqlx::query_as!( |
| 97 | 97 | Membership, |
| 98 | - r#"SELECT s.slug AS "slug: Slug", | |
| 98 | + r#"SELECT s.id AS "id: SchoolId", | |
| 99 | 99 | s.name, |
| 100 | 100 | s.status AS "status: SchoolStatus" |
| 101 | 101 | FROM person_school ps |
| 102 | 102 | 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"#, | |
| 104 | 104 | person.uuid(), |
| 105 | - slug.as_str() | |
| 105 | + id.uuid() | |
| 106 | 106 | ) |
| 107 | 107 | .fetch_optional(db) |
| 108 | 108 | .await?; |
| @@ -110,17 +110,15 @@ pub async fn membership_of( | ||
| 110 | 110 | } |
| 111 | 111 | |
| 112 | 112 | /// 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> { | |
| 118 | 116 | sqlx::query!( |
| 119 | 117 | "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 | |
| 121 | 119 | ON CONFLICT DO NOTHING", |
| 122 | 120 | person.uuid(), |
| 123 | - slug.as_str(), | |
| 121 | + id.uuid(), | |
| 124 | 122 | Timestamp::now().as_millis() |
| 125 | 123 | ) |
| 126 | 124 | .execute(db) |
| @@ -128,6 +126,17 @@ pub async fn add_membership(db: &Database, person: &PersonId, slug: &Slug) -> Re | ||
| 128 | 126 | Ok(()) |
| 129 | 127 | } |
| 130 | 128 | |
| 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 | + | |
| 131 | 140 | /// Drop every membership pointing at a school — the control-plane half of |
| 132 | 141 | /// [`crate::tenant::Tenants::drop`], inside the transaction that also drops the |
| 133 | 142 | /// entitlements and the registry row, so `ON DELETE NO ACTION` never refuses |
src/domain/builder.rsmodified+1 -1
| @@ -3,7 +3,7 @@ | ||
| 3 | 3 | //! A builder creates, suspends and drops schools; it is **not** a user of any |
| 4 | 4 | //! school and holds no role there. The two principals are kept apart by |
| 5 | 5 | //! 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 | |
| 7 | 7 | //! neither extractor can be fed the other's cookie. |
| 8 | 8 | //! |
| 9 | 9 | //! 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; | ||
| 14 | 14 | use crate::domain::session::SessionToken; |
| 15 | 15 | use crate::domain::timestamp::Timestamp; |
| 16 | 16 | use crate::domain::user::{PasswordHash, Username}; |
| 17 | -use crate::tenant::{SchoolStatus, Slug}; | |
| 17 | +use crate::tenant::{SchoolId, SchoolStatus}; | |
| 18 | 18 | |
| 19 | 19 | /// Typed person row id (control database). A UUIDv7 minted by the |
| 20 | 20 | /// process-wide monotonic generator, so `id` order is mint order. |
| @@ -60,14 +60,14 @@ impl Person { | ||
| 60 | 60 | /// One school a person belongs to, joined off the control registry. |
| 61 | 61 | #[derive(Debug, Clone, sqlx::FromRow)] |
| 62 | 62 | pub struct Membership { |
| 63 | - pub(crate) slug: Slug, | |
| 63 | + pub(crate) id: SchoolId, | |
| 64 | 64 | pub(crate) name: String, |
| 65 | 65 | pub(crate) status: SchoolStatus, |
| 66 | 66 | } |
| 67 | 67 | |
| 68 | 68 | impl Membership { |
| 69 | - pub fn slug(&self) -> &Slug { | |
| 70 | - &self.slug | |
| 69 | + pub fn id(&self) -> SchoolId { | |
| 70 | + self.id | |
| 71 | 71 | } |
| 72 | 72 | |
| 73 | 73 | pub fn name(&self) -> &str { |
src/lib.rsmodified+4 -4
| @@ -52,10 +52,10 @@ use crate::web::module_gate::gate; | ||
| 52 | 52 | modifiers(&SecurityAddon), |
| 53 | 53 | tags( |
| 54 | 54 | (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."), | |
| 57 | 57 | (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"), | |
| 59 | 59 | (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"), |
| 60 | 60 | (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."), |
| 61 | 61 | (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 | ||
| 444 | 444 | } |
| 445 | 445 | } |
| 446 | 446 | |
| 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 | |
| 448 | 448 | /// the only caller-derived attribute, and it is only known after the handler's |
| 449 | 449 | /// extractor filled the slot (see [`SchoolSlot`]). |
| 450 | 450 | 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; | ||
| 9 | 9 | use crate::domain::person::{Membership, Person, PersonId, PersonSession}; |
| 10 | 10 | use crate::domain::user::{PasswordHash, Username}; |
| 11 | 11 | use crate::error::AppError; |
| 12 | -use crate::tenant::Slug; | |
| 12 | +use crate::tenant::SchoolId; | |
| 13 | 13 | |
| 14 | 14 | /// Create the person, or hand back the one already standing under |
| 15 | 15 | /// `username`. The incoming hash is stored only on the create path — an |
| @@ -42,9 +42,9 @@ pub async fn create_or_load( | ||
| 42 | 42 | pub async fn link_school( |
| 43 | 43 | control: &Database, |
| 44 | 44 | person: &PersonId, |
| 45 | - slug: &Slug, | |
| 45 | + id: &SchoolId, | |
| 46 | 46 | ) -> Result<(), AppError> { |
| 47 | - person::add_membership(control, person, slug).await | |
| 47 | + person::add_membership(control, person, id).await | |
| 48 | 48 | } |
| 49 | 49 | |
| 50 | 50 | pub async fn read(control: &Database, id: &PersonId) -> Result<Option<Person>, AppError> { |
| @@ -70,9 +70,9 @@ pub async fn memberships( | ||
| 70 | 70 | pub async fn membership_of( |
| 71 | 71 | control: &Database, |
| 72 | 72 | person: &PersonId, |
| 73 | - slug: &Slug, | |
| 73 | + id: &SchoolId, | |
| 74 | 74 | ) -> Result<Option<Membership>, AppError> { |
| 75 | - person::membership_of(control, person, slug).await | |
| 75 | + person::membership_of(control, person, id).await | |
| 76 | 76 | } |
| 77 | 77 | |
| 78 | 78 | 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 | ||
| 13 | 13 | use crate::domain::role::Role; |
| 14 | 14 | use crate::domain::user::{Password, StudentNumber, User, UserId, Username}; |
| 15 | 15 | use crate::error::AppError; |
| 16 | -use crate::tenant::{Slug, Tenants}; | |
| 16 | +use crate::tenant::{SchoolId, Tenants}; | |
| 17 | 17 | |
| 18 | 18 | /// Idempotent startup seed: guarantee an admin account with this username. |
| 19 | 19 | /// Missing → created directly with [`Role::Admin`]. Already an admin → |
| @@ -23,11 +23,11 @@ use crate::tenant::{Slug, Tenants}; | ||
| 23 | 23 | /// be a privilege escalation, so that conflict is resolved out-of-band. |
| 24 | 24 | pub async fn ensure_admin( |
| 25 | 25 | tenants: &Tenants, |
| 26 | - slug: &Slug, | |
| 26 | + id: &SchoolId, | |
| 27 | 27 | username: Username, |
| 28 | 28 | password: Password, |
| 29 | 29 | ) -> Result<(), AppError> { |
| 30 | - let db = tenants.get(slug).await?; | |
| 30 | + let db = tenants.get(id).await?; | |
| 31 | 31 | // The person half runs first, so the school row can carry the person id |
| 32 | 32 | // it is the join key to. Login reads the control-plane credential, so the |
| 33 | 33 | // seeded admin needs their `person` row and the membership too. Both |
| @@ -40,7 +40,7 @@ pub async fn ensure_admin( | ||
| 40 | 40 | let person = |
| 41 | 41 | crate::service::person::create_or_load(tenants.control(), username.clone(), password_hash) |
| 42 | 42 | .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?; | |
| 44 | 44 | match user::find_by_username(&db, username.as_str()).await? { |
| 45 | 45 | Some(user) if user.role == Role::Admin => {} |
| 46 | 46 | Some(_) => { |
src/state.rsmodified+28 -28
| @@ -7,7 +7,7 @@ use tokio::sync::broadcast; | ||
| 7 | 7 | use crate::ai::AiBridge; |
| 8 | 8 | use crate::database::Database; |
| 9 | 9 | use crate::rate_limit::{RateLimitConfig, UserRateLimiter}; |
| 10 | -use crate::tenant::{Slug, Tenants}; | |
| 10 | +use crate::tenant::{SchoolId, Tenants}; | |
| 11 | 11 | |
| 12 | 12 | /// Shared application state handed to every handler. |
| 13 | 13 | #[derive(Clone)] |
| @@ -55,16 +55,16 @@ pub struct AppState { | ||
| 55 | 55 | pub metrics: crate::telemetry::Metrics, |
| 56 | 56 | } |
| 57 | 57 | |
| 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 | |
| 59 | 59 | /// school, but record keys are only unique *within* a database, so an |
| 60 | 60 | /// unscoped key would put two schools' identical attempts (or boards) in the |
| 61 | 61 | /// 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}") | |
| 68 | 68 | } |
| 69 | 69 | |
| 70 | 70 | /// 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>>>); | ||
| 82 | 82 | |
| 83 | 83 | impl ExamPresence { |
| 84 | 84 | /// 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) { | |
| 86 | 86 | 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; | |
| 88 | 88 | } |
| 89 | 89 | |
| 90 | 90 | /// Count one socket out of `attempt`'s room; `true` when it was the last |
| 91 | 91 | /// 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); | |
| 94 | 94 | let mut rooms = self.0.lock().expect("exam presence lock"); |
| 95 | 95 | match rooms.get_mut(attempt) { |
| 96 | 96 | Some(count) if *count > 1 => { |
| @@ -130,10 +130,10 @@ pub struct BoardHub(Arc<Mutex<BoardRooms>>); | ||
| 130 | 130 | impl BoardHub { |
| 131 | 131 | /// Count one socket into `board` and hand back its stream of other |
| 132 | 132 | /// 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> { | |
| 134 | 134 | let mut boards = self.0.lock().expect("board hub lock"); |
| 135 | 135 | let room = boards |
| 136 | - .entry(scoped_key(slug, board)) | |
| 136 | + .entry(scoped_key(id, board)) | |
| 137 | 137 | .or_insert_with(|| (broadcast::channel(crate::constant::BOARD_HUB_CAPACITY).0, 0)); |
| 138 | 138 | room.1 += 1; |
| 139 | 139 | room.0.subscribe() |
| @@ -141,11 +141,11 @@ impl BoardHub { | ||
| 141 | 141 | |
| 142 | 142 | /// Push `frame` to every socket currently subscribed to `board`. A send |
| 143 | 143 | /// 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) { | |
| 145 | 145 | let sender = { |
| 146 | 146 | let boards = self.0.lock().expect("board hub lock"); |
| 147 | 147 | boards |
| 148 | - .get(&scoped_key(slug, board)) | |
| 148 | + .get(&scoped_key(id, board)) | |
| 149 | 149 | .map(|room| room.0.clone()) |
| 150 | 150 | }; |
| 151 | 151 | if let Some(sender) = sender { |
| @@ -154,8 +154,8 @@ impl BoardHub { | ||
| 154 | 154 | } |
| 155 | 155 | |
| 156 | 156 | /// 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); | |
| 159 | 159 | let mut boards = self.0.lock().expect("board hub lock"); |
| 160 | 160 | match boards.get_mut(board) { |
| 161 | 161 | Some(room) if room.1 > 1 => room.1 -= 1, |
| @@ -172,13 +172,13 @@ impl BoardHub { | ||
| 172 | 172 | mod tests { |
| 173 | 173 | use super::*; |
| 174 | 174 | |
| 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) | |
| 177 | 177 | } |
| 178 | 178 | |
| 179 | 179 | #[tokio::test] |
| 180 | 180 | 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"); | |
| 182 | 182 | let hub = BoardHub::default(); |
| 183 | 183 | let mut alice = hub.subscribe(&a, "board-a"); |
| 184 | 184 | let mut bob = hub.subscribe(&a, "board-a"); |
| @@ -188,11 +188,11 @@ mod tests { | ||
| 188 | 188 | |
| 189 | 189 | // Boards are independent, and publishing into an empty one is a no-op. |
| 190 | 190 | 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"))); | |
| 192 | 192 | |
| 193 | 193 | hub.leave(&a, "board-a"); |
| 194 | 194 | assert!( |
| 195 | - hub.0.lock().unwrap().contains_key("alpha:board-a"), | |
| 195 | + hub.0.lock().unwrap().contains_key(&scoped_key(&a, "board-a")), | |
| 196 | 196 | "one socket of two out keeps the room" |
| 197 | 197 | ); |
| 198 | 198 | hub.leave(&a, "board-a"); |
| @@ -206,7 +206,7 @@ mod tests { | ||
| 206 | 206 | /// same board key. One process serves both — nothing may cross. |
| 207 | 207 | #[tokio::test] |
| 208 | 208 | 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")); | |
| 210 | 210 | let hub = BoardHub::default(); |
| 211 | 211 | let mut in_a = hub.subscribe(&a, "board-1"); |
| 212 | 212 | let mut in_b = hub.subscribe(&b, "board-1"); |
| @@ -225,13 +225,13 @@ mod tests { | ||
| 225 | 225 | // beta's room standing. |
| 226 | 226 | hub.leave(&a, "board-1"); |
| 227 | 227 | 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"))); | |
| 230 | 230 | } |
| 231 | 231 | |
| 232 | 232 | #[tokio::test] |
| 233 | 233 | 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"); | |
| 235 | 235 | let presence = ExamPresence::default(); |
| 236 | 236 | presence.enter(&a, "attempt-a"); |
| 237 | 237 | presence.enter(&a, "attempt-a"); |
| @@ -254,7 +254,7 @@ mod tests { | ||
| 254 | 254 | /// its walk-out would go unstamped. |
| 255 | 255 | #[tokio::test] |
| 256 | 256 | 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")); | |
| 258 | 258 | let presence = ExamPresence::default(); |
| 259 | 259 | presence.enter(&a, "attempt-1"); |
| 260 | 260 | presence.enter(&b, "attempt-1"); |
src/telemetry.rsmodified+6 -6
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | //! identity, no client address, no URL path (which holds record ids), no |
| 7 | 7 | //! request or response bodies, and no headers or cookies. What may leave: the |
| 8 | 8 | //! 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 | |
| 10 | 10 | //! (an exam room, a board) when an event is about that resource — never a |
| 11 | 11 | //! user, session or attempt id, which name a person. Every attribute or event |
| 12 | 12 | //! field added anywhere in this crate must fit that list — see the guard test |
| @@ -255,7 +255,7 @@ impl Metrics { | ||
| 255 | 255 | ); |
| 256 | 256 | } |
| 257 | 257 | |
| 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 | |
| 259 | 259 | /// only — never a user, never a path. |
| 260 | 260 | pub fn request_finished( |
| 261 | 261 | &self, |
| @@ -291,11 +291,11 @@ impl Default for Metrics { | ||
| 291 | 291 | /// A slot on the request for the school it turned out to belong to. |
| 292 | 292 | /// |
| 293 | 293 | /// 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 | |
| 295 | 295 | /// [`crate::web::tenant_state::resolve_tenant`] reads the session cookie, deep |
| 296 | 296 | /// inside the handler, where the request has already been moved. So the |
| 297 | 297 | /// 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 | |
| 299 | 299 | /// the only thing that ever goes in here. |
| 300 | 300 | #[derive(Clone, Default)] |
| 301 | 301 | pub struct SchoolSlot(Arc<OnceLock<String>>); |
| @@ -303,8 +303,8 @@ pub struct SchoolSlot(Arc<OnceLock<String>>); | ||
| 303 | 303 | impl SchoolSlot { |
| 304 | 304 | /// Name the school for this request. Later calls are ignored — a request |
| 305 | 305 | /// 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()); | |
| 308 | 308 | } |
| 309 | 309 | |
| 310 | 310 | pub fn get(&self) -> Option<&str> { |
src/tenant.rsmodified+137 -162
| @@ -22,12 +22,11 @@ use std::sync::{Arc, RwLock}; | ||
| 22 | 22 | use serde::Serialize; |
| 23 | 23 | use sqlx::postgres::PgConnectOptions; |
| 24 | 24 | |
| 25 | -use crate::constant::{MAX_SLUG_LEN, MIN_SLUG_LEN}; | |
| 26 | 25 | use uuid::Uuid; |
| 27 | 26 | |
| 28 | 27 | use crate::database::{ |
| 29 | 28 | Database, applied_versions, create_database_sql, ensure_database, migrate_school, |
| 30 | - pending_school_migrations, school_pool, unique_violation, | |
| 29 | + pending_school_migrations, school_pool, | |
| 31 | 30 | }; |
| 32 | 31 | use crate::domain::monotonic_id::next_uuid; |
| 33 | 32 | use crate::domain::timestamp::Timestamp; |
| @@ -35,77 +34,22 @@ use crate::error::{AppError, ValidationError}; | ||
| 35 | 34 | use crate::module::ModuleSet; |
| 36 | 35 | use crate::telemetry::Metrics; |
| 37 | 36 | |
| 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"; | |
| 74 | 42 | |
| 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"; | |
| 102 | 46 | |
| 103 | 47 | /// A school database's name: `{control_db}_school_{uuid hex}` — the uuid's |
| 104 | 48 | /// lowercase hex without dashes (the contract's example: |
| 105 | 49 | /// `019732e3-7b00-7000-8000-00000000dead` → |
| 106 | 50 | /// `…_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 | |
| 109 | 53 | /// the name's tail on deployments with a long control-database name — uuid |
| 110 | 54 | /// v7's random tail still separates schools far past any realistic registry |
| 111 | 55 | /// size, and creator and dialler truncate identically. |
| @@ -157,10 +101,12 @@ impl SchoolStatus { | ||
| 157 | 101 | } |
| 158 | 102 | } |
| 159 | 103 | |
| 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)] | |
| 164 | 110 | pub struct SchoolId(Uuid); |
| 165 | 111 | |
| 166 | 112 | impl SchoolId { |
| @@ -179,12 +125,61 @@ impl SchoolId { | ||
| 179 | 125 | pub fn uuid(self) -> Uuid { |
| 180 | 126 | self.0 |
| 181 | 127 | } |
| 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 | + } | |
| 182 | 178 | } |
| 183 | 179 | |
| 184 | 180 | #[derive(Debug, Clone, sqlx::FromRow)] |
| 185 | 181 | pub struct School { |
| 186 | 182 | id: Uuid, |
| 187 | - slug: Slug, | |
| 188 | 183 | name: String, |
| 189 | 184 | status: SchoolStatus, |
| 190 | 185 | created_at: Timestamp, |
| @@ -198,16 +193,12 @@ pub struct School { | ||
| 198 | 193 | } |
| 199 | 194 | |
| 200 | 195 | 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. | |
| 203 | 198 | pub fn get_id(&self) -> SchoolId { |
| 204 | 199 | SchoolId(self.id) |
| 205 | 200 | } |
| 206 | 201 | |
| 207 | - pub fn slug(&self) -> &Slug { | |
| 208 | - &self.slug | |
| 209 | - } | |
| 210 | - | |
| 211 | 202 | pub fn name(&self) -> &str { |
| 212 | 203 | &self.name |
| 213 | 204 | } |
| @@ -230,22 +221,22 @@ impl School { | ||
| 230 | 221 | Ok(module) => set.insert(module), |
| 231 | 222 | Err(_) => tracing::warn!( |
| 232 | 223 | "school {} has an unknown module `{name}` — ignoring it", |
| 233 | - self.slug | |
| 224 | + self.id | |
| 234 | 225 | ), |
| 235 | 226 | } |
| 236 | 227 | } |
| 237 | 228 | set |
| 238 | 229 | } |
| 239 | 230 | |
| 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> { | |
| 241 | 232 | 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, | |
| 243 | 234 | COALESCE(array_agg(sm.module) FILTER (WHERE sm.module IS NOT NULL), '{}') AS modules |
| 244 | 235 | FROM school s LEFT JOIN school_module sm ON sm.school = s.id |
| 245 | - WHERE s.slug = $1 | |
| 236 | + WHERE s.id = $1 | |
| 246 | 237 | GROUP BY s.id", |
| 247 | 238 | ) |
| 248 | - .bind(slug.as_str()) | |
| 239 | + .bind(id.uuid()) | |
| 249 | 240 | .fetch_optional(control) |
| 250 | 241 | .await |
| 251 | 242 | .map_err(Into::into) |
| @@ -260,11 +251,11 @@ impl School { | ||
| 260 | 251 | control: &Database, |
| 261 | 252 | ) -> Result<(Vec<School>, i64), AppError> { |
| 262 | 253 | 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, | |
| 264 | 255 | COALESCE(array_agg(sm.module) FILTER (WHERE sm.module IS NOT NULL), '{}') AS modules |
| 265 | 256 | FROM school s LEFT JOIN school_module sm ON sm.school = s.id |
| 266 | 257 | GROUP BY s.id |
| 267 | - ORDER BY s.created_at DESC, s.slug DESC | |
| 258 | + ORDER BY s.created_at DESC, s.id DESC | |
| 268 | 259 | LIMIT $1 OFFSET $2", |
| 269 | 260 | ) |
| 270 | 261 | .bind(limit) |
| @@ -277,10 +268,8 @@ impl School { | ||
| 277 | 268 | Ok((rows, total)) |
| 278 | 269 | } |
| 279 | 270 | |
| 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. | |
| 284 | 273 | /// |
| 285 | 274 | /// Both fields land in **one** statement, so a patch that carries both can |
| 286 | 275 | /// never leave half of itself behind, and an omitted field is kept by |
| @@ -288,7 +277,7 @@ impl School { | ||
| 288 | 277 | /// read, so a concurrent patch of the other field cannot be reverted |
| 289 | 278 | /// either. |
| 290 | 279 | pub async fn update( |
| 291 | - slug: &Slug, | |
| 280 | + id: &SchoolId, | |
| 292 | 281 | name: Option<&str>, |
| 293 | 282 | status: Option<SchoolStatus>, |
| 294 | 283 | control: &Database, |
| @@ -297,18 +286,18 @@ impl School { | ||
| 297 | 286 | "WITH updated AS ( |
| 298 | 287 | UPDATE school |
| 299 | 288 | 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 | |
| 302 | 291 | ) |
| 303 | - SELECT u.id, u.slug, u.name, u.status, u.created_at, | |
| 292 | + SELECT u.id, u.name, u.status, u.created_at, | |
| 304 | 293 | COALESCE(array_agg(sm.module) FILTER (WHERE sm.module IS NOT NULL), '{}') AS modules |
| 305 | 294 | FROM updated u |
| 306 | 295 | 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", | |
| 308 | 297 | ) |
| 309 | 298 | .bind(name) |
| 310 | 299 | .bind(status) |
| 311 | - .bind(slug.as_str()) | |
| 300 | + .bind(id.uuid()) | |
| 312 | 301 | .fetch_optional(control) |
| 313 | 302 | .await? |
| 314 | 303 | .ok_or(AppError::NotFound) |
| @@ -320,8 +309,8 @@ impl School { | ||
| 320 | 309 | pub struct Tenants { |
| 321 | 310 | control: Database, |
| 322 | 311 | /// 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. | |
| 325 | 314 | cache: Arc<RwLock<HashMap<String, Database>>>, |
| 326 | 315 | /// Dial options for the Postgres server the control pool came from — a |
| 327 | 316 | /// school pool is the same dial with only the database swapped. |
| @@ -342,7 +331,7 @@ pub struct Tenants { | ||
| 342 | 331 | /// [`crate::web::CurrentUser`], which is most of them) reads the registry once. |
| 343 | 332 | #[derive(Clone)] |
| 344 | 333 | pub struct ResolvedTenant { |
| 345 | - pub slug: Slug, | |
| 334 | + pub id: SchoolId, | |
| 346 | 335 | pub db: Database, |
| 347 | 336 | pub modules: ModuleSet, |
| 348 | 337 | } |
| @@ -409,15 +398,15 @@ impl Tenants { | ||
| 409 | 398 | /// extra control-db round trip per request; cache the row with a short TTL |
| 410 | 399 | /// if it ever shows up in a profile — the eviction in [`Tenants::set_status`] |
| 411 | 400 | /// 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) | |
| 414 | 403 | } |
| 415 | 404 | |
| 416 | 405 | /// [`Tenants::get`] plus what that one registry read already knew: the |
| 417 | 406 | /// school's module entitlements. Same verdicts, same single read — a |
| 418 | 407 | /// 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? { | |
| 421 | 410 | None => Err(AppError::Unauthorized), |
| 422 | 411 | Some(school) if school.status == SchoolStatus::Suspended => { |
| 423 | 412 | self.evict(school.get_id()).await; |
| @@ -428,7 +417,7 @@ impl Tenants { | ||
| 428 | 417 | Err(AppError::Forbidden("school is still being provisioned")) |
| 429 | 418 | } |
| 430 | 419 | Some(school) => Ok(ResolvedTenant { |
| 431 | - slug: slug.clone(), | |
| 420 | + id: school.get_id(), | |
| 432 | 421 | db: self.handle(school.get_id()).await?, |
| 433 | 422 | modules: school.modules(), |
| 434 | 423 | }), |
| @@ -441,8 +430,11 @@ impl Tenants { | ||
| 441 | 430 | /// still being provisioned is a `409`: the two routes that come through |
| 442 | 431 | /// here (`enter`, `reset_admin_password`) need its database to answer, and a |
| 443 | 432 | /// 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) | |
| 446 | 438 | .await? |
| 447 | 439 | .ok_or(AppError::NotFound)?; |
| 448 | 440 | if school.status == SchoolStatus::Provisioning { |
| @@ -459,7 +451,6 @@ impl Tenants { | ||
| 459 | 451 | pub async fn create( |
| 460 | 452 | &self, |
| 461 | 453 | id: SchoolId, |
| 462 | - slug: &Slug, | |
| 463 | 454 | name: &str, |
| 464 | 455 | modules: ModuleSet, |
| 465 | 456 | ) -> Result<Database, AppError> { |
| @@ -471,24 +462,19 @@ impl Tenants { | ||
| 471 | 462 | // school row never stands without the modules its creation asked for. |
| 472 | 463 | let mut tx = self.control.begin().await?; |
| 473 | 464 | 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)", | |
| 476 | 467 | ) |
| 477 | 468 | .bind(id.uuid()) |
| 478 | - .bind(slug.as_str()) | |
| 479 | 469 | .bind(name) |
| 480 | 470 | .bind(SchoolStatus::Provisioning) |
| 481 | 471 | .bind(Timestamp::now().as_millis()) |
| 482 | 472 | .execute(&mut *tx) |
| 483 | 473 | .await; |
| 484 | 474 | 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. | |
| 492 | 478 | return Err(err.into()); |
| 493 | 479 | } |
| 494 | 480 | for name in modules.names() { |
| @@ -500,9 +486,8 @@ impl Tenants { | ||
| 500 | 486 | } |
| 501 | 487 | tx.commit().await?; |
| 502 | 488 | |
| 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 | |
| 506 | 491 | // created before the failure is not a wedge: the adopt branch in |
| 507 | 492 | // [`Self::bring_up`] picks it up, migrations being idempotent.) |
| 508 | 493 | let db = match self.bring_up(id).await { |
| @@ -516,8 +501,7 @@ impl Tenants { | ||
| 516 | 501 | .bind(id.uuid()) |
| 517 | 502 | .execute(&self.control) |
| 518 | 503 | .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 | |
| 521 | 505 | // expensive half and whose name nothing will ever reuse (the id |
| 522 | 506 | // is minted per create, never replayed). Best-effort, but not |
| 523 | 507 | // silent: a failure here is a half-provisioned database nobody |
| @@ -583,8 +567,8 @@ impl Tenants { | ||
| 583 | 567 | /// [`School::update`], which is where the write itself lives. Suspending |
| 584 | 568 | /// also drops the cached pool, so nothing that already resolved keeps |
| 585 | 569 | /// 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?; | |
| 588 | 572 | if status == SchoolStatus::Suspended { |
| 589 | 573 | self.evict(school.get_id()).await; |
| 590 | 574 | } |
| @@ -595,26 +579,26 @@ impl Tenants { | ||
| 595 | 579 | /// eviction: entitlements are read off the registry row on every request, |
| 596 | 580 | /// so a change takes effect on the next call and no cached pool carries a |
| 597 | 581 | /// 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> { | |
| 599 | 583 | modules.validate()?; |
| 600 | 584 | // The swap is parent + children in one transaction: take the registry |
| 601 | 585 | // row's lock so racing sellers serialize, then replace the whole shelf. |
| 602 | 586 | 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()) | |
| 606 | 590 | .fetch_optional(&mut *tx) |
| 607 | 591 | .await?; |
| 608 | - let Some(id) = id else { | |
| 592 | + let Some(row_id) = locked else { | |
| 609 | 593 | return Err(AppError::NotFound); |
| 610 | 594 | }; |
| 611 | 595 | sqlx::query("DELETE FROM school_module WHERE school = $1") |
| 612 | - .bind(id) | |
| 596 | + .bind(row_id) | |
| 613 | 597 | .execute(&mut *tx) |
| 614 | 598 | .await?; |
| 615 | 599 | for name in modules.names() { |
| 616 | 600 | sqlx::query("INSERT INTO school_module (school, module) VALUES ($1, $2)") |
| 617 | - .bind(id) | |
| 601 | + .bind(row_id) | |
| 618 | 602 | .bind(name) |
| 619 | 603 | .execute(&mut *tx) |
| 620 | 604 | .await?; |
| @@ -626,11 +610,10 @@ impl Tenants { | ||
| 626 | 610 | /// Delete a school outright: its data, then its registry row, then its |
| 627 | 611 | /// pool. Irreversible on purpose — there is no soft-delete state, that is |
| 628 | 612 | /// 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 { | |
| 634 | 617 | return Ok(()); |
| 635 | 618 | }; |
| 636 | 619 | let id = school.get_id(); |
| @@ -731,15 +714,15 @@ impl Tenants { | ||
| 731 | 714 | /// `POST /podcast/jobs` for exactly this reason. |
| 732 | 715 | /// |
| 733 | 716 | /// 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 | |
| 735 | 718 | /// exactly as it stood — no registry row and no status is written here, so |
| 736 | 719 | /// a failed school stays as usable (or unusable) as it was before the |
| 737 | 720 | /// sweep, and the next boot retries it. sqlx's tracking table is what |
| 738 | 721 | /// makes the retry safe: a migration that died mid-flight is re-run, not |
| 739 | 722 | /// half-believed. |
| 740 | 723 | 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") | |
| 743 | 726 | .fetch_all(&self.control) |
| 744 | 727 | .await |
| 745 | 728 | { |
| @@ -755,21 +738,19 @@ impl Tenants { | ||
| 755 | 738 | }; |
| 756 | 739 | let total = rows.len(); |
| 757 | 740 | let mut migrated = 0usize; |
| 758 | - for (id, slug) in rows { | |
| 741 | + for (id,) in rows { | |
| 759 | 742 | let id = SchoolId(id); |
| 760 | 743 | match self.sweep_school(id).await { |
| 761 | 744 | Ok(pending) if pending > 0 => { |
| 762 | 745 | migrated += 1; |
| 763 | 746 | tracing::info!( |
| 764 | - school = %id.uuid(), | |
| 765 | - slug = %slug, | |
| 747 | + school = %id, | |
| 766 | 748 | "school schema sweep applied {pending} migration(s) to a school behind the head" |
| 767 | 749 | ); |
| 768 | 750 | } |
| 769 | 751 | Ok(_) => {} |
| 770 | 752 | Err(err) => tracing::error!( |
| 771 | - school = %id.uuid(), | |
| 772 | - slug = %slug, | |
| 753 | + school = %id, | |
| 773 | 754 | "school schema sweep failed — this school is left as it was and the next boot \ |
| 774 | 755 | retries it: {err}" |
| 775 | 756 | ), |
| @@ -865,33 +846,27 @@ mod tests { | ||
| 865 | 846 | use super::*; |
| 866 | 847 | |
| 867 | 848 | #[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); | |
| 874 | 853 | for bad in [ |
| 854 | + "019732e37b007000800000000000dead", | |
| 855 | + "urn:uuid:019732e3-7b00-7000-8000-00000000dead", | |
| 856 | + "{019732e3-7b00-7000-8000-00000000dead}", | |
| 857 | + "demo", | |
| 875 | 858 | "builder", |
| 876 | - "control", | |
| 877 | - "Demo", | |
| 878 | - "..", | |
| 879 | 859 | "", |
| 880 | - "x", | |
| 881 | - "-lead", | |
| 882 | - "has_underscore", | |
| 883 | - "has.dot", | |
| 884 | - &"x".repeat(33), | |
| 885 | 860 | ] { |
| 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"); | |
| 887 | 862 | } |
| 888 | 863 | } |
| 889 | 864 | |
| 890 | 865 | /// The database-per-school model lives or dies by this mapping: two |
| 891 | 866 | /// schools sharing a database name would share every row in it. The name |
| 892 | 867 | /// 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. | |
| 895 | 870 | #[test] |
| 896 | 871 | fn school_db_names_are_injective() { |
| 897 | 872 | let control = "hezarfen_control"; |
| @@ -901,8 +876,8 @@ mod tests { | ||
| 901 | 876 | school_db_name(control, id), |
| 902 | 877 | "hezarfen_control_school_019732e37b007000800000000000dead" |
| 903 | 878 | ); |
| 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. | |
| 906 | 881 | let other = Uuid::try_parse("019732e3-7b00-7000-8000-00000000beef").unwrap(); |
| 907 | 882 | assert_ne!( |
| 908 | 883 | school_db_name(control, id), |
src/web/auth.rsmodified+50 -27
| @@ -16,7 +16,7 @@ use crate::error::{AppError, ErrorResponse, ValidationError}; | ||
| 16 | 16 | use crate::rate_limit::{RateLimitConfig, RateLimiter}; |
| 17 | 17 | use crate::service; |
| 18 | 18 | use crate::state::AppState; |
| 19 | -use crate::tenant::Slug; | |
| 19 | +use crate::tenant::SchoolId; | |
| 20 | 20 | |
| 21 | 21 | use super::dto::Role; |
| 22 | 22 | use super::tenant_state::split_cookie; |
| @@ -40,6 +40,7 @@ pub fn routes(state: &AppState) -> OpenApiRouter<AppState> { | ||
| 40 | 40 | let limiter = limiter.clone(); |
| 41 | 41 | async move { limiter.enforce(req, next).await } |
| 42 | 42 | })) |
| 43 | + .routes(routes!(list_schools)) | |
| 43 | 44 | .routes(routes!(select_school)) |
| 44 | 45 | .routes(routes!(logout)) |
| 45 | 46 | .routes(routes!(me)) |
| @@ -51,9 +52,9 @@ pub fn routes(state: &AppState) -> OpenApiRouter<AppState> { | ||
| 51 | 52 | /// `school` to login is merely ignored, not broken. |
| 52 | 53 | #[derive(Deserialize, ToSchema)] |
| 53 | 54 | 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")] | |
| 57 | 58 | school: String, |
| 58 | 59 | #[schema(example = "ada", min_length = 3, max_length = 32)] |
| 59 | 60 | username: String, |
| @@ -75,15 +76,15 @@ struct LoginCredentials { | ||
| 75 | 76 | /// One school offered to a multi-school person. |
| 76 | 77 | #[derive(Serialize, ToSchema)] |
| 77 | 78 | struct SchoolChoice { |
| 78 | - #[schema(example = "demo")] | |
| 79 | - slug: String, | |
| 79 | + #[schema(example = "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d")] | |
| 80 | + id: String, | |
| 80 | 81 | #[schema(example = "Demo")] |
| 81 | 82 | name: String, |
| 82 | 83 | } |
| 83 | 84 | |
| 84 | 85 | /// What `POST /auth/login` answers when the person belongs to more than one |
| 85 | 86 | /// 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 | |
| 87 | 88 | /// order and omits suspended schools. |
| 88 | 89 | #[derive(Serialize, ToSchema)] |
| 89 | 90 | struct SchoolChoiceResponse { |
| @@ -93,7 +94,7 @@ struct SchoolChoiceResponse { | ||
| 93 | 94 | } |
| 94 | 95 | |
| 95 | 96 | /// 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 | |
| 97 | 98 | /// [`SchoolChoiceResponse`] and a `person.<token>` cookie). Disjoint by the |
| 98 | 99 | /// `id` field, so an untagged `oneOf` is unambiguous on the wire. |
| 99 | 100 | #[derive(Serialize, ToSchema)] |
| @@ -106,7 +107,7 @@ enum LoginResponse { | ||
| 106 | 107 | /// What `POST /auth/school` takes: which of the person's memberships to bind. |
| 107 | 108 | #[derive(Deserialize, ToSchema)] |
| 108 | 109 | struct SelectSchool { |
| 109 | - #[schema(example = "demo", min_length = 2, max_length = 32)] | |
| 110 | + #[schema(example = "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d")] | |
| 110 | 111 | school: String, |
| 111 | 112 | } |
| 112 | 113 | |
| @@ -123,6 +124,28 @@ struct RegisterResponse { | ||
| 123 | 124 | role: Role, |
| 124 | 125 | } |
| 125 | 126 | |
| 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 | + | |
| 126 | 149 | /// Register a new user account, or attach an existing person to one more |
| 127 | 150 | /// school: `{school, username, password}` in, `{username, role}` back (no |
| 128 | 151 | /// `id`; new accounts are `student`). Always `201` — see below. |
| @@ -162,7 +185,7 @@ async fn register( | ||
| 162 | 185 | // one that is suspended, must not reach the (expensive) hashing path — and |
| 163 | 186 | // an unknown school answers `401` here for the same anti-enumeration reason |
| 164 | 187 | // 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)?; | |
| 166 | 189 | let db = st.tenants.get(&school).await?; |
| 167 | 190 | let username = Username::try_new(&req.username)?; |
| 168 | 191 | // Registration-level policy, not a `Username` invariant: these names read |
| @@ -216,7 +239,7 @@ async fn register( | ||
| 216 | 239 | |
| 217 | 240 | /// Log in with username + password — no school. Sets a `session` cookie on |
| 218 | 241 | /// 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 | |
| 220 | 243 | /// single-school clients), several answer a [`SchoolChoiceResponse`] with a |
| 221 | 244 | /// `person.<token>` cookie that `POST /auth/school` binds. |
| 222 | 245 | #[utoipa::path( |
| @@ -225,7 +248,7 @@ async fn register( | ||
| 225 | 248 | tag = "auth", |
| 226 | 249 | request_body = LoginCredentials, |
| 227 | 250 | 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), | |
| 229 | 252 | (status = 401, description = "Bad credentials — unknown username, wrong password, or no school membership left to enter, all deliberately indistinguishable", body = ErrorResponse), |
| 230 | 253 | (status = 403, description = "Every school the person belongs to is suspended", body = ErrorResponse), |
| 231 | 254 | (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), |
| @@ -275,7 +298,7 @@ async fn login( | ||
| 275 | 298 | // including this one. |
| 276 | 299 | [] => Err(AppError::Forbidden("school is suspended")), |
| 277 | 300 | [only] => { |
| 278 | - let db = st.tenants.get(only.slug()).await?; | |
| 301 | + let db = st.tenants.get(&only.id()).await?; | |
| 279 | 302 | // The school-side row the session binds to. A membership without |
| 280 | 303 | // its `app_user` (a torn create) refuses like a bad credential |
| 281 | 304 | // rather than confirm anything. |
| @@ -287,11 +310,11 @@ async fn login( | ||
| 287 | 310 | // The caller is genuine; opportunistically drop expired session rows. |
| 288 | 311 | let _ = service::session::purge_expired(&db).await; |
| 289 | 312 | 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 | |
| 291 | 314 | // request finds its database without a second lookup path that |
| 292 | 315 | // could disagree. |
| 293 | 316 | let cookie = session_cookie( |
| 294 | - format!("{}.{}", only.slug(), session.token().as_str()), | |
| 317 | + format!("{}.{}", only.id(), session.token().as_str()), | |
| 295 | 318 | st.cookie_secure, |
| 296 | 319 | ); |
| 297 | 320 | Ok(( |
| @@ -302,7 +325,7 @@ async fn login( | ||
| 302 | 325 | many => { |
| 303 | 326 | // Not entering any school yet: the `person.<token>` cookie is the |
| 304 | 327 | // 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. | |
| 306 | 329 | let session = service::person::create_session(&st.db, person.get_id()).await?; |
| 307 | 330 | let cookie = session_cookie( |
| 308 | 331 | format!("{PERSON_COOKIE_PREFIX}.{}", session.token().as_str()), |
| @@ -311,7 +334,7 @@ async fn login( | ||
| 311 | 334 | let schools = many |
| 312 | 335 | .iter() |
| 313 | 336 | .map(|m| SchoolChoice { |
| 314 | - slug: m.slug().as_str().to_string(), | |
| 337 | + id: m.id().as_str(), | |
| 315 | 338 | name: m.name().to_string(), |
| 316 | 339 | }) |
| 317 | 340 | .collect(); |
| @@ -327,7 +350,7 @@ async fn login( | ||
| 327 | 350 | } |
| 328 | 351 | |
| 329 | 352 | /// 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 | |
| 331 | 354 | /// session is revoked. Deliberately outside the credential rate-limit tier — |
| 332 | 355 | /// this is not a credential guess, and it requires a session cookie already. |
| 333 | 356 | #[utoipa::path( |
| @@ -337,7 +360,7 @@ async fn login( | ||
| 337 | 360 | request_body = SelectSchool, |
| 338 | 361 | responses( |
| 339 | 362 | (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), | |
| 341 | 364 | (status = 403, description = "The school is suspended", body = ErrorResponse), |
| 342 | 365 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 343 | 366 | ), |
| @@ -360,15 +383,15 @@ async fn select_school( | ||
| 360 | 383 | .await? |
| 361 | 384 | .filter(|s| !s.is_expired()) |
| 362 | 385 | .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 | |
| 364 | 387 | // as one the person does not hold — the list login already gave them is |
| 365 | 388 | // 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) | |
| 368 | 391 | .await? |
| 369 | 392 | .ok_or(AppError::Unauthorized)?; |
| 370 | 393 | // Suspended → `403` here, like on every school door. |
| 371 | - let db = st.tenants.get(&slug).await?; | |
| 394 | + let db = st.tenants.get(&id).await?; | |
| 372 | 395 | let person = service::person::read(&st.db, session.person()) |
| 373 | 396 | .await? |
| 374 | 397 | .ok_or(AppError::Unauthorized)?; |
| @@ -382,7 +405,7 @@ async fn select_school( | ||
| 382 | 405 | let school_session = service::session::create(&db, user.get_id()).await?; |
| 383 | 406 | service::person::delete_session_by_token(&st.db, token).await?; |
| 384 | 407 | let cookie = session_cookie( |
| 385 | - format!("{slug}.{}", school_session.token().as_str()), | |
| 408 | + format!("{id}.{}", school_session.token().as_str()), | |
| 386 | 409 | st.cookie_secure, |
| 387 | 410 | ); |
| 388 | 411 | Ok((jar.add(cookie), Json(UserResponse::new(&user)))) |
| @@ -391,7 +414,7 @@ async fn select_school( | ||
| 391 | 414 | /// The `session` cookie, however it was earned. Shared by school login and the |
| 392 | 415 | /// builder surface (`web::builder`) so the two can never drift apart on path, |
| 393 | 416 | /// flags or lifetime — the value is the only difference between them |
| 394 | -/// (`<slug>.<token>` against `builder.<token>`). | |
| 417 | +/// (`<uuid>.<token>` against `builder.<token>`). | |
| 395 | 418 | pub(crate) fn session_cookie(value: String, secure: bool) -> Cookie<'static> { |
| 396 | 419 | Cookie::build(("session", value)) |
| 397 | 420 | .path("/") |
| @@ -425,8 +448,8 @@ async fn logout( | ||
| 425 | 448 | crate::service::builder::delete_by_token(&st.db, token).await?; |
| 426 | 449 | } else if prefix == PERSON_COOKIE_PREFIX { |
| 427 | 450 | 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 | |
| 430 | 453 | { |
| 431 | 454 | service::session::delete_by_token(&db, token).await?; |
| 432 | 455 | } |
src/web/board_ws.rsmodified+13 -13
| @@ -58,7 +58,7 @@ | ||
| 58 | 58 | use std::collections::VecDeque; |
| 59 | 59 | use std::time::Duration; |
| 60 | 60 | |
| 61 | -use crate::web::tenant_state::{SchoolSlug, State}; | |
| 61 | +use crate::web::tenant_state::{SchoolIdCookie, State}; | |
| 62 | 62 | use axum::extract::Path; |
| 63 | 63 | use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade}; |
| 64 | 64 | use axum::response::Response; |
| @@ -78,7 +78,7 @@ use crate::domain::user::UserId; | ||
| 78 | 78 | use crate::error::AppError; |
| 79 | 79 | use crate::service::{board, board_stroke}; |
| 80 | 80 | use crate::state::AppState; |
| 81 | -use crate::tenant::Slug; | |
| 81 | +use crate::tenant::SchoolId; | |
| 82 | 82 | use crate::web::CurrentUser; |
| 83 | 83 | use crate::web::room::{self, Incoming, RoomClosed, send, with_client_seq}; |
| 84 | 84 | |
| @@ -122,7 +122,7 @@ enum ClientMessage { | ||
| 122 | 122 | /// every action already re-reads through. |
| 123 | 123 | pub async fn board_ws( |
| 124 | 124 | State(st): State<AppState>, |
| 125 | - SchoolSlug(slug): SchoolSlug, | |
| 125 | + SchoolIdCookie(school): SchoolIdCookie, | |
| 126 | 126 | CurrentUser(user): CurrentUser, |
| 127 | 127 | Path(id): Path<String>, |
| 128 | 128 | ws: WebSocketUpgrade, |
| @@ -141,19 +141,19 @@ pub async fn board_ws( | ||
| 141 | 141 | } |
| 142 | 142 | let board_id = board.get_id().clone(); |
| 143 | 143 | 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))) | |
| 145 | 145 | } |
| 146 | 146 | |
| 147 | 147 | /// The room loop: the board's frames out, draw/clear/lock/ping in, until the |
| 148 | 148 | /// socket closes or the board ends (closed, deleted, or the caller taken off |
| 149 | 149 | /// 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) { | |
| 151 | 151 | // Subscribe *before* anything is read out of the database: a stroke that |
| 152 | 152 | // lands between a replay's read and this subscribe would otherwise be lost |
| 153 | 153 | // outright, whereas one delivered twice is deduplicated by its id at the |
| 154 | 154 | // 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()); | |
| 157 | 157 | // The ids this socket drew, in the order they were published. The hub has |
| 158 | 158 | // no idea who is listening, so the room filters its own strokes back out |
| 159 | 159 | // 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 | ||
| 182 | 182 | }, |
| 183 | 183 | incoming = socket.recv() => match room::classify(incoming) { |
| 184 | 184 | 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 | |
| 186 | 186 | } |
| 187 | 187 | Incoming::Gone => Err(RoomClosed), |
| 188 | 188 | Incoming::Ignore => Ok(()), |
| @@ -193,7 +193,7 @@ async fn room(mut socket: WebSocket, st: AppState, slug: Slug, board: BoardId, u | ||
| 193 | 193 | } |
| 194 | 194 | } |
| 195 | 195 | room::close(&mut socket).await; |
| 196 | - st.board_hub.leave(&slug, &board.key()); | |
| 196 | + st.board_hub.leave(&school, &board.key()); | |
| 197 | 197 | } |
| 198 | 198 | |
| 199 | 199 | type Step = Result<(), RoomClosed>; |
| @@ -401,7 +401,7 @@ fn stroke_body(stroke: &BoardStroke) -> Value { | ||
| 401 | 401 | async fn handle_message( |
| 402 | 402 | socket: &mut WebSocket, |
| 403 | 403 | text: &str, |
| 404 | - slug: &Slug, | |
| 404 | + school: &SchoolId, | |
| 405 | 405 | board: &BoardId, |
| 406 | 406 | user: &UserId, |
| 407 | 407 | mine: &mut VecDeque<String>, |
| @@ -475,7 +475,7 @@ async fn handle_message( | ||
| 475 | 475 | fanned["type"] = json!("stroke"); |
| 476 | 476 | fanned["epoch"] = json!(stroke.get_epoch()); |
| 477 | 477 | 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()); | |
| 479 | 479 | let mut frame = json!({ "type": "saved", "id": stroke.get_id().key() }); |
| 480 | 480 | with_client_seq(&mut frame, client_seq); |
| 481 | 481 | send(socket, frame).await |
| @@ -498,7 +498,7 @@ async fn handle_message( | ||
| 498 | 498 | // canvas is the next one. Same shape as `POST /boards/{id}/clear`. |
| 499 | 499 | Ok(marker) => { |
| 500 | 500 | st.board_hub.publish( |
| 501 | - slug, | |
| 501 | + school, | |
| 502 | 502 | &board.key(), |
| 503 | 503 | json!({ |
| 504 | 504 | "type": "cleared", |
| @@ -517,7 +517,7 @@ async fn handle_message( | ||
| 517 | 517 | Some(live) => match board::set_locked(&st.db, &live, locked, user).await { |
| 518 | 518 | Ok(_) => { |
| 519 | 519 | st.board_hub.publish( |
| 520 | - slug, | |
| 520 | + school, | |
| 521 | 521 | &board.key(), |
| 522 | 522 | json!({ "type": "locked", "locked": locked, "by": user.key() }).to_string(), |
| 523 | 523 | ); |
src/web/boards.rsmodified+15 -15
| @@ -18,7 +18,7 @@ | ||
| 18 | 18 | //! mid-session keeps drawing over an already-open socket until the room hears |
| 19 | 19 | //! about it, so a roster change *must* fan out. |
| 20 | 20 | |
| 21 | -use crate::web::tenant_state::{SchoolSlug, State}; | |
| 21 | +use crate::web::tenant_state::{SchoolIdCookie, State}; | |
| 22 | 22 | use axum::Json; |
| 23 | 23 | use axum::extract::{Path, Query}; |
| 24 | 24 | use axum::http::StatusCode; |
| @@ -40,7 +40,7 @@ use crate::error::{AppError, ErrorResponse, ValidationError}; | ||
| 40 | 40 | use crate::service::course::can_manage_course; |
| 41 | 41 | use crate::service::{board, board_stroke}; |
| 42 | 42 | use crate::state::AppState; |
| 43 | -use crate::tenant::Slug; | |
| 43 | +use crate::tenant::SchoolId; | |
| 44 | 44 | |
| 45 | 45 | use super::{CurrentUser, Page, PageParams, RequireStudent, paginate, set_or_clear}; |
| 46 | 46 | |
| @@ -62,8 +62,8 @@ pub fn routes() -> OpenApiRouter<AppState> { | ||
| 62 | 62 | |
| 63 | 63 | /// Push one frame to whoever is in the room right now. An empty room is the |
| 64 | 64 | /// 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()); | |
| 67 | 67 | } |
| 68 | 68 | |
| 69 | 69 | /// The roster frame every path that changes the invite list must publish. A |
| @@ -438,7 +438,7 @@ struct UpdateBoard { | ||
| 438 | 438 | )] |
| 439 | 439 | async fn update_board( |
| 440 | 440 | State(st): State<AppState>, |
| 441 | - SchoolSlug(slug): SchoolSlug, | |
| 441 | + SchoolIdCookie(school): SchoolIdCookie, | |
| 442 | 442 | CurrentUser(user): CurrentUser, |
| 443 | 443 | Path(id): Path<String>, |
| 444 | 444 | Json(req): Json<UpdateBoard>, |
| @@ -461,13 +461,13 @@ async fn update_board( | ||
| 461 | 461 | let participants = |
| 462 | 462 | board::resolve_participants(participants, board.get_participants(), &st.db).await?; |
| 463 | 463 | 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)); | |
| 465 | 465 | } |
| 466 | 466 | if let Some(locked) = req.locked { |
| 467 | 467 | board = board::set_locked(&st.db, &board, locked, user.get_id()).await?; |
| 468 | 468 | fan_out( |
| 469 | 469 | &st, |
| 470 | - &slug, | |
| 470 | + &school, | |
| 471 | 471 | board.get_id(), |
| 472 | 472 | json!({"type": "locked", "locked": locked, "by": user.get_id().key()}), |
| 473 | 473 | ); |
| @@ -503,7 +503,7 @@ async fn update_board( | ||
| 503 | 503 | )] |
| 504 | 504 | async fn clear_board( |
| 505 | 505 | State(st): State<AppState>, |
| 506 | - SchoolSlug(slug): SchoolSlug, | |
| 506 | + SchoolIdCookie(school): SchoolIdCookie, | |
| 507 | 507 | CurrentUser(user): CurrentUser, |
| 508 | 508 | Path(id): Path<String>, |
| 509 | 509 | ) -> Result<(StatusCode, Json<StrokeResponse>), AppError> { |
| @@ -514,7 +514,7 @@ async fn clear_board( | ||
| 514 | 514 | // next one. |
| 515 | 515 | fan_out( |
| 516 | 516 | &st, |
| 517 | - &slug, | |
| 517 | + &school, | |
| 518 | 518 | board.get_id(), |
| 519 | 519 | json!({ |
| 520 | 520 | "type": "cleared", |
| @@ -545,7 +545,7 @@ async fn clear_board( | ||
| 545 | 545 | )] |
| 546 | 546 | async fn close_board( |
| 547 | 547 | State(st): State<AppState>, |
| 548 | - SchoolSlug(slug): SchoolSlug, | |
| 548 | + SchoolIdCookie(school): SchoolIdCookie, | |
| 549 | 549 | CurrentUser(user): CurrentUser, |
| 550 | 550 | Path(id): Path<String>, |
| 551 | 551 | ) -> Result<Json<BoardResponse>, AppError> { |
| @@ -554,7 +554,7 @@ async fn close_board( | ||
| 554 | 554 | let board = board::close(&st.db, &board).await?; |
| 555 | 555 | fan_out( |
| 556 | 556 | &st, |
| 557 | - &slug, | |
| 557 | + &school, | |
| 558 | 558 | board.get_id(), |
| 559 | 559 | json!({ |
| 560 | 560 | "type": "closed", |
| @@ -719,7 +719,7 @@ impl InviteSource { | ||
| 719 | 719 | )] |
| 720 | 720 | async fn invite_board( |
| 721 | 721 | State(st): State<AppState>, |
| 722 | - SchoolSlug(slug): SchoolSlug, | |
| 722 | + SchoolIdCookie(school): SchoolIdCookie, | |
| 723 | 723 | CurrentUser(user): CurrentUser, |
| 724 | 724 | Path(id): Path<String>, |
| 725 | 725 | Json(req): Json<InviteSource>, |
| @@ -734,7 +734,7 @@ async fn invite_board( | ||
| 734 | 734 | board::ensure_creator(&board, &user)?; |
| 735 | 735 | let invited = req.resolve(&user, &st.db).await?; |
| 736 | 736 | 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)); | |
| 738 | 738 | Ok(Json(BoardResponse::new(&board))) |
| 739 | 739 | } |
| 740 | 740 | |
| @@ -757,7 +757,7 @@ async fn invite_board( | ||
| 757 | 757 | )] |
| 758 | 758 | async fn delete_board( |
| 759 | 759 | State(st): State<AppState>, |
| 760 | - SchoolSlug(slug): SchoolSlug, | |
| 760 | + SchoolIdCookie(school): SchoolIdCookie, | |
| 761 | 761 | CurrentUser(user): CurrentUser, |
| 762 | 762 | Path(id): Path<String>, |
| 763 | 763 | ) -> Result<StatusCode, AppError> { |
| @@ -767,6 +767,6 @@ async fn delete_board( | ||
| 767 | 767 | board::delete(&st.db, board).await?; |
| 768 | 768 | // Told after the row is gone: a room that acts on this and then re-reads |
| 769 | 769 | // 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"})); | |
| 771 | 771 | Ok(StatusCode::NO_CONTENT) |
| 772 | 772 | } |
src/web/builder.rsmodified+80 -89
| @@ -6,7 +6,7 @@ | ||
| 6 | 6 | //! |
| 7 | 7 | //! The two principals never mix: [`RequireBuilder`] takes only a |
| 8 | 8 | //! `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 | |
| 10 | 10 | //! the one bridge, and it does not blur the line — it mints an ordinary school |
| 11 | 11 | //! session for an admin account that already exists there. |
| 12 | 12 | //! |
| @@ -34,7 +34,7 @@ use crate::module::{Module, ModuleSet, Package}; | ||
| 34 | 34 | use crate::rate_limit::{RateLimitConfig, RateLimiter}; |
| 35 | 35 | use crate::service; |
| 36 | 36 | use crate::state::AppState; |
| 37 | -use crate::tenant::{School, SchoolId, SchoolStatus, Slug}; | |
| 37 | +use crate::tenant::{School, SchoolId, SchoolStatus}; | |
| 38 | 38 | use crate::validate::validate_required; |
| 39 | 39 | use crate::web::tenant_state::school_files_path; |
| 40 | 40 | |
| @@ -93,8 +93,8 @@ impl BuilderResponse { | ||
| 93 | 93 | |
| 94 | 94 | #[derive(Serialize, ToSchema)] |
| 95 | 95 | struct SchoolResponse { |
| 96 | - #[schema(example = "ata-koleji")] | |
| 97 | - slug: String, | |
| 96 | + #[schema(example = "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d")] | |
| 97 | + id: String, | |
| 98 | 98 | #[schema(example = "Ata Koleji")] |
| 99 | 99 | name: String, |
| 100 | 100 | /// `active` or `suspended` — plus `provisioning`, which a boot writes only |
| @@ -106,7 +106,7 @@ struct SchoolResponse { | ||
| 106 | 106 | /// Registered at, UTC unix-milliseconds. |
| 107 | 107 | created_at: i64, |
| 108 | 108 | /// 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`. | |
| 110 | 110 | #[schema(example = json!(["courses", "meals", "notes"]))] |
| 111 | 111 | modules: Vec<String>, |
| 112 | 112 | } |
| @@ -114,7 +114,7 @@ struct SchoolResponse { | ||
| 114 | 114 | impl SchoolResponse { |
| 115 | 115 | fn new(school: &School) -> Self { |
| 116 | 116 | Self { |
| 117 | - slug: school.slug().as_str().to_string(), | |
| 117 | + id: school.get_id().as_str(), | |
| 118 | 118 | name: school.name().to_string(), |
| 119 | 119 | status: school.status().as_str().to_string(), |
| 120 | 120 | created_at: school.created_at().as_millis(), |
| @@ -125,12 +125,6 @@ impl SchoolResponse { | ||
| 125 | 125 | |
| 126 | 126 | #[derive(Deserialize, ToSchema)] |
| 127 | 127 | 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, | |
| 134 | 128 | #[schema(example = "Ata Koleji", max_length = 120)] |
| 135 | 129 | name: String, |
| 136 | 130 | /// The school's first admin, created inside the new school's database. |
| @@ -210,18 +204,18 @@ struct EnterSchool { | ||
| 210 | 204 | username: String, |
| 211 | 205 | } |
| 212 | 206 | |
| 213 | -/// A school's display name: free text, unlike its slug. | |
| 207 | +/// A school's display name. | |
| 214 | 208 | fn school_name(value: &str) -> Result<String, AppError> { |
| 215 | 209 | validate_required("name", value, MAX_SCHOOL_NAME_LEN)?; |
| 216 | 210 | Ok(value.trim().to_string()) |
| 217 | 211 | } |
| 218 | 212 | |
| 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 | |
| 221 | 215 | /// [`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) | |
| 225 | 219 | } |
| 226 | 220 | |
| 227 | 221 | /// 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 | ||
| 333 | 327 | request_body = CreateSchool, |
| 334 | 328 | responses( |
| 335 | 329 | (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"})), | |
| 337 | 331 | (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"})), | |
| 339 | 333 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 340 | 334 | ), |
| 341 | 335 | )] |
| @@ -347,7 +341,6 @@ async fn create_school( | ||
| 347 | 341 | // Everything the request must get right is checked (and the admin password |
| 348 | 342 | // hashed) *before* a database is defined, so the ordinary rejection never |
| 349 | 343 | // creates anything to clean up. |
| 350 | - let slug = Slug::try_new(&req.slug)?; | |
| 351 | 344 | let name = school_name(&req.name)?; |
| 352 | 345 | let username = Username::try_new(&req.admin_username)?; |
| 353 | 346 | let password = Password::try_new(&req.admin_password)?; |
| @@ -375,9 +368,9 @@ async fn create_school( | ||
| 375 | 368 | |
| 376 | 369 | // The school's uuid is minted here, on the one path that creates schools: |
| 377 | 370 | // 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. | |
| 379 | 372 | 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?; | |
| 381 | 374 | let seeded = async { |
| 382 | 375 | crate::service::user::create_with_role( |
| 383 | 376 | &db, |
| @@ -389,20 +382,20 @@ async fn create_school( | ||
| 389 | 382 | .await?; |
| 390 | 383 | // The admin's person gets the membership the school row answers for — |
| 391 | 384 | // 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?; | |
| 393 | 386 | Ok::<(), AppError>(()) |
| 394 | 387 | } |
| 395 | 388 | .await; |
| 396 | 389 | if let Err(err) = seeded { |
| 397 | 390 | // A school nobody can log into is worse than no school: take the |
| 398 | 391 | // 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}"); | |
| 401 | 394 | } |
| 402 | 395 | return Err(err); |
| 403 | 396 | } |
| 404 | 397 | |
| 405 | - let school = School::read(&slug, st.tenants.control()) | |
| 398 | + let school = School::read(&id, st.tenants.control()) | |
| 406 | 399 | .await? |
| 407 | 400 | .ok_or_else(|| AppError::Internal("the school vanished as it was created".into()))?; |
| 408 | 401 | Ok((StatusCode::CREATED, Json(SchoolResponse::new(&school)))) |
| @@ -433,13 +426,13 @@ async fn list_schools( | ||
| 433 | 426 | Ok(Json(Page::new(items, total, limit, offset))) |
| 434 | 427 | } |
| 435 | 428 | |
| 436 | -/// One school by slug. | |
| 429 | +/// One school by id. | |
| 437 | 430 | #[utoipa::path( |
| 438 | 431 | get, |
| 439 | - path = "/schools/{slug}", | |
| 432 | + path = "/schools/{id}", | |
| 440 | 433 | tag = "builder", |
| 441 | 434 | security(("session_cookie" = [])), |
| 442 | - params(("slug" = String, Path, description = "School slug")), | |
| 435 | + params(("id" = String, Path, description = "School uuid")), | |
| 443 | 436 | responses( |
| 444 | 437 | (status = 200, description = "The school", body = SchoolResponse), |
| 445 | 438 | (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), |
| @@ -449,9 +442,9 @@ async fn list_schools( | ||
| 449 | 442 | async fn get_school( |
| 450 | 443 | State(st): State<AppState>, |
| 451 | 444 | RequireBuilder(_builder): RequireBuilder, |
| 452 | - Path(slug): Path<String>, | |
| 445 | + Path(id): Path<String>, | |
| 453 | 446 | ) -> 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()) | |
| 455 | 448 | .await? |
| 456 | 449 | .ok_or(AppError::NotFound)?; |
| 457 | 450 | Ok(Json(SchoolResponse::new(&school))) |
| @@ -459,10 +452,8 @@ async fn get_school( | ||
| 459 | 452 | |
| 460 | 453 | /// Rename a school and/or flip it between `active` and `suspended`. Omitted |
| 461 | 454 | /// 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. | |
| 466 | 457 | /// |
| 467 | 458 | /// `provisioning` is not a status a client can ask for: it is the boot's word |
| 468 | 459 | /// for a school that is still being made, and asking for it is a `400`. |
| @@ -471,10 +462,10 @@ async fn get_school( | ||
| 471 | 462 | /// request is a `403`, live session or not. |
| 472 | 463 | #[utoipa::path( |
| 473 | 464 | patch, |
| 474 | - path = "/schools/{slug}", | |
| 465 | + path = "/schools/{id}", | |
| 475 | 466 | tag = "builder", |
| 476 | 467 | security(("session_cookie" = [])), |
| 477 | - params(("slug" = String, Path, description = "School slug")), | |
| 468 | + params(("id" = String, Path, description = "School uuid")), | |
| 478 | 469 | request_body = UpdateSchool, |
| 479 | 470 | responses( |
| 480 | 471 | (status = 200, description = "The updated school", body = SchoolResponse), |
| @@ -487,10 +478,10 @@ async fn get_school( | ||
| 487 | 478 | async fn update_school( |
| 488 | 479 | State(st): State<AppState>, |
| 489 | 480 | RequireBuilder(_builder): RequireBuilder, |
| 490 | - Path(slug): Path<String>, | |
| 481 | + Path(id): Path<String>, | |
| 491 | 482 | Json(req): Json<UpdateSchool>, |
| 492 | 483 | ) -> Result<Json<SchoolResponse>, AppError> { |
| 493 | - let slug = path_slug(&slug)?; | |
| 484 | + let id = path_id(&id)?; | |
| 494 | 485 | let name = req.name.as_deref().map(school_name).transpose()?; |
| 495 | 486 | let status = req |
| 496 | 487 | .status |
| @@ -502,7 +493,7 @@ async fn update_school( | ||
| 502 | 493 | // a patch that carries both can never leave half of itself behind. An empty |
| 503 | 494 | // patch on an unknown school is still a 404 — the update answers it, rather |
| 504 | 495 | // 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?; | |
| 506 | 497 | if status == Some(SchoolStatus::Suspended) { |
| 507 | 498 | // A suspension evicts the pool so nothing that already resolved keeps |
| 508 | 499 | // serving; un-suspending needs no invalidation, the next request dials. |
| @@ -515,10 +506,10 @@ async fn update_school( | ||
| 515 | 506 | /// Irreversible — suspension is the reversible door. |
| 516 | 507 | #[utoipa::path( |
| 517 | 508 | delete, |
| 518 | - path = "/schools/{slug}", | |
| 509 | + path = "/schools/{id}", | |
| 519 | 510 | tag = "builder", |
| 520 | 511 | security(("session_cookie" = [])), |
| 521 | - params(("slug" = String, Path, description = "School slug")), | |
| 512 | + params(("id" = String, Path, description = "School uuid")), | |
| 522 | 513 | responses( |
| 523 | 514 | (status = 204, description = "Deleted"), |
| 524 | 515 | (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), |
| @@ -528,24 +519,24 @@ async fn update_school( | ||
| 528 | 519 | async fn delete_school( |
| 529 | 520 | State(st): State<AppState>, |
| 530 | 521 | RequireBuilder(_builder): RequireBuilder, |
| 531 | - Path(slug): Path<String>, | |
| 522 | + Path(id): Path<String>, | |
| 532 | 523 | ) -> 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()) | |
| 535 | 526 | .await? |
| 536 | 527 | .ok_or(AppError::NotFound)?; |
| 537 | - st.tenants.drop(&slug).await?; | |
| 528 | + st.tenants.drop(&id).await?; | |
| 538 | 529 | |
| 539 | 530 | // Rows first, bytes second — the same order every blob delete here keeps, so |
| 540 | 531 | // 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 | |
| 542 | 533 | // the raw path segment. |
| 543 | - let dir = school_files_path(&st.files_path, &slug); | |
| 534 | + let dir = school_files_path(&st.files_path, &id); | |
| 544 | 535 | if let Err(err) = tokio::fs::remove_dir_all(&dir).await |
| 545 | 536 | && err.kind() != std::io::ErrorKind::NotFound |
| 546 | 537 | { |
| 547 | 538 | tracing::warn!( |
| 548 | - "failed to remove the files of {slug} at {}: {err}", | |
| 539 | + "failed to remove the files of {id} at {}: {err}", | |
| 549 | 540 | dir.display() |
| 550 | 541 | ); |
| 551 | 542 | } |
| @@ -553,7 +544,7 @@ async fn delete_school( | ||
| 553 | 544 | } |
| 554 | 545 | |
| 555 | 546 | /// 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 | |
| 557 | 548 | /// there is no resource to act on. Inside a *body* the same name is a `400` |
| 558 | 549 | /// instead — a bad field, not a bad address. |
| 559 | 550 | fn path_module(raw: &str) -> Result<Module, AppError> { |
| @@ -564,10 +555,10 @@ fn path_module(raw: &str) -> Result<Module, AppError> { | ||
| 564 | 555 | /// [`Tenants::resolve`]: that one is the school's own door and refuses a |
| 565 | 556 | /// suspended school, and every route here keeps working on one. |
| 566 | 557 | async fn school_modules( |
| 567 | - slug: &Slug, | |
| 558 | + id: &SchoolId, | |
| 568 | 559 | control: &crate::database::Database, |
| 569 | 560 | ) -> Result<ModuleSet, AppError> { |
| 570 | - Ok(School::read(slug, control) | |
| 561 | + Ok(School::read(id, control) | |
| 571 | 562 | .await? |
| 572 | 563 | .ok_or(AppError::NotFound)? |
| 573 | 564 | .modules()) |
| @@ -596,10 +587,10 @@ fn refuse_if_needed(module: Module, set: &ModuleSet) -> Result<(), AppError> { | ||
| 596 | 587 | /// caller here has already decided. |
| 597 | 588 | async fn store_modules( |
| 598 | 589 | st: &AppState, |
| 599 | - slug: &Slug, | |
| 590 | + id: &SchoolId, | |
| 600 | 591 | modules: ModuleSet, |
| 601 | 592 | ) -> Result<Json<ModulesResponse>, AppError> { |
| 602 | - st.tenants.set_modules(slug, &modules).await?; | |
| 593 | + st.tenants.set_modules(id, &modules).await?; | |
| 603 | 594 | Ok(Json(ModulesResponse::new(&modules))) |
| 604 | 595 | } |
| 605 | 596 | |
| @@ -607,10 +598,10 @@ async fn store_modules( | ||
| 607 | 598 | /// school — entitlements are the vendor's ledger, not one of the school's doors. |
| 608 | 599 | #[utoipa::path( |
| 609 | 600 | get, |
| 610 | - path = "/schools/{slug}/modules", | |
| 601 | + path = "/schools/{id}/modules", | |
| 611 | 602 | tag = "builder", |
| 612 | 603 | security(("session_cookie" = [])), |
| 613 | - params(("slug" = String, Path, description = "School slug")), | |
| 604 | + params(("id" = String, Path, description = "School uuid")), | |
| 614 | 605 | responses( |
| 615 | 606 | (status = 200, description = "The school's enabled and disabled modules", body = ModulesResponse), |
| 616 | 607 | (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), |
| @@ -620,9 +611,9 @@ async fn store_modules( | ||
| 620 | 611 | async fn list_school_modules( |
| 621 | 612 | State(st): State<AppState>, |
| 622 | 613 | RequireBuilder(_builder): RequireBuilder, |
| 623 | - Path(slug): Path<String>, | |
| 614 | + Path(id): Path<String>, | |
| 624 | 615 | ) -> 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?; | |
| 626 | 617 | Ok(Json(ModulesResponse::new(&modules))) |
| 627 | 618 | } |
| 628 | 619 | |
| @@ -631,11 +622,11 @@ async fn list_school_modules( | ||
| 631 | 622 | /// off — enable those in the same `PATCH` instead. |
| 632 | 623 | #[utoipa::path( |
| 633 | 624 | post, |
| 634 | - path = "/schools/{slug}/modules/{module}", | |
| 625 | + path = "/schools/{id}/modules/{module}", | |
| 635 | 626 | tag = "builder", |
| 636 | 627 | security(("session_cookie" = [])), |
| 637 | 628 | params( |
| 638 | - ("slug" = String, Path, description = "School slug"), | |
| 629 | + ("id" = String, Path, description = "School uuid"), | |
| 639 | 630 | ("module" = String, Path, description = "Module name, as `GET /modules/catalog` publishes it"), |
| 640 | 631 | ), |
| 641 | 632 | responses( |
| @@ -648,17 +639,17 @@ async fn list_school_modules( | ||
| 648 | 639 | async fn enable_school_module( |
| 649 | 640 | State(st): State<AppState>, |
| 650 | 641 | RequireBuilder(_builder): RequireBuilder, |
| 651 | - Path((slug, module)): Path<(String, String)>, | |
| 642 | + Path((id, module)): Path<(String, String)>, | |
| 652 | 643 | ) -> Result<Json<ModulesResponse>, AppError> { |
| 653 | - let slug = path_slug(&slug)?; | |
| 644 | + let id = path_id(&id)?; | |
| 654 | 645 | 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?; | |
| 656 | 647 | if modules.contains(module) { |
| 657 | 648 | return Ok(Json(ModulesResponse::new(&modules))); |
| 658 | 649 | } |
| 659 | 650 | modules.insert(module); |
| 660 | 651 | modules.validate()?; |
| 661 | - store_modules(&st, &slug, modules).await | |
| 652 | + store_modules(&st, &id, modules).await | |
| 662 | 653 | } |
| 663 | 654 | |
| 664 | 655 | /// Take one module back. Idempotent, and refused while a module the school |
| @@ -668,11 +659,11 @@ async fn enable_school_module( | ||
| 668 | 659 | /// back with it. Only its routes stop answering. |
| 669 | 660 | #[utoipa::path( |
| 670 | 661 | delete, |
| 671 | - path = "/schools/{slug}/modules/{module}", | |
| 662 | + path = "/schools/{id}/modules/{module}", | |
| 672 | 663 | tag = "builder", |
| 673 | 664 | security(("session_cookie" = [])), |
| 674 | 665 | params( |
| 675 | - ("slug" = String, Path, description = "School slug"), | |
| 666 | + ("id" = String, Path, description = "School uuid"), | |
| 676 | 667 | ("module" = String, Path, description = "Module name, as `GET /modules/catalog` publishes it"), |
| 677 | 668 | ), |
| 678 | 669 | responses( |
| @@ -685,17 +676,17 @@ async fn enable_school_module( | ||
| 685 | 676 | async fn disable_school_module( |
| 686 | 677 | State(st): State<AppState>, |
| 687 | 678 | RequireBuilder(_builder): RequireBuilder, |
| 688 | - Path((slug, module)): Path<(String, String)>, | |
| 679 | + Path((id, module)): Path<(String, String)>, | |
| 689 | 680 | ) -> Result<Json<ModulesResponse>, AppError> { |
| 690 | - let slug = path_slug(&slug)?; | |
| 681 | + let id = path_id(&id)?; | |
| 691 | 682 | 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?; | |
| 693 | 684 | if !modules.contains(module) { |
| 694 | 685 | return Ok(Json(ModulesResponse::new(&modules))); |
| 695 | 686 | } |
| 696 | 687 | refuse_if_needed(module, &modules)?; |
| 697 | 688 | modules.remove(module); |
| 698 | - store_modules(&st, &slug, modules).await | |
| 689 | + store_modules(&st, &id, modules).await | |
| 699 | 690 | } |
| 700 | 691 | |
| 701 | 692 | /// 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( | ||
| 708 | 699 | /// the whole request is accepted. |
| 709 | 700 | #[utoipa::path( |
| 710 | 701 | patch, |
| 711 | - path = "/schools/{slug}/modules", | |
| 702 | + path = "/schools/{id}/modules", | |
| 712 | 703 | tag = "builder", |
| 713 | 704 | security(("session_cookie" = [])), |
| 714 | - params(("slug" = String, Path, description = "School slug")), | |
| 705 | + params(("id" = String, Path, description = "School uuid")), | |
| 715 | 706 | request_body = PatchModules, |
| 716 | 707 | responses( |
| 717 | 708 | (status = 200, description = "The school's modules after the change", body = ModulesResponse), |
| @@ -725,10 +716,10 @@ async fn disable_school_module( | ||
| 725 | 716 | async fn patch_school_modules( |
| 726 | 717 | State(st): State<AppState>, |
| 727 | 718 | RequireBuilder(_builder): RequireBuilder, |
| 728 | - Path(slug): Path<String>, | |
| 719 | + Path(id): Path<String>, | |
| 729 | 720 | Json(req): Json<PatchModules>, |
| 730 | 721 | ) -> Result<Json<ModulesResponse>, AppError> { |
| 731 | - let slug = path_slug(&slug)?; | |
| 722 | + let id = path_id(&id)?; | |
| 732 | 723 | let enable = req.side(req.enable.as_deref(), req.enable_packages.as_deref())?; |
| 733 | 724 | let disable = req.side(req.disable.as_deref(), req.disable_packages.as_deref())?; |
| 734 | 725 | // A name pulled both ways has no defensible resolution, and picking one |
| @@ -742,7 +733,7 @@ async fn patch_school_modules( | ||
| 742 | 733 | .into()); |
| 743 | 734 | } |
| 744 | 735 | |
| 745 | - let current = school_modules(&slug, st.tenants.control()).await?; | |
| 736 | + let current = school_modules(&id, st.tenants.control()).await?; | |
| 746 | 737 | let mut result = current.clone(); |
| 747 | 738 | for module in enable.iter() { |
| 748 | 739 | result.insert(module); |
| @@ -757,7 +748,7 @@ async fn patch_school_modules( | ||
| 757 | 748 | if result == current { |
| 758 | 749 | return Ok(Json(ModulesResponse::new(¤t))); |
| 759 | 750 | } |
| 760 | - store_modules(&st, &slug, result).await | |
| 751 | + store_modules(&st, &id, result).await | |
| 761 | 752 | } |
| 762 | 753 | |
| 763 | 754 | /// Reset an admin's password inside a school — the "we are locked out" call. |
| @@ -765,10 +756,10 @@ async fn patch_school_modules( | ||
| 765 | 756 | /// not survive the reset. Works on a suspended school. |
| 766 | 757 | #[utoipa::path( |
| 767 | 758 | post, |
| 768 | - path = "/schools/{slug}/admin-password", | |
| 759 | + path = "/schools/{id}/admin-password", | |
| 769 | 760 | tag = "builder", |
| 770 | 761 | security(("session_cookie" = [])), |
| 771 | - params(("slug" = String, Path, description = "School slug")), | |
| 762 | + params(("id" = String, Path, description = "School uuid")), | |
| 772 | 763 | request_body = AdminPassword, |
| 773 | 764 | responses( |
| 774 | 765 | (status = 204, description = "Password reset; that account's sessions are revoked"), |
| @@ -782,11 +773,11 @@ async fn patch_school_modules( | ||
| 782 | 773 | async fn reset_admin_password( |
| 783 | 774 | State(st): State<AppState>, |
| 784 | 775 | RequireBuilder(_builder): RequireBuilder, |
| 785 | - Path(slug): Path<String>, | |
| 776 | + Path(id): Path<String>, | |
| 786 | 777 | Json(req): Json<AdminPassword>, |
| 787 | 778 | ) -> 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?; | |
| 790 | 781 | let user = school_admin(&req.username, &db).await?; |
| 791 | 782 | let password_hash = Password::try_new(&req.password)?.hash_async().await?; |
| 792 | 783 | |
| @@ -806,16 +797,16 @@ async fn reset_admin_password( | ||
| 806 | 797 | } |
| 807 | 798 | |
| 808 | 799 | /// 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. | |
| 810 | 801 | /// |
| 811 | 802 | /// Refused on a suspended school (`403`): a suspension closes the school's |
| 812 | 803 | /// doors, and this is one of them. Un-suspend it first. |
| 813 | 804 | #[utoipa::path( |
| 814 | 805 | post, |
| 815 | - path = "/schools/{slug}/enter", | |
| 806 | + path = "/schools/{id}/enter", | |
| 816 | 807 | tag = "builder", |
| 817 | 808 | security(("session_cookie" = [])), |
| 818 | - params(("slug" = String, Path, description = "School slug")), | |
| 809 | + params(("id" = String, Path, description = "School uuid")), | |
| 819 | 810 | request_body = EnterSchool, |
| 820 | 811 | responses( |
| 821 | 812 | (status = 200, description = "Entered; that school's session cookie is set", body = UserResponse), |
| @@ -830,11 +821,11 @@ async fn enter_school( | ||
| 830 | 821 | State(st): State<AppState>, |
| 831 | 822 | RequireBuilder(_builder): RequireBuilder, |
| 832 | 823 | jar: CookieJar, |
| 833 | - Path(slug): Path<String>, | |
| 824 | + Path(id): Path<String>, | |
| 834 | 825 | Json(req): Json<EnterSchool>, |
| 835 | 826 | ) -> 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?; | |
| 838 | 829 | if status == SchoolStatus::Suspended { |
| 839 | 830 | return Err(AppError::Forbidden("school is suspended")); |
| 840 | 831 | } |
| @@ -842,7 +833,7 @@ async fn enter_school( | ||
| 842 | 833 | |
| 843 | 834 | let session = service::session::create(&db, user.get_id()).await?; |
| 844 | 835 | let cookie = session_cookie( |
| 845 | - format!("{slug}.{}", session.token().as_str()), | |
| 836 | + format!("{id}.{}", session.token().as_str()), | |
| 846 | 837 | st.cookie_secure, |
| 847 | 838 | ); |
| 848 | 839 | Ok((jar.add(cookie), Json(UserResponse::new(&user)))) |
src/web/chatbot.rsmodified+6 -6
| @@ -21,7 +21,7 @@ | ||
| 21 | 21 | use std::time::Duration; |
| 22 | 22 | |
| 23 | 23 | use crate::tenant::ResolvedTenant; |
| 24 | -use crate::web::tenant_state::{SchoolSlug, State, TenantExt}; | |
| 24 | +use crate::web::tenant_state::{SchoolIdCookie, State, TenantExt}; | |
| 25 | 25 | use axum::Json; |
| 26 | 26 | use axum::extract::{Path, Query}; |
| 27 | 27 | use axum::http::StatusCode; |
| @@ -379,7 +379,7 @@ async fn list_messages( | ||
| 379 | 379 | )] |
| 380 | 380 | async fn send_message( |
| 381 | 381 | State(st): State<AppState>, |
| 382 | - SchoolSlug(slug): SchoolSlug, | |
| 382 | + SchoolIdCookie(school): SchoolIdCookie, | |
| 383 | 383 | tenant: ResolvedTenant, |
| 384 | 384 | CurrentUser(user): CurrentUser, |
| 385 | 385 | Path(id): Path<String>, |
| @@ -387,7 +387,7 @@ async fn send_message( | ||
| 387 | 387 | ) -> Result<Response, AppError> { |
| 388 | 388 | // Charged first: a rejected turn must cost nothing and leave no row. |
| 389 | 389 | 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()))?; | |
| 391 | 391 | |
| 392 | 392 | let thread = own_thread(&id, user.get_id(), &st.db).await?; |
| 393 | 393 | let settings = service::settings::load(&st.db).await?; |
| @@ -447,7 +447,7 @@ async fn send_message( | ||
| 447 | 447 | // request was already resolved into, and one without the other is how |
| 448 | 448 | // an answer lands in the wrong school. |
| 449 | 449 | TenantExt { |
| 450 | - slug, | |
| 450 | + id: school, | |
| 451 | 451 | db: st.db.clone(), |
| 452 | 452 | modules: tenant.modules, |
| 453 | 453 | }, |
| @@ -573,7 +573,7 @@ async fn fetch_reply( | ||
| 573 | 573 | })?; |
| 574 | 574 | |
| 575 | 575 | let raw = bridge |
| 576 | - .dispatch(&tenant.slug, AI_CHAT_CAPABILITY, payload) | |
| 576 | + .dispatch(&tenant.id, AI_CHAT_CAPABILITY, payload) | |
| 577 | 577 | .await |
| 578 | 578 | .map_err(failure_code)?; |
| 579 | 579 | let reply: ChatReplyPayload = serde_json::from_value(raw).map_err(|err| { |
| @@ -927,7 +927,7 @@ mod tests { | ||
| 927 | 927 | } |
| 928 | 928 | |
| 929 | 929 | #[tokio::test] |
| 930 | - async fn failure_codes_are_stable_slugs() { | |
| 930 | + async fn failure_codes_are_stable() { | |
| 931 | 931 | assert_eq!( |
| 932 | 932 | failure_code(AiError::NoWorker("chat.reply".into())), |
| 933 | 933 | "unavailable" |
src/web/exam_ws.rsmodified+8 -8
| @@ -56,7 +56,7 @@ | ||
| 56 | 56 | |
| 57 | 57 | use std::time::Duration; |
| 58 | 58 | |
| 59 | -use crate::web::tenant_state::{SchoolSlug, State}; | |
| 59 | +use crate::web::tenant_state::{SchoolIdCookie, State}; | |
| 60 | 60 | use axum::extract::Path; |
| 61 | 61 | use axum::extract::ws::{WebSocket, WebSocketUpgrade}; |
| 62 | 62 | use axum::response::Response; |
| @@ -75,7 +75,7 @@ use crate::service::exam_attempt::{ | ||
| 75 | 75 | set_left, writable_attempt, |
| 76 | 76 | }; |
| 77 | 77 | use crate::state::AppState; |
| 78 | -use crate::tenant::Slug; | |
| 78 | +use crate::tenant::SchoolId; | |
| 79 | 79 | use crate::validate::validate_required; |
| 80 | 80 | use crate::web::CurrentUser; |
| 81 | 81 | use crate::web::room::{self, Incoming, RoomClosed, send, with_client_seq}; |
| @@ -131,7 +131,7 @@ enum ClientMessage { | ||
| 131 | 131 | /// stamp a student who was already reconnecting. |
| 132 | 132 | pub async fn attempt_ws( |
| 133 | 133 | State(st): State<AppState>, |
| 134 | - SchoolSlug(slug): SchoolSlug, | |
| 134 | + SchoolIdCookie(school): SchoolIdCookie, | |
| 135 | 135 | CurrentUser(user): CurrentUser, |
| 136 | 136 | Path(id): Path<String>, |
| 137 | 137 | ws: WebSocketUpgrade, |
| @@ -147,7 +147,7 @@ pub async fn attempt_ws( | ||
| 147 | 147 | crate::service::exam_attempt::require_open(&st.db, &exam).await?; |
| 148 | 148 | |
| 149 | 149 | 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))) | |
| 151 | 151 | } |
| 152 | 152 | |
| 153 | 153 | /// The room loop: state ticks out, answer/finish/ping in, until the socket |
| @@ -156,7 +156,7 @@ pub async fn attempt_ws( | ||
| 156 | 156 | async fn room( |
| 157 | 157 | mut socket: WebSocket, |
| 158 | 158 | st: AppState, |
| 159 | - slug: Slug, | |
| 159 | + school: SchoolId, | |
| 160 | 160 | exam: Exam, |
| 161 | 161 | attempt: ExamAttempt, |
| 162 | 162 | user: UserId, |
| @@ -168,7 +168,7 @@ async fn room( | ||
| 168 | 168 | let _connected = room::Connected::open( |
| 169 | 169 | &st.metrics, |
| 170 | 170 | "exam_room", |
| 171 | - slug.as_str(), | |
| 171 | + school.as_str(), | |
| 172 | 172 | exam_id.key().as_str(), |
| 173 | 173 | ); |
| 174 | 174 | // Join: this socket counts as presence in the sitting's room until it |
| @@ -178,7 +178,7 @@ async fn room( | ||
| 178 | 178 | // predate a stamp that raced the upgrade; clearing regardless is what |
| 179 | 179 | // keeps a reconnecting student unmarked. Best-effort — a failed clear |
| 180 | 180 | // 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()); | |
| 182 | 182 | if let Err(err) = set_left(&st.db, attempt, None).await { |
| 183 | 183 | tracing::warn!("exam room could not clear left_at on join: {err}"); |
| 184 | 184 | } |
| @@ -215,7 +215,7 @@ async fn room( | ||
| 215 | 215 | // stamped. With `allow_rejoin` off this is what locks further |
| 216 | 216 | // answering. Best-effort: a failed stamp only means it goes |
| 217 | 217 | // 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()) { | |
| 219 | 219 | crate::db::exam_attempt::stamp_left_if_running(&st.db, &attempt_id, Timestamp::now()) |
| 220 | 220 | .await |
| 221 | 221 | .unwrap_or_else(|err| { |
src/web/extractor.rsmodified+5 -5
| @@ -154,7 +154,7 @@ where | ||
| 154 | 154 | /// The deployment operator behind a `builder.<token>` cookie, resolved against |
| 155 | 155 | /// the **control** database. Any school cookie is `401` here, and this cookie |
| 156 | 156 | /// 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. | |
| 158 | 158 | pub struct RequireBuilder(pub Builder); |
| 159 | 159 | |
| 160 | 160 | impl<S> FromRequestParts<S> for RequireBuilder |
| @@ -189,14 +189,14 @@ where | ||
| 189 | 189 | } |
| 190 | 190 | } |
| 191 | 191 | |
| 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. | |
| 194 | 194 | pub const BUILDER_COOKIE_PREFIX: &str = "builder"; |
| 195 | 195 | |
| 196 | 196 | /// 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 | |
| 198 | 198 | /// 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 | |
| 200 | 200 | /// also name a school — a `person.` cookie is `401` on every school surface, |
| 201 | 201 | /// exactly like `builder.`. |
| 202 | 202 | pub const PERSON_COOKIE_PREFIX: &str = "person"; |
src/web/insights.rsmodified+9 -9
| @@ -213,9 +213,9 @@ async fn compute_student( | ||
| 213 | 213 | if !bridge.has_capability(AI_INSIGHT_STUDENT_CAPABILITY) { |
| 214 | 214 | return Ok(ai_unavailable("no AI service is connected right now")); |
| 215 | 215 | } |
| 216 | - let slug = tenant.slug.clone(); | |
| 216 | + let school = tenant.id; | |
| 217 | 217 | tokio::spawn(async move { |
| 218 | - match insight::compute_student(&bridge, &slug, &request).await { | |
| 218 | + match insight::compute_student(&bridge, &school, &request).await { | |
| 219 | 219 | Ok(answer) => tracing::info!( |
| 220 | 220 | "insight.student answered for {}: {} signal(s), {} recommendation(s)", |
| 221 | 221 | request.user_id, |
| @@ -286,10 +286,10 @@ async fn refresh( | ||
| 286 | 286 | return Ok(ai_unavailable("no AI service is connected right now")); |
| 287 | 287 | } |
| 288 | 288 | |
| 289 | - let slug = tenant.slug.clone(); | |
| 289 | + let school = tenant.id; | |
| 290 | 290 | tokio::spawn(async move { |
| 291 | 291 | let source = request.roster_source.clone(); |
| 292 | - match insight::refresh(&bridge, &slug, &request).await { | |
| 292 | + match insight::refresh(&bridge, &school, &request).await { | |
| 293 | 293 | Ok(answer) => tracing::info!( |
| 294 | 294 | "insight.refresh ({source} roster) answered: {} requested, {} computed, {} skipped, {} failed", |
| 295 | 295 | answer.requested.unwrap_or(0), |
| @@ -401,11 +401,11 @@ async fn generate_report( | ||
| 401 | 401 | return Ok(ai_unavailable("no AI service is connected right now")); |
| 402 | 402 | } |
| 403 | 403 | 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? | |
| 405 | 405 | else { |
| 406 | 406 | return Err(AppError::Internal(format!( |
| 407 | 407 | "the resolved school `{}` has no control row", |
| 408 | - tenant.slug.as_str() | |
| 408 | + tenant.id.as_str() | |
| 409 | 409 | ))); |
| 410 | 410 | }; |
| 411 | 411 | let request = ReportRequest { |
| @@ -419,7 +419,7 @@ async fn generate_report( | ||
| 419 | 419 | profiles: db::insight::all_profiles(&st.db).await?, |
| 420 | 420 | runs: db::insight::runs_for_report(&st.db, &run_day).await?, |
| 421 | 421 | }; |
| 422 | - let answer = match insight::report(&bridge, &tenant.slug, &request).await { | |
| 422 | + let answer = match insight::report(&bridge, &tenant.id, &request).await { | |
| 423 | 423 | Ok(answer) => answer, |
| 424 | 424 | Err(AiError::Remote { code, message }) => { |
| 425 | 425 | tracing::warn!("insight.report refused: {code}: {message}"); |
| @@ -842,7 +842,7 @@ async fn purge_departed( | ||
| 842 | 842 | )) |
| 843 | 843 | } |
| 844 | 844 | |
| 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 | |
| 846 | 846 | /// schedules over. |
| 847 | 847 | /// |
| 848 | 848 | /// This is the one operation of the family that is not school-scoped, and the |
| @@ -858,7 +858,7 @@ async fn purge_departed( | ||
| 858 | 858 | tag = "insights", |
| 859 | 859 | security(("session_cookie" = [])), |
| 860 | 860 | 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), | |
| 862 | 862 | (status = 401, description = "Not authenticated as a builder", body = ErrorResponse), |
| 863 | 863 | ), |
| 864 | 864 | )] |
src/web/limits.rsmodified+0 -11
| @@ -31,14 +31,6 @@ pub fn routes() -> OpenApiRouter<AppState> { | ||
| 31 | 31 | /// Account fields: credentials, profile, and the closed role set. |
| 32 | 32 | #[derive(Serialize, ToSchema)] |
| 33 | 33 | 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>, | |
| 42 | 34 | /// A school's display name, set by the vendor when the school is created. |
| 43 | 35 | max_school_name_len: usize, |
| 44 | 36 | min_username_len: usize, |
| @@ -536,9 +528,6 @@ impl LimitsResponse { | ||
| 536 | 528 | fn new(st: &AppState) -> Self { |
| 537 | 529 | Self { |
| 538 | 530 | 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(), | |
| 542 | 531 | max_school_name_len: MAX_SCHOOL_NAME_LEN, |
| 543 | 532 | min_username_len: MIN_USERNAME_LEN, |
| 544 | 533 | max_username_len: MAX_USERNAME_LEN, |
src/web/modules.rsmodified+1 -1
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | //! Module entitlements as data, on the school side of the line. |
| 2 | 2 | //! |
| 3 | 3 | //! 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 | |
| 5 | 5 | //! what a client needs to draw the product: the deployment's catalog (which |
| 6 | 6 | //! modules exist, what each one needs, how they are packaged) and the caller's |
| 7 | 7 | //! 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}; | ||
| 69 | 69 | use crate::service::course_note_file as note_files; |
| 70 | 70 | use crate::service::podcast_job as jobs; |
| 71 | 71 | use crate::state::AppState; |
| 72 | -use crate::web::tenant_state::{SchoolSlug, State}; | |
| 72 | +use crate::web::tenant_state::{SchoolIdCookie, State}; | |
| 73 | 73 | |
| 74 | 74 | use super::{CurrentUser, Page, PageParams, ai_unavailable, pump}; |
| 75 | 75 | |
| @@ -179,7 +179,7 @@ struct CancelVerdict { | ||
| 179 | 179 | )] |
| 180 | 180 | async fn submit( |
| 181 | 181 | State(st): State<AppState>, |
| 182 | - SchoolSlug(slug): SchoolSlug, | |
| 182 | + SchoolIdCookie(school): SchoolIdCookie, | |
| 183 | 183 | CurrentUser(user): CurrentUser, |
| 184 | 184 | Json(req): Json<SubmitPodcast>, |
| 185 | 185 | ) -> Result<Response, AppError> { |
| @@ -226,7 +226,7 @@ async fn submit( | ||
| 226 | 226 | format: req.format.clone(), |
| 227 | 227 | user_id: user.get_id().key(), |
| 228 | 228 | }; |
| 229 | - match podcast::submit(&bridge, &slug, payload).await { | |
| 229 | + match podcast::submit(&bridge, &school, payload).await { | |
| 230 | 230 | // The echo is checked, not trusted: this id is the only handle every |
| 231 | 231 | // later call uses, so an answer about some other job is a protocol |
| 232 | 232 | // failure, not a receipt. |
| @@ -556,7 +556,7 @@ async fn audio( | ||
| 556 | 556 | )] |
| 557 | 557 | async fn cancel( |
| 558 | 558 | State(st): State<AppState>, |
| 559 | - SchoolSlug(slug): SchoolSlug, | |
| 559 | + SchoolIdCookie(school): SchoolIdCookie, | |
| 560 | 560 | CurrentUser(user): CurrentUser, |
| 561 | 561 | Path(id): Path<String>, |
| 562 | 562 | ) -> Result<Response, AppError> { |
| @@ -582,7 +582,7 @@ async fn cancel( | ||
| 582 | 582 | }; |
| 583 | 583 | match podcast::cancel( |
| 584 | 584 | &bridge, |
| 585 | - &slug, | |
| 585 | + &school, | |
| 586 | 586 | PodcastCancelPayload { |
| 587 | 587 | job_id: job_id.clone(), |
| 588 | 588 | }, |
src/web/rag.rsmodified+9 -9
| @@ -43,7 +43,7 @@ | ||
| 43 | 43 | use std::time::Duration; |
| 44 | 44 | |
| 45 | 45 | use crate::tenant::ResolvedTenant; |
| 46 | -use crate::web::tenant_state::{SchoolSlug, State, TenantExt}; | |
| 46 | +use crate::web::tenant_state::{SchoolIdCookie, State, TenantExt}; | |
| 47 | 47 | use axum::Json; |
| 48 | 48 | use axum::extract::{Path, Query}; |
| 49 | 49 | use axum::http::StatusCode; |
| @@ -462,7 +462,7 @@ async fn list_messages( | ||
| 462 | 462 | )] |
| 463 | 463 | async fn send_message( |
| 464 | 464 | State(st): State<AppState>, |
| 465 | - SchoolSlug(slug): SchoolSlug, | |
| 465 | + SchoolIdCookie(school): SchoolIdCookie, | |
| 466 | 466 | tenant: ResolvedTenant, |
| 467 | 467 | CurrentUser(user): CurrentUser, |
| 468 | 468 | Path(id): Path<String>, |
| @@ -475,7 +475,7 @@ async fn send_message( | ||
| 475 | 475 | // Then the tier. Charged before anything is written, so a refused turn |
| 476 | 476 | // leaves no row behind. |
| 477 | 477 | 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()))?; | |
| 479 | 479 | |
| 480 | 480 | let settings = service::settings::load(&st.db).await?; |
| 481 | 481 | let reply_cap = content_cap(&settings); |
| @@ -538,7 +538,7 @@ async fn send_message( | ||
| 538 | 538 | // request was already resolved into, and one without the other is how |
| 539 | 539 | // an answer lands in the wrong school. |
| 540 | 540 | TenantExt { |
| 541 | - slug, | |
| 541 | + id: school, | |
| 542 | 542 | db: st.db.clone(), |
| 543 | 543 | modules: tenant.modules, |
| 544 | 544 | }, |
| @@ -619,7 +619,7 @@ async fn answer_turn( | ||
| 619 | 619 | let settled = match crate::ai::rag_chat::answer( |
| 620 | 620 | &db, |
| 621 | 621 | &bridge, |
| 622 | - &tenant.slug, | |
| 622 | + &tenant.id, | |
| 623 | 623 | &thread, |
| 624 | 624 | &fresh, |
| 625 | 625 | prompt.get_content().as_str().to_string(), |
| @@ -1107,7 +1107,7 @@ fn resolve_study_pair( | ||
| 1107 | 1107 | )] |
| 1108 | 1108 | async fn summarize( |
| 1109 | 1109 | State(st): State<AppState>, |
| 1110 | - SchoolSlug(slug): SchoolSlug, | |
| 1110 | + SchoolIdCookie(school): SchoolIdCookie, | |
| 1111 | 1111 | CurrentUser(user): CurrentUser, |
| 1112 | 1112 | Json(req): Json<StudyScopeRequest>, |
| 1113 | 1113 | ) -> Result<Response, AppError> { |
| @@ -1134,7 +1134,7 @@ async fn summarize( | ||
| 1134 | 1134 | asker_role: user.get_role().as_str().to_string(), |
| 1135 | 1135 | }; |
| 1136 | 1136 | |
| 1137 | - match rag_study::summarize(&bridge, &slug, payload).await { | |
| 1137 | + match rag_study::summarize(&bridge, &school, payload).await { | |
| 1138 | 1138 | Ok(reply) => Ok(Json(RagSummarizeResponse::from(reply)).into_response()), |
| 1139 | 1139 | Err(code) => Ok(failure(&code)), |
| 1140 | 1140 | } |
| @@ -1169,7 +1169,7 @@ async fn summarize( | ||
| 1169 | 1169 | )] |
| 1170 | 1170 | async fn questions( |
| 1171 | 1171 | State(st): State<AppState>, |
| 1172 | - SchoolSlug(slug): SchoolSlug, | |
| 1172 | + SchoolIdCookie(school): SchoolIdCookie, | |
| 1173 | 1173 | CurrentUser(user): CurrentUser, |
| 1174 | 1174 | Json(req): Json<QuestionsRequest>, |
| 1175 | 1175 | ) -> Result<Response, AppError> { |
| @@ -1199,7 +1199,7 @@ async fn questions( | ||
| 1199 | 1199 | seed_question: req.seed_question, |
| 1200 | 1200 | }; |
| 1201 | 1201 | |
| 1202 | - match rag_study::questions(&bridge, &slug, payload).await { | |
| 1202 | + match rag_study::questions(&bridge, &school, payload).await { | |
| 1203 | 1203 | Ok(reply) => Ok(Json(RagQuestionsResponse::from(reply)).into_response()), |
| 1204 | 1204 | Err(code) => Ok(failure(&code)), |
| 1205 | 1205 | } |
src/web/room.rsmodified+4 -3
| @@ -49,12 +49,13 @@ impl Connected { | ||
| 49 | 49 | /// `kind` is the room's telemetry name (`exam_room`, `board`), `id` a |
| 50 | 50 | /// **resource** id — the exam, the board — and never the person on the |
| 51 | 51 | /// 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 { | |
| 53 | 53 | metrics |
| 54 | 54 | .ws_connections |
| 55 | 55 | .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(); | |
| 58 | 59 | tracing::info!(kind, school, id, "websocket opened"); |
| 59 | 60 | Self { |
| 60 | 61 | metrics: metrics.clone(), |
src/web/school.rsmodified+4 -6
| @@ -2,8 +2,7 @@ | ||
| 2 | 2 | //! |
| 3 | 3 | //! `GET /schools` is the vendor registry and answers only a builder cookie. |
| 4 | 4 | //! 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. | |
| 7 | 6 | |
| 8 | 7 | use axum::Json; |
| 9 | 8 | use serde::Serialize; |
| @@ -23,8 +22,7 @@ pub fn routes() -> OpenApiRouter<AppState> { | ||
| 23 | 22 | |
| 24 | 23 | /// The school behind the session cookie. `id` is the registry uuid — the |
| 25 | 24 | /// 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. | |
| 28 | 26 | #[derive(Serialize, ToSchema)] |
| 29 | 27 | struct SchoolIdentity { |
| 30 | 28 | #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] |
| @@ -53,12 +51,12 @@ async fn current_school( | ||
| 53 | 51 | tenant: ResolvedTenant, |
| 54 | 52 | _user: CurrentUser, |
| 55 | 53 | ) -> Result<Json<SchoolIdentity>, AppError> { |
| 56 | - let school = School::read(&tenant.slug, st.tenants.control()) | |
| 54 | + let school = School::read(&tenant.id, st.tenants.control()) | |
| 57 | 55 | .await? |
| 58 | 56 | .ok_or_else(|| { |
| 59 | 57 | AppError::Internal(format!( |
| 60 | 58 | "the resolved school `{}` has no control row", |
| 61 | - tenant.slug | |
| 59 | + tenant.id | |
| 62 | 60 | )) |
| 63 | 61 | })?; |
| 64 | 62 | Ok(Json(SchoolIdentity { |
src/web/tenant_state.rsmodified+28 -28
| @@ -21,7 +21,7 @@ use crate::database::Database; | ||
| 21 | 21 | use crate::error::AppError; |
| 22 | 22 | use crate::module::ModuleSet; |
| 23 | 23 | use crate::state::AppState; |
| 24 | -use crate::tenant::{ResolvedTenant, Slug}; | |
| 24 | +use crate::tenant::{ResolvedTenant, SchoolId}; | |
| 25 | 25 | |
| 26 | 26 | /// The school a request has already been resolved into, injected as a request |
| 27 | 27 | /// extension by an in-process caller that has no cookie — today only the AI |
| @@ -30,16 +30,15 @@ use crate::tenant::{ResolvedTenant, Slug}; | ||
| 30 | 30 | /// [`crate::web::extractor::AiPrincipal`]. |
| 31 | 31 | #[derive(Clone)] |
| 32 | 32 | pub struct TenantExt { |
| 33 | - pub slug: Slug, | |
| 33 | + pub id: SchoolId, | |
| 34 | 34 | pub db: Database, |
| 35 | 35 | pub modules: ModuleSet, |
| 36 | 36 | } |
| 37 | 37 | |
| 38 | 38 | /// 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. | |
| 43 | 42 | pub fn split_cookie(value: &str) -> Option<(&str, &str)> { |
| 44 | 43 | let (prefix, token) = value.split_once('.')?; |
| 45 | 44 | (!prefix.is_empty() && !token.is_empty()).then_some((prefix, token)) |
| @@ -64,7 +63,7 @@ where | ||
| 64 | 63 | } |
| 65 | 64 | if let Some(tenant) = parts.extensions.get::<TenantExt>() { |
| 66 | 65 | return Ok(ResolvedTenant { |
| 67 | - slug: tenant.slug.clone(), | |
| 66 | + id: tenant.id, | |
| 68 | 67 | db: tenant.db.clone(), |
| 69 | 68 | modules: tenant.modules.clone(), |
| 70 | 69 | }); |
| @@ -77,16 +76,17 @@ where | ||
| 77 | 76 | // at all. Both are `401` here: the builder surface is a different extractor |
| 78 | 77 | // (`RequireBuilder`), and this one must never let it in. |
| 79 | 78 | 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)?; | |
| 81 | 80 | |
| 82 | 81 | let app = AppState::from_ref(state); |
| 83 | - let resolved = app.tenants.resolve(&slug).await?; | |
| 82 | + let resolved = app.tenants.resolve(&id).await?; | |
| 84 | 83 | // The one caller-derived label telemetry is allowed to carry: which school, |
| 85 | 84 | // 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()); | |
| 88 | 88 | if let Some(slot) = parts.extensions.get::<crate::telemetry::SchoolSlot>() { |
| 89 | - slot.set(slug.as_str()); | |
| 89 | + slot.set(&label); | |
| 90 | 90 | } |
| 91 | 91 | // Memoized on the request, not just returned: the next extractor on this |
| 92 | 92 | // same request (and the module gate ahead of both) reuses this verdict |
| @@ -115,7 +115,7 @@ where | ||
| 115 | 115 | let app = AppState::from_ref(state); |
| 116 | 116 | Ok(State(AppState { |
| 117 | 117 | 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), | |
| 119 | 119 | ..app |
| 120 | 120 | })) |
| 121 | 121 | } |
| @@ -138,9 +138,9 @@ where | ||
| 138 | 138 | |
| 139 | 139 | /// Just the school, for the handlers that need it as a key prefix (the exam |
| 140 | 140 | /// presence map, the whiteboard hub) rather than as a database handle. |
| 141 | -pub struct SchoolSlug(pub Slug); | |
| 141 | +pub struct SchoolIdCookie(pub SchoolId); | |
| 142 | 142 | |
| 143 | -impl<S> FromRequestParts<S> for SchoolSlug | |
| 143 | +impl<S> FromRequestParts<S> for SchoolIdCookie | |
| 144 | 144 | where |
| 145 | 145 | S: Send + Sync, |
| 146 | 146 | AppState: FromRef<S>, |
| @@ -148,15 +148,15 @@ where | ||
| 148 | 148 | type Rejection = AppError; |
| 149 | 149 | |
| 150 | 150 | 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)) | |
| 152 | 152 | } |
| 153 | 153 | } |
| 154 | 154 | |
| 155 | 155 | /// 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()) | |
| 160 | 160 | } |
| 161 | 161 | |
| 162 | 162 | #[cfg(test)] |
| @@ -171,7 +171,7 @@ mod tests { | ||
| 171 | 171 | use crate::database::init_test_tenants; |
| 172 | 172 | use crate::db::session; |
| 173 | 173 | use crate::domain::user::{Password, Username}; |
| 174 | - use crate::tenant::DEMO_SLUG; | |
| 174 | + use crate::tenant::DEMO_SCHOOL_ID; | |
| 175 | 175 | use crate::web::{CurrentUser, RequireBuilder}; |
| 176 | 176 | |
| 177 | 177 | async fn school_surface(State(_): State<AppState>, CurrentUser(_): CurrentUser) -> StatusCode { |
| @@ -187,7 +187,7 @@ mod tests { | ||
| 187 | 187 | async fn harness() -> (Router, String, String, crate::tenant::Tenants) { |
| 188 | 188 | let tenants = init_test_tenants().await; |
| 189 | 189 | let school = tenants |
| 190 | - .get(&Slug::try_new(DEMO_SLUG).unwrap()) | |
| 190 | + .get(&SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap()) | |
| 191 | 191 | .await |
| 192 | 192 | .expect("the demo school"); |
| 193 | 193 | |
| @@ -195,7 +195,7 @@ mod tests { | ||
| 195 | 195 | .await |
| 196 | 196 | .unwrap(); |
| 197 | 197 | 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()); | |
| 199 | 199 | |
| 200 | 200 | crate::service::builder::ensure( |
| 201 | 201 | tenants.control(), |
| @@ -273,7 +273,7 @@ mod tests { | ||
| 273 | 273 | |
| 274 | 274 | // A cookie with no school part names nothing resolvable — including the |
| 275 | 275 | // 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}."), ""); | |
| 277 | 277 | for uri in ["/school", "/builder"] { |
| 278 | 278 | assert_eq!( |
| 279 | 279 | status(&app, uri, Some(&bare)).await, |
| @@ -294,7 +294,7 @@ mod tests { | ||
| 294 | 294 | #[tokio::test] |
| 295 | 295 | async fn a_suspension_refuses_a_live_session() { |
| 296 | 296 | 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(); | |
| 298 | 298 | assert_eq!(status(&app, "/school", Some(&school)).await, StatusCode::OK); |
| 299 | 299 | |
| 300 | 300 | tenants |
| @@ -325,7 +325,7 @@ mod tests { | ||
| 325 | 325 | #[tokio::test] |
| 326 | 326 | async fn a_request_resolves_its_school_exactly_once() { |
| 327 | 327 | 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(); | |
| 329 | 329 | let state = AppState { |
| 330 | 330 | db: tenants.control().clone(), |
| 331 | 331 | tenants: tenants.clone(), |
| @@ -341,7 +341,7 @@ mod tests { | ||
| 341 | 341 | }; |
| 342 | 342 | let request = Request::builder() |
| 343 | 343 | .uri("/school") |
| 344 | - .header("cookie", format!("session={DEMO_SLUG}.whatever")) | |
| 344 | + .header("cookie", format!("session={DEMO_SCHOOL_ID}.whatever")) | |
| 345 | 345 | .body(Body::empty()) |
| 346 | 346 | .unwrap(); |
| 347 | 347 | let (mut parts, _) = request.into_parts(); |
| @@ -361,7 +361,7 @@ mod tests { | ||
| 361 | 361 | let second = resolve_tenant(&mut parts, &state) |
| 362 | 362 | .await |
| 363 | 363 | .expect("a second read would have seen the suspension and refused"); |
| 364 | - assert_eq!(second.slug, demo); | |
| 364 | + assert_eq!(second.id, demo); | |
| 365 | 365 | } |
| 366 | 366 | |
| 367 | 367 | #[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}; | |
| 2 | 2 | use axum::Json; |
| 3 | 3 | use axum::extract::{DefaultBodyLimit, Multipart, Path, Query}; |
| 4 | 4 | use axum::http::StatusCode; |
| @@ -416,7 +416,7 @@ struct CreateUser { | ||
| 416 | 416 | )] |
| 417 | 417 | async fn create_user( |
| 418 | 418 | State(st): State<AppState>, |
| 419 | - SchoolSlug(slug): SchoolSlug, | |
| 419 | + SchoolIdCookie(school): SchoolIdCookie, | |
| 420 | 420 | _admin: RequireAdmin, |
| 421 | 421 | Json(req): Json<CreateUser>, |
| 422 | 422 | ) -> Result<(StatusCode, Json<UserResponse>), AppError> { |
| @@ -467,7 +467,7 @@ async fn create_user( | ||
| 467 | 467 | student_number, |
| 468 | 468 | ) |
| 469 | 469 | .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?; | |
| 471 | 471 | Ok((StatusCode::CREATED, Json(UserResponse::new(&user)))) |
| 472 | 472 | } |
| 473 | 473 | |
| @@ -670,7 +670,7 @@ async fn update_user_preferences( | ||
| 670 | 670 | )] |
| 671 | 671 | async fn set_role( |
| 672 | 672 | State(st): State<AppState>, |
| 673 | - SchoolSlug(slug): SchoolSlug, | |
| 673 | + SchoolIdCookie(school): SchoolIdCookie, | |
| 674 | 674 | RequireAdmin(admin): RequireAdmin, |
| 675 | 675 | Path(id): Path<String>, |
| 676 | 676 | Json(req): Json<SetRole>, |
| @@ -695,7 +695,7 @@ async fn set_role( | ||
| 695 | 695 | // stroke came back refused. |
| 696 | 696 | for board in boards { |
| 697 | 697 | st.board_hub.publish( |
| 698 | - &slug, | |
| 698 | + &school, | |
| 699 | 699 | board.get_id().key().as_str(), |
| 700 | 700 | json!({ |
| 701 | 701 | "type": "participants", |
| @@ -710,7 +710,7 @@ async fn set_role( | ||
| 710 | 710 | ); |
| 711 | 711 | if let Some(closed_at) = board.get_closed_at() { |
| 712 | 712 | st.board_hub.publish( |
| 713 | - &slug, | |
| 713 | + &school, | |
| 714 | 714 | board.get_id().key().as_str(), |
| 715 | 715 | json!({"type": "closed", "closed_at": closed_at.as_millis()}).to_string(), |
| 716 | 716 | ); |
tests/ai_bridge.rsmodified+48 -53
| @@ -19,7 +19,7 @@ use hezarfen_backend::ai::protocol::{ | ||
| 19 | 19 | use hezarfen_backend::ai::{AiBridge, AiError, BridgeConfig}; |
| 20 | 20 | use hezarfen_backend::constant::{AI_ALPN, AI_MAX_CONCURRENT_PER_WORKER, AI_PROTOCOL}; |
| 21 | 21 | use hezarfen_backend::module::ModuleSet; |
| 22 | -use hezarfen_backend::tenant::{DEMO_SLUG, Slug}; | |
| 22 | +use hezarfen_backend::tenant::{DEMO_SCHOOL_ID, SchoolId}; | |
| 23 | 23 | use serde_json::{Value, json}; |
| 24 | 24 | |
| 25 | 25 | const TOKEN: &str = "shared-ai-token"; |
| @@ -71,8 +71,8 @@ fn client_endpoint(bridge: &AiBridge) -> quinn::Endpoint { | ||
| 71 | 71 | } |
| 72 | 72 | |
| 73 | 73 | /// 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") | |
| 76 | 76 | } |
| 77 | 77 | |
| 78 | 78 | fn hello(service: &str, capabilities: &[&str]) -> Hello { |
| @@ -1519,7 +1519,7 @@ async fn api_read(conn: &quinn::Connection, request: ApiRequest) -> ApiResponse | ||
| 1519 | 1519 | |
| 1520 | 1520 | /// A `GET` of `path` as `on_behalf_of` (or as the service itself). |
| 1521 | 1521 | 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) | |
| 1523 | 1523 | } |
| 1524 | 1524 | |
| 1525 | 1525 | /// 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 | ||
| 1841 | 1841 | await_workers(&bridge, 1).await; |
| 1842 | 1842 | |
| 1843 | 1843 | 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(); | |
| 1845 | 1845 | let beta_db = tenants |
| 1846 | 1846 | .create( |
| 1847 | - hezarfen_backend::tenant::SchoolId::generate(), | |
| 1848 | - &beta, | |
| 1847 | + beta, | |
| 1849 | 1848 | "Beta College", |
| 1850 | 1849 | ModuleSet::all(), |
| 1851 | 1850 | ) |
| @@ -1874,7 +1873,7 @@ async fn an_index_dispatch_names_the_notes_own_school_and_stores_the_answer_ther | ||
| 1874 | 1873 | ); |
| 1875 | 1874 | |
| 1876 | 1875 | 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"); | |
| 1878 | 1877 | assert_eq!(seen[0].payload["course_note"], note); |
| 1879 | 1878 | } |
| 1880 | 1879 | |
| @@ -1900,7 +1899,7 @@ async fn a_course_note_is_indexed_and_its_output_stored_with_its_sources() { | ||
| 1900 | 1899 | let seen = service.seen(); |
| 1901 | 1900 | assert_eq!(seen[0].capability, AI_RAG_INDEX_CAPABILITY); |
| 1902 | 1901 | assert_eq!( |
| 1903 | - seen[0].school, DEMO_SLUG, | |
| 1902 | + seen[0].school, DEMO_SCHOOL_ID, | |
| 1904 | 1903 | "the frame names the caller's school" |
| 1905 | 1904 | ); |
| 1906 | 1905 | 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() { | ||
| 2053 | 2052 | |
| 2054 | 2053 | let request = ApiRequest { |
| 2055 | 2054 | id: "trace-course-notes".into(), |
| 2056 | - school: DEMO_SLUG.into(), | |
| 2055 | + school: DEMO_SCHOOL_ID.into(), | |
| 2057 | 2056 | path: "/course-notes".into(), |
| 2058 | 2057 | query: Some(format!("course={course}")), |
| 2059 | 2058 | on_behalf_of: Some(student), |
| @@ -2081,7 +2080,7 @@ async fn a_course_the_student_is_not_in_is_refused_by_the_handler() { | ||
| 2081 | 2080 | |
| 2082 | 2081 | let request = ApiRequest { |
| 2083 | 2082 | id: "trace-foreign-course".into(), |
| 2084 | - school: DEMO_SLUG.into(), | |
| 2083 | + school: DEMO_SCHOOL_ID.into(), | |
| 2085 | 2084 | path: "/course-notes".into(), |
| 2086 | 2085 | query: Some(format!("course={foreign}")), |
| 2087 | 2086 | on_behalf_of: Some(student), |
| @@ -2101,7 +2100,7 @@ async fn writing_a_course_note_is_refused_before_dispatch() { | ||
| 2101 | 2100 | |
| 2102 | 2101 | let request = ApiRequest { |
| 2103 | 2102 | id: "trace-post".into(), |
| 2104 | - school: DEMO_SLUG.into(), | |
| 2103 | + school: DEMO_SCHOOL_ID.into(), | |
| 2105 | 2104 | path: "/course-notes".into(), |
| 2106 | 2105 | query: None, |
| 2107 | 2106 | on_behalf_of: None, |
| @@ -2170,7 +2169,7 @@ async fn blob_read(conn: &quinn::Connection, request: BlobRequest) -> (BlobRespo | ||
| 2170 | 2169 | } |
| 2171 | 2170 | |
| 2172 | 2171 | 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) | |
| 2174 | 2173 | } |
| 2175 | 2174 | |
| 2176 | 2175 | /// 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() | ||
| 2228 | 2227 | panic!("the enrolled student was refused: {}", blob_refusal(header)); |
| 2229 | 2228 | }; |
| 2230 | 2229 | 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"); | |
| 2232 | 2231 | assert_eq!(name, "recap.pdf"); |
| 2233 | 2232 | assert_eq!(content_type, "application/pdf"); |
| 2234 | 2233 | 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() | ||
| 2752 | 2751 | }); |
| 2753 | 2752 | let attrs = attrs_of(request); |
| 2754 | 2753 | assert!( |
| 2755 | - attrs.contains(&("school".to_string(), DEMO_SLUG.to_string())), | |
| 2754 | + attrs.contains(&("school".to_string(), DEMO_SCHOOL_ID.to_string())), | |
| 2756 | 2755 | "the span names the school slug: {attrs:?}" |
| 2757 | 2756 | ); |
| 2758 | 2757 | assert!( |
| @@ -3061,7 +3060,7 @@ async fn no_rag_worker_means_503_and_no_rows() { | ||
| 3061 | 3060 | #[tokio::test] |
| 3062 | 3061 | async fn a_school_without_the_chatbot_module_has_no_rag_nest() { |
| 3063 | 3062 | 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(); | |
| 3065 | 3064 | let cookie = common::login_as(&app, &db, "ada", "admin").await; |
| 3066 | 3065 | |
| 3067 | 3066 | 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() { | ||
| 3483 | 3482 | let seen = service.seen(); |
| 3484 | 3483 | assert_eq!(seen.len(), 1, "one dispatch per call, never a re-send"); |
| 3485 | 3484 | 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"); | |
| 3487 | 3486 | let payload = &seen[0].payload; |
| 3488 | 3487 | assert_eq!(payload["asker"], student); |
| 3489 | 3488 | assert_eq!(payload["asker_role"], "student"); |
| @@ -3844,7 +3843,7 @@ async fn an_insight_student_dispatch_names_the_school_and_round_trips() { | ||
| 3844 | 3843 | let seen = await_seen(&service, 1).await; |
| 3845 | 3844 | assert_eq!(seen.len(), 1, "one dispatch per request, never a re-send"); |
| 3846 | 3845 | 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"); | |
| 3848 | 3847 | assert_eq!(seen[0].payload["user_id"], ali); |
| 3849 | 3848 | |
| 3850 | 3849 | // The same worker driven directly answers the contract's shape, so the |
| @@ -4292,7 +4291,6 @@ use hezarfen_backend::constant::{ | ||
| 4292 | 4291 | }; |
| 4293 | 4292 | use hezarfen_backend::domain::user::{Password, Username}; |
| 4294 | 4293 | use hezarfen_backend::service::builder; |
| 4295 | -use hezarfen_backend::tenant::SchoolId; | |
| 4296 | 4294 | |
| 4297 | 4295 | /// One capability call: a fresh client-initiated stream, one frame out, one |
| 4298 | 4296 | /// back, stream dropped — the same lifecycle as `api_read` above. |
| @@ -4308,10 +4306,10 @@ async fn capability_call( | ||
| 4308 | 4306 | frame_or_fail(&mut recv, "read CapabilityResponse").await |
| 4309 | 4307 | } |
| 4310 | 4308 | |
| 4311 | -fn insight_call(capability: &str, school: &str, payload: Value) -> CapabilityRequest { | |
| 4309 | +fn insight_call(capability: &str, school: impl AsRef<str>, payload: Value) -> CapabilityRequest { | |
| 4312 | 4310 | CapabilityRequest { |
| 4313 | 4311 | id: format!("trace-{capability}"), |
| 4314 | - school: school.to_string(), | |
| 4312 | + school: school.as_ref().to_string(), | |
| 4315 | 4313 | capability: capability.to_string(), |
| 4316 | 4314 | payload, |
| 4317 | 4315 | } |
| @@ -4383,7 +4381,7 @@ async fn a_capability_call_writes_the_row_the_schools_own_read_door_serves() { | ||
| 4383 | 4381 | &service.conn, |
| 4384 | 4382 | insight_call( |
| 4385 | 4383 | AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY, |
| 4386 | - DEMO_SLUG, | |
| 4384 | + DEMO_SCHOOL_ID, | |
| 4387 | 4385 | summary_payload(&student, 1_800_000_000_000i64), |
| 4388 | 4386 | ), |
| 4389 | 4387 | ) |
| @@ -4398,7 +4396,7 @@ async fn a_capability_call_writes_the_row_the_schools_own_read_door_serves() { | ||
| 4398 | 4396 | }; |
| 4399 | 4397 | assert_eq!(id, format!("trace-{AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY}")); |
| 4400 | 4398 | assert_eq!( |
| 4401 | - school, DEMO_SLUG, | |
| 4399 | + school, DEMO_SCHOOL_ID, | |
| 4402 | 4400 | "the answer echoes the school the frame named" |
| 4403 | 4401 | ); |
| 4404 | 4402 | assert_eq!(payload["written"], 1); |
| @@ -4428,7 +4426,7 @@ async fn the_insight_ledger_and_pending_list_round_trip_over_the_bridge() { | ||
| 4428 | 4426 | |
| 4429 | 4427 | let run = insight_call( |
| 4430 | 4428 | AI_INSIGHT_RUN_UPSERT_CAPABILITY, |
| 4431 | - DEMO_SLUG, | |
| 4429 | + DEMO_SCHOOL_ID, | |
| 4432 | 4430 | json!({ "run": { |
| 4433 | 4431 | "run_day": "2026-09-17", |
| 4434 | 4432 | "started_at": 1_700_000_000_000i64, |
| @@ -4453,7 +4451,7 @@ async fn the_insight_ledger_and_pending_list_round_trip_over_the_bridge() { | ||
| 4453 | 4451 | let pending = ok_capability( |
| 4454 | 4452 | capability_call( |
| 4455 | 4453 | &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!({})), | |
| 4457 | 4455 | ) |
| 4458 | 4456 | .await, |
| 4459 | 4457 | ); |
| @@ -4463,7 +4461,7 @@ async fn the_insight_ledger_and_pending_list_round_trip_over_the_bridge() { | ||
| 4463 | 4461 | // CHECK violation dressed as a server fault. |
| 4464 | 4462 | let bad_day = insight_call( |
| 4465 | 4463 | AI_INSIGHT_RUN_UPSERT_CAPABILITY, |
| 4466 | - DEMO_SLUG, | |
| 4464 | + DEMO_SCHOOL_ID, | |
| 4467 | 4465 | json!({ "run": { |
| 4468 | 4466 | "run_day": "17.09.2026", |
| 4469 | 4467 | "started_at": 1, |
| @@ -4489,7 +4487,7 @@ async fn the_sweep_and_purge_capabilities_answer_per_table_verdicts() { | ||
| 4489 | 4487 | &service.conn, |
| 4490 | 4488 | insight_call( |
| 4491 | 4489 | AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY, |
| 4492 | - DEMO_SLUG, | |
| 4490 | + DEMO_SCHOOL_ID, | |
| 4493 | 4491 | summary_payload(&student, 1), // long past |
| 4494 | 4492 | ), |
| 4495 | 4493 | ) |
| @@ -4499,7 +4497,7 @@ async fn the_sweep_and_purge_capabilities_answer_per_table_verdicts() { | ||
| 4499 | 4497 | let verdicts = ok_capability( |
| 4500 | 4498 | capability_call( |
| 4501 | 4499 | &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!({})), | |
| 4503 | 4501 | ) |
| 4504 | 4502 | .await, |
| 4505 | 4503 | ); |
| @@ -4510,7 +4508,7 @@ async fn the_sweep_and_purge_capabilities_answer_per_table_verdicts() { | ||
| 4510 | 4508 | // obeyed, it would delete every student's derived rows in one call. |
| 4511 | 4509 | let empty = insight_call( |
| 4512 | 4510 | "insight.departed.purge", |
| 4513 | - DEMO_SLUG, | |
| 4511 | + DEMO_SCHOOL_ID, | |
| 4514 | 4512 | json!({ "students": [] }), |
| 4515 | 4513 | ); |
| 4516 | 4514 | let (code, _) = refused_capability(capability_call(&service.conn, empty).await); |
| @@ -4531,11 +4529,10 @@ async fn a_capability_call_cannot_touch_another_schools_rows() { | ||
| 4531 | 4529 | let _mudur = common::login_as(&app, &demo_db, "mudur", "manager").await; |
| 4532 | 4530 | let ayse = common::login_as(&app, &demo_db, "ayse", "student").await; |
| 4533 | 4531 | 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(); | |
| 4535 | 4533 | let beta_db = tenants |
| 4536 | 4534 | .create( |
| 4537 | - SchoolId::generate(), | |
| 4538 | - &beta, | |
| 4535 | + SchoolId::try_parse(hezarfen_backend::tenant::BETA_SCHOOL_ID).unwrap(), | |
| 4539 | 4536 | "Beta College", |
| 4540 | 4537 | ModuleSet::all(), |
| 4541 | 4538 | ) |
| @@ -4578,7 +4575,7 @@ async fn a_capability_call_refuses_unknown_names_and_payloads_that_do_not_fit() | ||
| 4578 | 4575 | // would make this a generic door is the shape that is missing. |
| 4579 | 4576 | let unknown = insight_call( |
| 4580 | 4577 | "insight.database.query", |
| 4581 | - DEMO_SLUG, | |
| 4578 | + DEMO_SCHOOL_ID, | |
| 4582 | 4579 | json!({ "sql": "SELECT 1" }), |
| 4583 | 4580 | ); |
| 4584 | 4581 | 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() | ||
| 4588 | 4585 | // A payload that does not fit the operation's contract. |
| 4589 | 4586 | let bad = insight_call( |
| 4590 | 4587 | AI_INSIGHT_SUMMARY_UPSERT_CAPABILITY, |
| 4591 | - DEMO_SLUG, | |
| 4588 | + DEMO_SCHOOL_ID, | |
| 4592 | 4589 | json!({ "rows": [{ "student": "not-a-uuid", "confidence": "stable", |
| 4593 | 4590 | "computed_at": 1, "retain_until": 2 }] }), |
| 4594 | 4591 | ); |
| @@ -4617,11 +4614,10 @@ async fn the_school_directory_is_the_one_deployment_scoped_operation() { | ||
| 4617 | 4614 | .await; |
| 4618 | 4615 | await_workers(&bridge, 1).await; |
| 4619 | 4616 | 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(); | |
| 4621 | 4618 | tenants |
| 4622 | 4619 | .create( |
| 4623 | - SchoolId::generate(), | |
| 4624 | - &beta, | |
| 4620 | + beta, | |
| 4625 | 4621 | "Beta College", |
| 4626 | 4622 | ModuleSet::all(), |
| 4627 | 4623 | ) |
| @@ -4642,7 +4638,7 @@ async fn the_school_directory_is_the_one_deployment_scoped_operation() { | ||
| 4642 | 4638 | .iter() |
| 4643 | 4639 | .map(|s| s.as_str().expect("slug")) |
| 4644 | 4640 | .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"); | |
| 4646 | 4642 | |
| 4647 | 4643 | // Over HTTP the same operation is the builder's: a school session must |
| 4648 | 4644 | // 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() { | ||
| 4926 | 4922 | |
| 4927 | 4923 | let answer = capability_call( |
| 4928 | 4924 | conn, |
| 4929 | - report_call(DEMO_SLUG, &job, &user, "running", "script", 0.5), | |
| 4925 | + report_call(DEMO_SCHOOL_ID, &job, &user, "running", "script", 0.5), | |
| 4930 | 4926 | ) |
| 4931 | 4927 | .await; |
| 4932 | 4928 | 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() { | ||
| 4938 | 4934 | let (code, _) = refused_capability( |
| 4939 | 4935 | capability_call( |
| 4940 | 4936 | conn, |
| 4941 | - report_call(DEMO_SLUG, &job, &user, "done", "done", 1.0), | |
| 4937 | + report_call(DEMO_SCHOOL_ID, &job, &user, "done", "done", 1.0), | |
| 4942 | 4938 | ) |
| 4943 | 4939 | .await, |
| 4944 | 4940 | ); |
| @@ -4950,7 +4946,7 @@ async fn the_report_and_upload_handshake_lands_on_the_backends_own_row() { | ||
| 4950 | 4946 | capability_call( |
| 4951 | 4947 | conn, |
| 4952 | 4948 | report_call( |
| 4953 | - DEMO_SLUG, | |
| 4949 | + DEMO_SCHOOL_ID, | |
| 4954 | 4950 | &job, |
| 4955 | 4951 | "00000000-0000-7000-8000-000000000000", |
| 4956 | 4952 | "failed", |
| @@ -4963,7 +4959,7 @@ async fn the_report_and_upload_handshake_lands_on_the_backends_own_row() { | ||
| 4963 | 4959 | assert_eq!(code, "not_permitted"); |
| 4964 | 4960 | // And so is a transition the service's own table forbids. |
| 4965 | 4961 | 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, | |
| 4967 | 4963 | ); |
| 4968 | 4964 | assert_eq!(code, "invalid_payload"); |
| 4969 | 4965 | 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() { | ||
| 4972 | 4968 | // stamped with the reference and the duration. |
| 4973 | 4969 | let body = blob_bytes(200 * 1024); |
| 4974 | 4970 | 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); | |
| 4976 | 4972 | assert_eq!(size, body.len() as u64); |
| 4977 | 4973 | 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); | |
| 4979 | 4975 | assert_eq!(std::fs::read(&stored).expect("the stored episode"), body); |
| 4980 | 4976 | let row = podcast_row(&db, &job).await; |
| 4981 | 4977 | 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() { | ||
| 4986 | 4982 | ok_capability( |
| 4987 | 4983 | capability_call( |
| 4988 | 4984 | conn, |
| 4989 | - report_call(DEMO_SLUG, &job, &user, "done", "done", 1.0) | |
| 4985 | + report_call(DEMO_SCHOOL_ID, &job, &user, "done", "done", 1.0) | |
| 4990 | 4986 | ) |
| 4991 | 4987 | .await |
| 4992 | 4988 | )["stored"], |
| @@ -4999,7 +4995,7 @@ async fn the_report_and_upload_handshake_lands_on_the_backends_own_row() { | ||
| 4999 | 4995 | let (code, _) = refused_capability( |
| 5000 | 4996 | capability_call( |
| 5001 | 4997 | conn, |
| 5002 | - report_call(DEMO_SLUG, &stranger, &user, "running", "ocr", 0.1), | |
| 4998 | + report_call(DEMO_SCHOOL_ID, &stranger, &user, "running", "ocr", 0.1), | |
| 5003 | 4999 | ) |
| 5004 | 5000 | .await, |
| 5005 | 5001 | ); |
| @@ -5019,11 +5015,10 @@ async fn a_report_or_upload_cannot_reach_another_schools_job() { | ||
| 5019 | 5015 | .await; |
| 5020 | 5016 | await_workers(&bridge, 1).await; |
| 5021 | 5017 | 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(); | |
| 5023 | 5019 | let beta_db = tenants |
| 5024 | 5020 | .create( |
| 5025 | - hezarfen_backend::tenant::SchoolId::generate(), | |
| 5026 | - &beta, | |
| 5021 | + beta, | |
| 5027 | 5022 | "Beta College", |
| 5028 | 5023 | ModuleSet::all(), |
| 5029 | 5024 | ) |
| @@ -5034,7 +5029,7 @@ async fn a_report_or_upload_cannot_reach_another_schools_job() { | ||
| 5034 | 5029 | let (code, _) = refused_capability( |
| 5035 | 5030 | capability_call( |
| 5036 | 5031 | &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), | |
| 5038 | 5033 | ) |
| 5039 | 5034 | .await, |
| 5040 | 5035 | ); |
| @@ -5049,7 +5044,7 @@ async fn a_report_or_upload_cannot_reach_another_schools_job() { | ||
| 5049 | 5044 | let (code, _) = upload_refusal( |
| 5050 | 5045 | podcast_upload( |
| 5051 | 5046 | &service.conn, |
| 5052 | - DEMO_SLUG, | |
| 5047 | + DEMO_SCHOOL_ID, | |
| 5053 | 5048 | &job, |
| 5054 | 5049 | "bolum.mp3", |
| 5055 | 5050 | "audio/mpeg", |
| @@ -5059,7 +5054,7 @@ async fn a_report_or_upload_cannot_reach_another_schools_job() { | ||
| 5059 | 5054 | ); |
| 5060 | 5055 | assert_eq!(code, "unknown_job"); |
| 5061 | 5056 | let leaked = common::files_dir() |
| 5062 | - .join(DEMO_SLUG) | |
| 5057 | + .join(DEMO_SCHOOL_ID) | |
| 5063 | 5058 | .join(format!("podcast/{job}.mp3")); |
| 5064 | 5059 | assert!( |
| 5065 | 5060 | !leaked.exists(), |
| @@ -5091,7 +5086,7 @@ async fn an_upload_past_the_audio_ceiling_is_refused_before_a_byte_is_read() { | ||
| 5091 | 5086 | let request = BlobUploadRequest { |
| 5092 | 5087 | id: "trace-oversize".to_string(), |
| 5093 | 5088 | upload: true, |
| 5094 | - school: DEMO_SLUG.to_string(), | |
| 5089 | + school: DEMO_SCHOOL_ID.to_string(), | |
| 5095 | 5090 | job_id: job.clone(), |
| 5096 | 5091 | name: "bolum.mp3".to_string(), |
| 5097 | 5092 | content_type: "audio/mpeg".to_string(), |
tests/ai_protocol.rsmodified+28 -29
| @@ -24,14 +24,14 @@ use std::time::Duration; | ||
| 24 | 24 | |
| 25 | 25 | use hezarfen_backend::ai::{AiBridge, AiError, BridgeConfig}; |
| 26 | 26 | use hezarfen_backend::module::ModuleSet; |
| 27 | -use hezarfen_backend::tenant::{SchoolStatus, Slug, Tenants}; | |
| 27 | +use hezarfen_backend::tenant::{SchoolStatus, SchoolId, Tenants}; | |
| 28 | 28 | use serde_json::{Value, json}; |
| 29 | 29 | |
| 30 | 30 | const TOKEN: &str = "shared-ai-token"; |
| 31 | 31 | |
| 32 | 32 | /// The school every frame in this suite names. A literal for the same reason |
| 33 | 33 | /// `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"; | |
| 35 | 35 | |
| 36 | 36 | /// The protocol identifier this suite pins. Deliberately a literal, not |
| 37 | 37 | /// `AI_PROTOCOL`: importing the constant would let a rename sail through, and |
| @@ -269,7 +269,7 @@ fn dispatch( | ||
| 269 | 269 | ) -> tokio::task::JoinHandle<Result<Value, AiError>> { |
| 270 | 270 | let bridge = bridge.clone(); |
| 271 | 271 | 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"); | |
| 273 | 273 | tokio::spawn(async move { bridge.dispatch(&school, &capability, payload).await }) |
| 274 | 274 | } |
| 275 | 275 | |
| @@ -814,7 +814,7 @@ async fn closing_the_control_stream_deregisters_the_service() { | ||
| 814 | 814 | assert!(matches!( |
| 815 | 815 | bridge |
| 816 | 816 | .dispatch( |
| 817 | - &hezarfen_backend::tenant::Slug::try_new(SCHOOL).unwrap(), | |
| 817 | + &hezarfen_backend::tenant::SchoolId::try_parse(SCHOOL).unwrap(), | |
| 818 | 818 | "ocr.extract", |
| 819 | 819 | json!(null) |
| 820 | 820 | ) |
| @@ -967,7 +967,7 @@ async fn a_chat_request_names_the_askers_school_role() { | ||
| 967 | 967 | |
| 968 | 968 | let tenants = hezarfen_backend::database::init_test_tenants().await; |
| 969 | 969 | 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()) | |
| 971 | 971 | .await |
| 972 | 972 | .expect("the demo school"); |
| 973 | 973 | 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() { | ||
| 1179 | 1179 | |
| 1180 | 1180 | let (answer, _) = raw::api_read( |
| 1181 | 1181 | &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}"#, | |
| 1183 | 1183 | ) |
| 1184 | 1184 | .await; |
| 1185 | 1185 | assert_eq!(answer["outcome"], "ok", "{answer}"); |
| @@ -1201,43 +1201,43 @@ async fn the_api_refusal_frame_carries_exactly_the_published_keys_and_codes() { | ||
| 1201 | 1201 | let cases = [ |
| 1202 | 1202 | ( |
| 1203 | 1203 | "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(), | |
| 1205 | 1205 | ), |
| 1206 | 1206 | ( |
| 1207 | 1207 | "method_not_allowed", |
| 1208 | 1208 | // 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(), | |
| 1210 | 1210 | ), |
| 1211 | 1211 | ( |
| 1212 | 1212 | "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(), | |
| 1214 | 1214 | ), |
| 1215 | 1215 | ( |
| 1216 | 1216 | // Order pin: both refusals apply, the method one wins. |
| 1217 | 1217 | "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(), | |
| 1219 | 1219 | ), |
| 1220 | 1220 | ( |
| 1221 | 1221 | "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"}"# | |
| 1223 | 1223 | .to_string(), |
| 1224 | 1224 | ), |
| 1225 | 1225 | ( |
| 1226 | 1226 | "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(), | |
| 1228 | 1228 | ), |
| 1229 | 1229 | // A frame that names no school at all: required, never defaulted. |
| 1230 | 1230 | ("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). | |
| 1233 | 1233 | ( |
| 1234 | - "malformed", | |
| 1234 | + "unknown_school", | |
| 1235 | 1235 | r#"{"id":"t8","school":"NOT A SLUG","path":"/auth/me"}"#.to_string(), |
| 1236 | 1236 | ), |
| 1237 | - // A well-formed slug this deployment does not serve. | |
| 1237 | + // A hyphenated uuid this deployment does not serve. | |
| 1238 | 1238 | ( |
| 1239 | 1239 | "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(), | |
| 1241 | 1241 | ), |
| 1242 | 1242 | ]; |
| 1243 | 1243 | |
| @@ -1304,8 +1304,7 @@ async fn two_schools(bridge: &AiBridge) -> (axum::Router, Tenants, String, Strin | ||
| 1304 | 1304 | let (app, demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await; |
| 1305 | 1305 | let beta_db = tenants |
| 1306 | 1306 | .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(), | |
| 1309 | 1308 | "Beta College", |
| 1310 | 1309 | ModuleSet::all(), |
| 1311 | 1310 | ) |
| @@ -1334,7 +1333,7 @@ async fn an_api_read_answers_out_of_the_school_the_frame_named() { | ||
| 1334 | 1333 | await_workers(&bridge, 1).await; |
| 1335 | 1334 | let (_app, _tenants, demo_ayse, beta_ayse) = two_schools(&bridge).await; |
| 1336 | 1335 | |
| 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)] { | |
| 1338 | 1337 | let (answer, _) = raw::api_read( |
| 1339 | 1338 | &service.conn, |
| 1340 | 1339 | format!( |
| @@ -1350,7 +1349,7 @@ async fn an_api_read_answers_out_of_the_school_the_frame_named() { | ||
| 1350 | 1349 | } |
| 1351 | 1350 | |
| 1352 | 1351 | // 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)] { | |
| 1354 | 1353 | let (answer, _) = raw::api_read( |
| 1355 | 1354 | &service.conn, |
| 1356 | 1355 | format!( |
| @@ -1376,13 +1375,13 @@ async fn a_suspended_school_is_refused_with_its_own_code() { | ||
| 1376 | 1375 | let (_app, tenants, _demo_ayse, beta_ayse) = two_schools(&bridge).await; |
| 1377 | 1376 | |
| 1378 | 1377 | 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}"}}"# | |
| 1380 | 1379 | ); |
| 1381 | 1380 | let (answer, _) = raw::api_read(&service.conn, read.as_bytes()).await; |
| 1382 | 1381 | assert_eq!(answer["outcome"], "ok", "the school starts out active"); |
| 1383 | 1382 | |
| 1384 | 1383 | 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) | |
| 1386 | 1385 | .await |
| 1387 | 1386 | .expect("suspend beta"); |
| 1388 | 1387 | |
| @@ -1390,7 +1389,7 @@ async fn a_suspended_school_is_refused_with_its_own_code() { | ||
| 1390 | 1389 | assert_eq!(answer["outcome"], "err", "{answer}"); |
| 1391 | 1390 | assert_eq!(answer["code"], "school_suspended", "{answer}"); |
| 1392 | 1391 | assert_eq!( |
| 1393 | - answer["school"], "beta", | |
| 1392 | + answer["school"], "019732e3-7b00-7000-8000-00000000beef", | |
| 1394 | 1393 | "the refusal names the school back" |
| 1395 | 1394 | ); |
| 1396 | 1395 | assert_eq!(answer["id"], "t-susp"); |
| @@ -1398,7 +1397,7 @@ async fn a_suspended_school_is_refused_with_its_own_code() { | ||
| 1398 | 1397 | // The demo school is untouched by its neighbour's suspension. |
| 1399 | 1398 | let (answer, _) = raw::api_read( |
| 1400 | 1399 | &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"}"#, | |
| 1402 | 1401 | ) |
| 1403 | 1402 | .await; |
| 1404 | 1403 | assert_eq!(answer["outcome"], "ok", "{answer}"); |
| @@ -1424,7 +1423,7 @@ async fn a_blob_read_names_its_school_too() { | ||
| 1424 | 1423 | assert_eq!(header["status"], "ok", "{header}"); |
| 1425 | 1424 | assert_eq!(body.len(), uploaded.len()); |
| 1426 | 1425 | |
| 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")] { | |
| 1428 | 1427 | let (header, _, body) = raw::blob_read( |
| 1429 | 1428 | &service.conn, |
| 1430 | 1429 | format!( |
| @@ -1575,7 +1574,7 @@ async fn a_blob_refusal_frame_carries_exactly_the_published_keys_and_no_bytes() | ||
| 1575 | 1574 | let mut modules = ModuleSet::all(); |
| 1576 | 1575 | modules.remove(hezarfen_backend::module::Module::CourseNotes); |
| 1577 | 1576 | tenants |
| 1578 | - .set_modules(&Slug::try_new(SCHOOL).unwrap(), &modules) | |
| 1577 | + .set_modules(&SchoolId::try_parse(SCHOOL).unwrap(), &modules) | |
| 1579 | 1578 | .await |
| 1580 | 1579 | .expect("take course_notes off the demo school"); |
| 1581 | 1580 | |
| @@ -1637,7 +1636,7 @@ async fn an_api_read_still_answers_on_the_shared_client_stream_path() { | ||
| 1637 | 1636 | assert_eq!(answer["status"], 200); |
| 1638 | 1637 | |
| 1639 | 1638 | // 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; | |
| 1641 | 1640 | assert_eq!(answer["outcome"], "err", "{answer}"); |
| 1642 | 1641 | assert_eq!(answer["code"], "malformed"); |
| 1643 | 1642 | assert_eq!(answer["id"], "t-neither"); |
| @@ -1744,7 +1743,7 @@ async fn the_capability_shape_does_not_steal_the_shapes_that_existed_before() { | ||
| 1744 | 1743 | assert_eq!(answer["payload"]["students"], json!([]), "{answer}"); |
| 1745 | 1744 | |
| 1746 | 1745 | // 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; | |
| 1748 | 1747 | assert_eq!(answer["outcome"], "err", "{answer}"); |
| 1749 | 1748 | assert_eq!(answer["code"], "malformed"); |
| 1750 | 1749 | } |
tests/auth_enumeration.rsmodified+5 -5
| @@ -12,13 +12,13 @@ use serde_json::json; | ||
| 12 | 12 | #[tokio::test] |
| 13 | 13 | async fn duplicate_register_is_indistinguishable_from_a_fresh_one() { |
| 14 | 14 | 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" }); | |
| 16 | 16 | |
| 17 | 17 | let first = send(&app, "POST", "/auth/register", None, Some(taken)).await; |
| 18 | 18 | assert_eq!(first.status, StatusCode::CREATED); |
| 19 | 19 | |
| 20 | 20 | // 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" }); | |
| 22 | 22 | let started = Instant::now(); |
| 23 | 23 | let dup = send( |
| 24 | 24 | &app, |
| @@ -35,7 +35,7 @@ async fn duplicate_register_is_indistinguishable_from_a_fresh_one() { | ||
| 35 | 35 | "POST", |
| 36 | 36 | "/auth/register", |
| 37 | 37 | None, |
| 38 | - Some(json!({ "school": "demo", "username": "grace", "password": "secret1" })), | |
| 38 | + Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "grace", "password": "secret1" })), | |
| 39 | 39 | ) |
| 40 | 40 | .await; |
| 41 | 41 | |
| @@ -136,7 +136,7 @@ async fn the_taken_body_equals_the_fresh_body_for_the_same_username() { | ||
| 136 | 136 | "POST", |
| 137 | 137 | "/auth/register", |
| 138 | 138 | None, |
| 139 | - Some(json!({ "school": "demo", "username": "ada", "password": "secret1" })), | |
| 139 | + Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ada", "password": "secret1" })), | |
| 140 | 140 | ) |
| 141 | 141 | .await; |
| 142 | 142 | let taken = send( |
| @@ -144,7 +144,7 @@ async fn the_taken_body_equals_the_fresh_body_for_the_same_username() { | ||
| 144 | 144 | "POST", |
| 145 | 145 | "/auth/register", |
| 146 | 146 | None, |
| 147 | - Some(json!({ "school": "demo", "username": "ada", "password": "another1" })), | |
| 147 | + Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "ada", "password": "another1" })), | |
| 148 | 148 | ) |
| 149 | 149 | .await; |
| 150 | 150 |
tests/builder_api.rsmodified+364 -493
| @@ -10,7 +10,7 @@ use axum::http::StatusCode; | ||
| 10 | 10 | use common::*; |
| 11 | 11 | use hezarfen_backend::domain::user::{Password, Username}; |
| 12 | 12 | use hezarfen_backend::service::builder; |
| 13 | -use hezarfen_backend::tenant::{DEMO_SLUG, Tenants}; | |
| 13 | +use hezarfen_backend::tenant::{DEMO_SCHOOL_ID, SchoolId, Tenants}; | |
| 14 | 14 | use serde_json::{Value, json}; |
| 15 | 15 | |
| 16 | 16 | const BUILDER_USER: &str = "operator"; |
| @@ -31,7 +31,7 @@ async fn deployment() -> (Router, hezarfen_backend::database::Database, Tenants) | ||
| 31 | 31 | } |
| 32 | 32 | |
| 33 | 33 | async fn builder_login(app: &Router) -> String { |
| 34 | - let res = send( | |
| 34 | + let res = bsend( | |
| 35 | 35 | app, |
| 36 | 36 | "POST", |
| 37 | 37 | "/builder/login", |
| @@ -43,16 +43,16 @@ async fn builder_login(app: &Router) -> String { | ||
| 43 | 43 | res.cookie.expect("builder cookie set on login") |
| 44 | 44 | } |
| 45 | 45 | |
| 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( | |
| 49 | 50 | app, |
| 50 | 51 | "POST", |
| 51 | 52 | "/schools", |
| 52 | 53 | Some(cookie), |
| 53 | 54 | Some(json!({ |
| 54 | - "slug": slug, | |
| 55 | - "name": format!("{slug} school"), | |
| 55 | + "name": format!("{label} school"), | |
| 56 | 56 | "admin_username": "admin", |
| 57 | 57 | "admin_password": admin_pass, |
| 58 | 58 | })), |
| @@ -60,13 +60,34 @@ async fn create_school(app: &Router, cookie: &str, slug: &str, admin_pass: &str) | ||
| 60 | 60 | .await |
| 61 | 61 | } |
| 62 | 62 | |
| 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 | + | |
| 63 | 84 | /// Log `username` into the school named `slug`. The login itself names no |
| 64 | 85 | /// school any more — the admin fixtures reuse one username across many |
| 65 | 86 | /// schools, which makes that admin one *person* with several memberships — |
| 66 | 87 | /// so when login answers a choice list, bind the requested school before |
| 67 | 88 | /// returning. The result is whatever a plain school login would have said. |
| 68 | 89 | async fn school_login(app: &Router, slug: &str, username: &str, password: &str) -> Res { |
| 69 | - let res = send( | |
| 90 | + let res = bsend( | |
| 70 | 91 | app, |
| 71 | 92 | "POST", |
| 72 | 93 | "/auth/login", |
| @@ -76,12 +97,12 @@ async fn school_login(app: &Router, slug: &str, username: &str, password: &str) | ||
| 76 | 97 | .await; |
| 77 | 98 | if res.body["schools"].is_array() { |
| 78 | 99 | assert_eq!(res.status, StatusCode::OK, "choice login {username}"); |
| 79 | - let selected = send( | |
| 100 | + let selected = bsend( | |
| 80 | 101 | app, |
| 81 | 102 | "POST", |
| 82 | 103 | "/auth/school", |
| 83 | 104 | res.cookie.as_deref(), |
| 84 | - Some(json!({ "school": slug })), | |
| 105 | + Some(json!({ "school": school_choice(&res.body, slug) })), | |
| 85 | 106 | ) |
| 86 | 107 | .await; |
| 87 | 108 | assert_eq!( |
| @@ -94,13 +115,71 @@ async fn school_login(app: &Router, slug: &str, username: &str, password: &str) | ||
| 94 | 115 | res |
| 95 | 116 | } |
| 96 | 117 | |
| 97 | -fn slugs(body: &Value) -> Vec<String> { | |
| 118 | +fn school_ids(body: &Value) -> Vec<String> { | |
| 98 | 119 | items(body) |
| 99 | 120 | .iter() |
| 100 | - .map(|item| item["slug"].as_str().expect("slug").to_string()) | |
| 121 | + .map(|item| item["id"].as_str().expect("id").to_string()) | |
| 101 | 122 | .collect() |
| 102 | 123 | } |
| 103 | 124 | |
| 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 | + | |
| 104 | 183 | /// The two cookies share a name and nothing else. This is the whole point of |
| 105 | 184 | /// the split: neither principal may ever be accepted where the other belongs. |
| 106 | 185 | #[tokio::test] |
| @@ -108,7 +187,7 @@ async fn a_builder_logs_in_and_its_cookie_works_here_and_nowhere_else() { | ||
| 108 | 187 | let (app, _db, _tenants) = deployment().await; |
| 109 | 188 | let builder = builder_login(&app).await; |
| 110 | 189 | |
| 111 | - let me = send(&app, "GET", "/builder/me", Some(&builder), None).await; | |
| 190 | + let me = bsend(&app, "GET", "/builder/me", Some(&builder), None).await; | |
| 112 | 191 | assert_eq!(me.status, StatusCode::OK); |
| 113 | 192 | assert_eq!(me.body["username"], BUILDER_USER); |
| 114 | 193 | 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() { | ||
| 116 | 195 | // A school user's cookie is not a builder's… |
| 117 | 196 | let student = login(&app, "ali").await; |
| 118 | 197 | assert_eq!( |
| 119 | - send(&app, "GET", "/builder/me", Some(&student), None) | |
| 198 | + bsend(&app, "GET", "/builder/me", Some(&student), None) | |
| 120 | 199 | .await |
| 121 | 200 | .status, |
| 122 | 201 | StatusCode::UNAUTHORIZED, |
| 123 | 202 | "a school cookie reached the builder surface" |
| 124 | 203 | ); |
| 125 | 204 | assert_eq!( |
| 126 | - send(&app, "GET", "/schools", Some(&student), None) | |
| 205 | + bsend(&app, "GET", "/schools", Some(&student), None) | |
| 127 | 206 | .await |
| 128 | 207 | .status, |
| 129 | 208 | StatusCode::UNAUTHORIZED |
| 130 | 209 | ); |
| 131 | 210 | // …and a builder's is not a school user's. |
| 132 | 211 | assert_eq!( |
| 133 | - send(&app, "GET", "/auth/me", Some(&builder), None) | |
| 212 | + bsend(&app, "GET", "/auth/me", Some(&builder), None) | |
| 134 | 213 | .await |
| 135 | 214 | .status, |
| 136 | 215 | StatusCode::UNAUTHORIZED, |
| @@ -143,17 +222,17 @@ async fn a_builder_logs_in_and_its_cookie_works_here_and_nowhere_else() { | ||
| 143 | 222 | json!({ "username": "ghost", "password": BUILDER_PASS }), |
| 144 | 223 | ] { |
| 145 | 224 | assert_eq!( |
| 146 | - send(&app, "POST", "/builder/login", None, Some(bad)) | |
| 225 | + bsend(&app, "POST", "/builder/login", None, Some(bad)) | |
| 147 | 226 | .await |
| 148 | 227 | .status, |
| 149 | 228 | StatusCode::UNAUTHORIZED |
| 150 | 229 | ); |
| 151 | 230 | } |
| 152 | 231 | |
| 153 | - let out = send(&app, "POST", "/builder/logout", Some(&builder), None).await; | |
| 232 | + let out = bsend(&app, "POST", "/builder/logout", Some(&builder), None).await; | |
| 154 | 233 | assert_eq!(out.status, StatusCode::NO_CONTENT); |
| 155 | 234 | assert_eq!( |
| 156 | - send(&app, "GET", "/builder/me", Some(&builder), None) | |
| 235 | + bsend(&app, "GET", "/builder/me", Some(&builder), None) | |
| 157 | 236 | .await |
| 158 | 237 | .status, |
| 159 | 238 | StatusCode::UNAUTHORIZED, |
| @@ -175,76 +254,47 @@ async fn creating_a_school_seeds_an_admin_who_can_log_in() { | ||
| 175 | 254 | "create school: {:?}", |
| 176 | 255 | created.body |
| 177 | 256 | ); |
| 178 | - assert_eq!(created.body["slug"], "ata-koleji"); | |
| 257 | + let id = created_id(&created); | |
| 258 | + assert_eq!(created.body["name"], "ata-koleji school"); | |
| 179 | 259 | 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 | + ); | |
| 180 | 264 | |
| 181 | - let login = school_login(&app, "ata-koleji", "admin", "secret1").await; | |
| 265 | + let login = school_login(&app, &id, "admin", "secret1").await; | |
| 182 | 266 | assert_eq!(login.status, StatusCode::OK, "seeded admin logs in"); |
| 183 | 267 | let cookie = login.cookie.expect("school cookie"); |
| 184 | 268 | assert!( |
| 185 | - cookie.starts_with("session=ata-koleji."), | |
| 269 | + cookie.starts_with(&format!("session={id}.")), | |
| 186 | 270 | "the cookie names its school: {cookie}" |
| 187 | 271 | ); |
| 188 | - let me = send(&app, "GET", "/auth/me", Some(&cookie), None).await; | |
| 272 | + let me = bsend(&app, "GET", "/auth/me", Some(&cookie), None).await; | |
| 189 | 273 | assert_eq!(me.status, StatusCode::OK); |
| 190 | 274 | assert_eq!( |
| 191 | 275 | me.body["role"], "admin", |
| 192 | 276 | "the seed is an admin, not a student" |
| 193 | 277 | ); |
| 194 | 278 | |
| 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. | |
| 230 | 282 | 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" }), | |
| 233 | 285 | ] { |
| 234 | 286 | assert_eq!( |
| 235 | - send(&app, "POST", "/schools", Some(&builder), Some(body)) | |
| 287 | + bsend(&app, "POST", "/schools", Some(&builder), Some(body)) | |
| 236 | 288 | .await |
| 237 | 289 | .status, |
| 238 | 290 | StatusCode::BAD_REQUEST |
| 239 | 291 | ); |
| 240 | 292 | } |
| 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"); | |
| 246 | 296 | assert!( |
| 247 | - cookie.starts_with("session=ata-koleji."), | |
| 297 | + cookie.starts_with(&format!("session={id}.")), | |
| 248 | 298 | "a refused create must not have made a school: {cookie:?}" |
| 249 | 299 | ); |
| 250 | 300 | } |
| @@ -255,25 +305,22 @@ async fn creating_a_school_seeds_an_admin_who_can_log_in() { | ||
| 255 | 305 | async fn a_suspension_closes_the_school_and_a_resume_reopens_it() { |
| 256 | 306 | let (app, _db, _tenants) = deployment().await; |
| 257 | 307 | 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); | |
| 264 | 311 | |
| 265 | - let list = send(&app, "GET", "/schools", Some(&builder), None).await; | |
| 312 | + let list = bsend(&app, "GET", "/schools", Some(&builder), None).await; | |
| 266 | 313 | 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)); | |
| 269 | 316 | assert_eq!(total(&list.body), 2); |
| 270 | 317 | // 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; | |
| 272 | 319 | assert_eq!(items(&page.body).len(), 1); |
| 273 | 320 | assert_eq!(total(&page.body), 2); |
| 274 | 321 | |
| 275 | 322 | assert_eq!( |
| 276 | - send(&app, "GET", "/schools/ghost", Some(&builder), None) | |
| 323 | + bsend(&app, "GET", "/schools/ghost", Some(&builder), None) | |
| 277 | 324 | .await |
| 278 | 325 | .status, |
| 279 | 326 | StatusCode::NOT_FOUND |
| @@ -281,11 +328,11 @@ async fn a_suspension_closes_the_school_and_a_resume_reopens_it() { | ||
| 281 | 328 | |
| 282 | 329 | // A partial patch touches only what it names: the name moves, the status |
| 283 | 330 | // 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( | |
| 286 | 333 | &app, |
| 287 | 334 | "PATCH", |
| 288 | - "/schools/beta", | |
| 335 | + &format!("/schools/{beta}"), | |
| 289 | 336 | Some(&builder), |
| 290 | 337 | Some(json!({ "name": "Beta Koleji" })), |
| 291 | 338 | ) |
| @@ -293,15 +340,15 @@ async fn a_suspension_closes_the_school_and_a_resume_reopens_it() { | ||
| 293 | 340 | assert_eq!(renamed.status, StatusCode::OK); |
| 294 | 341 | assert_eq!(renamed.body["name"], "Beta Koleji"); |
| 295 | 342 | assert_eq!(renamed.body["status"], "active"); |
| 296 | - assert_eq!(renamed.body["slug"], "beta"); | |
| 343 | + assert_eq!(renamed.body["id"], beta); | |
| 297 | 344 | assert_eq!(renamed.body["created_at"], before.body["created_at"]); |
| 298 | 345 | // An empty patch is a no-op read, and a bad status is a 400 — including |
| 299 | 346 | // `provisioning`, which is the boot's own word for a school that is still |
| 300 | 347 | // being made and not a state a vendor can ask for. |
| 301 | - let untouched = send( | |
| 348 | + let untouched = bsend( | |
| 302 | 349 | &app, |
| 303 | 350 | "PATCH", |
| 304 | - "/schools/beta", | |
| 351 | + &format!("/schools/{beta}"), | |
| 305 | 352 | Some(&builder), |
| 306 | 353 | Some(json!({})), |
| 307 | 354 | ) |
| @@ -309,10 +356,10 @@ async fn a_suspension_closes_the_school_and_a_resume_reopens_it() { | ||
| 309 | 356 | assert_eq!(untouched.body["name"], "Beta Koleji"); |
| 310 | 357 | for refused in ["closed", "provisioning"] { |
| 311 | 358 | assert_eq!( |
| 312 | - send( | |
| 359 | + bsend( | |
| 313 | 360 | &app, |
| 314 | 361 | "PATCH", |
| 315 | - "/schools/beta", | |
| 362 | + &format!("/schools/{beta}"), | |
| 316 | 363 | Some(&builder), |
| 317 | 364 | Some(json!({ "status": refused })), |
| 318 | 365 | ) |
| @@ -324,14 +371,14 @@ async fn a_suspension_closes_the_school_and_a_resume_reopens_it() { | ||
| 324 | 371 | } |
| 325 | 372 | |
| 326 | 373 | // 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") | |
| 328 | 375 | .await |
| 329 | 376 | .cookie |
| 330 | 377 | .expect("school cookie"); |
| 331 | - let suspended = send( | |
| 378 | + let suspended = bsend( | |
| 332 | 379 | &app, |
| 333 | 380 | "PATCH", |
| 334 | - "/schools/beta", | |
| 381 | + &format!("/schools/{beta}"), | |
| 335 | 382 | Some(&builder), |
| 336 | 383 | Some(json!({ "status": "suspended" })), |
| 337 | 384 | ) |
| @@ -340,12 +387,12 @@ async fn a_suspension_closes_the_school_and_a_resume_reopens_it() { | ||
| 340 | 387 | assert_eq!(suspended.body["status"], "suspended"); |
| 341 | 388 | |
| 342 | 389 | assert_eq!( |
| 343 | - school_login(&app, "beta", "admin", "secret1").await.status, | |
| 390 | + school_login(&app, &beta, "admin", "secret1").await.status, | |
| 344 | 391 | StatusCode::FORBIDDEN, |
| 345 | 392 | "a suspended school refuses login" |
| 346 | 393 | ); |
| 347 | 394 | assert_eq!( |
| 348 | - send(&app, "GET", "/auth/me", Some(&live), None) | |
| 395 | + bsend(&app, "GET", "/auth/me", Some(&live), None) | |
| 349 | 396 | .await |
| 350 | 397 | .status, |
| 351 | 398 | StatusCode::FORBIDDEN, |
| @@ -353,17 +400,17 @@ async fn a_suspension_closes_the_school_and_a_resume_reopens_it() { | ||
| 353 | 400 | ); |
| 354 | 401 | // The builder still manages it — that is how it gets un-suspended. |
| 355 | 402 | assert_eq!( |
| 356 | - send(&app, "GET", "/schools/beta", Some(&builder), None) | |
| 403 | + bsend(&app, "GET", &format!("/schools/{beta}"), Some(&builder), None) | |
| 357 | 404 | .await |
| 358 | 405 | .status, |
| 359 | 406 | StatusCode::OK |
| 360 | 407 | ); |
| 361 | 408 | // …except entering it, the one door a suspension must also close. |
| 362 | 409 | assert_eq!( |
| 363 | - send( | |
| 410 | + bsend( | |
| 364 | 411 | &app, |
| 365 | 412 | "POST", |
| 366 | - "/schools/beta/enter", | |
| 413 | + &format!("/schools/{beta}/enter"), | |
| 367 | 414 | Some(&builder), |
| 368 | 415 | Some(json!({ "username": "admin" })), |
| 369 | 416 | ) |
| @@ -372,16 +419,16 @@ async fn a_suspension_closes_the_school_and_a_resume_reopens_it() { | ||
| 372 | 419 | StatusCode::FORBIDDEN |
| 373 | 420 | ); |
| 374 | 421 | |
| 375 | - send( | |
| 422 | + bsend( | |
| 376 | 423 | &app, |
| 377 | 424 | "PATCH", |
| 378 | - "/schools/beta", | |
| 425 | + &format!("/schools/{beta}"), | |
| 379 | 426 | Some(&builder), |
| 380 | 427 | Some(json!({ "status": "active" })), |
| 381 | 428 | ) |
| 382 | 429 | .await; |
| 383 | 430 | assert_eq!( |
| 384 | - send(&app, "GET", "/auth/me", Some(&live), None) | |
| 431 | + bsend(&app, "GET", "/auth/me", Some(&live), None) | |
| 385 | 432 | .await |
| 386 | 433 | .status, |
| 387 | 434 | StatusCode::OK, |
| @@ -401,7 +448,7 @@ async fn resetting_an_admin_password_revokes_the_old_credential_and_its_sessions | ||
| 401 | 448 | .await |
| 402 | 449 | .cookie |
| 403 | 450 | .expect("school cookie"); |
| 404 | - let person_cookie = send( | |
| 451 | + let person_cookie = bsend( | |
| 405 | 452 | &app, |
| 406 | 453 | "POST", |
| 407 | 454 | "/auth/login", |
| @@ -415,7 +462,7 @@ async fn resetting_an_admin_password_revokes_the_old_credential_and_its_sessions | ||
| 415 | 462 | // An account that is not an admin of that school, and one that is not there |
| 416 | 463 | // at all, are told apart. |
| 417 | 464 | assert_eq!( |
| 418 | - send( | |
| 465 | + bsend( | |
| 419 | 466 | &app, |
| 420 | 467 | "POST", |
| 421 | 468 | "/schools/gamma/admin-password", |
| @@ -426,15 +473,19 @@ async fn resetting_an_admin_password_revokes_the_old_credential_and_its_sessions | ||
| 426 | 473 | .status, |
| 427 | 474 | StatusCode::NOT_FOUND |
| 428 | 475 | ); |
| 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"); | |
| 429 | 480 | let gamma_db = _tenants |
| 430 | - .get(&hezarfen_backend::tenant::Slug::try_new("gamma").unwrap()) | |
| 481 | + .get(&hezarfen_backend::tenant::SchoolId::from_uuid(gamma_id)) | |
| 431 | 482 | .await |
| 432 | 483 | .unwrap(); |
| 433 | 484 | hezarfen_backend::db::user::create(&gamma_db, Username::try_new("veli").unwrap(), None) |
| 434 | 485 | .await |
| 435 | 486 | .unwrap(); |
| 436 | 487 | assert_eq!( |
| 437 | - send( | |
| 488 | + bsend( | |
| 438 | 489 | &app, |
| 439 | 490 | "POST", |
| 440 | 491 | "/schools/gamma/admin-password", |
| @@ -447,7 +498,7 @@ async fn resetting_an_admin_password_revokes_the_old_credential_and_its_sessions | ||
| 447 | 498 | "a student is not the school's admin" |
| 448 | 499 | ); |
| 449 | 500 | |
| 450 | - let reset = send( | |
| 501 | + let reset = bsend( | |
| 451 | 502 | &app, |
| 452 | 503 | "POST", |
| 453 | 504 | "/schools/gamma/admin-password", |
| @@ -467,19 +518,19 @@ async fn resetting_an_admin_password_revokes_the_old_credential_and_its_sessions | ||
| 467 | 518 | StatusCode::OK |
| 468 | 519 | ); |
| 469 | 520 | assert_eq!( |
| 470 | - send(&app, "GET", "/auth/me", Some(&old_cookie), None) | |
| 521 | + bsend(&app, "GET", "/auth/me", Some(&old_cookie), None) | |
| 471 | 522 | .await |
| 472 | 523 | .status, |
| 473 | 524 | StatusCode::UNAUTHORIZED, |
| 474 | 525 | "a reset that leaves the old cookie working resets nothing" |
| 475 | 526 | ); |
| 476 | 527 | assert_eq!( |
| 477 | - send( | |
| 528 | + bsend( | |
| 478 | 529 | &app, |
| 479 | 530 | "POST", |
| 480 | 531 | "/auth/school", |
| 481 | 532 | Some(&person_cookie), |
| 482 | - Some(json!({ "school": "gamma" })), | |
| 533 | + Some(json!({ "school": gamma_id.to_string() })), | |
| 483 | 534 | ) |
| 484 | 535 | .await |
| 485 | 536 | .status, |
| @@ -497,7 +548,7 @@ async fn entering_a_school_acts_in_that_school_and_no_other() { | ||
| 497 | 548 | create_school(&app, &builder, "alpha", "secret1").await; |
| 498 | 549 | create_school(&app, &builder, "beta", "secret1").await; |
| 499 | 550 | |
| 500 | - let entered = send( | |
| 551 | + let entered = bsend( | |
| 501 | 552 | &app, |
| 502 | 553 | "POST", |
| 503 | 554 | "/schools/alpha/enter", |
| @@ -509,14 +560,14 @@ async fn entering_a_school_acts_in_that_school_and_no_other() { | ||
| 509 | 560 | assert_eq!(entered.body["username"], "admin"); |
| 510 | 561 | assert_eq!(entered.body["role"], "admin"); |
| 511 | 562 | 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}"); | |
| 513 | 564 | |
| 514 | 565 | // 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; | |
| 516 | 567 | assert_eq!(me.status, StatusCode::OK); |
| 517 | 568 | assert_eq!(me.body["role"], "admin"); |
| 518 | 569 | assert_eq!( |
| 519 | - send(&app, "GET", "/builder/me", Some(&alpha), None) | |
| 570 | + bsend(&app, "GET", "/builder/me", Some(&alpha), None) | |
| 520 | 571 | .await |
| 521 | 572 | .status, |
| 522 | 573 | StatusCode::UNAUTHORIZED, |
| @@ -525,7 +576,7 @@ async fn entering_a_school_acts_in_that_school_and_no_other() { | ||
| 525 | 576 | |
| 526 | 577 | // A row written in alpha is invisible from beta — the isolation the whole |
| 527 | 578 | // per-school database exists for. |
| 528 | - let note = send( | |
| 579 | + let note = bsend( | |
| 529 | 580 | &app, |
| 530 | 581 | "POST", |
| 531 | 582 | "/notes", |
| @@ -535,7 +586,7 @@ async fn entering_a_school_acts_in_that_school_and_no_other() { | ||
| 535 | 586 | .await; |
| 536 | 587 | assert_eq!(note.status, StatusCode::CREATED); |
| 537 | 588 | let note_id = id_of(¬e.body); |
| 538 | - let beta = send( | |
| 589 | + let beta = bsend( | |
| 539 | 590 | &app, |
| 540 | 591 | "POST", |
| 541 | 592 | "/schools/beta/enter", |
| @@ -546,7 +597,7 @@ async fn entering_a_school_acts_in_that_school_and_no_other() { | ||
| 546 | 597 | .cookie |
| 547 | 598 | .expect("beta cookie"); |
| 548 | 599 | assert_eq!( |
| 549 | - send(&app, "GET", &format!("/notes/{note_id}"), Some(&beta), None) | |
| 600 | + bsend(&app, "GET", &format!("/notes/{note_id}"), Some(&beta), None) | |
| 550 | 601 | .await |
| 551 | 602 | .status, |
| 552 | 603 | StatusCode::NOT_FOUND, |
| @@ -555,7 +606,7 @@ async fn entering_a_school_acts_in_that_school_and_no_other() { | ||
| 555 | 606 | |
| 556 | 607 | // Unknown school, unknown account, non-admin account. |
| 557 | 608 | assert_eq!( |
| 558 | - send( | |
| 609 | + bsend( | |
| 559 | 610 | &app, |
| 560 | 611 | "POST", |
| 561 | 612 | "/schools/ghost/enter", |
| @@ -567,7 +618,7 @@ async fn entering_a_school_acts_in_that_school_and_no_other() { | ||
| 567 | 618 | StatusCode::NOT_FOUND |
| 568 | 619 | ); |
| 569 | 620 | assert_eq!( |
| 570 | - send( | |
| 621 | + bsend( | |
| 571 | 622 | &app, |
| 572 | 623 | "POST", |
| 573 | 624 | "/schools/alpha/enter", |
| @@ -595,7 +646,7 @@ async fn deleting_a_school_takes_its_data_and_its_files() { | ||
| 595 | 646 | .await |
| 596 | 647 | .cookie |
| 597 | 648 | .expect("school cookie"); |
| 598 | - let note = send( | |
| 649 | + let note = bsend( | |
| 599 | 650 | &app, |
| 600 | 651 | "POST", |
| 601 | 652 | "/notes", |
| @@ -614,17 +665,18 @@ async fn deleting_a_school_takes_its_data_and_its_files() { | ||
| 614 | 665 | ) |
| 615 | 666 | .await; |
| 616 | 667 | 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)); | |
| 619 | 671 | assert!(blob.exists(), "{} should exist", blob.display()); |
| 620 | 672 | blobs.push(blob); |
| 621 | 673 | } |
| 622 | 674 | |
| 623 | - let deleted = send(&app, "DELETE", "/schools/delta", Some(&builder), None).await; | |
| 675 | + let deleted = bsend(&app, "DELETE", "/schools/delta", Some(&builder), None).await; | |
| 624 | 676 | assert_eq!(deleted.status, StatusCode::NO_CONTENT); |
| 625 | 677 | |
| 626 | 678 | assert_eq!( |
| 627 | - send(&app, "GET", "/schools/delta", Some(&builder), None) | |
| 679 | + bsend(&app, "GET", "/schools/delta", Some(&builder), None) | |
| 628 | 680 | .await |
| 629 | 681 | .status, |
| 630 | 682 | StatusCode::NOT_FOUND |
| @@ -633,14 +685,12 @@ async fn deleting_a_school_takes_its_data_and_its_files() { | ||
| 633 | 685 | // `epsilon` left to enter — the dropped slug is neither offered nor 403'd. |
| 634 | 686 | let after_delete = school_login(&app, "delta", "admin", "secret1").await; |
| 635 | 687 | 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 | + } | |
| 644 | 694 | assert!( |
| 645 | 695 | blobs[1].exists(), |
| 646 | 696 | "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() { | ||
| 654 | 704 | ); |
| 655 | 705 | // Deleting it again is a 404, not a second destruction. |
| 656 | 706 | assert_eq!( |
| 657 | - send(&app, "DELETE", "/schools/delta", Some(&builder), None) | |
| 707 | + bsend(&app, "DELETE", "/schools/delta", Some(&builder), None) | |
| 658 | 708 | .await |
| 659 | 709 | .status, |
| 660 | 710 | StatusCode::NOT_FOUND |
| @@ -665,7 +715,6 @@ async fn deleting_a_school_takes_its_data_and_its_files() { | ||
| 665 | 715 | // REFUTE-mode probes on the irreversible paths (appended by a verifier). |
| 666 | 716 | // --------------------------------------------------------------------------- |
| 667 | 717 | |
| 668 | -use hezarfen_backend::tenant::Slug; | |
| 669 | 718 | |
| 670 | 719 | /// Claim 1: no `/schools/{slug}` route can be aimed outside `FILES_PATH/<slug>`. |
| 671 | 720 | /// 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() { | ||
| 725 | 774 | ("POST", "/enter", Some(json!({ "username": "admin" }))), |
| 726 | 775 | ] { |
| 727 | 776 | 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; | |
| 729 | 778 | assert!( |
| 730 | 779 | res.status == StatusCode::NOT_FOUND |
| 731 | 780 | || res.status == StatusCode::METHOD_NOT_ALLOWED |
| @@ -744,7 +793,7 @@ async fn probe_hostile_slug_segments_never_delete_anything() { | ||
| 744 | 793 | |
| 745 | 794 | // Also the empty segment, which is a different route shape entirely. |
| 746 | 795 | 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; | |
| 748 | 797 | assert!( |
| 749 | 798 | !res.status.is_success() || method == "GET", |
| 750 | 799 | "{method} /schools/ -> {}", |
| @@ -775,7 +824,7 @@ async fn probe_hostile_slug_segments_never_delete_anything() { | ||
| 775 | 824 | /// keeps working; a re-created slug is an *empty* school. |
| 776 | 825 | #[tokio::test] |
| 777 | 826 | async fn probe_drop_is_scoped_and_recreation_is_empty() { |
| 778 | - let (app, _db, _tenants) = deployment().await; | |
| 827 | + let (app, _db, tenants) = deployment().await; | |
| 779 | 828 | let builder = builder_login(&app).await; |
| 780 | 829 | create_school(&app, &builder, "p2a", "secret1").await; |
| 781 | 830 | create_school(&app, &builder, "p2b", "secret1").await; |
| @@ -789,7 +838,7 @@ async fn probe_drop_is_scoped_and_recreation_is_empty() { | ||
| 789 | 838 | .cookie |
| 790 | 839 | .expect("p2b cookie"); |
| 791 | 840 | // A row only p2a has. |
| 792 | - let note = send( | |
| 841 | + let note = bsend( | |
| 793 | 842 | &app, |
| 794 | 843 | "POST", |
| 795 | 844 | "/notes", |
| @@ -799,17 +848,21 @@ async fn probe_drop_is_scoped_and_recreation_is_empty() { | ||
| 799 | 848 | .await; |
| 800 | 849 | assert_eq!(note.status, StatusCode::CREATED); |
| 801 | 850 | // 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( | |
| 803 | 856 | &app, |
| 804 | 857 | "POST", |
| 805 | 858 | "/auth/register", |
| 806 | 859 | None, |
| 807 | - Some(json!({ "school": "p2a", "username": "ali", "password": "secret1" })), | |
| 860 | + Some(json!({ "school": p2a_id.to_string(), "username": "ali", "password": "secret1" })), | |
| 808 | 861 | ) |
| 809 | 862 | .await; |
| 810 | 863 | |
| 811 | 864 | assert_eq!( |
| 812 | - send(&app, "DELETE", "/schools/p2a", Some(&builder), None) | |
| 865 | + bsend(&app, "DELETE", "/schools/p2a", Some(&builder), None) | |
| 813 | 866 | .await |
| 814 | 867 | .status, |
| 815 | 868 | StatusCode::NO_CONTENT |
| @@ -817,22 +870,23 @@ async fn probe_drop_is_scoped_and_recreation_is_empty() { | ||
| 817 | 870 | |
| 818 | 871 | // The neighbour's already-resolved handle is untouched. |
| 819 | 872 | assert_eq!( |
| 820 | - send(&app, "GET", "/auth/me", Some(&b), None).await.status, | |
| 873 | + bsend(&app, "GET", "/auth/me", Some(&b), None).await.status, | |
| 821 | 874 | StatusCode::OK, |
| 822 | 875 | "dropping p2a disturbed p2b's cached handle" |
| 823 | 876 | ); |
| 824 | 877 | // The dropped school is unknown, not forbidden. |
| 825 | 878 | assert_eq!( |
| 826 | - send(&app, "GET", "/auth/me", Some(&a), None).await.status, | |
| 879 | + bsend(&app, "GET", "/auth/me", Some(&a), None).await.status, | |
| 827 | 880 | StatusCode::UNAUTHORIZED |
| 828 | 881 | ); |
| 829 | 882 | // The person behind `admin` still belongs to p2b: the login has that |
| 830 | 883 | // school left to enter, and the dropped slug is not among the choices. |
| 831 | 884 | let after_drop = school_login(&app, "p2a", "admin", "secret1").await; |
| 832 | 885 | assert_eq!(after_drop.status, StatusCode::OK); |
| 886 | + let kept = after_drop.cookie.expect("cookie"); | |
| 833 | 887 | 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}" | |
| 836 | 890 | ); |
| 837 | 891 | |
| 838 | 892 | // 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() { | ||
| 845 | 899 | .await |
| 846 | 900 | .cookie |
| 847 | 901 | .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; | |
| 849 | 903 | assert_eq!(users.status, StatusCode::OK, "{:?}", users.body); |
| 850 | 904 | assert_eq!( |
| 851 | 905 | total(&users.body), |
| @@ -853,7 +907,7 @@ async fn probe_drop_is_scoped_and_recreation_is_empty() { | ||
| 853 | 907 | "a re-created school carries users from the dropped one: {:?}", |
| 854 | 908 | users.body |
| 855 | 909 | ); |
| 856 | - let notes = send(&app, "GET", "/notes", Some(&fresh), None).await; | |
| 910 | + let notes = bsend(&app, "GET", "/notes", Some(&fresh), None).await; | |
| 857 | 911 | assert_eq!(notes.status, StatusCode::OK); |
| 858 | 912 | assert_eq!(total(¬es.body), 0, "old rows survived the drop"); |
| 859 | 913 | |
| @@ -867,7 +921,7 @@ async fn probe_drop_is_scoped_and_recreation_is_empty() { | ||
| 867 | 921 | mismatched.body |
| 868 | 922 | ); |
| 869 | 923 | assert_eq!( |
| 870 | - send(&app, "GET", "/schools/p2c", Some(&builder), None) | |
| 924 | + bsend(&app, "GET", "/schools/p2c", Some(&builder), None) | |
| 871 | 925 | .await |
| 872 | 926 | .status, |
| 873 | 927 | StatusCode::NOT_FOUND, |
| @@ -875,140 +929,6 @@ async fn probe_drop_is_scoped_and_recreation_is_empty() { | ||
| 875 | 929 | ); |
| 876 | 930 | } |
| 877 | 931 | |
| 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 | - | |
| 1012 | 932 | /// Claim 4: `admin-password` and `enter` cannot be aimed at a non-admin, at a |
| 1013 | 933 | /// stranger's account, or (for `enter`) at a suspended school; and a reset kills |
| 1014 | 934 | /// **every** live session of that account. |
| @@ -1018,27 +938,33 @@ async fn probe_admin_targets_and_reset_revokes_all_sessions() { | ||
| 1018 | 938 | let builder = builder_login(&app).await; |
| 1019 | 939 | create_school(&app, &builder, "p4a", "secret1").await; |
| 1020 | 940 | 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(); | |
| 1022 | 948 | |
| 1023 | 949 | // Three non-admins in p4a, and a name that only exists in p4b. |
| 1024 | 950 | for (name, role) in [("tea", "teacher"), ("stu", "student"), ("par", "parent")] { |
| 1025 | - let reg = send( | |
| 951 | + let reg = bsend( | |
| 1026 | 952 | &app, |
| 1027 | 953 | "POST", |
| 1028 | 954 | "/auth/register", |
| 1029 | 955 | None, |
| 1030 | - Some(json!({ "school": "p4a", "username": name, "password": "secret1" })), | |
| 956 | + Some(json!({ "school": p4a_id.to_string(), "username": name, "password": "secret1" })), | |
| 1031 | 957 | ) |
| 1032 | 958 | .await; |
| 1033 | 959 | assert_eq!(reg.status, StatusCode::CREATED, "register {name}"); |
| 1034 | 960 | set_role(&a_db, name, role).await; |
| 1035 | 961 | } |
| 1036 | - let reg = send( | |
| 962 | + let reg = bsend( | |
| 1037 | 963 | &app, |
| 1038 | 964 | "POST", |
| 1039 | 965 | "/auth/register", |
| 1040 | 966 | None, |
| 1041 | - Some(json!({ "school": "p4b", "username": "onlyb", "password": "secret1" })), | |
| 967 | + Some(json!({ "school": p4b_id.to_string(), "username": "onlyb", "password": "secret1" })), | |
| 1042 | 968 | ) |
| 1043 | 969 | .await; |
| 1044 | 970 | assert_eq!(reg.status, StatusCode::CREATED); |
| @@ -1051,7 +977,7 @@ async fn probe_admin_targets_and_reset_revokes_all_sessions() { | ||
| 1051 | 977 | ), |
| 1052 | 978 | ("/schools/p4a/enter", json!({ "username": target })), |
| 1053 | 979 | ] { |
| 1054 | - let res = send(&app, "POST", path, Some(&builder), Some(body)).await; | |
| 980 | + let res = bsend(&app, "POST", path, Some(&builder), Some(body)).await; | |
| 1055 | 981 | assert_eq!( |
| 1056 | 982 | res.status, |
| 1057 | 983 | StatusCode::CONFLICT, |
| @@ -1069,7 +995,7 @@ async fn probe_admin_targets_and_reset_revokes_all_sessions() { | ||
| 1069 | 995 | ), |
| 1070 | 996 | ("/schools/p4a/enter", json!({ "username": "onlyb" })), |
| 1071 | 997 | ] { |
| 1072 | - let res = send(&app, "POST", path, Some(&builder), Some(body)).await; | |
| 998 | + let res = bsend(&app, "POST", path, Some(&builder), Some(body)).await; | |
| 1073 | 999 | assert_eq!( |
| 1074 | 1000 | res.status, |
| 1075 | 1001 | StatusCode::NOT_FOUND, |
| @@ -1094,7 +1020,7 @@ async fn probe_admin_targets_and_reset_revokes_all_sessions() { | ||
| 1094 | 1020 | .cookie |
| 1095 | 1021 | .expect("teacher session"); |
| 1096 | 1022 | |
| 1097 | - let reset = send( | |
| 1023 | + let reset = bsend( | |
| 1098 | 1024 | &app, |
| 1099 | 1025 | "POST", |
| 1100 | 1026 | "/schools/p4a/admin-password", |
| @@ -1105,7 +1031,7 @@ async fn probe_admin_targets_and_reset_revokes_all_sessions() { | ||
| 1105 | 1031 | assert_eq!(reset.status, StatusCode::NO_CONTENT); |
| 1106 | 1032 | for (n, cookie) in [(1, &s1), (2, &s2)] { |
| 1107 | 1033 | assert_eq!( |
| 1108 | - send(&app, "GET", "/auth/me", Some(cookie), None) | |
| 1034 | + bsend(&app, "GET", "/auth/me", Some(cookie), None) | |
| 1109 | 1035 | .await |
| 1110 | 1036 | .status, |
| 1111 | 1037 | StatusCode::UNAUTHORIZED, |
| @@ -1113,14 +1039,14 @@ async fn probe_admin_targets_and_reset_revokes_all_sessions() { | ||
| 1113 | 1039 | ); |
| 1114 | 1040 | } |
| 1115 | 1041 | assert_eq!( |
| 1116 | - send(&app, "GET", "/auth/me", Some(&tea), None).await.status, | |
| 1042 | + bsend(&app, "GET", "/auth/me", Some(&tea), None).await.status, | |
| 1117 | 1043 | StatusCode::OK, |
| 1118 | 1044 | "the reset revoked a bystander's session" |
| 1119 | 1045 | ); |
| 1120 | 1046 | |
| 1121 | 1047 | // `enter` on a suspended school is 403; `admin-password` still works. |
| 1122 | 1048 | assert_eq!( |
| 1123 | - send( | |
| 1049 | + bsend( | |
| 1124 | 1050 | &app, |
| 1125 | 1051 | "PATCH", |
| 1126 | 1052 | "/schools/p4a", |
| @@ -1131,7 +1057,7 @@ async fn probe_admin_targets_and_reset_revokes_all_sessions() { | ||
| 1131 | 1057 | .status, |
| 1132 | 1058 | StatusCode::OK |
| 1133 | 1059 | ); |
| 1134 | - let entered = send( | |
| 1060 | + let entered = bsend( | |
| 1135 | 1061 | &app, |
| 1136 | 1062 | "POST", |
| 1137 | 1063 | "/schools/p4a/enter", |
| @@ -1150,7 +1076,7 @@ async fn probe_admin_targets_and_reset_revokes_all_sessions() { | ||
| 1150 | 1076 | "a refused enter still set a school cookie" |
| 1151 | 1077 | ); |
| 1152 | 1078 | assert_eq!( |
| 1153 | - send( | |
| 1079 | + bsend( | |
| 1154 | 1080 | &app, |
| 1155 | 1081 | "POST", |
| 1156 | 1082 | "/schools/p4a/admin-password", |
| @@ -1177,11 +1103,11 @@ async fn probe_builder_session_hygiene() { | ||
| 1177 | 1103 | |
| 1178 | 1104 | // The builder's own token, worn as a school cookie. |
| 1179 | 1105 | for uri in ["/auth/me", "/users", "/notes"] { |
| 1180 | - let res = send( | |
| 1106 | + let res = bsend( | |
| 1181 | 1107 | &app, |
| 1182 | 1108 | "GET", |
| 1183 | 1109 | uri, |
| 1184 | - Some(&format!("session={DEMO_SLUG}.{builder_token}")), | |
| 1110 | + Some(&format!("session={DEMO_SCHOOL_ID}.{builder_token}")), | |
| 1185 | 1111 | None, |
| 1186 | 1112 | ) |
| 1187 | 1113 | .await; |
| @@ -1193,7 +1119,7 @@ async fn probe_builder_session_hygiene() { | ||
| 1193 | 1119 | } |
| 1194 | 1120 | // And a school token worn as a builder cookie. |
| 1195 | 1121 | for uri in ["/builder/me", "/schools"] { |
| 1196 | - let res = send( | |
| 1122 | + let res = bsend( | |
| 1197 | 1123 | &app, |
| 1198 | 1124 | "GET", |
| 1199 | 1125 | uri, |
| @@ -1210,7 +1136,7 @@ async fn probe_builder_session_hygiene() { | ||
| 1210 | 1136 | |
| 1211 | 1137 | // Logout is a server-side revocation: the same cookie is dead everywhere. |
| 1212 | 1138 | assert_eq!( |
| 1213 | - send(&app, "POST", "/builder/logout", Some(&builder), None) | |
| 1139 | + bsend(&app, "POST", "/builder/logout", Some(&builder), None) | |
| 1214 | 1140 | .await |
| 1215 | 1141 | .status, |
| 1216 | 1142 | StatusCode::NO_CONTENT |
| @@ -1223,14 +1149,14 @@ async fn probe_builder_session_hygiene() { | ||
| 1223 | 1149 | "/schools", |
| 1224 | 1150 | Some(json!({ |
| 1225 | 1151 | "slug": "p5ghost", |
| 1226 | - "name": "ghost", | |
| 1152 | + "name": "p5ghost school", | |
| 1227 | 1153 | "admin_username": "admin", |
| 1228 | 1154 | "admin_password": "secret1" |
| 1229 | 1155 | })), |
| 1230 | 1156 | ), |
| 1231 | 1157 | ("DELETE", "/schools/demo", None), |
| 1232 | 1158 | ] { |
| 1233 | - let res = send(&app, method, uri, Some(&builder), body).await; | |
| 1159 | + let res = bsend(&app, method, uri, Some(&builder), body).await; | |
| 1234 | 1160 | assert_eq!( |
| 1235 | 1161 | res.status, |
| 1236 | 1162 | StatusCode::UNAUTHORIZED, |
| @@ -1239,67 +1165,28 @@ async fn probe_builder_session_hygiene() { | ||
| 1239 | 1165 | } |
| 1240 | 1166 | // …and nothing was created or destroyed by those calls. |
| 1241 | 1167 | 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; | |
| 1243 | 1169 | assert!( |
| 1244 | - !slugs(&list.body).contains(&"p5ghost".to_string()), | |
| 1170 | + !school_names(&list.body).contains(&"p5ghost school"), | |
| 1245 | 1171 | "a logged-out builder created a school" |
| 1246 | 1172 | ); |
| 1247 | 1173 | assert!( |
| 1248 | - slugs(&list.body).contains(&DEMO_SLUG.to_string()), | |
| 1174 | + school_ids(&list.body).contains(&DEMO_SCHOOL_ID.to_string()), | |
| 1249 | 1175 | "a logged-out builder deleted the demo school" |
| 1250 | 1176 | ); |
| 1251 | 1177 | // Logout is idempotent and safe without a cookie. |
| 1252 | 1178 | assert_eq!( |
| 1253 | - send(&app, "POST", "/builder/logout", None, None) | |
| 1179 | + bsend(&app, "POST", "/builder/logout", None, None) | |
| 1254 | 1180 | .await |
| 1255 | 1181 | .status, |
| 1256 | 1182 | StatusCode::NO_CONTENT |
| 1257 | 1183 | ); |
| 1258 | 1184 | } |
| 1259 | 1185 | |
| 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. | |
| 1261 | 1188 | #[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() { | |
| 1303 | 1190 | let deployment = common::deployment_with(&[]).await; |
| 1304 | 1191 | let app = deployment.app; |
| 1305 | 1192 | builder::ensure( |
| @@ -1311,71 +1198,49 @@ async fn probe_remote_deployment_creates_and_deletes_a_hyphenated_school() { | ||
| 1311 | 1198 | .expect("seed the builder"); |
| 1312 | 1199 | |
| 1313 | 1200 | let builder = builder_login(&app).await; |
| 1314 | - // A plain slug proves the harness itself works. | |
| 1315 | 1201 | 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); | |
| 1316 | 1204 | 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") | |
| 1324 | 1206 | .await |
| 1325 | 1207 | .status, |
| 1326 | 1208 | StatusCode::OK |
| 1327 | 1209 | ); |
| 1328 | 1210 | |
| 1329 | - // The advertised, hyphenated slug. Collect the whole chain before asserting, | |
| 1330 | - // so a failure reports the state the deployment is left in. | |
| 1331 | 1211 | 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); | |
| 1370 | 1233 | assert!( |
| 1371 | 1234 | login_after_delete |
| 1372 | 1235 | .cookie |
| 1373 | 1236 | .expect("cookie") |
| 1374 | - .contains("atakoleji."), | |
| 1237 | + .contains(&format!("{plain_id}.")), | |
| 1375 | 1238 | "the deleted school must not come back at login" |
| 1376 | 1239 | ); |
| 1377 | 1240 | } |
| 1378 | 1241 | |
| 1242 | + | |
| 1243 | + | |
| 1379 | 1244 | // --------------------------------------------------------------------------- |
| 1380 | 1245 | // Module entitlements: the vendor's shelf. Every assertion here is about the |
| 1381 | 1246 | // 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> { | ||
| 1393 | 1258 | } |
| 1394 | 1259 | |
| 1395 | 1260 | async fn school_modules(app: &Router, cookie: &str, slug: &str) -> Res { |
| 1396 | - send( | |
| 1261 | + bsend( | |
| 1397 | 1262 | app, |
| 1398 | 1263 | "GET", |
| 1399 | 1264 | &format!("/schools/{slug}/modules"), |
| @@ -1408,7 +1273,7 @@ async fn a_school_starts_with_everything_and_one_module_toggles_back_and_forth() | ||
| 1408 | 1273 | let (app, _db, _tenants) = deployment().await; |
| 1409 | 1274 | let builder = builder_login(&app).await; |
| 1410 | 1275 | |
| 1411 | - let listed = school_modules(&app, &builder, DEMO_SLUG).await; | |
| 1276 | + let listed = school_modules(&app, &builder, DEMO_SCHOOL_ID).await; | |
| 1412 | 1277 | assert_eq!(listed.status, StatusCode::OK, "{:?}", listed.body); |
| 1413 | 1278 | assert_eq!(enabled(&listed.body).len(), 21, "{:?}", listed.body); |
| 1414 | 1279 | assert_eq!( |
| @@ -1416,10 +1281,10 @@ async fn a_school_starts_with_everything_and_one_module_toggles_back_and_forth() | ||
| 1416 | 1281 | &[] as &[Value] |
| 1417 | 1282 | ); |
| 1418 | 1283 | |
| 1419 | - let off = send( | |
| 1284 | + let off = bsend( | |
| 1420 | 1285 | &app, |
| 1421 | 1286 | "DELETE", |
| 1422 | - &format!("/schools/{DEMO_SLUG}/modules/notes"), | |
| 1287 | + &format!("/schools/{DEMO_SCHOOL_ID}/modules/notes"), | |
| 1423 | 1288 | Some(&builder), |
| 1424 | 1289 | None, |
| 1425 | 1290 | ) |
| @@ -1428,16 +1293,16 @@ async fn a_school_starts_with_everything_and_one_module_toggles_back_and_forth() | ||
| 1428 | 1293 | assert_eq!(off.body["disabled"], json!(["notes"])); |
| 1429 | 1294 | assert!(!enabled(&off.body).contains(&"notes".to_string())); |
| 1430 | 1295 | assert_eq!( |
| 1431 | - school_modules(&app, &builder, DEMO_SLUG).await.body, | |
| 1296 | + school_modules(&app, &builder, DEMO_SCHOOL_ID).await.body, | |
| 1432 | 1297 | off.body, |
| 1433 | 1298 | "the GET must show what the DELETE answered" |
| 1434 | 1299 | ); |
| 1435 | 1300 | |
| 1436 | 1301 | // Idempotent both ways: taking back what is already gone changes nothing. |
| 1437 | - let again = send( | |
| 1302 | + let again = bsend( | |
| 1438 | 1303 | &app, |
| 1439 | 1304 | "DELETE", |
| 1440 | - &format!("/schools/{DEMO_SLUG}/modules/notes"), | |
| 1305 | + &format!("/schools/{DEMO_SCHOOL_ID}/modules/notes"), | |
| 1441 | 1306 | Some(&builder), |
| 1442 | 1307 | None, |
| 1443 | 1308 | ) |
| @@ -1445,20 +1310,20 @@ async fn a_school_starts_with_everything_and_one_module_toggles_back_and_forth() | ||
| 1445 | 1310 | assert_eq!(again.status, StatusCode::OK); |
| 1446 | 1311 | assert_eq!(again.body, off.body); |
| 1447 | 1312 | |
| 1448 | - let on = send( | |
| 1313 | + let on = bsend( | |
| 1449 | 1314 | &app, |
| 1450 | 1315 | "POST", |
| 1451 | - &format!("/schools/{DEMO_SLUG}/modules/notes"), | |
| 1316 | + &format!("/schools/{DEMO_SCHOOL_ID}/modules/notes"), | |
| 1452 | 1317 | Some(&builder), |
| 1453 | 1318 | None, |
| 1454 | 1319 | ) |
| 1455 | 1320 | .await; |
| 1456 | 1321 | assert_eq!(on.status, StatusCode::OK, "{:?}", on.body); |
| 1457 | 1322 | assert_eq!(on.body, listed.body, "back to the full shelf"); |
| 1458 | - let once_more = send( | |
| 1323 | + let once_more = bsend( | |
| 1459 | 1324 | &app, |
| 1460 | 1325 | "POST", |
| 1461 | - &format!("/schools/{DEMO_SLUG}/modules/notes"), | |
| 1326 | + &format!("/schools/{DEMO_SCHOOL_ID}/modules/notes"), | |
| 1462 | 1327 | Some(&builder), |
| 1463 | 1328 | None, |
| 1464 | 1329 | ) |
| @@ -1467,10 +1332,10 @@ async fn a_school_starts_with_everything_and_one_module_toggles_back_and_forth() | ||
| 1467 | 1332 | assert_eq!(once_more.body, listed.body); |
| 1468 | 1333 | |
| 1469 | 1334 | // A name nobody sells addresses nothing. |
| 1470 | - let ghost = send( | |
| 1335 | + let ghost = bsend( | |
| 1471 | 1336 | &app, |
| 1472 | 1337 | "POST", |
| 1473 | - &format!("/schools/{DEMO_SLUG}/modules/kantin"), | |
| 1338 | + &format!("/schools/{DEMO_SCHOOL_ID}/modules/kantin"), | |
| 1474 | 1339 | Some(&builder), |
| 1475 | 1340 | None, |
| 1476 | 1341 | ) |
| @@ -1484,14 +1349,14 @@ async fn a_dependency_is_named_whichever_direction_breaks_it() { | ||
| 1484 | 1349 | let builder = builder_login(&app).await; |
| 1485 | 1350 | |
| 1486 | 1351 | // Enabling: a lone school that bought only notes cannot take exams alone. |
| 1487 | - let created = send( | |
| 1352 | + let created = bsend( | |
| 1488 | 1353 | &app, |
| 1489 | 1354 | "POST", |
| 1490 | 1355 | "/schools", |
| 1491 | 1356 | Some(&builder), |
| 1492 | 1357 | Some(json!({ |
| 1493 | 1358 | "slug": "lone", |
| 1494 | - "name": "Lone", | |
| 1359 | + "name": "lone school", | |
| 1495 | 1360 | "admin_username": "admin", |
| 1496 | 1361 | "admin_password": "secret1", |
| 1497 | 1362 | "modules": ["notes"], |
| @@ -1499,7 +1364,7 @@ async fn a_dependency_is_named_whichever_direction_breaks_it() { | ||
| 1499 | 1364 | ) |
| 1500 | 1365 | .await; |
| 1501 | 1366 | assert_eq!(created.status, StatusCode::CREATED, "{:?}", created.body); |
| 1502 | - let refused = send( | |
| 1367 | + let refused = bsend( | |
| 1503 | 1368 | &app, |
| 1504 | 1369 | "POST", |
| 1505 | 1370 | "/schools/lone/modules/exams", |
| @@ -1517,10 +1382,10 @@ async fn a_dependency_is_named_whichever_direction_breaks_it() { | ||
| 1517 | 1382 | ); |
| 1518 | 1383 | |
| 1519 | 1384 | // Disabling: what is still needed says so, by name. |
| 1520 | - let held = send( | |
| 1385 | + let held = bsend( | |
| 1521 | 1386 | &app, |
| 1522 | 1387 | "DELETE", |
| 1523 | - &format!("/schools/{DEMO_SLUG}/modules/exams"), | |
| 1388 | + &format!("/schools/{DEMO_SCHOOL_ID}/modules/exams"), | |
| 1524 | 1389 | Some(&builder), |
| 1525 | 1390 | None, |
| 1526 | 1391 | ) |
| @@ -1528,10 +1393,10 @@ async fn a_dependency_is_named_whichever_direction_breaks_it() { | ||
| 1528 | 1393 | assert_eq!(held.status, StatusCode::CONFLICT, "{:?}", held.body); |
| 1529 | 1394 | assert_eq!(held.body["error"], json!("exams is required by marks")); |
| 1530 | 1395 | |
| 1531 | - let courses = send( | |
| 1396 | + let courses = bsend( | |
| 1532 | 1397 | &app, |
| 1533 | 1398 | "DELETE", |
| 1534 | - &format!("/schools/{DEMO_SLUG}/modules/courses"), | |
| 1399 | + &format!("/schools/{DEMO_SCHOOL_ID}/modules/courses"), | |
| 1535 | 1400 | Some(&builder), |
| 1536 | 1401 | None, |
| 1537 | 1402 | ) |
| @@ -1552,7 +1417,7 @@ async fn a_dependency_is_named_whichever_direction_breaks_it() { | ||
| 1552 | 1417 | ); |
| 1553 | 1418 | } |
| 1554 | 1419 | 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(), | |
| 1556 | 1421 | 21 |
| 1557 | 1422 | ); |
| 1558 | 1423 | } |
| @@ -1561,7 +1426,7 @@ async fn a_dependency_is_named_whichever_direction_breaks_it() { | ||
| 1561 | 1426 | async fn a_batch_is_all_or_nothing_and_packages_round_trip() { |
| 1562 | 1427 | let (app, _db, _tenants) = deployment().await; |
| 1563 | 1428 | 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(); | |
| 1565 | 1430 | |
| 1566 | 1431 | // One bad name in a list voids the whole request. |
| 1567 | 1432 | for (body, field) in [ |
| @@ -1571,10 +1436,10 @@ async fn a_batch_is_all_or_nothing_and_packages_round_trip() { | ||
| 1571 | 1436 | ), |
| 1572 | 1437 | (json!({ "enable_packages": ["kantin"] }), "package"), |
| 1573 | 1438 | ] { |
| 1574 | - let bad = send( | |
| 1439 | + let bad = bsend( | |
| 1575 | 1440 | &app, |
| 1576 | 1441 | "PATCH", |
| 1577 | - &format!("/schools/{DEMO_SLUG}/modules"), | |
| 1442 | + &format!("/schools/{DEMO_SCHOOL_ID}/modules"), | |
| 1578 | 1443 | Some(&builder), |
| 1579 | 1444 | Some(body), |
| 1580 | 1445 | ) |
| @@ -1585,14 +1450,14 @@ async fn a_batch_is_all_or_nothing_and_packages_round_trip() { | ||
| 1585 | 1450 | message.contains("kantin") && message.contains(field), |
| 1586 | 1451 | "{message}" |
| 1587 | 1452 | ); |
| 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); | |
| 1589 | 1454 | } |
| 1590 | 1455 | |
| 1591 | 1456 | // A name pulled both ways at once has no answer. |
| 1592 | - let both = send( | |
| 1457 | + let both = bsend( | |
| 1593 | 1458 | &app, |
| 1594 | 1459 | "PATCH", |
| 1595 | - &format!("/schools/{DEMO_SLUG}/modules"), | |
| 1460 | + &format!("/schools/{DEMO_SCHOOL_ID}/modules"), | |
| 1596 | 1461 | Some(&builder), |
| 1597 | 1462 | Some(json!({ "enable": ["meals"], "disable": ["meals"] })), |
| 1598 | 1463 | ) |
| @@ -1606,13 +1471,13 @@ async fn a_batch_is_all_or_nothing_and_packages_round_trip() { | ||
| 1606 | 1471 | "{:?}", |
| 1607 | 1472 | both.body |
| 1608 | 1473 | ); |
| 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); | |
| 1610 | 1475 | |
| 1611 | 1476 | // A resulting set that breaks a dependency is refused as a whole. |
| 1612 | - let orphaned = send( | |
| 1477 | + let orphaned = bsend( | |
| 1613 | 1478 | &app, |
| 1614 | 1479 | "PATCH", |
| 1615 | - &format!("/schools/{DEMO_SLUG}/modules"), | |
| 1480 | + &format!("/schools/{DEMO_SCHOOL_ID}/modules"), | |
| 1616 | 1481 | Some(&builder), |
| 1617 | 1482 | Some(json!({ "disable": ["exams"] })), |
| 1618 | 1483 | ) |
| @@ -1626,13 +1491,13 @@ async fn a_batch_is_all_or_nothing_and_packages_round_trip() { | ||
| 1626 | 1491 | "{:?}", |
| 1627 | 1492 | orphaned.body |
| 1628 | 1493 | ); |
| 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); | |
| 1630 | 1495 | |
| 1631 | 1496 | // An empty body is a no-op, not an error. |
| 1632 | - let empty = send( | |
| 1497 | + let empty = bsend( | |
| 1633 | 1498 | &app, |
| 1634 | 1499 | "PATCH", |
| 1635 | - &format!("/schools/{DEMO_SLUG}/modules"), | |
| 1500 | + &format!("/schools/{DEMO_SCHOOL_ID}/modules"), | |
| 1636 | 1501 | Some(&builder), |
| 1637 | 1502 | Some(json!({})), |
| 1638 | 1503 | ) |
| @@ -1641,10 +1506,10 @@ async fn a_batch_is_all_or_nothing_and_packages_round_trip() { | ||
| 1641 | 1506 | assert_eq!(empty.body, before); |
| 1642 | 1507 | |
| 1643 | 1508 | // A whole package off and back on again, each in one call. |
| 1644 | - let sold_back = send( | |
| 1509 | + let sold_back = bsend( | |
| 1645 | 1510 | &app, |
| 1646 | 1511 | "PATCH", |
| 1647 | - &format!("/schools/{DEMO_SLUG}/modules"), | |
| 1512 | + &format!("/schools/{DEMO_SCHOOL_ID}/modules"), | |
| 1648 | 1513 | Some(&builder), |
| 1649 | 1514 | Some(json!({ "disable_packages": ["academics"] })), |
| 1650 | 1515 | ) |
| @@ -1667,14 +1532,14 @@ async fn a_batch_is_all_or_nothing_and_packages_round_trip() { | ||
| 1667 | 1532 | ] |
| 1668 | 1533 | ); |
| 1669 | 1534 | assert_eq!( |
| 1670 | - school_modules(&app, &builder, DEMO_SLUG).await.body, | |
| 1535 | + school_modules(&app, &builder, DEMO_SCHOOL_ID).await.body, | |
| 1671 | 1536 | sold_back.body |
| 1672 | 1537 | ); |
| 1673 | 1538 | |
| 1674 | - let resold = send( | |
| 1539 | + let resold = bsend( | |
| 1675 | 1540 | &app, |
| 1676 | 1541 | "PATCH", |
| 1677 | - &format!("/schools/{DEMO_SLUG}/modules"), | |
| 1542 | + &format!("/schools/{DEMO_SCHOOL_ID}/modules"), | |
| 1678 | 1543 | Some(&builder), |
| 1679 | 1544 | Some(json!({ "enable_packages": ["academics"] })), |
| 1680 | 1545 | ) |
| @@ -1692,13 +1557,13 @@ async fn only_a_builder_sells_modules_and_the_school_feels_it_at_once() { | ||
| 1692 | 1557 | let student = login(&app, "ali").await; |
| 1693 | 1558 | |
| 1694 | 1559 | 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")), | |
| 1699 | 1564 | ] { |
| 1700 | 1565 | 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; | |
| 1702 | 1567 | assert_eq!( |
| 1703 | 1568 | res.status, |
| 1704 | 1569 | StatusCode::UNAUTHORIZED, |
| @@ -1706,34 +1571,34 @@ async fn only_a_builder_sells_modules_and_the_school_feels_it_at_once() { | ||
| 1706 | 1571 | ); |
| 1707 | 1572 | } |
| 1708 | 1573 | |
| 1709 | - let menus = send(&app, "GET", "/meals/menus", Some(&student), None).await; | |
| 1574 | + let menus = bsend(&app, "GET", "/meals/menus", Some(&student), None).await; | |
| 1710 | 1575 | assert_eq!(menus.status, StatusCode::OK, "{:?}", menus.body); |
| 1711 | 1576 | |
| 1712 | - let off = send( | |
| 1577 | + let off = bsend( | |
| 1713 | 1578 | &app, |
| 1714 | 1579 | "DELETE", |
| 1715 | - &format!("/schools/{DEMO_SLUG}/modules/meals"), | |
| 1580 | + &format!("/schools/{DEMO_SCHOOL_ID}/modules/meals"), | |
| 1716 | 1581 | Some(&builder), |
| 1717 | 1582 | None, |
| 1718 | 1583 | ) |
| 1719 | 1584 | .await; |
| 1720 | 1585 | assert_eq!(off.status, StatusCode::OK, "{:?}", off.body); |
| 1721 | 1586 | |
| 1722 | - let refused = send(&app, "GET", "/meals/menus", Some(&student), None).await; | |
| 1587 | + let refused = bsend(&app, "GET", "/meals/menus", Some(&student), None).await; | |
| 1723 | 1588 | assert_eq!(refused.status, StatusCode::FORBIDDEN, "{:?}", refused.body); |
| 1724 | 1589 | assert_eq!(refused.body["module"], "meals"); |
| 1725 | 1590 | |
| 1726 | - let on = send( | |
| 1591 | + let on = bsend( | |
| 1727 | 1592 | &app, |
| 1728 | 1593 | "POST", |
| 1729 | - &format!("/schools/{DEMO_SLUG}/modules/meals"), | |
| 1594 | + &format!("/schools/{DEMO_SCHOOL_ID}/modules/meals"), | |
| 1730 | 1595 | Some(&builder), |
| 1731 | 1596 | None, |
| 1732 | 1597 | ) |
| 1733 | 1598 | .await; |
| 1734 | 1599 | assert_eq!(on.status, StatusCode::OK, "{:?}", on.body); |
| 1735 | 1600 | assert_eq!( |
| 1736 | - send(&app, "GET", "/meals/menus", Some(&student), None) | |
| 1601 | + bsend(&app, "GET", "/meals/menus", Some(&student), None) | |
| 1737 | 1602 | .await |
| 1738 | 1603 | .status, |
| 1739 | 1604 | StatusCode::OK, |
| @@ -1748,14 +1613,14 @@ async fn a_school_is_created_with_the_modules_it_bought() { | ||
| 1748 | 1613 | let (app, _db, _tenants) = deployment().await; |
| 1749 | 1614 | let builder = builder_login(&app).await; |
| 1750 | 1615 | |
| 1751 | - let created = send( | |
| 1616 | + let created = bsend( | |
| 1752 | 1617 | &app, |
| 1753 | 1618 | "POST", |
| 1754 | 1619 | "/schools", |
| 1755 | 1620 | Some(&builder), |
| 1756 | 1621 | Some(json!({ |
| 1757 | 1622 | "slug": "notes-only", |
| 1758 | - "name": "Notes Only", | |
| 1623 | + "name": "notes-only school", | |
| 1759 | 1624 | "admin_username": "admin", |
| 1760 | 1625 | "admin_password": "secret1", |
| 1761 | 1626 | "modules": ["notes"], |
| @@ -1764,7 +1629,7 @@ async fn a_school_is_created_with_the_modules_it_bought() { | ||
| 1764 | 1629 | .await; |
| 1765 | 1630 | assert_eq!(created.status, StatusCode::CREATED, "{:?}", created.body); |
| 1766 | 1631 | 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; | |
| 1768 | 1633 | assert_eq!(read.body["modules"], json!(["notes"])); |
| 1769 | 1634 | assert_eq!( |
| 1770 | 1635 | enabled(&school_modules(&app, &builder, "notes-only").await.body), |
| @@ -1777,15 +1642,15 @@ async fn a_school_is_created_with_the_modules_it_bought() { | ||
| 1777 | 1642 | ] { |
| 1778 | 1643 | let mut request = json!({ |
| 1779 | 1644 | "slug": "doomed", |
| 1780 | - "name": "Doomed", | |
| 1645 | + "name": "doomed school", | |
| 1781 | 1646 | "admin_username": "admin", |
| 1782 | 1647 | "admin_password": "secret1", |
| 1783 | 1648 | }); |
| 1784 | 1649 | 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; | |
| 1786 | 1651 | assert_eq!(res.status, status, "{:?}", res.body); |
| 1787 | 1652 | assert_eq!( |
| 1788 | - send(&app, "GET", "/schools/doomed", Some(&builder), None) | |
| 1653 | + bsend(&app, "GET", "/schools/doomed", Some(&builder), None) | |
| 1789 | 1654 | .await |
| 1790 | 1655 | .status, |
| 1791 | 1656 | StatusCode::NOT_FOUND, |
| @@ -1805,7 +1670,7 @@ async fn a_school_is_created_with_the_modules_it_bought() { | ||
| 1805 | 1670 | async fn the_catalog_is_public_and_a_school_user_reads_its_own_set() { |
| 1806 | 1671 | let (app, _db, _tenants) = deployment().await; |
| 1807 | 1672 | |
| 1808 | - let catalog = send(&app, "GET", "/modules/catalog", None, None).await; | |
| 1673 | + let catalog = bsend(&app, "GET", "/modules/catalog", None, None).await; | |
| 1809 | 1674 | assert_eq!(catalog.status, StatusCode::OK, "{:?}", catalog.body); |
| 1810 | 1675 | let modules = catalog.body["modules"].as_array().expect("modules").clone(); |
| 1811 | 1676 | assert_eq!(modules.len(), 21); |
| @@ -1831,11 +1696,11 @@ async fn the_catalog_is_public_and_a_school_user_reads_its_own_set() { | ||
| 1831 | 1696 | } |
| 1832 | 1697 | |
| 1833 | 1698 | 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; | |
| 1835 | 1700 | assert_eq!(mine.status, StatusCode::OK, "{:?}", mine.body); |
| 1836 | 1701 | assert_eq!(enabled(&mine.body), names); |
| 1837 | 1702 | assert_eq!( |
| 1838 | - send(&app, "GET", "/modules", None, None).await.status, | |
| 1703 | + bsend(&app, "GET", "/modules", None, None).await.status, | |
| 1839 | 1704 | StatusCode::UNAUTHORIZED |
| 1840 | 1705 | ); |
| 1841 | 1706 | } |
| @@ -1849,14 +1714,14 @@ async fn the_catalog_is_public_and_a_school_user_reads_its_own_set() { | ||
| 1849 | 1714 | async fn probe_a_module_less_school_still_works() { |
| 1850 | 1715 | let (app, _db, _tenants) = deployment().await; |
| 1851 | 1716 | let builder = builder_login(&app).await; |
| 1852 | - let created = send( | |
| 1717 | + let created = bsend( | |
| 1853 | 1718 | &app, |
| 1854 | 1719 | "POST", |
| 1855 | 1720 | "/schools", |
| 1856 | 1721 | Some(&builder), |
| 1857 | 1722 | Some(json!({ |
| 1858 | 1723 | "slug": "bare", |
| 1859 | - "name": "Bare School", | |
| 1724 | + "name": "bare school", | |
| 1860 | 1725 | "admin_username": "admin", |
| 1861 | 1726 | "admin_password": "secret1", |
| 1862 | 1727 | "modules": [], |
| @@ -1879,7 +1744,7 @@ async fn probe_a_module_less_school_still_works() { | ||
| 1879 | 1744 | "/modules", |
| 1880 | 1745 | "/modules/catalog", |
| 1881 | 1746 | ] { |
| 1882 | - let res = send(&app, "GET", path, Some(&cookie), None).await; | |
| 1747 | + let res = bsend(&app, "GET", path, Some(&cookie), None).await; | |
| 1883 | 1748 | assert_eq!( |
| 1884 | 1749 | res.status, |
| 1885 | 1750 | StatusCode::OK, |
| @@ -1888,10 +1753,10 @@ async fn probe_a_module_less_school_still_works() { | ||
| 1888 | 1753 | res.body |
| 1889 | 1754 | ); |
| 1890 | 1755 | } |
| 1891 | - let mine = send(&app, "GET", "/modules", Some(&cookie), None).await; | |
| 1756 | + let mine = bsend(&app, "GET", "/modules", Some(&cookie), None).await; | |
| 1892 | 1757 | assert_eq!(mine.body["enabled"], json!([])); |
| 1893 | 1758 | |
| 1894 | - let prefs = send( | |
| 1759 | + let prefs = bsend( | |
| 1895 | 1760 | &app, |
| 1896 | 1761 | "PATCH", |
| 1897 | 1762 | "/users/me/preferences", |
| @@ -1914,10 +1779,10 @@ async fn probe_narrowing_every_package_away_leaves_the_school_usable() { | ||
| 1914 | 1779 | let builder = builder_login(&app).await; |
| 1915 | 1780 | let cookie = login_as(&app, &db, "boss", "admin").await; |
| 1916 | 1781 | |
| 1917 | - let res = send( | |
| 1782 | + let res = bsend( | |
| 1918 | 1783 | &app, |
| 1919 | 1784 | "PATCH", |
| 1920 | - &format!("/schools/{DEMO_SLUG}/modules"), | |
| 1785 | + &format!("/schools/{DEMO_SCHOOL_ID}/modules"), | |
| 1921 | 1786 | Some(&builder), |
| 1922 | 1787 | Some(json!({ |
| 1923 | 1788 | "disable_packages": ["academics", "communication", "operations", "ai"], |
| @@ -1935,7 +1800,7 @@ async fn probe_narrowing_every_package_away_leaves_the_school_usable() { | ||
| 1935 | 1800 | "/users/me/profile", |
| 1936 | 1801 | "/modules", |
| 1937 | 1802 | ] { |
| 1938 | - let r = send(&app, "GET", path, Some(&cookie), None).await; | |
| 1803 | + let r = bsend(&app, "GET", path, Some(&cookie), None).await; | |
| 1939 | 1804 | assert_eq!( |
| 1940 | 1805 | r.status, |
| 1941 | 1806 | StatusCode::OK, |
| @@ -1945,7 +1810,7 @@ async fn probe_narrowing_every_package_away_leaves_the_school_usable() { | ||
| 1945 | 1810 | ); |
| 1946 | 1811 | } |
| 1947 | 1812 | assert_eq!( |
| 1948 | - send(&app, "GET", "/modules", Some(&cookie), None) | |
| 1813 | + bsend(&app, "GET", "/modules", Some(&cookie), None) | |
| 1949 | 1814 | .await |
| 1950 | 1815 | .body["enabled"], |
| 1951 | 1816 | json!([]) |
| @@ -1958,7 +1823,7 @@ async fn probe_no_route_refuses_a_module_a_school_has() { | ||
| 1958 | 1823 | let (app, db, _tenants) = deployment().await; |
| 1959 | 1824 | let cookie = login_as(&app, &db, "boss", "admin").await; |
| 1960 | 1825 | |
| 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; | |
| 1962 | 1827 | assert_eq!(spec.status, StatusCode::OK, "openapi spec"); |
| 1963 | 1828 | let paths = spec.body["paths"].as_object().expect("paths object"); |
| 1964 | 1829 | 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() { | ||
| 1980 | 1845 | }) |
| 1981 | 1846 | .collect::<Vec<_>>() |
| 1982 | 1847 | .join("/"); |
| 1983 | - let res = send(&app, "GET", &concrete, Some(&cookie), None).await; | |
| 1848 | + let res = bsend(&app, "GET", &concrete, Some(&cookie), None).await; | |
| 1984 | 1849 | swept += 1; |
| 1985 | 1850 | if res.body.get("error").and_then(|e| e.as_str()) == Some("module disabled") { |
| 1986 | 1851 | refused.push(format!("{concrete} -> {} {:?}", res.status, res.body)); |
| @@ -2001,17 +1866,17 @@ async fn probe_no_route_refuses_a_module_a_school_has() { | ||
| 2001 | 1866 | async fn probe_gate_ordering_versus_auth() { |
| 2002 | 1867 | let (app, _db, _tenants) = deployment().await; |
| 2003 | 1868 | let builder = builder_login(&app).await; |
| 2004 | - let off = send( | |
| 1869 | + let off = bsend( | |
| 2005 | 1870 | &app, |
| 2006 | 1871 | "DELETE", |
| 2007 | - &format!("/schools/{DEMO_SLUG}/modules/meals"), | |
| 1872 | + &format!("/schools/{DEMO_SCHOOL_ID}/modules/meals"), | |
| 2008 | 1873 | Some(&builder), |
| 2009 | 1874 | None, |
| 2010 | 1875 | ) |
| 2011 | 1876 | .await; |
| 2012 | 1877 | assert_eq!(off.status, StatusCode::OK, "{:?}", off.body); |
| 2013 | 1878 | |
| 2014 | - let anon = send(&app, "GET", "/meals/menus", None, None).await; | |
| 1879 | + let anon = bsend(&app, "GET", "/meals/menus", None, None).await; | |
| 2015 | 1880 | assert_eq!( |
| 2016 | 1881 | anon.status, |
| 2017 | 1882 | StatusCode::UNAUTHORIZED, |
| @@ -2026,7 +1891,7 @@ async fn probe_gate_ordering_versus_auth() { | ||
| 2026 | 1891 | anon.body |
| 2027 | 1892 | ); |
| 2028 | 1893 | |
| 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; | |
| 2030 | 1895 | assert_eq!( |
| 2031 | 1896 | as_builder.status, |
| 2032 | 1897 | StatusCode::UNAUTHORIZED, |
| @@ -2045,18 +1910,24 @@ async fn probe_disabling_in_one_school_leaves_the_other_alone() { | ||
| 2045 | 1910 | let res = create_school(&app, &builder, slug, "secret1").await; |
| 2046 | 1911 | assert_eq!(res.status, StatusCode::CREATED, "{slug}: {:?}", res.body); |
| 2047 | 1912 | } |
| 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( | |
| 2060 | 1931 | &app, |
| 2061 | 1932 | "DELETE", |
| 2062 | 1933 | "/schools/alpha/modules/meals", |
| @@ -2066,10 +1937,10 @@ async fn probe_disabling_in_one_school_leaves_the_other_alone() { | ||
| 2066 | 1937 | .await; |
| 2067 | 1938 | assert_eq!(off.status, StatusCode::OK, "{:?}", off.body); |
| 2068 | 1939 | |
| 2069 | - let a = send(&app, "GET", "/meals/menus", Some(&alpha), None).await; | |
| 1940 | + let a = bsend(&app, "GET", "/meals/menus", Some(&alpha), None).await; | |
| 2070 | 1941 | assert_eq!(a.status, StatusCode::FORBIDDEN, "{:?}", a.body); |
| 2071 | 1942 | 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; | |
| 2073 | 1944 | assert_eq!( |
| 2074 | 1945 | b.status, |
| 2075 | 1946 | StatusCode::OK, |
| @@ -2090,19 +1961,19 @@ async fn probe_a_refused_batch_leaves_the_row_byte_identical() { | ||
| 2090 | 1961 | sqlx::query_scalar( |
| 2091 | 1962 | "SELECT sm.module FROM school_module sm |
| 2092 | 1963 | 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", | |
| 2094 | 1965 | ) |
| 2095 | - .bind(DEMO_SLUG) | |
| 1966 | + .bind(hezarfen_backend::tenant::SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap().uuid()) | |
| 2096 | 1967 | .fetch_all(tenants.control()) |
| 2097 | 1968 | .await |
| 2098 | 1969 | .expect("raw read") |
| 2099 | 1970 | } |
| 2100 | 1971 | |
| 2101 | 1972 | let before = raw_row(&tenants).await; |
| 2102 | - let res = send( | |
| 1973 | + let res = bsend( | |
| 2103 | 1974 | &app, |
| 2104 | 1975 | "PATCH", |
| 2105 | - &format!("/schools/{DEMO_SLUG}/modules"), | |
| 1976 | + &format!("/schools/{DEMO_SCHOOL_ID}/modules"), | |
| 2106 | 1977 | Some(&builder), |
| 2107 | 1978 | Some(json!({ "enable": ["exams"], "disable": ["courses"] })), |
| 2108 | 1979 | ) |
| @@ -2174,7 +2045,7 @@ async fn probe_registry_reads_per_request() { | ||
| 2174 | 2045 | let (app, db, _tenants) = deployment().await; |
| 2175 | 2046 | let cookie = login_as(&app, &db, "boss", "admin").await; |
| 2176 | 2047 | 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; | |
| 2178 | 2049 | assert_eq!(res.status, StatusCode::OK, "{:?}", res.body); |
| 2179 | 2050 | let seen = count.load(Ordering::Relaxed); |
| 2180 | 2051 | 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() { | ||
| 2195 | 2066 | |
| 2196 | 2067 | // Exams off, courses still on: the child pair must refuse as `exams`. |
| 2197 | 2068 | for module in ["marks", "exams"] { |
| 2198 | - let off = send( | |
| 2069 | + let off = bsend( | |
| 2199 | 2070 | &app, |
| 2200 | 2071 | "DELETE", |
| 2201 | - &format!("/schools/{DEMO_SLUG}/modules/{module}"), | |
| 2072 | + &format!("/schools/{DEMO_SCHOOL_ID}/modules/{module}"), | |
| 2202 | 2073 | Some(&builder), |
| 2203 | 2074 | None, |
| 2204 | 2075 | ) |
| 2205 | 2076 | .await; |
| 2206 | 2077 | assert_eq!(off.status, StatusCode::OK, "{module}: {:?}", off.body); |
| 2207 | 2078 | } |
| 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; | |
| 2209 | 2080 | assert_eq!( |
| 2210 | 2081 | child.status, |
| 2211 | 2082 | StatusCode::FORBIDDEN, |
| @@ -2215,10 +2086,10 @@ async fn probe_child_gates_under_courses_and_the_404_inside_a_disabled_nest() { | ||
| 2215 | 2086 | ); |
| 2216 | 2087 | assert_eq!(child.body["module"], "exams", "{:?}", child.body); |
| 2217 | 2088 | // …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; | |
| 2219 | 2090 | assert_eq!(parent.status, StatusCode::OK, "{:?}", parent.body); |
| 2220 | 2091 | // 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; | |
| 2222 | 2093 | assert_ne!( |
| 2223 | 2094 | sibling.status, |
| 2224 | 2095 | StatusCode::FORBIDDEN, |
| @@ -2227,16 +2098,16 @@ async fn probe_child_gates_under_courses_and_the_404_inside_a_disabled_nest() { | ||
| 2227 | 2098 | ); |
| 2228 | 2099 | |
| 2229 | 2100 | // A disabled nest is a refusal on the routes that exist, not a wall. |
| 2230 | - let off = send( | |
| 2101 | + let off = bsend( | |
| 2231 | 2102 | &app, |
| 2232 | 2103 | "DELETE", |
| 2233 | - &format!("/schools/{DEMO_SLUG}/modules/meals"), | |
| 2104 | + &format!("/schools/{DEMO_SCHOOL_ID}/modules/meals"), | |
| 2234 | 2105 | Some(&builder), |
| 2235 | 2106 | None, |
| 2236 | 2107 | ) |
| 2237 | 2108 | .await; |
| 2238 | 2109 | 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; | |
| 2240 | 2111 | assert_eq!( |
| 2241 | 2112 | ghost.status, |
| 2242 | 2113 | StatusCode::NOT_FOUND, |
| @@ -2244,6 +2115,6 @@ async fn probe_child_gates_under_courses_and_the_404_inside_a_disabled_nest() { | ||
| 2244 | 2115 | ghost.status, |
| 2245 | 2116 | ghost.body |
| 2246 | 2117 | ); |
| 2247 | - let real = send(&app, "GET", "/meals/menus", Some(&cookie), None).await; | |
| 2118 | + let real = bsend(&app, "GET", "/meals/menus", Some(&cookie), None).await; | |
| 2248 | 2119 | assert_eq!(real.status, StatusCode::FORBIDDEN, "{:?}", real.body); |
| 2249 | 2120 | } |
tests/common/mod.rsmodified+30 -15
| @@ -17,7 +17,7 @@ use hezarfen_backend::module::ModuleSet; | ||
| 17 | 17 | use hezarfen_backend::rate_limit::RateLimitConfig; |
| 18 | 18 | use hezarfen_backend::state::AppState; |
| 19 | 19 | 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}; | |
| 21 | 21 | use hezarfen_backend::{build_router, database}; |
| 22 | 22 | use serde_json::{Value, json}; |
| 23 | 23 | use tempfile::TempDir; |
| @@ -65,10 +65,29 @@ pub async fn app_and_tenants() -> (Router, Database, Tenants) { | ||
| 65 | 65 | (app, db, tenants) |
| 66 | 66 | } |
| 67 | 67 | |
| 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 | + | |
| 68 | 87 | /// Where the demo school's blobs land: one directory per school under |
| 69 | 88 | /// `FILES_PATH`, created on the school's first upload. |
| 70 | 89 | pub fn blob_dir() -> PathBuf { |
| 71 | - let dir = files_dir().join(DEMO_SLUG); | |
| 90 | + let dir = files_dir().join(DEMO_SCHOOL_ID); | |
| 72 | 91 | std::fs::create_dir_all(&dir).expect("blob dir"); |
| 73 | 92 | dir |
| 74 | 93 | } |
| @@ -96,7 +115,7 @@ pub async fn mem_deployment() -> (Tenants, Database) { | ||
| 96 | 115 | /// The demo school's handle out of a registry. |
| 97 | 116 | pub async fn demo_db(tenants: &Tenants) -> Database { |
| 98 | 117 | tenants |
| 99 | - .get(&Slug::try_new(DEMO_SLUG).expect("the demo slug")) | |
| 118 | + .get(&SchoolId::try_parse(DEMO_SCHOOL_ID).expect("the demo school")) | |
| 100 | 119 | .await |
| 101 | 120 | .expect("the demo school resolves") |
| 102 | 121 | } |
| @@ -199,7 +218,7 @@ pub async fn set_role(db: &Database, username: &str, role: &str) { | ||
| 199 | 218 | /// Register (password `secret1`), promote to `role`, then log in. Returns the |
| 200 | 219 | /// session `Cookie` value. |
| 201 | 220 | 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 | |
| 203 | 222 | } |
| 204 | 223 | |
| 205 | 224 | /// [`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( | ||
| 217 | 236 | "POST", |
| 218 | 237 | "/auth/register", |
| 219 | 238 | None, |
| 220 | - Some(json!({ "school": school, "username": username, "password": "secret1" })), | |
| 239 | + Some(json!({ "school": school_wire(school), "username": username, "password": "secret1" })), | |
| 221 | 240 | ) |
| 222 | 241 | .await; |
| 223 | 242 | assert_eq!(reg.status, StatusCode::CREATED, "register {username}"); |
| @@ -240,7 +259,7 @@ pub async fn login_as_school( | ||
| 240 | 259 | "POST", |
| 241 | 260 | "/auth/school", |
| 242 | 261 | res.cookie.as_deref(), |
| 243 | - Some(json!({ "school": school })), | |
| 262 | + Some(json!({ "school": school_wire(school) })), | |
| 244 | 263 | ) |
| 245 | 264 | .await; |
| 246 | 265 | assert_eq!( |
| @@ -425,7 +444,7 @@ pub async fn login(app: &Router, username: &str) -> String { | ||
| 425 | 444 | "POST", |
| 426 | 445 | "/auth/register", |
| 427 | 446 | None, |
| 428 | - Some(json!({ "school": DEMO_SLUG, "username": username, "password": "secret1" })), | |
| 447 | + Some(json!({ "school": DEMO_SCHOOL_ID, "username": username, "password": "secret1" })), | |
| 429 | 448 | ) |
| 430 | 449 | .await; |
| 431 | 450 | assert_eq!(reg.status, StatusCode::CREATED, "register {username}"); |
| @@ -855,16 +874,12 @@ pub struct TestDeployment { | ||
| 855 | 874 | pub async fn deployment_with(schools: &[(&str, &str)]) -> TestDeployment { |
| 856 | 875 | let files = tempfile::tempdir().expect("files tempdir"); |
| 857 | 876 | 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); | |
| 859 | 879 | 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()) | |
| 866 | 881 | .await |
| 867 | - .unwrap_or_else(|err| panic!("create school {slug}: {err}")); | |
| 882 | + .unwrap_or_else(|err| panic!("create school {label}: {err}")); | |
| 868 | 883 | } |
| 869 | 884 | let app = build_router(AppState { |
| 870 | 885 | db: tenants.control().clone(), |
tests/e2e.rsmodified+7 -7
| @@ -4,7 +4,7 @@ | ||
| 4 | 4 | use hezarfen_backend::database::Database; |
| 5 | 5 | use hezarfen_backend::rate_limit::RateLimitConfig; |
| 6 | 6 | use hezarfen_backend::state::AppState; |
| 7 | -use hezarfen_backend::tenant::{DEMO_SLUG, Slug}; | |
| 7 | +use hezarfen_backend::tenant::{DEMO_SCHOOL_ID, SchoolId}; | |
| 8 | 8 | use hezarfen_backend::{build_router, database}; |
| 9 | 9 | mod common; |
| 10 | 10 | |
| @@ -23,7 +23,7 @@ async fn spawn_server() -> (String, Database) { | ||
| 23 | 23 | async fn spawn_server_with_ai(ai: Option<hezarfen_backend::ai::AiBridge>) -> (String, Database) { |
| 24 | 24 | let tenants = database::init_test_tenants().await; |
| 25 | 25 | let db = tenants |
| 26 | - .get(&Slug::try_new(DEMO_SLUG).unwrap()) | |
| 26 | + .get(&SchoolId::try_parse(DEMO_SCHOOL_ID).unwrap()) | |
| 27 | 27 | .await |
| 28 | 28 | .expect("the demo school"); |
| 29 | 29 | // The deployment's operator, seeded exactly as `main` does from |
| @@ -86,7 +86,7 @@ fn client() -> Client { | ||
| 86 | 86 | async fn register(client: &Client, base: &str, user: &str) -> reqwest::Response { |
| 87 | 87 | client |
| 88 | 88 | .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" })) | |
| 90 | 90 | .send() |
| 91 | 91 | .await |
| 92 | 92 | .unwrap() |
| @@ -3925,7 +3925,6 @@ async fn a_builder_creates_a_school_over_tcp_and_its_admin_logs_in() { | ||
| 3925 | 3925 | let res = vendor |
| 3926 | 3926 | .post(format!("{base}/schools")) |
| 3927 | 3927 | .json(&json!({ |
| 3928 | - "slug": "tcp-koleji", | |
| 3929 | 3928 | "name": "TCP Koleji", |
| 3930 | 3929 | "admin_username": "admin", |
| 3931 | 3930 | "admin_password": "secret1", |
| @@ -3935,7 +3934,8 @@ async fn a_builder_creates_a_school_over_tcp_and_its_admin_logs_in() { | ||
| 3935 | 3934 | .unwrap(); |
| 3936 | 3935 | assert_eq!(res.status(), StatusCode::CREATED); |
| 3937 | 3936 | 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()); | |
| 3939 | 3939 | assert_eq!(school["status"], "active"); |
| 3940 | 3940 | |
| 3941 | 3941 | // 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() { | ||
| 4031 | 4031 | .unwrap(); |
| 4032 | 4032 | assert_eq!(res.status(), StatusCode::OK); |
| 4033 | 4033 | let res = vendor |
| 4034 | - .patch(format!("{base}/schools/demo")) | |
| 4034 | + .patch(format!("{base}/schools/{DEMO_SCHOOL_ID}")) | |
| 4035 | 4035 | .json(&json!({ "status": "suspended" })) |
| 4036 | 4036 | .send() |
| 4037 | 4037 | .await |
| @@ -4066,7 +4066,7 @@ async fn probe_a_suspended_school_refuses_websocket_upgrades() { | ||
| 4066 | 4066 | |
| 4067 | 4067 | // Resume: the same cookie, the same socket. |
| 4068 | 4068 | let res = vendor |
| 4069 | - .patch(format!("{base}/schools/demo")) | |
| 4069 | + .patch(format!("{base}/schools/{DEMO_SCHOOL_ID}")) | |
| 4070 | 4070 | .json(&json!({ "status": "active" })) |
| 4071 | 4071 | .send() |
| 4072 | 4072 | .await |
tests/etag.rsmodified+1 -1
| @@ -154,7 +154,7 @@ async fn handler_owned_etag_passes_through_and_never_304s() { | ||
| 154 | 154 | #[tokio::test] |
| 155 | 155 | async fn mutations_are_never_etagged() { |
| 156 | 156 | 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" }); | |
| 158 | 158 | let res = app |
| 159 | 159 | .clone() |
| 160 | 160 | .oneshot( |
tests/insight_report.rsmodified+4 -6
| @@ -26,7 +26,7 @@ use hezarfen_backend::constant::{ | ||
| 26 | 26 | }; |
| 27 | 27 | use hezarfen_backend::database::Database; |
| 28 | 28 | use hezarfen_backend::domain::timestamp::Timestamp; |
| 29 | -use hezarfen_backend::tenant::DEMO_SLUG; | |
| 29 | +use hezarfen_backend::tenant::DEMO_SCHOOL_ID; | |
| 30 | 30 | use serde_json::{Value, json}; |
| 31 | 31 | use uuid::Uuid; |
| 32 | 32 | |
| @@ -453,11 +453,9 @@ async fn a_generated_report_is_stored_and_served_to_its_manager() { | ||
| 453 | 453 | request.payload["requested_by"], manager_id, |
| 454 | 454 | "the dispatch names the authenticated caller, not the school" |
| 455 | 455 | ); |
| 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"); | |
| 461 | 459 | assert!( |
| 462 | 460 | request.payload["school"]["name"] |
| 463 | 461 | .as_str() |
tests/integration.rsmodified+127 -107
| @@ -93,7 +93,7 @@ async fn time_serves_server_clock_without_auth() { | ||
| 93 | 93 | async fn get_school_returns_uuid_and_name_without_slug() { |
| 94 | 94 | let (app, db, tenants) = app_and_tenants().await; |
| 95 | 95 | 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'") | |
| 97 | 97 | .fetch_one(tenants.control()) |
| 98 | 98 | .await |
| 99 | 99 | .expect("demo school"); |
| @@ -229,7 +229,7 @@ async fn limits_publishes_the_bounds_the_api_actually_enforces() { | ||
| 229 | 229 | .as_u64() |
| 230 | 230 | .expect("max_username_len is an integer") as usize; |
| 231 | 231 | 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" }); | |
| 233 | 233 | let res = send(&app, "POST", "/auth/register", None, Some(too_long)).await; |
| 234 | 234 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 235 | 235 | } |
| @@ -273,25 +273,25 @@ async fn register_validates_input() { | ||
| 273 | 273 | let app = mem_app().await; |
| 274 | 274 | |
| 275 | 275 | // 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" }); | |
| 277 | 277 | let res = send(&app, "POST", "/auth/register", None, Some(short)).await; |
| 278 | 278 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 279 | 279 | |
| 280 | 280 | // 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" }); | |
| 282 | 282 | let res = send(&app, "POST", "/auth/register", None, Some(blank)).await; |
| 283 | 283 | assert_eq!(res.status, StatusCode::BAD_REQUEST); |
| 284 | 284 | |
| 285 | 285 | // Uppercase anywhere in the username -> 400. |
| 286 | 286 | 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" }); | |
| 288 | 288 | let res = send(&app, "POST", "/auth/register", None, Some(upper)).await; |
| 289 | 289 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad} accepted"); |
| 290 | 290 | } |
| 291 | 291 | |
| 292 | 292 | // Username must start and end with a letter or digit -> 400. |
| 293 | 293 | 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" }); | |
| 295 | 295 | let res = send(&app, "POST", "/auth/register", None, Some(edge)).await; |
| 296 | 296 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad} accepted"); |
| 297 | 297 | } |
| @@ -306,26 +306,26 @@ async fn register_validates_input() { | ||
| 306 | 306 | "a/b", |
| 307 | 307 | "a\"b", |
| 308 | 308 | ] { |
| 309 | - let ugly = json!({ "school": "demo", "username": bad, "password": "secret1" }); | |
| 309 | + let ugly = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": bad, "password": "secret1" }); | |
| 310 | 310 | let res = send(&app, "POST", "/auth/register", None, Some(ugly)).await; |
| 311 | 311 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad:?} accepted"); |
| 312 | 312 | } |
| 313 | 313 | |
| 314 | 314 | // Consecutive separators -> 400. |
| 315 | 315 | 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" }); | |
| 317 | 317 | let res = send(&app, "POST", "/auth/register", None, Some(doubled)).await; |
| 318 | 318 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{bad} accepted"); |
| 319 | 319 | } |
| 320 | 320 | |
| 321 | 321 | // 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" }); | |
| 323 | 323 | let res = send(&app, "POST", "/auth/register", None, Some(dotted)).await; |
| 324 | 324 | assert_eq!(res.status, StatusCode::CREATED); |
| 325 | 325 | assert_eq!(res.body["username"], "ali.k_1-b"); |
| 326 | 326 | |
| 327 | 327 | // 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" }); | |
| 329 | 329 | let res = send(&app, "POST", "/auth/register", None, Some(ok)).await; |
| 330 | 330 | assert_eq!(res.status, StatusCode::CREATED); |
| 331 | 331 | assert_eq!(res.body["username"], "bob"); |
| @@ -336,7 +336,7 @@ async fn register_validates_input() { | ||
| 336 | 336 | // deliberately indistinguishable — see tests/auth_enumeration.rs), but the |
| 337 | 337 | // write is still rejected: the original password keeps working and the |
| 338 | 338 | // 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" }); | |
| 340 | 340 | let res = send(&app, "POST", "/auth/register", None, Some(dup)).await; |
| 341 | 341 | assert_eq!(res.status, StatusCode::CREATED); |
| 342 | 342 | let res = send( |
| @@ -381,7 +381,7 @@ async fn register_rejects_reserved_usernames() { | ||
| 381 | 381 | "moderator", |
| 382 | 382 | "staff", |
| 383 | 383 | ] { |
| 384 | - let creds = json!({ "school": "demo", "username": name, "password": "secret1" }); | |
| 384 | + let creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": name, "password": "secret1" }); | |
| 385 | 385 | let res = send(&app, "POST", "/auth/register", None, Some(creds)).await; |
| 386 | 386 | assert_eq!(res.status, StatusCode::BAD_REQUEST, "{name} accepted"); |
| 387 | 387 | let msg = res.body["error"].as_str().unwrap_or_default(); |
| @@ -408,7 +408,7 @@ async fn login_rejects_bad_credentials() { | ||
| 408 | 408 | "POST", |
| 409 | 409 | "/auth/register", |
| 410 | 410 | None, |
| 411 | - Some(json!({ "school": "demo", "username": "kate", "password": "secret1" })), | |
| 411 | + Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "kate", "password": "secret1" })), | |
| 412 | 412 | ) |
| 413 | 413 | .await; |
| 414 | 414 | |
| @@ -452,6 +452,8 @@ const PUBLIC: &[(&str, &str)] = &[ | ||
| 452 | 452 | // Person-cookie gated, not a school session: OpenAPI declares no |
| 453 | 453 | // session_cookie security, so the public-route audit lists it here. |
| 454 | 454 | ("POST", "/auth/school"), |
| 455 | + // Register's school picker: active `{id, name}` rows, no session. | |
| 456 | + ("GET", "/auth/schools"), | |
| 455 | 457 | // Idempotent: revokes the session if there is one, `204` either way. |
| 456 | 458 | ("POST", "/auth/logout"), |
| 457 | 459 | // 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() { | ||
| 1355 | 1357 | ( |
| 1356 | 1358 | "/auth/register", |
| 1357 | 1359 | None, |
| 1358 | - r#"{"school": "demo", "username": 5, "password": "secret1"}"#, | |
| 1360 | + r#"{"school": "019732e3-7b00-7000-8000-00000000dead", "username": 5, "password": "secret1"}"#, | |
| 1359 | 1361 | "plain Json, type mismatch", |
| 1360 | 1362 | ), |
| 1361 | 1363 | ( |
| 1362 | 1364 | "/auth/register", |
| 1363 | 1365 | None, |
| 1364 | - r#"{"school": "demo", "username": "veli"}"#, | |
| 1366 | + r#"{"school": "019732e3-7b00-7000-8000-00000000dead", "username": "veli"}"#, | |
| 1365 | 1367 | "plain Json, missing required field", |
| 1366 | 1368 | ), |
| 1367 | 1369 | ( |
| @@ -1405,7 +1407,7 @@ async fn malformed_json_bodies_answer_422_across_every_extractor_shape() { | ||
| 1405 | 1407 | for (body, why) in [ |
| 1406 | 1408 | ("not json at all", "unparseable JSON"), |
| 1407 | 1409 | ( |
| 1408 | - r#"{"school": "demo", "username": "a", "password": "secret1"}"#, | |
| 1410 | + r#"{"school": "019732e3-7b00-7000-8000-00000000dead", "username": "a", "password": "secret1"}"#, | |
| 1409 | 1411 | "well-typed value refused by a domain rule", |
| 1410 | 1412 | ), |
| 1411 | 1413 | ] { |
| @@ -6450,7 +6452,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() { | ||
| 6450 | 6452 | "/auth/register", |
| 6451 | 6453 | None, |
| 6452 | 6454 | 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" }), | |
| 6454 | 6456 | ), |
| 6455 | 6457 | ) |
| 6456 | 6458 | .await; |
| @@ -6466,7 +6468,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() { | ||
| 6466 | 6468 | "POST", |
| 6467 | 6469 | "/auth/register", |
| 6468 | 6470 | None, |
| 6469 | - Some(json!({ "school": "demo", "username": spoof, "password": "spoof1" })), | |
| 6471 | + Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": spoof, "password": "spoof1" })), | |
| 6470 | 6472 | ) |
| 6471 | 6473 | .await; |
| 6472 | 6474 | assert_eq!(res.status, StatusCode::CREATED, "{spoof:?}"); |
| @@ -6517,7 +6519,7 @@ async fn padded_usernames_are_canonicalized_not_distinct_accounts() { | ||
| 6517 | 6519 | "POST", |
| 6518 | 6520 | "/auth/register", |
| 6519 | 6521 | None, |
| 6520 | - Some(json!({ "school": "demo", "username": " veli ", "password": "secret1" })), | |
| 6522 | + Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": " veli ", "password": "secret1" })), | |
| 6521 | 6523 | ) |
| 6522 | 6524 | .await; |
| 6523 | 6525 | assert_eq!(res.status, StatusCode::CREATED); |
| @@ -6825,7 +6827,7 @@ async fn concurrent_duplicate_registrations_conflict_not_500() { | ||
| 6825 | 6827 | "POST", |
| 6826 | 6828 | "/auth/register", |
| 6827 | 6829 | None, |
| 6828 | - Some(json!({ "school": "demo", "username": "dup", "password": "secret1" })), | |
| 6830 | + Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "dup", "password": "secret1" })), | |
| 6829 | 6831 | ) |
| 6830 | 6832 | .await |
| 6831 | 6833 | .status |
| @@ -6855,7 +6857,7 @@ async fn concurrent_duplicate_registrations_conflict_not_500() { | ||
| 6855 | 6857 | "POST", |
| 6856 | 6858 | "/auth/register", |
| 6857 | 6859 | None, |
| 6858 | - Some(json!({ "school": "demo", "username": "dup", "password": "hijack1" })), | |
| 6860 | + Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "dup", "password": "hijack1" })), | |
| 6859 | 6861 | ) |
| 6860 | 6862 | .await; |
| 6861 | 6863 | assert_eq!(res.status, StatusCode::CREATED); |
| @@ -6942,7 +6944,7 @@ async fn child_lists_of_missing_parents_are_404() { | ||
| 6942 | 6944 | #[tokio::test] |
| 6943 | 6945 | async fn session_cookie_secure_attribute_follows_config() { |
| 6944 | 6946 | 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" }); | |
| 6946 | 6948 | assert_eq!( |
| 6947 | 6949 | send(app, "POST", "/auth/register", None, Some(creds)) |
| 6948 | 6950 | .await |
| @@ -7051,7 +7053,7 @@ async fn db_down_refuses_before_touching_the_database() { | ||
| 7051 | 7053 | .uri("/auth/register") |
| 7052 | 7054 | .header("content-type", "application/json") |
| 7053 | 7055 | .body(Body::from( |
| 7054 | - json!({"school": "demo", "username": "gulsah", "password": "sifre12345"}) | |
| 7056 | + json!({"school": "019732e3-7b00-7000-8000-00000000dead", "username": "gulsah", "password": "sifre12345"}) | |
| 7055 | 7057 | .to_string(), |
| 7056 | 7058 | )) |
| 7057 | 7059 | .unwrap(), |
| @@ -7075,7 +7077,7 @@ async fn db_down_refuses_before_touching_the_database() { | ||
| 7075 | 7077 | .uri("/auth/register") |
| 7076 | 7078 | .header("content-type", "application/json") |
| 7077 | 7079 | .body(Body::from( |
| 7078 | - json!({"school": "demo", "username": "kerem", "password": "sifre12345"}) | |
| 7080 | + json!({"school": "019732e3-7b00-7000-8000-00000000dead", "username": "kerem", "password": "sifre12345"}) | |
| 7079 | 7081 | .to_string(), |
| 7080 | 7082 | )) |
| 7081 | 7083 | .unwrap(), |
| @@ -7091,11 +7093,11 @@ async fn db_down_refuses_before_touching_the_database() { | ||
| 7091 | 7093 | |
| 7092 | 7094 | // Recovery is eviction: the dead pool leaves the cache, the next request |
| 7093 | 7095 | // 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'") | |
| 7095 | 7097 | .fetch_one(tenants.control()) |
| 7096 | 7098 | .await |
| 7097 | 7099 | .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"); | |
| 7099 | 7101 | tenants |
| 7100 | 7102 | .evict(hezarfen_backend::tenant::SchoolId::from_uuid(demo_id)) |
| 7101 | 7103 | .await; |
| @@ -7112,7 +7114,7 @@ async fn db_down_refuses_before_touching_the_database() { | ||
| 7112 | 7114 | .uri("/auth/register") |
| 7113 | 7115 | .header("content-type", "application/json") |
| 7114 | 7116 | .body(Body::from( |
| 7115 | - json!({"school": "demo", "username": "kerem", "password": "sifre12345"}) | |
| 7117 | + json!({"school": "019732e3-7b00-7000-8000-00000000dead", "username": "kerem", "password": "sifre12345"}) | |
| 7116 | 7118 | .to_string(), |
| 7117 | 7119 | )) |
| 7118 | 7120 | .unwrap(), |
| @@ -7346,7 +7348,7 @@ async fn admin_seed_creates_working_admin() { | ||
| 7346 | 7348 | let password = Password::try_new("secret1").unwrap(); |
| 7347 | 7349 | hezarfen_backend::service::user::ensure_admin( |
| 7348 | 7350 | &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(), | |
| 7350 | 7352 | username, |
| 7351 | 7353 | password, |
| 7352 | 7354 | ) |
| @@ -7373,7 +7375,7 @@ async fn admin_seed_is_idempotent() { | ||
| 7373 | 7375 | let password = Password::try_new("secret1").unwrap(); |
| 7374 | 7376 | hezarfen_backend::service::user::ensure_admin( |
| 7375 | 7377 | &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(), | |
| 7377 | 7379 | username, |
| 7378 | 7380 | password, |
| 7379 | 7381 | ) |
| @@ -7404,7 +7406,7 @@ async fn admin_seed_refuses_existing_non_admin() { | ||
| 7404 | 7406 | let password = Password::try_new("attacker-pw").unwrap(); |
| 7405 | 7407 | hezarfen_backend::service::user::ensure_admin( |
| 7406 | 7408 | &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(), | |
| 7408 | 7410 | username, |
| 7409 | 7411 | password, |
| 7410 | 7412 | ) |
| @@ -28375,7 +28377,7 @@ async fn course_note_rag_reindex_reports_503_and_writes_nothing_without_a_servic | ||
| 28375 | 28377 | // Multi-school isolation probes (REFUTE lane B). Two schools, same usernames. |
| 28376 | 28378 | // ========================================================================= |
| 28377 | 28379 | |
| 28378 | -use hezarfen_backend::tenant::{DEMO_SLUG, SchoolStatus, Slug, Tenants}; | |
| 28380 | +use hezarfen_backend::tenant::{DEMO_SCHOOL_ID, SchoolStatus, SchoolId, Tenants}; | |
| 28379 | 28381 | |
| 28380 | 28382 | /// Demo (school A) plus a second school "beta" (school B), and the registry. |
| 28381 | 28383 | async fn two_schools() -> ( |
| @@ -28385,11 +28387,10 @@ async fn two_schools() -> ( | ||
| 28385 | 28387 | Tenants, |
| 28386 | 28388 | ) { |
| 28387 | 28389 | 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"); | |
| 28389 | 28391 | let db_b = tenants |
| 28390 | 28392 | .create( |
| 28391 | - hezarfen_backend::tenant::SchoolId::generate(), | |
| 28392 | - &slug_b, | |
| 28393 | + slug_b, | |
| 28393 | 28394 | "Beta Koleji", |
| 28394 | 28395 | ModuleSet::all(), |
| 28395 | 28396 | ) |
| @@ -28406,7 +28407,7 @@ const TWO_SCHOOLS: &[(&str, &str)] = &[("beta", "Beta Koleji")]; | ||
| 28406 | 28407 | /// One school's handle out of the registry. |
| 28407 | 28408 | async fn school_db(tenants: &Tenants, slug: &str) -> hezarfen_backend::database::Database { |
| 28408 | 28409 | tenants |
| 28409 | - .get(&Slug::try_new(slug).expect("a school slug")) | |
| 28410 | + .get(&common::school_id(slug)) | |
| 28410 | 28411 | .await |
| 28411 | 28412 | .unwrap_or_else(|err| panic!("the {slug} handle: {err}")) |
| 28412 | 28413 | } |
| @@ -28548,9 +28549,9 @@ async fn remote_probe_cross_school_lists_show_only_own_rows() { | ||
| 28548 | 28549 | } |
| 28549 | 28550 | |
| 28550 | 28551 | 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; | |
| 28552 | 28553 | 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; | |
| 28554 | 28555 | let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await; |
| 28555 | 28556 | |
| 28556 | 28557 | let mut before = Vec::new(); |
| @@ -28609,9 +28610,9 @@ async fn probe_cross_school_ids_are_not_found_under_the_other_cookie_on( | ||
| 28609 | 28610 | app: &axum::Router, |
| 28610 | 28611 | tenants: &Tenants, |
| 28611 | 28612 | ) { |
| 28612 | - let db_a = school_db(tenants, DEMO_SLUG).await; | |
| 28613 | + let db_a = school_db(tenants, DEMO_SCHOOL_ID).await; | |
| 28613 | 28614 | 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; | |
| 28615 | 28616 | let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await; |
| 28616 | 28617 | let ids = seed_school_b(app, &b).await; |
| 28617 | 28618 | 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() { | ||
| 28715 | 28716 | } |
| 28716 | 28717 | |
| 28717 | 28718 | 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; | |
| 28719 | 28720 | 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; | |
| 28723 | 28724 | let b_admin = common::login_as_school(app, &db_b, "beta", "boran", "admin").await; |
| 28724 | 28725 | common::login_as_school(app, &db_b, "beta", "bstudent", "student").await; |
| 28725 | 28726 | |
| @@ -28821,7 +28822,7 @@ async fn probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it | ||
| 28821 | 28822 | tenants: &Tenants, |
| 28822 | 28823 | ) { |
| 28823 | 28824 | 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(); | |
| 28825 | 28826 | let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await; |
| 28826 | 28827 | |
| 28827 | 28828 | // Alive first. |
| @@ -28877,7 +28878,7 @@ async fn probe_suspension_blocks_login_and_a_live_cookie_then_resume_restores_it | ||
| 28877 | 28878 | "POST", |
| 28878 | 28879 | "/auth/register", |
| 28879 | 28880 | None, |
| 28880 | - Some(json!({ "school": "beta", "username": "newcomer", "password": "secret1" })), | |
| 28881 | + Some(json!({ "school": common::school_wire("beta"), "username": "newcomer", "password": "secret1" })), | |
| 28881 | 28882 | ) |
| 28882 | 28883 | .await; |
| 28883 | 28884 | assert_eq!( |
| @@ -28920,9 +28921,9 @@ async fn remote_probe_cookie_confusion_is_impossible_both_ways() { | ||
| 28920 | 28921 | } |
| 28921 | 28922 | |
| 28922 | 28923 | 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; | |
| 28924 | 28925 | 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; | |
| 28926 | 28927 | let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await; |
| 28927 | 28928 | let token_a = common::cookie_token(&a).to_string(); |
| 28928 | 28929 | |
| @@ -28990,8 +28991,8 @@ async fn probe_cookie_confusion_is_impossible_both_ways_on(app: &axum::Router, t | ||
| 28990 | 28991 | } |
| 28991 | 28992 | // (4) a builder token wearing a school prefix. |
| 28992 | 28993 | 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), | |
| 28995 | 28996 | ] { |
| 28996 | 28997 | let res = send(app, "GET", "/auth/me", Some(&raw), None).await; |
| 28997 | 28998 | assert_eq!( |
| @@ -29005,8 +29006,8 @@ async fn probe_cookie_confusion_is_impossible_both_ways_on(app: &axum::Router, t | ||
| 29005 | 29006 | // (5) THE one: A's live token under B's prefix, and B's under A's. |
| 29006 | 29007 | let token_b = common::cookie_token(&b).to_string(); |
| 29007 | 29008 | 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"), | |
| 29010 | 29011 | ] { |
| 29011 | 29012 | for route in ["/auth/me", "/users", "/notes", "/settings"] { |
| 29012 | 29013 | 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() { | ||
| 29048 | 29049 | } |
| 29049 | 29050 | |
| 29050 | 29051 | 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; | |
| 29052 | 29053 | let db_b = school_db(tenants, "beta").await; |
| 29053 | 29054 | |
| 29054 | 29055 | // 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 | ||
| 29068 | 29069 | ); |
| 29069 | 29070 | |
| 29070 | 29071 | // 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)] { | |
| 29072 | 29073 | let res = send( |
| 29073 | 29074 | app, |
| 29074 | 29075 | "POST", |
| 29075 | 29076 | "/auth/register", |
| 29076 | 29077 | None, |
| 29077 | - Some(json!({ "school": slug, "username": "ayse", "password": "secret1" })), | |
| 29078 | + Some(json!({ "school": common::school_wire(slug), "username": "ayse", "password": "secret1" })), | |
| 29078 | 29079 | ) |
| 29079 | 29080 | .await; |
| 29080 | 29081 | assert_eq!( |
| @@ -29162,9 +29163,9 @@ async fn probe_uploaded_files_are_school_scoped_on( | ||
| 29162 | 29163 | tenants: &Tenants, |
| 29163 | 29164 | files: &std::path::Path, |
| 29164 | 29165 | ) { |
| 29165 | - let db_a = school_db(tenants, DEMO_SLUG).await; | |
| 29166 | + let db_a = school_db(tenants, DEMO_SCHOOL_ID).await; | |
| 29166 | 29167 | 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; | |
| 29168 | 29169 | let b = common::login_as_school(app, &db_b, "beta", "ali", "student").await; |
| 29169 | 29170 | |
| 29170 | 29171 | let note = send( |
| @@ -29183,8 +29184,8 @@ async fn probe_uploaded_files_are_school_scoped_on( | ||
| 29183 | 29184 | let file_id = id_of(&up.body); |
| 29184 | 29185 | |
| 29185 | 29186 | // 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")); | |
| 29188 | 29189 | let count = |dir: &std::path::Path| { |
| 29189 | 29190 | std::fs::read_dir(dir) |
| 29190 | 29191 | .map(|it| it.count()) |
| @@ -29240,9 +29241,9 @@ async fn probe_school_rows_never_reach_the_control_database_on( | ||
| 29240 | 29241 | app: &axum::Router, |
| 29241 | 29242 | tenants: &Tenants, |
| 29242 | 29243 | ) { |
| 29243 | - let db_a = school_db(tenants, DEMO_SLUG).await; | |
| 29244 | + let db_a = school_db(tenants, DEMO_SCHOOL_ID).await; | |
| 29244 | 29245 | 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; | |
| 29246 | 29247 | let b = common::login_as_school(app, &db_b, "beta", "boran", "admin").await; |
| 29247 | 29248 | common::login_as_school(app, &db_b, "beta", "bstudent", "student").await; |
| 29248 | 29249 | let ids = seed_school_b(app, &b).await; |
| @@ -29278,11 +29279,11 @@ async fn probe_school_rows_never_reach_the_control_database_on( | ||
| 29278 | 29279 | ); |
| 29279 | 29280 | } |
| 29280 | 29281 | // 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") | |
| 29282 | 29283 | .fetch_all(control) |
| 29283 | 29284 | .await |
| 29284 | 29285 | .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()]); | |
| 29286 | 29287 | |
| 29287 | 29288 | // User search never crosses the wall. Compare the returned names, not the |
| 29288 | 29289 | // 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( | ||
| 29357 | 29358 | async fn remote_probe_remote_mode_keeps_two_schools_apart() { |
| 29358 | 29359 | let d = common::deployment_with(&[("ata-koleji", "Ata"), ("2024school", "2024")]).await; |
| 29359 | 29360 | 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(); | |
| 29362 | 29363 | |
| 29363 | 29364 | // Same username in both schools is one person with two memberships. |
| 29364 | 29365 | // Login into the second school therefore returns a person cookie; bind |
| @@ -29496,9 +29497,10 @@ async fn namespace_databases(tenants: &Tenants) -> Vec<String> { | ||
| 29496 | 29497 | /// database's `heztest_` prefix runs the name one character past that — the |
| 29497 | 29498 | /// server creates and dials the truncated name on both sides, so the |
| 29498 | 29499 | /// 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) | |
| 29502 | 29504 | .fetch_one(control) |
| 29503 | 29505 | .await |
| 29504 | 29506 | .expect("school id"); |
| @@ -29516,8 +29518,8 @@ async fn remote_probe_a_school_is_a_database_and_delete_removes_it() { | ||
| 29516 | 29518 | .fetch_one(d.tenants.control()) |
| 29517 | 29519 | .await |
| 29518 | 29520 | .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; | |
| 29521 | 29523 | let mut expected = vec![control_db.clone(), demo_db.clone(), beta_db]; |
| 29522 | 29524 | expected.sort(); |
| 29523 | 29525 | assert_eq!( |
| @@ -29544,7 +29546,7 @@ async fn remote_probe_a_school_is_a_database_and_delete_removes_it() { | ||
| 29544 | 29546 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 29545 | 29547 | let builder = res.cookie.expect("builder cookie"); |
| 29546 | 29548 | |
| 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; | |
| 29548 | 29550 | assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); |
| 29549 | 29551 | let mut expected = vec![control_db.clone(), demo_db]; |
| 29550 | 29552 | expected.sort(); |
| @@ -29562,7 +29564,7 @@ async fn remote_probe_raw_sql_on_a_school_handle_counts_only_its_own_rows() { | ||
| 29562 | 29564 | let d = common::deployment_with(TWO_SCHOOLS).await; |
| 29563 | 29565 | // Different counts, so a leak cannot hide behind equal numbers. |
| 29564 | 29566 | for (slug, users) in [ |
| 29565 | - (DEMO_SLUG, ["ada", "ali", "ayse"].as_slice()), | |
| 29567 | + (DEMO_SCHOOL_ID, ["ada", "ali", "ayse"].as_slice()), | |
| 29566 | 29568 | ("beta", &["boran"]), |
| 29567 | 29569 | ] { |
| 29568 | 29570 | for username in users { |
| @@ -29571,7 +29573,7 @@ async fn remote_probe_raw_sql_on_a_school_handle_counts_only_its_own_rows() { | ||
| 29571 | 29573 | "POST", |
| 29572 | 29574 | "/auth/register", |
| 29573 | 29575 | None, |
| 29574 | - Some(json!({ "school": slug, "username": username, "password": "secret1" })), | |
| 29576 | + Some(json!({ "school": common::school_wire(slug), "username": username, "password": "secret1" })), | |
| 29575 | 29577 | ) |
| 29576 | 29578 | .await; |
| 29577 | 29579 | assert_eq!( |
| @@ -29589,7 +29591,7 @@ async fn remote_probe_raw_sql_on_a_school_handle_counts_only_its_own_rows() { | ||
| 29589 | 29591 | .await |
| 29590 | 29592 | .expect("count query") |
| 29591 | 29593 | }; |
| 29592 | - let db_a = school_db(&d.tenants, DEMO_SLUG).await; | |
| 29594 | + let db_a = school_db(&d.tenants, DEMO_SCHOOL_ID).await; | |
| 29593 | 29595 | let db_b = school_db(&d.tenants, "beta").await; |
| 29594 | 29596 | assert_eq!(count(&db_a).await, 3, "demo's own users"); |
| 29595 | 29597 | 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() | ||
| 29606 | 29608 | "POST", |
| 29607 | 29609 | "/auth/register", |
| 29608 | 29610 | None, |
| 29609 | - Some(json!({ "school": DEMO_SLUG, "username": "ada", "password": "secret1" })), | |
| 29611 | + Some(json!({ "school": DEMO_SCHOOL_ID, "username": "ada", "password": "secret1" })), | |
| 29610 | 29612 | ) |
| 29611 | 29613 | .await; |
| 29612 | 29614 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 29613 | 29615 | |
| 29614 | - let db_a = school_db(&d.tenants, DEMO_SLUG).await; | |
| 29616 | + let db_a = school_db(&d.tenants, DEMO_SCHOOL_ID).await; | |
| 29615 | 29617 | let db_b = school_db(&d.tenants, "beta").await; |
| 29616 | 29618 | let id: Uuid = sqlx::query_scalar("SELECT id FROM app_user LIMIT 1") |
| 29617 | 29619 | .fetch_one(&db_a) |
| @@ -29640,9 +29642,9 @@ async fn remote_probe_a_record_id_minted_in_one_school_is_absent_in_the_other() | ||
| 29640 | 29642 | #[tokio::test] |
| 29641 | 29643 | async fn remote_probe_a_suspended_school_reconnects_with_its_rows_intact() { |
| 29642 | 29644 | 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; | |
| 29646 | 29648 | let note = send( |
| 29647 | 29649 | &d.app, |
| 29648 | 29650 | "POST", |
| @@ -29666,7 +29668,7 @@ async fn remote_probe_a_suspended_school_reconnects_with_its_rows_intact() { | ||
| 29666 | 29668 | .expect("resume"); |
| 29667 | 29669 | |
| 29668 | 29670 | // 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; | |
| 29670 | 29672 | let titles: Vec<String> = sqlx::query_scalar("SELECT title FROM note") |
| 29671 | 29673 | .fetch_all(&reconnected) |
| 29672 | 29674 | .await |
| @@ -29702,7 +29704,7 @@ use hezarfen_backend::module::Module; | ||
| 29702 | 29704 | #[tokio::test] |
| 29703 | 29705 | async fn a_disabled_module_refuses_its_nest_and_leaves_the_rest_alone() { |
| 29704 | 29706 | 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(); | |
| 29706 | 29708 | let cookie = login_as(&app, &db, "ada", "admin").await; |
| 29707 | 29709 | |
| 29708 | 29710 | let res = send(&app, "GET", "/meals/menus", Some(&cookie), None).await; |
| @@ -29770,7 +29772,7 @@ fn all_without(module: Module) -> ModuleSet { | ||
| 29770 | 29772 | #[tokio::test] |
| 29771 | 29773 | async fn a_course_child_route_is_gated_by_its_own_module() { |
| 29772 | 29774 | 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(); | |
| 29774 | 29776 | let cookie = login_as(&app, &db, "ada", "admin").await; |
| 29775 | 29777 | let course = create_course(&app, &cookie, "Fizik").await; |
| 29776 | 29778 | |
| @@ -29815,7 +29817,7 @@ async fn a_course_child_route_is_gated_by_its_own_module() { | ||
| 29815 | 29817 | #[tokio::test] |
| 29816 | 29818 | async fn a_disabled_module_refuses_its_websocket_upgrade() { |
| 29817 | 29819 | 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(); | |
| 29819 | 29821 | let cookie = login_as(&app, &db, "ada", "admin").await; |
| 29820 | 29822 | |
| 29821 | 29823 | let mut without = all_without(Module::Exams); |
| @@ -29907,7 +29909,7 @@ const MODULE_ROUTES: [(Module, &str, &str); 21] = [ | ||
| 29907 | 29909 | #[tokio::test] |
| 29908 | 29910 | async fn every_module_gates_its_own_nest_when_the_builder_takes_it_back() { |
| 29909 | 29911 | 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(); | |
| 29911 | 29913 | let cookie = login_as(&app, &db, "ada", "admin").await; |
| 29912 | 29914 | let builder = sweep_builder_login(&app).await; |
| 29913 | 29915 | |
| @@ -29920,7 +29922,7 @@ async fn every_module_gates_its_own_nest_when_the_builder_takes_it_back() { | ||
| 29920 | 29922 | res.body |
| 29921 | 29923 | ); |
| 29922 | 29924 | |
| 29923 | - let one = format!("/schools/{DEMO_SLUG}/modules/{module}"); | |
| 29925 | + let one = format!("/schools/{DEMO_SCHOOL_ID}/modules/{module}"); | |
| 29924 | 29926 | if module.dependents().is_empty() { |
| 29925 | 29927 | let res = send(&app, "DELETE", &one, Some(&builder), None).await; |
| 29926 | 29928 | assert_eq!( |
| @@ -29993,7 +29995,7 @@ async fn every_module_gates_its_own_nest_when_the_builder_takes_it_back() { | ||
| 29993 | 29995 | #[tokio::test] |
| 29994 | 29996 | async fn every_course_child_route_names_its_own_module() { |
| 29995 | 29997 | 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(); | |
| 29997 | 29999 | let cookie = login_as(&app, &db, "ada", "admin").await; |
| 29998 | 30000 | let course = create_course(&app, &cookie, "Fizik").await; |
| 29999 | 30001 | let class = create_class(&app, &cookie, "9-F", json!({})).await; |
| @@ -30045,7 +30047,7 @@ async fn every_course_child_route_names_its_own_module() { | ||
| 30045 | 30047 | /// and can be told what it has — none of that lives behind a module. |
| 30046 | 30048 | #[tokio::test] |
| 30047 | 30049 | 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; | |
| 30049 | 30051 | let builder = sweep_builder_login(&app).await; |
| 30050 | 30052 | |
| 30051 | 30053 | let res = send( |
| @@ -30054,8 +30056,7 @@ async fn a_school_with_no_modules_can_still_use_the_core_routes() { | ||
| 30054 | 30056 | "/schools", |
| 30055 | 30057 | Some(&builder), |
| 30056 | 30058 | Some(json!({ |
| 30057 | - "slug": "bare", | |
| 30058 | - "name": "Bare School", | |
| 30059 | + "name": "bare school", | |
| 30059 | 30060 | "admin_username": "admin", |
| 30060 | 30061 | "admin_password": "secret1", |
| 30061 | 30062 | "modules": [], |
| @@ -30065,12 +30066,16 @@ async fn a_school_with_no_modules_can_still_use_the_core_routes() { | ||
| 30065 | 30066 | assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); |
| 30066 | 30067 | assert_eq!(res.body["modules"], json!([])); |
| 30067 | 30068 | |
| 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"); | |
| 30068 | 30073 | let res = send( |
| 30069 | 30074 | &app, |
| 30070 | 30075 | "POST", |
| 30071 | 30076 | "/auth/login", |
| 30072 | 30077 | None, |
| 30073 | - Some(json!({ "school": "bare", "username": "admin", "password": "secret1" })), | |
| 30078 | + Some(json!({ "username": "admin", "password": "secret1" })), | |
| 30074 | 30079 | ) |
| 30075 | 30080 | .await; |
| 30076 | 30081 | assert_eq!( |
| @@ -30079,7 +30084,20 @@ async fn a_school_with_no_modules_can_still_use_the_core_routes() { | ||
| 30079 | 30084 | "a bare school still logs in: {}", |
| 30080 | 30085 | res.body |
| 30081 | 30086 | ); |
| 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 | + }; | |
| 30083 | 30101 | |
| 30084 | 30102 | for route in [ |
| 30085 | 30103 | "/auth/me", |
| @@ -30268,7 +30286,7 @@ async fn login_without_school_enters_a_single_school_person() { | ||
| 30268 | 30286 | "POST", |
| 30269 | 30287 | "/auth/register", |
| 30270 | 30288 | None, |
| 30271 | - Some(json!({ "school": DEMO_SLUG, "username": "personada", "password": "secret1" })), | |
| 30289 | + Some(json!({ "school": DEMO_SCHOOL_ID, "username": "personada", "password": "secret1" })), | |
| 30272 | 30290 | ) |
| 30273 | 30291 | .await; |
| 30274 | 30292 | assert_eq!(reg.status, StatusCode::CREATED, "{}", reg.body); |
| @@ -30285,7 +30303,7 @@ async fn login_without_school_enters_a_single_school_person() { | ||
| 30285 | 30303 | assert!(res.body["id"].is_string(), "the person's id: {}", res.body); |
| 30286 | 30304 | assert_eq!(res.body["username"], "personada"); |
| 30287 | 30305 | 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}"); | |
| 30289 | 30307 | |
| 30290 | 30308 | let res = send(&app, "GET", "/auth/me", Some(&cookie), None).await; |
| 30291 | 30309 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| @@ -30298,13 +30316,13 @@ async fn login_without_school_enters_a_single_school_person() { | ||
| 30298 | 30316 | async fn a_multischool_person_selects_a_school() { |
| 30299 | 30317 | let d = common::deployment_with(TWO_SCHOOLS).await; |
| 30300 | 30318 | let app = &d.app; |
| 30301 | - for school in [DEMO_SLUG, "beta"] { | |
| 30319 | + for school in [DEMO_SCHOOL_ID, "beta"] { | |
| 30302 | 30320 | let reg = send( |
| 30303 | 30321 | app, |
| 30304 | 30322 | "POST", |
| 30305 | 30323 | "/auth/register", |
| 30306 | 30324 | None, |
| 30307 | - Some(json!({ "school": school, "username": "personada", "password": "secret1" })), | |
| 30325 | + Some(json!({ "school": common::school_wire(school), "username": "personada", "password": "secret1" })), | |
| 30308 | 30326 | ) |
| 30309 | 30327 | .await; |
| 30310 | 30328 | assert_eq!( |
| @@ -30325,14 +30343,16 @@ async fn a_multischool_person_selects_a_school() { | ||
| 30325 | 30343 | .await; |
| 30326 | 30344 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 30327 | 30345 | assert_eq!(res.body["username"], "personada"); |
| 30328 | - let mut slugs: Vec<&str> = res.body["schools"] | |
| 30346 | + let mut ids: Vec<&str> = res.body["schools"] | |
| 30329 | 30347 | .as_array() |
| 30330 | 30348 | .expect("schools list") |
| 30331 | 30349 | .iter() |
| 30332 | - .map(|s| s["slug"].as_str().expect("school slug")) | |
| 30350 | + .map(|s| s["id"].as_str().expect("school id")) | |
| 30333 | 30351 | .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); | |
| 30336 | 30356 | assert!( |
| 30337 | 30357 | res.body.get("id").is_none(), |
| 30338 | 30358 | "no school chosen yet: {}", |
| @@ -30350,13 +30370,13 @@ async fn a_multischool_person_selects_a_school() { | ||
| 30350 | 30370 | "POST", |
| 30351 | 30371 | "/auth/school", |
| 30352 | 30372 | Some(&person), |
| 30353 | - Some(json!({ "school": DEMO_SLUG })), | |
| 30373 | + Some(json!({ "school": DEMO_SCHOOL_ID })), | |
| 30354 | 30374 | ) |
| 30355 | 30375 | .await; |
| 30356 | 30376 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 30357 | 30377 | assert!(res.body["id"].is_string(), "the person's id: {}", res.body); |
| 30358 | 30378 | 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}"); | |
| 30360 | 30380 | let res = send(app, "GET", "/auth/me", Some(&cookie), None).await; |
| 30361 | 30381 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| 30362 | 30382 | } |
| @@ -30368,13 +30388,13 @@ async fn a_multischool_person_selects_a_school() { | ||
| 30368 | 30388 | async fn school_selection_refuses_non_members_and_wrong_cookies() { |
| 30369 | 30389 | let d = common::deployment_with(TWO_SCHOOLS).await; |
| 30370 | 30390 | let app = &d.app; |
| 30371 | - for school in [DEMO_SLUG, "beta"] { | |
| 30391 | + for school in [DEMO_SCHOOL_ID, "beta"] { | |
| 30372 | 30392 | let reg = send( |
| 30373 | 30393 | app, |
| 30374 | 30394 | "POST", |
| 30375 | 30395 | "/auth/register", |
| 30376 | 30396 | None, |
| 30377 | - Some(json!({ "school": school, "username": "personada", "password": "secret1" })), | |
| 30397 | + Some(json!({ "school": common::school_wire(school), "username": "personada", "password": "secret1" })), | |
| 30378 | 30398 | ) |
| 30379 | 30399 | .await; |
| 30380 | 30400 | assert_eq!( |
| @@ -30412,7 +30432,7 @@ async fn school_selection_refuses_non_members_and_wrong_cookies() { | ||
| 30412 | 30432 | "POST", |
| 30413 | 30433 | "/auth/school", |
| 30414 | 30434 | None, |
| 30415 | - Some(json!({ "school": DEMO_SLUG })), | |
| 30435 | + Some(json!({ "school": DEMO_SCHOOL_ID })), | |
| 30416 | 30436 | ) |
| 30417 | 30437 | .await; |
| 30418 | 30438 | assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{}", res.body); |
| @@ -30423,7 +30443,7 @@ async fn school_selection_refuses_non_members_and_wrong_cookies() { | ||
| 30423 | 30443 | "POST", |
| 30424 | 30444 | "/auth/school", |
| 30425 | 30445 | Some(&person), |
| 30426 | - Some(json!({ "school": DEMO_SLUG })), | |
| 30446 | + Some(json!({ "school": DEMO_SCHOOL_ID })), | |
| 30427 | 30447 | ) |
| 30428 | 30448 | .await; |
| 30429 | 30449 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
| @@ -30435,7 +30455,7 @@ async fn school_selection_refuses_non_members_and_wrong_cookies() { | ||
| 30435 | 30455 | "POST", |
| 30436 | 30456 | "/auth/school", |
| 30437 | 30457 | Some(&school_cookie), |
| 30438 | - Some(json!({ "school": DEMO_SLUG })), | |
| 30458 | + Some(json!({ "school": DEMO_SCHOOL_ID })), | |
| 30439 | 30459 | ) |
| 30440 | 30460 | .await; |
| 30441 | 30461 | assert_eq!(res.status, StatusCode::UNAUTHORIZED, "{}", res.body); |
| @@ -30451,7 +30471,7 @@ async fn login_ignores_a_leftover_school_field() { | ||
| 30451 | 30471 | "POST", |
| 30452 | 30472 | "/auth/register", |
| 30453 | 30473 | None, |
| 30454 | - Some(json!({ "school": DEMO_SLUG, "username": "personada", "password": "secret1" })), | |
| 30474 | + Some(json!({ "school": DEMO_SCHOOL_ID, "username": "personada", "password": "secret1" })), | |
| 30455 | 30475 | ) |
| 30456 | 30476 | .await; |
| 30457 | 30477 | assert_eq!(reg.status, StatusCode::CREATED, "{}", reg.body); |
| @@ -30461,7 +30481,7 @@ async fn login_ignores_a_leftover_school_field() { | ||
| 30461 | 30481 | "POST", |
| 30462 | 30482 | "/auth/login", |
| 30463 | 30483 | None, |
| 30464 | - Some(json!({ "school": "demo", "username": "personada", "password": "secret1" })), | |
| 30484 | + Some(json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "personada", "password": "secret1" })), | |
| 30465 | 30485 | ) |
| 30466 | 30486 | .await; |
| 30467 | 30487 | assert_eq!(res.status, StatusCode::OK, "{}", res.body); |
tests/pagination.rsmodified+2 -2
| @@ -16,7 +16,7 @@ use serde_json::json; | ||
| 16 | 16 | async fn seed_students(app: &axum::Router, n: usize) { |
| 17 | 17 | for i in 0..n { |
| 18 | 18 | 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" }); | |
| 20 | 20 | let res = send(app, "POST", "/auth/register", None, Some(creds)).await; |
| 21 | 21 | assert_eq!(res.status, StatusCode::CREATED, "register {name}"); |
| 22 | 22 | } |
| @@ -330,7 +330,7 @@ async fn user_search_is_paged_not_capped() { | ||
| 330 | 330 | // 12 accounts sharing the "grp" fragment — past the old cap. |
| 331 | 331 | for i in 0..12 { |
| 332 | 332 | 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" }); | |
| 334 | 334 | let res = send(&app, "POST", "/auth/register", None, Some(creds)).await; |
| 335 | 335 | assert_eq!(res.status, StatusCode::CREATED); |
| 336 | 336 | } |
tests/persistence.rsmodified+25 -34
| @@ -14,7 +14,7 @@ use hezarfen_backend::database::Database; | ||
| 14 | 14 | use hezarfen_backend::module::ModuleSet; |
| 15 | 15 | use hezarfen_backend::rate_limit::RateLimitConfig; |
| 16 | 16 | use hezarfen_backend::state::AppState; |
| 17 | -use hezarfen_backend::tenant::{Slug, Tenants}; | |
| 17 | +use hezarfen_backend::tenant::Tenants; | |
| 18 | 18 | use hezarfen_backend::{build_router, database}; |
| 19 | 19 | use serde_json::json; |
| 20 | 20 | |
| @@ -46,7 +46,7 @@ async fn reboot(db: &Database, tenants: &Tenants) -> Router { | ||
| 46 | 46 | async fn settings_and_terms_survive_remigration() { |
| 47 | 47 | let (app, db, tenants) = common::app_and_tenants().await; |
| 48 | 48 | |
| 49 | - let creds = json!({ "school": "demo", "username": "boss", "password": "secret1" }); | |
| 49 | + let creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "boss", "password": "secret1" }); | |
| 50 | 50 | send(&app, "POST", "/auth/register", None, Some(creds)).await; |
| 51 | 51 | set_role(&db, "boss", "manager").await; |
| 52 | 52 | let login = json!({ "username": "boss", "password": "secret1" }); |
| @@ -128,8 +128,8 @@ async fn appointments_survive_remigration() { | ||
| 128 | 128 | const PROPOSED_END: i64 = START + 8_000_003; |
| 129 | 129 | |
| 130 | 130 | 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" }); | |
| 133 | 133 | for creds in [&teacher_creds, &student_creds] { |
| 134 | 134 | assert_eq!( |
| 135 | 135 | send(&app, "POST", "/auth/register", None, Some((*creds).clone())) |
| @@ -274,8 +274,8 @@ async fn appointments_survive_remigration() { | ||
| 274 | 274 | #[tokio::test] |
| 275 | 275 | async fn attempt_history_survives_remigration() { |
| 276 | 276 | 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" }); | |
| 279 | 279 | for creds in [&teacher_creds, &student_creds] { |
| 280 | 280 | assert_eq!( |
| 281 | 281 | send(&app, "POST", "/auth/register", None, Some((*creds).clone())) |
| @@ -565,7 +565,7 @@ async fn chat_thread_delete_cascades_and_stays_owner_scoped() { | ||
| 565 | 565 | async fn settings_slots_without_a_serving_minute_still_patch() { |
| 566 | 566 | let (app, db, tenants) = common::app_and_tenants().await; |
| 567 | 567 | |
| 568 | - let creds = json!({ "school": "demo", "username": "boss", "password": "secret1" }); | |
| 568 | + let creds = json!({ "school": "019732e3-7b00-7000-8000-00000000dead", "username": "boss", "password": "secret1" }); | |
| 569 | 569 | send(&app, "POST", "/auth/register", None, Some(creds)).await; |
| 570 | 570 | set_role(&db, "boss", "manager").await; |
| 571 | 571 | let login = json!({ "username": "boss", "password": "secret1" }); |
| @@ -618,8 +618,8 @@ async fn settings_slots_without_a_serving_minute_still_patch() { | ||
| 618 | 618 | #[tokio::test] |
| 619 | 619 | async fn fee_plans_and_their_charges_survive_remigration() { |
| 620 | 620 | 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" }); | |
| 623 | 623 | for creds in [&manager_creds, &student_creds] { |
| 624 | 624 | assert_eq!( |
| 625 | 625 | send(&app, "POST", "/auth/register", None, Some((*creds).clone())) |
| @@ -859,14 +859,9 @@ async fn boards_and_their_strokes_survive_remigration() { | ||
| 859 | 859 | #[tokio::test] |
| 860 | 860 | async fn an_empty_module_list_survives_a_second_boot() { |
| 861 | 861 | let tenants = database::init_test_tenants().await; |
| 862 | - let slug = Slug::try_new("bare").unwrap(); | |
| 862 | + let bare = hezarfen_backend::tenant::SchoolId::generate(); | |
| 863 | 863 | 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()) | |
| 870 | 865 | .await |
| 871 | 866 | .expect("a school with nothing switched on"); |
| 872 | 867 | |
| @@ -877,9 +872,9 @@ async fn an_empty_module_list_survives_a_second_boot() { | ||
| 877 | 872 | let stored: i64 = sqlx::query_scalar( |
| 878 | 873 | "SELECT count(*) FROM school_module sm |
| 879 | 874 | JOIN school s ON s.id = sm.school |
| 880 | - WHERE s.slug = $1", | |
| 875 | + WHERE s.id = $1", | |
| 881 | 876 | ) |
| 882 | - .bind(slug.as_str()) | |
| 877 | + .bind(bare.uuid()) | |
| 883 | 878 | .fetch_one(tenants.control()) |
| 884 | 879 | .await |
| 885 | 880 | .expect("read the row back"); |
| @@ -909,7 +904,6 @@ async fn probe_control_migration_is_idempotent_over_aged_rows() { | ||
| 909 | 904 | tenants |
| 910 | 905 | .create( |
| 911 | 906 | hezarfen_backend::tenant::SchoolId::generate(), |
| 912 | - &Slug::try_new(slug).unwrap(), | |
| 913 | 907 | name, |
| 914 | 908 | modules, |
| 915 | 909 | ) |
| @@ -944,16 +938,14 @@ async fn probe_control_migration_is_idempotent_over_aged_rows() { | ||
| 944 | 938 | async fn a_half_made_school_is_finished_by_the_next_boot() { |
| 945 | 939 | let tenants = database::init_test_tenants().await; |
| 946 | 940 | let control = tenants.control().clone(); |
| 947 | - let slug = Slug::try_new("half-made").unwrap(); | |
| 948 | 941 | let id = hezarfen_backend::tenant::SchoolId::generate(); |
| 949 | 942 | |
| 950 | 943 | // Exactly what `Tenants::create` commits before it mints a database: the |
| 951 | 944 | // registry row (as `provisioning`) and its entitlements. |
| 952 | 945 | 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)", | |
| 954 | 947 | ) |
| 955 | 948 | .bind(id.uuid()) |
| 956 | - .bind(slug.as_str()) | |
| 957 | 949 | .bind("Half Made") |
| 958 | 950 | .bind("provisioning") |
| 959 | 951 | .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() { | ||
| 962 | 954 | .expect("seed a half-made school row"); |
| 963 | 955 | |
| 964 | 956 | assert!( |
| 965 | - tenants.get(&slug).await.is_err(), | |
| 957 | + tenants.get(&id).await.is_err(), | |
| 966 | 958 | "a school that is still being made must not serve" |
| 967 | 959 | ); |
| 968 | - assert_eq!(status_of(&control, "half-made").await, "provisioning"); | |
| 960 | + assert_eq!(status_of(&control, &id.as_str()).await, "provisioning"); | |
| 969 | 961 | |
| 970 | 962 | tenants |
| 971 | 963 | .reconcile_provisioning() |
| 972 | 964 | .await |
| 973 | 965 | .expect("the boot finishes what the previous one started"); |
| 974 | 966 | |
| 975 | - assert_eq!(status_of(&control, "half-made").await, "active"); | |
| 967 | + assert_eq!(status_of(&control, &id.as_str()).await, "active"); | |
| 976 | 968 | let db = tenants |
| 977 | - .get(&slug) | |
| 969 | + .get(&id) | |
| 978 | 970 | .await |
| 979 | 971 | .expect("the finished school answers"); |
| 980 | 972 | 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() { | ||
| 986 | 978 | // The database the reconciliation minted is this test's, so it goes with |
| 987 | 979 | // the test (the harness only drops what `create` minted). |
| 988 | 980 | tenants |
| 989 | - .drop(&slug) | |
| 981 | + .drop(&id) | |
| 990 | 982 | .await |
| 991 | 983 | .expect("clean up the minted school"); |
| 992 | 984 | } |
| @@ -1009,11 +1001,9 @@ async fn a_half_made_school_is_finished_by_the_next_boot() { | ||
| 1009 | 1001 | #[tokio::test] |
| 1010 | 1002 | async fn a_school_behind_the_schema_head_is_migrated_by_the_next_boot() { |
| 1011 | 1003 | let tenants = database::init_test_tenants().await; |
| 1012 | - let slug = Slug::try_new("behind-the-head").unwrap(); | |
| 1013 | 1004 | let school = tenants |
| 1014 | 1005 | .create( |
| 1015 | 1006 | hezarfen_backend::tenant::SchoolId::generate(), |
| 1016 | - &slug, | |
| 1017 | 1007 | "Behind The Head", |
| 1018 | 1008 | ModuleSet::all(), |
| 1019 | 1009 | ) |
| @@ -1062,9 +1052,10 @@ async fn a_school_behind_the_schema_head_is_migrated_by_the_next_boot() { | ||
| 1062 | 1052 | } |
| 1063 | 1053 | |
| 1064 | 1054 | /// 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) | |
| 1068 | 1059 | .fetch_one(control) |
| 1069 | 1060 | .await |
| 1070 | 1061 | .unwrap() |
| @@ -1076,11 +1067,11 @@ async fn status_of(control: &Database, slug: &str) -> String { | ||
| 1076 | 1067 | async fn school_rows(control: &Database) -> Vec<(String, String, String, Vec<String>)> { |
| 1077 | 1068 | use sqlx::Row as _; |
| 1078 | 1069 | sqlx::query( |
| 1079 | - "SELECT s.slug, s.name, s.status, | |
| 1070 | + "SELECT s.id::text, s.name, s.status, | |
| 1080 | 1071 | COALESCE(array_agg(sm.module) FILTER (WHERE sm.module IS NOT NULL), '{}') |
| 1081 | 1072 | FROM school s LEFT JOIN school_module sm ON sm.school = s.id |
| 1082 | 1073 | GROUP BY s.id |
| 1083 | - ORDER BY s.slug", | |
| 1074 | + ORDER BY s.id", | |
| 1084 | 1075 | ) |
| 1085 | 1076 | .fetch_all(control) |
| 1086 | 1077 | .await |
tests/podcast.rsmodified+8 -8
| @@ -33,7 +33,7 @@ use hezarfen_backend::constant::{ | ||
| 33 | 33 | use hezarfen_backend::database::Database; |
| 34 | 34 | use hezarfen_backend::domain::timestamp::Timestamp; |
| 35 | 35 | use hezarfen_backend::module::{Module, ModuleSet}; |
| 36 | -use hezarfen_backend::tenant::{DEMO_SLUG, Slug}; | |
| 36 | +use hezarfen_backend::tenant::{DEMO_SCHOOL_ID, SchoolId}; | |
| 37 | 37 | use serde_json::{Value, json}; |
| 38 | 38 | use uuid::Uuid; |
| 39 | 39 | |
| @@ -111,8 +111,8 @@ fn client_endpoint(bridge: &AiBridge) -> quinn::Endpoint { | ||
| 111 | 111 | endpoint |
| 112 | 112 | } |
| 113 | 113 | |
| 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") | |
| 116 | 116 | } |
| 117 | 117 | |
| 118 | 118 | fn hello(service: &str, capabilities: &[&str]) -> Hello { |
| @@ -412,7 +412,7 @@ fn report_frame( | ||
| 412 | 412 | ) -> Value { |
| 413 | 413 | json!({ |
| 414 | 414 | "id": format!("report-{state}"), |
| 415 | - "school": DEMO_SLUG, | |
| 415 | + "school": DEMO_SCHOOL_ID, | |
| 416 | 416 | "capability": "podcast.report", |
| 417 | 417 | "payload": { |
| 418 | 418 | "job_id": job_id, |
| @@ -433,7 +433,7 @@ fn upload_frame(job_id: &str, name: &str, content_type: &str, size: usize) -> Va | ||
| 433 | 433 | json!({ |
| 434 | 434 | "id": format!("upload-{job_id}"), |
| 435 | 435 | "upload": true, |
| 436 | - "school": DEMO_SLUG, | |
| 436 | + "school": DEMO_SCHOOL_ID, | |
| 437 | 437 | "job_id": job_id, |
| 438 | 438 | "name": name, |
| 439 | 439 | "content_type": content_type, |
| @@ -650,7 +650,7 @@ async fn a_submit_writes_the_row_and_hands_the_service_its_own_job_id() { | ||
| 650 | 650 | let seen = service.seen(); |
| 651 | 651 | assert_eq!(seen.len(), 1, "exactly one dispatch"); |
| 652 | 652 | 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"); | |
| 654 | 654 | assert_eq!( |
| 655 | 655 | seen[0].payload["job_id"], job_id, |
| 656 | 656 | "the service was handed the row's own id" |
| @@ -1239,10 +1239,10 @@ async fn the_history_never_shows_another_schools_jobs() { | ||
| 1239 | 1239 | let demo_db = common::demo_db(&deployment.tenants).await; |
| 1240 | 1240 | let beta_db = deployment |
| 1241 | 1241 | .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")) | |
| 1243 | 1243 | .await |
| 1244 | 1244 | .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; | |
| 1246 | 1246 | let beta_cookie = common::login_as_school(app, &beta_db, "beta", "ali", "teacher").await; |
| 1247 | 1247 | let demo_user = common::me_id(app, &demo_cookie).await; |
| 1248 | 1248 | 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() { | ||
| 105 | 105 | #[tokio::test] |
| 106 | 106 | async fn register_and_login_share_the_auth_bucket() { |
| 107 | 107 | 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" }); | |
| 109 | 109 | |
| 110 | 110 | let (status, _, _) = send_as(&app, "1.1.1.1", "POST", "/auth/register", Some(creds)).await; |
| 111 | 111 | assert_eq!(status, StatusCode::CREATED); |
tests/regress_bank_images.rsmodified+1 -1
| @@ -65,7 +65,7 @@ async fn mem_app() -> (Router, Database, TempDir) { | ||
| 65 | 65 | /// Every blob file currently on disk, by name. |
| 66 | 66 | fn blobs(files: &TempDir) -> Vec<String> { |
| 67 | 67 | // 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); | |
| 69 | 69 | if !dir.exists() { |
| 70 | 70 | return Vec::new(); |
| 71 | 71 | } |
tests/spec_bounds.rsmodified+0 -16
| @@ -61,8 +61,6 @@ async fn spec() -> Value { | ||
| 61 | 61 | fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { |
| 62 | 62 | vec![ |
| 63 | 63 | // --- builder (the vendor surface) --- |
| 64 | - ("CreateSchool", "slug", "minLength", MIN_SLUG_LEN as i64), | |
| 65 | - ("CreateSchool", "slug", "maxLength", MAX_SLUG_LEN as i64), | |
| 66 | 64 | ( |
| 67 | 65 | "CreateSchool", |
| 68 | 66 | "name", |
| @@ -160,18 +158,6 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { | ||
| 160 | 158 | MAX_PASSWORD_LEN as i64, |
| 161 | 159 | ), |
| 162 | 160 | // --- 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 | - ), | |
| 175 | 161 | ( |
| 176 | 162 | "RegisterCredentials", |
| 177 | 163 | "username", |
| @@ -250,8 +236,6 @@ fn expectations() -> Vec<(&'static str, &'static str, &'static str, i64)> { | ||
| 250 | 236 | "maxLength", |
| 251 | 237 | MAX_STUDENT_NUMBER_LEN as i64, |
| 252 | 238 | ), |
| 253 | - ("SelectSchool", "school", "minLength", MIN_SLUG_LEN as i64), | |
| 254 | - ("SelectSchool", "school", "maxLength", MAX_SLUG_LEN as i64), | |
| 255 | 239 | ("UpdateProfile", "name", "maxLength", MAX_NAME_LEN as i64), |
| 256 | 240 | ("UpdateProfile", "surname", "maxLength", MAX_NAME_LEN as i64), |
| 257 | 241 | ("UpdateProfile", "email", "maxLength", MAX_EMAIL_LEN as i64), |