Skip to main content

mixtape_tools/sqlite/
config.rs

1//! Configuration types for SQLite tool permissions
2//!
3//! This module provides configuration for restricting SQLite tool access
4//! to specific databases and tables.
5
6use std::collections::HashSet;
7use thiserror::Error;
8
9/// Errors that can occur when building a [`SqliteConfig`].
10#[derive(Debug, Error)]
11pub enum ConfigError {
12    /// An empty deny list was specified, which allows all tables.
13    /// Use [`TablePermissionMode::AllowAll`] instead.
14    #[error(
15        "empty deny list for {operation} permissions allows all tables - use AllowAll or omit"
16    )]
17    EmptyDenyList {
18        /// Whether this was for "read" or "write" permissions
19        operation: &'static str,
20    },
21}
22
23/// Table permission mode - either allow specific tables or deny specific tables
24#[derive(Debug, Clone, Default)]
25pub enum TablePermissionMode {
26    /// Allow all tables (default behavior)
27    #[default]
28    AllowAll,
29    /// Only allow access to specified tables
30    AllowList(HashSet<String>),
31    /// Deny access to specified tables, allow all others
32    DenyList(HashSet<String>),
33}
34
35impl TablePermissionMode {
36    /// Check if access to a table is allowed
37    pub fn is_allowed(&self, table: &str) -> bool {
38        match self {
39            TablePermissionMode::AllowAll => true,
40            TablePermissionMode::AllowList(allowed) => allowed.contains(table),
41            TablePermissionMode::DenyList(denied) => !denied.contains(table),
42        }
43    }
44
45    /// Create an allow-list permission
46    pub fn allow<I, S>(tables: I) -> Self
47    where
48        I: IntoIterator<Item = S>,
49        S: Into<String>,
50    {
51        TablePermissionMode::AllowList(tables.into_iter().map(Into::into).collect())
52    }
53
54    /// Create a deny-list permission.
55    ///
56    /// Note: Empty deny lists are rejected at [`SqliteConfigBuilder::build()`] time
57    /// since they allow all tables, which is confusing. Use [`TablePermissionMode::AllowAll`] instead.
58    pub fn deny<I, S>(tables: I) -> Self
59    where
60        I: IntoIterator<Item = S>,
61        S: Into<String>,
62    {
63        TablePermissionMode::DenyList(tables.into_iter().map(Into::into).collect())
64    }
65
66    /// Returns true if this is an empty deny list (which allows everything).
67    fn is_empty_deny_list(&self) -> bool {
68        matches!(self, TablePermissionMode::DenyList(tables) if tables.is_empty())
69    }
70}
71
72/// Table permissions for read and write operations
73#[derive(Debug, Clone, Default)]
74pub struct TablePermissions {
75    /// Tables allowed/denied for read operations (SELECT)
76    pub read: TablePermissionMode,
77
78    /// Tables allowed/denied for write operations (INSERT, UPDATE, DELETE)
79    pub write: TablePermissionMode,
80}
81
82impl TablePermissions {
83    /// Create permissions that allow all operations
84    pub fn allow_all() -> Self {
85        Self::default()
86    }
87
88    /// Create read-only permissions for specific tables
89    pub fn read_only<I, S>(tables: I) -> Self
90    where
91        I: IntoIterator<Item = S>,
92        S: Into<String>,
93    {
94        Self {
95            read: TablePermissionMode::AllowList(tables.into_iter().map(Into::into).collect()),
96            write: TablePermissionMode::AllowList(HashSet::new()), // Empty allow list denies all
97        }
98    }
99}
100
101/// Configuration for SQLite tools with permission constraints
102#[derive(Debug, Clone, Default)]
103pub struct SqliteConfig {
104    /// Restrict tool to a specific database path.
105    /// When set, the tool will ignore any db_path in the input and always use this path.
106    pub db_path: Option<String>,
107
108    /// Table-level permissions
109    pub table_permissions: TablePermissions,
110}
111
112impl SqliteConfig {
113    /// Create a new configuration with no restrictions
114    pub fn new() -> Self {
115        Self::default()
116    }
117
118    /// Create a builder for constructing configuration
119    pub fn builder() -> SqliteConfigBuilder {
120        SqliteConfigBuilder::default()
121    }
122
123    /// Check if a table is allowed for read access
124    pub fn can_read(&self, table: &str) -> bool {
125        self.table_permissions.read.is_allowed(table)
126    }
127
128    /// Check if a table is allowed for write access
129    pub fn can_write(&self, table: &str) -> bool {
130        self.table_permissions.write.is_allowed(table)
131    }
132
133    /// Get the effective database path (configured path takes precedence)
134    pub fn effective_db_path(&self, input_path: Option<String>) -> Option<String> {
135        self.db_path.clone().or(input_path)
136    }
137}
138
139/// Builder for SqliteConfig
140#[derive(Debug, Clone, Default)]
141pub struct SqliteConfigBuilder {
142    db_path: Option<String>,
143    table_permissions: TablePermissions,
144}
145
146impl SqliteConfigBuilder {
147    /// Restrict to a specific database path
148    pub fn db_path(mut self, path: impl Into<String>) -> Self {
149        self.db_path = Some(path.into());
150        self
151    }
152
153    /// Set read permissions
154    pub fn read_tables(mut self, mode: TablePermissionMode) -> Self {
155        self.table_permissions.read = mode;
156        self
157    }
158
159    /// Set write permissions
160    pub fn write_tables(mut self, mode: TablePermissionMode) -> Self {
161        self.table_permissions.write = mode;
162        self
163    }
164
165    /// Allow only specific tables for reading
166    pub fn allow_read<I, S>(mut self, tables: I) -> Self
167    where
168        I: IntoIterator<Item = S>,
169        S: Into<String>,
170    {
171        self.table_permissions.read = TablePermissionMode::allow(tables);
172        self
173    }
174
175    /// Deny specific tables for reading
176    pub fn deny_read<I, S>(mut self, tables: I) -> Self
177    where
178        I: IntoIterator<Item = S>,
179        S: Into<String>,
180    {
181        self.table_permissions.read = TablePermissionMode::deny(tables);
182        self
183    }
184
185    /// Allow only specific tables for writing
186    pub fn allow_write<I, S>(mut self, tables: I) -> Self
187    where
188        I: IntoIterator<Item = S>,
189        S: Into<String>,
190    {
191        self.table_permissions.write = TablePermissionMode::allow(tables);
192        self
193    }
194
195    /// Deny specific tables for writing
196    pub fn deny_write<I, S>(mut self, tables: I) -> Self
197    where
198        I: IntoIterator<Item = S>,
199        S: Into<String>,
200    {
201        self.table_permissions.write = TablePermissionMode::deny(tables);
202        self
203    }
204
205    /// Deny all write operations
206    pub fn read_only(mut self) -> Self {
207        // An empty allow list denies everything
208        self.table_permissions.write = TablePermissionMode::AllowList(HashSet::new());
209        self
210    }
211
212    /// Build the configuration.
213    ///
214    /// # Errors
215    ///
216    /// Returns [`ConfigError::EmptyDenyList`] if either read or write permissions
217    /// use an empty deny list, since that allows all tables (use `AllowAll` instead).
218    pub fn build(self) -> Result<SqliteConfig, ConfigError> {
219        // Validate: empty deny lists are confusing since they allow everything
220        if self.table_permissions.read.is_empty_deny_list() {
221            return Err(ConfigError::EmptyDenyList { operation: "read" });
222        }
223        if self.table_permissions.write.is_empty_deny_list() {
224            return Err(ConfigError::EmptyDenyList { operation: "write" });
225        }
226
227        Ok(SqliteConfig {
228            db_path: self.db_path,
229            table_permissions: self.table_permissions,
230        })
231    }
232}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237
238    #[test]
239    fn test_table_permission_mode_allow_all() {
240        let mode = TablePermissionMode::AllowAll;
241        assert!(mode.is_allowed("users"));
242        assert!(mode.is_allowed("secrets"));
243        assert!(mode.is_allowed("anything"));
244    }
245
246    #[test]
247    fn test_table_permission_mode_allow_list() {
248        let mode = TablePermissionMode::allow(["users", "orders"]);
249        assert!(mode.is_allowed("users"));
250        assert!(mode.is_allowed("orders"));
251        assert!(!mode.is_allowed("secrets"));
252        assert!(!mode.is_allowed("admin"));
253    }
254
255    #[test]
256    fn test_table_permission_mode_deny_list() {
257        let mode = TablePermissionMode::deny(["secrets", "admin_logs"]);
258        assert!(mode.is_allowed("users"));
259        assert!(mode.is_allowed("orders"));
260        assert!(!mode.is_allowed("secrets"));
261        assert!(!mode.is_allowed("admin_logs"));
262    }
263
264    #[test]
265    fn test_empty_deny_list_returns_error_read() {
266        let result = SqliteConfig::builder()
267            .deny_read(Vec::<String>::new())
268            .build();
269
270        assert!(result.is_err());
271        let err = result.unwrap_err();
272        assert!(err.to_string().contains("empty deny list"));
273        assert!(err.to_string().contains("read"));
274    }
275
276    #[test]
277    fn test_empty_deny_list_returns_error_write() {
278        let result = SqliteConfig::builder()
279            .deny_write(Vec::<String>::new())
280            .build();
281
282        assert!(result.is_err());
283        let err = result.unwrap_err();
284        assert!(err.to_string().contains("empty deny list"));
285        assert!(err.to_string().contains("write"));
286    }
287
288    #[test]
289    fn test_sqlite_config_builder_db_path() {
290        let config = SqliteConfig::builder()
291            .db_path("/data/app.db")
292            .build()
293            .unwrap();
294
295        assert_eq!(config.db_path, Some("/data/app.db".to_string()));
296    }
297
298    #[test]
299    fn test_sqlite_config_builder_allow_read() {
300        let config = SqliteConfig::builder()
301            .allow_read(["users", "products"])
302            .build()
303            .unwrap();
304
305        assert!(config.can_read("users"));
306        assert!(config.can_read("products"));
307        assert!(!config.can_read("secrets"));
308    }
309
310    #[test]
311    fn test_sqlite_config_builder_deny_write() {
312        let config = SqliteConfig::builder()
313            .deny_write(["audit_log"])
314            .build()
315            .unwrap();
316
317        assert!(config.can_write("users"));
318        assert!(!config.can_write("audit_log"));
319    }
320
321    #[test]
322    fn test_sqlite_config_builder_read_only() {
323        let config = SqliteConfig::builder().read_only().build().unwrap();
324
325        assert!(config.can_read("users"));
326        assert!(!config.can_write("users"));
327        assert!(!config.can_write("anything"));
328    }
329
330    #[test]
331    fn test_effective_db_path_config_takes_precedence() {
332        let config = SqliteConfig::builder()
333            .db_path("/configured/path.db")
334            .build()
335            .unwrap();
336
337        // Configured path should override input path
338        assert_eq!(
339            config.effective_db_path(Some("/input/path.db".to_string())),
340            Some("/configured/path.db".to_string())
341        );
342
343        // Configured path should be used when input is None
344        assert_eq!(
345            config.effective_db_path(None),
346            Some("/configured/path.db".to_string())
347        );
348    }
349
350    #[test]
351    fn test_effective_db_path_falls_back_to_input() {
352        let config = SqliteConfig::new();
353
354        // Without configured path, input path should be used
355        assert_eq!(
356            config.effective_db_path(Some("/input/path.db".to_string())),
357            Some("/input/path.db".to_string())
358        );
359
360        // Without either, should be None
361        assert_eq!(config.effective_db_path(None), None);
362    }
363
364    #[test]
365    fn test_combined_permissions() {
366        let config = SqliteConfig::builder()
367            .db_path("/data/app.db")
368            .allow_read(["users", "products", "orders"])
369            .allow_write(["orders"])
370            .build()
371            .unwrap();
372
373        // Read permissions
374        assert!(config.can_read("users"));
375        assert!(config.can_read("products"));
376        assert!(config.can_read("orders"));
377        assert!(!config.can_read("secrets"));
378
379        // Write permissions
380        assert!(!config.can_write("users"));
381        assert!(!config.can_write("products"));
382        assert!(config.can_write("orders"));
383        assert!(!config.can_write("secrets"));
384    }
385}