Skip to main content

graphd_engine/
sandbox.rs

1//! Statement-level sandboxing for multi-tenant graph databases.
2//!
3//! Uses keyword-based query text analysis to block dangerous operations.
4//! Prevents filesystem I/O, cross-tenant escape, and extension loading.
5
6use std::collections::HashSet;
7
8use crate::error::GraphdError;
9
10/// Configuration for statement-level sandboxing.
11pub struct SandboxConfig {
12    allowed_call_options: HashSet<String>,
13}
14
15impl SandboxConfig {
16    /// Create a sandbox config suitable for multi-tenant environments.
17    ///
18    /// Blocks: COPY FROM/TO, EXPORT/IMPORT/ATTACH/DETACH DATABASE, LOAD EXTENSION.
19    /// Filters: CALL statements by option name allowlist.
20    /// Allows: Everything else (MATCH, CREATE, DROP, ALTER, EXPLAIN, etc.).
21    pub fn multi_tenant() -> Self {
22        let allowed_call_options: HashSet<String> = [
23            "timeout",
24            "threads",
25            "warning_limit",
26            "progress_bar",
27            "var_length_extend_max_depth",
28            "recursive_pattern_semantic",
29            "recursive_pattern_factor",
30            // FTS (full-text search) — safe, operate on tenant's own tables.
31            "create_fts_index",
32            "query_fts_index",
33            "drop_fts_index",
34            "fts_query",
35            // Vector (HNSW index) — safe, operate on tenant's own tables.
36            "create_vector_index",
37            "query_vector_index",
38            "drop_vector_index",
39            // Algo (graph algorithms) — safe, read-only on tenant's own tables.
40            "strongly_connected_components",
41            "scc",
42            "strongly_connected_components_kosaraju",
43            "scc_ko",
44            "weakly_connected_components",
45            "wcc",
46            "page_rank",
47            "pr",
48            "k_core_decomposition",
49            "kcore",
50            "louvain",
51            "spanning_forest",
52            "sf",
53        ]
54        .iter()
55        .map(|s| s.to_string())
56        .collect();
57
58        Self {
59            allowed_call_options,
60        }
61    }
62
63    /// Check whether a query is allowed by the sandbox.
64    ///
65    /// Analyzes query keywords to block dangerous operations.
66    /// Returns `Ok(())` if allowed, `Err(message)` if blocked.
67    pub fn check_query(&self, _conn: &lbug::Connection<'_>, query: &str) -> Result<(), GraphdError> {
68        self.check_query_text(query)
69    }
70
71    /// Check query text without needing a connection (for testing).
72    pub fn check_query_text(&self, query: &str) -> Result<(), GraphdError> {
73        let normalized = query.trim();
74        if normalized.is_empty() {
75            return Ok(());
76        }
77
78        let upper = normalized.to_uppercase();
79        let tokens = first_tokens(&upper, 3);
80
81        // Block all COPY statements (COPY FROM / COPY TO)
82        if tokens.first().map_or(false, |t| t == "COPY") {
83            return Err(GraphdError::Forbidden("COPY is blocked in multi-tenant mode".into()));
84        }
85
86        // Block EXPORT DATABASE / IMPORT DATABASE
87        if tokens.first().map_or(false, |t| t == "EXPORT" || t == "IMPORT") {
88            return Err(GraphdError::Forbidden(format!(
89                "{} is blocked in multi-tenant mode",
90                tokens[0]
91            )));
92        }
93
94        // Block ATTACH / DETACH
95        if tokens.first().map_or(false, |t| t == "ATTACH" || t == "DETACH") {
96            return Err(GraphdError::Forbidden(format!(
97                "{} is blocked in multi-tenant mode",
98                tokens[0]
99            )));
100        }
101
102        // Block USE DATABASE (but allow USE GRAPH)
103        if tokens.first().map_or(false, |t| t == "USE") {
104            if tokens.get(1).map_or(false, |t| t != "GRAPH") {
105                return Err(GraphdError::Forbidden("USE DATABASE is blocked in multi-tenant mode".into()));
106            }
107        }
108
109        // Block LOAD EXTENSION / INSTALL
110        if tokens.first().map_or(false, |t| t == "LOAD" || t == "INSTALL") {
111            return Err(GraphdError::Forbidden(format!(
112                "{} is blocked in multi-tenant mode",
113                tokens[0]
114            )));
115        }
116
117        // Filter CALL statements by option name
118        if tokens.first().map_or(false, |t| t == "CALL") {
119            return self.check_call_statement(query);
120        }
121
122        Ok(())
123    }
124
125    /// Check a CALL statement by parsing the option name from the query.
126    fn check_call_statement(&self, query: &str) -> Result<(), GraphdError> {
127        let trimmed = query.trim();
128        let after_call = if let Some(rest) = strip_prefix_ci(trimmed, "CALL") {
129            rest.trim_start()
130        } else {
131            return Err(GraphdError::Forbidden("Expected CALL statement".into()));
132        };
133
134        let option_name: String = after_call
135            .chars()
136            .take_while(|c| c.is_alphanumeric() || *c == '_')
137            .collect();
138
139        if option_name.is_empty() {
140            return Err(GraphdError::Forbidden(
141                "Could not parse option name from CALL statement".into(),
142            ));
143        }
144
145        let option_lower = option_name.to_lowercase();
146        if self.allowed_call_options.contains(&option_lower) {
147            Ok(())
148        } else {
149            Err(GraphdError::Forbidden(format!(
150                "CALL option '{}' is not allowed in multi-tenant mode",
151                option_name
152            )))
153        }
154    }
155}
156
157/// Extract the first N whitespace-separated tokens from a string.
158fn first_tokens(s: &str, n: usize) -> Vec<String> {
159    s.split_whitespace().take(n).map(String::from).collect()
160}
161
162/// Case-insensitive prefix strip.
163fn strip_prefix_ci<'a>(s: &'a str, prefix: &str) -> Option<&'a str> {
164    if s.len() >= prefix.len() && s[..prefix.len()].eq_ignore_ascii_case(prefix) {
165        Some(&s[prefix.len()..])
166    } else {
167        None
168    }
169}
170
171#[cfg(test)]
172mod tests {
173    use super::*;
174
175    fn sandbox() -> SandboxConfig {
176        SandboxConfig::multi_tenant()
177    }
178
179    // === Allowed queries ===
180
181    #[test]
182    fn allows_match() {
183        assert!(sandbox().check_query_text("MATCH (n) RETURN n").is_ok());
184    }
185
186    #[test]
187    fn allows_create_node_table() {
188        assert!(sandbox()
189            .check_query_text("CREATE NODE TABLE Person(name STRING, PRIMARY KEY(name))")
190            .is_ok());
191    }
192
193    #[test]
194    fn allows_create_rel_table() {
195        assert!(sandbox()
196            .check_query_text("CREATE REL TABLE Knows(FROM Person TO Person)")
197            .is_ok());
198    }
199
200    #[test]
201    fn allows_create_node() {
202        assert!(sandbox()
203            .check_query_text("CREATE (:Person {name: 'Alice'})")
204            .is_ok());
205    }
206
207    #[test]
208    fn allows_drop() {
209        assert!(sandbox().check_query_text("DROP TABLE Person").is_ok());
210    }
211
212    #[test]
213    fn allows_alter() {
214        assert!(sandbox()
215            .check_query_text("ALTER TABLE Person ADD age INT64")
216            .is_ok());
217    }
218
219    #[test]
220    fn allows_explain() {
221        assert!(sandbox()
222            .check_query_text("EXPLAIN MATCH (n) RETURN n")
223            .is_ok());
224    }
225
226    #[test]
227    fn allows_return() {
228        assert!(sandbox().check_query_text("RETURN 1 + 2").is_ok());
229    }
230
231    #[test]
232    fn allows_use_graph() {
233        assert!(sandbox().check_query_text("USE GRAPH my_graph").is_ok());
234    }
235
236    // === Blocked queries ===
237
238    #[test]
239    fn blocks_copy_from() {
240        assert!(sandbox()
241            .check_query_text("COPY Person FROM '/etc/passwd'")
242            .is_err());
243    }
244
245    #[test]
246    fn blocks_copy_to() {
247        assert!(sandbox()
248            .check_query_text("COPY (MATCH (n) RETURN n) TO '/tmp/data.csv'")
249            .is_err());
250    }
251
252    #[test]
253    fn blocks_export_database() {
254        assert!(sandbox()
255            .check_query_text("EXPORT DATABASE '/tmp/export'")
256            .is_err());
257    }
258
259    #[test]
260    fn blocks_import_database() {
261        assert!(sandbox()
262            .check_query_text("IMPORT DATABASE '/tmp/import'")
263            .is_err());
264    }
265
266    #[test]
267    fn blocks_attach() {
268        assert!(sandbox()
269            .check_query_text("ATTACH '/tmp/other.db' AS other")
270            .is_err());
271    }
272
273    #[test]
274    fn blocks_detach() {
275        assert!(sandbox().check_query_text("DETACH other").is_err());
276    }
277
278    #[test]
279    fn blocks_use_database() {
280        assert!(sandbox().check_query_text("USE other_db").is_err());
281    }
282
283    #[test]
284    fn blocks_load_extension() {
285        assert!(sandbox()
286            .check_query_text("LOAD EXTENSION httpfs")
287            .is_err());
288    }
289
290    #[test]
291    fn blocks_install() {
292        assert!(sandbox().check_query_text("INSTALL httpfs").is_err());
293    }
294
295    // === CALL filtering ===
296
297    #[test]
298    fn call_option_allowed() {
299        let sb = sandbox();
300        assert!(sb.check_query_text("CALL timeout = 5000").is_ok());
301        assert!(sb.check_query_text("CALL threads = 2").is_ok());
302        assert!(sb.check_query_text("CALL warning_limit = 100").is_ok());
303    }
304
305    #[test]
306    fn call_option_blocked() {
307        let sb = sandbox();
308        assert!(sb.check_query_text("CALL home_directory = '/tmp'").is_err());
309        assert!(sb.check_query_text("CALL file_search_path = '/etc'").is_err());
310        assert!(sb.check_query_text("CALL auto_checkpoint = false").is_err());
311        assert!(sb.check_query_text("CALL enable_multi_writes = true").is_err());
312    }
313
314    #[test]
315    fn call_case_insensitive() {
316        let sb = sandbox();
317        assert!(sb.check_query_text("CALL Timeout = 5000").is_ok());
318        assert!(sb.check_query_text("CALL THREADS = 2").is_ok());
319    }
320
321    // === FTS calls ===
322
323    #[test]
324    fn call_fts_allowed() {
325        let sb = sandbox();
326        assert!(sb.check_query_text("CALL CREATE_FTS_INDEX('Entity', 'idx', 'name')").is_ok());
327        assert!(sb.check_query_text("CALL QUERY_FTS_INDEX('Entity', 'idx', 'search')").is_ok());
328        assert!(sb.check_query_text("CALL DROP_FTS_INDEX('Entity', 'idx')").is_ok());
329        assert!(sb.check_query_text("CALL FTS_QUERY('idx', 'search')").is_ok());
330    }
331
332    // === Vector calls ===
333
334    #[test]
335    fn call_vector_allowed() {
336        let sb = sandbox();
337        assert!(sb.check_query_text("CALL CREATE_VECTOR_INDEX('Entity', 'idx', 'embedding')").is_ok());
338        assert!(sb.check_query_text("CALL QUERY_VECTOR_INDEX('Entity', 'idx', $vec, TOP := 10)").is_ok());
339        assert!(sb.check_query_text("CALL DROP_VECTOR_INDEX('Entity', 'idx')").is_ok());
340    }
341
342    // === Algo calls ===
343
344    #[test]
345    fn call_algo_allowed() {
346        let sb = sandbox();
347        assert!(sb.check_query_text("CALL WEAKLY_CONNECTED_COMPONENTS('Person', 'Knows')").is_ok());
348        assert!(sb.check_query_text("CALL WCC('Person', 'Knows')").is_ok());
349        assert!(sb.check_query_text("CALL PAGE_RANK('Person', 'Knows')").is_ok());
350        assert!(sb.check_query_text("CALL PR('Person', 'Knows')").is_ok());
351        assert!(sb.check_query_text("CALL STRONGLY_CONNECTED_COMPONENTS('Person', 'Knows')").is_ok());
352        assert!(sb.check_query_text("CALL SCC('Person', 'Knows')").is_ok());
353        assert!(sb.check_query_text("CALL LOUVAIN('Person', 'Knows')").is_ok());
354        assert!(sb.check_query_text("CALL K_CORE_DECOMPOSITION('Person', 'Knows')").is_ok());
355        assert!(sb.check_query_text("CALL KCORE('Person', 'Knows')").is_ok());
356        assert!(sb.check_query_text("CALL SPANNING_FOREST('Person', 'Knows')").is_ok());
357        assert!(sb.check_query_text("CALL SF('Person', 'Knows')").is_ok());
358    }
359
360    // === Edge cases ===
361
362    #[test]
363    fn case_insensitive_blocks() {
364        assert!(sandbox().check_query_text("copy Person FROM '/etc/passwd'").is_err());
365        assert!(sandbox().check_query_text("EXPORT database '/tmp'").is_err());
366        assert!(sandbox().check_query_text("attach '/tmp/db'").is_err());
367    }
368
369    #[test]
370    fn empty_query_allowed() {
371        assert!(sandbox().check_query_text("").is_ok());
372        assert!(sandbox().check_query_text("   ").is_ok());
373    }
374}