use std::collections::HashMap; use forge_core::server_settings::Group; use forge_core::store::backup_runs::{BackupRun, RunKind}; use forge_core::{AuditAction, Error, Store, User}; use serde::Deserialize; use topcoat::Result; use topcoat::context::{Cx, context}; use topcoat::router::content::Form; use topcoat::router::error::{forbidden, see_other}; use topcoat::router::response::Response; use topcoat::router::{page, query_params, route}; use topcoat::view::{View, component, view}; use crate::audit::{self, Actor, Target}; use crate::auth::check_csrf; use crate::backup::scheduler::{configured_dir, start_manual}; use crate::i18n::admin::{self as g, K}; use crate::i18n::{self, Key, Lang}; use crate::live::{Topic, stream_changes}; use crate::pages::admin_server::{ BACKUP_KEYS, Row, notice_of, reset_form, save_topic, setting_lines, setting_rows, with_notice, }; use crate::pages::admin_users::admin_only; use crate::state::AppState; use crate::views::parts::{RailItem, head, post_act, rail}; use crate::views::{alert, enc, human_size, rel_time, shell, stamp_unix}; const RUN_LIMIT: u32 = 20; #[query_params(error = bad_request)] struct NoticeQuery { notice: Option, } #[derive(Deserialize)] struct RunForm { #[serde(default)] csrf: String, } struct RunRow { kind: String, trigger: String, started: String, duration: String, size: String, status: String, detail: String, } fn duration_text(run: &BackupRun) -> String { let start = stamp_unix(&run.started_at); let Some(end) = run.finished_at.as_deref().map(stamp_unix) else { return "-".to_owned(); }; let secs = (end - start).max(0); if secs < 60 { format!("{secs}s") } else { format!("{}m {}s", secs / 60, secs % 60) } } fn run_row(run: &BackupRun, lang: Lang) -> RunRow { let (status, detail) = match (run.finished_at.is_some(), run.ok) { (false, _) => (g::t(lang, K::StatusInProgress).to_owned(), String::new()), (true, Some(true)) => (g::t(lang, K::StatusOk).to_owned(), String::new()), (true, _) => ( g::t(lang, K::StatusFailed).to_owned(), run.error.clone().unwrap_or_default(), ), }; RunRow { kind: g::kind_name(lang, run.kind).to_owned(), trigger: g::trigger_name(lang, run.trigger).to_owned(), started: run.started_at.clone(), duration: duration_text(run), size: run.bytes.map(|b| human_size(lang, b)).unwrap_or_default(), status, detail, } } #[component] pub(crate) async fn backups_rail(cx: &Cx, lang: Lang, current: &'static str) -> Result { let items = vec![ RailItem { name: g::t(lang, K::Backups).to_owned(), val: String::new(), href: "/admin/backups".to_owned(), current: current == "backups", }, RailItem { name: g::t(lang, K::Replication).to_owned(), val: String::new(), href: "/admin/replication".to_owned(), current: current == "replication", }, ]; Ok(view! { rail(label: g::t(lang, K::Backups), items: items) }) } #[component] async fn backups_view( cx: &Cx, lang: Lang, csrf: String, enabled: bool, settings: Vec, rows: Vec, running: Option, notice: Option, ) -> Result { let backup_running = matches!(running, Some(RunKind::Backup)).then(|| g::running_line(lang, RunKind::Backup)); let fsck_running = matches!(running, Some(RunKind::Fsck)).then(|| g::running_line(lang, RunKind::Fsck)); Ok(view! { head(title: g::t(lang, K::Backups),
post_act(label: g::t(lang, K::RunFsckNow), action: "/admin/backups/fsck", csrf: csrf.as_str()) ) if let Some(message) = notice {

(message.as_str())

}
backups_rail(lang: lang, current: "backups")
if let Some(line) = backup_running {

(line)

} if let Some(line) = fsck_running {

(line)

}

(g::t(lang, K::Settings))

if !enabled {

(g::t(lang, K::ScheduledBackupsOff))

}
setting_lines(lang: lang, rows: settings)
reset_form(csrf: csrf.clone(), back: "/admin/backups".to_owned())

(g::t(lang, K::RecentRuns))

if rows.is_empty() {

(g::t(lang, K::NoRunsYet))

} else { for row in rows.into_iter() {
(row.kind.as_str()) " · " (row.trigger.as_str()) (row.status.as_str()) " · " rel_time(lang: lang, stamp: row.started.as_str()) " · " (row.duration.as_str()) if !row.size.is_empty() { " · " (row.size.as_str()) }
if !row.detail.is_empty() { alert(message: row.detail.as_str()) } } }
}) } async fn runs_fingerprint(store: &Store, running: Option) -> Result { let runs = store.recent_runs(RUN_LIMIT).await?; Ok(format!("{running:?}|{runs:?}")) } #[route(GET "/admin/backups/events")] async fn backups_events(cx: &Cx) -> Result { admin_only(cx).await?; let state = context::(cx); let store = state.store.clone(); let jobs = state.jobs.clone(); stream_changes( cx, crate::live::admin(), &[Topic::AdminBackups], move || { let store = store.clone(); let running = jobs.running(); async move { runs_fingerprint(&store, running).await } }, ) .await } #[page("/admin/backups")] async fn backups_page(cx: &Cx) -> Result { let viewer = admin_only(cx).await?; let query = query_params::(cx)?; let state = context::(cx); let lang = i18n::lang(cx, Some(&viewer.0)); let runs = state.store.recent_runs(RUN_LIMIT).await?; let rows: Vec = runs.iter().map(|run| run_row(run, lang)).collect(); let running = state.jobs.running(); let settings = setting_rows(state, lang, BACKUP_KEYS).await?; let enabled = state.config.backup.enabled(); let csrf = viewer.1.csrf_token.clone(); let title = g::t(lang, K::Backups); Ok(view! { shell(title: title, viewer: Some(&viewer), backups_view(lang: lang, csrf: csrf, enabled: enabled, settings: settings, rows: rows, running: running, notice: query.notice.clone())) }) } #[route(POST "/admin/backups")] async fn backups_save(cx: &Cx, Form(form): Form>) -> Result { let viewer = admin_only(cx).await?; if !check_csrf(&viewer.1, form.get("csrf").map_or("", String::as_str)) { return Err(forbidden().into()); } let lang = i18n::lang(cx, Some(&viewer.0)); let state = context::(cx); let notice = notice_of( lang, save_topic( cx, state, &viewer.0, Group::Backups, BACKUP_KEYS, form, lang, ) .await, ); Err(see_other(with_notice("/admin/backups", ¬ice)).into()) } #[route(POST "/admin/backups/run")] async fn backups_run(cx: &Cx, Form(form): Form) -> Result { start_run(cx, form.csrf, RunKind::Backup).await } #[route(POST "/admin/backups/fsck")] async fn backups_fsck(cx: &Cx, Form(form): Form) -> Result { start_run(cx, form.csrf, RunKind::Fsck).await } async fn start_run(cx: &Cx, csrf: String, kind: RunKind) -> Result { let viewer = admin_only(cx).await?; if !check_csrf(&viewer.1, &csrf) { return Err(forbidden().into()); } let lang = i18n::lang(cx, Some(&viewer.0)); let state = context::(cx); let notice = match launch(cx, state, &viewer.0, kind, lang).await { Ok(()) => g::started_notice(lang, kind), Err(e) => match e { Error::Conflict(message) => message, other => other.to_string(), }, }; let location = format!("/admin/backups?notice={}", enc(¬ice)); Err(see_other(&location).into()) } async fn launch( cx: &Cx, state: &AppState, user: &User, kind: RunKind, lang: Lang, ) -> forge_core::Result<()> { if !state.config.backup.enabled() { return Err(Error::Config( g::t(lang, K::ErrBackupsNotConfigured).to_owned(), )); } configured_dir(state)?; let guard = state.jobs.claim(kind)?; let (action, target_kind) = match kind { RunKind::Backup => (AuditAction::BackupStarted, "backup"), RunKind::Fsck => (AuditAction::FsckStarted, "fsck"), }; audit::record( &state.store, Some(cx), Actor::User(user), action, Target { kind: target_kind, id: "", name: "", }, serde_json::json!({ "trigger": "manual" }), ) .await; start_manual(state, guard) } #[cfg(test)] mod tests { use super::*; use forge_core::model::Visibility; use forge_core::store::backup_runs::RunTrigger; use topcoat::router::request::Request; use topcoat::router::{Body, Router, to_bytes}; use crate::auth::SESSION_COOKIE; use crate::test_support::{app_router, create_session, test_state}; const ADMIN_TOKEN: &str = "backups-admin-session"; const USER_TOKEN: &str = "backups-user-session"; const CSRF: &str = "backups-csrf"; struct Fixture { _dir: tempfile::TempDir, router: Router, state: AppState, } async fn fixture(configured: bool) -> Fixture { let dir = tempfile::tempdir().expect("tempdir"); let data_dir = dir.path().join("data"); std::fs::create_dir_all(&data_dir).expect("data dir"); let mut state = test_state(&data_dir).await; let mut config = crate::test_support::test_config(&data_dir); if configured { config.backup.dir = dir.path().join("out"); config.backup.keep = 2; } state.config = std::sync::Arc::new(config); let admin = state .store .create_user("root", None, "h", true) .await .expect("admin"); let user = state .store .create_user("plain", None, "h", false) .await .expect("user"); create_session(&state.store, &admin.id, ADMIN_TOKEN, CSRF).await; create_session(&state.store, &user.id, USER_TOKEN, CSRF).await; let repo = state .store .create_repo(&admin.id, "demo", "", Visibility::Private, "main") .await .expect("repo"); let path = forge_git::repo::repo_path(&data_dir, &repo.id).expect("path"); forge_git::repo::init_bare(&state.git, &path, "main") .await .expect("init"); let router = app_router(state.clone()); Fixture { _dir: dir, router, state, } } async fn send( router: &Router, method: &str, uri: &str, token: Option<&str>, form: Option, ) -> (u16, String) { let mut builder = Request::builder().method(method).uri(uri); if let Some(token) = token { builder = builder.header("cookie", format!("__Host-{SESSION_COOKIE}={token}")); } let body = match form { Some(form) => { builder = builder.header("content-type", "application/x-www-form-urlencoded"); Body::from(form) } None => Body::empty(), }; let res = router.handle(builder.body(body).expect("request")).await; let status = res.status().as_u16(); let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body"); (status, String::from_utf8_lossy(&bytes).into_owned()) } #[tokio::test] async fn backups_page_and_manual_runs() { let fx = fixture(true).await; let (anon, _) = send(&fx.router, "GET", "/admin/backups", None, None).await; assert_eq!(anon, 404, "anonymous page"); let (user, _) = send(&fx.router, "GET", "/admin/backups", Some(USER_TOKEN), None).await; assert_eq!(user, 404, "plain user page"); let (posted, _) = send( &fx.router, "POST", "/admin/backups/run", Some(USER_TOKEN), Some(format!("csrf={CSRF}")), ) .await; assert_eq!(posted, 404, "plain user run"); let held = fx.state.jobs.claim(RunKind::Backup).expect("claim"); let (status, _) = send( &fx.router, "POST", "/admin/backups/run", Some(ADMIN_TOKEN), Some(format!("csrf={CSRF}")), ) .await; assert_eq!(status, 303, "busy run"); let (_, page) = send( &fx.router, "GET", "/admin/backups?notice=already%20running%3A%20x", Some(ADMIN_TOKEN), None, ) .await; assert!(page.contains("already running"), "busy notice"); assert!( fx.state .store .recent_runs(5) .await .expect("runs") .is_empty(), "busy run records nothing" ); drop(held); let (bad, _) = send( &fx.router, "POST", "/admin/backups/fsck", Some(ADMIN_TOKEN), Some("csrf=wrong".into()), ) .await; assert_eq!(bad, 403, "fsck without csrf"); let (status, _) = send( &fx.router, "POST", "/admin/backups/fsck", Some(ADMIN_TOKEN), Some(format!("csrf={CSRF}")), ) .await; assert_eq!(status, 303, "fsck with csrf"); let mut runs = Vec::new(); for _ in 0..500 { runs = fx.state.store.recent_runs(5).await.expect("runs"); if runs.iter().any(|r| r.finished_at.is_some()) { break; } tokio::time::sleep(std::time::Duration::from_millis(20)).await; } assert_eq!(runs.len(), 1, "{runs:?}"); assert_eq!(runs[0].kind, RunKind::Fsck, "fsck run kind"); assert_eq!(runs[0].trigger, RunTrigger::Manual, "fsck run trigger"); assert_eq!(runs[0].ok, Some(true), "fsck run result"); let audit = fx .state .store .list_audit(&Default::default(), None, 10) .await .expect("audit"); assert!( audit.iter().any(|e| e.action == AuditAction::FsckStarted), "fsck is audited" ); let (_, page) = send(&fx.router, "GET", "/admin/backups", Some(ADMIN_TOKEN), None).await; assert!(page.contains("fsck"), "fsck run is listed"); let mut config = (*fx.state.config).clone(); config.backup.healthcheck_url = "https://hc.example.test/ping/SECRET-TOKEN".into(); let mut state = fx.state.clone(); state.config = std::sync::Arc::new(config); let router = app_router(state.clone()); let id = state .store .start_run(RunKind::Backup, RunTrigger::Schedule) .await .expect("start"); state .store .finish_run(&id, false, None, None, Some("disk full")) .await .expect("finish"); let (status, body) = send(&router, "GET", "/admin/backups", Some(ADMIN_TOKEN), None).await; assert_eq!(status, 200); assert!(body.contains("schedule")); assert!(body.contains("disk full")); assert!( !body.contains("hc.example.test"), "a healthcheck URL is a secret and is never rendered" ); assert!( !body.contains("SECRET-TOKEN"), "the healthcheck token must not be shown" ); assert!(body.contains("Run backup now")); assert!(body.contains("Run fsck now")); } #[tokio::test] async fn unconfigured_instance_refuses_manual_runs() { let fx = fixture(false).await; let (status, _) = send( &fx.router, "POST", "/admin/backups/run", Some(ADMIN_TOKEN), Some(format!("csrf={CSRF}")), ) .await; assert_eq!(status, 303); assert!( fx.state .store .recent_runs(5) .await .expect("runs") .is_empty() ); assert_eq!(fx.state.jobs.running(), None); } }