forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.7 MiBe587be7Tahinli12 hours ago323 commits

admin_cli.rs801 lines, 28.9 KiBHistoryRawDownload
1//! `forge admin create-user <username> [--admin]`: creates a user from the CLI.
2//! The first user on an instance is always an admin.
3//! `forge admin set-username <current> <NewCase>`: changes only the capitalization of a username.
4//! `forge admin reset-password <username>`: sets a random temporary password and signs the
5//! user out everywhere.
6//! `forge admin trash-list`: lists deleted repos in `data_dir/trash`, oldest first.
7//! `forge admin trash-purge --older-than-days N`: permanently removes trash older than N days.
8//! `forge admin audit-purge --older-than-days N`: deletes audit log entries older than N days.
9//! `forge admin backup --out DIR [--include-key] [--repos-only | --db-only]`: writes a backup
10//! set under DIR (see `docs/backup.md`). Exits non-zero on any failure.
11//! `forge admin fsck [--full]`: git fsck on every repo plus the database integrity check.
12//! `forge admin lfs-gc`: deletes LFS object files no repo links, once they are a day old.
13//! `forge admin backup-verify PATH`: checks a backup set (hashes, bundles, database). Exits
14//! non-zero if any check fails.
15//! `forge admin restore --from SET --data-dir NEW_DIR`: restores a verified backup set into a
16//! new data dir (see `docs/backup.md`).
17//! `forge admin delete-user <username> [--yes]`: deletes an account and moves its content to
18//! the ghost user. Without `--yes` it only prints what would happen and fails.
19//! Actions taken here are recorded in the audit log with actor `cli`.
20
21use std::path::{Path, PathBuf};
22use std::time::Duration;
23
24use forge_core::store::user_delete::{DeletionReport, GHOST_USERNAME};
25use forge_core::{AuditAction, Config, Error, Store, names, token};
26use forge_git::GitEnv;
27
28use crate::admin_client::{notify_live, running_server};
29use crate::audit::{self, Actor, Target};
30use crate::auth::hash_password_async;
31use crate::backup::{
32 BackupOptions, BackupSource, BackupSummary, FsckSummary, Scope, create_backup, restore_backup,
33 run_fsck, verify_backup,
34};
35use crate::boot::{MIN_GIT, find_git};
36use forge_core::store::backup_runs::{RunKind, RunTrigger};
37
38/// Length of a temporary password from `admin reset-password`.
39const TEMPORARY_PASSWORD_CHARS: usize = 20;
40
41const MIN_PASSWORD_CHARS: usize = 12;
42
43/// Creates a user. The password comes from FORGE_PASSWORD, or is prompted for twice on the tty.
44/// Refusal text for admin commands that would give a login to an organization.
45const ORG_NO_LOGIN: &str =
46 "an organization cannot sign in, so it has no password or login name here";
47/// Refusal text for `create-user` on a name that an organization already holds.
48const ORG_NAME_TAKEN: &str = "that name belongs to an organization";
49
50pub async fn create_user(
51 config_path: &Path,
52 username: &str,
53 make_admin: bool,
54) -> forge_core::Result<()> {
55 let (username, _) = names::validate_username(username)?;
56 let pw = read_password()?;
57 if pw.chars().count() < MIN_PASSWORD_CHARS {
58 return Err(Error::Invalid(format!(
59 "password must be at least {MIN_PASSWORD_CHARS} characters"
60 )));
61 }
62
63 let config = Config::load(config_path)?;
64 if let Some(parent) = config.database.parent() {
65 std::fs::create_dir_all(parent)?;
66 }
67 let store = Store::open(&config.database).await?;
68 if store
69 .user_by_username(&username)
70 .await?
71 .is_some_and(|existing| existing.is_org())
72 {
73 return Err(Error::Conflict(ORG_NAME_TAKEN.into()));
74 }
75
76 let hash = hash_password_async(pw).await?;
77 // The first user is always an admin. The insert is atomic, so a concurrent creator falls
78 // through to the ordinary path instead of racing into a second admin.
79 let user = match store.create_first_admin(&username, None, &hash).await? {
80 Some(user) => user,
81 None => {
82 store
83 .create_user(&username, None, &hash, make_admin)
84 .await?
85 }
86 };
87
88 audit::record(
89 &store,
90 None,
91 Actor::Cli,
92 AuditAction::UserCreated,
93 Target {
94 kind: "user",
95 id: &user.id,
96 name: &user.username,
97 },
98 serde_json::json!({ "admin": user.is_admin }),
99 )
100 .await;
101 notify_live(
102 &config,
103 serde_json::json!({ "admin": ["users", "audit"], "user_ids": [user.id] }),
104 )
105 .await;
106 println!(
107 "created user {} (id {}{})",
108 user.username,
109 user.id,
110 if user.is_admin { ", admin" } else { "" }
111 );
112 Ok(())
113}
114
115/// Deletes a user account and moves its authored content to the ghost user. Without `yes` this
116/// is a dry run: it prints what would happen, changes nothing and fails.
117pub async fn delete_user(config_path: &Path, username: &str, yes: bool) -> forge_core::Result<()> {
118 let config = Config::load(config_path)?;
119 let store = Store::open(&config.database).await?;
120 // The id is gone once the account is deleted, so it is read first.
121 let user_id = store.user_by_username(username).await?.map(|u| u.id);
122 let report = delete_user_in(&store, username, yes).await?;
123 if let Some(id) = user_id {
124 notify_live(
125 &config,
126 serde_json::json!({ "admin": ["users", "audit"], "user_ids": [id] }),
127 )
128 .await;
129 }
130 print_deletion_report(&format!("deleted {username}"), &report);
131 Ok(())
132}
133
134/// The store-level part of [`delete_user`]. Returns the report of what was (or, with `yes`
135/// unset, would be) done. Without `yes` nothing is written and an error is returned, so the
136/// command exits nonzero. The ghost account is not created by a dry run.
137pub async fn delete_user_in(
138 store: &Store,
139 username: &str,
140 yes: bool,
141) -> forge_core::Result<DeletionReport> {
142 let user = store
143 .user_by_username(username)
144 .await?
145 .ok_or(Error::NotFound)?;
146 if names::normalize_name(&user.username) == GHOST_USERNAME {
147 return Err(Error::Forbidden(
148 "the ghost account cannot be deleted".into(),
149 ));
150 }
151 let ghost_id = store.user_by_username(GHOST_USERNAME).await?.map(|g| g.id);
152 let preview = store
153 .deletion_preview(&user.id, ghost_id.as_deref())
154 .await?;
155 if !yes {
156 print_deletion_report(&format!("would delete {}", user.username), &preview);
157 return Err(Error::Invalid(format!(
158 "dry run: nothing was deleted. Run again with --yes to delete {}",
159 user.username
160 )));
161 }
162 let ghost = store.ensure_ghost_user().await?;
163 let report = store.delete_user(&user.id, &ghost.id).await?;
164 audit::record(
165 store,
166 None,
167 Actor::Cli,
168 AuditAction::UserDeleted,
169 Target {
170 kind: "user",
171 id: &user.id,
172 name: &user.username,
173 },
174 serde_json::json!({ "reassigned_to": GHOST_USERNAME }),
175 )
176 .await;
177 tracing::info!(user = %user.username, "admin deleted a user account");
178 Ok(report)
179}
180
181fn print_deletion_report(header: &str, report: &DeletionReport) {
182 println!("{header}:");
183 println!(" moved to the ghost user:");
184 for (label, n) in &report.reassigned {
185 println!(" {n} {label}");
186 }
187 println!(" removed with the account:");
188 for (label, n) in &report.removed {
189 println!(" {n} {label}");
190 }
191}
192
193/// Changes the capitalization of an existing user's username. `current` is matched
194/// case-insensitively; `new_display` must differ from it only in case.
195pub async fn set_username(
196 config_path: &Path,
197 current: &str,
198 new_display: &str,
199) -> forge_core::Result<()> {
200 let config = Config::load(config_path)?;
201 let store = Store::open(&config.database).await?;
202 let user = store
203 .user_by_username(current)
204 .await?
205 .ok_or(Error::NotFound)?;
206 if user.is_org() {
207 return Err(Error::Forbidden(ORG_NO_LOGIN.into()));
208 }
209 let display = names::capitalization_change(&user.username, new_display)?;
210 store.set_username_display(&user.id, &display).await?;
211 audit::record(
212 &store,
213 None,
214 Actor::Cli,
215 AuditAction::UsernameChanged,
216 Target {
217 kind: "user",
218 id: &user.id,
219 name: &display,
220 },
221 serde_json::json!({ "from": user.username }),
222 )
223 .await;
224 notify_live(
225 &config,
226 serde_json::json!({
227 "admin": ["users", "audit"],
228 "user_ids": [user.id],
229 "account_ids": [user.id],
230 }),
231 )
232 .await;
233 println!("renamed {} to {}", user.username, display);
234 Ok(())
235}
236
237/// Sets a random temporary password for `username`, revokes every session of that user and
238/// prints the password. Returns the password. Nothing else changes.
239pub async fn reset_password(config_path: &Path, username: &str) -> forge_core::Result<()> {
240 let config = Config::load(config_path)?;
241 let store = Store::open(&config.database).await?;
242 let user_id = store.user_by_username(username).await?.map(|u| u.id);
243 let (password, display) = reset_password_in(&store, username).await?;
244 if let Some(id) = user_id {
245 notify_live(
246 &config,
247 serde_json::json!({
248 "admin": ["users", "audit"],
249 "user_ids": [id],
250 "account_ids": [id],
251 }),
252 )
253 .await;
254 }
255 println!("temporary password for {display}: {password}");
256 println!("all sessions of {display} were signed out; change this password after logging in");
257 Ok(())
258}
259
260/// The store-level part of [`reset_password`]. Returns the new password and the display name.
261pub async fn reset_password_in(
262 store: &Store,
263 username: &str,
264) -> forge_core::Result<(String, String)> {
265 let user = store
266 .user_by_username(username)
267 .await?
268 .ok_or(Error::NotFound)?;
269 if user.is_org() {
270 return Err(Error::Forbidden(ORG_NO_LOGIN.into()));
271 }
272 if names::normalize_name(&user.username) == GHOST_USERNAME {
273 return Err(Error::Forbidden("the ghost account has no password".into()));
274 }
275 let password = token::random_readable(TEMPORARY_PASSWORD_CHARS);
276 let hash = hash_password_async(password.clone()).await?;
277 store.set_password_hash(&user.id, &hash).await?;
278 store.delete_user_sessions(&user.id).await?;
279 audit::record(
280 store,
281 None,
282 Actor::Cli,
283 AuditAction::PasswordResetByAdmin,
284 Target {
285 kind: "user",
286 id: &user.id,
287 name: &user.username,
288 },
289 serde_json::Value::Null,
290 )
291 .await;
292 tracing::info!(user = %user.username, "admin reset a password and revoked sessions");
293 Ok((password, user.username))
294}
295
296/// Prints each trash entry as `<deleted_at unix seconds>\t<repo id>\t<path>`.
297pub fn trash_list(config_path: &Path) -> forge_core::Result<()> {
298 let config = Config::load(config_path)?;
299 let entries = forge_git::repo::list_trash(&config.data_dir)?;
300 if entries.is_empty() {
301 println!("trash is empty");
302 }
303 for entry in entries {
304 println!(
305 "{}\t{}\t{}",
306 entry.deleted_at,
307 entry.repo_id,
308 entry.path.display()
309 );
310 }
311 Ok(())
312}
313
314/// Permanently removes trash entries deleted at least `days` days ago.
315pub fn trash_purge(config_path: &Path, days: u64) -> forge_core::Result<()> {
316 let config = Config::load(config_path)?;
317 let now = std::time::SystemTime::now()
318 .duration_since(std::time::UNIX_EPOCH)
319 .map(|d| d.as_secs())
320 .map_err(|e| Error::Invalid(format!("system clock is before 1970: {e}")))?;
321 let older_than = days.saturating_mul(86_400);
322 let removed = forge_git::repo::purge_trash(&config.data_dir, older_than, now)?;
323 for path in &removed {
324 tracing::info!(path = %path.display(), "purged trashed repository");
325 println!("purged {}", path.display());
326 }
327 println!("purged {} trashed repositories", removed.len());
328 Ok(())
329}
330
331/// Deletes audit log entries older than `days` days. The purge itself is logged to tracing, not
332/// to the audit log, so the log it shrinks does not record its own removal.
333pub async fn audit_purge(config_path: &Path, days: u64) -> forge_core::Result<()> {
334 let config = Config::load(config_path)?;
335 let store = Store::open(&config.database).await?;
336 let cutoff = forge_core::time::stamp_ago(Duration::from_secs(days.saturating_mul(86_400)));
337 let removed = store.purge_audit_before(&cutoff).await?;
338 tracing::info!(removed, cutoff = %cutoff, "purged audit log entries");
339 if removed > 0 {
340 notify_live(&config, serde_json::json!({ "admin": ["audit"] })).await;
341 }
342 println!("purged {removed} audit log entries older than {days} days");
343 Ok(())
344}
345
346fn read_password() -> forge_core::Result<String> {
347 if let Ok(pw) = std::env::var("FORGE_PASSWORD") {
348 return Ok(pw);
349 }
350 let first = rpassword::prompt_password("Password: ")?;
351 let second = rpassword::prompt_password("Repeat password: ")?;
352 if first != second {
353 return Err(Error::Invalid("passwords do not match".to_string()));
354 }
355 Ok(first)
356}
357
358/// Parses the flags of `admin backup`. `--out DIR` is required. `--repos-only` and `--db-only`
359/// cannot be combined. The key is left out unless `--include-key` is given.
360pub fn parse_backup_args(args: &[&str]) -> std::result::Result<BackupOptions, String> {
361 let mut out = None;
362 let mut include_key = false;
363 let mut scope = None;
364 let mut rest = args.iter();
365 while let Some(arg) = rest.next() {
366 match *arg {
367 "--out" => {
368 let dir = rest.next().ok_or("--out needs a directory")?;
369 out = Some(PathBuf::from(dir));
370 }
371 "--include-key" => include_key = true,
372 "--repos-only" | "--db-only" => {
373 let wanted = if *arg == "--repos-only" {
374 Scope::ReposOnly
375 } else {
376 Scope::DbOnly
377 };
378 if scope.replace(wanted).is_some() {
379 return Err("--repos-only and --db-only cannot be combined".into());
380 }
381 }
382 other => return Err(format!("unknown backup option: {other}")),
383 }
384 }
385 let out = out.ok_or("backup needs --out DIR")?;
386 Ok(BackupOptions {
387 out,
388 include_key,
389 scope: scope.unwrap_or(Scope::All),
390 })
391}
392
393/// Writes a backup set (`admin backup`). If the server is running, it writes the set and records
394/// the run (trigger `cli`). Otherwise the database is opened directly, so the server must be
395/// stopped.
396pub async fn backup(config_path: &Path, opts: BackupOptions) -> forge_core::Result<()> {
397 let config = Config::load(config_path)?;
398 let out = std::path::absolute(&opts.out)?;
399 if let Some(server) = running_server(&config).await? {
400 let body = serde_json::json!({
401 "out": out,
402 "include_key": opts.include_key,
403 "scope": opts.scope,
404 });
405 let summary: BackupSummary = server.post("/internal/admin/backup", &body).await?;
406 print_backup_summary(&summary);
407 return Ok(());
408 }
409 let data_dir = config.data_dir.canonicalize()?;
410 let store = Store::open(&config.database).await?;
411 let git = GitEnv {
412 git_bin: find_git(),
413 data_dir,
414 };
415 forge_git::version::require_min_version(&git, MIN_GIT).await?;
416 let source = BackupSource {
417 store: store.clone(),
418 git,
419 base_url: config.base_url.clone(),
420 };
421 let target_name = out.to_string_lossy().into_owned();
422 audit::record(
423 &store,
424 None,
425 Actor::Cli,
426 AuditAction::BackupStarted,
427 Target {
428 kind: "backup",
429 id: "",
430 name: &target_name,
431 },
432 serde_json::json!({ "trigger": "cli" }),
433 )
434 .await;
435 let run = store.start_run(RunKind::Backup, RunTrigger::Cli).await?;
436 let outcome = create_backup(&source, &BackupOptions { out, ..opts }).await;
437 let (ok, path, bytes, error) = match &outcome {
438 Ok(summary) => (
439 true,
440 Some(summary.path.to_string_lossy().into_owned()),
441 Some(summary.bytes),
442 None,
443 ),
444 Err(e) => (false, None, None, Some(e.to_string())),
445 };
446 if let Err(e) = store
447 .finish_run(&run, ok, path.as_deref(), bytes, error.as_deref())
448 .await
449 {
450 tracing::error!(error = %e, "could not record the outcome of an offline backup");
451 }
452 let summary = outcome?;
453 tracing::info!(path = %summary.path.display(), bytes = summary.bytes, "backup set written");
454 print_backup_summary(&summary);
455 Ok(())
456}
457
458fn print_backup_summary(summary: &BackupSummary) {
459 println!("backup written: {}", summary.path.display());
460 println!(
461 " scope: {:?}, files: {} ({} bytes)",
462 summary.scope, summary.files, summary.bytes
463 );
464 println!(
465 " repos: {} (bundles: {}, empty: {})",
466 summary.repos, summary.bundles, summary.empty_repos
467 );
468 match summary.schema_version {
469 Some(v) => println!(" database: snapshot at schema version {v}"),
470 None => println!(" database: not included"),
471 }
472 println!(
473 " key: {}",
474 if summary.key_included {
475 "included (keep this set private)"
476 } else {
477 "not included (back up forge.key separately)"
478 }
479 );
480}
481
482/// Runs `git fsck` on every repo and the database integrity check (`admin fsck [--full]`). The
483/// server runs it when it is up, otherwise the database is opened directly. Fails when any check
484/// fails.
485pub async fn fsck(config_path: &Path, full: bool) -> forge_core::Result<()> {
486 let config = Config::load(config_path)?;
487 let summary: FsckSummary = match running_server(&config).await? {
488 Some(server) => {
489 server
490 .post("/internal/admin/fsck", &serde_json::json!({ "full": full }))
491 .await?
492 }
493 None => {
494 let store = Store::open(&config.database).await?;
495 let git = GitEnv {
496 git_bin: find_git(),
497 data_dir: config.data_dir.canonicalize()?,
498 };
499 audit::record(
500 &store,
501 None,
502 Actor::Cli,
503 AuditAction::FsckStarted,
504 Target {
505 kind: "fsck",
506 id: "",
507 name: "",
508 },
509 serde_json::json!({ "trigger": "cli", "full": full }),
510 )
511 .await;
512 let run = store.start_run(RunKind::Fsck, RunTrigger::Cli).await?;
513 let outcome = run_fsck(&store, &git, full).await;
514 let (ok, error) = match &outcome {
515 Ok(summary) if summary.is_ok() => (true, None),
516 Ok(summary) => (false, Some(summary.problems.join("\n"))),
517 Err(e) => (false, Some(e.to_string())),
518 };
519 if let Err(e) = store
520 .finish_run(&run, ok, None, None, error.as_deref())
521 .await
522 {
523 tracing::error!(error = %e, "could not record the outcome of an offline fsck");
524 }
525 outcome?
526 }
527 };
528 println!(
529 "fsck ({}): {} repos checked",
530 if summary.full { "full" } else { "quick" },
531 summary.repos
532 );
533 for problem in &summary.problems {
534 println!(" problem: {problem}");
535 }
536 if summary.is_ok() {
537 println!(" database: integrity check ok");
538 Ok(())
539 } else {
540 Err(Error::Invalid(format!(
541 "fsck found {} problem(s)",
542 summary.problems.len()
543 )))
544 }
545}
546
547/// Deletes unlinked LFS objects and abandoned upload temp files (`admin lfs-gc`). The server runs
548/// it when it is up, otherwise the database is opened directly.
549pub async fn lfs_gc(config_path: &Path) -> forge_core::Result<()> {
550 let config = Config::load(config_path)?;
551 let summary: crate::lfs::gc::GcSummary = match running_server(&config).await? {
552 Some(server) => {
553 server
554 .post("/internal/admin/lfs-gc", &serde_json::json!({}))
555 .await?
556 }
557 None => {
558 let store = Store::open(&config.database).await?;
559 crate::lfs::gc::gc(&store, &config.data_dir, crate::lfs::gc::GC_MIN_AGE).await?
560 }
561 };
562 println!(
563 "lfs-gc: {} object file(s) checked, {} removed ({} bytes), {} abandoned upload(s) removed",
564 summary.checked, summary.removed, summary.bytes_freed, summary.temp_removed
565 );
566 Ok(())
567}
568
569/// Verifies a backup set (`admin backup-verify`). Prints every problem found and fails if there
570/// is any. Scratch repos go next to the set, not in `/tmp`.
571pub async fn backup_verify(path: &Path) -> forge_core::Result<()> {
572 let path = std::path::absolute(path)?;
573 let parent = path
574 .parent()
575 .ok_or_else(|| Error::Invalid("the backup set has no parent directory".into()))?
576 .to_path_buf();
577 // Git runs with the set's parent as its HOME, so no user gitconfig is read.
578 let git = GitEnv {
579 git_bin: find_git(),
580 data_dir: parent,
581 };
582 forge_git::version::require_min_version(&git, MIN_GIT).await?;
583 let report = verify_backup(&path, &git).await?;
584 println!("backup set: {}", report.path.display());
585 println!(
586 " scope: {:?}, files: {} ({} bytes)",
587 report.scope, report.files, report.bytes
588 );
589 println!(
590 " repos: {} (bundles verified: {}, empty: {})",
591 report.repos, report.bundles_verified, report.empty_repos
592 );
593 if let Some(v) = report.schema_version {
594 println!(" database: schema version {v}, integrity_check ok");
595 }
596 if report.is_ok() {
597 println!("result: OK");
598 return Ok(());
599 }
600 for problem in &report.problems {
601 println!(" problem: {problem}");
602 }
603 println!("result: FAILED ({} problem(s))", report.problems.len());
604 Err(Error::Invalid(format!(
605 "backup set failed verification: {}",
606 report.path.display()
607 )))
608}
609
610/// Parses the flags of `admin restore`: `--from SET --data-dir NEW_DIR`, both required.
611pub fn parse_restore_args(args: &[&str]) -> std::result::Result<(PathBuf, PathBuf), String> {
612 let mut from = None;
613 let mut data_dir = None;
614 let mut rest = args.iter();
615 while let Some(arg) = rest.next() {
616 match *arg {
617 "--from" => {
618 let set = rest.next().ok_or("--from needs a backup set path")?;
619 from = Some(PathBuf::from(set));
620 }
621 "--data-dir" => {
622 let dir = rest.next().ok_or("--data-dir needs a directory")?;
623 data_dir = Some(PathBuf::from(dir));
624 }
625 other => return Err(format!("unknown restore option: {other}")),
626 }
627 }
628 match (from, data_dir) {
629 (Some(from), Some(dir)) => Ok((from, dir)),
630 _ => Err("restore needs --from SET and --data-dir NEW_DIR".into()),
631 }
632}
633
634/// Restores a verified backup set into a new data dir (`admin restore`). Needs no config and no
635/// running server. The restored database is written to `NEW_DIR/forge.db`, the layout a fresh
636/// install uses. Point `database` in the config at it before starting the server.
637pub async fn restore(set: &Path, new_data_dir: &Path) -> forge_core::Result<()> {
638 let git_bin = find_git();
639 let set_abs = std::path::absolute(set)?;
640 let probe = GitEnv {
641 git_bin: git_bin.clone(),
642 data_dir: set_abs.parent().unwrap_or(&set_abs).to_path_buf(),
643 };
644 forge_git::version::require_min_version(&probe, MIN_GIT).await?;
645 match restore_backup(&set_abs, new_data_dir, &git_bin).await {
646 Ok(report) => {
647 println!("restored into: {}", report.data_dir.display());
648 println!(" database: {}", report.database.display());
649 println!(
650 " repos: {} from bundles, {} empty",
651 report.repos, report.empty_repos
652 );
653 println!(
654 " key: {}",
655 if report.key_restored {
656 "restored (forge.key, mode 0600)"
657 } else {
658 "NOT restored"
659 }
660 );
661 for warning in &report.warnings {
662 println!("WARNING: {warning}");
663 }
664 println!(
665 "next: set `database = \"{}\"` and `data_dir = \"{}\"` in the config,",
666 report.database.display(),
667 report.data_dir.display()
668 );
669 println!(" then run `forge admin fsck --full` before starting the server.");
670 Ok(())
671 }
672 Err(e) => {
673 eprintln!("RESTORE FAILED: {e}");
674 if new_data_dir.exists() {
675 eprintln!(
676 "The directory {} was left as it is for inspection. Do not start the server from it.",
677 new_data_dir.display()
678 );
679 }
680 Err(e)
681 }
682 }
683}
684
685#[cfg(test)]
686mod tests {
687 use super::*;
688 use crate::auth::verify_password_async;
689
690 #[tokio::test]
691 async fn reset_password_sets_a_20_char_password_and_revokes_sessions() {
692 let dir = tempfile::tempdir().unwrap();
693 let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
694 let hash = hash_password_async("the original password".into())
695 .await
696 .unwrap();
697 let user = store
698 .create_user("Tahinli", None, &hash, false)
699 .await
700 .unwrap();
701 let expiry = forge_core::time::stamp_after(std::time::Duration::from_secs(3600));
702 store
703 .create_session(&user.id, "h1", "c1", &expiry, None, None)
704 .await
705 .unwrap();
706 store
707 .create_session(&user.id, "h2", "c2", &expiry, None, None)
708 .await
709 .unwrap();
710
711 let (password, display) = reset_password_in(&store, "tahinli").await.unwrap();
712 assert_eq!(password.chars().count(), TEMPORARY_PASSWORD_CHARS);
713 assert_eq!(display, "Tahinli");
714 assert!(store.list_sessions(&user.id).await.unwrap().is_empty());
715
716 let fresh = store.user_by_id(&user.id).await.unwrap().unwrap();
717 assert!(
718 verify_password_async(password, fresh.password_hash.clone())
719 .await
720 .unwrap()
721 );
722 let old_ok = verify_password_async("the original password".into(), fresh.password_hash)
723 .await
724 .unwrap();
725 assert!(!old_ok);
726 }
727
728 #[tokio::test]
729 async fn delete_user_dry_run_changes_nothing() {
730 let dir = tempfile::tempdir().unwrap();
731 let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
732 store.create_user("Dana", None, "hash", true).await.unwrap();
733 store
734 .create_user("Tahinli", None, "hash", false)
735 .await
736 .unwrap();
737
738 let dry = delete_user_in(&store, "tahinli", false).await;
739 assert!(matches!(dry, Err(Error::Invalid(_))), "{dry:?}");
740 assert!(store.user_by_username("tahinli").await.unwrap().is_some());
741 assert!(
742 store
743 .user_by_username(GHOST_USERNAME)
744 .await
745 .unwrap()
746 .is_none(),
747 "a dry run must not create the ghost account"
748 );
749
750 delete_user_in(&store, "tahinli", true).await.unwrap();
751 assert!(store.user_by_username("tahinli").await.unwrap().is_none());
752 assert!(
753 store
754 .user_by_username(GHOST_USERNAME)
755 .await
756 .unwrap()
757 .is_some()
758 );
759 }
760
761 #[tokio::test]
762 async fn reset_password_for_an_unknown_user_is_not_found() {
763 let dir = tempfile::tempdir().unwrap();
764 let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
765 let err = reset_password_in(&store, "nobody").await;
766 assert!(matches!(err, Err(Error::NotFound)));
767 }
768}
769
770#[cfg(test)]
771mod org_account_tests {
772 use super::*;
773
774 /// An organization has no password to reset, and deleting its last owner is refused with the
775 /// message the admin page and the CLI show.
776 #[tokio::test]
777 async fn org_accounts_refuse_password_reset_and_last_owner_deletion() {
778 let dir = tempfile::tempdir().unwrap();
779 let store = Store::open(&dir.path().join("forge.db")).await.unwrap();
780 store.create_user("Dana", None, "hash", true).await.unwrap();
781 let tahinli = store
782 .create_user("Tahinli", None, "hash", false)
783 .await
784 .unwrap();
785 let org = store.create_org("acme", &tahinli.id).await.unwrap();
786
787 assert!(matches!(
788 reset_password_in(&store, "acme").await,
789 Err(Error::Forbidden(_))
790 ));
791 let untouched = store.user_by_id(&org.id).await.unwrap().unwrap();
792 assert_eq!(untouched.password_hash, "!org");
793
794 let refused = delete_user_in(&store, "tahinli", true).await;
795 assert!(
796 matches!(&refused, Err(Error::Conflict(msg)) if msg == forge_core::store::user_delete::LAST_ORG_OWNER),
797 "{refused:?}"
798 );
799 assert!(store.user_by_id(&tahinli.id).await.unwrap().is_some());
800 }
801}