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