forge
Explore
Log in

Don't you dare go Hollow

Seed an admin account at startup

Browse files at this commit

ea497d9d81447b0cb4cd22cce0947817fa7fad7fAhmet Kaan GümüşParent: eb282a0
  • feat
    • seed an admin account at startup
Show full message
✨ feat(admin): seed an admin account at startup

ADMIN_USERNAME and ADMIN_PASSWORD (both-or-neither; half a pair aborts
boot, blank counts as unset) create an admin at startup when the
username doesn't exist. The seed is idempotent and never rewrites
credentials: an existing admin is left as-is, and a non-admin holding
the name is never promoted — that would be a privilege escalation, so
it only logs a warning pointing at the out-of-band paths.

compose.yaml ships local-dev credentials for first boot; .env.example
documents the knob.
.env.examplemodified+7 -0
@@ -30,3 +30,10 @@ RUST_LOG=info,hezarfen_backend=debug
30 # to that header — otherwise the header is client-forged and limits are30 # to that header — otherwise the header is client-forged and limits are
31 # trivially bypassed. When off (default), the peer address is used.31 # trivially bypassed. When off (default), the peer address is used.
32 # TRUST_PROXY=true32 # TRUST_PROXY=true
33+
34+# Seed an admin account at startup: if this username doesn't exist yet it is
35+# created with this password and the `admin` role. Both must be set together.
36+# If the username exists as a non-admin, nothing is changed (a warning is
37+# logged) — the seed never promotes or rewrites an existing account.
38+# ADMIN_USERNAME=admin
39+# ADMIN_PASSWORD=admin123
compose.yamlmodified+4 -0
@@ -14,6 +14,10 @@ services:
14 DB_NAMESPACE: hezarfen14 DB_NAMESPACE: hezarfen
15 DB_DATABASE: hezarfen15 DB_DATABASE: hezarfen
16 RUST_LOG: info,hezarfen_backend=debug16 RUST_LOG: info,hezarfen_backend=debug
17+ # First-boot admin seed: created once if the username doesn't exist yet.
18+ # Local-dev credentials — change or remove before exposing this anywhere.
19+ ADMIN_USERNAME: admin
20+ ADMIN_PASSWORD: admin123
17 # Production knobs — uncomment as needed (see .env.example for docs):21 # Production knobs — uncomment as needed (see .env.example for docs):
18 # COOKIE_SECURE: "true"22 # COOKIE_SECURE: "true"
19 # CORS_ALLOWED_ORIGINS: https://app.example.com23 # CORS_ALLOWED_ORIGINS: https://app.example.com
src/config.rsmodified+12 -0
@@ -21,6 +21,11 @@ pub struct Config {
21 /// Per-IP request limits (`RATE_LIMIT_AUTH_PER_MINUTE`,21 /// Per-IP request limits (`RATE_LIMIT_AUTH_PER_MINUTE`,
22 /// `RATE_LIMIT_API_PER_MINUTE`, `TRUST_PROXY`). `0` disables a tier.22 /// `RATE_LIMIT_API_PER_MINUTE`, `TRUST_PROXY`). `0` disables a tier.
23 pub rate_limit: RateLimitConfig,23 pub rate_limit: RateLimitConfig,
24+ /// Startup admin seed (`ADMIN_USERNAME` + `ADMIN_PASSWORD`). When both are
25+ /// set, an admin account with these credentials is created at boot if the
26+ /// username doesn't exist yet. Blank values count as unset.
27+ pub admin_username: Option<String>,
28+ pub admin_password: Option<String>,
24 }29 }
25 30
26 impl Config {31 impl Config {
@@ -43,10 +48,17 @@ impl Config {
43 ),48 ),
44 trust_proxy: parse_flag(env::var("TRUST_PROXY").ok()),49 trust_proxy: parse_flag(env::var("TRUST_PROXY").ok()),
45 },50 },
51+ admin_username: parse_optional(env::var("ADMIN_USERNAME").ok()),
52+ admin_password: parse_optional(env::var("ADMIN_PASSWORD").ok()),
46 }53 }
47 }54 }
48 }55 }
49 56
57+/// Treat an unset or blank variable as absent.
58+fn parse_optional(value: Option<String>) -> Option<String> {
59+ value.filter(|v| !v.trim().is_empty())
60+}
61+
50 /// Parse a per-minute limit, falling back to `default` when unset or62 /// Parse a per-minute limit, falling back to `default` when unset or
51 /// unparseable. An explicit `0` is honoured: it turns that tier off.63 /// unparseable. An explicit `0` is honoured: it turns that tier off.
52 fn parse_limit(value: Option<String>, default: u32) -> u32 {64 fn parse_limit(value: Option<String>, default: u32) -> u32 {
src/domain/user.rsmodified+30 -0
@@ -217,6 +217,36 @@ impl User {
217 }217 }
218 }218 }
219 219
220+ /// Idempotent startup seed: guarantee an admin account with this username.
221+ /// Missing → created directly with [`Role::Admin`]. Already an admin →
222+ /// nothing to do (the stored password stays whatever it is — the seed never
223+ /// rewrites credentials). Taken by a non-admin → refuse to touch it and log
224+ /// a warning: silently promoting an account someone else registered would
225+ /// be a privilege escalation, so that conflict is resolved out-of-band.
226+ pub async fn ensure_admin(
227+ username: Username,
228+ password: Password,
229+ db: &Database,
230+ ) -> Result<(), AppError> {
231+ match Self::find_by_username(username.as_str(), db).await? {
232+ Some(user) if user.role == Role::Admin => Ok(()),
233+ Some(_) => {
234+ tracing::warn!(
235+ username = username.as_str(),
236+ "ADMIN_USERNAME names an existing non-admin account; refusing to promote it. \
237+ Grant the role through an existing admin or the manual SurrealQL path."
238+ );
239+ Ok(())
240+ }
241+ None => {
242+ let created = Self::create(username, password.hash()?, db).await?;
243+ let admin = created.set_role(Role::Admin, db).await?;
244+ tracing::info!(username = admin.username.as_str(), "seeded admin account");
245+ Ok(())
246+ }
247+ }
248+ }
249+
220 pub async fn read(id: &UserId, db: &Database) -> Result<Option<User>, AppError> {250 pub async fn read(id: &UserId, db: &Database) -> Result<Option<User>, AppError> {
221 Ok(db.select(id.record()).await?)251 Ok(db.select(id.record()).await?)
222 }252 }
src/main.rsmodified+22 -0
@@ -1,4 +1,7 @@
1+use anyhow::Context;
1 use hezarfen_backend::config::Config;2 use hezarfen_backend::config::Config;
3+use hezarfen_backend::database::Database;
4+use hezarfen_backend::domain::user::{Password, User, Username};
2 use hezarfen_backend::state::AppState;5 use hezarfen_backend::state::AppState;
3 use hezarfen_backend::{build_router, database};6 use hezarfen_backend::{build_router, database};
4 7
@@ -14,6 +17,7 @@ async fn main() -> anyhow::Result<()> {
14 17
15 let cfg = Config::from_env();18 let cfg = Config::from_env();
16 let db = database::init(&cfg).await?;19 let db = database::init(&cfg).await?;
20+ seed_admin(&cfg, &db).await?;
17 let app = build_router(AppState {21 let app = build_router(AppState {
18 db,22 db,
19 cookie_secure: cfg.cookie_secure,23 cookie_secure: cfg.cookie_secure,
@@ -35,6 +39,24 @@ async fn main() -> anyhow::Result<()> {
35 Ok(())39 Ok(())
36 }40 }
37 41
42+/// Apply the `ADMIN_USERNAME` / `ADMIN_PASSWORD` bootstrap, if configured.
43+/// Both-or-neither: half a credential pair is a deployment mistake, so it
44+/// aborts startup rather than silently running without the seed.
45+async fn seed_admin(cfg: &Config, db: &Database) -> anyhow::Result<()> {
46+ match (&cfg.admin_username, &cfg.admin_password) {
47+ (Some(username), Some(password)) => {
48+ let username = Username::try_new(username).context("invalid ADMIN_USERNAME")?;
49+ let password = Password::try_new(password).context("invalid ADMIN_PASSWORD")?;
50+ User::ensure_admin(username, password, db)
51+ .await
52+ .context("failed to seed the admin account")?;
53+ Ok(())
54+ }
55+ (None, None) => Ok(()),
56+ _ => anyhow::bail!("ADMIN_USERNAME and ADMIN_PASSWORD must be set together"),
57+ }
58+}
59+
38 /// Resolve on SIGINT (Ctrl-C) or SIGTERM. As PID 1 in a container the process60 /// Resolve on SIGINT (Ctrl-C) or SIGTERM. As PID 1 in a container the process
39 /// gets no default signal handling, so without this a `podman stop` waits out61 /// gets no default signal handling, so without this a `podman stop` waits out
40 /// its grace period and SIGKILLs us — skipping the embedded store's clean close.62 /// its grace period and SIGKILLs us — skipping the embedded store's clean close.