forge
Explore
Log in

Don't you dare go Hollow

Tell the AI service which role is asking

Browse files at this commit

d5def0261daa7a3c0a1d696784de7740fb6be161Ahmet Kaan GümüşParent: cb766df
  • feat
    • tell the AI service which role is asking
Show full message
🤖 feat: tell the AI service which role is asking

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.mdmodified+10 -0
@@ -3714,10 +3714,20 @@ Requests then arrive as ordinary `hab/1` `Request` frames whose `payload` is:
3714 3714
3715 ```json3715 ```json
3716 { "message": "and the second law?",3716 { "message": "and the second law?",
3717+ "asker_role": "student",
3717 "history": [ {"role":"user","content":"what is the first law?"},3718 "history": [ {"role":"user","content":"what is the first law?"},
3718 {"role":"assistant","content":"an object at rest …"} ] }3719 {"role":"assistant","content":"an object at rest …"} ] }
3719 ```3720 ```
3720 3721
3722+`asker_role` is the **school role of the person asking** — one of `parent`,
3723+`student`, `teacher`, `manager`, `admin` (the same lowercase strings the rest of
3724+the API uses). Answer to it: a student must not be handed an answer scoped for a
3725+manager. It is read live from the authenticated session on every request and can
3726+never be set by the client — the send body carries `content` and nothing else —
3727+so it is safe to trust. Note it is *not* the `role` inside a `history` entry:
3728+that one is `user`/`assistant`, who *said* the turn. The backend does no
3729+role-based filtering of its own; scoping the answer is the service's job.
3730+
3721 `history` is **oldest first** (index 0 is furthest back), optional (absent or3731 `history` is **oldest first** (index 0 is furthest back), optional (absent or
3722 `[]` = a fresh thread), and **excludes** the new message — that one is3732 `[]` = a fresh thread), and **excludes** the new message — that one is
3723 `message`. It carries the last `chatbot_history_turns` **settled messages** —3733 `message`. It carries the last `chatbot_history_turns` **settled messages** —
src/ai/chat.rsmodified+33 -3
@@ -40,6 +40,17 @@ pub struct ChatTurn {
40 pub struct ChatRequestPayload {40 pub struct ChatRequestPayload {
41 /// The user's new message. `history` does *not* contain it.41 /// The user's new message. `history` does *not* contain it.
42 pub message: String,42 pub message: String,
43+ /// The **school role** of the person asking — `"parent"`, `"student"`,
44+ /// `"teacher"`, `"manager"` or `"admin"`, the same lowercase strings the
45+ /// rest of the API uses ([`Role::as_str`](crate::domain::role::Role::as_str)).
46+ /// Deliberately not `role`: that name belongs to [`ChatTurn`], where it says
47+ /// who *said* a turn.
48+ ///
49+ /// Read live from the authenticated session on every request and never
50+ /// taken from the request body, so a service may answer on it: a student
51+ /// must not be handed an answer scoped for a manager. Scoping the answer is
52+ /// the service's job — the backend only forwards the role.
53+ pub asker_role: String,
43 /// The last N turns of the conversation, **oldest first** — index 0 is the54 /// The last N turns of the conversation, **oldest first** — index 0 is the
44 /// furthest back, the final element is the turn immediately before55 /// furthest back, the final element is the turn immediately before
45 /// `message`. Same order a model's `messages` array expects, so a service56 /// `message`. Same order a model's `messages` array expects, so a service
@@ -65,12 +76,14 @@ pub struct ChatReplyPayload {
65 #[cfg(test)]76 #[cfg(test)]
66 mod tests {77 mod tests {
67 use super::*;78 use super::*;
79+ use crate::domain::role::Role;
68 use serde_json::json;80 use serde_json::json;
69 81
70 #[test]82 #[test]
71 fn payloads_round_trip() {83 fn payloads_round_trip() {
72 let request = ChatRequestPayload {84 let request = ChatRequestPayload {
73 message: "and the second?".into(),85 message: "and the second?".into(),
86+ asker_role: Role::Student.as_str().to_string(),
74 history: vec![87 history: vec![
75 ChatTurn {88 ChatTurn {
76 role: ChatRole::User,89 role: ChatRole::User,
@@ -104,6 +117,7 @@ mod tests {
104 // silently breaks every one of them, so pin the encoding.117 // silently breaks every one of them, so pin the encoding.
105 let request = serde_json::to_value(ChatRequestPayload {118 let request = serde_json::to_value(ChatRequestPayload {
106 message: "hi".into(),119 message: "hi".into(),
120+ asker_role: Role::Teacher.as_str().to_string(),
107 history: vec![121 history: vec![
108 ChatTurn {122 ChatTurn {
109 role: ChatRole::User,123 role: ChatRole::User,
@@ -120,12 +134,24 @@ mod tests {
120 request,134 request,
121 json!({135 json!({
122 "message": "hi",136 "message": "hi",
137+ "asker_role": "teacher",
123 "history": [138 "history": [
124 { "role": "user", "content": "a" },139 { "role": "user", "content": "a" },
125 { "role": "assistant", "content": "b" },140 { "role": "assistant", "content": "b" },
126 ],141 ],
127 })142 })
128 );143 );
144+ // Every role reaches the wire as its documented lowercase slug — the
145+ // one `Role::as_str` already publishes, not a second spelling.
146+ for role in crate::constant::ROLES {
147+ let encoded = serde_json::to_value(ChatRequestPayload {
148+ message: "hi".into(),
149+ asker_role: role.as_str().to_string(),
150+ history: Vec::new(),
151+ })
152+ .unwrap();
153+ assert_eq!(encoded["asker_role"], role.as_str());
154+ }
129 assert_eq!(155 assert_eq!(
130 serde_json::to_value(ChatReplyPayload { text: "ok".into() }).unwrap(),156 serde_json::to_value(ChatReplyPayload { text: "ok".into() }).unwrap(),
131 json!({ "text": "ok" })157 json!({ "text": "ok" })
@@ -137,10 +163,13 @@ mod tests {
137 fn history_is_optional_on_the_wire() {163 fn history_is_optional_on_the_wire() {
138 // The smallest legal request: a first turn, from a service author who164 // The smallest legal request: a first turn, from a service author who
139 // never sends an empty array.165 // never sends an empty array.
140- let bare: ChatRequestPayload = serde_json::from_value(json!({ "message": "hi" })).unwrap();166+ let bare: ChatRequestPayload =
167+ serde_json::from_value(json!({ "message": "hi", "asker_role": "student" })).unwrap();
141 assert!(bare.history.is_empty());168 assert!(bare.history.is_empty());
142- let empty: ChatRequestPayload =169+ let empty: ChatRequestPayload = serde_json::from_value(
143- serde_json::from_value(json!({ "message": "hi", "history": [] })).unwrap();170+ json!({ "message": "hi", "asker_role": "student", "history": [] }),
171+ )
172+ .unwrap();
144 assert_eq!(bare, empty);173 assert_eq!(bare, empty);
145 }174 }
146 175
@@ -150,6 +179,7 @@ mod tests {
150 // oldest turn depends on it.179 // oldest turn depends on it.
151 let raw = json!({180 let raw = json!({
152 "message": "third",181 "message": "third",
182+ "asker_role": "student",
153 "history": [183 "history": [
154 { "role": "user", "content": "first" },184 { "role": "user", "content": "first" },
155 { "role": "assistant", "content": "second" },185 { "role": "assistant", "content": "second" },
src/web/chatbot.rsmodified+10 -0
@@ -44,6 +44,7 @@ use crate::domain::chatbot_message::{
44 ChatContent, ChatbotMessage, ChatbotMessageId, MessageRole, MessageStatus,44 ChatContent, ChatbotMessage, ChatbotMessageId, MessageRole, MessageStatus,
45 };45 };
46 use crate::domain::chatbot_thread::{ChatbotThread, ChatbotThreadId, ChatbotThreadTitle};46 use crate::domain::chatbot_thread::{ChatbotThread, ChatbotThreadId, ChatbotThreadTitle};
47+use crate::domain::role::Role;
47 use crate::domain::settings::Settings;48 use crate::domain::settings::Settings;
48 use crate::domain::user::UserId;49 use crate::domain::user::UserId;
49 use crate::error::{AppError, ErrorResponse, ValidationError};50 use crate::error::{AppError, ErrorResponse, ValidationError};
@@ -426,11 +427,16 @@ async fn send_message(
426 // interleave across the two creates above, and picking "the newest user row427 // interleave across the two creates above, and picking "the newest user row
427 // before this answer" out of the thread then answers the *other* request's428 // before this answer" out of the thread then answers the *other* request's
428 // question twice.429 // question twice.
430+ // The asker's role goes with the turn so the service can scope its answer.
431+ // Read here, from the session's own user row (roles are re-read on every
432+ // request), so it is the live role at the moment the question was asked —
433+ // never a stored copy, and never anything the body could assert.
429 tokio::spawn(answer_turn(434 tokio::spawn(answer_turn(
430 bridge,435 bridge,
431 st.db.clone(),436 st.db.clone(),
432 prompt.get_id().clone(),437 prompt.get_id().clone(),
433 answer,438 answer,
439+ user.get_role(),
434 settings.get_chatbot_history_turns().max(0) as usize,440 settings.get_chatbot_history_turns().max(0) as usize,
435 reply_cap,441 reply_cap,
436 ));442 ));
@@ -471,6 +477,7 @@ async fn answer_turn(
471 db: Database,477 db: Database,
472 prompt_id: ChatbotMessageId,478 prompt_id: ChatbotMessageId,
473 answer: ChatbotMessage,479 answer: ChatbotMessage,
480+ asker_role: Role,
474 history_turns: usize,481 history_turns: usize,
475 reply_cap: usize,482 reply_cap: usize,
476 ) {483 ) {
@@ -504,6 +511,7 @@ async fn answer_turn(
504 &thread,511 &thread,
505 &fresh,512 &fresh,
506 prompt.get_content().as_str().to_string(),513 prompt.get_content().as_str().to_string(),
514+ asker_role,
507 history_turns,515 history_turns,
508 reply_cap,516 reply_cap,
509 )517 )
@@ -534,6 +542,7 @@ async fn fetch_reply(
534 thread: &ChatbotThreadId,542 thread: &ChatbotThreadId,
535 fresh: &[ChatbotMessageId; 2],543 fresh: &[ChatbotMessageId; 2],
536 prompt: String,544 prompt: String,
545+ asker_role: Role,
537 history_turns: usize,546 history_turns: usize,
538 reply_cap: usize,547 reply_cap: usize,
539 ) -> Result<(ChatContent, bool), String> {548 ) -> Result<(ChatContent, bool), String> {
@@ -546,6 +555,7 @@ async fn fetch_reply(
546 };555 };
547 let payload = serde_json::to_value(ChatRequestPayload {556 let payload = serde_json::to_value(ChatRequestPayload {
548 message: prompt,557 message: prompt,
558+ asker_role: asker_role.as_str().to_string(),
549 history,559 history,
550 })560 })
551 .map_err(|err| {561 .map_err(|err| {
tests/ai_bridge.rsmodified+60 -0
@@ -1256,6 +1256,66 @@ async fn two_racing_turns_on_one_thread_each_answer_their_own_prompt() {
1256 );1256 );
1257 }1257 }
1258 1258
1259+#[tokio::test]
1260+async fn a_service_is_told_the_askers_own_school_role() {
1261+ // The service answers differently for a student than for a manager, so the
1262+ // role it reads must be the asker's own. Two different roles go through the
1263+ // real endpoint: a hardcoded slug would pass one of them and fail the other.
1264+ let bridge = bridge().await;
1265+ let service = connect_service(
1266+ &bridge,
1267+ hello("tutor", &[AI_CHAT_CAPABILITY]),
1268+ Behaviour::Reply("peki".into()),
1269+ )
1270+ .await;
1271+ await_workers(&bridge, 1).await;
1272+ let (app, db) = chat_app(&bridge).await;
1273+
1274+ for (name, role) in [("ali", "student"), ("veli", "manager")] {
1275+ let cookie = common::login_as(&app, &db, name, role).await;
1276+ let res = common::send(
1277+ &app,
1278+ "POST",
1279+ "/chatbot/threads",
1280+ Some(&cookie),
1281+ Some(json!({})),
1282+ )
1283+ .await;
1284+ assert_eq!(res.status, StatusCode::CREATED, "{}", res.body);
1285+ let thread = common::id_of(&res.body);
1286+
1287+ // The body tries to promote itself. It must change nothing: the role is
1288+ // read from the session, and a send body carries only `content`.
1289+ let res = common::send(
1290+ &app,
1291+ "POST",
1292+ &format!("/chatbot/threads/{thread}/messages"),
1293+ Some(&cookie),
1294+ Some(json!({ "content": "soru", "asker_role": "admin" })),
1295+ )
1296+ .await;
1297+ assert_eq!(res.status, StatusCode::ACCEPTED, "{}", res.body);
1298+ let mid = res.body["message_id"].as_str().expect("message_id");
1299+ assert_eq!(
1300+ settled(&app, &cookie, &thread, mid).await["status"],
1301+ "complete"
1302+ );
1303+ }
1304+
1305+ // Read as untyped JSON, the way a service in another language reads it.
1306+ let seen = service.seen();
1307+ assert_eq!(seen.len(), 2);
1308+ assert_eq!(seen[0].payload["asker_role"], "student");
1309+ assert_eq!(
1310+ seen[1].payload["asker_role"], "manager",
1311+ "the second turn was asked by a manager: {}",
1312+ seen[1].payload
1313+ );
1314+ // And the author role on a turn is a different key, so neither can be read
1315+ // for the other.
1316+ assert!(seen[0].payload["history"].is_array());
1317+}
1318+
1259 /// Every row of a thread, oldest first.1319 /// Every row of a thread, oldest first.
1260 async fn thread_rows(app: &Router, cookie: &str, thread: &str) -> Vec<Value> {1320 async fn thread_rows(app: &Router, cookie: &str, thread: &str) -> Vec<Value> {
1261 let res = common::send(1321 let res = common::send(
tests/ai_protocol.rsmodified+74 -0
@@ -17,6 +17,8 @@
17 //! It doubles as the reference implementation: `raw::Service` below is the17 //! It doubles as the reference implementation: `raw::Service` below is the
18 //! whole client side of `hab/1` in about a hundred lines.18 //! whole client side of `hab/1` in about a hundred lines.
19 19
20+mod common;
21+
20 use std::sync::Arc;22 use std::sync::Arc;
21 use std::time::Duration;23 use std::time::Duration;
22 24
@@ -868,3 +870,75 @@ async fn several_raw_services_serve_one_capability_together() {
868 "every request answered once"870 "every request answered once"
869 );871 );
870 }872 }
873+
874+// ------------------------------------------------------ capability payload --
875+//
876+// The frame shapes above are capability-agnostic. `chat.reply` is the one
877+// capability whose *payload* is a published contract too, and the payload is
878+// built by the HTTP handler — so the only way to pin it as a foreign service
879+// sees it is to drive the real endpoint and read the bytes off the wire.
880+
881+#[tokio::test]
882+async fn a_chat_request_names_the_askers_school_role() {
883+ // A chat service scopes its answer by who is asking, so the payload must
884+ // carry the asker's school role as a bare lowercase string — read here out
885+ // of the raw frame bytes, never through the crate's own payload struct.
886+ let bridge = bridge().await;
887+ let service = raw::handshake(&bridge, &raw::hello("tutor", "chat.reply")).await;
888+ await_workers(&bridge, 1).await;
889+
890+ let db = hezarfen_backend::database::init_mem()
891+ .await
892+ .expect("mem db");
893+ let app = hezarfen_backend::build_router(hezarfen_backend::state::AppState {
894+ db: db.clone(),
895+ files_path: common::files_dir(),
896+ cookie_secure: false,
897+ rate_limit: hezarfen_backend::rate_limit::RateLimitConfig::unlimited(),
898+ chatbot_limit: Default::default(),
899+ exam_presence: Default::default(),
900+ board_hub: Default::default(),
901+ db_up: Default::default(),
902+ ai: Some(bridge.clone()),
903+ });
904+ let cookie = common::login_as(&app, &db, "veli", "teacher").await;
905+ let res = common::send(
906+ &app,
907+ "POST",
908+ "/chatbot/threads",
909+ Some(&cookie),
910+ Some(json!({})),
911+ )
912+ .await;
913+ let thread = common::id_of(&res.body);
914+ let res = common::send(
915+ &app,
916+ "POST",
917+ &format!("/chatbot/threads/{thread}/messages"),
918+ Some(&cookie),
919+ Some(json!({ "content": "ikinci yasa nedir?" })),
920+ )
921+ .await;
922+ assert_eq!(res.status, axum::http::StatusCode::ACCEPTED, "{}", res.body);
923+
924+ let (request, bytes, send, _recv) = raw::take_request(&service.conn).await;
925+ assert_eq!(request["capability"], "chat.reply");
926+ assert_eq!(
927+ raw::keys(&request["payload"]),
928+ ["asker_role", "history", "message"],
929+ "the documented chat request payload keys"
930+ );
931+ assert_eq!(request["payload"]["message"], "ikinci yasa nedir?");
932+ assert_eq!(request["payload"]["asker_role"], "teacher");
933+ // Byte-level: a bare `"teacher"`, not an object-wrapped or capitalised
934+ // enum — a re-tagged role would still parse as JSON above.
935+ let text = String::from_utf8(bytes).expect("the frame body is UTF-8 JSON");
936+ assert!(text.contains(r#""asker_role":"teacher""#), "{text}");
937+
938+ let id = request["id"].as_str().expect("trace id").to_string();
939+ raw::answer(
940+ send,
941+ format!(r#"{{"status":"ok","id":"{id}","payload":{{"text":"F = ma"}}}}"#).as_bytes(),
942+ )
943+ .await;
944+}