diff --git a/.env.example b/.env.example index 5d7ca9b..268236f 100644 --- a/.env.example +++ b/.env.example @@ -30,3 +30,10 @@ RUST_LOG=info,hezarfen_backend=debug # to that header — otherwise the header is client-forged and limits are # trivially bypassed. When off (default), the peer address is used. # TRUST_PROXY=true + +# Seed an admin account at startup: if this username doesn't exist yet it is +# created with this password and the `admin` role. Both must be set together. +# If the username exists as a non-admin, nothing is changed (a warning is +# logged) — the seed never promotes or rewrites an existing account. +# ADMIN_USERNAME=admin +# ADMIN_PASSWORD=admin123 diff --git a/compose.yaml b/compose.yaml index 2080639..d88118f 100644 --- a/compose.yaml +++ b/compose.yaml @@ -14,6 +14,10 @@ services: DB_NAMESPACE: hezarfen DB_DATABASE: hezarfen RUST_LOG: info,hezarfen_backend=debug + # First-boot admin seed: created once if the username doesn't exist yet. + # Local-dev credentials — change or remove before exposing this anywhere. + ADMIN_USERNAME: admin + ADMIN_PASSWORD: admin123 # Production knobs — uncomment as needed (see .env.example for docs): # COOKIE_SECURE: "true" # CORS_ALLOWED_ORIGINS: https://app.example.com diff --git a/src/config.rs b/src/config.rs index 53dcdc4..8d9c8e2 100644 --- a/src/config.rs +++ b/src/config.rs @@ -21,6 +21,11 @@ pub struct Config { /// Per-IP request limits (`RATE_LIMIT_AUTH_PER_MINUTE`, /// `RATE_LIMIT_API_PER_MINUTE`, `TRUST_PROXY`). `0` disables a tier. pub rate_limit: RateLimitConfig, + /// Startup admin seed (`ADMIN_USERNAME` + `ADMIN_PASSWORD`). When both are + /// set, an admin account with these credentials is created at boot if the + /// username doesn't exist yet. Blank values count as unset. + pub admin_username: Option, + pub admin_password: Option, } impl Config { @@ -43,10 +48,17 @@ impl Config { ), trust_proxy: parse_flag(env::var("TRUST_PROXY").ok()), }, + admin_username: parse_optional(env::var("ADMIN_USERNAME").ok()), + admin_password: parse_optional(env::var("ADMIN_PASSWORD").ok()), } } } +/// Treat an unset or blank variable as absent. +fn parse_optional(value: Option) -> Option { + value.filter(|v| !v.trim().is_empty()) +} + /// Parse a per-minute limit, falling back to `default` when unset or /// unparseable. An explicit `0` is honoured: it turns that tier off. fn parse_limit(value: Option, default: u32) -> u32 { diff --git a/src/domain/user.rs b/src/domain/user.rs index 055e90c..b5b9f72 100644 --- a/src/domain/user.rs +++ b/src/domain/user.rs @@ -217,6 +217,36 @@ impl User { } } + /// Idempotent startup seed: guarantee an admin account with this username. + /// Missing → created directly with [`Role::Admin`]. Already an admin → + /// nothing to do (the stored password stays whatever it is — the seed never + /// rewrites credentials). Taken by a non-admin → refuse to touch it and log + /// a warning: silently promoting an account someone else registered would + /// be a privilege escalation, so that conflict is resolved out-of-band. + pub async fn ensure_admin( + username: Username, + password: Password, + db: &Database, + ) -> Result<(), AppError> { + match Self::find_by_username(username.as_str(), db).await? { + Some(user) if user.role == Role::Admin => Ok(()), + Some(_) => { + tracing::warn!( + username = username.as_str(), + "ADMIN_USERNAME names an existing non-admin account; refusing to promote it. \ + Grant the role through an existing admin or the manual SurrealQL path." + ); + Ok(()) + } + None => { + let created = Self::create(username, password.hash()?, db).await?; + let admin = created.set_role(Role::Admin, db).await?; + tracing::info!(username = admin.username.as_str(), "seeded admin account"); + Ok(()) + } + } + } + pub async fn read(id: &UserId, db: &Database) -> Result, AppError> { Ok(db.select(id.record()).await?) } diff --git a/src/main.rs b/src/main.rs index 90b1c25..20e4487 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,7 @@ +use anyhow::Context; use hezarfen_backend::config::Config; +use hezarfen_backend::database::Database; +use hezarfen_backend::domain::user::{Password, User, Username}; use hezarfen_backend::state::AppState; use hezarfen_backend::{build_router, database}; @@ -14,6 +17,7 @@ async fn main() -> anyhow::Result<()> { let cfg = Config::from_env(); let db = database::init(&cfg).await?; + seed_admin(&cfg, &db).await?; let app = build_router(AppState { db, cookie_secure: cfg.cookie_secure, @@ -35,6 +39,24 @@ async fn main() -> anyhow::Result<()> { Ok(()) } +/// Apply the `ADMIN_USERNAME` / `ADMIN_PASSWORD` bootstrap, if configured. +/// Both-or-neither: half a credential pair is a deployment mistake, so it +/// aborts startup rather than silently running without the seed. +async fn seed_admin(cfg: &Config, db: &Database) -> anyhow::Result<()> { + match (&cfg.admin_username, &cfg.admin_password) { + (Some(username), Some(password)) => { + let username = Username::try_new(username).context("invalid ADMIN_USERNAME")?; + let password = Password::try_new(password).context("invalid ADMIN_PASSWORD")?; + User::ensure_admin(username, password, db) + .await + .context("failed to seed the admin account")?; + Ok(()) + } + (None, None) => Ok(()), + _ => anyhow::bail!("ADMIN_USERNAME and ADMIN_PASSWORD must be set together"), + } +} + /// Resolve on SIGINT (Ctrl-C) or SIGTERM. As PID 1 in a container the process /// gets no default signal handling, so without this a `podman stop` waits out /// its grace period and SIGKILLs us — skipping the embedded store's clean close.