//! SQLite pool for access tokens (WS-D owns this file). use std::path::Path; use std::time::Duration; use anyhow::{Context, Result}; use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions}; use sqlx::SqlitePool; use crate::config::Config; /// Open (creating if needed) `config.auth.db_path` and migrate. pub async fn open(config: &Config) -> Result { let path = &config.auth.db_path; if let Some(dir) = path.parent().filter(|d| !d.as_os_str().is_empty()) { create_private_dir(dir)?; } let opts = SqliteConnectOptions::new() .filename(path) .create_if_missing(true) .journal_mode(SqliteJournalMode::Wal) .busy_timeout(Duration::from_secs(5)); let pool = SqlitePoolOptions::new() .max_connections(4) .connect_with(opts) .await .with_context(|| format!("opening token database {}", path.display()))?; migrate(&pool).await?; Ok(pool) } /// Run the embedded migrations. pub async fn migrate(pool: &SqlitePool) -> Result<()> { sqlx::migrate!("./migrations") .run(pool) .await .context("running database migrations") } fn create_private_dir(dir: &Path) -> Result<()> { if dir.exists() { return Ok(()); } let mut b = std::fs::DirBuilder::new(); b.recursive(true); #[cfg(unix)] { use std::os::unix::fs::DirBuilderExt; b.mode(0o700); } b.create(dir) .with_context(|| format!("creating {}", dir.display())) } #[cfg(test)] mod tests { use super::*; #[tokio::test] async fn creates_dir_0700_and_migrates() { let tmp = std::env::temp_dir().join(format!("slinuxm-dbtest-{}", std::process::id())); std::fs::remove_dir_all(&tmp).ok(); let mut c = Config::default(); c.auth.db_path = tmp.join("state/db.sqlite"); let pool = open(&c).await.unwrap(); let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM tokens") .fetch_one(&pool) .await .unwrap(); assert_eq!(n, 0); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; let m = std::fs::metadata(tmp.join("state")).unwrap(); assert_eq!(m.permissions().mode() & 0o777, 0o700); } // reopening an existing DB works drop(pool); open(&c).await.unwrap(); std::fs::remove_dir_all(tmp).ok(); } }