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
3030 # to that header — otherwise the header is client-forged and limits are
3131 # trivially bypassed. When off (default), the peer address is used.
3232 # 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:
1414 DB_NAMESPACE: hezarfen
1515 DB_DATABASE: hezarfen
1616 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
1721 # Production knobs — uncomment as needed (see .env.example for docs):
1822 # COOKIE_SECURE: "true"
1923 # CORS_ALLOWED_ORIGINS: https://app.example.com
src/config.rsmodified+12 -0
@@ -21,6 +21,11 @@ pub struct Config {
2121 /// Per-IP request limits (`RATE_LIMIT_AUTH_PER_MINUTE`,
2222 /// `RATE_LIMIT_API_PER_MINUTE`, `TRUST_PROXY`). `0` disables a tier.
2323 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>,
2429 }
2530
2631 impl Config {
@@ -43,10 +48,17 @@ impl Config {
4348 ),
4449 trust_proxy: parse_flag(env::var("TRUST_PROXY").ok()),
4550 },
51+ admin_username: parse_optional(env::var("ADMIN_USERNAME").ok()),
52+ admin_password: parse_optional(env::var("ADMIN_PASSWORD").ok()),
4653 }
4754 }
4855 }
4956
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+
5062 /// Parse a per-minute limit, falling back to `default` when unset or
5163 /// unparseable. An explicit `0` is honoured: it turns that tier off.
5264 fn parse_limit(value: Option<String>, default: u32) -> u32 {
src/domain/user.rsmodified+30 -0
@@ -217,6 +217,36 @@ impl User {
217217 }
218218 }
219219
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+
220250 pub async fn read(id: &UserId, db: &Database) -> Result<Option<User>, AppError> {
221251 Ok(db.select(id.record()).await?)
222252 }
src/main.rsmodified+22 -0
@@ -1,4 +1,7 @@
1+use anyhow::Context;
12 use hezarfen_backend::config::Config;
3+use hezarfen_backend::database::Database;
4+use hezarfen_backend::domain::user::{Password, User, Username};
25 use hezarfen_backend::state::AppState;
36 use hezarfen_backend::{build_router, database};
47
@@ -14,6 +17,7 @@ async fn main() -> anyhow::Result<()> {
1417
1518 let cfg = Config::from_env();
1619 let db = database::init(&cfg).await?;
20+ seed_admin(&cfg, &db).await?;
1721 let app = build_router(AppState {
1822 db,
1923 cookie_secure: cfg.cookie_secure,
@@ -35,6 +39,24 @@ async fn main() -> anyhow::Result<()> {
3539 Ok(())
3640 }
3741
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+
3860 /// Resolve on SIGINT (Ctrl-C) or SIGTERM. As PID 1 in a container the process
3961 /// gets no default signal handling, so without this a `podman stop` waits out
4062 /// its grace period and SIGKILLs us — skipping the embedded store's clean close.