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