manage user create; staff only by deliberate grant

d2b4d8f · gmorell · 2026-12-02 16:07

9 files +151 -25
Message
{commit_body(@commit)}

Files changed

modified Justfile
+5 −0
@@ -64,6 +64,11 @@ serve:
64 64 manage *args:
65 65 cargo run --bin manage -- {{args}}
66 66
67 +# Create a staff account directly (prints a generated password once).
68 +# Usage: just admin <username> <email>
69 +admin username email:
70 + cargo run --bin manage -- user create {{username}} --email {{email}} --staff
71 +
67 72 # Generate an invite token. Usage: just invite [days]
68 73 invite days="7":
69 74 cargo run --bin manage -- invite create --days {{days}}
modified README.md
+13 −4
@@ -16,11 +16,19 @@ just deps # npm install (frontend deps)
16 16 just assets # build CSS + JS + webfonts
17 17 just db-up # start Postgres via podman compose
18 18 just migrate # apply migrations
19 −just invite # mint an invite token, prints a /register?token=... URL
19 +just admin alice alice@example.com # first (staff) account; prints its password
20 20 just serve # run the web service on :3000
21 21 ```
22 22
23 −Then open the printed registration URL to create the first account.
23 +Sign in with the printed password. Further members join through invites
24 +(`just invite`, or the Invites page), or are created the same way.
25 +
26 +### Staff
27 +
28 +Staff (category/reaction admin, moderation) is only ever granted on purpose:
29 +`manage user create … --staff`, or `manage user set-staff <name>` for an
30 +existing account. Registering — even as the very first account — never makes
31 +anyone staff.
24 32
25 33 ## Configuration (environment)
26 34
@@ -39,6 +47,7 @@ Then open the printed registration URL to create the first account.
39 47
40 48 - `recourse` — the web service
41 49 - `manage` — admin CLI:
42 − - `manage user list | set-staff <name> [--revoke] | activate <name> | deactivate <name> | delete <name> --yes`
50 + - `manage user create <name> --email E [--staff] [--password-stdin]` — no invite needed; without `--password-stdin` a strong password is generated and printed once
51 + - `manage user list | set-staff <name> [--revoke] | set-trust <name> <0-4> | activate <name> | deactivate <name> | delete <name> --yes`
43 52 - `manage invite create [--email E] [--days N] | list | show <token>`
44 − - Justfile shortcuts: `just manage …`, `just invite [days]`, `just staff <name>`
53 + - Justfile shortcuts: `just manage …`, `just admin <name> <email>`, `just invite [days]`, `just staff <name>`, `just trust <name> <level>`
modified src/auth/mod.rs
+2 −2
@@ -6,13 +6,13 @@ pub mod users;
6 6 pub use api_tokens::{
7 7 create_api_token, delete_api_token, generate_api_token, list_api_tokens, validate_api_token,
8 8 };
9 −pub use password::{hash_password, verify_password};
9 +pub use password::{generate_password, hash_password, verify_password};
10 10 pub use tokens::{
11 11 cleanup_expired_sessions, create_registration_token, create_session, delete_session,
12 12 generate_registration_token, generate_session_token, mark_registration_token_used,
13 13 validate_registration_token, validate_session,
14 14 };
15 15 pub use users::{
16 − authenticate_user, change_password, create_user, deactivate_user, get_user_by_id,
16 + authenticate_user, change_password, create_user, create_user_direct, deactivate_user, get_user_by_id,
17 17 update_user, CreateUserRequest, LoginRequest,
18 18 };
modified src/auth/password.rs
+25 −0
@@ -18,6 +18,23 @@ pub fn hash_password(password: &str) -> Result<String> {
18 18 Ok(password_hash.to_string())
19 19 }
20 20
21 +/// Generate a strong random password (24 characters from a 56-symbol
22 +/// alphabet without look-alikes, ~139 bits) from the OS CSPRNG. Used by
23 +/// `manage user create` when no password is supplied.
24 +pub fn generate_password() -> String {
25 + use argon2::password_hash::rand_core::{OsRng, RngCore};
26 + const ALPHABET: &[u8] = b"ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789";
27 + let mut out = String::with_capacity(24);
28 + while out.len() < 24 {
29 + let b = (OsRng.next_u32() & 0xff) as usize;
30 + // Rejection sampling keeps the distribution uniform.
31 + if b < ALPHABET.len() * (256 / ALPHABET.len()) {
32 + out.push(ALPHABET[b % ALPHABET.len()] as char);
33 + }
34 + }
35 + out
36 +}
37 +
21 38 /// Verify a password against its hash.
22 39 pub fn verify_password(password: &str, hash: &str) -> Result<bool> {
23 40 let parsed_hash = PasswordHash::new(hash).context("Failed to parse password hash")?;
@@ -42,6 +59,14 @@ mod tests {
42 59 assert!(!verify_password("wrong_password", &hash).unwrap());
43 60 }
44 61
62 + #[test]
63 + fn generated_passwords_are_long_and_distinct() {
64 + let a = generate_password();
65 + assert_eq!(a.len(), 24);
66 + assert!(a.chars().all(|c| c.is_ascii_alphanumeric()));
67 + assert_ne!(a, generate_password());
68 + }
69 +
45 70 #[test]
46 71 fn test_salt_is_random() {
47 72 let a = hash_password("same").unwrap();
modified src/auth/users.rs
+62 −19
@@ -48,38 +48,81 @@ pub async fn create_user(db: &DatabaseConnection, request: CreateUserRequest) ->
48 48 let password_hash =
49 49 password::hash_password(&request.password).context("Failed to hash password")?;
50 50
51 − // The very first account to register becomes staff/admin (Discourse-style),
52 − // so there's always someone who can manage categories on a fresh install.
53 − let is_first_user = users::Entity::find()
54 − .count(db)
51 + // Staff is never granted implicitly: use `manage user create --staff` or
52 + // `manage user set-staff`.
53 + let new_user = new_user_model(request.username, request.email, password_hash, false);
54 +
55 + let user = new_user.insert(db).await.context("Failed to create user")?;
56 +
57 + tokens::mark_registration_token_used(db, reg_token.id, user.id)
55 58 .await
56 − .context("Failed to count users")?
57 − == 0;
59 + .context("Failed to mark registration token as used")?;
60 +
61 + Ok(user)
62 +}
58 63
59 − let new_user = users::ActiveModel {
64 +/// A fresh `users` row with recourse's defaults (trust level 0, latest sort,
65 +/// reaction notifications on, no avatar).
66 +pub(crate) fn new_user_model(
67 + username: String,
68 + email: String,
69 + password_hash: String,
70 + is_staff: bool,
71 +) -> users::ActiveModel {
72 + let now = Utc::now();
73 + users::ActiveModel {
60 74 id: Set(Uuid::now_v7()),
61 − username: Set(request.username),
62 − email: Set(request.email),
75 + username: Set(username),
76 + email: Set(email),
63 77 password_hash: Set(password_hash),
64 78 is_active: Set(true),
65 − is_staff: Set(is_first_user),
79 + is_staff: Set(is_staff),
66 80 preferred_sort: Set("latest".to_string()),
67 81 reaction_notifications: Set(true),
68 82 trust_level: Set(0),
69 − created_at: Set(Utc::now().into()),
70 − updated_at: Set(Utc::now().into()),
83 + created_at: Set(now.into()),
84 + updated_at: Set(now.into()),
71 85 last_login_at: Set(None),
72 86 avatar_data: Set(None),
73 87 avatar_content_type: Set(None),
74 − };
75 −
76 − let user = new_user.insert(db).await.context("Failed to create user")?;
88 + }
89 +}
77 90
78 − tokens::mark_registration_token_used(db, reg_token.id, user.id)
91 +/// Create a user directly, without an invite — the operator path used by
92 +/// `manage user create`. Refuses a taken username or email.
93 +pub async fn create_user_direct(
94 + db: &DatabaseConnection,
95 + username: &str,
96 + email: &str,
97 + password: &str,
98 + is_staff: bool,
99 +) -> Result<users::Model> {
100 + let username = username.trim();
101 + let email = email.trim();
102 + if username.is_empty() || email.is_empty() {
103 + return Err(anyhow::anyhow!("username and email are required"));
104 + }
105 + let taken = users::Entity::find()
106 + .filter(
107 + Condition::any()
108 + .add(users::Column::Username.eq(username))
109 + .add(users::Column::Email.eq(email)),
110 + )
111 + .one(db)
79 112 .await
80 − .context("Failed to mark registration token as used")?;
81 −
82 − Ok(user)
113 + .context("Failed to check existing users")?;
114 + if let Some(other) = taken {
115 + return Err(if other.username == username {
116 + anyhow::anyhow!("username '{username}' is already taken")
117 + } else {
118 + anyhow::anyhow!("email '{email}' is already in use")
119 + });
120 + }
121 + let password_hash = password::hash_password(password).context("Failed to hash password")?;
122 + new_user_model(username.to_string(), email.to_string(), password_hash, is_staff)
123 + .insert(db)
124 + .await
125 + .context("Failed to create user")
83 126 }
84 127
85 128 /// Authenticate a user by username + password, bumping `last_login_at`.
modified src/bin/manage.rs
+44 −0
@@ -3,6 +3,7 @@
3 3 //! Grouped subcommands so new management surfaces (categories, topics, …) can
4 4 //! be added as new `Command` variants without disturbing the existing ones.
5 5 //!
6 +//! manage user create <username> --email E [--staff] [--password-stdin]
6 7 //! manage user list
7 8 //! manage user set-staff <username> [--revoke]
8 9 //! manage user activate|deactivate <username>
@@ -44,6 +45,20 @@ enum Command {
44 45
45 46 #[derive(Subcommand)]
46 47 enum UserCmd {
48 + /// Create an account directly (no invite). Prints a generated password
49 + /// unless --password-stdin is given.
50 + Create {
51 + username: String,
52 + #[arg(long)]
53 + email: String,
54 + /// Grant staff/admin rights (category, reaction and moderation tools)
55 + #[arg(long)]
56 + staff: bool,
57 + /// Read the password from the first line of stdin instead of
58 + /// generating one
59 + #[arg(long)]
60 + password_stdin: bool,
61 + },
47 62 /// List all users
48 63 List,
49 64 /// Grant (or with --revoke, remove) staff/admin rights
@@ -111,6 +126,35 @@ async fn find_user(db: &DatabaseConnection, username: &str) -> Result<users::Mod
111 126
112 127 async fn run_user(db: &DatabaseConnection, cmd: UserCmd) -> Result<(), DynErr> {
113 128 match cmd {
129 + UserCmd::Create {
130 + username,
131 + email,
132 + staff,
133 + password_stdin,
134 + } => {
135 + let (password, generated) = if password_stdin {
136 + let mut line = String::new();
137 + std::io::stdin().read_line(&mut line)?;
138 + let pw = line.trim_end_matches(['\r', '\n']).to_string();
139 + if pw.is_empty() {
140 + return Err("empty password on stdin".into());
141 + }
142 + (pw, false)
143 + } else {
144 + (auth::generate_password(), true)
145 + };
146 + let user = auth::create_user_direct(db, &username, &email, &password, staff).await?;
147 + println!(
148 + "Created {}{} <{}>.",
149 + user.username,
150 + if user.is_staff { " (staff)" } else { "" },
151 + user.email
152 + );
153 + if generated {
154 + println!();
155 + println!("Password (shown once, store it now): {password}");
156 + }
157 + }
114 158 UserCmd::List => {
115 159 let rows = users::Entity::find()
116 160 .order_by_asc(users::Column::CreatedAt)

Parents: b1da290