From 20e856a55c0278c5cbec6e81d09cf64e2a18d09e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Tue, 22 Sep 2026 23:16:37 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix:=20scope=20manager=20study?= =?UTF-8?q?=20questions=20to=20the=20school=20and=20publish=20its=20name?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An admin with no personal class row was dispatched to rag.chat with zero scope pairs, so every study question abstained. Managers and admins now get every class-course pair. A rag.index registration replays notes that have files, because that index is in-memory and a restart wipes it. GET /school returns {id, name} to every school session. No slug. --- ...75d79c52ba5c429f24759b08164865f79f24b.json | 74 +++++++++++ README.md | 7 +- src/ai/rag.rs | 114 ++++++++++++++++ src/ai/rag_chat.rs | 2 +- src/ai/server.rs | 51 +++++++- src/db/course_note.rs | 24 ++++ src/lib.rs | 5 +- src/service/rag_scope.rs | 122 ++++++++++++++---- src/web/mod.rs | 1 + src/web/rag.rs | 37 +++--- src/web/school.rs | 68 ++++++++++ tests/integration.rs | 58 ++++++++- 12 files changed, 516 insertions(+), 47 deletions(-) create mode 100644 .sqlx/query-a7556b35313487c902861391f5575d79c52ba5c429f24759b08164865f79f24b.json create mode 100644 src/web/school.rs diff --git a/.sqlx/query-a7556b35313487c902861391f5575d79c52ba5c429f24759b08164865f79f24b.json b/.sqlx/query-a7556b35313487c902861391f5575d79c52ba5c429f24759b08164865f79f24b.json new file mode 100644 index 0000000..deabffd --- /dev/null +++ b/.sqlx/query-a7556b35313487c902861391f5575d79c52ba5c429f24759b08164865f79f24b.json @@ -0,0 +1,74 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT id AS \"id: CourseNoteId\", course AS \"course: CourseId\",\n author AS \"author: UserId\", title AS \"title: CourseNoteTitle\",\n content AS \"content: CourseNoteContent\"\n FROM course_note\n WHERE EXISTS (\n SELECT 1 FROM course_note_file\n WHERE course_note_file.course_note = course_note.id\n )\n ORDER BY id DESC", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: CourseNoteId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_note", + "name": "id" + } + } + }, + { + "ordinal": 1, + "name": "course: CourseId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_note", + "name": "course" + } + } + }, + { + "ordinal": 2, + "name": "author: UserId", + "type_info": "Uuid", + "origin": { + "Table": { + "table": "course_note", + "name": "author" + } + } + }, + { + "ordinal": 3, + "name": "title: CourseNoteTitle", + "type_info": "Text", + "origin": { + "Table": { + "table": "course_note", + "name": "title" + } + } + }, + { + "ordinal": 4, + "name": "content: CourseNoteContent", + "type_info": "Text", + "origin": { + "Table": { + "table": "course_note", + "name": "content" + } + } + } + ], + "parameters": { + "Left": [] + }, + "nullable": [ + false, + false, + false, + false, + false + ] + }, + "hash": "a7556b35313487c902861391f5575d79c52ba5c429f24759b08164865f79f24b" +} diff --git a/README.md b/README.md index 9ed44d1..a97889e 100644 --- a/README.md +++ b/README.md @@ -1446,6 +1446,7 @@ window filtering, before paging; negative values are a `400` naming the field. | POST | `/rag/threads/{id}/messages` | student | Ask the corpus a question: `{content}`, at most the school's `max_chatbot_message_len`. Answers `202 {message_id, status: "pending"}` the moment both rows are written — the answer itself lands later, in the reserved assistant row. `503` when no AI service offers `rag.chat`, and nothing is written; `429` + `Retry-After` over the per-user send limit. | | GET | `/rag/threads/{id}/messages/{mid}` | student | Poll one turn. The non-SSE fallback for `/stream`, reading the same row — including the projection that presents a long-stale `pending` as `failed`, so the two can never disagree about a turn's state. | | GET | `/rag/threads/{id}/messages/{mid}/stream` | student | Watch one turn as Server-Sent Events: `delta` chunks of the answer, then a single `done` carrying the finished message, or one `error`. The stream closes after `done`/`error` — one stream per turn, not per thread. | +| GET | `/school` | student | The school the session cookie is bound to: its uuid and display name. | | GET | `/schools` | builder | Every school this deployment serves, newest first. Paged via `?limit=&offset=` (omit `limit` for the full list). | | POST | `/schools` | builder | Create a school: its registry row, its database, its schema, and its first admin account — one call, or none of it. | | GET | `/schools/{slug}` | builder | One school by slug. | @@ -4182,8 +4183,10 @@ The HTTP doors are `POST /rag/summarize` and `POST /rag/questions`, with a flat body: `ders` (required, non-empty), `sinif`, `pages`, `span_ids`, `scope_label`, and for questions `n` (default 5, at most 20), `difficulty` (default `orta`) and `seed_question`. Authorization is the nest's own scope derivation, applied -twice: the caller's `(sınıf, ders)` pairs come from their live memberships and -the body only **names a target inside them** — a pair the caller does not hold is +twice: the caller's `(sınıf, ders)` pairs come from the same derivation as +`rag.chat` (a manager or an admin gets every class-course pair in the school; +everyone else, their live memberships) and the body only **names a target +inside them** — a pair the caller does not hold is a `403`, and omitting `sinif` for a ders taught at more than one grade is a `400`, because choosing a corpus for the caller would answer from material they never named. The door maps the service's `soru`/`cevap`/`zorluk` onto this API's diff --git a/src/ai/rag.rs b/src/ai/rag.rs index 221d539..f663ebc 100644 --- a/src/ai/rag.rs +++ b/src/ai/rag.rs @@ -11,6 +11,13 @@ //! unreadable answer all leave the previously stored //! [`RagOutput`](crate::domain::rag_output::RagOutput) rows exactly as they //! are. A slightly stale index beats no index. +//! +//! A service restart wipes an in-memory index and does not replay it. +//! [`spawn_index_replay`] runs when a worker that offers `rag.index` +//! registers, and calls [`index_course_note`] for every course note that has +//! files, in every active school. The spawn returns immediately: the QUIC +//! handshake must not wait on it. A chatbot, zeka, or podcast registration +//! does not offer `rag.index`, so it does not replay. use serde::{Deserialize, Serialize}; @@ -218,9 +225,96 @@ pub fn spawn_index(state: &AppState, tenant: &ResolvedTenant, note: CourseNote) tokio::spawn(async move { index_course_note(&state, &tenant, ¬e).await }); } +/// Whether a worker that just registered should have the course-note index +/// replayed. Only `rag.index` does. `rag.chat`, the chatbot, zeka, and the +/// podcast worker do not — their registration must not walk every school. +pub(crate) fn should_replay_index(capabilities: &[String]) -> bool { + capabilities + .iter() + .any(|capability| capability == AI_RAG_INDEX_CAPABILITY) +} + +/// [`replay_indexed_notes`] off the handshake path. Returns as soon as the +/// task is spawned. `state.ai` must already be the bridge that just +/// registered the worker; `state.db` may still be the control database — +/// each school is swapped in before [`index_course_note`]. +pub(crate) fn spawn_index_replay(state: AppState) { + tokio::spawn(async move { + replay_indexed_notes(state).await; + }); +} + +/// Re-dispatch [`index_course_note`] for every course note that has files, in +/// every active school. One note at a time: a replay is a catch-up, not a +/// stampede, and the worker's own concurrency cap is what bounds a single +/// dispatch. +async fn replay_indexed_notes(state: AppState) { + let directory = match crate::db::insight::active_schools(state.tenants.control()).await { + Ok(directory) => directory, + Err(err) => { + tracing::warn!("rag.index replay could not list active schools: {err}"); + return; + } + }; + for slug in directory.schools { + replay_school(&state, &slug).await; + } +} + +async fn replay_school(state: &AppState, slug: &str) { + let slug = match crate::tenant::Slug::try_new(slug) { + Ok(slug) => slug, + Err(err) => { + tracing::warn!("rag.index replay skipped an unreadable school slug: {err}"); + return; + } + }; + let tenant = match state.tenants.resolve(&slug).await { + Ok(tenant) => tenant, + Err(err) => { + tracing::warn!("rag.index replay skipped `{slug}`: {err}"); + return; + } + }; + if !tenant.modules.contains(Module::Chatbot) { + tracing::debug!("rag.index replay skipped `{slug}`: the school has no chatbot module"); + return; + } + let notes = match crate::db::course_note::list_with_files(&tenant.db).await { + Ok(notes) => notes, + Err(err) => { + tracing::warn!("rag.index replay could not list course notes in `{slug}`: {err}"); + return; + } + }; + if notes.is_empty() { + tracing::debug!("rag.index replay: `{slug}` has no course notes with files"); + return; + } + tracing::info!( + school = %slug, + notes = notes.len(), + "replaying rag.index for course notes with files" + ); + // `index_course_note` writes through `state.db`, which on the request + // path is the shadow school's database. The root handed in here is the + // control database, so the school handle has to be swapped in first. + let school_state = AppState { + db: tenant.db.clone(), + ..state.clone() + }; + for note in ¬es { + index_course_note(&school_state, &tenant, note).await; + } +} + #[cfg(test)] mod tests { use super::*; + use crate::constant::{ + AI_CHAT_CAPABILITY, AI_INSIGHT_STUDENT_CAPABILITY, AI_PODCAST_SUBMIT_CAPABILITY, + AI_RAG_CHAT_CAPABILITY, + }; use serde_json::json; #[test] @@ -267,4 +361,24 @@ mod tests { .unwrap(); assert!(bare.files.is_empty()); } + + /// Chatbot, zeka, podcast, and even `rag.chat` must not replay. A worker + /// that offers `rag.index` alongside something else still does. + #[test] + fn index_replay_runs_only_when_the_worker_offers_rag_index() { + assert!(should_replay_index(&[AI_RAG_INDEX_CAPABILITY.to_string()])); + assert!(should_replay_index(&[ + AI_CHAT_CAPABILITY.to_string(), + AI_RAG_INDEX_CAPABILITY.to_string(), + ])); + assert!(!should_replay_index(&[AI_CHAT_CAPABILITY.to_string()])); + assert!(!should_replay_index(&[AI_RAG_CHAT_CAPABILITY.to_string()])); + assert!(!should_replay_index(&[ + AI_INSIGHT_STUDENT_CAPABILITY.to_string() + ])); + assert!(!should_replay_index(&[ + AI_PODCAST_SUBMIT_CAPABILITY.to_string() + ])); + assert!(!should_replay_index(&[])); + } } diff --git a/src/ai/rag_chat.rs b/src/ai/rag_chat.rs index 5493d02..c02f7b4 100644 --- a/src/ai/rag_chat.rs +++ b/src/ai/rag_chat.rs @@ -134,7 +134,7 @@ pub struct RagChatReplyPayload { /// /// The request is built from what the session already proves — `asker` and /// `asker_role` are read from the live session by the caller, never taken from -/// a body, and `scope` from the asker's own memberships — and the reply is +/// a body, and `scope` from [`crate::service::rag_scope`] — and the reply is /// mapped into what a message row can hold: the answer text, the abstention, /// and the citations whose corpus `doc_id` resolves to a course-note file the /// asker may view. diff --git a/src/ai/server.rs b/src/ai/server.rs index a45700c..b80effc 100644 --- a/src/ai/server.rs +++ b/src/ai/server.rs @@ -23,7 +23,7 @@ use crate::ai::registry::{AiRegistry, WorkerSnapshot, clamp_concurrency}; use crate::ai::tls; use crate::constant::{ AI_BLOB_WRITE_STALL_SECS, AI_HANDSHAKE_TIMEOUT_SECS, AI_MAX_FRAME_BYTES, AI_PROTOCOL, - REQUEST_TIMEOUT_SECS, + AI_RAG_INDEX_CAPABILITY, REQUEST_TIMEOUT_SECS, }; use crate::database::Database; @@ -32,6 +32,7 @@ use crate::domain::monotonic_id::next_uuid; use crate::domain::user::{User, UserId}; use crate::error::AppError; use crate::module::Module; +use crate::state::AppState; use crate::telemetry::Metrics; use crate::service::course::can_view_course; use crate::tenant::{ResolvedTenant, Slug, Tenants}; @@ -122,6 +123,11 @@ struct Inner { /// process's instruments are built with the router, after the listener is /// bound. metrics: OnceLock, + /// Root [`AppState`] with `ai` cleared, armed by [`AiBridge::arm_api`]. + /// A `rag.index` registration replays the course-note index through it. + /// `ai` stays `None` here so this lock does not cycle back into the + /// bridge that holds it; the replay fills the bridge in on a clone. + replay: OnceLock, } impl Inner { @@ -187,6 +193,7 @@ impl AiBridge { request_timeout: config.request_timeout, endpoint, metrics: OnceLock::new(), + replay: OnceLock::new(), }); tracing::info!( "AI bridge listening on {bound} (protocol {AI_PROTOCOL}, cert sha256 {fingerprint})" @@ -376,6 +383,7 @@ impl AiBridge { tenants: Tenants, files_path: std::path::PathBuf, metrics: Metrics, + state: &AppState, ) { // Not warned about on a second call: the instruments are the same // process-global ones either way, so re-arming changes nothing. @@ -392,6 +400,17 @@ impl AiBridge { { tracing::warn!("the AI bridge api path was already armed — keeping the first router"); } + // `ai` cleared: storing the caller's state as-is would cycle + // AppState -> bridge -> this lock -> AppState, and the replay fills + // the bridge back in on a clone. A worker that registered in the + // boot window, before this arm, already missed its own kick. + let mut rooted = state.clone(); + rooted.ai = None; + if self.inner.replay.set(rooted).is_err() { + tracing::warn!("rag index replay was already armed — keeping the first state"); + } else if self.has_capability(AI_RAG_INDEX_CAPABILITY) { + spawn_index_replay_if_armed(&self.inner); + } } /// Stop listening and close every service connection. @@ -442,7 +461,7 @@ async fn serve_connection(inner: Arc, conn: quinn::Connection) { ) .await; - let (worker_id, service, _control) = match handshake { + let (worker_id, service, capabilities, _control) = match handshake { Ok(Ok(registered)) => registered, Ok(Err(())) => return, Err(_) => { @@ -452,6 +471,12 @@ async fn serve_connection(inner: Arc, conn: quinn::Connection) { return; } }; + // The welcome is already on the wire. Spawned, not awaited: walking + // every school's notes must not hold the handshake, and a registration + // that does not offer `rag.index` does not enter. + if crate::ai::rag::should_replay_index(&capabilities) { + spawn_index_replay_if_armed(&inner); + } // The control stream is held open (`_control`) for the connection's life. // Nothing more is read on it: its closure, not a heartbeat frame, is how a @@ -1202,7 +1227,7 @@ type Control = (quinn::SendStream, quinn::RecvStream); async fn register( inner: &Inner, conn: &quinn::Connection, -) -> Result<(String, String, Control), ()> { +) -> Result<(String, String, Vec, Control), ()> { let (mut send, mut recv) = match conn.accept_bi().await { Ok(streams) => streams, Err(e) => { @@ -1288,7 +1313,7 @@ async fn register( max_concurrent, "AI service registered" ); - Ok((worker_id, hello.service, (send, recv))) + Ok((worker_id, hello.service, hello.capabilities, (send, recv))) } /// Send a rejection the service can act on, then close. Best-effort: a peer @@ -1311,6 +1336,24 @@ async fn refuse( conn.close(1u32.into(), message.as_bytes()); } +/// Re-index course notes with files, off the handshake path. +/// +/// No-op when [`AiBridge::arm_api`] has not stored the root state yet. A +/// worker that dials in during that window is covered by the arm-time kick, +/// once the state exists and the worker is already in the registry. +fn spawn_index_replay_if_armed(inner: &Arc) { + let Some(mut state) = inner.replay.get().cloned() else { + tracing::warn!( + "rag.index worker registered before replay state was armed; skipping index replay" + ); + return; + }; + state.ai = Some(AiBridge { + inner: Arc::clone(inner), + }); + crate::ai::rag::spawn_index_replay(state); +} + /// Compare two secrets without leaking their common prefix length through /// timing. Length difference is not secret (and cannot be hidden here), but /// the byte comparison must not short-circuit. diff --git a/src/db/course_note.rs b/src/db/course_note.rs index 63db375..70f9c97 100644 --- a/src/db/course_note.rs +++ b/src/db/course_note.rs @@ -79,6 +79,30 @@ pub async fn list_for_course( .await } +/// Every course note that has at least one attachment, newest first. +/// +/// One statement: the attachment table is filtered in the `EXISTS`, not +/// queried once per note. A note with no files is absent — a `rag.index` +/// replay has nothing to send for it. `file_count` is not the predicate: +/// the file rows are the ground truth, and the counter is only a cap. +pub async fn list_with_files(db: &Database) -> Result, AppError> { + let notes = sqlx::query_as!( + CourseNote, + r#"SELECT id AS "id: CourseNoteId", course AS "course: CourseId", + author AS "author: UserId", title AS "title: CourseNoteTitle", + content AS "content: CourseNoteContent" + FROM course_note + WHERE EXISTS ( + SELECT 1 FROM course_note_file + WHERE course_note_file.course_note = course_note.id + ) + ORDER BY id DESC"#, + ) + .fetch_all(db) + .await?; + Ok(notes) +} + /// Request-scoped: no lock spans the handler's read and this write, so an /// omitted field (`None`) is not written at all. Passing the snapshot's /// value back instead would revert a concurrent edit of that field — diff --git a/src/lib.rs b/src/lib.rs index a86501c..3b2f21b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -54,9 +54,10 @@ use crate::web::module_gate::gate; (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"), (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"), (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."), + (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`."), (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 `.` (see the `builder` tag for cookie prefixing); with two or more it answers `{username, schools: [{slug, name}]}` and a `person.` 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"), (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"), - (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 the asker's own `(sınıf, ders)` pairs, derived on each request from their live memberships — their şubeler' instances, 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."), + (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."), (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."), (name = "podcast", description = "Podcast generation, relayed through the same QUIC bridge as the chatbot and the RAG nest — and the **backend owns the job**, not just the HTTP surface. `POST /podcast/jobs` (`{source_id, format?}`) resolves the note's newest `application/pdf` attachment — the blob key the dispatch hands the service as `source_key`, so the service opens `//` — refusing `409 source_missing` when the note has no PDF or its bytes are missing from this host, then mints the job id, writes the row, dispatches `podcast.submit` to the service and answers `202` with `{job_id, state, eta_secs}`; `GET /podcast/jobs/{id}` polls the backend's own row `{state, stage, progress, error_code}` with no service round trip, `GET /podcast/jobs/{id}/result` collects a finished job's `{audio_id, duration_secs, format}` (`409` while it is still running), `GET /podcast/jobs/{id}/audio` streams the episode the service uploaded into this school's own blob directory, and `POST /podcast/jobs/{id}/cancel` asks the service to stop it (`cancelled` is \"this call stopped work\", so a finished job answers `false`; a terminal job answers without the service); `GET /podcast/jobs` is the caller's own history, newest first (`?limit=&offset=`), each row carrying the title of the note it narrated. The service reports every transition back through the `podcast.report` capability and uploads the finished mp3 — so status, result and audio keep answering while the service is down or restarted, and a job nobody is updating reads as failed/interrupted after an ETA-scaled window. Submit and cancel refuse `503` when no worker is connected; none of the four read doors needs one (404 for an unknown or foreign job, 410 past the retention window, 409 before the job is done or when its blob is missing from this host)."), (name = "users", description = "User info: self-service profile and UI preferences (theme `light`/`dark`, language `tr`/`en`, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names — `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins…, accent color `palette_color` as `#rrggbb` — returned on every user response, `null` until chosen), name search for the pickers (any authenticated user, optionally role-filtered; a student or parent sees only the staff they may message), plus account creation (admin only: `POST /users` mints a school account outright, born with the role the caller names — `student` by default), listing, lookup, and role/profile/preferences administration (admin only). An admin never changes their own role, and the school's **last** admin cannot be demoted at all (`409`) — role management can no longer lock everyone out, not even when two admins demote each other at the same instant. Also the parent↔student ties: admins link students to a `parent` account under `/users/{id}/students` (link, list, unlink — a role change on either side drops its ties in the *same transaction* as the role write, so a failure mid-way leaves the old role with all its ties intact rather than a half-applied change), and a parent lists their own students at `/users/me/students`; every one of those lists is filtered to accounts that hold the `student` role **right now**, so a tie whose student was promoted out names nobody, exactly as it grants nothing; the tie grants the parent read access to those students' mark, attendance, pomodoro, and homework reports and nothing else. Every account also has a **public profile** (`GET /users/me/profile`, `GET /users/{id}/profile`): username, `display_name` (the self-chosen one, else the `name surname` join, else `null` — the very same three steps every embedded person ref resolves, so a chosen name shows school-wide; it never replaces `name`/`surname`, which stay the school-office record, and it deliberately stays out of the user search fold), role, `bio`, avatar metadata, a narrowed class/course block (id/name/grade and id/title/kind only — never a class's creator or homeroom teacher — capped at `max_profile_classes` / `max_profile_courses`, since `/classes/me` and `/courses/me` are the full paged lists), a sixteen-key `stats` block, and the badges those stats have earned. Four stats are computed at read (finished pomodoro stints and their focused milliseconds, plus the full course and class counts) and twelve are stored lifetime tallies maintained at write time, so a tally can outlive the rows behind it — a deleted exam does not un-sit it; all sixteen read `0`, never `null`. Five are the student's own work (`homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` — **exams sat**, not sittings: a retake of an exam already counted moves nothing, since an `open` exam with unlimited attempts is a start/finish loop a student runs with no teacher in it —, `pomodoro_finished_total`, `pomodoro_focus_ms_total` — the last two count only stints that **counted**: at least `pomodoro.min_counted_ms` long and within that UTC day's `pomodoro.max_counted_per_day`, since a start/finish pair is two requests with nobody else in it, so `pomodoro_sessions` may legitimately run ahead of them), and seven more cover both sides of the school: `marks_given_total` (grades a teacher recorded, exam sittings and homework alike, once per pair — a regrade moves nothing, but deleting the grade gives it back, since the grader who deletes is the grader who was credited and grade → un-grade → regrade would otherwise count the same work twice), `lessons_held_total` (a session teacher's lessons, credited by the **first roll call taken at or after the lesson's own `starts_at`**, so neither a lesson scheduled and cancelled nor two hundred marked before they begin count for anything), `pool_approved_total` and `pool_published_total` (the approver's and the asker's halves of one pending→approved transition — a teacher approving their own question publishes it but earns neither, since a counter moves only when one person's work was judged by somebody else), `lessons_attended_total` (a **student** marked `present` or `late` at lesson roll call, moved back down by a correction to any other status and untouched by daily/event attendance), `high_mark_total` (the student's exam marks at or above `badges.high_mark_min`, once per sitting, given back when the mark is deleted on the same terms as the grader's — but unlike the grader's, a **regrade does move it** whenever the correction crosses the cut in either direction, since it counts marks *stored* above the line rather than first gradings, which is the only way the credit and the refund read the same value; homework marks are optional and often status-only, so they never count), and `study_streak_total` — the **longest** run of consecutive days the student finished a pomodoro stint that counted, not a sum, spelled `_total` like every other key so a client joins it to the catalog's `stat` name mechanically. Days there end at **midnight UTC**, like every other day calculation here, and the run is read as a high-water mark, so breaking it never takes a badge back. **Badges are auto-earned only** — no route awards or revokes one; a badge appears when a stored counter crosses a hardcoded threshold and is **permanent**, surviving that counter falling back (withdrawing a submission decrements the counter, never the badge), with `earned_at` pinned at the first crossing and the list ordered oldest first. Each entry is `{id, earned_at}`: labels and icons belong to the client, keyed by id, exactly as for `roles` and course `kinds`. The catalog behind the ids is `badges.catalog[]` at `GET /limits` (`{id, stat, threshold}`, 34 badges over twelve counters, `stat` being the API's name for the counter rather than the column it is stored in) alongside `badges.high_mark_min`, the exam mark the `high_mark` ladder counts from (the id alone does not say it), both compiled in, so a threshold moves only with a deploy. Contact details (`email`, `phone`, `birth_date`) are **not** part of it and keep exactly the gate they have today. Any authenticated account reads any profile — except a `parent`, who reads their own and their linked students' only, with the link *and* the target's live role re-read per call, so an unlinked or promoted-out student stops being readable at once. The courses block follows the owner's **live** role: teacher+ lists what they teach, everyone else what they are enrolled in, so a demoted ex-teacher lists enrollments and not what they created — and it is then cut to the courses the *reader* may already read at `GET /courses/{id}` (a title a reader is `403` on there must not arrive here instead), so a stranger sees an empty block while the owner and manager+ see it whole; the truncation runs after that filter. The class block is cut the same way, against the bar `GET /classes/user/{id}` holds: teacher+, a parent linked to that student, or the owner reading their own profile — every other reader (a fellow student included) gets an empty `classes` array rather than a `403`, since a class name and grade are exactly what the `/classes` routes withhold below teacher+. **Every** number in `stats` stays the owner's true total either way, not just those two — `pomodoro_focus_ms`/`pomodoro_focus_ms_total` are the same figure `GET /pomodoro/{id}` serves behind its observer gate, and `lessons_attended_total`, `homework_submitted_total`, `homework_on_time_total`, `exam_sat_total` and `high_mark_total` are magnitudes of the mark and attendance data behind that same gate (for a reader who is exactly a `teacher`, wider than the `can_manage_course`-narrowed `/marks/user/{id}` and `/attendance/user/{id}` reports). That is deliberate: they are motivational counters, a magnitude names no course, class, lesson or exam, and a per-reader figure would make one profile read differently to different people. `display_name` (≤ 50) and `bio` (≤ 500) ride the same `PATCH /users/me` / `PATCH /users/{id}/profile` pair as the rest of the personal info, `\"\"` clearing either. One avatar per account: `POST /users/me/avatar` (multipart, raster types only — no SVG, whose script can run when the bytes render inline school-wide — at most the school's `max_file_bytes` rather than a knob of its own; replacing one drops the previous picture), the bytes at `GET /users/{id}/avatar` — or `GET /users/me/avatar` for the caller's own, so a client never needs to know its own id — (same reach as the profile, served `nosniff` and `private, no-store`), removed by the owner at `DELETE /users/me/avatar` or, as moderation, by an admin at `DELETE /users/{id}/avatar`"), @@ -155,6 +156,7 @@ pub fn build_router(state: AppState) -> Router { .routes(routes!(server_time)) .merge(web::limits::routes()) .merge(web::modules::routes()) + .merge(web::school::routes()) .nest("/ai", web::ai::routes()) .nest("/auth", web::auth::routes(&state)) .merge(web::builder::routes(&state)) @@ -282,6 +284,7 @@ pub fn build_router(state: AppState) -> Router { state.tenants.clone(), state.files_path.clone(), metrics.clone(), + &state, ); } diff --git a/src/service/rag_scope.rs b/src/service/rag_scope.rs index b43a63d..6eabaac 100644 --- a/src/service/rag_scope.rs +++ b/src/service/rag_scope.rs @@ -4,8 +4,8 @@ //! separately would cross-product into combinations the asker never named //! ([`crate::constant::MAX_RAG_SCOPE_PAIRS`]) — so every question needs the set //! of pairs its asker is allowed to retrieve from, and that set is derived -//! *here*, from the asker's own rows, never from the request body: a scope a -//! client could name is a scope a client could widen. +//! *here*, never from the request body: a scope a client could name is a +//! scope a client could widen. //! //! The derivation is the school's own visibility rules, not a second copy of //! them. A student's or a teacher's pairs are the courses their @@ -15,14 +15,21 @@ //! school-scoped course belongs to no section. A parent has no sections of //! their own, so their scope is their linked children's, read child by child //! through the same reader: what a parent may ask about is exactly what their -//! children could be taught. +//! children could be taught. A manager or an admin is none of those people: +//! their scope is every class-course instance in the school +//! ([`crate::db::class_group::list_all`] plus +//! [`crate::db::class_course::list_for_class_ids`]), not the rows their own +//! account happens to hold. An empty personal membership is not an empty +//! school, and it is not a legal empty scope. //! //! Two consequences are deliberate. An empty scope is legal and returned as an -//! empty list — the service answers an unscopable question by abstaining, and a -//! `400` here would refuse questions the asker is entitled to ask. And a union -//! over the cap is **refused**, never narrowed: dropping pairs would answer a -//! question scoped to corpora the asker did not name, which is worse than no -//! answer at all. +//! empty list when the asker really has nothing to retrieve from — a student +//! in no section, a teacher with no assignment, a parent with no linked child, +//! a manager of a school that has no class-course instance. The service +//! answers an unscopable question by abstaining, and a `400` here would refuse +//! questions the asker is entitled to ask. And a union over the cap is +//! **refused**, never narrowed: dropping pairs would answer a question scoped +//! to corpora the asker did not name, which is worse than no answer at all. use std::collections::{HashMap, HashSet}; @@ -40,25 +47,34 @@ use crate::error::{AppError, ValidationError}; /// first-seen order and deduped — one entry per distinct pair. /// /// `role` is the caller's **live** session role, the same value the -/// `rag.chat` payload carries: the instance arm is the asker's own rows for -/// everyone but a parent (a section membership, a homeroom column and a -/// teaching assignment are all keyed on live roles anyway), and the parent -/// arm is the one that has to be chosen by role, because a parent's own +/// `rag.chat` payload carries. A manager or an admin reads every class-course +/// instance in the school. Everyone else reads their own rows: a section +/// membership, a homeroom column and a teaching assignment are all keyed on +/// the live role, and the parent arm is chosen by role because a parent's own /// sections do not exist. /// -/// The instance arm reads its rows through [`super::instance::visible_instances`] -/// and the two lookup tables (the class sections the pairs sit in and the -/// titles of every course named) in one batch read each — never one query per -/// instance: a teacher can be assigned to dozens of sections, and a per-row -/// lookup would spend the request's whole budget before the AI service is even -/// called. +/// The non-manager instance arm reads its rows through +/// [`super::instance::visible_instances`], and both arms finish with the same +/// two lookup tables (the class sections the pairs sit in and the titles of +/// every course named) in one batch read each — never one query per instance. +/// A teacher can be assigned to dozens of sections, and a per-row lookup would +/// spend the request's whole budget before the AI service is even called. pub async fn for_user( db: &Database, user: &User, role: Role, ) -> Result, AppError> { let mut instances: Vec = Vec::new(); - if role == Role::Parent { + if role.at_least(Role::Manager) { + // A manager or an admin asks about the school, not about the rows + // their own account holds. A system admin is in no section, no + // homeroom and no teaching assignment, so the personal read is empty + // — and an empty personal read is not an empty school. + let (classes, _) = crate::db::class_group::list_all(db, None, None, 0).await?; + let class_ids: Vec = + classes.iter().map(|class| class.get_id().clone()).collect(); + instances = crate::db::class_course::list_for_class_ids(db, &class_ids).await?; + } else if role == Role::Parent { // A parent's scope is what their children are taught — read through // the same visibility rule, one child at a time because the rule // keys on the person asking. A link whose student side changed role @@ -86,11 +102,15 @@ pub async fn for_user( } // The school-scoped courses the asker joined directly (club, supervised // study). Every role may hold one — the table's own gate is the student - // role, so for staff this read is simply empty. - let memberships = + // role, so for staff this read is simply empty. A manager's scope is the + // school's instances, not this personal list, so the read is skipped. + let memberships = if role.at_least(Role::Manager) { + Vec::new() + } else { crate::db::course_membership::list_for_user(db, user.get_id(), None, 0) .await? - .0; + .0 + }; // One batch read per lookup, over every id the two arms named: the class // sections decide each instance's grade, and the courses carry the titles @@ -360,4 +380,62 @@ mod tests { let scope = for_user(&db, &student, Role::Student).await.unwrap(); assert_eq!(scope, vec![pair(Some("6"), "Matematik")]); } + + /// A manager or an admin with no personal class row still scopes every + /// class-course pair in the school. A student or a teacher with none does + /// not: their empty membership stays an empty scope. Two sections at one + /// grade teaching one subject are still one pair — the cap refuses a + /// union, it does not get a duplicate slot. + #[tokio::test] + async fn a_manager_with_no_membership_scopes_the_whole_school() { + let (db, _leases) = crate::database::init_test_db().await; + let manager = person(&db, "ragscope-manager", Role::Manager).await; + let admin = person(&db, "ragscope-admin", Role::Admin).await; + let student = person(&db, "ragscope-empty-student", Role::Student).await; + let teacher = person(&db, "ragscope-empty-teacher", Role::Teacher).await; + let grade_eight_a = graded_class(&db, "8-A", "8").await; + let grade_eight_b = graded_class(&db, "8-B", "8").await; + let grade_nine = graded_class(&db, "9-A", "9").await; + attach(&db, &grade_eight_a, "Biology").await; + attach(&db, &grade_eight_b, "Biology").await; + attach(&db, &grade_nine, "Chemistry").await; + + let expected = vec![ + (Some("8".to_owned()), "Biology".to_owned()), + (Some("9".to_owned()), "Chemistry".to_owned()), + ]; + let manager_scope = for_user(&db, &manager, Role::Manager).await.unwrap(); + let admin_scope = for_user(&db, &admin, Role::Admin).await.unwrap(); + assert_eq!(pair_keys(&manager_scope), expected); + assert_eq!(pair_keys(&admin_scope), expected); + assert_eq!( + manager_scope.len(), + 2, + "the repeated grade-8 subject is one pair" + ); + assert!( + for_user(&db, &student, Role::Student) + .await + .unwrap() + .is_empty(), + "a student with no membership still has an empty scope" + ); + assert!( + for_user(&db, &teacher, Role::Teacher) + .await + .unwrap() + .is_empty(), + "a teacher with no assignment still has an empty scope" + ); + } + + /// First-seen order is the wire order; the assertion compares the set. + fn pair_keys(pairs: &[RagScopePair]) -> Vec<(Option, String)> { + let mut keys: Vec<_> = pairs + .iter() + .map(|pair| (pair.sinif.clone(), pair.ders.clone())) + .collect(); + keys.sort(); + keys + } } diff --git a/src/web/mod.rs b/src/web/mod.rs index 5e71a90..c5072e0 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -36,6 +36,7 @@ pub mod pomodoro; pub mod questions; pub mod rag; pub mod room; +pub mod school; pub mod sessions; pub mod settings; pub mod subjects; diff --git a/src/web/rag.rs b/src/web/rag.rs index b044dcd..50a8dc4 100644 --- a/src/web/rag.rs +++ b/src/web/rag.rs @@ -6,8 +6,9 @@ //! thread, the payload format, and the last look at the reply before it is //! stored. There are no intent or rule tables, and every thread is private to //! its owner. What differs is the **scope**: every question carries the -//! `(class, course)` pairs the corpus is routed by, derived server-side from the -//! asker's own memberships ([`crate::service::rag_scope`]) and never from the +//! `(class, course)` pairs the corpus is routed by, derived server-side +//! ([`crate::service::rag_scope`]: a manager or an admin gets every class-course +//! pair in the school, everyone else their own memberships) and never from the //! request body, and every citation the service returns is resolved here to //! the course-note file that owns the cited document — the `doc_id` only the //! backend can turn into something a reader can open. @@ -438,7 +439,7 @@ async fn list_messages( /// thread is a `404` and is never charged), then the per-user rate limit (a /// refused turn leaves no trace), then availability (so an unavailable service /// produces a `503` and no dead pending row), then the scope the question is -/// asked under — derived from the asker's own memberships, never from the +/// asked under — derived by [`crate::service::rag_scope`], never from the /// body. Once the rows are written the turn always settles: the answering task /// stamps `complete`/`failed`, a reader projects a long-stale `pending` as /// failed, and the boot sweep repairs whatever a process death left behind. @@ -500,12 +501,15 @@ async fn send_message( return Ok(ai_unavailable("no AI service is connected right now")); } - // The scope the corpus is routed by, derived from the asker's own - // memberships on every question — never from the body, so a student cannot + // The scope the corpus is routed by, derived on every question — a + // manager or an admin gets every class-course pair in the school, everyone + // else their own memberships — never from the body, so a student cannot // widen their own retrieval, and never from a stored copy, so a // membership change takes effect on the next question. An empty scope is - // legal and is sent as-is: the service abstains rather than the backend - // refusing a question it cannot know is answerable. + // legal when the asker really has nothing to retrieve from, and is sent + // as-is: the service abstains rather than the backend refusing a question + // it cannot know is answerable. An admin's empty personal membership is + // not that case. let scope = service::rag_scope::for_user(&st.db, &user, user.get_role()).await?; // Each create rides the thread's own row — it moves `updated_at` (the @@ -891,7 +895,7 @@ struct StudyScopeRequest { impl StudyScopeRequest { /// The wire scope this request names, with the **resolved** pair as its /// `(sinif, ders)` half: the corpus the service is addressed to is the one - /// the asker's own memberships authorized, never the body's spelling of + /// [`crate::service::rag_scope`] authorized, never the body's spelling of /// it. fn into_scope(self, pair: RagScopePair) -> RagScope { RagScope { @@ -1072,9 +1076,11 @@ fn resolve_study_pair( /// /// Synchronous by design: the summary is what the caller asked for, so there is /// no thread to open, no row to poll and nothing stored. The scope is derived -/// from the asker's own memberships — never from the body, which only names a -/// target inside them — and the `(sinif, ders)` pair that reaches the service -/// is the derived one. `503` when no AI service offers `rag.summarize`. +/// by [`crate::service::rag_scope`] — a manager or an admin gets every +/// class-course pair in the school, everyone else their own memberships — +/// never from the body, which only names a target inside them — and the +/// `(sinif, ders)` pair that reaches the service is the derived one. `503` +/// when no AI service offers `rag.summarize`. /// `abstained: true` with a `reason` is a complete answer riding a `200`. /// /// The dispatch deadline (25 s) is deliberately under the middleware's own @@ -1114,10 +1120,11 @@ async fn summarize( return Ok(ai_unavailable("no AI service is connected right now")); } - // The scope the corpus is routed by, derived from the asker's own - // memberships on every request — never from the body, so a caller cannot - // summarize a corpus they cannot study. The body's `ders`/`sinif` only pick - // a pair out of that set. + // The scope the corpus is routed by, derived on every request — a manager + // or an admin gets every class-course pair in the school, everyone else + // their own memberships — never from the body, so a caller cannot + // summarize a corpus they cannot study. The body's `ders`/`sinif` only + // pick a pair out of that set. let pairs = service::rag_scope::for_user(&st.db, &user, user.get_role()).await?; let pair = resolve_study_pair(&pairs, &req.ders, req.sinif.as_deref())?; let payload = RagSummarizePayload { diff --git a/src/web/school.rs b/src/web/school.rs new file mode 100644 index 0000000..6a61078 --- /dev/null +++ b/src/web/school.rs @@ -0,0 +1,68 @@ +//! The caller's own school, on the school side of the line. +//! +//! `GET /schools` is the vendor registry and answers only a builder cookie. +//! This route is the inverse: the school the session cookie is already bound +//! to, readable by every authenticated role. The uuid is the identity; the +//! slug stays off the wire. + +use axum::Json; +use serde::Serialize; +use utoipa::ToSchema; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; + +use crate::error::{AppError, ErrorResponse}; +use crate::state::AppState; +use crate::tenant::{ResolvedTenant, School}; +use crate::web::CurrentUser; +use crate::web::tenant_state::State; + +pub fn routes() -> OpenApiRouter { + OpenApiRouter::new().routes(routes!(current_school)) +} + +/// The school behind the session cookie. `id` is the registry uuid — the +/// identity the database name and every structural reference mint from — and +/// `name` is the display name. The slug is not here: it is a label, not an +/// identity, and this response does not publish it. +#[derive(Serialize, ToSchema)] +struct SchoolIdentity { + #[schema(example = "019732e3-7b00-7000-8000-00000000dead")] + id: String, + #[schema(example = "Ata Koleji")] + name: String, +} + +/// The school the session cookie is bound to: its uuid and display name. +/// +/// Any authenticated school user may read it, including a student or a parent. +/// A builder cookie names no school and is `401`, the same as on every other +/// school surface. +#[utoipa::path( + get, + path = "/school", + tag = "school", + security(("session_cookie" = [])), + responses( + (status = 200, description = "The school this session is bound to", body = SchoolIdentity), + (status = 401, description = "Not authenticated", body = ErrorResponse), + ), +)] +async fn current_school( + State(st): State, + tenant: ResolvedTenant, + _user: CurrentUser, +) -> Result, AppError> { + let school = School::read(&tenant.slug, st.tenants.control()) + .await? + .ok_or_else(|| { + AppError::Internal(format!( + "the resolved school `{}` has no control row", + tenant.slug + )) + })?; + Ok(Json(SchoolIdentity { + id: school.get_id().uuid().to_string(), + name: school.name().to_string(), + })) +} diff --git a/tests/integration.rs b/tests/integration.rs index 8caff72..660e728 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -85,6 +85,56 @@ async fn time_serves_server_clock_without_auth() { assert!(before <= now && now <= after); } +/// `GET /school` is the school the session cookie is already bound to. +/// Every authenticated role may read it; a missing cookie and a builder +/// cookie are both `401`, the same as every other school surface. The body +/// is the registry uuid and the display name — never the slug. +#[tokio::test] +async fn get_school_returns_uuid_and_name_without_slug() { + let (app, db, tenants) = app_and_tenants().await; + let (id, name): (Uuid, String) = + sqlx::query_as("SELECT id, name FROM school WHERE slug = 'demo'") + .fetch_one(tenants.control()) + .await + .expect("demo school"); + + let anon = send(&app, "GET", "/school", None, None).await; + assert_eq!(anon.status, StatusCode::UNAUTHORIZED); + + hezarfen_backend::service::builder::ensure( + tenants.control(), + Username::try_new("operator").unwrap(), + Password::try_new("secret1").unwrap(), + ) + .await + .expect("seed the builder"); + let builder_login = send( + &app, + "POST", + "/builder/login", + None, + Some(json!({ "username": "operator", "password": "secret1" })), + ) + .await; + assert_eq!(builder_login.status, StatusCode::OK, "{}", builder_login.body); + let builder_cookie = builder_login.cookie.expect("builder cookie"); + let builder = send(&app, "GET", "/school", Some(&builder_cookie), None).await; + assert_eq!(builder.status, StatusCode::UNAUTHORIZED, "{}", builder.body); + + let expected = json!({ "id": id.to_string(), "name": name }); + for (username, role) in [("school_student", "student"), ("school_parent", "parent")] { + let cookie = login_as(&app, &db, username, role).await; + let res = send(&app, "GET", "/school", Some(&cookie), None).await; + assert_eq!(res.status, StatusCode::OK, "{role}: {}", res.body); + assert_eq!(res.body, expected, "{role}"); + assert!( + res.body.get("slug").is_none(), + "{role} response must not carry a slug: {}", + res.body + ); + } +} + #[tokio::test] async fn limits_publishes_the_bounds_the_api_actually_enforces() { let app = mem_app().await; @@ -434,7 +484,7 @@ async fn protected_routes_require_session() { /// Floor on the number of protected operations swept. It only ever goes /// up: raise it when routes are added. Without it, deleting a route family /// would delete its own coverage and still pass. - const MIN_PROTECTED: usize = 342; + const MIN_PROTECTED: usize = 343; let app = mem_app().await; let spec = send(&app, "GET", "/api-docs/openapi.json", None, None) @@ -30051,7 +30101,7 @@ async fn a_school_with_no_modules_can_still_use_the_core_routes() { /// Route prefixes that are deliberately ungated, each with the reason it is — /// a nest here is one no school can be sold or refused. -const CORE_PREFIXES: [(&str, &str); 13] = [ +const CORE_PREFIXES: [(&str, &str); 14] = [ ("/", "the health mirror at the root"), ("/health", "liveness, read before any school is resolved"), ("/time", "the server clock, a deploy constant"), @@ -30083,6 +30133,10 @@ const CORE_PREFIXES: [(&str, &str); 13] = [ "the vendor principal, which is not a school user", ), ("/schools", "the vendor's registry surface, same principal"), + ( + "/school", + "the caller's own school identity, not a sold module", + ), ]; /// Every module's nest prefix. Written down rather than derived: the point is