diff --git a/README.md b/README.md index 0cc9c52..d5c63e4 100644 --- a/README.md +++ b/README.md @@ -3586,6 +3586,9 @@ exactly, segment for segment (`src/constant.rs`, `AI_API_ALLOWLIST`): /homework/{id}/result /homework/{id}/submission /homework/report/{user} +/course-notes +/course-notes/{id} +/course-notes/{id}/files ``` `{x}` takes exactly one non-empty segment. There is no prefix match and no diff --git a/src/ai/api.rs b/src/ai/api.rs index 44ab131..5688ff5 100644 --- a/src/ai/api.rs +++ b/src/ai/api.rs @@ -72,6 +72,16 @@ mod tests { assert!(!path_allowed("/notes/note123/files/f1")); } + #[test] + fn course_notes_are_readable_but_their_blobs_are_not() { + assert!(path_allowed("/course-notes")); + assert!(path_allowed("/course-notes/note123")); + // The listing of a note's files is JSON; the bytes behind one are not. + assert!(path_allowed("/course-notes/note123/files")); + assert!(!path_allowed("/course-notes/note123/files/f1")); + assert!(!path_allowed("/course-notes/")); + } + #[test] fn trailing_slash_is_a_different_path() { assert!(!path_allowed("/notes/")); diff --git a/src/constant.rs b/src/constant.rs index ef9286d..f11a14f 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -622,7 +622,8 @@ pub const AI_HANDSHAKE_TIMEOUT_SECS: u64 = 10; /// (string arrays are exempt from that completeness gate). /// /// JSON-only, and only what a study-companion needs: who the user is, their -/// notes, their homework, and their own progress reports. Byte-serving routes +/// notes, their course's notes, their homework, and their own progress reports. +/// Byte-serving routes /// (note files, submission files, avatars, question images) are left out — the /// frames carry JSON, and a blob has no business crossing this seam yet. pub const AI_API_ALLOWLIST: &[&str] = &[ @@ -631,6 +632,9 @@ pub const AI_API_ALLOWLIST: &[&str] = &[ "/users/{id}/profile", "/notes", "/notes/{id}", + "/course-notes", + "/course-notes/{id}", + "/course-notes/{id}/files", "/homework", "/homework/{id}", "/homework/{id}/result", diff --git a/src/lib.rs b/src/lib.rs index b1808f8..fd5428b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -41,7 +41,7 @@ use crate::state::AppState; modifiers(&SecurityAddon), tags( (name = "meta", description = "Liveness, the authoritative clock, and the validation contract. `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). 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/1`, 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. 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, 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`. 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). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"), + (name = "ai", description = "AI-bridge discovery. The AI features run as separate services that dial IN to this backend over QUIC (protocol/ALPN `hab/1`, 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. 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`. 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). See the README's \"AI bridge (QUIC)\" section for the frame-level protocol"), (name = "auth", description = "Registration, login, session lifecycle. `POST /auth/register` answers `201` whether or not the username was free, and the two bodies are byte-identical: it returns only `{username, role}` — the echoed name and the `student` role every fresh account gets — and deliberately **no `id`**, since on the taken path there is no row to name (log in to learn your id). A deliberate anti-enumeration measure, since the route is unauthenticated and a `409` would let anyone harvest the school's user list. The accepted cost is that a caller who collides gets no distinct error and simply cannot log in with that password; do not \"fix\" this back to a `409`"), (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 = "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 (teacher+, optionally role-filtered), plus 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`"), diff --git a/tests/ai_bridge.rs b/tests/ai_bridge.rs index 3654710..b2bafc5 100644 --- a/tests/ai_bridge.rs +++ b/tests/ai_bridge.rs @@ -1819,3 +1819,118 @@ async fn deleting_a_course_note_takes_its_rag_outputs_with_it() { assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body); assert!(outputs(&db, ¬e).await.is_empty()); } + +// ------------------------------------------------------- course notes read -- + +/// A registered service, a router, and a course the seeded student is +/// enrolled in (plus one they are not) with a teacher's note in each. +/// Returns (service, student id, note id, enrolled course, foreign course). +async fn course_notes_fixture(bridge: &AiBridge) -> (FakeService, String, String, String, String) { + let service = connect_service( + bridge, + hello("tutor", &[AI_CHAT_CAPABILITY]), + Behaviour::Echo, + ) + .await; + await_workers(bridge, 1).await; + let (app, db) = common::app_with_ai(Some(bridge.clone())).await; + + let student_cookie = common::login_as(&app, &db, "ayse", "student").await; + let student = common::me_id(&app, &student_cookie).await; + let teacher = common::login_as(&app, &db, "hoca", "teacher").await; + + let course = common::create_course(&app, &teacher, "Physics").await; + common::enroll(&app, &teacher, &course, &student).await; + let foreign = common::create_course(&app, &teacher, "Chemistry").await; + + let res = common::send( + &app, + "POST", + "/course-notes", + Some(&teacher), + Some(json!({ "course": course, "title": "Newton", "content": "F = ma" })), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "teacher creates the note"); + let note = common::id_of(&res.body); + + (service, student, note, course, foreign) +} + +#[tokio::test] +async fn a_service_reads_a_course_note_on_behalf_of_an_enrolled_student() { + // The point of #27: a study companion answering about a lesson needs the + // teacher's own material, read with the student's reach and no wider. + let bridge = bridge().await; + let (service, student, note, course, _foreign) = course_notes_fixture(&bridge).await; + + let request = ApiRequest { + id: "trace-course-notes".into(), + path: "/course-notes".into(), + query: Some(format!("course={course}")), + on_behalf_of: Some(student), + method: None, + }; + let (status, body) = ok_answer(api_read(&service.conn, request).await); + assert_eq!(status, 200); + let items = common::items(&body); + assert_eq!( + items.len(), + 1, + "the enrolled student sees the course's note" + ); + assert_eq!(items[0]["id"], note); + assert_eq!(items[0]["title"], "Newton"); +} + +#[tokio::test] +async fn a_course_the_student_is_not_in_is_refused_by_the_handler() { + // The bridge widens the scope, never the reach: the handler's own guard + // is what answers, and it rides back as an `Ok` carrying that status. + let bridge = bridge().await; + let (service, student, _note, _course, foreign) = course_notes_fixture(&bridge).await; + + let request = ApiRequest { + id: "trace-foreign-course".into(), + path: "/course-notes".into(), + query: Some(format!("course={foreign}")), + on_behalf_of: Some(student), + method: None, + }; + let (status, _) = ok_answer(api_read(&service.conn, request).await); + assert_eq!(status, 403, "not enrolled: the course-view guard forbids"); +} + +#[tokio::test] +async fn writing_a_course_note_is_refused_before_dispatch() { + // Read scope means read: the allowlist admits the path, the method gate + // still refuses, and nothing reaches the router. + let bridge = bridge().await; + let (service, _student, _note, _course, _foreign) = course_notes_fixture(&bridge).await; + + let request = ApiRequest { + id: "trace-post".into(), + path: "/course-notes".into(), + query: None, + on_behalf_of: None, + method: Some("POST".into()), + }; + match api_read(&service.conn, request).await { + ApiResponse::Err { code, .. } => assert_eq!(code, "method_not_allowed"), + ApiResponse::Ok { status, .. } => panic!("a POST was dispatched, answering {status}"), + } +} + +#[tokio::test] +async fn a_course_note_file_download_stays_out_of_the_read_scope() { + // The listing of a note's files is JSON and allowed; the bytes behind one + // are not — frames carry JSON under an 8 MiB cap. + let bridge = bridge().await; + let (service, student, note, _course, _foreign) = course_notes_fixture(&bridge).await; + + let path = format!("/course-notes/{note}/files/somefile"); + match api_read(&service.conn, read_of(&path, Some(&student))).await { + ApiResponse::Err { code, .. } => assert_eq!(code, "path_not_allowed"), + ApiResponse::Ok { status, .. } => panic!("a blob route was dispatched, answering {status}"), + } +}