forge
Clone
https://git.tahinli.com/Tahinli/forge.git
0 watching·0 forks·Rust·AGPL-3.0·7.1 MiB·490f099·Tahinli·7 hours ago·322 commits
| 1 | //! Page: backups (`/admin/backups`). Instance admins only; anyone else gets 404. |
| 2 | //! |
| 3 | //! Shows the backup settings as a settings topic, saved here (`POST /admin/backups`, the same rows |
| 4 | //! and save as the server settings), then the last 20 backup and fsck runs, and two POST buttons |
| 5 | //! that start a run in the background. A button press is audited and redirects back here with a |
| 6 | //! notice. The rail beside the page holds Replication too. |
| 7 | |
| 8 | use std::collections::HashMap; |
| 9 | |
| 10 | use forge_core::server_settings::Group; |
| 11 | use forge_core::store::backup_runs::{BackupRun, RunKind}; |
| 12 | use forge_core::{AuditAction, Error, Store, User}; |
| 13 | use serde::Deserialize; |
| 14 | use topcoat::Result; |
| 15 | use topcoat::context::{Cx, context}; |
| 16 | use topcoat::router::content::Form; |
| 17 | use topcoat::router::error::{forbidden, see_other}; |
| 18 | use topcoat::router::response::Response; |
| 19 | use topcoat::router::{page, query_params, route}; |
| 20 | use topcoat::view::{View, component, view}; |
| 21 | |
| 22 | use crate::audit::{self, Actor, Target}; |
| 23 | use crate::auth::check_csrf; |
| 24 | use crate::backup::scheduler::{configured_dir, start_manual}; |
| 25 | use crate::i18n::admin::{self as g, K}; |
| 26 | use crate::i18n::{self, Key, Lang}; |
| 27 | use crate::live::{Topic, stream_changes}; |
| 28 | use crate::pages::admin_server::{ |
| 29 | BACKUP_KEYS, Row, notice_of, reset_form, save_topic, setting_lines, setting_rows, with_notice, |
| 30 | }; |
| 31 | use crate::pages::admin_users::admin_only; |
| 32 | use crate::pages::issues_list::stamp_unix; |
| 33 | use crate::state::AppState; |
| 34 | use crate::views::parts::{RailItem, head, post_act, rail}; |
| 35 | use crate::views::{alert, enc, rel_time, shell}; |
| 36 | |
| 37 | /// Runs shown on the page. |
| 38 | const RUN_LIMIT: u32 = 20; |
| 39 | |
| 40 | #[query_params(error = bad_request)] |
| 41 | pub(crate) struct NoticeQuery { |
| 42 | notice: Option<String>, |
| 43 | } |
| 44 | |
| 45 | #[derive(Deserialize)] |
| 46 | struct RunForm { |
| 47 | #[serde(default)] |
| 48 | csrf: String, |
| 49 | } |
| 50 | |
| 51 | /// One table row, already formatted. |
| 52 | struct RunRow { |
| 53 | kind: String, |
| 54 | trigger: String, |
| 55 | started: String, |
| 56 | duration: String, |
| 57 | size: String, |
| 58 | status: String, |
| 59 | detail: String, |
| 60 | } |
| 61 | |
| 62 | /// `"512 B"`, `"12.3 KiB"`, `"4.0 MiB"` and so on. |
| 63 | fn human_bytes(bytes: u64) -> String { |
| 64 | const UNITS: [&str; 4] = ["KiB", "MiB", "GiB", "TiB"]; |
| 65 | if bytes < 1024 { |
| 66 | return format!("{bytes} B"); |
| 67 | } |
| 68 | let mut value = bytes as f64 / 1024.0; |
| 69 | let mut unit = 0; |
| 70 | while value >= 1024.0 && unit + 1 < UNITS.len() { |
| 71 | value /= 1024.0; |
| 72 | unit += 1; |
| 73 | } |
| 74 | format!("{value:.1} {}", UNITS[unit]) |
| 75 | } |
| 76 | |
| 77 | fn duration_text(run: &BackupRun) -> String { |
| 78 | let start = stamp_unix(&run.started_at); |
| 79 | let Some(end) = run.finished_at.as_deref().map(stamp_unix) else { |
| 80 | return "-".to_owned(); |
| 81 | }; |
| 82 | let secs = (end - start).max(0); |
| 83 | if secs < 60 { |
| 84 | format!("{secs}s") |
| 85 | } else { |
| 86 | format!("{}m {}s", secs / 60, secs % 60) |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | fn run_row(run: &BackupRun, lang: Lang) -> RunRow { |
| 91 | let (status, detail) = match (run.finished_at.is_some(), run.ok) { |
| 92 | (false, _) => (g::t(lang, K::StatusInProgress).to_owned(), String::new()), |
| 93 | (true, Some(true)) => (g::t(lang, K::StatusOk).to_owned(), String::new()), |
| 94 | (true, _) => ( |
| 95 | g::t(lang, K::StatusFailed).to_owned(), |
| 96 | run.error.clone().unwrap_or_default(), |
| 97 | ), |
| 98 | }; |
| 99 | RunRow { |
| 100 | kind: g::kind_name(lang, run.kind).to_owned(), |
| 101 | trigger: g::trigger_name(lang, run.trigger).to_owned(), |
| 102 | started: run.started_at.clone(), |
| 103 | duration: duration_text(run), |
| 104 | size: run.bytes.map(human_bytes).unwrap_or_default(), |
| 105 | status, |
| 106 | detail, |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | /// The rail of the Backups tab: Backups and Replication. |
| 111 | #[component] |
| 112 | pub(crate) async fn backups_rail(cx: &Cx, lang: Lang, current: &'static str) -> Result<impl View> { |
| 113 | let items = vec![ |
| 114 | RailItem { |
| 115 | name: g::t(lang, K::Backups).to_owned(), |
| 116 | val: String::new(), |
| 117 | href: "/admin/backups".to_owned(), |
| 118 | current: current == "backups", |
| 119 | }, |
| 120 | RailItem { |
| 121 | name: g::t(lang, K::Replication).to_owned(), |
| 122 | val: String::new(), |
| 123 | href: "/admin/replication".to_owned(), |
| 124 | current: current == "replication", |
| 125 | }, |
| 126 | ]; |
| 127 | Ok(view! { |
| 128 | rail(label: g::t(lang, K::Backups), items: items) |
| 129 | }) |
| 130 | } |
| 131 | |
| 132 | #[component] |
| 133 | async fn backups_view( |
| 134 | cx: &Cx, |
| 135 | lang: Lang, |
| 136 | csrf: String, |
| 137 | enabled: bool, |
| 138 | settings: Vec<Row>, |
| 139 | rows: Vec<RunRow>, |
| 140 | running: Option<RunKind>, |
| 141 | notice: Option<String>, |
| 142 | ) -> Result<impl View> { |
| 143 | let backup_running = |
| 144 | matches!(running, Some(RunKind::Backup)).then(|| g::running_line(lang, RunKind::Backup)); |
| 145 | let fsck_running = |
| 146 | matches!(running, Some(RunKind::Fsck)).then(|| g::running_line(lang, RunKind::Fsck)); |
| 147 | Ok(view! { |
| 148 | head(title: g::t(lang, K::Backups), |
| 149 | <form id="run-backup" method="post" action="/admin/backups/run" class="act-form"> |
| 150 | <input type="hidden" name="csrf" value=(csrf.as_str())> |
| 151 | <button type="submit" class="button">(g::t(lang, K::RunBackupNow))</button> |
| 152 | </form> |
| 153 | post_act(label: g::t(lang, K::RunFsckNow), action: "/admin/backups/fsck", csrf: csrf.as_str()) |
| 154 | ) |
| 155 | if let Some(message) = notice { |
| 156 | <p class="state" role="status">(message.as_str())</p> |
| 157 | } |
| 158 | <div class="work"> |
| 159 | backups_rail(lang: lang, current: "backups") |
| 160 | <div class="sheet" data-live="/admin/backups/events"> |
| 161 | if let Some(line) = backup_running { |
| 162 | <p class="state">(line)</p> |
| 163 | } |
| 164 | if let Some(line) = fsck_running { |
| 165 | <p class="state">(line)</p> |
| 166 | } |
| 167 | <section class="sec"> |
| 168 | <h2>(g::t(lang, K::Settings))</h2> |
| 169 | if !enabled { |
| 170 | <p class="state">(g::t(lang, K::ScheduledBackupsOff))</p> |
| 171 | } |
| 172 | <form method="post" action="/admin/backups" class="srv-form"> |
| 173 | <input type="hidden" name="csrf" value=(csrf.as_str())> |
| 174 | <input type="hidden" name="back" value="/admin/backups"> |
| 175 | setting_lines(lang: lang, rows: settings) |
| 176 | <div class="acts srv-save"> |
| 177 | <button type="submit" class="primary">(i18n::t(lang, Key::Save))</button> |
| 178 | </div> |
| 179 | </form> |
| 180 | reset_form(csrf: csrf.clone(), back: "/admin/backups".to_owned()) |
| 181 | </section> |
| 182 | <section class="sec"> |
| 183 | <h2>(g::t(lang, K::RecentRuns))</h2> |
| 184 | if rows.is_empty() { |
| 185 | <p class="state">(g::t(lang, K::NoRunsYet))</p> |
| 186 | } else { |
| 187 | for row in rows.into_iter() { |
| 188 | <div class="line" data-kb-row=""> |
| 189 | <span class="name">(row.kind.as_str()) " · " (row.trigger.as_str())</span> |
| 190 | <span class="val">(row.status.as_str()) " · " rel_time(lang: lang, stamp: row.started.as_str()) " · " (row.duration.as_str()) |
| 191 | if !row.size.is_empty() { |
| 192 | " · " (row.size.as_str()) |
| 193 | } |
| 194 | </span> |
| 195 | </div> |
| 196 | if !row.detail.is_empty() { |
| 197 | alert(message: row.detail.as_str()) |
| 198 | } |
| 199 | } |
| 200 | } |
| 201 | </section> |
| 202 | </div> |
| 203 | </div> |
| 204 | }) |
| 205 | } |
| 206 | |
| 207 | /// The backups page's state, as one string: the run in progress and the recent runs. |
| 208 | async fn runs_fingerprint(store: &Store, running: Option<RunKind>) -> Result<String> { |
| 209 | let runs = store.recent_runs(RUN_LIMIT).await?; |
| 210 | Ok(format!("{running:?}|{runs:?}")) |
| 211 | } |
| 212 | |
| 213 | /// The backups page's change stream. Admins only. |
| 214 | #[route(GET "/admin/backups/events")] |
| 215 | async fn backups_events(cx: &Cx) -> Result<Response> { |
| 216 | admin_only(cx).await?; |
| 217 | let state = context::<AppState>(cx); |
| 218 | let store = state.store.clone(); |
| 219 | let jobs = state.jobs.clone(); |
| 220 | stream_changes( |
| 221 | cx, |
| 222 | crate::live::admin(), |
| 223 | &[Topic::AdminBackups], |
| 224 | move || { |
| 225 | let store = store.clone(); |
| 226 | let running = jobs.running(); |
| 227 | async move { runs_fingerprint(&store, running).await } |
| 228 | }, |
| 229 | ) |
| 230 | .await |
| 231 | } |
| 232 | |
| 233 | #[page("/admin/backups")] |
| 234 | async fn backups_page(cx: &Cx) -> Result<impl View> { |
| 235 | let viewer = admin_only(cx).await?; |
| 236 | let query = query_params::<NoticeQuery>(cx)?; |
| 237 | let state = context::<AppState>(cx); |
| 238 | let lang = i18n::lang(cx, Some(&viewer.0)); |
| 239 | let runs = state.store.recent_runs(RUN_LIMIT).await?; |
| 240 | let rows: Vec<RunRow> = runs.iter().map(|run| run_row(run, lang)).collect(); |
| 241 | let running = state.jobs.running(); |
| 242 | let settings = setting_rows(state, lang, BACKUP_KEYS).await?; |
| 243 | let enabled = state.config.backup.enabled(); |
| 244 | let csrf = viewer.1.csrf_token.clone(); |
| 245 | let title = g::t(lang, K::Backups); |
| 246 | Ok(view! { |
| 247 | shell(title: title, viewer: Some(&viewer), backups_view(lang: lang, csrf: csrf, enabled: enabled, settings: settings, rows: rows, running: running, notice: query.notice.clone())) |
| 248 | }) |
| 249 | } |
| 250 | |
| 251 | /// Saves the backup settings from the page's form. Admins only, with the CSRF token. |
| 252 | #[route(POST "/admin/backups")] |
| 253 | async fn backups_save(cx: &Cx, Form(form): Form<HashMap<String, String>>) -> Result<Response> { |
| 254 | let viewer = admin_only(cx).await?; |
| 255 | if !check_csrf(&viewer.1, form.get("csrf").map_or("", String::as_str)) { |
| 256 | return Err(forbidden().into()); |
| 257 | } |
| 258 | let lang = i18n::lang(cx, Some(&viewer.0)); |
| 259 | let state = context::<AppState>(cx); |
| 260 | let notice = notice_of( |
| 261 | lang, |
| 262 | save_topic( |
| 263 | cx, |
| 264 | state, |
| 265 | &viewer.0, |
| 266 | Group::Backups, |
| 267 | BACKUP_KEYS, |
| 268 | form, |
| 269 | lang, |
| 270 | ) |
| 271 | .await, |
| 272 | ); |
| 273 | Err(see_other(with_notice("/admin/backups", ¬ice)).into()) |
| 274 | } |
| 275 | |
| 276 | #[route(POST "/admin/backups/run")] |
| 277 | async fn backups_run(cx: &Cx, Form(form): Form<RunForm>) -> Result<Response> { |
| 278 | start_run(cx, form.csrf, RunKind::Backup).await |
| 279 | } |
| 280 | |
| 281 | #[route(POST "/admin/backups/fsck")] |
| 282 | async fn backups_fsck(cx: &Cx, Form(form): Form<RunForm>) -> Result<Response> { |
| 283 | start_run(cx, form.csrf, RunKind::Fsck).await |
| 284 | } |
| 285 | |
| 286 | /// Starts a run in the background, audits the request and redirects back with a notice. |
| 287 | async fn start_run(cx: &Cx, csrf: String, kind: RunKind) -> Result<Response> { |
| 288 | let viewer = admin_only(cx).await?; |
| 289 | if !check_csrf(&viewer.1, &csrf) { |
| 290 | return Err(forbidden().into()); |
| 291 | } |
| 292 | let lang = i18n::lang(cx, Some(&viewer.0)); |
| 293 | let state = context::<AppState>(cx); |
| 294 | let notice = match launch(cx, state, &viewer.0, kind, lang).await { |
| 295 | Ok(()) => g::started_notice(lang, kind), |
| 296 | Err(e) => match e { |
| 297 | Error::Conflict(message) => message, |
| 298 | other => other.to_string(), |
| 299 | }, |
| 300 | }; |
| 301 | let location = format!("/admin/backups?notice={}", enc(¬ice)); |
| 302 | Err(see_other(&location).into()) |
| 303 | } |
| 304 | |
| 305 | /// Claims the run slot, records the audit entry and starts the run. Refusals come back as errors. |
| 306 | async fn launch( |
| 307 | cx: &Cx, |
| 308 | state: &AppState, |
| 309 | user: &User, |
| 310 | kind: RunKind, |
| 311 | lang: Lang, |
| 312 | ) -> forge_core::Result<()> { |
| 313 | if !state.config.backup.enabled() { |
| 314 | return Err(Error::Config( |
| 315 | g::t(lang, K::ErrBackupsNotConfigured).to_owned(), |
| 316 | )); |
| 317 | } |
| 318 | // Refuse a bad directory here, not in the background task. |
| 319 | configured_dir(state)?; |
| 320 | let guard = state.jobs.claim(kind)?; |
| 321 | let (action, target_kind) = match kind { |
| 322 | RunKind::Backup => (AuditAction::BackupStarted, "backup"), |
| 323 | RunKind::Fsck => (AuditAction::FsckStarted, "fsck"), |
| 324 | }; |
| 325 | audit::record( |
| 326 | &state.store, |
| 327 | Some(cx), |
| 328 | Actor::User(user), |
| 329 | action, |
| 330 | Target { |
| 331 | kind: target_kind, |
| 332 | id: "", |
| 333 | name: "", |
| 334 | }, |
| 335 | serde_json::json!({ "trigger": "manual" }), |
| 336 | ) |
| 337 | .await; |
| 338 | start_manual(state, guard) |
| 339 | } |
| 340 | |
| 341 | #[cfg(test)] |
| 342 | mod tests { |
| 343 | use super::*; |
| 344 | use forge_core::model::Visibility; |
| 345 | use forge_core::store::backup_runs::RunTrigger; |
| 346 | use topcoat::router::request::Request; |
| 347 | use topcoat::router::{Body, Router, to_bytes}; |
| 348 | |
| 349 | use crate::auth::SESSION_COOKIE; |
| 350 | use crate::test_support::{app_router, create_session, test_state}; |
| 351 | |
| 352 | const ADMIN_TOKEN: &str = "backups-admin-session"; |
| 353 | const USER_TOKEN: &str = "backups-user-session"; |
| 354 | const CSRF: &str = "backups-csrf"; |
| 355 | |
| 356 | struct Fixture { |
| 357 | _dir: tempfile::TempDir, |
| 358 | router: Router, |
| 359 | state: AppState, |
| 360 | } |
| 361 | |
| 362 | /// An instance with an admin, a plain user, one repo, and backups configured under the temp |
| 363 | /// directory. |
| 364 | async fn fixture(configured: bool) -> Fixture { |
| 365 | let dir = tempfile::tempdir().expect("tempdir"); |
| 366 | let data_dir = dir.path().join("data"); |
| 367 | std::fs::create_dir_all(&data_dir).expect("data dir"); |
| 368 | let mut state = test_state(&data_dir).await; |
| 369 | let mut config = crate::test_support::test_config(&data_dir); |
| 370 | if configured { |
| 371 | config.backup.dir = dir.path().join("out"); |
| 372 | config.backup.keep = 2; |
| 373 | } |
| 374 | state.config = std::sync::Arc::new(config); |
| 375 | let admin = state |
| 376 | .store |
| 377 | .create_user("root", None, "h", true) |
| 378 | .await |
| 379 | .expect("admin"); |
| 380 | let user = state |
| 381 | .store |
| 382 | .create_user("plain", None, "h", false) |
| 383 | .await |
| 384 | .expect("user"); |
| 385 | create_session(&state.store, &admin.id, ADMIN_TOKEN, CSRF).await; |
| 386 | create_session(&state.store, &user.id, USER_TOKEN, CSRF).await; |
| 387 | let repo = state |
| 388 | .store |
| 389 | .create_repo(&admin.id, "demo", "", Visibility::Private, "main") |
| 390 | .await |
| 391 | .expect("repo"); |
| 392 | // fsck reads the repo from disk, so it must exist for the run to pass. |
| 393 | let path = forge_git::repo::repo_path(&data_dir, &repo.id).expect("path"); |
| 394 | forge_git::repo::init_bare(&state.git, &path, "main") |
| 395 | .await |
| 396 | .expect("init"); |
| 397 | let router = app_router(state.clone()); |
| 398 | Fixture { |
| 399 | _dir: dir, |
| 400 | router, |
| 401 | state, |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | async fn send( |
| 406 | router: &Router, |
| 407 | method: &str, |
| 408 | uri: &str, |
| 409 | token: Option<&str>, |
| 410 | form: Option<String>, |
| 411 | ) -> (u16, String) { |
| 412 | let mut builder = Request::builder().method(method).uri(uri); |
| 413 | if let Some(token) = token { |
| 414 | builder = builder.header("cookie", format!("__Host-{SESSION_COOKIE}={token}")); |
| 415 | } |
| 416 | let body = match form { |
| 417 | Some(form) => { |
| 418 | builder = builder.header("content-type", "application/x-www-form-urlencoded"); |
| 419 | Body::from(form) |
| 420 | } |
| 421 | None => Body::empty(), |
| 422 | }; |
| 423 | let res = router.handle(builder.body(body).expect("request")).await; |
| 424 | let status = res.status().as_u16(); |
| 425 | let bytes = to_bytes(res.into_body(), usize::MAX).await.expect("body"); |
| 426 | (status, String::from_utf8_lossy(&bytes).into_owned()) |
| 427 | } |
| 428 | |
| 429 | /// One configured instance serves every scenario below, since building it is the slow part. |
| 430 | /// The scenarios run in order: the run-count checks need the runs recorded so far. |
| 431 | #[tokio::test] |
| 432 | async fn backups_page_and_manual_runs() { |
| 433 | let fx = fixture(true).await; |
| 434 | |
| 435 | // Anonymous visitors and plain users get a 404 for the page and for the run endpoint. |
| 436 | let (anon, _) = send(&fx.router, "GET", "/admin/backups", None, None).await; |
| 437 | assert_eq!(anon, 404, "anonymous page"); |
| 438 | let (user, _) = send(&fx.router, "GET", "/admin/backups", Some(USER_TOKEN), None).await; |
| 439 | assert_eq!(user, 404, "plain user page"); |
| 440 | let (posted, _) = send( |
| 441 | &fx.router, |
| 442 | "POST", |
| 443 | "/admin/backups/run", |
| 444 | Some(USER_TOKEN), |
| 445 | Some(format!("csrf={CSRF}")), |
| 446 | ) |
| 447 | .await; |
| 448 | assert_eq!(posted, 404, "plain user run"); |
| 449 | |
| 450 | // A backup already running refuses a second one, and the refusal records no run. |
| 451 | let held = fx.state.jobs.claim(RunKind::Backup).expect("claim"); |
| 452 | let (status, _) = send( |
| 453 | &fx.router, |
| 454 | "POST", |
| 455 | "/admin/backups/run", |
| 456 | Some(ADMIN_TOKEN), |
| 457 | Some(format!("csrf={CSRF}")), |
| 458 | ) |
| 459 | .await; |
| 460 | assert_eq!(status, 303, "busy run"); |
| 461 | let (_, page) = send( |
| 462 | &fx.router, |
| 463 | "GET", |
| 464 | "/admin/backups?notice=already%20running%3A%20x", |
| 465 | Some(ADMIN_TOKEN), |
| 466 | None, |
| 467 | ) |
| 468 | .await; |
| 469 | assert!(page.contains("already running"), "busy notice"); |
| 470 | assert!( |
| 471 | fx.state |
| 472 | .store |
| 473 | .recent_runs(5) |
| 474 | .await |
| 475 | .expect("runs") |
| 476 | .is_empty(), |
| 477 | "busy run records nothing" |
| 478 | ); |
| 479 | drop(held); |
| 480 | |
| 481 | // A POST without the CSRF token is refused. With it, fsck starts, is audited and recorded. |
| 482 | let (bad, _) = send( |
| 483 | &fx.router, |
| 484 | "POST", |
| 485 | "/admin/backups/fsck", |
| 486 | Some(ADMIN_TOKEN), |
| 487 | Some("csrf=wrong".into()), |
| 488 | ) |
| 489 | .await; |
| 490 | assert_eq!(bad, 403, "fsck without csrf"); |
| 491 | |
| 492 | let (status, _) = send( |
| 493 | &fx.router, |
| 494 | "POST", |
| 495 | "/admin/backups/fsck", |
| 496 | Some(ADMIN_TOKEN), |
| 497 | Some(format!("csrf={CSRF}")), |
| 498 | ) |
| 499 | .await; |
| 500 | assert_eq!(status, 303, "fsck with csrf"); |
| 501 | |
| 502 | // Wait for the background fsck to finish and record itself. |
| 503 | let mut runs = Vec::new(); |
| 504 | for _ in 0..500 { |
| 505 | runs = fx.state.store.recent_runs(5).await.expect("runs"); |
| 506 | if runs.iter().any(|r| r.finished_at.is_some()) { |
| 507 | break; |
| 508 | } |
| 509 | tokio::time::sleep(std::time::Duration::from_millis(20)).await; |
| 510 | } |
| 511 | assert_eq!(runs.len(), 1, "{runs:?}"); |
| 512 | assert_eq!(runs[0].kind, RunKind::Fsck, "fsck run kind"); |
| 513 | assert_eq!(runs[0].trigger, RunTrigger::Manual, "fsck run trigger"); |
| 514 | assert_eq!(runs[0].ok, Some(true), "fsck run result"); |
| 515 | |
| 516 | let audit = fx |
| 517 | .state |
| 518 | .store |
| 519 | .list_audit(&Default::default(), None, 10) |
| 520 | .await |
| 521 | .expect("audit"); |
| 522 | assert!( |
| 523 | audit.iter().any(|e| e.action == AuditAction::FsckStarted), |
| 524 | "fsck is audited" |
| 525 | ); |
| 526 | |
| 527 | let (_, page) = send(&fx.router, "GET", "/admin/backups", Some(ADMIN_TOKEN), None).await; |
| 528 | assert!(page.contains("fsck"), "fsck run is listed"); |
| 529 | |
| 530 | // The page lists runs, and the healthcheck URL is shown without its secret token. |
| 531 | let mut config = (*fx.state.config).clone(); |
| 532 | config.backup.healthcheck_url = "https://hc.example.test/ping/SECRET-TOKEN".into(); |
| 533 | let mut state = fx.state.clone(); |
| 534 | state.config = std::sync::Arc::new(config); |
| 535 | let router = app_router(state.clone()); |
| 536 | |
| 537 | let id = state |
| 538 | .store |
| 539 | .start_run(RunKind::Backup, RunTrigger::Schedule) |
| 540 | .await |
| 541 | .expect("start"); |
| 542 | state |
| 543 | .store |
| 544 | .finish_run(&id, false, None, None, Some("disk full")) |
| 545 | .await |
| 546 | .expect("finish"); |
| 547 | |
| 548 | let (status, body) = send(&router, "GET", "/admin/backups", Some(ADMIN_TOKEN), None).await; |
| 549 | assert_eq!(status, 200); |
| 550 | assert!(body.contains("schedule")); |
| 551 | assert!(body.contains("disk full")); |
| 552 | assert!( |
| 553 | !body.contains("hc.example.test"), |
| 554 | "a healthcheck URL is a secret and is never rendered" |
| 555 | ); |
| 556 | assert!( |
| 557 | !body.contains("SECRET-TOKEN"), |
| 558 | "the healthcheck token must not be shown" |
| 559 | ); |
| 560 | assert!(body.contains("Run backup now")); |
| 561 | assert!(body.contains("Run fsck now")); |
| 562 | } |
| 563 | |
| 564 | #[tokio::test] |
| 565 | async fn unconfigured_instance_refuses_manual_runs() { |
| 566 | let fx = fixture(false).await; |
| 567 | let (status, _) = send( |
| 568 | &fx.router, |
| 569 | "POST", |
| 570 | "/admin/backups/run", |
| 571 | Some(ADMIN_TOKEN), |
| 572 | Some(format!("csrf={CSRF}")), |
| 573 | ) |
| 574 | .await; |
| 575 | assert_eq!(status, 303); |
| 576 | assert!( |
| 577 | fx.state |
| 578 | .store |
| 579 | .recent_runs(5) |
| 580 | .await |
| 581 | .expect("runs") |
| 582 | .is_empty() |
| 583 | ); |
| 584 | assert_eq!(fx.state.jobs.running(), None); |
| 585 | } |
| 586 | |
| 587 | #[test] |
| 588 | fn human_bytes_scales() { |
| 589 | assert_eq!(human_bytes(512), "512 B"); |
| 590 | assert_eq!(human_bytes(2048), "2.0 KiB"); |
| 591 | assert_eq!(human_bytes(3 * 1024 * 1024), "3.0 MiB"); |
| 592 | } |
| 593 | } |