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