Files
skyg-linux-tracker/src/db.rs
T

142 lines
4.6 KiB
Rust

//! 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<SqlitePool> {
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?;
restrict_files(path);
Ok(pool)
}
/// Make the DB and its WAL/SHM sidecars owner-only (0600).
fn restrict_files(db: &Path) {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
for suffix in ["", "-wal", "-shm"] {
let mut name = db.as_os_str().to_owned();
name.push(suffix);
let p = std::path::PathBuf::from(name);
if p.exists() {
if let Err(e) = std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o600))
{
tracing::warn!(path = %p.display(), error = %e, "could not chmod 0600");
}
}
}
}
#[cfg(not(unix))]
let _ = db;
}
/// 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() {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = std::fs::metadata(dir)?.permissions().mode();
if mode & 0o077 != 0 {
if let Err(e) =
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
{
tracing::warn!(dir = %dir.display(), mode = format!("{:o}", mode & 0o777), error = %e,
"state directory is accessible to others and could not be tightened");
}
}
}
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() {
use rand::TryRng;
let mut r = [0u8; 8];
rand::rngs::SysRng.try_fill_bytes(&mut r).unwrap();
let tmp = std::env::temp_dir().join(format!(
"slinuxm-dbtest-{}",
r.iter().map(|b| format!("{b:02x}")).collect::<String>()
));
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);
for f in ["db.sqlite", "db.sqlite-wal", "db.sqlite-shm"] {
let p = tmp.join("state").join(f);
if p.exists() {
let m = std::fs::metadata(&p).unwrap().permissions().mode();
assert_eq!(m & 0o777, 0o600, "{f}");
}
}
assert!(tmp.join("state/db.sqlite").exists());
}
// a looser existing dir is tightened on reopen
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let d = tmp.join("state");
std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o755)).unwrap();
drop(pool);
open(&c).await.unwrap();
let m = std::fs::metadata(&d).unwrap().permissions().mode();
assert_eq!(m & 0o777, 0o700);
}
#[cfg(not(unix))]
drop(pool);
open(&c).await.unwrap();
std::fs::remove_dir_all(tmp).ok();
}
}