From 4195374c230ded7bbe59ed786965c7d545cbfc17 Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 16:22:14 +0100 Subject: [PATCH] fix(mcp): harden stdio opens, commits and user-supplied ranges - Check per call that synapse.db exists and is on this binary's schema, so the stdio server never migrates or re-stamps the app's live database. - Keep the transaction open (rolled back on drop) when COMMIT fails. - Reject dates outside years 1000-9999 and oversized cursors (overflow). - core: export SCHEMA_VERSION. Co-Authored-By: Claude Opus 5.5 --- crates/synapse-core/src/lib.rs | 1 + crates/synapse-mcp/src/lib.rs | 47 +++++++++++++++++++++++++++++-- crates/synapse-mcp/src/tools.rs | 13 +++++++-- crates/synapse-mcp/tests/stdio.rs | 33 ++++++++++++++++++++++ crates/synapse-mcp/tests/tools.rs | 25 ++++++++++++++++ 5 files changed, 115 insertions(+), 4 deletions(-) diff --git a/crates/synapse-core/src/lib.rs b/crates/synapse-core/src/lib.rs index 77d1947..afb0185 100644 --- a/crates/synapse-core/src/lib.rs +++ b/crates/synapse-core/src/lib.rs @@ -20,6 +20,7 @@ pub mod types; pub use error::{Error, Result}; pub use model::*; +pub use schema::VERSION as SCHEMA_VERSION; pub use store::Graph; pub use structure::{ HubConversion, HubInfo, HubPreview, Structure, is_legacy_page, namespace_parent, diff --git a/crates/synapse-mcp/src/lib.rs b/crates/synapse-mcp/src/lib.rs index 75cbe22..a1fa86e 100644 --- a/crates/synapse-mcp/src/lib.rs +++ b/crates/synapse-mcp/src/lib.rs @@ -75,7 +75,7 @@ impl GraphHost for LocalHost { let dir = self.dir.clone(); Box::pin(async move { tokio::task::spawn_blocking(move || { - let g = Graph::open(&dir).map_err(ToolError::from)?; + let g = open_local(&dir)?; job(&g) }) .await @@ -84,6 +84,48 @@ impl GraphHost for LocalHost { } } +/// Opens the app's graph without surprises: it must still exist (never re-created) and be +/// on this binary's schema (`Graph::open` would migrate or re-stamp a live database). +fn open_local(dir: &std::path::Path) -> Result { + let db = dir.join("synapse.db"); + if !db.is_file() { + return Err(ToolError::new(format!("graph {} is gone", dir.display()))); + } + let schema: Option = { + let conn = rusqlite::Connection::open_with_flags( + &db, + rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY | rusqlite::OpenFlags::SQLITE_OPEN_NO_MUTEX, + )?; + conn.busy_timeout(std::time::Duration::from_secs(5))?; + conn.query_row("SELECT value FROM meta WHERE key='schema'", [], |r| { + r.get::<_, String>(0) + }) + .ok() + }; + let want = synapse_core::SCHEMA_VERSION.to_string(); + if schema.as_deref() != Some(want.as_str()) { + return Err(ToolError::new(format!( + "graph schema is v{} but this synapse-mcp expects v{want}; use a synapse-mcp built \ + from the same version as the app", + schema.as_deref().unwrap_or("?") + ))); + } + with_retry_open(|| Graph::open(dir).map_err(ToolError::from)) +} + +fn with_retry_open(f: impl Fn() -> Result) -> Result { + let mut attempt = 0; + loop { + match f() { + Err(e) if e.busy && attempt < BUSY_RETRIES => { + attempt += 1; + std::thread::sleep(std::time::Duration::from_millis(200 * attempt as u64)); + } + other => return other, + } + } +} + /// Rolls back on drop unless committed. struct Txn<'a> { g: &'a Graph, @@ -96,8 +138,9 @@ impl<'a> Txn<'a> { Ok(Self { g, open: true }) } fn commit(mut self) -> Result<(), ToolError> { - self.open = false; + // On failure `open` stays true and Drop rolls back, so no transaction leaks. self.g.conn().execute_batch("COMMIT")?; + self.open = false; Ok(()) } } diff --git a/crates/synapse-mcp/src/tools.rs b/crates/synapse-mcp/src/tools.rs index 37827f8..f4a1d3b 100644 --- a/crates/synapse-mcp/src/tools.rs +++ b/crates/synapse-mcp/src/tools.rs @@ -69,6 +69,8 @@ impl From for ToolError { pub type ToolResult = Result; const MAX_RANGE_DAYS: i64 = 31; +/// Cursors are offsets; capped so offset arithmetic cannot overflow. +const MAX_CURSOR: usize = 1 << 32; const MAX_TIMELINE_DAYS: i64 = 92; // ------------------------------------------------------------------ helpers @@ -98,7 +100,10 @@ pub fn parse_date(g: &Graph, s: &str) -> Result { "yesterday" => Ok(today - Duration::days(1)), "tomorrow" => Ok(today + Duration::days(1)), _ => NaiveDate::parse_from_str(s, "%Y-%m-%d") - .map_err(|_| err(format!("bad date {s:?}: use YYYY-MM-DD or \"today\""))), + .ok() + // Sane years only: date arithmetic near chrono's limits would overflow. + .filter(|d| (1000..=9999).contains(&chrono::Datelike::year(d))) + .ok_or_else(|| err(format!("bad date {s:?}: use YYYY-MM-DD or \"today\""))), } } @@ -131,7 +136,11 @@ fn date_range( fn parse_cursor(c: &Option) -> Result { match c.as_deref().map(str::trim).filter(|c| !c.is_empty()) { None => Ok(0), - Some(c) => c.parse().map_err(|_| err(format!("bad cursor {c:?}"))), + Some(c) => c + .parse::() + .ok() + .filter(|n| *n <= MAX_CURSOR) + .ok_or_else(|| err(format!("bad cursor {c:?}"))), } } diff --git a/crates/synapse-mcp/tests/stdio.rs b/crates/synapse-mcp/tests/stdio.rs index 87b8c30..07614b4 100644 --- a/crates/synapse-mcp/tests/stdio.rs +++ b/crates/synapse-mcp/tests/stdio.rs @@ -161,3 +161,36 @@ fn refuses_a_missing_graph() { assert!(!out.status.success()); assert!(!dir.path().join("nope").exists(), "must not create a graph"); } + +#[test] +fn refuses_a_graph_on_another_schema() { + let dir = tempfile::tempdir().unwrap(); + { + let g = Graph::open(dir.path()).unwrap(); + g.conn() + .execute("UPDATE meta SET value='1' WHERE key='schema'", []) + .unwrap(); + } + let mut s = Server::start(dir.path(), &[]); + s.init(); + let r = s.call( + 2, + "tools/call", + json!({"name": "list_pages", "arguments": {}}), + ); + let text = r["result"]["content"][0]["text"].as_str().unwrap(); + assert!(text.contains("schema is v1"), "{r}"); + drop(s); + let g = Graph::open(dir.path()).unwrap(); + let v: String = g + .conn() + .query_row("SELECT value FROM meta WHERE key='schema'", [], |r| { + r.get(0) + }) + .unwrap(); + assert_eq!( + v, + synapse_core::SCHEMA_VERSION.to_string(), + "re-opened by core only here" + ); +} diff --git a/crates/synapse-mcp/tests/tools.rs b/crates/synapse-mcp/tests/tools.rs index d755dc9..a721fc7 100644 --- a/crates/synapse-mcp/tests/tools.rs +++ b/crates/synapse-mcp/tests/tools.rs @@ -620,3 +620,28 @@ fn resources_render_pages() { let out = read(&g, |g| tools::page_resource(g, "Dune")); assert!(out.contains("- Arrakis is a desert planet\n"), "{out}"); } + +#[test] +fn extreme_dates_and_cursors_are_rejected() { + let (_d, g) = fixture(); + let e = read_err(&g, |g| { + tools::timeline( + g, + &RangeParams { + from: None, + to: Some("-262143-01-03".into()), + }, + ) + }); + assert!(e.contains("bad date"), "{e}"); + let e = read_err(&g, |g| { + tools::list_pages( + g, + &ListPagesParams { + cursor: Some(usize::MAX.to_string()), + ..Default::default() + }, + ) + }); + assert!(e.contains("bad cursor"), "{e}"); +}