WS-D: harden file modes, token names; more auth tests

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YShymaPrXmc3KYRUg2HMSs
This commit is contained in:
ariandClaude Sonnet 5.5 committed 2026-10-15 18:00:36 -04:00
1 parent b6c814a18f
commit e25f0e83bf
3 files changed
+121 -4

No files matched your search

+54
View File
@@ -189,4 +189,58 @@ mod tests {
c.server.bind = "0.0.0.0".parse().unwrap(); c.server.bind = "0.0.0.0".parse().unwrap();
assert!(c.validate().is_err()); assert!(c.validate().is_err());
} }
#[tokio::test]
async fn fails_closed_without_db() {
let mut state = fake_state(Config::default());
state.db = None;
let app = app(state);
let (st, _) = status(&app, "/api/v1/x", Some("Bearer slinuxm_abc")).await;
assert_eq!(st, StatusCode::SERVICE_UNAVAILABLE);
}
#[tokio::test]
async fn db_error_is_503() {
let p = pool().await;
let mut state = fake_state(Config::default());
state.db = Some(p.clone());
let app = app(state);
p.close().await;
let (st, _) = status(&app, "/api/v1/x", Some("Bearer slinuxm_abc")).await;
assert_eq!(st, StatusCode::SERVICE_UNAVAILABLE);
}
#[tokio::test]
async fn scheme_is_case_insensitive() {
let p = pool().await;
let mut state = fake_state(Config::default());
state.db = Some(p.clone());
let app = app(state);
let t = tokens::create(&p, "c").await.unwrap();
for scheme in ["bearer", "BEARER", "Bearer"] {
let h = format!("{scheme} {t}");
assert_eq!(status(&app, "/api/v1/x", Some(&h)).await.0, StatusCode::OK);
}
}
#[tokio::test]
async fn last_used_is_throttled() {
let p = pool().await;
let t = tokens::create(&p, "t").await.unwrap();
assert!(tokens::verify(&p, &t).await.unwrap());
let first = tokens::list(&p).await.unwrap()[0].last_used_at.clone();
assert!(first.is_some());
assert!(tokens::verify(&p, &t).await.unwrap());
assert_eq!(tokens::list(&p).await.unwrap()[0].last_used_at, first);
}
#[tokio::test]
async fn token_names_are_trimmed_and_validated() {
let p = pool().await;
tokens::create(&p, " ci ").await.unwrap();
assert_eq!(tokens::list(&p).await.unwrap()[0].name, "ci");
assert!(tokens::create(&p, "ci").await.is_err());
assert!(tokens::create(&p, "a\nb").await.is_err());
assert!(tokens::create(&p, " ").await.is_err());
}
} }
+5 -1
View File
@@ -54,9 +54,13 @@ fn now_string() -> String {
/// Create a token and return the plaintext (shown once, never stored). /// Create a token and return the plaintext (shown once, never stored).
pub async fn create(pool: &SqlitePool, name: &str) -> Result<String> { pub async fn create(pool: &SqlitePool, name: &str) -> Result<String> {
if name.trim().is_empty() { let name = name.trim();
if name.is_empty() {
bail!("token name must not be empty"); bail!("token name must not be empty");
} }
if name.chars().any(char::is_control) {
bail!("token name must not contain control characters");
}
let mut bytes = [0u8; 32]; let mut bytes = [0u8; 32];
SysRng SysRng
.try_fill_bytes(&mut bytes) .try_fill_bytes(&mut bytes)
+62 -3
View File
@@ -26,9 +26,31 @@ pub async fn open(config: &Config) -> Result<SqlitePool> {
.await .await
.with_context(|| format!("opening token database {}", path.display()))?; .with_context(|| format!("opening token database {}", path.display()))?;
migrate(&pool).await?; migrate(&pool).await?;
restrict_files(path);
Ok(pool) 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. /// Run the embedded migrations.
pub async fn migrate(pool: &SqlitePool) -> Result<()> { pub async fn migrate(pool: &SqlitePool) -> Result<()> {
sqlx::migrate!("./migrations") sqlx::migrate!("./migrations")
@@ -39,6 +61,19 @@ pub async fn migrate(pool: &SqlitePool) -> Result<()> {
fn create_private_dir(dir: &Path) -> Result<()> { fn create_private_dir(dir: &Path) -> Result<()> {
if dir.exists() { 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(()); return Ok(());
} }
let mut b = std::fs::DirBuilder::new(); let mut b = std::fs::DirBuilder::new();
@@ -58,8 +93,13 @@ mod tests {
#[tokio::test] #[tokio::test]
async fn creates_dir_0700_and_migrates() { async fn creates_dir_0700_and_migrates() {
let tmp = std::env::temp_dir().join(format!("slinuxm-dbtest-{}", std::process::id())); use rand::TryRng;
std::fs::remove_dir_all(&tmp).ok(); 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(); let mut c = Config::default();
c.auth.db_path = tmp.join("state/db.sqlite"); c.auth.db_path = tmp.join("state/db.sqlite");
let pool = open(&c).await.unwrap(); let pool = open(&c).await.unwrap();
@@ -73,8 +113,27 @@ mod tests {
use std::os::unix::fs::PermissionsExt; use std::os::unix::fs::PermissionsExt;
let m = std::fs::metadata(tmp.join("state")).unwrap(); let m = std::fs::metadata(tmp.join("state")).unwrap();
assert_eq!(m.permissions().mode() & 0o777, 0o700); 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());
} }
// reopening an existing DB works // 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); drop(pool);
open(&c).await.unwrap(); open(&c).await.unwrap();
std::fs::remove_dir_all(tmp).ok(); std::fs::remove_dir_all(tmp).ok();