From 317ef9c3590a86675d3d7f2c6d61d3c7906f5e93 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 17:02:29 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=A4=96=20feat:=20allowlist=20the=20GET=20?= =?UTF-8?q?paths=20ai=20services=20may=20read?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Deny-by-default: the bridge will only ever dispatch a service's read into the router when the path matches AI_API_ALLOWLIST segment for segment. No prefix match, no wildcard tail, so a new route family is unreachable to the services until it is listed on purpose. v1 is JSON-only and scoped to what a study companion needs: identity and profile, notes, homework reads, and the marks/attendance/pomodoro reports. Byte-serving routes (note files, submission files, avatars, question images) are left out — the frames carry JSON. The entries are router paths kept by hand, so integration.rs pins each one to a GET in the emitted OpenAPI document: a route rename now breaks the test instead of silently shrinking the services' scope. --- src/ai/api.rs | 106 +++++++++++++++++++++++++++++++++++ src/ai/mod.rs | 2 + src/constant.rs | 29 ++++++++++ tests/integration.rs | 24 ++++++++ tests/limits_completeness.rs | 5 ++ 5 files changed, 166 insertions(+) create mode 100644 src/ai/api.rs diff --git a/src/ai/api.rs b/src/ai/api.rs new file mode 100644 index 0000000..44ab131 --- /dev/null +++ b/src/ai/api.rs @@ -0,0 +1,106 @@ +//! Which REST paths an AI service may read. +//! +//! Deny-by-default: a request the bridge dispatches into the router has to +//! match one of [`AI_API_ALLOWLIST`]'s patterns exactly, segment for segment. +//! There is no prefix match and no wildcard tail — `/notes` never admits +//! `/notes/{id}/files/{file_id}` — so a new route family is unreachable to the +//! services until somebody adds it to the list on purpose. +//! +//! Pure path logic, deliberately independent of the rest of `ai`: it is the +//! access scope, and a scope that needed a connection to evaluate would be +//! harder to test than to bypass. + +use crate::constant::AI_API_ALLOWLIST; + +/// Whether an AI service may `GET` this path. +/// +/// The path is the router path alone: a query string travels in its own frame +/// field, so a `?` here means the caller built the request wrong and the +/// request is refused rather than silently matched on its prefix. +pub fn path_allowed(path: &str) -> bool { + if !path.starts_with('/') || path.contains('?') { + return false; + } + AI_API_ALLOWLIST + .iter() + .any(|pattern| pattern_matches(pattern, path)) +} + +/// One `/`-separated pattern against one path. A literal segment must be +/// equal; a `{name}` placeholder takes exactly one non-empty segment. +fn pattern_matches(pattern: &str, path: &str) -> bool { + let mut expected = pattern[1..].split('/'); + let mut actual = path[1..].split('/'); + loop { + match (expected.next(), actual.next()) { + (None, None) => return true, + (Some(segment), Some(given)) => { + let ok = if segment.starts_with('{') && segment.ends_with('}') { + !given.is_empty() + } else { + segment == given + }; + if !ok { + return false; + } + } + // Different segment counts: a trailing slash or a deeper path is a + // different route, never a longer match of this one. + _ => return false, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn literal_path_matches_exactly() { + assert!(path_allowed("/auth/me")); + assert!(path_allowed("/notes")); + assert!(!path_allowed("/auth/m")); + assert!(!path_allowed("/AUTH/ME")); + } + + #[test] + fn placeholder_takes_one_segment() { + assert!(path_allowed("/notes/note123")); + assert!(path_allowed("/users/user456/profile")); + // A placeholder is one segment, not a tail. + assert!(!path_allowed("/notes/note123/files")); + assert!(!path_allowed("/notes/note123/files/f1")); + } + + #[test] + fn trailing_slash_is_a_different_path() { + assert!(!path_allowed("/notes/")); + assert!(!path_allowed("/auth/me/")); + assert!(!path_allowed("/notes/note123/")); + } + + #[test] + fn empty_segments_never_fill_a_placeholder() { + assert!(!path_allowed("/notes//")); + assert!(!path_allowed("//notes")); + assert!(!path_allowed("/users//profile")); + } + + #[test] + fn query_string_is_refused() { + assert!(!path_allowed("/notes?limit=10")); + assert!(!path_allowed("/notes/note123?x=1")); + } + + #[test] + fn unlisted_and_malformed_paths_are_denied() { + assert!(!path_allowed("")); + assert!(!path_allowed("notes")); + assert!(!path_allowed("/")); + // Real routes that are deliberately out of scope. + assert!(!path_allowed("/users")); + assert!(!path_allowed("/users/user456/avatar")); + assert!(!path_allowed("/settings")); + assert!(!path_allowed("/exams")); + } +} diff --git a/src/ai/mod.rs b/src/ai/mod.rs index 3425eaa..35f3f1d 100644 --- a/src/ai/mod.rs +++ b/src/ai/mod.rs @@ -11,6 +11,7 @@ //! no head-of-line blocking — a 30-second inference on stream 7 does not delay //! the answer on stream 9. Connection setup happens once, not per request. //! +//! * [`api`] — which REST paths a service may read back through the bridge //! * [`protocol`] — frames on the wire //! * [`chat`] — the JSON payloads carried for the `chat.reply` capability //! * [`server`] — the listener, handshake, and [`server::AiBridge::dispatch`] @@ -20,6 +21,7 @@ //! The transport is generic; the features land on top of it. So far that is //! the chatbot (`web::chatbot`), which routes on the `chat.reply` capability. +pub mod api; pub mod chat; pub mod error; pub mod protocol; diff --git a/src/constant.rs b/src/constant.rs index 75a176b..7cbbe76 100644 --- a/src/constant.rs +++ b/src/constant.rs @@ -600,6 +600,35 @@ pub const AI_MAX_REQUEST_TIMEOUT_SECS: u64 = 60; /// occupy the listener indefinitely. pub const AI_HANDSHAKE_TIMEOUT_SECS: u64 = 10; +/// The only REST paths an AI service may read over the bridge — deny-by-default, +/// matched segment-wise by [`crate::ai::api`] with `{x}` standing for exactly +/// one segment. This list *is* the services' access scope, so it is a service +/// contract documented in `README.md`, not a tunable published at `/limits` +/// (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 +/// (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] = &[ + "/auth/me", + "/users/me/profile", + "/users/{id}/profile", + "/notes", + "/notes/{id}", + "/homework", + "/homework/{id}", + "/homework/{id}/result", + "/homework/{id}/submission", + "/homework/report/{user}", + "/marks/me", + "/marks/{user}", + "/attendance/me", + "/attendance/{user}", + "/pomodoro/me", + "/pomodoro/{user}", +]; + // --- rate limiting ----------------------------------------------------- /// Default requests-per-minute-per-IP for `/auth/login` + `/auth/register`. diff --git a/tests/integration.rs b/tests/integration.rs index 4015e28..45f61c1 100644 --- a/tests/integration.rs +++ b/tests/integration.rs @@ -430,6 +430,30 @@ async fn protected_routes_require_session() { ); } +/// The AI allowlist is a hand-kept list of router paths, so it can only drift +/// one way: a route is renamed and every entry naming it silently stops +/// matching, leaving the AI services with a scope that quietly shrank. Pinning +/// each entry to a `GET` in the emitted document makes the rename break here +/// instead of out there. +#[tokio::test] +async fn ai_allowlist_entries_are_real_get_routes() { + let app = mem_app().await; + let spec = send(&app, "GET", "/api-docs/openapi.json", None, None) + .await + .body; + let paths = spec["paths"].as_object().expect("spec has paths"); + + for entry in hezarfen_backend::constant::AI_API_ALLOWLIST { + let item = paths + .get(*entry) + .unwrap_or_else(|| panic!("allowlisted {entry} is not a path in the OpenAPI document")); + assert!( + item.get("get").is_some(), + "allowlisted {entry} exists but serves no GET" + ); + } +} + #[tokio::test] async fn garbage_cookie_is_unauthorized() { let app = mem_app().await; diff --git a/tests/limits_completeness.rs b/tests/limits_completeness.rs index 3d13f6b..b054896 100644 --- a/tests/limits_completeness.rs +++ b/tests/limits_completeness.rs @@ -102,6 +102,11 @@ const EXCLUDED: &[(&str, &str)] = &[ ("AI_IDLE_TIMEOUT_SECS", "QUIC connection idle timeout"), ("AI_KEEPALIVE_SECS", "QUIC connection keepalive"), ("AI_HANDSHAKE_TIMEOUT_SECS", "AI service handshake deadline"), + ( + "AI_API_ALLOWLIST", + "the AI services' read scope; a service contract in README, and \ + publishing it would hand every browser the map", + ), ( "AI_CHAT_CAPABILITY", "capability string an AI service declares",