Skip to main content

mixtape_tools/sqlite/
configured.rs

1//! Configured tool wrappers with permission support
2//!
3//! This module provides wrapper tools that enforce database path and table
4//! permission restrictions configured at tool creation time.
5
6use crate::prelude::*;
7use crate::sqlite::config::SqliteConfig;
8use crate::sqlite::error::SqliteToolError;
9use crate::sqlite::query::{
10    BulkInsertInput, BulkInsertTool, ReadQueryInput, ReadQueryTool, SchemaQueryInput,
11    SchemaQueryTool, WriteQueryInput, WriteQueryTool,
12};
13use crate::sqlite::sql_parser::extract_table_operations;
14use std::sync::Arc;
15
16/// Validate query permissions against the configuration
17fn validate_query(config: &SqliteConfig, sql: &str) -> Result<(), SqliteToolError> {
18    let ops =
19        extract_table_operations(sql).map_err(|e| SqliteToolError::InvalidQuery(e.to_string()))?;
20
21    // Check read permissions
22    for table in &ops.read {
23        if !config.can_read(table) {
24            return Err(SqliteToolError::PermissionDenied {
25                operation: "read".to_string(),
26                table: table.clone(),
27            });
28        }
29    }
30
31    // Check write permissions
32    for table in &ops.write {
33        if !config.can_write(table) {
34            return Err(SqliteToolError::PermissionDenied {
35                operation: "write".to_string(),
36                table: table.clone(),
37            });
38        }
39    }
40
41    Ok(())
42}
43
44/// A ReadQueryTool with permission configuration
45pub struct ConfiguredReadQueryTool {
46    config: Arc<SqliteConfig>,
47    inner: ReadQueryTool,
48}
49
50impl ConfiguredReadQueryTool {
51    /// Create a new configured read query tool
52    pub fn new(config: SqliteConfig) -> Self {
53        Self {
54            config: Arc::new(config),
55            inner: ReadQueryTool,
56        }
57    }
58
59    /// Create with a shared config (useful when multiple tools share permissions)
60    pub fn with_shared_config(config: Arc<SqliteConfig>) -> Self {
61        Self {
62            config,
63            inner: ReadQueryTool,
64        }
65    }
66}
67
68impl Tool for ConfiguredReadQueryTool {
69    type Input = ReadQueryInput;
70
71    fn name(&self) -> &str {
72        self.inner.name()
73    }
74
75    fn description(&self) -> &str {
76        self.inner.description()
77    }
78
79    async fn execute(&self, mut input: Self::Input) -> Result<ToolResult, ToolError> {
80        input.db_path = self.config.effective_db_path(input.db_path);
81        validate_query(&self.config, &input.query)?;
82        self.inner.execute(input).await
83    }
84}
85
86/// A WriteQueryTool with permission configuration
87pub struct ConfiguredWriteQueryTool {
88    config: Arc<SqliteConfig>,
89    inner: WriteQueryTool,
90}
91
92impl ConfiguredWriteQueryTool {
93    /// Create a new configured write query tool
94    pub fn new(config: SqliteConfig) -> Self {
95        Self {
96            config: Arc::new(config),
97            inner: WriteQueryTool,
98        }
99    }
100
101    /// Create with a shared config
102    pub fn with_shared_config(config: Arc<SqliteConfig>) -> Self {
103        Self {
104            config,
105            inner: WriteQueryTool,
106        }
107    }
108}
109
110impl Tool for ConfiguredWriteQueryTool {
111    type Input = WriteQueryInput;
112
113    fn name(&self) -> &str {
114        self.inner.name()
115    }
116
117    fn description(&self) -> &str {
118        self.inner.description()
119    }
120
121    async fn execute(&self, mut input: Self::Input) -> Result<ToolResult, ToolError> {
122        input.db_path = self.config.effective_db_path(input.db_path);
123        validate_query(&self.config, &input.query)?;
124        self.inner.execute(input).await
125    }
126}
127
128/// A SchemaQueryTool with permission configuration
129pub struct ConfiguredSchemaQueryTool {
130    config: Arc<SqliteConfig>,
131    inner: SchemaQueryTool,
132}
133
134impl ConfiguredSchemaQueryTool {
135    /// Create a new configured schema query tool
136    pub fn new(config: SqliteConfig) -> Self {
137        Self {
138            config: Arc::new(config),
139            inner: SchemaQueryTool,
140        }
141    }
142
143    /// Create with a shared config
144    pub fn with_shared_config(config: Arc<SqliteConfig>) -> Self {
145        Self {
146            config,
147            inner: SchemaQueryTool,
148        }
149    }
150}
151
152impl Tool for ConfiguredSchemaQueryTool {
153    type Input = SchemaQueryInput;
154
155    fn name(&self) -> &str {
156        self.inner.name()
157    }
158
159    fn description(&self) -> &str {
160        self.inner.description()
161    }
162
163    async fn execute(&self, mut input: Self::Input) -> Result<ToolResult, ToolError> {
164        input.db_path = self.config.effective_db_path(input.db_path);
165        validate_query(&self.config, &input.query)?;
166        self.inner.execute(input).await
167    }
168}
169
170/// A BulkInsertTool with permission configuration
171pub struct ConfiguredBulkInsertTool {
172    config: Arc<SqliteConfig>,
173    inner: BulkInsertTool,
174}
175
176impl ConfiguredBulkInsertTool {
177    /// Create a new configured bulk insert tool
178    pub fn new(config: SqliteConfig) -> Self {
179        Self {
180            config: Arc::new(config),
181            inner: BulkInsertTool,
182        }
183    }
184
185    /// Create with a shared config
186    pub fn with_shared_config(config: Arc<SqliteConfig>) -> Self {
187        Self {
188            config,
189            inner: BulkInsertTool,
190        }
191    }
192}
193
194impl Tool for ConfiguredBulkInsertTool {
195    type Input = BulkInsertInput;
196
197    fn name(&self) -> &str {
198        self.inner.name()
199    }
200
201    fn description(&self) -> &str {
202        self.inner.description()
203    }
204
205    async fn execute(&self, mut input: Self::Input) -> Result<ToolResult, ToolError> {
206        input.db_path = self.config.effective_db_path(input.db_path);
207        if !self.config.can_write(&input.table) {
208            return Err(SqliteToolError::PermissionDenied {
209                operation: "write".to_string(),
210                table: input.table.clone(),
211            }
212            .into());
213        }
214        self.inner.execute(input).await
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221    use crate::sqlite::test_utils::TestDatabase;
222
223    #[tokio::test]
224    async fn test_configured_read_tool_allows_permitted_table() {
225        let db = TestDatabase::with_schema(
226            "CREATE TABLE users (id INTEGER, name TEXT);
227             INSERT INTO users VALUES (1, 'Alice');",
228        )
229        .await;
230
231        let config = SqliteConfig::builder()
232            .db_path(db.key())
233            .allow_read(["users"])
234            .build()
235            .unwrap();
236
237        let tool = ConfiguredReadQueryTool::new(config);
238        let result = tool
239            .execute(ReadQueryInput::new("SELECT * FROM users"))
240            .await;
241
242        assert!(result.is_ok());
243    }
244
245    #[tokio::test]
246    async fn test_configured_read_tool_denies_unpermitted_table() {
247        let db = TestDatabase::with_schema(
248            "CREATE TABLE secrets (id INTEGER, data TEXT);
249             INSERT INTO secrets VALUES (1, 'secret data');",
250        )
251        .await;
252
253        let config = SqliteConfig::builder()
254            .db_path(db.key())
255            .allow_read(["users"]) // secrets not in allow list
256            .build()
257            .unwrap();
258
259        let tool = ConfiguredReadQueryTool::new(config);
260        let result = tool
261            .execute(ReadQueryInput::new("SELECT * FROM secrets"))
262            .await;
263
264        assert!(result.is_err());
265        let err_msg = result.unwrap_err().to_string();
266        assert!(err_msg.contains("Permission denied"));
267        assert!(err_msg.contains("secrets"));
268    }
269
270    #[tokio::test]
271    async fn test_configured_write_tool_allows_permitted_table() {
272        let db = TestDatabase::with_schema("CREATE TABLE orders (id INTEGER, amount REAL);").await;
273
274        let config = SqliteConfig::builder()
275            .db_path(db.key())
276            .allow_write(["orders"])
277            .build()
278            .unwrap();
279
280        let tool = ConfiguredWriteQueryTool::new(config);
281        let result = tool
282            .execute(WriteQueryInput {
283                query: "INSERT INTO orders VALUES (1, 99.99)".to_string(),
284                params: vec![],
285                db_path: None,
286            })
287            .await;
288
289        assert!(result.is_ok());
290    }
291
292    #[tokio::test]
293    async fn test_configured_write_tool_denies_unpermitted_table() {
294        let db = TestDatabase::with_schema("CREATE TABLE audit_log (id INTEGER, msg TEXT);").await;
295
296        let config = SqliteConfig::builder()
297            .db_path(db.key())
298            .deny_write(["audit_log"])
299            .build()
300            .unwrap();
301
302        let tool = ConfiguredWriteQueryTool::new(config);
303        let result = tool
304            .execute(WriteQueryInput {
305                query: "INSERT INTO audit_log VALUES (1, 'hacked')".to_string(),
306                params: vec![],
307                db_path: None,
308            })
309            .await;
310
311        assert!(result.is_err());
312        let err_msg = result.unwrap_err().to_string();
313        assert!(err_msg.contains("Permission denied"));
314        assert!(err_msg.contains("audit_log"));
315    }
316
317    #[tokio::test]
318    async fn test_configured_tool_uses_configured_db_path() {
319        let db = TestDatabase::with_schema("CREATE TABLE test (id INTEGER);").await;
320
321        let config = SqliteConfig::builder().db_path(db.key()).build().unwrap();
322
323        let tool = ConfiguredReadQueryTool::new(config);
324
325        // Input provides a different path, but configured path should be used
326        let result = tool
327            .execute(ReadQueryInput::new("SELECT * FROM test").db_path("/nonexistent/path.db"))
328            .await;
329
330        // Should succeed because it uses the configured path, not the input path
331        assert!(result.is_ok());
332    }
333
334    #[tokio::test]
335    async fn test_configured_bulk_insert_checks_permissions() {
336        let db = TestDatabase::with_schema("CREATE TABLE users (id INTEGER, name TEXT);").await;
337
338        let config = SqliteConfig::builder()
339            .db_path(db.key())
340            .deny_write(["users"])
341            .build()
342            .unwrap();
343
344        let tool = ConfiguredBulkInsertTool::new(config);
345        let mut record = serde_json::Map::new();
346        record.insert("id".to_string(), serde_json::json!(1));
347        record.insert("name".to_string(), serde_json::json!("Alice"));
348
349        let result = tool
350            .execute(BulkInsertInput {
351                table: "users".to_string(),
352                data: vec![record],
353                batch_size: 1000,
354                db_path: None,
355            })
356            .await;
357
358        assert!(result.is_err());
359        let err_msg = result.unwrap_err().to_string();
360        assert!(err_msg.contains("Permission denied"));
361    }
362
363    #[tokio::test]
364    async fn test_read_only_config_blocks_all_writes() {
365        let db = TestDatabase::with_schema("CREATE TABLE data (id INTEGER);").await;
366
367        let config = SqliteConfig::builder()
368            .db_path(db.key())
369            .read_only()
370            .build()
371            .unwrap();
372
373        let tool = ConfiguredWriteQueryTool::new(config);
374        let result = tool
375            .execute(WriteQueryInput {
376                query: "INSERT INTO data VALUES (1)".to_string(),
377                params: vec![],
378                db_path: None,
379            })
380            .await;
381
382        assert!(result.is_err());
383    }
384
385    #[tokio::test]
386    async fn test_shared_config_between_tools() {
387        let db = TestDatabase::with_schema(
388            "CREATE TABLE users (id INTEGER, name TEXT);
389             CREATE TABLE orders (id INTEGER, user_id INTEGER);",
390        )
391        .await;
392
393        let config = Arc::new(
394            SqliteConfig::builder()
395                .db_path(db.key())
396                .allow_read(["users", "orders"])
397                .allow_write(["orders"])
398                .build()
399                .unwrap(),
400        );
401
402        let read_tool = ConfiguredReadQueryTool::with_shared_config(config.clone());
403        let write_tool = ConfiguredWriteQueryTool::with_shared_config(config.clone());
404
405        // Read from users should work
406        assert!(read_tool
407            .execute(ReadQueryInput::new("SELECT * FROM users"))
408            .await
409            .is_ok());
410
411        // Write to users should fail
412        assert!(write_tool
413            .execute(WriteQueryInput {
414                query: "INSERT INTO users VALUES (1, 'test')".to_string(),
415                params: vec![],
416                db_path: None,
417            })
418            .await
419            .is_err());
420
421        // Write to orders should work
422        assert!(write_tool
423            .execute(WriteQueryInput {
424                query: "INSERT INTO orders VALUES (1, 1)".to_string(),
425                params: vec![],
426                db_path: None,
427            })
428            .await
429            .is_ok());
430    }
431}