forge
Explore
Log in

Don't you dare go Hollow

Allowlist the GET paths ai services may read

Browse files at this commit

317ef9c3590a86675d3d7f2c6d61d3c7906f5e93Ahmet Kaan GümüşParent: 3a01d26
  • feat
    • allowlist the GET paths ai services may read
Show full message
🤖 feat: allowlist the GET paths ai services may read

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.rsadded+106 -0
@@ -0,0 +1,106 @@
1+//! Which REST paths an AI service may read.
2+//!
3+//! Deny-by-default: a request the bridge dispatches into the router has to
4+//! match one of [`AI_API_ALLOWLIST`]'s patterns exactly, segment for segment.
5+//! There is no prefix match and no wildcard tail — `/notes` never admits
6+//! `/notes/{id}/files/{file_id}` — so a new route family is unreachable to the
7+//! services until somebody adds it to the list on purpose.
8+//!
9+//! Pure path logic, deliberately independent of the rest of `ai`: it is the
10+//! access scope, and a scope that needed a connection to evaluate would be
11+//! harder to test than to bypass.
12+
13+use crate::constant::AI_API_ALLOWLIST;
14+
15+/// Whether an AI service may `GET` this path.
16+///
17+/// The path is the router path alone: a query string travels in its own frame
18+/// field, so a `?` here means the caller built the request wrong and the
19+/// request is refused rather than silently matched on its prefix.
20+pub fn path_allowed(path: &str) -> bool {
21+ if !path.starts_with('/') || path.contains('?') {
22+ return false;
23+ }
24+ AI_API_ALLOWLIST
25+ .iter()
26+ .any(|pattern| pattern_matches(pattern, path))
27+}
28+
29+/// One `/`-separated pattern against one path. A literal segment must be
30+/// equal; a `{name}` placeholder takes exactly one non-empty segment.
31+fn pattern_matches(pattern: &str, path: &str) -> bool {
32+ let mut expected = pattern[1..].split('/');
33+ let mut actual = path[1..].split('/');
34+ loop {
35+ match (expected.next(), actual.next()) {
36+ (None, None) => return true,
37+ (Some(segment), Some(given)) => {
38+ let ok = if segment.starts_with('{') && segment.ends_with('}') {
39+ !given.is_empty()
40+ } else {
41+ segment == given
42+ };
43+ if !ok {
44+ return false;
45+ }
46+ }
47+ // Different segment counts: a trailing slash or a deeper path is a
48+ // different route, never a longer match of this one.
49+ _ => return false,
50+ }
51+ }
52+}
53+
54+#[cfg(test)]
55+mod tests {
56+ use super::*;
57+
58+ #[test]
59+ fn literal_path_matches_exactly() {
60+ assert!(path_allowed("/auth/me"));
61+ assert!(path_allowed("/notes"));
62+ assert!(!path_allowed("/auth/m"));
63+ assert!(!path_allowed("/AUTH/ME"));
64+ }
65+
66+ #[test]
67+ fn placeholder_takes_one_segment() {
68+ assert!(path_allowed("/notes/note123"));
69+ assert!(path_allowed("/users/user456/profile"));
70+ // A placeholder is one segment, not a tail.
71+ assert!(!path_allowed("/notes/note123/files"));
72+ assert!(!path_allowed("/notes/note123/files/f1"));
73+ }
74+
75+ #[test]
76+ fn trailing_slash_is_a_different_path() {
77+ assert!(!path_allowed("/notes/"));
78+ assert!(!path_allowed("/auth/me/"));
79+ assert!(!path_allowed("/notes/note123/"));
80+ }
81+
82+ #[test]
83+ fn empty_segments_never_fill_a_placeholder() {
84+ assert!(!path_allowed("/notes//"));
85+ assert!(!path_allowed("//notes"));
86+ assert!(!path_allowed("/users//profile"));
87+ }
88+
89+ #[test]
90+ fn query_string_is_refused() {
91+ assert!(!path_allowed("/notes?limit=10"));
92+ assert!(!path_allowed("/notes/note123?x=1"));
93+ }
94+
95+ #[test]
96+ fn unlisted_and_malformed_paths_are_denied() {
97+ assert!(!path_allowed(""));
98+ assert!(!path_allowed("notes"));
99+ assert!(!path_allowed("/"));
100+ // Real routes that are deliberately out of scope.
101+ assert!(!path_allowed("/users"));
102+ assert!(!path_allowed("/users/user456/avatar"));
103+ assert!(!path_allowed("/settings"));
104+ assert!(!path_allowed("/exams"));
105+ }
106+}
src/ai/mod.rsmodified+2 -0
@@ -11,6 +11,7 @@
11 //! no head-of-line blocking — a 30-second inference on stream 7 does not delay11 //! no head-of-line blocking — a 30-second inference on stream 7 does not delay
12 //! the answer on stream 9. Connection setup happens once, not per request.12 //! the answer on stream 9. Connection setup happens once, not per request.
13 //!13 //!
14+//! * [`api`] — which REST paths a service may read back through the bridge
14 //! * [`protocol`] — frames on the wire15 //! * [`protocol`] — frames on the wire
15 //! * [`chat`] — the JSON payloads carried for the `chat.reply` capability16 //! * [`chat`] — the JSON payloads carried for the `chat.reply` capability
16 //! * [`server`] — the listener, handshake, and [`server::AiBridge::dispatch`]17 //! * [`server`] — the listener, handshake, and [`server::AiBridge::dispatch`]
@@ -20,6 +21,7 @@
20 //! The transport is generic; the features land on top of it. So far that is21 //! The transport is generic; the features land on top of it. So far that is
21 //! the chatbot (`web::chatbot`), which routes on the `chat.reply` capability.22 //! the chatbot (`web::chatbot`), which routes on the `chat.reply` capability.
22 23
24+pub mod api;
23 pub mod chat;25 pub mod chat;
24 pub mod error;26 pub mod error;
25 pub mod protocol;27 pub mod protocol;
src/constant.rsmodified+29 -0
@@ -600,6 +600,35 @@ pub const AI_MAX_REQUEST_TIMEOUT_SECS: u64 = 60;
600 /// occupy the listener indefinitely.600 /// occupy the listener indefinitely.
601 pub const AI_HANDSHAKE_TIMEOUT_SECS: u64 = 10;601 pub const AI_HANDSHAKE_TIMEOUT_SECS: u64 = 10;
602 602
603+/// The only REST paths an AI service may read over the bridge — deny-by-default,
604+/// matched segment-wise by [`crate::ai::api`] with `{x}` standing for exactly
605+/// one segment. This list *is* the services' access scope, so it is a service
606+/// contract documented in `README.md`, not a tunable published at `/limits`
607+/// (string arrays are exempt from that completeness gate).
608+///
609+/// JSON-only, and only what a study-companion needs: who the user is, their
610+/// notes, their homework, and their own progress reports. Byte-serving routes
611+/// (note files, submission files, avatars, question images) are left out — the
612+/// frames carry JSON, and a blob has no business crossing this seam yet.
613+pub const AI_API_ALLOWLIST: &[&str] = &[
614+ "/auth/me",
615+ "/users/me/profile",
616+ "/users/{id}/profile",
617+ "/notes",
618+ "/notes/{id}",
619+ "/homework",
620+ "/homework/{id}",
621+ "/homework/{id}/result",
622+ "/homework/{id}/submission",
623+ "/homework/report/{user}",
624+ "/marks/me",
625+ "/marks/{user}",
626+ "/attendance/me",
627+ "/attendance/{user}",
628+ "/pomodoro/me",
629+ "/pomodoro/{user}",
630+];
631+
603 // --- rate limiting -----------------------------------------------------632 // --- rate limiting -----------------------------------------------------
604 633
605 /// Default requests-per-minute-per-IP for `/auth/login` + `/auth/register`.634 /// Default requests-per-minute-per-IP for `/auth/login` + `/auth/register`.
tests/integration.rsmodified+24 -0
@@ -430,6 +430,30 @@ async fn protected_routes_require_session() {
430 );430 );
431 }431 }
432 432
433+/// The AI allowlist is a hand-kept list of router paths, so it can only drift
434+/// one way: a route is renamed and every entry naming it silently stops
435+/// matching, leaving the AI services with a scope that quietly shrank. Pinning
436+/// each entry to a `GET` in the emitted document makes the rename break here
437+/// instead of out there.
438+#[tokio::test]
439+async fn ai_allowlist_entries_are_real_get_routes() {
440+ let app = mem_app().await;
441+ let spec = send(&app, "GET", "/api-docs/openapi.json", None, None)
442+ .await
443+ .body;
444+ let paths = spec["paths"].as_object().expect("spec has paths");
445+
446+ for entry in hezarfen_backend::constant::AI_API_ALLOWLIST {
447+ let item = paths
448+ .get(*entry)
449+ .unwrap_or_else(|| panic!("allowlisted {entry} is not a path in the OpenAPI document"));
450+ assert!(
451+ item.get("get").is_some(),
452+ "allowlisted {entry} exists but serves no GET"
453+ );
454+ }
455+}
456+
433 #[tokio::test]457 #[tokio::test]
434 async fn garbage_cookie_is_unauthorized() {458 async fn garbage_cookie_is_unauthorized() {
435 let app = mem_app().await;459 let app = mem_app().await;
tests/limits_completeness.rsmodified+5 -0
@@ -102,6 +102,11 @@ const EXCLUDED: &[(&str, &str)] = &[
102 ("AI_IDLE_TIMEOUT_SECS", "QUIC connection idle timeout"),102 ("AI_IDLE_TIMEOUT_SECS", "QUIC connection idle timeout"),
103 ("AI_KEEPALIVE_SECS", "QUIC connection keepalive"),103 ("AI_KEEPALIVE_SECS", "QUIC connection keepalive"),
104 ("AI_HANDSHAKE_TIMEOUT_SECS", "AI service handshake deadline"),104 ("AI_HANDSHAKE_TIMEOUT_SECS", "AI service handshake deadline"),
105+ (
106+ "AI_API_ALLOWLIST",
107+ "the AI services' read scope; a service contract in README, and \
108+ publishing it would hand every browser the map",
109+ ),
105 (110 (
106 "AI_CHAT_CAPABILITY",111 "AI_CHAT_CAPABILITY",
107 "capability string an AI service declares",112 "capability string an AI service declares",