use std::collections::HashSet;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ConfigError {
#[error(
"empty deny list for {operation} permissions allows all tables - use AllowAll or omit"
)]
EmptyDenyList {
operation: &'static str,
},
}
#[derive(Debug, Clone, Default)]
pub enum TablePermissionMode {
#[default]
AllowAll,
AllowList(HashSet<String>),
DenyList(HashSet<String>),
}
impl TablePermissionMode {
pub fn is_allowed(&self, table: &str) -> bool {
match self {
TablePermissionMode::AllowAll => true,
TablePermissionMode::AllowList(allowed) => allowed.contains(table),
TablePermissionMode::DenyList(denied) => !denied.contains(table),
}
}
pub fn allow<I, S>(tables: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
TablePermissionMode::AllowList(tables.into_iter().map(Into::into).collect())
}
pub fn deny<I, S>(tables: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
TablePermissionMode::DenyList(tables.into_iter().map(Into::into).collect())
}
fn is_empty_deny_list(&self) -> bool {
matches!(self, TablePermissionMode::DenyList(tables) if tables.is_empty())
}
}
#[derive(Debug, Clone, Default)]
pub struct TablePermissions {
pub read: TablePermissionMode,
pub write: TablePermissionMode,
}
impl TablePermissions {
pub fn allow_all() -> Self {
Self::default()
}
pub fn read_only<I, S>(tables: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
Self {
read: TablePermissionMode::AllowList(tables.into_iter().map(Into::into).collect()),
write: TablePermissionMode::AllowList(HashSet::new()), }
}
}
#[derive(Debug, Clone, Default)]
pub struct SqliteConfig {
pub db_path: Option<String>,
pub table_permissions: TablePermissions,
}
impl SqliteConfig {
pub fn new() -> Self {
Self::default()
}
pub fn builder() -> SqliteConfigBuilder {
SqliteConfigBuilder::default()
}
pub fn can_read(&self, table: &str) -> bool {
self.table_permissions.read.is_allowed(table)
}
pub fn can_write(&self, table: &str) -> bool {
self.table_permissions.write.is_allowed(table)
}
pub fn effective_db_path(&self, input_path: Option<String>) -> Option<String> {
self.db_path.clone().or(input_path)
}
}
#[derive(Debug, Clone, Default)]
pub struct SqliteConfigBuilder {
db_path: Option<String>,
table_permissions: TablePermissions,
}
impl SqliteConfigBuilder {
pub fn db_path(mut self, path: impl Into<String>) -> Self {
self.db_path = Some(path.into());
self
}
pub fn read_tables(mut self, mode: TablePermissionMode) -> Self {
self.table_permissions.read = mode;
self
}
pub fn write_tables(mut self, mode: TablePermissionMode) -> Self {
self.table_permissions.write = mode;
self
}
pub fn allow_read<I, S>(mut self, tables: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.table_permissions.read = TablePermissionMode::allow(tables);
self
}
pub fn deny_read<I, S>(mut self, tables: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.table_permissions.read = TablePermissionMode::deny(tables);
self
}
pub fn allow_write<I, S>(mut self, tables: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.table_permissions.write = TablePermissionMode::allow(tables);
self
}
pub fn deny_write<I, S>(mut self, tables: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.table_permissions.write = TablePermissionMode::deny(tables);
self
}
pub fn read_only(mut self) -> Self {
self.table_permissions.write = TablePermissionMode::AllowList(HashSet::new());
self
}
pub fn build(self) -> Result<SqliteConfig, ConfigError> {
if self.table_permissions.read.is_empty_deny_list() {
return Err(ConfigError::EmptyDenyList { operation: "read" });
}
if self.table_permissions.write.is_empty_deny_list() {
return Err(ConfigError::EmptyDenyList { operation: "write" });
}
Ok(SqliteConfig {
db_path: self.db_path,
table_permissions: self.table_permissions,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_table_permission_mode_allow_all() {
let mode = TablePermissionMode::AllowAll;
assert!(mode.is_allowed("users"));
assert!(mode.is_allowed("secrets"));
assert!(mode.is_allowed("anything"));
}
#[test]
fn test_table_permission_mode_allow_list() {
let mode = TablePermissionMode::allow(["users", "orders"]);
assert!(mode.is_allowed("users"));
assert!(mode.is_allowed("orders"));
assert!(!mode.is_allowed("secrets"));
assert!(!mode.is_allowed("admin"));
}
#[test]
fn test_table_permission_mode_deny_list() {
let mode = TablePermissionMode::deny(["secrets", "admin_logs"]);
assert!(mode.is_allowed("users"));
assert!(mode.is_allowed("orders"));
assert!(!mode.is_allowed("secrets"));
assert!(!mode.is_allowed("admin_logs"));
}
#[test]
fn test_empty_deny_list_returns_error_read() {
let result = SqliteConfig::builder()
.deny_read(Vec::<String>::new())
.build();
assert!(result.is_err());
let err = result.unwrap_err();
assert!(err.to_string().contains("empty deny list"));
assert!(err.to_string().contains("read"));
}
#[test]
fn test_empty_deny_list_returns_error_write() {
let result = SqliteConfig::builder()
.deny_write(Vec::<String>::new())
.build();
assert!(result.is_err());
let err = result.unwrap_err();
assert!(err.to_string().contains("empty deny list"));
assert!(err.to_string().contains("write"));
}
#[test]
fn test_sqlite_config_builder_db_path() {
let config = SqliteConfig::builder()
.db_path("/data/app.db")
.build()
.unwrap();
assert_eq!(config.db_path, Some("/data/app.db".to_string()));
}
#[test]
fn test_sqlite_config_builder_allow_read() {
let config = SqliteConfig::builder()
.allow_read(["users", "products"])
.build()
.unwrap();
assert!(config.can_read("users"));
assert!(config.can_read("products"));
assert!(!config.can_read("secrets"));
}
#[test]
fn test_sqlite_config_builder_deny_write() {
let config = SqliteConfig::builder()
.deny_write(["audit_log"])
.build()
.unwrap();
assert!(config.can_write("users"));
assert!(!config.can_write("audit_log"));
}
#[test]
fn test_sqlite_config_builder_read_only() {
let config = SqliteConfig::builder().read_only().build().unwrap();
assert!(config.can_read("users"));
assert!(!config.can_write("users"));
assert!(!config.can_write("anything"));
}
#[test]
fn test_effective_db_path_config_takes_precedence() {
let config = SqliteConfig::builder()
.db_path("/configured/path.db")
.build()
.unwrap();
assert_eq!(
config.effective_db_path(Some("/input/path.db".to_string())),
Some("/configured/path.db".to_string())
);
assert_eq!(
config.effective_db_path(None),
Some("/configured/path.db".to_string())
);
}
#[test]
fn test_effective_db_path_falls_back_to_input() {
let config = SqliteConfig::new();
assert_eq!(
config.effective_db_path(Some("/input/path.db".to_string())),
Some("/input/path.db".to_string())
);
assert_eq!(config.effective_db_path(None), None);
}
#[test]
fn test_combined_permissions() {
let config = SqliteConfig::builder()
.db_path("/data/app.db")
.allow_read(["users", "products", "orders"])
.allow_write(["orders"])
.build()
.unwrap();
assert!(config.can_read("users"));
assert!(config.can_read("products"));
assert!(config.can_read("orders"));
assert!(!config.can_read("secrets"));
assert!(!config.can_write("users"));
assert!(!config.can_write("products"));
assert!(config.can_write("orders"));
assert!(!config.can_write("secrets"));
}
}