OXYGENHUB
# 8597fb5ca16c oxygenhub / crates / hub / src / backups.rs
84.3 KiB · Rust · last changed Drops: per-user gists, each a small hidden Oxygen repository (#279) 15 days ago source blame history raw
1
//! Backups (docs/backups.md, oxygenhub#169): each user and organisation
2
//! copies its repositories, on a schedule, to a destination it controls.
3
//!
4
//! A repository is its store directory (`.oxy/`): packs and loose objects
5
//! that never change once written, and small files that do (refs, the
6
//! operation log, policies, signature indexes). A run copies each file
7
//! once, named by its BLAKE3 (`blobs/`), and writes a manifest of path to
8
//! hash per repository (`runs/<at>/repos/`), so only what changed travels
9
//! and any kept run can be restored byte for byte, signatures and all.
10
//! The large files are copied first; the walk is then repeated under the
11
//! repository's read lock, which pushes wait on, so each manifest is one
12
//! consistent moment. Beside each manifest go the hub's records for the
13
//! repository as JSON (never a secret value), the owner's records, and
14
//! last a `DONE` marker: a run without one was cut short and is ignored.
15
16
use crate::db::{self, Pool};
17
use crate::repos::RepoName;
18
use crate::Shared;
19
use anyhow::{bail, Context, Result};
20
use serde::{Deserialize, Serialize};
21
use std::collections::HashMap;
22
use std::path::{Path, PathBuf};
23
24
/// How often, as the settings offer it.
25
pub const EVERY: &[(&str, &str)] = &[("off", "Off"), ("hourly", "Every hour"), ("daily", "Every day")];
26
/// How long runs are kept, in days.
27
pub const KEEP: &[i64] = &[7, 30, 90];
28
29
/// What an owner backs up, where and how often.
30
#[derive(Clone, Debug, sqlx::FromRow, Serialize)]
31
pub struct Setting {
32
    pub owner: String,
33
    pub kind: String,
34
    pub every: String,
35
    pub destination: String,
36
    pub target: String,
37
    pub prefix: String,
38
    pub provider: String,
39
    pub keep_days: i64,
40
    pub updated_ms: i64,
41
    /// An S3 bucket's region (migration 0063).
42
    #[sqlx(default)]
43
    pub region: String,
44
}
45
46
impl Setting {
47
    pub fn off(owner: &str, kind: &str) -> Setting {
48
        Setting {
49
            owner: owner.into(),
50
            kind: kind.into(),
51
            every: "off".into(),
52
            destination: "dir".into(),
53
            target: String::new(),
54
            prefix: String::new(),
55
            provider: String::new(),
56
            keep_days: 30,
57
            updated_ms: 0,
58
            region: String::new(),
59
        }
60
    }
61
62
    /// Seconds between runs; none when off.
63
    pub fn period_s(&self) -> Option<i64> {
64
        match self.every.as_str() {
65
            "hourly" => Some(3600),
66
            "daily" => Some(86_400),
67
            _ => None,
68
        }
69
    }
70
}
71
72
/// One run, as the settings page and the API show it.
73
#[derive(Clone, Debug, sqlx::FromRow, Serialize)]
74
pub struct Run {
75
    pub id: i64,
76
    pub owner: String,
77
    pub started_ms: i64,
78
    pub finished_ms: Option<i64>,
79
    pub status: String,
80
    pub at: String,
81
    pub repos: i64,
82
    pub files: i64,
83
    pub sent: i64,
84
    pub bytes: i64,
85
    pub detail: String,
86
    pub trigger: String,
87
}
88
89
pub async fn setting(pool: &Pool, owner: &str) -> sqlx::Result<Option<Setting>> {
90
    sqlx::query_as("SELECT * FROM backup_settings WHERE owner = $1").bind(owner).fetch_optional(pool).await
91
}
92
93
pub async fn save(pool: &Pool, s: &Setting) -> sqlx::Result<()> {
94
    sqlx::query(
95
        "INSERT INTO backup_settings (owner, kind, every, destination, target, prefix, provider, keep_days, updated_ms, region) \
96
         VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) ON CONFLICT(owner) DO UPDATE SET kind = excluded.kind, every = excluded.every, \
97
         destination = excluded.destination, target = excluded.target, prefix = excluded.prefix, provider = excluded.provider, \
98
         keep_days = excluded.keep_days, updated_ms = excluded.updated_ms, region = excluded.region",
99
    )
100
    .bind(&s.owner)
101
    .bind(&s.kind)
102
    .bind(&s.every)
103
    .bind(&s.destination)
104
    .bind(&s.target)
105
    .bind(&s.prefix)
106
    .bind(&s.provider)
107
    .bind(s.keep_days)
108
    .bind(db::now_ms())
109
    .bind(&s.region)
110
    .execute(pool)
111
    .await?;
112
    Ok(())
113
}
114
115
pub async fn runs(pool: &Pool, owner: &str, limit: i64) -> sqlx::Result<Vec<Run>> {
116
    sqlx::query_as("SELECT * FROM backup_runs WHERE owner = $1 ORDER BY id DESC LIMIT $2").bind(owner).bind(limit).fetch_all(pool).await
117
}
118
119
/// What a repository may choose about its backup (§5): with its owner's,
120
/// left out, or at least hourly or daily whatever its owner's schedule.
121
pub const REPO_CHOICES: &[(&str, &str)] =
122
    &[("", "With its owner's backup"), ("hourly", "At least every hour"), ("daily", "At least every day"), ("off", "Left out")];
123
124
/// Whether `row` is in its owner's run: never when it is left out, always
125
/// when it has its own schedule, else as its owner's schedule says (a run
126
/// asked for by hand takes every repository not left out).
127
pub fn included(s: &Setting, row: &db::repos::RepoRow, by_hand: bool) -> bool {
128
    match row.backup.as_str() {
129
        "off" => false,
130
        "hourly" | "daily" => true,
131
        _ => by_hand || s.every != "off",
132
    }
133
}
134
135
/// Seconds between an owner's runs: the shortest of its own schedule and
136
/// its repositories' own; none when nothing is scheduled.
137
pub fn period_with(s: &Setting, repos: &[db::repos::RepoRow]) -> Option<i64> {
138
    let own = repos.iter().filter_map(|r| match r.backup.as_str() {
139
        "hourly" => Some(3600),
140
        "daily" => Some(86_400),
141
        _ => None,
142
    });
143
    s.period_s().into_iter().chain(own).min()
144
}
145
146
/// One owner's backup as Admin › Backups shows it (§5): its setting, its
147
/// newest run, and how many runs failed in the last day. An administrator
148
/// sees that it ran, never what it wrote.
149
#[derive(Clone, Debug, Serialize)]
150
pub struct Overview {
151
    pub setting: Setting,
152
    pub last: Option<Run>,
153
    pub failed_day: i64,
154
    /// The repositories it covers now.
155
    pub repos: i64,
156
}
157
158
impl Overview {
159
    /// Where its runs go, as a person reads it.
160
    pub fn place(&self) -> String {
161
        place(&self.setting)
162
    }
163
}
164
165
/// Where a setting's runs go, as a person reads it.
166
pub fn place(s: &Setting) -> String {
167
    match s.destination.as_str() {
168
        "gcs" if s.prefix.is_empty() => format!("gs://{}", s.target),
169
        "gcs" => format!("gs://{}/{}", s.target, s.prefix),
170
        "s3" if s.prefix.is_empty() => format!("s3://{} ({})", s.target, s.region),
171
        "s3" => format!("s3://{}/{} ({})", s.target, s.prefix, s.region),
172
        _ => format!("{}/{}", s.target, s.owner),
173
    }
174
}
175
176
/// Every owner's backup (Admin › Backups), and the owners of repositories
177
/// that none covers, with how many each has.
178
pub async fn overview(pool: &Pool) -> sqlx::Result<(Vec<Overview>, Vec<(String, i64)>)> {
179
    let settings: Vec<Setting> = sqlx::query_as("SELECT * FROM backup_settings ORDER BY owner").fetch_all(pool).await?;
180
    let counts: Vec<(String, i64)> =
181
        sqlx::query_as("SELECT owner, COUNT(*) FROM repositories WHERE kind = 'repo' GROUP BY owner ORDER BY owner")
182
            .fetch_all(pool)
183
            .await?;
184
    let day_ago = db::now_ms() - 86_400_000;
185
    let mut out = Vec::new();
186
    for s in settings {
187
        let last = runs(pool, &s.owner, 1).await?.into_iter().next();
188
        let failed_day: i64 =
189
            sqlx::query_scalar("SELECT COUNT(*) FROM backup_runs WHERE owner = $1 AND status = 'failed' AND started_ms >= $2")
190
                .bind(&s.owner)
191
                .bind(day_ago)
192
                .fetch_one(pool)
193
                .await?;
194
        let repos = db::repos::list(pool).await?.iter().filter(|r| r.owner == s.owner && included(&s, r, false)).count() as i64;
195
        out.push(Overview { setting: s, last, failed_day, repos });
196
    }
197
    let uncovered = counts.into_iter().filter(|(owner, _)| !out.iter().any(|o| o.setting.owner == *owner && o.repos > 0)).collect();
198
    Ok((out, uncovered))
199
}
200
201
// ---------------------------------------------------------------- where
202
203
/// Where backups are written: keys are `/`-separated paths.
204
pub trait Destination: Send + Sync {
205
    fn exists(&self, key: &str) -> Result<bool>;
206
    /// Write `bytes` at `key`, whole or not at all.
207
    fn put(&self, key: &str, bytes: &[u8]) -> Result<()>;
208
    fn get(&self, key: &str) -> Result<Vec<u8>>;
209
    /// The names directly under `prefix` (files and "directories").
210
    fn list(&self, prefix: &str) -> Result<Vec<String>>;
211
    /// Remove `key` and everything under it.
212
    fn remove(&self, key: &str) -> Result<()>;
213
}
214
215
/// A directory on the hub's host.
216
pub struct Directory {
217
    pub root: PathBuf,
218
}
219
220
impl Directory {
221
    fn path(&self, key: &str) -> Result<PathBuf> {
222
        if key.split('/').any(|p| p == ".." || p == ".") || key.starts_with('/') {
223
            bail!("not a clean key: {key}");
224
        }
225
        Ok(self.root.join(key))
226
    }
227
}
228
229
impl Destination for Directory {
230
    fn exists(&self, key: &str) -> Result<bool> {
231
        Ok(self.path(key)?.exists())
232
    }
233
    fn put(&self, key: &str, bytes: &[u8]) -> Result<()> {
234
        let p = self.path(key)?;
235
        std::fs::create_dir_all(p.parent().context("no parent")?)?;
236
        let tmp = p.with_extension(format!("part-{}", std::process::id()));
237
        std::fs::write(&tmp, bytes)?;
238
        std::fs::rename(&tmp, &p)?;
239
        Ok(())
240
    }
241
    fn get(&self, key: &str) -> Result<Vec<u8>> {
242
        let p = self.path(key)?;
243
        std::fs::read(&p).with_context(|| format!("read {}", p.display()))
244
    }
245
    fn list(&self, prefix: &str) -> Result<Vec<String>> {
246
        let p = self.path(prefix)?;
247
        let mut out: Vec<String> = match std::fs::read_dir(&p) {
248
            Ok(d) => d.flatten().map(|e| e.file_name().to_string_lossy().into_owned()).collect(),
249
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Vec::new(),
250
            Err(e) => return Err(e.into()),
251
        };
252
        out.sort();
253
        Ok(out)
254
    }
255
    fn remove(&self, key: &str) -> Result<()> {
256
        let p = self.path(key)?;
257
        if p.is_dir() {
258
            std::fs::remove_dir_all(p)?;
259
        } else if p.exists() {
260
            std::fs::remove_file(p)?;
261
        }
262
        Ok(())
263
    }
264
}
265
266
/// A Cloud Storage bucket, reached keylessly (docs/backups.md §3, §6):
267
/// the hub mints a short token as `backup:OWNER`, Google's STS exchanges
268
/// it for an access token through the owner's workload identity
269
/// provider, and that writes the bucket. No key exists anywhere; the
270
/// access token lasts an hour and is fetched again before it runs out.
271
pub struct Gcs {
272
    bucket: String,
273
    /// Keys go under this, when set.
274
    prefix: String,
275
    storage: String,
276
    sts: String,
277
    /// The provider's resource name, `//iam.googleapis.com/projects/…`.
278
    provider: String,
279
    subject: String,
280
    app: Shared,
281
    client: reqwest::Client,
282
    rt: tokio::runtime::Handle,
283
    token: std::sync::Mutex<Option<(String, i64)>>,
284
}
285
286
impl Gcs {
287
    pub fn new(app: &Shared, s: &Setting) -> Gcs {
288
        Gcs {
289
            bucket: s.target.clone(),
290
            prefix: s.prefix.trim_matches('/').to_string(),
291
            storage: app.config.backups.storage_url.trim_end_matches('/').to_string(),
292
            sts: app.config.backups.sts_url.trim_end_matches('/').to_string(),
293
            provider: s.provider.clone(),
294
            subject: format!("backup:{}", s.owner),
295
            app: app.clone(),
296
            client: reqwest::Client::builder().timeout(std::time::Duration::from_secs(300)).build().unwrap_or_default(),
297
            rt: tokio::runtime::Handle::current(),
298
            token: std::sync::Mutex::new(None),
299
        }
300
    }
301
302
    fn name(&self, key: &str) -> String {
303
        if self.prefix.is_empty() {
304
            key.to_string()
305
        } else {
306
            format!("{}/{key}", self.prefix)
307
        }
308
    }
309
310
    /// An access token, exchanged for a fresh one of the hub's when the
311
    /// last is within five minutes of running out.
312
    fn access(&self) -> Result<String> {
313
        let now = db::now_ms();
314
        if let Some((t, until)) = self.token.lock().unwrap().as_ref() {
315
            if *until - now > 300_000 {
316
                return Ok(t.clone());
317
            }
318
        }
319
        let (token, expires_in) = self.rt.block_on(async {
320
            let issuer = self.app.oidc().await?;
321
            // Google's default audience for a provider: its name over https.
322
            let audience = format!("https:{}", self.provider);
323
            let jwt = issuer.mint_for(self.app.config.base_url(), &self.subject, &audience, db::now_ms(), 600);
324
            let res = self
325
                .client
326
                .post(format!("{}/v1/token", self.sts))
327
                .json(&serde_json::json!({
328
                    "grantType": "urn:ietf:params:oauth:grant-type:token-exchange",
329
                    "audience": self.provider,
330
                    "scope": "https://www.googleapis.com/auth/devstorage.read_write",
331
                    "requestedTokenType": "urn:ietf:params:oauth:token-type:access_token",
332
                    "subjectToken": jwt,
333
                    "subjectTokenType": "urn:ietf:params:oauth:token-type:jwt",
334
                }))
335
                .send()
336
                .await?;
337
            let status = res.status();
338
            let body: serde_json::Value = res.json().await.unwrap_or_default();
339
            if !status.is_success() {
340
                bail!(
341
                    "Google's token exchange refused {}: {} (check the provider's issuer is this hub's address and its attribute condition admits backup:)",
342
                    self.subject,
343
                    body["error_description"].as_str().or(body["error"].as_str()).unwrap_or("no reason given")
344
                );
345
            }
346
            let token = body["access_token"].as_str().context("the token exchange gave no access token")?.to_string();
347
            anyhow::Ok((token, body["expires_in"].as_i64().unwrap_or(3600)))
348
        })?;
349
        *self.token.lock().unwrap() = Some((token.clone(), now + expires_in * 1000));
350
        Ok(token)
351
    }
352
353
    fn object_url(&self, key: &str) -> Result<reqwest::Url> {
354
        let mut u = reqwest::Url::parse(&format!("{}/storage/v1/b/{}/o", self.storage, self.bucket))?;
355
        u.path_segments_mut().map_err(|_| anyhow::anyhow!("bad storage URL"))?.push(&self.name(key));
356
        Ok(u)
357
    }
358
359
    fn refused(&self, what: &str, status: reqwest::StatusCode, body: &str) -> anyhow::Error {
360
        let hint = if status == reqwest::StatusCode::FORBIDDEN || status == reqwest::StatusCode::UNAUTHORIZED {
361
            format!(" (grant roles/storage.objectAdmin on gs://{} to the principal …/subject/{})", self.bucket, self.subject)
362
        } else {
363
            String::new()
364
        };
365
        anyhow::anyhow!("GCS {what}: {status}{hint}: {}", body.chars().take(200).collect::<String>())
366
    }
367
368
    /// Every object name under `full` (no delimiter), for removal.
369
    fn all_under(&self, full: &str) -> Result<Vec<String>> {
370
        let mut out = Vec::new();
371
        let mut page: Option<String> = None;
372
        loop {
373
            let token = self.access()?;
374
            let mut u = reqwest::Url::parse(&format!("{}/storage/v1/b/{}/o", self.storage, self.bucket))?;
375
            u.query_pairs_mut().append_pair("prefix", full).append_pair("fields", "items(name),nextPageToken");
376
            if let Some(p) = &page {
377
                u.query_pairs_mut().append_pair("pageToken", p);
378
            }
379
            let body: serde_json::Value = self.rt.block_on(async {
380
                let res = self.client.get(u).bearer_auth(&token).send().await?;
381
                let status = res.status();
382
                let text = res.text().await?;
383
                if !status.is_success() {
384
                    return Err(self.refused("list", status, &text));
385
                }
386
                anyhow::Ok(serde_json::from_str(&text)?)
387
            })?;
388
            out.extend(body["items"].as_array().into_iter().flatten().filter_map(|i| i["name"].as_str().map(String::from)));
389
            match body["nextPageToken"].as_str() {
390
                Some(p) => page = Some(p.to_string()),
391
                None => return Ok(out),
392
            }
393
        }
394
    }
395
}
396
397
/// An S3 bucket, written keylessly (§3): the hub's own short-lived token
398
/// (`sub = backup:OWNER`, audience `sts.amazonaws.com`) is exchanged at AWS
399
/// STS (AssumeRoleWithWebIdentity) for an hour's credentials of the role
400
/// the owner names, and they sign each request (Signature Version 4).
401
pub struct S3 {
402
    bucket: String,
403
    prefix: String,
404
    region: String,
405
    /// The bucket's endpoint: scheme, host and any path before keys.
406
    base: reqwest::Url,
407
    sts: String,
408
    /// The IAM role's ARN.
409
    role: String,
410
    subject: String,
411
    app: Shared,
412
    client: reqwest::Client,
413
    rt: tokio::runtime::Handle,
414
    creds: std::sync::Mutex<Option<Creds>>,
415
}
416
417
#[derive(Clone)]
418
struct Creds {
419
    id: String,
420
    secret: String,
421
    token: String,
422
    until: i64,
423
}
424
425
/// The audience AWS expects of a web identity token.
426
pub const AWS_AUDIENCE: &str = "sts.amazonaws.com";
427
428
/// Percent-encoding as AWS signs it: everything but unreserved characters,
429
/// and `/` too unless `keep_slash`.
430
pub fn aws_encode(s: &str, keep_slash: bool) -> String {
431
    let mut out = String::new();
432
    for b in s.bytes() {
433
        match b {
434
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(b as char),
435
            b'/' if keep_slash => out.push('/'),
436
            _ => out.push_str(&format!("%{b:02X}")),
437
        }
438
    }
439
    out
440
}
441
442
fn hmac(key: &[u8], data: &str) -> Vec<u8> {
443
    use hmac::Mac;
444
    let mut m = hmac::Hmac::<sha2::Sha256>::new_from_slice(key).expect("any key length");
445
    m.update(data.as_bytes());
446
    m.finalize().into_bytes().to_vec()
447
}
448
449
fn sha256_hex(data: &[u8]) -> String {
450
    use sha2::Digest;
451
    hex::encode(sha2::Sha256::digest(data))
452
}
453
454
/// AWS Signature Version 4: the `Authorization` header for one request.
455
/// `uri` is the path as encoded on the wire, `query` the decoded pairs,
456
/// `headers` the signed ones (any case), `payload` the body's SHA-256 in
457
/// hex, `amz_date` as `20130524T000000Z`.
458
#[allow(clippy::too_many_arguments)]
459
pub fn sigv4(
460
    method: &str,
461
    uri: &str,
462
    query: &[(String, String)],
463
    headers: &[(String, String)],
464
    payload: &str,
465
    (id, secret): (&str, &str),
466
    region: &str,
467
    service: &str,
468
    amz_date: &str,
469
) -> String {
470
    let mut q: Vec<(String, String)> = query.iter().map(|(k, v)| (aws_encode(k, false), aws_encode(v, false))).collect();
471
    q.sort();
472
    let query = q.iter().map(|(k, v)| format!("{k}={v}")).collect::<Vec<_>>().join("&");
473
    let mut h: Vec<(String, String)> = headers.iter().map(|(k, v)| (k.to_ascii_lowercase(), v.trim().to_string())).collect();
474
    h.sort();
475
    let canonical_headers: String = h.iter().map(|(k, v)| format!("{k}:{v}\n")).collect();
476
    let signed = h.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>().join(";");
477
    let request = format!("{method}\n{uri}\n{query}\n{canonical_headers}\n{signed}\n{payload}");
478
    let date = &amz_date[..8];
479
    let scope = format!("{date}/{region}/{service}/aws4_request");
480
    let to_sign = format!("AWS4-HMAC-SHA256\n{amz_date}\n{scope}\n{}", sha256_hex(request.as_bytes()));
481
    let key = hmac(&hmac(&hmac(&hmac(format!("AWS4{secret}").as_bytes(), date), region), service), "aws4_request");
482
    let signature = hex::encode(hmac(&key, &to_sign));
483
    format!("AWS4-HMAC-SHA256 Credential={id}/{scope}, SignedHeaders={signed}, Signature={signature}")
484
}
485
486
/// The text of the first `<tag>` in `xml`, unescaped.
487
fn xml_text(xml: &str, tag: &str) -> Option<String> {
488
    xml_blocks(xml, tag).into_iter().next().map(xml_unescape)
489
}
490
491
/// The inside of every `<tag>…</tag>` in `xml`.
492
fn xml_blocks<'a>(xml: &'a str, tag: &str) -> Vec<&'a str> {
493
    let (open, close) = (format!("<{tag}>"), format!("</{tag}>"));
494
    let mut out = Vec::new();
495
    let mut rest = xml;
496
    while let Some(i) = rest.find(&open) {
497
        let after = &rest[i + open.len()..];
498
        let Some(j) = after.find(&close) else { break };
499
        out.push(&after[..j]);
500
        rest = &after[j + close.len()..];
501
    }
502
    out
503
}
504
505
fn xml_unescape(s: &str) -> String {
506
    s.replace("&lt;", "<").replace("&gt;", ">").replace("&quot;", "\"").replace("&apos;", "'").replace("&amp;", "&")
507
}
508
509
fn amz_date(ms: i64) -> String {
510
    let t = time::OffsetDateTime::from_unix_timestamp_nanos(ms as i128 * 1_000_000).unwrap_or(time::OffsetDateTime::UNIX_EPOCH);
511
    format!("{:04}{:02}{:02}T{:02}{:02}{:02}Z", t.year(), u8::from(t.month()), t.day(), t.hour(), t.minute(), t.second())
512
}
513
514
impl S3 {
515
    pub fn new(app: &Shared, s: &Setting) -> S3 {
516
        let url = app.config.backups.s3_url.replace("{bucket}", &s.target).replace("{region}", &s.region);
517
        S3 {
518
            bucket: s.target.clone(),
519
            prefix: s.prefix.trim_matches('/').to_string(),
520
            region: s.region.clone(),
521
            base: reqwest::Url::parse(url.trim_end_matches('/')).unwrap_or_else(|_| reqwest::Url::parse("https://invalid.").unwrap()),
522
            sts: app.config.backups.aws_sts_url.trim_end_matches('/').to_string(),
523
            role: s.provider.clone(),
524
            subject: format!("backup:{}", s.owner),
525
            app: app.clone(),
526
            client: reqwest::Client::builder().timeout(std::time::Duration::from_secs(300)).build().unwrap_or_default(),
527
            rt: tokio::runtime::Handle::current(),
528
            creds: std::sync::Mutex::new(None),
529
        }
530
    }
531
532
    fn name(&self, key: &str) -> String {
533
        if self.prefix.is_empty() {
534
            key.to_string()
535
        } else {
536
            format!("{}/{key}", self.prefix)
537
        }
538
    }
539
540
    /// Credentials of the owner's role, exchanged again when the last are
541
    /// within five minutes of running out.
542
    fn creds(&self) -> Result<Creds> {
543
        let now = db::now_ms();
544
        if let Some(c) = self.creds.lock().unwrap().as_ref() {
545
            if c.until - now > 300_000 {
546
                return Ok(c.clone());
547
            }
548
        }
549
        let session: String = format!("oxygenhub-{}", self.subject.trim_start_matches("backup:"))
550
            .chars()
551
            .filter(|c| c.is_ascii_alphanumeric() || "=,.@-_".contains(*c))
552
            .take(64)
553
            .collect();
554
        let c = self.rt.block_on(async {
555
            let issuer = self.app.oidc().await?;
556
            let jwt = issuer.mint_for(self.app.config.base_url(), &self.subject, AWS_AUDIENCE, db::now_ms(), 600);
557
            let res = self
558
                .client
559
                .post(format!("{}/", self.sts))
560
                .form(&[
561
                    ("Action", "AssumeRoleWithWebIdentity"),
562
                    ("Version", "2011-06-15"),
563
                    ("RoleArn", self.role.as_str()),
564
                    ("RoleSessionName", session.as_str()),
565
                    ("WebIdentityToken", jwt.as_str()),
566
                    ("DurationSeconds", "3600"),
567
                ])
568
                .send()
569
                .await?;
570
            let status = res.status();
571
            let text = res.text().await.unwrap_or_default();
572
            if !status.is_success() {
573
                bail!(
574
                    "AWS STS refused {} for {}: {} (check the role's trust policy: this hub's address as its OIDC provider, audience {AWS_AUDIENCE}, and sub {})",
575
                    self.subject,
576
                    self.role,
577
                    xml_text(&text, "Message").unwrap_or_else(|| status.to_string()),
578
                    self.subject
579
                );
580
            }
581
            let get = |t: &str| xml_text(&text, t).with_context(|| format!("AWS STS gave no {t}"));
582
            anyhow::Ok(Creds { id: get("AccessKeyId")?, secret: get("SecretAccessKey")?, token: get("SessionToken")?, until: now + 3_600_000 })
583
        })?;
584
        *self.creds.lock().unwrap() = Some(c.clone());
585
        Ok(c)
586
    }
587
588
    /// One signed request: `key` is an object's (none for the bucket).
589
    fn send(
590
        &self,
591
        method: reqwest::Method,
592
        key: Option<&str>,
593
        query: &[(String, String)],
594
        body: Vec<u8>,
595
    ) -> Result<(reqwest::StatusCode, Vec<u8>)> {
596
        let c = self.creds()?;
597
        let base_path = self.base.path().trim_end_matches('/');
598
        let uri = match key {
599
            Some(k) => format!("{base_path}/{}", aws_encode(&self.name(k), true)),
600
            None => format!("{base_path}/"),
601
        };
602
        let host = match self.base.port() {
603
            Some(p) => format!("{}:{p}", self.base.host_str().unwrap_or_default()),
604
            None => self.base.host_str().unwrap_or_default().to_string(),
605
        };
606
        let payload = sha256_hex(&body);
607
        let date = amz_date(db::now_ms());
608
        let headers = vec![
609
            ("host".to_string(), host.clone()),
610
            ("x-amz-content-sha256".to_string(), payload.clone()),
611
            ("x-amz-date".to_string(), date.clone()),
612
            ("x-amz-security-token".to_string(), c.token.clone()),
613
        ];
614
        let auth = sigv4(method.as_str(), &uri, query, &headers, &payload, (&c.id, &c.secret), &self.region, "s3", &date);
615
        let mut q: Vec<(String, String)> = query.iter().map(|(k, v)| (aws_encode(k, false), aws_encode(v, false))).collect();
616
        q.sort();
617
        let qs = q.iter().map(|(k, v)| format!("{k}={v}")).collect::<Vec<_>>().join("&");
618
        let url = format!("{}://{host}{uri}{}{qs}", self.base.scheme(), if qs.is_empty() { "" } else { "?" });
619
        self.rt.block_on(async {
620
            let mut req = self
621
                .client
622
                .request(method, &url)
623
                .header("authorization", auth)
624
                .header("x-amz-content-sha256", &payload)
625
                .header("x-amz-date", &date)
626
                .header("x-amz-security-token", &c.token);
627
            if !body.is_empty() {
628
                req = req.header("content-type", "application/octet-stream").body(body);
629
            }
630
            let res = req.send().await?;
631
            let status = res.status();
632
            anyhow::Ok((status, res.bytes().await?.to_vec()))
633
        })
634
    }
635
636
    fn refused(&self, what: &str, status: reqwest::StatusCode, body: &[u8]) -> anyhow::Error {
637
        let text = String::from_utf8_lossy(body);
638
        let hint = if status == reqwest::StatusCode::FORBIDDEN {
639
            format!(" (the role {} needs s3:GetObject, s3:PutObject, s3:DeleteObject and s3:ListBucket on {})", self.role, self.bucket)
640
        } else {
641
            String::new()
642
        };
643
        anyhow::anyhow!("S3 {what}: {status}{hint}: {}", xml_text(&text, "Message").unwrap_or_else(|| text.chars().take(200).collect()))
644
    }
645
646
    /// The keys under `full` (`delimited`: and the next level's prefixes).
647
    fn listing(&self, full: &str, delimited: bool) -> Result<(Vec<String>, Vec<String>)> {
648
        let (mut keys, mut prefixes) = (Vec::new(), Vec::new());
649
        let mut token: Option<String> = None;
650
        loop {
651
            let mut q = vec![("list-type".to_string(), "2".to_string()), ("prefix".to_string(), full.to_string())];
652
            if delimited {
653
                q.push(("delimiter".to_string(), "/".to_string()));
654
            }
655
            if let Some(t) = &token {
656
                q.push(("continuation-token".to_string(), t.clone()));
657
            }
658
            let (status, body) = self.send(reqwest::Method::GET, None, &q, Vec::new())?;
659
            if !status.is_success() {
660
                return Err(self.refused("list", status, &body));
661
            }
662
            let text = String::from_utf8_lossy(&body).into_owned();
663
            for c in xml_blocks(&text, "Contents") {
664
                keys.extend(xml_text(c, "Key"));
665
            }
666
            for c in xml_blocks(&text, "CommonPrefixes") {
667
                prefixes.extend(xml_text(c, "Prefix"));
668
            }
669
            match (xml_text(&text, "IsTruncated").as_deref(), xml_text(&text, "NextContinuationToken")) {
670
                (Some("true"), Some(t)) => token = Some(t),
671
                _ => return Ok((keys, prefixes)),
672
            }
673
        }
674
    }
675
}
676
677
impl Destination for S3 {
678
    fn exists(&self, key: &str) -> Result<bool> {
679
        let (status, body) = self.send(reqwest::Method::HEAD, Some(key), &[], Vec::new())?;
680
        match status {
681
            s if s.is_success() => Ok(true),
682
            reqwest::StatusCode::NOT_FOUND => Ok(false),
683
            s => Err(self.refused("read", s, &body)),
684
        }
685
    }
686
    fn put(&self, key: &str, bytes: &[u8]) -> Result<()> {
687
        let (status, body) = self.send(reqwest::Method::PUT, Some(key), &[], bytes.to_vec())?;
688
        if !status.is_success() {
689
            return Err(self.refused("write", status, &body));
690
        }
691
        Ok(())
692
    }
693
    fn get(&self, key: &str) -> Result<Vec<u8>> {
694
        let (status, body) = self.send(reqwest::Method::GET, Some(key), &[], Vec::new())?;
695
        if !status.is_success() {
696
            return Err(self.refused(&format!("read {key}"), status, &body));
697
        }
698
        Ok(body)
699
    }
700
    fn list(&self, prefix: &str) -> Result<Vec<String>> {
701
        let full = format!("{}/", self.name(prefix.trim_end_matches('/')));
702
        let (keys, prefixes) = self.listing(&full, true)?;
703
        let mut out: std::collections::BTreeSet<String> = keys.iter().map(|k| k.trim_start_matches(&full).to_string()).collect();
704
        out.extend(prefixes.iter().map(|p| p.trim_start_matches(&full).trim_end_matches('/').to_string()));
705
        Ok(out.into_iter().filter(|n| !n.is_empty()).collect())
706
    }
707
    fn remove(&self, key: &str) -> Result<()> {
708
        let full = self.name(key);
709
        let (mut keys, _) = self.listing(&format!("{full}/"), false)?;
710
        keys.push(full);
711
        for k in keys {
712
            let rel = if self.prefix.is_empty() { k.clone() } else { k.trim_start_matches(&format!("{}/", self.prefix)).to_string() };
713
            let (status, body) = self.send(reqwest::Method::DELETE, Some(&rel), &[], Vec::new())?;
714
            if !status.is_success() && status != reqwest::StatusCode::NOT_FOUND {
715
                return Err(self.refused("remove", status, &body));
716
            }
717
        }
718
        Ok(())
719
    }
720
}
721
722
impl Destination for Gcs {
723
    fn exists(&self, key: &str) -> Result<bool> {
724
        let token = self.access()?;
725
        let mut u = self.object_url(key)?;
726
        u.query_pairs_mut().append_pair("fields", "name");
727
        self.rt.block_on(async {
728
            let res = self.client.get(u).bearer_auth(&token).send().await?;
729
            match res.status() {
730
                s if s.is_success() => Ok(true),
731
                reqwest::StatusCode::NOT_FOUND => Ok(false),
732
                s => Err(self.refused("read", s, &res.text().await.unwrap_or_default())),
733
            }
734
        })
735
    }
736
    fn put(&self, key: &str, bytes: &[u8]) -> Result<()> {
737
        let token = self.access()?;
738
        let mut u = reqwest::Url::parse(&format!("{}/upload/storage/v1/b/{}/o", self.storage, self.bucket))?;
739
        u.query_pairs_mut().append_pair("uploadType", "media").append_pair("name", &self.name(key));
740
        let body = bytes.to_vec();
741
        self.rt.block_on(async {
742
            let res = self.client.post(u).bearer_auth(&token).header("content-type", "application/octet-stream").body(body).send().await?;
743
            let status = res.status();
744
            if !status.is_success() {
745
                return Err(self.refused("write", status, &res.text().await.unwrap_or_default()));
746
            }
747
            Ok(())
748
        })
749
    }
750
    fn get(&self, key: &str) -> Result<Vec<u8>> {
751
        let token = self.access()?;
752
        let mut u = self.object_url(key)?;
753
        u.query_pairs_mut().append_pair("alt", "media");
754
        self.rt.block_on(async {
755
            let res = self.client.get(u).bearer_auth(&token).send().await?;
756
            let status = res.status();
757
            if !status.is_success() {
758
                return Err(self.refused(&format!("read {key}"), status, &res.text().await.unwrap_or_default()));
759
            }
760
            Ok(res.bytes().await?.to_vec())
761
        })
762
    }
763
    fn list(&self, prefix: &str) -> Result<Vec<String>> {
764
        let full = format!("{}/", self.name(prefix.trim_end_matches('/')));
765
        let mut out = std::collections::BTreeSet::new();
766
        let mut page: Option<String> = None;
767
        loop {
768
            let token = self.access()?;
769
            let mut u = reqwest::Url::parse(&format!("{}/storage/v1/b/{}/o", self.storage, self.bucket))?;
770
            u.query_pairs_mut()
771
                .append_pair("prefix", &full)
772
                .append_pair("delimiter", "/")
773
                .append_pair("fields", "items(name),prefixes,nextPageToken");
774
            if let Some(p) = &page {
775
                u.query_pairs_mut().append_pair("pageToken", p);
776
            }
777
            let body: serde_json::Value = self.rt.block_on(async {
778
                let res = self.client.get(u).bearer_auth(&token).send().await?;
779
                let status = res.status();
780
                let text = res.text().await?;
781
                if !status.is_success() {
782
                    return Err(self.refused("list", status, &text));
783
                }
784
                anyhow::Ok(serde_json::from_str(&text)?)
785
            })?;
786
            for n in body["items"].as_array().into_iter().flatten().filter_map(|i| i["name"].as_str()) {
787
                out.insert(n.trim_start_matches(&full).to_string());
788
            }
789
            for p in body["prefixes"].as_array().into_iter().flatten().filter_map(|p| p.as_str()) {
790
                out.insert(p.trim_start_matches(&full).trim_end_matches('/').to_string());
791
            }
792
            match body["nextPageToken"].as_str() {
793
                Some(p) => page = Some(p.to_string()),
794
                None => return Ok(out.into_iter().filter(|n| !n.is_empty()).collect()),
795
            }
796
        }
797
    }
798
    fn remove(&self, key: &str) -> Result<()> {
799
        let mut names = self.all_under(&format!("{}/", self.name(key)))?;
800
        names.push(self.name(key));
801
        for n in names {
802
            let token = self.access()?;
803
            let mut u = reqwest::Url::parse(&format!("{}/storage/v1/b/{}/o", self.storage, self.bucket))?;
804
            u.path_segments_mut().map_err(|_| anyhow::anyhow!("bad storage URL"))?.push(&n);
805
            self.rt.block_on(async {
806
                let res = self.client.delete(u).bearer_auth(&token).send().await?;
807
                match res.status() {
808
                    s if s.is_success() || s == reqwest::StatusCode::NOT_FOUND => Ok(()),
809
                    s => Err(self.refused("delete", s, &res.text().await.unwrap_or_default())),
810
                }
811
            })?;
812
        }
813
        Ok(())
814
    }
815
}
816
817
/// Check a destination end to end: write a probe, read it back, remove it.
818
pub fn probe(dest: &dyn Destination) -> Result<()> {
819
    let marker = format!("probe {}", db::now_ms());
820
    dest.put(".oxyhub-probe", marker.as_bytes())?;
821
    if dest.get(".oxyhub-probe")? != marker.as_bytes() {
822
        bail!("the probe read back differently");
823
    }
824
    dest.remove(".oxyhub-probe")
825
}
826
827
/// The owner's destination, from its setting and the site's rules.
828
pub fn destination(app: &Shared, s: &Setting) -> Result<Box<dyn Destination>> {
829
    match s.destination.as_str() {
830
        "dir" => {
831
            let allowed = &app.config.backups.directories;
832
            let target = PathBuf::from(&s.target);
833
            if !allowed.contains(&target) {
834
                bail!("{} is not a backup directory this hub allows (hub.toml [backups] directories)", s.target);
835
            }
836
            let mut root = target.join(&s.owner);
837
            if !s.prefix.is_empty() {
838
                root = root.join(s.prefix.trim_matches('/'));
839
            }
840
            Ok(Box::new(Directory { root }))
841
        }
842
        "gcs" => {
843
            if s.target.is_empty() || s.provider.is_empty() {
844
                bail!("a GCS destination needs its bucket and its workload identity provider");
845
            }
846
            Ok(Box::new(Gcs::new(app, s)))
847
        }
848
        "s3" => {
849
            if s.target.is_empty() || s.provider.is_empty() || s.region.is_empty() {
850
                bail!("an S3 destination needs its bucket, its region and the IAM role the hub assumes");
851
            }
852
            Ok(Box::new(S3::new(app, s)))
853
        }
854
        other => bail!("unknown destination {other:?}"),
855
    }
856
}
857
858
// ---------------------------------------------------------------- what
859
860
/// One file of a repository's store, in a manifest.
861
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
862
pub struct File {
863
    pub path: String,
864
    pub size: u64,
865
    /// Its modification time in nanoseconds: unchanged size and time mean
866
    /// unchanged content, so it is not hashed again.
867
    pub mtime: i128,
868
    pub hash: String,
869
}
870
871
/// A repository at one run.
872
#[derive(Clone, Debug, Serialize, Deserialize)]
873
pub struct Manifest {
874
    pub owner: String,
875
    pub name: String,
876
    /// `repos` or `wikis`.
877
    pub kind: String,
878
    pub files: Vec<File>,
879
}
880
881
fn blob_key(hash: &str) -> String {
882
    format!("blobs/{}/{hash}", &hash[..2])
883
}
884
885
/// The large files that never change once written come first.
886
fn immutable(path: &str) -> bool {
887
    path.starts_with(".oxy/objects/") && (path.contains("/pack-") || path.contains("/loose/"))
888
}
889
890
#[derive(Default)]
891
struct Sent {
892
    files: i64,
893
    sent: i64,
894
    bytes: i64,
895
}
896
897
/// Walk `dir`, sending each file the destination lacks; `known` says which
898
/// paths are unchanged since the last run (and their hashes).
899
fn copy_dir(dest: &dyn Destination, dir: &Path, known: &HashMap<String, File>, only_immutable: bool, sent: &mut Sent) -> Result<Vec<File>> {
900
    let mut out = Vec::new();
901
    let mut stack = vec![dir.to_path_buf()];
902
    while let Some(d) = stack.pop() {
903
        let entries = match std::fs::read_dir(&d) {
904
            Ok(e) => e,
905
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
906
            Err(e) => return Err(e.into()),
907
        };
908
        for e in entries.flatten() {
909
            let p = e.path();
910
            let ft = e.file_type()?;
911
            if ft.is_dir() {
912
                stack.push(p);
913
                continue;
914
            }
915
            if !ft.is_file() {
916
                continue;
917
            }
918
            let rel = p.strip_prefix(dir).unwrap_or(&p).to_string_lossy().replace('\\', "/");
919
            if only_immutable && !immutable(&rel) {
920
                continue;
921
            }
922
            // A file packed away while the walk ran is simply gone.
923
            let Ok(md) = std::fs::metadata(&p) else { continue };
924
            let mtime =
925
                md.modified().ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_nanos() as i128).unwrap_or(0);
926
            let size = md.len();
927
            sent.files += 1;
928
            if let Some(k) = known.get(&rel).filter(|k| k.size == size && k.mtime == mtime) {
929
                out.push(k.clone());
930
                continue;
931
            }
932
            let Ok(bytes) = std::fs::read(&p) else { continue };
933
            let hash = blake3::hash(&bytes).to_hex().to_string();
934
            let key = blob_key(&hash);
935
            if !dest.exists(&key)? {
936
                dest.put(&key, &bytes)?;
937
                sent.sent += 1;
938
                sent.bytes += bytes.len() as i64;
939
            }
940
            out.push(File { path: rel, size, mtime, hash });
941
        }
942
    }
943
    out.sort_by(|a, b| a.path.cmp(&b.path));
944
    Ok(out)
945
}
946
947
// ---------------------------------------------------------------- records
948
949
/// Tables and columns never written: secrets, credentials, sessions.
950
fn private_table(t: &str) -> bool {
951
    ["secret", "token", "session", "password", "totp", "recovery", "sqlx"].iter().any(|w| t.contains(w))
952
}
953
954
fn private_column(c: &str) -> bool {
955
    ["secret", "token", "password", "salt", "totp", "sealed", "hash_key"].iter().any(|w| c.contains(w))
956
}
957
958
async fn tables(pool: &Pool) -> Result<Vec<String>> {
959
    let mut t = catalog::tables(pool).await?;
960
    t.retain(|t| !private_table(t));
961
    t.sort();
962
    Ok(t)
963
}
964
965
async fn columns(pool: &Pool, table: &str) -> Result<Vec<String>> {
966
    Ok(table_cols(pool, table).await?.into_iter().map(|c| c.name).collect())
967
}
968
969
/// The rows of `table` matching `cond`, as a JSON array, private columns
970
/// left out, blobs as hex and flags as 0 or 1, whichever engine wrote them,
971
/// so a run from either restores into either.
972
async fn rows(pool: &Pool, table: &str, cond: &str) -> Result<serde_json::Value> {
973
    let cols: Vec<Col> = table_cols(pool, table).await?.into_iter().filter(|c| !private_column(&c.name)).collect();
974
    if cols.is_empty() {
975
        return Ok(serde_json::json!([]));
976
    }
977
    let text: String = sqlx::query_scalar(&catalog::rows_sql(table, &cols, cond)).fetch_one(pool).await?;
978
    Ok(serde_json::from_str(&text)?)
979
}
980
981
/// What backups ask of the database's own catalog, per engine. Column
982
/// types are given in SQLite's words (INTEGER, TEXT, BLOB, REAL) plus
983
/// BOOLEAN, which only Postgres has.
984
#[cfg(not(feature = "postgres"))]
985
mod catalog {
986
    use super::{Col, Pool, Result};
987
988
    pub async fn tables(pool: &Pool) -> Result<Vec<String>> {
989
        Ok(sqlx::query_scalar("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'").fetch_all(pool).await?)
990
    }
991
992
    pub async fn cols(pool: &Pool, table: &str) -> Result<Vec<Col>> {
993
        let rows: Vec<(String, String, i64, Option<String>, i64)> =
994
            sqlx::query_as(&format!("SELECT name, type, \"notnull\", dflt_value, pk FROM pragma_table_info('{table}')"))
995
                .fetch_all(pool)
996
                .await?;
997
        Ok(rows.into_iter().map(|(name, ty, notnull, default, pk)| Col { name, ty, notnull: notnull != 0, default, pk }).collect())
998
    }
999
1000
    /// `(parent table, column, parent column)` for each reference.
1001
    pub async fn fks(pool: &Pool, table: &str) -> Result<Vec<(String, String, String)>> {
1002
        Ok(sqlx::query_as(&format!("SELECT \"table\", \"from\", \"to\" FROM pragma_foreign_key_list('{table}')")).fetch_all(pool).await?)
1003
    }
1004
1005
    pub fn rows_sql(table: &str, cols: &[Col], cond: &str) -> String {
1006
        let fields: Vec<String> =
1007
            cols.iter().map(|c| format!("'{0}', CASE WHEN typeof(\"{0}\") = 'blob' THEN hex(\"{0}\") ELSE \"{0}\" END", c.name)).collect();
1008
        format!("SELECT json_group_array(json_object({})) FROM \"{table}\" WHERE {cond}", fields.join(", "))
1009
    }
1010
1011
    /// How a restored row goes in when its key is taken: `INSERT …` then this.
1012
    pub fn insert(verb: super::Verb, _cols: &[String]) -> (&'static str, String) {
1013
        match verb {
1014
            super::Verb::Replace => ("INSERT OR REPLACE", String::new()),
1015
            super::Verb::New => ("INSERT", String::new()),
1016
            super::Verb::Ignore => ("INSERT OR IGNORE", String::new()),
1017
        }
1018
    }
1019
}
1020
1021
#[cfg(feature = "postgres")]
1022
mod catalog {
1023
    use super::{Col, Pool, Result};
1024
1025
    pub async fn tables(pool: &Pool) -> Result<Vec<String>> {
1026
        Ok(sqlx::query_scalar(
1027
            "SELECT CAST(relname AS TEXT) FROM pg_class WHERE relkind = 'r' AND relnamespace = CAST(current_schema() AS regnamespace)",
1028
        )
1029
        .fetch_all(pool)
1030
        .await?)
1031
    }
1032
1033
    /// Generated columns (the search index's) are left out: they are made,
1034
    /// never restored.
1035
    pub async fn cols(pool: &Pool, table: &str) -> Result<Vec<Col>> {
1036
        // pg_catalog, not information_schema: many times faster.
1037
        let rows: Vec<(String, String, bool, Option<String>, i64)> = sqlx::query_as(
1038
            "SELECT CAST(a.attname AS TEXT), format_type(a.atttypid, a.atttypmod), a.attnotnull, pg_get_expr(d.adbin, d.adrelid), \
1039
               CAST(COALESCE((SELECT array_position(k.conkey, a.attnum) FROM pg_constraint k WHERE k.conrelid = t.oid AND k.contype = 'p'), 0) AS BIGINT) \
1040
             FROM pg_attribute a JOIN pg_class t ON t.oid = a.attrelid \
1041
             LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum \
1042
             WHERE t.relname = $1 AND t.relnamespace = CAST(current_schema() AS regnamespace) \
1043
               AND a.attnum > 0 AND NOT a.attisdropped AND a.attgenerated = '' ORDER BY a.attnum",
1044
        )
1045
        .bind(table)
1046
        .fetch_all(pool)
1047
        .await?;
1048
        Ok(rows
1049
            .into_iter()
1050
            .map(|(name, ty, notnull, default, pk)| {
1051
                let ty = match ty.as_str() {
1052
                    "bigint" | "integer" | "smallint" => "INTEGER",
1053
                    "bytea" => "BLOB",
1054
                    "boolean" => "BOOLEAN",
1055
                    "double precision" | "real" => "REAL",
1056
                    _ => "TEXT",
1057
                };
1058
                // An identity column's default is the sequence, as SQLite's
1059
                // rowid: none to give.
1060
                let default = default.filter(|d| !d.starts_with("nextval("));
1061
                Col { name, ty: ty.to_string(), notnull, default, pk }
1062
            })
1063
            .collect())
1064
    }
1065
1066
    /// `(parent table, column, parent column)` for each reference.
1067
    pub async fn fks(pool: &Pool, table: &str) -> Result<Vec<(String, String, String)>> {
1068
        Ok(sqlx::query_as(
1069
            "SELECT CAST(p.relname AS TEXT), CAST(a.attname AS TEXT), CAST(pa.attname AS TEXT) FROM pg_constraint k \
1070
             JOIN pg_class t ON t.oid = k.conrelid JOIN pg_class p ON p.oid = k.confrelid \
1071
             JOIN pg_attribute a ON a.attrelid = k.conrelid AND a.attnum = k.conkey[1] \
1072
             JOIN pg_attribute pa ON pa.attrelid = k.confrelid AND pa.attnum = k.confkey[1] \
1073
             WHERE k.contype = 'f' AND t.relname = $1 AND t.relnamespace = CAST(current_schema() AS regnamespace)",
1074
        )
1075
        .bind(table)
1076
        .fetch_all(pool)
1077
        .await?)
1078
    }
1079
1080
    pub fn rows_sql(table: &str, cols: &[Col], cond: &str) -> String {
1081
        let fields: Vec<String> = cols
1082
            .iter()
1083
            .map(|c| match c.ty.as_str() {
1084
                "BLOB" => format!("upper(encode(\"{0}\", 'hex')) AS \"{0}\"", c.name),
1085
                "BOOLEAN" => format!("CASE WHEN \"{0}\" THEN 1 ELSE 0 END AS \"{0}\"", c.name),
1086
                _ => format!("\"{0}\"", c.name),
1087
            })
1088
            .collect();
1089
        format!("SELECT CAST(COALESCE(json_agg(r), '[]') AS TEXT) FROM (SELECT {} FROM \"{table}\" WHERE {cond}) r", fields.join(", "))
1090
    }
1091
1092
    /// How a restored row goes in when its key is taken: `INSERT …` then this.
1093
    pub fn insert(verb: super::Verb, cols: &[String]) -> (&'static str, String) {
1094
        match verb {
1095
            super::Verb::Replace => {
1096
                let set: Vec<String> = cols.iter().filter(|c| *c != "repo_id").map(|c| format!("\"{c}\" = excluded.\"{c}\"")).collect();
1097
                let tail = if set.is_empty() {
1098
                    " ON CONFLICT (repo_id) DO NOTHING".to_string()
1099
                } else {
1100
                    format!(" ON CONFLICT (repo_id) DO UPDATE SET {}", set.join(", "))
1101
                };
1102
                ("INSERT", tail)
1103
            }
1104
            super::Verb::New => ("INSERT", String::new()),
1105
            super::Verb::Ignore => ("INSERT", " ON CONFLICT DO NOTHING".to_string()),
1106
        }
1107
    }
1108
}
1109
1110
/// How restored rows meet the rows already there.
1111
#[derive(Clone, Copy)]
1112
enum Verb {
1113
    /// One row per repository: the restored one wins.
1114
    Replace,
1115
    /// A row with an id of its own, given a new one.
1116
    New,
1117
    /// Kept as it is when already there.
1118
    Ignore,
1119
}
1120
1121
/// Every row about something: the tables with column `key` equal to `id`,
1122
/// then, three levels deep, the tables whose foreign keys point at rows
1123
/// already taken (an issue's comments, a proposal's reviews and their
1124
/// threads).
1125
async fn records(pool: &Pool, key: &str, id: i64) -> Result<serde_json::Value> {
1126
    let all = tables(pool).await?;
1127
    let mut conds: Vec<(String, String)> = Vec::new();
1128
    for t in &all {
1129
        if columns(pool, t).await?.iter().any(|c| c == key) {
1130
            conds.push((t.clone(), format!("\"{key}\" = {id}")));
1131
        }
1132
    }
1133
    for _ in 0..3 {
1134
        let mut more = Vec::new();
1135
        for t in &all {
1136
            if conds.iter().any(|(c, _)| c == t) || more.iter().any(|(c, _): &(String, String)| c == t) {
1137
                continue;
1138
            }
1139
            let fks = catalog::fks(pool, t).await?;
1140
            if let Some((parent, from, to, pcond)) = fks
1141
                .iter()
1142
                .find_map(|(p, f, to)| conds.iter().find(|(c, _)| c == p).map(|(_, pc)| (p.clone(), f.clone(), to.clone(), pc.clone())))
1143
            {
1144
                more.push((t.clone(), format!("\"{from}\" IN (SELECT \"{to}\" FROM \"{parent}\" WHERE {pcond})")));
1145
            }
1146
        }
1147
        if more.is_empty() {
1148
            break;
1149
        }
1150
        conds.extend(more);
1151
    }
1152
    let mut out = serde_json::Map::new();
1153
    for (t, cond) in conds {
1154
        let r = rows(pool, &t, &cond).await?;
1155
        if r.as_array().is_some_and(|a| !a.is_empty()) {
1156
            out.insert(t, r);
1157
        }
1158
    }
1159
    Ok(serde_json::Value::Object(out))
1160
}
1161
1162
/// The key of a run's records naming the accounts, teams and organisations
1163
/// their rows point at, by id: `{"accounts": {"7": "andy"}, …}`.
1164
const NAMES: &str = "_names";
1165
1166
/// Tables a restore leaves out: the search index (rebuilt from what is
1167
/// restored), and what is passing or personal rather than the
1168
/// repository's: inboxes, webhook deliveries, runners' declines.
1169
const NOT_RESTORED: [&str; 5] = ["search", "notifications", "deliveries", "flow_declines", NAMES];
1170
1171
async fn fk_list(pool: &Pool, table: &str) -> Result<Vec<(String, String, String)>> {
1172
    catalog::fks(pool, table).await
1173
}
1174
1175
/// The names behind the account, team and organisation ids that `rec`'s
1176
/// rows point at, so a restore on another hub finds them again by name.
1177
async fn names_of(pool: &Pool, rec: &serde_json::Value) -> Result<serde_json::Value> {
1178
    let mut ids: HashMap<String, std::collections::BTreeSet<i64>> = HashMap::new();
1179
    for (table, rows) in rec.as_object().into_iter().flatten() {
1180
        let Some(rows) = rows.as_array() else { continue };
1181
        for (parent, from, _) in fk_list(pool, table).await? {
1182
            if ["accounts", "teams", "organisations"].contains(&parent.as_str()) {
1183
                ids.entry(parent).or_default().extend(rows.iter().filter_map(|r| r[&from].as_i64()));
1184
            }
1185
        }
1186
    }
1187
    let mut out = serde_json::Map::new();
1188
    for (kind, sql) in [
1189
        ("accounts", "SELECT id, username FROM accounts WHERE id = $1"),
1190
        ("organisations", "SELECT id, name FROM organisations WHERE id = $1"),
1191
        ("teams", "SELECT t.id, o.name || '/' || t.name FROM teams t JOIN organisations o ON o.id = t.org_id WHERE t.id = $1"),
1192
    ] {
1193
        let mut m = serde_json::Map::new();
1194
        for id in ids.get(kind).into_iter().flatten() {
1195
            if let Some((id, name)) = sqlx::query_as::<_, (i64, String)>(sql).bind(id).fetch_optional(pool).await? {
1196
                m.insert(id.to_string(), name.into());
1197
            }
1198
        }
1199
        out.insert(kind.into(), m.into());
1200
    }
1201
    Ok(out.into())
1202
}
1203
1204
/// The id `name` has on this hub as one of `_names`' kinds.
1205
async fn id_by_name(pool: &Pool, kind: &str, name: &str) -> Result<Option<i64>> {
1206
    Ok(match kind {
1207
        "accounts" => sqlx::query_scalar("SELECT id FROM accounts WHERE username = $1").bind(name).fetch_optional(pool).await?,
1208
        "organisations" => sqlx::query_scalar("SELECT id FROM organisations WHERE name = $1").bind(name).fetch_optional(pool).await?,
1209
        "teams" => match name.split_once('/') {
1210
            Some((org, team)) => {
1211
                sqlx::query_scalar("SELECT t.id FROM teams t JOIN organisations o ON o.id = t.org_id WHERE o.name = $1 AND t.name = $2")
1212
                    .bind(org)
1213
                    .bind(team)
1214
                    .fetch_optional(pool)
1215
                    .await?
1216
            }
1217
            None => None,
1218
        },
1219
        _ => None,
1220
    })
1221
}
1222
1223
/// One column of a table on this hub.
1224
struct Col {
1225
    name: String,
1226
    ty: String,
1227
    notnull: bool,
1228
    default: Option<String>,
1229
    pk: i64,
1230
}
1231
1232
async fn table_cols(pool: &Pool, table: &str) -> Result<Vec<Col>> {
1233
    catalog::cols(pool, table).await
1234
}
1235
1236
/// Bind one value of a backed-up row to a column of type `ty`: blobs were
1237
/// written as hex, flags as 0 or 1 (a Postgres BOOLEAN takes them as such).
1238
fn bind_json<'q>(
1239
    q: sqlx::query::Query<'q, crate::db::Db, <crate::db::Db as sqlx::Database>::Arguments<'q>>,
1240
    v: serde_json::Value,
1241
    ty: &str,
1242
) -> sqlx::query::Query<'q, crate::db::Db, <crate::db::Db as sqlx::Database>::Arguments<'q>> {
1243
    let blob = ty.eq_ignore_ascii_case("BLOB");
1244
    if ty == "BOOLEAN" {
1245
        return match v {
1246
            serde_json::Value::Null => q.bind(None::<bool>),
1247
            serde_json::Value::Bool(b) => q.bind(b),
1248
            serde_json::Value::Number(n) => q.bind(n.as_f64().unwrap_or(0.0) != 0.0),
1249
            other => q.bind(matches!(other.as_str(), Some("1" | "true"))),
1250
        };
1251
    }
1252
    match v {
1253
        serde_json::Value::Null => q.bind(None::<i64>),
1254
        serde_json::Value::Bool(b) => q.bind(b as i64),
1255
        serde_json::Value::Number(n) => match n.as_i64() {
1256
            Some(i) => q.bind(i),
1257
            None => q.bind(n.as_f64().unwrap_or(0.0)),
1258
        },
1259
        serde_json::Value::String(s) if blob => q.bind(hex::decode(&s).unwrap_or_else(|_| s.into_bytes())),
1260
        serde_json::Value::String(s) => q.bind(s),
1261
        other => q.bind(other.to_string()),
1262
    }
1263
}
1264
1265
/// Restore one repository's records from a run into this hub, the
1266
/// repository being `repo` here and `old` in the backup (docs/backups.md
1267
/// §7): its issues, proposals, labels, milestones, releases and their
1268
/// assets, checks, Flow runs and the rest, each table after the tables it
1269
/// points at, every id mapped to its new one and every account, team and
1270
/// organisation found again by name. A row pointing at an account this
1271
/// hub lacks keeps a blank reference where it may, and is left out where
1272
/// it may not. What needs re-entering (webhook secrets, never backed up)
1273
/// and what was left out come back as notes.
1274
async fn restore_records(
1275
    app: &Shared,
1276
    dest: &std::sync::Arc<dyn Destination>,
1277
    rec: &serde_json::Value,
1278
    old: i64,
1279
    repo: i64,
1280
) -> Result<Vec<String>> {
1281
    let pool = &app.db;
1282
    let obj = rec.as_object().context("the records are not an object")?;
1283
    let mut by_name: HashMap<(String, i64), Option<i64>> = HashMap::new();
1284
    for (kind, m) in obj.get(NAMES).and_then(|n| n.as_object()).into_iter().flatten() {
1285
        for (id, name) in m.as_object().into_iter().flatten() {
1286
            let (Ok(id), Some(name)) = (id.parse::<i64>(), name.as_str()) else { continue };
1287
            by_name.insert((kind.clone(), id), id_by_name(pool, kind, name).await?);
1288
        }
1289
    }
1290
    let here: std::collections::HashSet<String> = tables(pool).await?.into_iter().collect();
1291
    let mut notes = Vec::new();
1292
    let mut todo: Vec<String> = Vec::new();
1293
    for t in obj.keys().filter(|t| t.as_str() != "repositories" && !NOT_RESTORED.contains(&t.as_str())) {
1294
        if here.contains(t) {
1295
            todo.push(t.clone());
1296
        } else {
1297
            notes.push(format!("{t}: not a table on this hub, left out"));
1298
        }
1299
    }
1300
    let mut fks: HashMap<String, Vec<(String, String, String)>> = HashMap::new();
1301
    for t in &todo {
1302
        fks.insert(t.clone(), fk_list(pool, t).await?);
1303
    }
1304
    // Each table after the tables of the records it points at.
1305
    let mut order = Vec::new();
1306
    while !todo.is_empty() {
1307
        let mut ready: Vec<String> =
1308
            todo.iter().filter(|t| fks[*t].iter().all(|(p, _, _)| p == *t || !todo.contains(p))).cloned().collect();
1309
        if ready.is_empty() {
1310
            ready.push(todo[0].clone());
1311
        }
1312
        todo.retain(|t| !ready.contains(t));
1313
        order.extend(ready);
1314
    }
1315
    let mut maps: HashMap<String, HashMap<i64, i64>> = HashMap::new();
1316
    maps.insert("repositories".into(), [(old, repo)].into());
1317
    let mut left_out: std::collections::BTreeMap<String, usize> = Default::default();
1318
    let mut tx = pool.begin().await?;
1319
    for table in &order {
1320
        let cols = table_cols(pool, table).await?;
1321
        let keys: Vec<&str> = cols.iter().filter(|c| c.pk > 0).map(|c| c.name.as_str()).collect();
1322
        let by_id = keys == ["id"] && cols.iter().any(|c| c.name == "id" && c.ty.eq_ignore_ascii_case("INTEGER"));
1323
        let verb = if keys == ["repo_id"] {
1324
            Verb::Replace
1325
        } else if by_id {
1326
            Verb::New
1327
        } else {
1328
            Verb::Ignore
1329
        };
1330
        let mut rows: Vec<&serde_json::Map<String, serde_json::Value>> =
1331
            obj[table].as_array().into_iter().flatten().filter_map(|r| r.as_object()).collect();
1332
        rows.sort_by_key(|r| r.get("id").and_then(|v| v.as_i64()).unwrap_or(0));
1333
        'row: for row in rows {
1334
            let (mut names, mut values) = (Vec::new(), Vec::new());
1335
            for c in &cols {
1336
                if by_id && c.name == "id" {
1337
                    continue;
1338
                }
1339
                let mut v = row.get(&c.name).cloned().filter(|v| !v.is_null());
1340
                if let Some((parent, _, _)) = fks[table].iter().find(|(_, from, _)| *from == c.name) {
1341
                    if let Some(was) = v.as_ref().and_then(|v| v.as_i64()) {
1342
                        let now = match parent.as_str() {
1343
                            "accounts" | "teams" | "organisations" => by_name.get(&(parent.clone(), was)).copied().flatten(),
1344
                            p => maps.get(p).and_then(|m| m.get(&was)).copied(),
1345
                        };
1346
                        if now.is_none() && c.notnull {
1347
                            *left_out.entry(table.clone()).or_default() += 1;
1348
                            continue 'row;
1349
                        }
1350
                        v = now.map(serde_json::Value::from);
1351
                    }
1352
                }
1353
                match v {
1354
                    Some(v) => {
1355
                        names.push(c.name.clone());
1356
                        values.push((v, c.ty.as_str()));
1357
                    }
1358
                    // Never backed up (a secret): blank here, to enter again.
1359
                    None if c.notnull && c.default.is_none() => {
1360
                        names.push(c.name.clone());
1361
                        let blank = if c.ty.to_ascii_uppercase().contains("INT") || c.ty == "BOOLEAN" {
1362
                            serde_json::json!(0)
1363
                        } else {
1364
                            serde_json::json!("")
1365
                        };
1366
                        values.push((blank, c.ty.as_str()));
1367
                    }
1368
                    None => {}
1369
                }
1370
            }
1371
            // A row with a new id says what it is (a plain INSERT, so one row).
1372
            let (insert, tail) = catalog::insert(verb, &names);
1373
            let sql = format!(
1374
                "{insert} INTO \"{table}\" ({}) VALUES ({}){tail}{}",
1375
                names.iter().map(|n| format!("\"{n}\"")).collect::<Vec<_>>().join(", "),
1376
                (1..=names.len()).map(|i| format!("${i}")).collect::<Vec<_>>().join(", "),
1377
                if by_id { " RETURNING id" } else { "" }
1378
            );
1379
            let mut q = sqlx::query(&sql);
1380
            for (v, ty) in values {
1381
                q = bind_json(q, v, ty);
1382
            }
1383
            let context = || format!("restore a row of {table}");
1384
            if by_id {
1385
                let made: i64 = sqlx::Row::try_get(&q.fetch_one(&mut *tx).await.with_context(context)?, 0)?;
1386
                if let Some(was) = row.get("id").and_then(|v| v.as_i64()) {
1387
                    maps.entry(table.clone()).or_default().insert(was, made);
1388
                }
1389
            } else {
1390
                q.execute(&mut *tx).await.with_context(context)?;
1391
            }
1392
        }
1393
    }
1394
    tx.commit().await?;
1395
    for (table, n) in left_out {
1396
        notes.push(format!("{table}: {n} row(s) left out: they name accounts or rows this hub lacks"));
1397
    }
1398
    // Search finds what came back.
1399
    for (kind, table) in [("issue", "issues"), ("proposal", "proposals")] {
1400
        let found: Vec<(i64, i64, String, String)> =
1401
            sqlx::query_as(&format!("SELECT id, number, title, body FROM {table} WHERE repo_id = $1")).bind(repo).fetch_all(pool).await?;
1402
        for (id, number, title, body) in found {
1403
            db::notify::index(pool, kind, repo, id, number, &title, &body).await?;
1404
        }
1405
    }
1406
    // Webhook secrets were never written: they are entered again.
1407
    let hooks: Vec<String> =
1408
        sqlx::query_scalar("SELECT url FROM hooks WHERE repo_id = $1 AND secret = ''").bind(repo).fetch_all(pool).await?;
1409
    for url in hooks {
1410
        notes.push(format!("webhook {url}: enter its secret again (Settings › Webhooks)"));
1411
    }
1412
    // Release assets, each checked against its name.
1413
    for hash in obj.get("release_assets").and_then(|a| a.as_array()).into_iter().flatten().filter_map(|a| a["hash"].as_str()) {
1414
        if hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
1415
            continue;
1416
        }
1417
        let path = crate::web::releases::blob_path(app, hash);
1418
        if path.exists() {
1419
            continue;
1420
        }
1421
        let got = tokio::task::block_in_place(|| dest.get(&blob_key(hash)));
1422
        match got {
1423
            Ok(bytes) if blake3::hash(&bytes).to_hex().as_str() == hash => {
1424
                std::fs::create_dir_all(path.parent().context("no parent")?)?;
1425
                std::fs::write(&path, &bytes)?;
1426
            }
1427
            Ok(_) => notes.push(format!("release asset {}: the copy does not match its hash", &hash[..12])),
1428
            Err(_) => notes.push(format!("release asset {}: not in the backup", &hash[..12])),
1429
        }
1430
    }
1431
    Ok(notes)
1432
}
1433
1434
// ---------------------------------------------------------------- a run
1435
1436
fn run_name(ms: i64) -> String {
1437
    let t = time::OffsetDateTime::from_unix_timestamp_nanos(ms as i128 * 1_000_000).unwrap_or(time::OffsetDateTime::UNIX_EPOCH);
1438
    format!("{:04}{:02}{:02}T{:02}{:02}{:02}Z", t.year(), u8::from(t.month()), t.day(), t.hour(), t.minute(), t.second())
1439
}
1440
1441
/// The last whole run's manifests, by `kind/name`.
1442
fn last_manifests(dest: &dyn Destination) -> HashMap<String, HashMap<String, File>> {
1443
    let mut out = HashMap::new();
1444
    let Ok(at) = dest.get("LATEST").map(|b| String::from_utf8_lossy(&b).trim().to_string()) else { return out };
1445
    for name in dest.list(&format!("runs/{at}/repos")).unwrap_or_default() {
1446
        if let Ok(m) = dest.get(&format!("runs/{at}/repos/{name}")).and_then(|b| Ok(serde_json::from_slice::<Manifest>(&b)?)) {
1447
            out.insert(format!("{}/{}", m.kind, m.name), m.files.into_iter().map(|f| (f.path.clone(), f)).collect());
1448
        }
1449
    }
1450
    out
1451
}
1452
1453
/// Back up `owner` now, as its setting says. The run is recorded whatever
1454
/// happens; a failure notifies the owner once until a run succeeds.
1455
pub async fn run(app: &Shared, owner: &str, trigger: &str) -> Result<Run> {
1456
    let s = setting(&app.db, owner).await?.with_context(|| format!("{owner} has no backup set up"))?;
1457
    let started = db::now_ms();
1458
    let at = run_name(started);
1459
    let id: i64 = sqlx::query_scalar(
1460
        "INSERT INTO backup_runs (owner, started_ms, status, at, trigger) VALUES ($1, $2, 'running', $3, $4) RETURNING id",
1461
    )
1462
    .bind(owner)
1463
    .bind(started)
1464
    .bind(&at)
1465
    .bind(trigger)
1466
    .fetch_one(&app.db)
1467
    .await?;
1468
    let outcome = run_into(app, &s, &at, trigger == "now").await;
1469
    let (status, detail, sent) = match outcome {
1470
        Ok((sent, problems)) if problems.is_empty() => ("ok", String::new(), sent),
1471
        Ok((sent, problems)) => ("partial", problems.join("; "), sent),
1472
        Err(e) => ("failed", format!("{e:#}"), (0, Sent::default())),
1473
    };
1474
    sqlx::query(
1475
        "UPDATE backup_runs SET finished_ms = $1, status = $2, detail = $3, repos = $4, files = $5, sent = $6, bytes = $7 WHERE id = $8",
1476
    )
1477
    .bind(db::now_ms())
1478
    .bind(status)
1479
    .bind(&detail)
1480
    .bind(sent.0)
1481
    .bind(sent.1.files)
1482
    .bind(sent.1.sent)
1483
    .bind(sent.1.bytes)
1484
    .bind(id)
1485
    .execute(&app.db)
1486
    .await?;
1487
    let r: Run = sqlx::query_as("SELECT * FROM backup_runs WHERE id = $1").bind(id).fetch_one(&app.db).await?;
1488
    if status != "ok" {
1489
        notify_failure(app, &s, status, &detail).await;
1490
    } else {
1491
        notify_recovered(app, &s, &r).await;
1492
    }
1493
    Ok(r)
1494
}
1495
1496
async fn run_into(app: &Shared, s: &Setting, at: &str, by_hand: bool) -> Result<((i64, Sent), Vec<String>)> {
1497
    let dest: std::sync::Arc<dyn Destination> = destination(app, s)?.into();
1498
    let known = {
1499
        let d = dest.clone();
1500
        tokio::task::spawn_blocking(move || last_manifests(d.as_ref())).await?
1501
    };
1502
    // Its repositories, but those left out (§5).
1503
    let mine: Vec<db::repos::RepoRow> =
1504
        db::repos::list(&app.db).await?.into_iter().filter(|r| r.owner == s.owner && included(s, r, by_hand)).collect();
1505
    let mut problems = Vec::new();
1506
    let mut sent = Sent::default();
1507
    let mut repos = 0i64;
1508
    for row in &mine {
1509
        let Some(name) = RepoName::new(&row.owner, &row.name) else { continue };
1510
        for (kind, store) in [("repos", &app.repos), ("wikis", &app.wikis)] {
1511
            if !store.exists(&name) {
1512
                continue;
1513
            }
1514
            let dir = store.dir(&name);
1515
            let k = known.get(&format!("{kind}/{}", row.name)).cloned().unwrap_or_default();
1516
            // The large, unchanging files without the lock, then the whole
1517
            // walk again under the read lock: pushes wait for that moment.
1518
            let (d1, dir1, k1) = (dest.clone(), dir.clone(), k.clone());
1519
            let first = tokio::task::spawn_blocking(move || {
1520
                let mut s = Sent::default();
1521
                copy_dir(d1.as_ref(), &dir1, &k1, true, &mut s).map(|f| (f, s))
1522
            })
1523
            .await?;
1524
            let mut k2 = k;
1525
            if let Ok((files, _)) = &first {
1526
                for f in files {
1527
                    k2.insert(f.path.clone(), f.clone());
1528
                }
1529
            }
1530
            // Writers wait while the last pass copies (readers carry on),
1531
            // so the refs copied name only objects copied (#249).
1532
            let guard = store.write_guard(&name).await;
1533
            let (d2, dir2) = (dest.clone(), dir.clone());
1534
            let second = tokio::task::spawn_blocking(move || {
1535
                let _guard = guard;
1536
                let mut s = Sent::default();
1537
                copy_dir(d2.as_ref(), &dir2, &k2, false, &mut s).map(|f| (f, s))
1538
            })
1539
            .await?;
1540
            match second {
1541
                Ok((files, s2)) => {
1542
                    let s1 = first.map(|(_, s)| s).unwrap_or_default();
1543
                    sent.files += s2.files;
1544
                    sent.sent += s1.sent + s2.sent;
1545
                    sent.bytes += s1.bytes + s2.bytes;
1546
                    let m = Manifest { owner: row.owner.clone(), name: row.name.clone(), kind: kind.into(), files };
1547
                    let key = format!("runs/{at}/repos/{kind}-{}.json", row.name);
1548
                    tokio::task::block_in_place(|| dest.put(&key, &serde_json::to_vec(&m)?))?;
1549
                    if kind == "repos" {
1550
                        repos += 1;
1551
                    }
1552
                }
1553
                Err(e) => problems.push(format!("{}/{} ({kind}): {e:#}", row.owner, row.name)),
1554
            }
1555
        }
1556
        let rec = async {
1557
            let mut r = records(&app.db, "repo_id", row.id).await?;
1558
            // The repository's own row, which restore recreates first, and
1559
            // the names behind the accounts, teams and organisations its
1560
            // rows point at, which another hub finds them by.
1561
            let own = rows(&app.db, "repositories", &format!("id = {}", row.id)).await?;
1562
            let names = names_of(&app.db, &r).await?;
1563
            if let Some(m) = r.as_object_mut() {
1564
                m.insert("repositories".into(), own);
1565
                m.insert(NAMES.into(), names);
1566
            }
1567
            anyhow::Ok(r)
1568
        };
1569
        match rec.await {
1570
            Ok(r) => {
1571
                tokio::task::block_in_place(|| dest.put(&format!("runs/{at}/records/{}.json", row.name), &serde_json::to_vec(&r)?))?;
1572
                // Release assets live beside the stores, named by their
1573
                // BLAKE3: each sent once, as the stores' files are.
1574
                for hash in r["release_assets"].as_array().into_iter().flatten().filter_map(|a| a["hash"].as_str()) {
1575
                    if hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
1576
                        continue;
1577
                    }
1578
                    let path = crate::web::releases::blob_path(app, hash);
1579
                    let key = blob_key(hash);
1580
                    let put = tokio::task::block_in_place(|| -> Result<Option<i64>> {
1581
                        if dest.exists(&key)? {
1582
                            return Ok(None);
1583
                        }
1584
                        let bytes = std::fs::read(&path).with_context(|| format!("read release asset {}", &hash[..12]))?;
1585
                        dest.put(&key, &bytes)?;
1586
                        Ok(Some(bytes.len() as i64))
1587
                    });
1588
                    match put {
1589
                        Ok(Some(n)) => {
1590
                            sent.files += 1;
1591
                            sent.sent += 1;
1592
                            sent.bytes += n;
1593
                        }
1594
                        Ok(None) => sent.files += 1,
1595
                        Err(e) => problems.push(format!("{}/{} release asset: {e:#}", row.owner, row.name)),
1596
                    }
1597
                }
1598
            }
1599
            Err(e) => problems.push(format!("{}/{} records: {e:#}", row.owner, row.name)),
1600
        }
1601
    }
1602
    // The owner itself.
1603
    let owner_rows = if s.kind == "org" {
1604
        match db::accounts::org_by_name(&app.db, &s.owner).await? {
1605
            Some(o) => records(&app.db, "org_id", o.id).await?,
1606
            None => serde_json::json!({}),
1607
        }
1608
    } else {
1609
        match db::accounts::account_by_name(&app.db, &s.owner).await? {
1610
            Some(a) => records(&app.db, "account_id", a.id).await?,
1611
            None => serde_json::json!({}),
1612
        }
1613
    };
1614
    // The blocking calls of a destination (GCS drives its client on this
1615
    // runtime) run where blocking is allowed.
1616
    tokio::task::block_in_place(|| -> Result<()> {
1617
        dest.put(&format!("runs/{at}/owner.json"), &serde_json::to_vec(&owner_rows)?)?;
1618
        dest.put(&format!("runs/{at}/DONE"), at.as_bytes())?;
1619
        dest.put("LATEST", at.as_bytes())?;
1620
        prune(dest.as_ref(), s.keep_days)
1621
    })?;
1622
    Ok(((repos, sent), problems))
1623
}
1624
1625
/// Drop whole runs older than `keep_days`, and the blobs no kept run
1626
/// names. The newest whole run is always kept.
1627
pub fn prune(dest: &dyn Destination, keep_days: i64) -> Result<()> {
1628
    let cutoff = run_name(db::now_ms() - keep_days.max(1) * 86_400_000);
1629
    let runs = dest.list("runs")?;
1630
    let whole: Vec<&String> = runs.iter().filter(|r| dest.exists(&format!("runs/{r}/DONE")).unwrap_or(false)).collect();
1631
    let newest = whole.last().map(|s| s.to_string());
1632
    let mut removed = false;
1633
    for r in &runs {
1634
        if r.as_str() < cutoff.as_str() && Some(r.to_string()) != newest {
1635
            dest.remove(&format!("runs/{r}"))?;
1636
            removed = true;
1637
        }
1638
    }
1639
    if !removed {
1640
        return Ok(());
1641
    }
1642
    let mut wanted = std::collections::HashSet::new();
1643
    for r in dest.list("runs")? {
1644
        for m in dest.list(&format!("runs/{r}/repos"))? {
1645
            if let Ok(m) = dest.get(&format!("runs/{r}/repos/{m}")).and_then(|b| Ok(serde_json::from_slice::<Manifest>(&b)?)) {
1646
                wanted.extend(m.files.into_iter().map(|f| f.hash));
1647
            }
1648
        }
1649
    }
1650
    for shard in dest.list("blobs")? {
1651
        for b in dest.list(&format!("blobs/{shard}"))? {
1652
            if !wanted.contains(&b) {
1653
                dest.remove(&format!("blobs/{shard}/{b}"))?;
1654
            }
1655
        }
1656
    }
1657
    Ok(())
1658
}
1659
1660
/// Who hears about `s`'s backups, and where they look: the user, or the
1661
/// organisation's owners.
1662
async fn told(app: &Shared, s: &Setting) -> Option<(Vec<(i64, db::notify::Reason)>, String)> {
1663
    let p = db::notify::Reason::Participating;
1664
    if s.kind == "org" {
1665
        let o = db::accounts::org_by_name(&app.db, &s.owner).await.ok().flatten()?;
1666
        let owners = db::accounts::org_members(&app.db, o.id)
1667
            .await
1668
            .ok()?
1669
            .into_iter()
1670
            .filter(|(_, r)| r == "owner")
1671
            .map(|(a, _)| (a.id, p))
1672
            .collect();
1673
        Some((owners, format!("/orgs/{}/settings/backups", s.owner)))
1674
    } else {
1675
        let a = db::accounts::account_by_name(&app.db, &s.owner).await.ok().flatten()?;
1676
        Some((vec![(a.id, p)], "/settings/backups".into()))
1677
    }
1678
}
1679
1680
/// The status of `owner`'s finished run before the newest.
1681
async fn status_before(app: &Shared, owner: &str) -> Option<String> {
1682
    sqlx::query_scalar("SELECT status FROM backup_runs WHERE owner = $1 AND finished_ms IS NOT NULL ORDER BY id DESC LIMIT 1 OFFSET 1")
1683
        .bind(owner)
1684
        .fetch_optional(&app.db)
1685
        .await
1686
        .ok()
1687
        .flatten()
1688
}
1689
1690
/// A run that did not finish whole tells the owner (inbox and email), once
1691
/// per spell of failures: not when the run before failed too.
1692
async fn notify_failure(app: &Shared, s: &Setting, status: &str, detail: &str) {
1693
    if status_before(app, &s.owner).await.is_some_and(|b| b != "ok") {
1694
        return;
1695
    }
1696
    let Some((who, url)) = told(app, s).await else { return };
1697
    let title = format!("Backup of {} {status}: {}", s.owner, detail.chars().take(160).collect::<String>());
1698
    crate::notify::tell(app, "backup", &title, &url, "backups", None, who).await;
1699
}
1700
1701
/// A whole run after one that was not: the owner hears it works again
1702
/// (oxygenhub#183).
1703
async fn notify_recovered(app: &Shared, s: &Setting, run: &Run) {
1704
    if !status_before(app, &s.owner).await.is_some_and(|b| b != "ok") {
1705
        return;
1706
    }
1707
    let Some((who, url)) = told(app, s).await else { return };
1708
    let title = format!("Backup of {} works again: {} repositories to {}", s.owner, run.repos, place(s));
1709
    crate::notify::tell(app, "backup.recovered", &title, &url, "backups", None, who).await;
1710
}
1711
1712
/// The hour (UTC) each day's backup summary goes out.
1713
const SUMMARY_HOUR: u8 = 7;
1714
const SUMMARY_SENT: &str = "backups.summary_day";
1715
1716
/// One message a day per owner (oxygenhub#183): the last day's runs, how
1717
/// they went and what they sent. Sent at the first scheduler tick from
1718
/// SUMMARY_HOUR (UTC), once a day. How many owners were told.
1719
pub async fn daily_summary(app: &Shared, now_ms: i64, force: bool) -> sqlx::Result<usize> {
1720
    let t = time::OffsetDateTime::from_unix_timestamp_nanos(now_ms as i128 * 1_000_000).unwrap_or(time::OffsetDateTime::UNIX_EPOCH);
1721
    let day = format!("{:04}-{:02}-{:02}", t.year(), u8::from(t.month()), t.day());
1722
    if !force && (t.hour() < SUMMARY_HOUR || db::accounts::setting(&app.db, SUMMARY_SENT).await?.as_deref() == Some(day.as_str())) {
1723
        return Ok(0);
1724
    }
1725
    db::accounts::set_setting(&app.db, SUMMARY_SENT, &day).await?;
1726
    let settings: Vec<Setting> = sqlx::query_as("SELECT * FROM backup_settings WHERE updated_ms > 0").fetch_all(&app.db).await?;
1727
    let mut sent = 0;
1728
    for s in settings {
1729
        let runs: Vec<Run> = sqlx::query_as("SELECT * FROM backup_runs WHERE owner = $1 AND started_ms >= $2 ORDER BY id")
1730
            .bind(&s.owner)
1731
            .bind(now_ms - 86_400_000)
1732
            .fetch_all(&app.db)
1733
            .await?;
1734
        if runs.is_empty() {
1735
            continue;
1736
        }
1737
        let ok = runs.iter().filter(|r| r.status == "ok").count();
1738
        let bytes: i64 = runs.iter().map(|r| r.bytes).sum();
1739
        let repos = runs.iter().rev().find(|r| r.status == "ok").map_or(0, |r| r.repos);
1740
        let how = if ok == runs.len() { "all ok".to_string() } else { format!("{} not whole", runs.len() - ok) };
1741
        let title = format!(
1742
            "Backups of {} today: {} runs, {how}, {repos} repositories, {:.1} MiB sent to {}",
1743
            s.owner,
1744
            runs.len(),
1745
            bytes as f64 / 1_048_576.0,
1746
            place(&s)
1747
        );
1748
        let Some((who, url)) = told(app, &s).await else { continue };
1749
        crate::notify::tell(app, "backup.summary", &title, &url, "backups", None, who).await;
1750
        sent += 1;
1751
    }
1752
    Ok(sent)
1753
}
1754
1755
/// Run each owner's backup when it is due, one at a time. A run left
1756
/// "running" by a restart is marked failed first.
1757
pub async fn scheduler(app: Shared) {
1758
    let _ = sqlx::query(
1759
        "UPDATE backup_runs SET status = 'failed', detail = 'the hub restarted during the run', finished_ms = $1 WHERE status = 'running'",
1760
    )
1761
    .bind(db::now_ms())
1762
    .execute(&app.db)
1763
    .await;
1764
    loop {
1765
        tokio::time::sleep(std::time::Duration::from_secs(60)).await;
1766
        if let Err(e) = daily_summary(&app, db::now_ms(), false).await {
1767
            tracing::warn!("backup summary: {e}");
1768
        }
1769
        for s in due(&app.db).await.unwrap_or_default() {
1770
            if let Err(e) = run(&app, &s.owner, "schedule").await {
1771
                tracing::warn!("backup of {}: {e:#}", s.owner);
1772
            }
1773
        }
1774
    }
1775
}
1776
1777
/// The owners whose next run is due now: by their own schedule, or by
1778
/// the shortest schedule one of their repositories chose (§5). A run takes
1779
/// every included repository and sends only what changed, so each run
1780
/// stays whole and a restore point has everything.
1781
pub async fn due(pool: &Pool) -> sqlx::Result<Vec<Setting>> {
1782
    let all: Vec<Setting> = sqlx::query_as("SELECT * FROM backup_settings WHERE updated_ms > 0").fetch_all(pool).await?;
1783
    let repos = db::repos::list(pool).await?;
1784
    let now = db::now_ms();
1785
    let mut out = Vec::new();
1786
    for s in all {
1787
        let theirs: Vec<db::repos::RepoRow> = repos.iter().filter(|r| r.owner == s.owner).cloned().collect();
1788
        let Some(period) = period_with(&s, &theirs) else { continue };
1789
        let last: Option<i64> =
1790
            sqlx::query_scalar("SELECT MAX(started_ms) FROM backup_runs WHERE owner = $1").bind(&s.owner).fetch_one(pool).await?;
1791
        if last.is_none_or(|l| now - l >= period * 1000) {
1792
            out.push(s);
1793
        }
1794
    }
1795
    Ok(out)
1796
}
1797
1798
/// Restore every repository of the whole run `at` (the latest when none)
1799
/// from `dest` into `repos_root/OWNER/NAME` and `wikis_root/…`, refusing to
1800
/// overwrite one that exists. Each file is checked against its hash.
1801
pub fn restore(dest: &dyn Destination, at: Option<&str>, repos_root: &Path, wikis_root: &Path) -> Result<Vec<String>> {
1802
    let at = match at {
1803
        Some(a) => a.to_string(),
1804
        None => String::from_utf8_lossy(&dest.get("LATEST").context("no whole run at this destination")?).trim().to_string(),
1805
    };
1806
    if !dest.exists(&format!("runs/{at}/DONE"))? {
1807
        bail!("run {at} is not whole (no DONE): pick another with --run");
1808
    }
1809
    let mut done = Vec::new();
1810
    for name in dest.list(&format!("runs/{at}/repos"))? {
1811
        let m: Manifest = serde_json::from_slice(&dest.get(&format!("runs/{at}/repos/{name}"))?)?;
1812
        let root = if m.kind == "wikis" { wikis_root } else { repos_root };
1813
        let dir = root.join(&m.owner).join(&m.name);
1814
        if dir.exists() {
1815
            bail!("{} exists: restore into an empty hub, or move it aside", dir.display());
1816
        }
1817
        for f in &m.files {
1818
            let bytes = dest.get(&blob_key(&f.hash))?;
1819
            if blake3::hash(&bytes).to_hex().as_str() != f.hash {
1820
                bail!("{}/{} {}: the copy does not match its hash", m.owner, m.name, f.path);
1821
            }
1822
            let p = dir.join(&f.path);
1823
            std::fs::create_dir_all(p.parent().context("no parent")?)?;
1824
            std::fs::write(&p, &bytes)?;
1825
        }
1826
        done.push(format!("{}/{} ({})", m.owner, m.name, m.kind));
1827
    }
1828
    Ok(done)
1829
}
1830
1831
/// Restore the whole run `at` (the latest when none) into this hub: each
1832
/// repository's and wiki's store byte for byte, then its row and settings,
1833
/// then its records (issues, proposals, releases and the rest), so it shows
1834
/// on the hub as it was (docs/backups.md §7). What was restored, then any
1835
/// notes (`note: …`) on what needs entering again or was left out.
1836
pub async fn restore_into_hub(app: &Shared, dest: std::sync::Arc<dyn Destination>, at: Option<String>) -> Result<Vec<String>> {
1837
    let (repos_root, wikis_root) = (app.repos.root().to_path_buf(), app.wikis.root().to_path_buf());
1838
    let (d, a) = (dest.clone(), at.clone());
1839
    let done = tokio::task::spawn_blocking(move || restore(d.as_ref(), a.as_deref(), &repos_root, &wikis_root)).await??;
1840
    let at = match at {
1841
        Some(a) => a,
1842
        None => String::from_utf8_lossy(&tokio::task::block_in_place(|| dest.get("LATEST"))?).trim().to_string(),
1843
    };
1844
    let mut notes = Vec::new();
1845
    for name in tokio::task::block_in_place(|| dest.list(&format!("runs/{at}/records")))? {
1846
        let rec: serde_json::Value =
1847
            serde_json::from_slice(&tokio::task::block_in_place(|| dest.get(&format!("runs/{at}/records/{name}")))?)?;
1848
        let Some(row) = rec["repositories"].as_array().and_then(|a| a.first()) else { continue };
1849
        let (owner, repo) = (row["owner"].as_str().unwrap_or_default(), row["name"].as_str().unwrap_or_default());
1850
        if owner.is_empty() || db::repos::get(&app.db, owner, repo).await?.is_some() {
1851
            continue;
1852
        }
1853
        let visibility = match row["visibility"].as_str() {
1854
            Some("private") => hub_api::Visibility::Private,
1855
            Some("internal") => hub_api::Visibility::Internal,
1856
            _ => hub_api::Visibility::Public,
1857
        };
1858
        let made = db::repos::create(&app.db, owner, repo, row["description"].as_str().unwrap_or_default(), visibility).await?;
1859
        // Its settings as they were: every column the row kept but its
1860
        // name, its id and a fork's parent (another hub's id).
1861
        let cols = table_cols(&app.db, "repositories").await?;
1862
        let set: Vec<(&Col, serde_json::Value)> = cols
1863
            .iter()
1864
            .filter(|c| !["id", "owner", "name", "forked_from"].contains(&c.name.as_str()))
1865
            .filter_map(|c| row.get(&c.name).filter(|v| !v.is_null()).map(|v| (c, v.clone())))
1866
            .collect();
1867
        if !set.is_empty() {
1868
            let sql = format!(
1869
                "UPDATE repositories SET {} WHERE id = ${}",
1870
                set.iter().enumerate().map(|(i, (c, _))| format!("\"{}\" = ${}", c.name, i + 1)).collect::<Vec<_>>().join(", "),
1871
                set.len() + 1
1872
            );
1873
            let mut q = sqlx::query(&sql);
1874
            for (c, v) in set {
1875
                q = bind_json(q, v, &c.ty);
1876
            }
1877
            q.bind(made.id).execute(&app.db).await?;
1878
        }
1879
        let old = row["id"].as_i64().unwrap_or(-1);
1880
        for n in restore_records(app, &dest, &rec, old, made.id).await.with_context(|| format!("restore {owner}/{repo}'s records"))? {
1881
            notes.push(format!("note: {owner}/{repo}: {n}"));
1882
        }
1883
    }
1884
    let mut done = done;
1885
    done.extend(notes);
1886
    Ok(done)
1887
}
1888
1889
#[cfg(test)]
1890
mod tests {
1891
    use super::*;
1892
1893
    #[test]
1894
    fn a_directory_destination_keeps_keys_inside_its_root() {
1895
        let d = tempfile::tempdir().unwrap();
1896
        let dest = Directory { root: d.path().to_path_buf() };
1897
        dest.put("runs/a/DONE", b"a").unwrap();
1898
        assert_eq!(dest.get("runs/a/DONE").unwrap(), b"a");
1899
        assert_eq!(dest.list("runs").unwrap(), vec!["a"]);
1900
        assert!(dest.put("../escape", b"x").is_err() && dest.put("/abs", b"x").is_err());
1901
        dest.remove("runs").unwrap();
1902
        assert!(dest.list("runs").unwrap().is_empty());
1903
    }
1904
1905
    #[test]
1906
    fn files_are_sent_once_and_unchanged_ones_not_read_again() {
1907
        let src = tempfile::tempdir().unwrap();
1908
        let out = tempfile::tempdir().unwrap();
1909
        let dest = Directory { root: out.path().to_path_buf() };
1910
        std::fs::create_dir_all(src.path().join(".oxy/objects/loose")).unwrap();
1911
        std::fs::write(src.path().join(".oxy/objects/loose/aa"), b"object").unwrap();
1912
        std::fs::write(src.path().join(".oxy/ops-head"), b"ref one").unwrap();
1913
        let mut s = Sent::default();
1914
        let files = copy_dir(&dest, src.path(), &HashMap::new(), false, &mut s).unwrap();
1915
        assert_eq!((files.len(), s.sent), (2, 2));
1916
        let known: HashMap<String, File> = files.iter().map(|f| (f.path.clone(), f.clone())).collect();
1917
        let mut s = Sent::default();
1918
        let again = copy_dir(&dest, src.path(), &known, false, &mut s).unwrap();
1919
        assert_eq!((again, s.sent), (files.clone(), 0), "nothing new travels");
1920
        // The first pass takes only the files that never change.
1921
        let mut s = Sent::default();
1922
        let first = copy_dir(&dest, src.path(), &HashMap::new(), true, &mut s).unwrap();
1923
        assert_eq!(first.iter().map(|f| f.path.as_str()).collect::<Vec<_>>(), vec![".oxy/objects/loose/aa"]);
1924
    }
1925
1926
    #[test]
1927
    fn requests_are_signed_as_aws_documents() {
1928
        // AWS's own example (S3 API reference, "Signature calculations":
1929
        // GET Object), with its published signature. Its documented example
1930
        // keys are put together at run time, so this file is not itself a
1931
        // push protection or history scan finding (#277).
1932
        let key_id = format!("{}{}", "AKIA", "IOSFODNN7EXAMPLE");
1933
        let secret = format!("{}{}", "wJalrXUtnFEMI/K7MDENG/", "bPxRfiCYEXAMPLEKEY");
1934
        let empty = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
1935
        let headers = vec![
1936
            ("Host".to_string(), "examplebucket.s3.amazonaws.com".to_string()),
1937
            ("Range".to_string(), "bytes=0-9".to_string()),
1938
            ("x-amz-content-sha256".to_string(), empty.to_string()),
1939
            ("x-amz-date".to_string(), "20130524T000000Z".to_string()),
1940
        ];
1941
        let auth =
1942
            sigv4("GET", "/test.txt", &[], &headers, empty, (key_id.as_str(), secret.as_str()), "us-east-1", "s3", "20130524T000000Z");
1943
        assert_eq!(
1944
            auth,
1945
            format!(
1946
                "AWS4-HMAC-SHA256 Credential={key_id}/20130524/us-east-1/s3/aws4_request, \
1947
                 SignedHeaders=host;range;x-amz-content-sha256;x-amz-date, \
1948
                 Signature=f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41"
1949
            )
1950
        );
1951
        assert_eq!(aws_encode("runs/2026 x+y", true), "runs/2026%20x%2By");
1952
        assert_eq!(aws_encode("a/b", false), "a%2Fb");
1953
        assert_eq!(xml_text("<A><Key>runs/x&amp;y</Key></A>", "Key").as_deref(), Some("runs/x&y"));
1954
    }
1955
1956
    #[test]
1957
    fn run_names_sort_by_time() {
1958
        assert_eq!(run_name(0), "19700101T000000Z");
1959
        assert!(run_name(1_791_900_000_000) < run_name(1_791_903_600_000));
1960
    }
1961
}