OXYGENHUB

Coverage / crates/hub/src/api/backups.rs 81.9%

118 of 144 lines run, 32 of 86 functions · run #472 on main · run missed

1
//! The backups API (oxygenhub#179, docs/backups.md §5): what the Backups
2
//! pages do, for a user's own repositories and an organisation's (its
3
//! owners only), with the scope `repo:admin`.
4
5
use super::{caller, not_found, ApiError, Caller};
6
use crate::auth;
7
use crate::backups::{self, Run, Setting};
8
use crate::db::{self, accounts::Account};
9
use crate::web::backups::{setting_of, SettingInput};
10
use crate::Shared;
11
use axum::extract::{Path, State};
12
use axum::http::{HeaderMap, StatusCode};
13
use axum::Json;
14
use serde::{Deserialize, Serialize};
15
16
/// A setting as the API takes it: the page's fields, `keep_days` a number.
17
#[derive(Deserialize)]
18
pub struct Body {
19
    pub every: String,
20
    #[serde(default)]
21
    pub destination: String,
22
    /// A directory destination: one the hub allows.
23
    #[serde(default)]
24
    pub dir: String,
25
    /// A GCS destination: its bucket and workload identity provider.
26
    #[serde(default)]
27
    pub bucket: String,
28
    #[serde(default)]
29
    pub provider: String,
30
    #[serde(default)]
31
    pub prefix: String,
32
    #[serde(default = "thirty")]
33
    pub keep_days: i64,
34
    /// An S3 destination: its bucket, region and the IAM role's ARN.
35
    #[serde(default)]
36
    pub s3_bucket: String,
37
    #[serde(default)]
38
    pub s3_region: String,
39
    #[serde(default)]
40
    pub s3_role: String,
41
}
42
433×
fn thirty() -> i64 {
443×
    30
453×
}
46
47
#[derive(Serialize)]
48
pub struct State_ {
49
    pub setting: Option<Setting>,
50
    /// Where its runs go, as the pages say it.
51
    pub place: Option<String>,
52
    pub runs: Vec<Run>,
53
}
54
55
/// The owner a call acts for: the caller's own account, or an organisation
56
/// it owns. Someone else's is not found.
5713×
async fn owner_of(app: &Shared, c: &Caller, org: Option<&str>) -> Result<(Account, String, &'static str), ApiError> {
5813×
    let me = c.require("repo:admin")?.clone();
5912×
    match org {
60
        None => {
619×
            let name = me.username.clone();
629×
            Ok((me, name, "user"))
63
        }
643×
        Some(name) => {
653×
            let o = db::accounts::org_by_name(&app.db, name).await?.ok_or_else(|| not_found("no such organisation"))?;
663×
            if !auth::roles::is_org_owner(&app.db, &me, o.id).await? {
672×
                return Err(not_found("no such organisation"));
681×
            }
691×
            Ok((me, o.name, "org"))
70
        }
71
    }
7213×
}
73
743×
async fn state(app: &Shared, owner: &str) -> Result<State_, ApiError> {
753×
    let setting = backups::setting(&app.db, owner).await?;
763×
    let place = setting.as_ref().map(backups::place);
773×
    Ok(State_ { setting, place, runs: backups::runs(&app.db, owner, 10).await? })
783×
}
79
802×
async fn get(app: Shared, headers: HeaderMap, org: Option<String>) -> Result<Json<State_>, ApiError> {
812×
    let c = caller(&app, &headers).await?;
822×
    let (_, owner, _) = owner_of(&app, &c, org.as_deref()).await?;
831×
    Ok(Json(state(&app, &owner).await?))
842×
}
85
865×
async fn put(app: Shared, headers: HeaderMap, org: Option<String>, b: Body) -> Result<Json<State_>, ApiError> {
875×
    let c = caller(&app, &headers).await?;
885×
    let (me, owner, kind) = owner_of(&app, &c, org.as_deref()).await?;
893×
    let input = SettingInput {
903×
        every: b.every,
913×
        destination: b.destination,
923×
        dir: b.dir,
933×
        bucket: b.bucket,
943×
        provider: b.provider,
953×
        prefix: b.prefix,
963×
        keep_days: b.keep_days.to_string(),
973×
        s3_bucket: b.s3_bucket,
983×
        s3_region: b.s3_region,
993×
        s3_role: b.s3_role,
1003×
    };
1013×
    let s = setting_of(&app, &owner, kind, &input).map_err(|e| ApiError(StatusCode::BAD_REQUEST, e))?;
1022×
    backups::save(&app.db, &s).await?;
1032×
    db::accounts::audit(&app.db, Some(&me), "backup.setting", &owner, &format!("{} to {}", s.every, backups::place(&s))).await.ok();
1042×
    Ok(Json(state(&app, &owner).await?))
1055×
}
106
1071×
async fn test(app: Shared, headers: HeaderMap, org: Option<String>) -> Result<Json<serde_json::Value>, ApiError> {
1081×
    let c = caller(&app, &headers).await?;
1091×
    let (_, owner, _) = owner_of(&app, &c, org.as_deref()).await?;
1101×
    let set =
1111×
        backups::setting(&app.db, &owner).await?.ok_or_else(|| ApiError(StatusCode::CONFLICT, "save where backups go first".into()))?;
1121×
    let dest = backups::destination(&app, &set).map_err(|e| ApiError(StatusCode::CONFLICT, format!("{e:#}")))?;
1131×
    tokio::task::spawn_blocking(move || backups::probe(dest.as_ref()))
1141×
        .await
1151×
        .map_err(|e| ApiError(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?
1161×
        .map_err(|e| ApiError(StatusCode::CONFLICT, format!("TEST failed: {e:#}")))?;
1171×
    Ok(Json(serde_json::json!({ "ok": true, "place": backups::place(&set) })))
1181×
}
119
1202×
async fn run(app: Shared, headers: HeaderMap, org: Option<String>) -> Result<(StatusCode, Json<serde_json::Value>), ApiError> {
1212×
    let c = caller(&app, &headers).await?;
1222×
    let (_, owner, _) = owner_of(&app, &c, org.as_deref()).await?;
1232×
    if backups::setting(&app.db, &owner).await?.is_none() {
1241×
        return Err(ApiError(StatusCode::CONFLICT, "save where backups go first".into()));
1251×
    }
1261×
    let (app2, owner2) = (app.clone(), owner.clone());
1271×
    tokio::spawn(async move {
1281×
        if let Err(e) = backups::run(&app2, &owner2, "now").await {
1290×
            tracing::warn!("backup of {owner2}: {e:#}");
1301×
        }
1311×
    });
1321×
    Ok((StatusCode::ACCEPTED, Json(serde_json::json!({ "owner": owner, "started": true }))))
1332×
}
134
1353×
async fn runs(app: Shared, headers: HeaderMap, org: Option<String>) -> Result<Json<Vec<Run>>, ApiError> {
1363×
    let c = caller(&app, &headers).await?;
1373×
    let (_, owner, _) = owner_of(&app, &c, org.as_deref()).await?;
1383×
    Ok(Json(backups::runs(&app.db, &owner, 50).await?))
1393×
}
140
1411×
pub async fn user_get(State(app): State<Shared>, headers: HeaderMap) -> Result<Json<State_>, ApiError> {
1421×
    get(app, headers, None).await
1431×
}
1443×
pub async fn user_put(State(app): State<Shared>, headers: HeaderMap, Json(b): Json<Body>) -> Result<Json<State_>, ApiError> {
1453×
    put(app, headers, None, b).await
1463×
}
1471×
pub async fn user_test(State(app): State<Shared>, headers: HeaderMap) -> Result<Json<serde_json::Value>, ApiError> {
1481×
    test(app, headers, None).await
1491×
}
1502×
pub async fn user_run(State(app): State<Shared>, headers: HeaderMap) -> Result<(StatusCode, Json<serde_json::Value>), ApiError> {
1512×
    run(app, headers, None).await
1522×
}
1533×
pub async fn user_runs(State(app): State<Shared>, headers: HeaderMap) -> Result<Json<Vec<Run>>, ApiError> {
1543×
    runs(app, headers, None).await
1553×
}
1561×
pub async fn org_get(State(app): State<Shared>, headers: HeaderMap, Path(name): Path<String>) -> Result<Json<State_>, ApiError> {
1571×
    get(app, headers, Some(name)).await
1581×
}
1592×
pub async fn org_put(
1602×
    State(app): State<Shared>,
1612×
    headers: HeaderMap,
1622×
    Path(name): Path<String>,
1632×
    Json(b): Json<Body>,
1642×
) -> Result<Json<State_>, ApiError> {
1652×
    put(app, headers, Some(name), b).await
1662×
}
1670×
pub async fn org_test(
1680×
    State(app): State<Shared>,
1690×
    headers: HeaderMap,
1700×
    Path(name): Path<String>,
1710×
) -> Result<Json<serde_json::Value>, ApiError> {
1720×
    test(app, headers, Some(name)).await
1730×
}
1740×
pub async fn org_run(
1750×
    State(app): State<Shared>,
1760×
    headers: HeaderMap,
1770×
    Path(name): Path<String>,
1780×
) -> Result<(StatusCode, Json<serde_json::Value>), ApiError> {
1790×
    run(app, headers, Some(name)).await
1800×
}
1810×
pub async fn org_runs(State(app): State<Shared>, headers: HeaderMap, Path(name): Path<String>) -> Result<Json<Vec<Run>>, ApiError> {
1820×
    runs(app, headers, Some(name)).await
1830×
}