From d5def0261daa7a3c0a1d696784de7740fb6be161 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 12 Aug 2026 00:40:14 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=A4=96=20feat:=20tell=20the=20AI=20servic?= =?UTF-8?q?e=20which=20role=20is=20asking?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The chatbot has to answer a student differently than a manager, but the bridge payload never said who was on the other end — only the prompt and the turn history crossed. Carry the asker's school role with the request so the service can scope its answer. The role is read live off the authenticated session on every request and there is no DTO field for it, so a client cannot claim a role it does not hold. It rides as a bare lowercase slug from Role::as_str(), named asker_role rather than role so it is not confused with the message-author role already on each history turn. Breaking for the AI services: the field is required, so they must read it before this binary goes up. --- README.md | 10 ++++++ src/ai/chat.rs | 36 +++++++++++++++++++-- src/web/chatbot.rs | 10 ++++++ tests/ai_bridge.rs | 60 +++++++++++++++++++++++++++++++++++ tests/ai_protocol.rs | 74 ++++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 187 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 6ef08fa..83c3ca5 100644 --- a/README.md +++ b/README.md @@ -3714,10 +3714,20 @@ Requests then arrive as ordinary `hab/1` `Request` frames whose `payload` is: ```json { "message": "and the second law?", + "asker_role": "student", "history": [ {"role":"user","content":"what is the first law?"}, {"role":"assistant","content":"an object at rest …"} ] } ``` +`asker_role` is the **school role of the person asking** — one of `parent`, +`student`, `teacher`, `manager`, `admin` (the same lowercase strings the rest of +the API uses). Answer to it: a student must not be handed an answer scoped for a +manager. It is read live from the authenticated session on every request and can +never be set by the client — the send body carries `content` and nothing else — +so it is safe to trust. Note it is *not* the `role` inside a `history` entry: +that one is `user`/`assistant`, who *said* the turn. The backend does no +role-based filtering of its own; scoping the answer is the service's job. + `history` is **oldest first** (index 0 is furthest back), optional (absent or `[]` = a fresh thread), and **excludes** the new message — that one is `message`. It carries the last `chatbot_history_turns` **settled messages** — diff --git a/src/ai/chat.rs b/src/ai/chat.rs index 9cb0df1..3a673f2 100644 --- a/src/ai/chat.rs +++ b/src/ai/chat.rs @@ -40,6 +40,17 @@ pub struct ChatTurn { pub struct ChatRequestPayload { /// The user's new message. `history` does *not* contain it. pub message: String, + /// The **school role** of the person asking — `"parent"`, `"student"`, + /// `"teacher"`, `"manager"` or `"admin"`, the same lowercase strings the + /// rest of the API uses ([`Role::as_str`](crate::domain::role::Role::as_str)). + /// Deliberately not `role`: that name belongs to [`ChatTurn`], where it says + /// who *said* a turn. + /// + /// Read live from the authenticated session on every request and never + /// taken from the request body, so a service may answer on it: a student + /// must not be handed an answer scoped for a manager. Scoping the answer is + /// the service's job — the backend only forwards the role. + pub asker_role: String, /// The last N turns of the conversation, **oldest first** — index 0 is the /// furthest back, the final element is the turn immediately before /// `message`. Same order a model's `messages` array expects, so a service @@ -65,12 +76,14 @@ pub struct ChatReplyPayload { #[cfg(test)] mod tests { use super::*; + use crate::domain::role::Role; use serde_json::json; #[test] fn payloads_round_trip() { let request = ChatRequestPayload { message: "and the second?".into(), + asker_role: Role::Student.as_str().to_string(), history: vec![ ChatTurn { role: ChatRole::User, @@ -104,6 +117,7 @@ mod tests { // silently breaks every one of them, so pin the encoding. let request = serde_json::to_value(ChatRequestPayload { message: "hi".into(), + asker_role: Role::Teacher.as_str().to_string(), history: vec![ ChatTurn { role: ChatRole::User, @@ -120,12 +134,24 @@ mod tests { request, json!({ "message": "hi", + "asker_role": "teacher", "history": [ { "role": "user", "content": "a" }, { "role": "assistant", "content": "b" }, ], }) ); + // Every role reaches the wire as its documented lowercase slug — the + // one `Role::as_str` already publishes, not a second spelling. + for role in crate::constant::ROLES { + let encoded = serde_json::to_value(ChatRequestPayload { + message: "hi".into(), + asker_role: role.as_str().to_string(), + history: Vec::new(), + }) + .unwrap(); + assert_eq!(encoded["asker_role"], role.as_str()); + } assert_eq!( serde_json::to_value(ChatReplyPayload { text: "ok".into() }).unwrap(), json!({ "text": "ok" }) @@ -137,10 +163,13 @@ mod tests { fn history_is_optional_on_the_wire() { // The smallest legal request: a first turn, from a service author who // never sends an empty array. - let bare: ChatRequestPayload = serde_json::from_value(json!({ "message": "hi" })).unwrap(); + let bare: ChatRequestPayload = + serde_json::from_value(json!({ "message": "hi", "asker_role": "student" })).unwrap(); assert!(bare.history.is_empty()); - let empty: ChatRequestPayload = - serde_json::from_value(json!({ "message": "hi", "history": [] })).unwrap(); + let empty: ChatRequestPayload = serde_json::from_value( + json!({ "message": "hi", "asker_role": "student", "history": [] }), + ) + .unwrap(); assert_eq!(bare, empty); } @@ -150,6 +179,7 @@ mod tests { // oldest turn depends on it. let raw = json!({ "message": "third", + "asker_role": "student", "history": [ { "role": "user", "content": "first" }, { "role": "assistant", "content": "second" }, diff --git a/src/web/chatbot.rs b/src/web/chatbot.rs index 4cff243..b9d8fc8 100644 --- a/src/web/chatbot.rs +++ b/src/web/chatbot.rs @@ -44,6 +44,7 @@ use crate::domain::chatbot_message::{ ChatContent, ChatbotMessage, ChatbotMessageId, MessageRole, MessageStatus, }; use crate::domain::chatbot_thread::{ChatbotThread, ChatbotThreadId, ChatbotThreadTitle}; +use crate::domain::role::Role; use crate::domain::settings::Settings; use crate::domain::user::UserId; use crate::error::{AppError, ErrorResponse, ValidationError}; @@ -426,11 +427,16 @@ async fn send_message( // interleave across the two creates above, and picking "the newest user row // before this answer" out of the thread then answers the *other* request's // question twice. + // The asker's role goes with the turn so the service can scope its answer. + // Read here, from the session's own user row (roles are re-read on every + // request), so it is the live role at the moment the question was asked — + // never a stored copy, and never anything the body could assert. tokio::spawn(answer_turn( bridge, st.db.clone(), prompt.get_id().clone(), answer, + user.get_role(), settings.get_chatbot_history_turns().max(0) as usize, reply_cap, )); @@ -471,6 +477,7 @@ async fn answer_turn( db: Database, prompt_id: ChatbotMessageId, answer: ChatbotMessage, + asker_role: Role, history_turns: usize, reply_cap: usize, ) { @@ -504,6 +511,7 @@ async fn answer_turn( &thread, &fresh, prompt.get_content().as_str().to_string(), + asker_role, history_turns, reply_cap, ) @@ -534,6 +542,7 @@ async fn fetch_reply( thread: &ChatbotThreadId, fresh: &[ChatbotMessageId; 2], prompt: String, + asker_role: Role, history_turns: usize, reply_cap: usize, ) -> Result<(ChatContent, bool), String> { @@ -546,6 +555,7 @@ async fn fetch_reply( }; let payload = serde_json::to_value(ChatRequestPayload { message: prompt, + asker_role: asker_role.as_str().to_string(), history, }) .map_err(|err| { diff --git a/tests/ai_bridge.rs b/tests/ai_bridge.rs index f7d2080..bb94379 100644 --- a/tests/ai_bridge.rs +++ b/tests/ai_bridge.rs @@ -1256,6 +1256,66 @@ async fn two_racing_turns_on_one_thread_each_answer_their_own_prompt() { ); } +#[tokio::test] +async fn a_service_is_told_the_askers_own_school_role() { + // The service answers differently for a student than for a manager, so the + // role it reads must be the asker's own. Two different roles go through the + // real endpoint: a hardcoded slug would pass one of them and fail the other. + let bridge = bridge().await; + let service = connect_service( + &bridge, + hello("tutor", &[AI_CHAT_CAPABILITY]), + Behaviour::Reply("peki".into()), + ) + .await; + await_workers(&bridge, 1).await; + let (app, db) = chat_app(&bridge).await; + + for (name, role) in [("ali", "student"), ("veli", "manager")] { + let cookie = common::login_as(&app, &db, name, role).await; + let res = common::send( + &app, + "POST", + "/chatbot/threads", + Some(&cookie), + Some(json!({})), + ) + .await; + assert_eq!(res.status, StatusCode::CREATED, "{}", res.body); + let thread = common::id_of(&res.body); + + // The body tries to promote itself. It must change nothing: the role is + // read from the session, and a send body carries only `content`. + let res = common::send( + &app, + "POST", + &format!("/chatbot/threads/{thread}/messages"), + Some(&cookie), + Some(json!({ "content": "soru", "asker_role": "admin" })), + ) + .await; + assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body); + let mid = res.body["message_id"].as_str().expect("message_id"); + assert_eq!( + settled(&app, &cookie, &thread, mid).await["status"], + "complete" + ); + } + + // Read as untyped JSON, the way a service in another language reads it. + let seen = service.seen(); + assert_eq!(seen.len(), 2); + assert_eq!(seen[0].payload["asker_role"], "student"); + assert_eq!( + seen[1].payload["asker_role"], "manager", + "the second turn was asked by a manager: {}", + seen[1].payload + ); + // And the author role on a turn is a different key, so neither can be read + // for the other. + assert!(seen[0].payload["history"].is_array()); +} + /// Every row of a thread, oldest first. async fn thread_rows(app: &Router, cookie: &str, thread: &str) -> Vec { let res = common::send( diff --git a/tests/ai_protocol.rs b/tests/ai_protocol.rs index b4fd6aa..cdc7a8d 100644 --- a/tests/ai_protocol.rs +++ b/tests/ai_protocol.rs @@ -17,6 +17,8 @@ //! It doubles as the reference implementation: `raw::Service` below is the //! whole client side of `hab/1` in about a hundred lines. +mod common; + use std::sync::Arc; use std::time::Duration; @@ -868,3 +870,75 @@ async fn several_raw_services_serve_one_capability_together() { "every request answered once" ); } + +// ------------------------------------------------------ capability payload -- +// +// The frame shapes above are capability-agnostic. `chat.reply` is the one +// capability whose *payload* is a published contract too, and the payload is +// built by the HTTP handler — so the only way to pin it as a foreign service +// sees it is to drive the real endpoint and read the bytes off the wire. + +#[tokio::test] +async fn a_chat_request_names_the_askers_school_role() { + // A chat service scopes its answer by who is asking, so the payload must + // carry the asker's school role as a bare lowercase string — read here out + // of the raw frame bytes, never through the crate's own payload struct. + let bridge = bridge().await; + let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await; + await_workers(&bridge, 1).await; + + let db = hezarfen_backend::database::init_mem() + .await + .expect("mem db"); + let app = hezarfen_backend::build_router(hezarfen_backend::state::AppState { + db: db.clone(), + files_path: common::files_dir(), + cookie_secure: false, + rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(), + chatbot_limit: Default::default(), + exam_presence: Default::default(), + board_hub: Default::default(), + db_up: Default::default(), + ai: Some(bridge.clone()), + }); + let cookie = common::login_as(&app, &db, "veli", "teacher").await; + let res = common::send( + &app, + "POST", + "/chatbot/threads", + Some(&cookie), + Some(json!({})), + ) + .await; + let thread = common::id_of(&res.body); + let res = common::send( + &app, + "POST", + &format!("/chatbot/threads/{thread}/messages"), + Some(&cookie), + Some(json!({ "content": "ikinci yasa nedir?" })), + ) + .await; + assert_eq!(res.status, axum::http::StatusCode::ACCEPTED, "{}", res.body); + + let (request, bytes, send, _recv) = raw::take_request(&service.conn).await; + assert_eq!(request["capability"], "chat.reply"); + assert_eq!( + raw::keys(&request["payload"]), + ["asker_role", "history", "message"], + "the documented chat request payload keys" + ); + assert_eq!(request["payload"]["message"], "ikinci yasa nedir?"); + assert_eq!(request["payload"]["asker_role"], "teacher"); + // Byte-level: a bare `"teacher"`, not an object-wrapped or capitalised + // enum — a re-tagged role would still parse as JSON above. + let text = String::from_utf8(bytes).expect("the frame body is UTF-8 JSON"); + assert!(text.contains(r#""asker_role":"teacher""#), "{text}"); + + let id = request["id"].as_str().expect("trace id").to_string(); + raw::answer( + send, + format!(r#"{{"status":"ok","id":"{id}","payload":{{"text":"F = ma"}}}}"#).as_bytes(), + ) + .await; +}