OXYGENHUB
◆ api-unknown-fields oxygenhub / crates / hub / src / web / release_trust.rs
31.2 KiB · Rust · last changed Release trust counts receipts by keys this hub certified 18 days ago source blame history raw
df940d75 Andy McCall ↶ 1
//! A release's trust report (hub spec §9.1): who wrote what the release
2
//! holds and how it is authenticated, what built each asset, in which
3
//! pinned environment, from which inputs, under which signed receipt, and
4
//! an audit of all of it. The page draws it as a graph; the same report is
5
//! JSON for export, carrying the signed receipts so an auditor can check
6
//! them offline with `oxy receipt verify`.
7
8
use super::{filters, lookup, Error, Page, RepoShell, Shell};
9
use crate::auth::Viewer;
10
use crate::db::{self, flow as fdb, releases as rdb};
11
use crate::repos::RepoName;
12
use crate::Shared;
13
use askama::Template;
14
use axum::extract::{Path, Query, State};
15
use axum::response::{IntoResponse, Response};
16
use oxy_core::hash::{ChangeHash, ObjectRef};
17
use oxy_core::identity::{verify, Domain};
18
use oxy_core::repo::SignatureStatus;
19
use serde::{Deserialize, Serialize};
20
use std::collections::{BTreeMap, HashMap};
21
22
/// A key as the report names it.
23
#[derive(Clone, Debug, Default, Serialize)]
24
pub struct KeyInfo {
25
    pub key: String,
26
    pub name: String,
27
    pub email: String,
28
    /// The account the key is linked to on this hub.
29
    pub account: Option<String>,
30
}
31
32
#[derive(Clone, Debug, Default, Serialize)]
33
pub struct AuthorTrust {
34
    pub who: KeyInfo,
35
    pub changes: usize,
36
    /// Changes authenticated by their own signature.
37
    pub signed: usize,
38
    /// Changes authenticated by a seal.
39
    pub sealed: usize,
40
    pub unsigned: usize,
41
    /// Authenticated by a key since revoked.
42
    pub revoked: usize,
43
    pub invalid: usize,
44
}
45
46
#[derive(Clone, Debug, Serialize)]
47
pub struct BuildTrust {
48
    pub run: i64,
49
    pub job: String,
50
    pub run_url: String,
51
    /// The heads the run built, joined with `+`.
52
    pub heads: String,
53
    /// Whether that is exactly the tagged state.
54
    pub same_state_as_tag: bool,
55
    pub pipeline_hash: String,
56
    pub scope_tree_hash: String,
57
    /// Hash of the environment the job ran in (runtime, pinned parts,
58
    /// rootfs, argv, env).
59
    pub environment: String,
60
    pub rootfs: String,
61
    pub runtime: String,
62
    pub exit_code: Option<i64>,
63
    pub runner: Option<KeyInfo>,
64
    /// The receipt attestation, when a signed receipt was kept.
65
    pub receipt: Option<String>,
66
    pub receipt_url: Option<String>,
67
    /// Why the kept receipt does not verify now, if it does not.
68
    pub receipt_problem: Option<String>,
69
    pub runner_revoked: bool,
24472413 Andy McCall ↶ 70
    /// The runner's key is one a runner token on this hub signs with, or a
71
    /// short-lived key this hub certified for the repository (#241).
df940d75 Andy McCall ↶ 72
    pub runner_known: bool,
24472413 Andy McCall ↶ 73
    /// The subject this hub certified the short-lived key that signed the
74
    /// receipt for, when it was one.
75
    pub certified_for: Option<String>,
df940d75 Andy McCall ↶ 76
    /// The signed receipt, hex, for `oxy receipt verify`.
77
    pub signed_receipt: Option<String>,
78
}
79
80
#[derive(Clone, Debug, Serialize)]
81
pub struct AssetTrust {
82
    pub name: String,
83
    pub size: i64,
84
    pub blake3: String,
85
    pub url: String,
86
    pub build: Option<BuildTrust>,
87
}
88
89
#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
90
#[serde(rename_all = "lowercase")]
91
pub enum Verdict {
92
    Pass,
93
    Warn,
94
    Fail,
95
}
96
97
#[derive(Clone, Debug, Serialize)]
98
pub struct Check {
99
    pub verdict: Verdict,
100
    pub title: String,
101
    pub detail: String,
102
}
103
104
impl Check {
105
    pub fn glyph(&self) -> &'static str {
106
        match self.verdict {
107
            Verdict::Pass => "✔",
108
            Verdict::Warn => "!",
109
            Verdict::Fail => "✘",
110
        }
111
    }
112
    pub fn class(&self) -> &'static str {
113
        match self.verdict {
114
            Verdict::Pass => "pass",
115
            Verdict::Warn => "warn",
116
            Verdict::Fail => "fail",
117
        }
118
    }
119
}
120
bf5101d3 Andy McCall ↶ 121
/// One claim of the trust summary: `pass`, `warn` or `fail`, and what it says.
122
pub struct TrustBadge {
123
    pub class: &'static str,
124
    pub text: String,
125
}
126
df940d75 Andy McCall ↶ 127
#[derive(Clone, Debug, Serialize)]
128
pub struct ReleaseTrust {
129
    pub repository: String,
130
    pub tag: String,
131
    pub title: String,
132
    pub release_url: String,
133
    pub heads: Vec<String>,
134
    pub tag_signer: Option<KeyInfo>,
135
    /// `valid`, `unsigned`, `invalid: …` or `revoked`.
136
    pub tag_signature: String,
137
    /// The previous release, which bounds the changes counted.
138
    pub since: Option<String>,
139
    pub changes: usize,
140
    pub authors: Vec<AuthorTrust>,
141
    pub assets: Vec<AssetTrust>,
142
    pub audit: Vec<Check>,
143
    pub generated_ms: i64,
144
}
145
146
impl ReleaseTrust {
147
    pub fn verdict_class(&self) -> &'static str {
148
        match self.verdict() {
149
            Verdict::Pass => "pass",
150
            Verdict::Warn => "warn",
151
            Verdict::Fail => "fail",
152
        }
bf5101d3 Andy McCall ↶ 153
    }
154
155
    /// The page's trust summary, one badge per claim: the tag's signature,
156
    /// how many changes are authenticated, and how many assets an attested
157
    /// OxygenFlow build produced (oxygenhub#79).
158
    pub fn summary(&self) -> Vec<TrustBadge> {
159
        let tag = match self.tag_signature.as_str() {
160
            "valid" => ("pass", format!("Tag signed by {}", self.tag_signer.as_ref().map(|k| k.name.as_str()).unwrap_or("its signer"))),
161
            "unsigned" => ("warn", "Tag unsigned".to_string()),
162
            other => ("fail", format!("Tag signature {other}")),
163
        };
164
        let authenticated: usize = self.authors.iter().map(|a| a.signed + a.sealed).sum();
165
        let bad: usize = self.authors.iter().map(|a| a.invalid + a.revoked).sum();
166
        let changes = (
167
            if bad > 0 {
168
                "fail"
169
            } else if authenticated < self.changes {
170
                "warn"
171
            } else {
172
                "pass"
173
            },
174
            format!("{authenticated} of {} changes signed or sealed", self.changes),
175
        );
176
        let attested =
177
            self.assets.iter().filter(|a| a.build.as_ref().is_some_and(|b| b.receipt.is_some() && b.receipt_problem.is_none())).count();
178
        let assets = (
179
            if attested == self.assets.len() { "pass" } else { "warn" },
180
            if self.assets.is_empty() {
181
                "No assets".to_string()
182
            } else {
183
                format!("{attested} of {} assets built and attested by OxygenFlow", self.assets.len())
184
            },
185
        );
186
        [tag, changes, assets].into_iter().map(|(class, text)| TrustBadge { class, text }).collect()
df940d75 Andy McCall ↶ 187
    }
188
189
    pub fn verdict(&self) -> Verdict {
190
        if self.audit.iter().any(|c| c.verdict == Verdict::Fail) {
191
            Verdict::Fail
192
        } else if self.audit.iter().any(|c| c.verdict == Verdict::Warn) {
193
            Verdict::Warn
194
        } else {
195
            Verdict::Pass
196
        }
197
    }
198
}
199
200
/// What the repository says about the release: read in one go.
201
struct RepoFacts {
202
    heads: Vec<ChangeHash>,
203
    tag_signer: Option<KeyInfo>,
204
    tag_signature: String,
205
    authors: Vec<AuthorTrust>,
206
    changes: usize,
207
    /// Kept receipts by attestation: (runner, problem, revoked, signed hex).
24472413 Andy McCall ↶ 208
    receipts: HashMap<String, KeptReceipt>,
df940d75 Andy McCall ↶ 209
}
210
211
fn key_info(r: &oxy_core::repo::Repo, key: &ObjectRef) -> KeyInfo {
212
    match r.store().get_identity(key) {
213
        Ok(i) => KeyInfo { key: key.to_hex(), name: i.name, email: i.email, account: None },
214
        Err(_) => KeyInfo { key: key.to_hex(), ..Default::default() },
215
    }
216
}
217
218
/// An asset's build: the matching artifact's job, with its run and job rows.
219
type Build = (fdb::Provenance, Option<fdb::Run>, Option<fdb::Job>);
220
221
/// Build the report for release `tag`, or `None` when there is no such
222
/// release or its tag is gone.
24472413 Andy McCall ↶ 223
/// A kept receipt as the report sees it: its signer, why it does not
224
/// verify (if it does not), whether the key was revoked, the signed
225
/// receipt in hex, and the issuer and subject of a short-lived key's
226
/// certificate.
227
type KeptReceipt = (KeyInfo, Option<String>, bool, String, Option<(String, String)>);
228
df940d75 Andy McCall ↶ 229
pub async fn report(app: &Shared, repo: &RepoName, row: &db::repos::RepoRow, tag: &str) -> Result<Option<ReleaseTrust>, String> {
230
    let releases = rdb::list(&app.db, row.id).await.map_err(|e| e.to_string())?;
231
    let Some(rel) = releases.iter().find(|r| r.tag == tag).cloned() else { return Ok(None) };
232
    // The previous release: the next older one in the list (newest first).
233
    let since = releases.iter().skip_while(|r| r.id != rel.id).nth(1).map(|r| r.tag.clone());
234
    let assets = rdb::assets(&app.db, rel.id).await.map_err(|e| e.to_string())?;
235
    let mut builds: Vec<Option<Build>> = Vec::new();
236
    for a in &assets {
237
        match fdb::provenance(&app.db, row.id, &a.hash).await.map_err(|e| e.to_string())? {
238
            Some(p) => {
239
                let run = fdb::run(&app.db, row.id, p.run_number).await.map_err(|e| e.to_string())?;
240
                let job = match &run {
241
                    Some(r) => fdb::jobs(&app.db, r.id).await.map_err(|e| e.to_string())?.into_iter().find(|j| j.name == p.job),
242
                    None => None,
243
                };
244
                builds.push(Some((p, run, job)));
245
            }
246
            None => builds.push(None),
247
        }
248
    }
249
    let attests: Vec<String> = builds.iter().flatten().map(|(p, _, _)| p.receipt_attest.clone()).filter(|a| !a.is_empty()).collect();
250
    let (tag_s, since_s) = (tag.to_string(), since.clone());
251
    let facts = app
252
        .repos
253
        .read(repo, move |r, cache| {
254
            let Some(heads) = r.tag_heads(&tag_s)? else { return Ok(None) };
255
            // The tag's attestation and whether its signature verifies.
256
            let (tag_signer, tag_signature) = match r.tag_attest(&tag_s)? {
257
                Some((ar, sa)) => match sa.sigs.first() {
258
                    Some(sig) => {
259
                        let who = key_info(r, &sig.key);
260
                        let verdict = match r.store().get_identity(&sig.key) {
261
                            Ok(id) => match verify(&id, sig, Domain::Attest, &ar) {
262
                                Ok(()) if r.is_revoked(&sig.key)? => "revoked".to_string(),
263
                                Ok(()) => "valid".to_string(),
264
                                Err(e) => format!("invalid: {e}"),
265
                            },
266
                            Err(_) => "invalid: the signer's identity is missing".to_string(),
267
                        };
268
                        (Some(who), verdict)
269
                    }
270
                    None => (None, "unsigned".to_string()),
271
                },
272
                None => (None, "unsigned".to_string()),
273
            };
274
            // The changes the release adds over the previous one, by author.
275
            let now = cache.load(r, &heads)?;
276
            let before = match &since_s {
277
                Some(p) => r.tag_heads(p)?.unwrap_or_default(),
278
                None => vec![],
279
            };
280
            let then = cache.load(r, &before)?;
281
            let mut by_author: BTreeMap<String, AuthorTrust> = BTreeMap::new();
282
            let mut changes = 0;
283
            for (h, meta) in now.state.changes() {
284
                if then.state.contains(h) {
285
                    continue;
286
                }
287
                changes += 1;
288
                let a = by_author
289
                    .entry(meta.author.to_hex())
290
                    .or_insert_with(|| AuthorTrust { who: key_info(r, &meta.author), ..Default::default() });
291
                if meta.author.is_zero() {
292
                    a.who.name = "(no author: imported or made before an identity)".into();
293
                }
294
                a.changes += 1;
295
                match r.authenticate_change(h)? {
296
                    SignatureStatus::Valid { revoked: true, .. } => a.revoked += 1,
297
                    SignatureStatus::Valid { sealed: true, .. } => a.sealed += 1,
298
                    SignatureStatus::Valid { .. } => a.signed += 1,
299
                    SignatureStatus::Unsigned => a.unsigned += 1,
300
                    SignatureStatus::Invalid(_) => a.invalid += 1,
301
                }
302
            }
303
            let mut authors: Vec<AuthorTrust> = by_author.into_values().collect();
304
            authors.sort_by(|a, b| b.changes.cmp(&a.changes).then(a.who.name.cmp(&b.who.name)));
305
            // Kept receipts, verified again from the store.
306
            let mut receipts = HashMap::new();
307
            for a in &attests {
308
                let Some(ar) = ObjectRef::from_hex(a) else { continue };
309
                if let Ok(i) = r.receipt(&ar) {
310
                    let runner = KeyInfo {
311
                        key: i.signed.runner.hash().to_hex(),
312
                        name: i.signed.runner.name.clone(),
313
                        email: i.signed.runner.email.clone(),
314
                        account: None,
315
                    };
24472413 Andy McCall ↶ 316
                    // A short-lived key's certificate: its issuer and subject.
317
                    let certified = i.signed.certificate.as_ref().map(|c| (c.cert.cert.issuer.to_hex(), c.cert.cert.subject.clone()));
318
                    receipts.insert(a.clone(), (runner, i.problem.clone(), i.revoked, hex::encode(i.signed.encode()), certified));
df940d75 Andy McCall ↶ 319
                }
320
            }
321
            Ok(Some(RepoFacts { heads, tag_signer, tag_signature, authors, changes, receipts }))
322
        })
323
        .await
324
        .map_err(|e| e.to_string())?;
325
    let Some(mut facts) = facts else { return Ok(None) };
326
327
    // Link keys to accounts.
328
    let links: HashMap<String, String> = db::accounts::identity_accounts(&app.db).await.unwrap_or_default().into_iter().collect();
329
    if let Some(s) = facts.tag_signer.as_mut() {
330
        s.account = links.get(&s.key).cloned();
331
    }
332
    for a in &mut facts.authors {
333
        a.who.account = links.get(&a.who.key).cloned();
334
    }
b6b7e4cf Andy McCall ↶ 335
    let known_runner_keys: Vec<String> = db::runners::keys(&app.db).await.unwrap_or_default();
df940d75 Andy McCall ↶ 336
337
    let base = format!("{}/{}", app.config.base_url(), row.slug());
338
    let mut tag_heads: Vec<String> = facts.heads.iter().map(|h| h.to_hex()).collect();
339
    tag_heads.sort();
340
    let tag_state = tag_heads.join("+");
341
    let mut asset_rows = Vec::new();
342
    for (a, b) in assets.iter().zip(builds) {
343
        let build = b.map(|(p, run, job)| {
344
            let receipt_json: serde_json::Value =
345
                job.as_ref().and_then(|j| serde_json::from_str(&j.receipt).ok()).unwrap_or(serde_json::Value::Null);
346
            let sandbox: serde_json::Value =
347
                job.as_ref().and_then(|j| serde_json::from_str(&j.sandbox).ok()).unwrap_or(serde_json::Value::Null);
348
            let heads = run.as_ref().map(|r| r.heads.clone()).unwrap_or_default();
349
            let kept = facts.receipts.get(&p.receipt_attest).cloned();
24472413 Andy McCall ↶ 350
            // Certified by this hub's key for this repository: as good as
351
            // a runner key of this hub (the certificate itself was checked
352
            // with the receipt).
353
            let certified_for = kept
354
                .as_ref()
355
                .and_then(|(.., c)| c.clone())
356
                .filter(|(issuer, subject)| *issuer == app.hub_key.key.to_hex() && subject.starts_with(&format!("repo:{}:", row.slug())));
357
            let certified_for = certified_for.map(|(_, subject)| subject);
df940d75 Andy McCall ↶ 358
            let s = |v: &serde_json::Value| v.as_str().unwrap_or("").to_string();
359
            BuildTrust {
360
                run: p.run_number,
361
                job: p.job.clone(),
362
                run_url: format!("{base}/flow/{}", p.run_number),
363
                same_state_as_tag: heads == tag_state,
364
                heads,
365
                pipeline_hash: s(&receipt_json["pipeline_hash"]),
366
                scope_tree_hash: s(&receipt_json["scope_tree_hash"]),
367
                environment: s(&receipt_json["environment"]),
368
                rootfs: s(&sandbox["rootfs"]),
369
                runtime: s(&sandbox["runtime"]),
370
                exit_code: job.as_ref().and_then(|j| j.exit_code),
24472413 Andy McCall ↶ 371
                runner_known: kept.as_ref().is_some_and(|(k, ..)| known_runner_keys.contains(&k.key)) || certified_for.is_some(),
372
                certified_for,
df940d75 Andy McCall ↶ 373
                runner: kept.as_ref().map(|(k, ..)| k.clone()),
374
                receipt: kept.as_ref().map(|_| p.receipt_attest.clone()),
375
                receipt_url: kept.as_ref().map(|_| format!("{base}/receipts/{}", p.receipt_attest)),
376
                receipt_problem: kept.as_ref().and_then(|(_, pr, ..)| pr.clone()),
24472413 Andy McCall ↶ 377
                runner_revoked: kept.as_ref().is_some_and(|(_, _, rv, ..)| *rv),
378
                signed_receipt: kept.map(|(_, _, _, hex, _)| hex),
df940d75 Andy McCall ↶ 379
            }
380
        });
381
        asset_rows.push(AssetTrust {
382
            name: a.name.clone(),
383
            size: a.size,
384
            blake3: a.hash.clone(),
385
            url: format!("{base}/asset/{}/{}", a.id, a.name),
386
            build,
387
        });
388
    }
389
    let mut t = ReleaseTrust {
390
        repository: row.slug(),
391
        tag: tag.to_string(),
392
        title: rel.title.clone(),
393
        release_url: format!("{base}/releases/tag/{tag}"),
394
        heads: tag_heads,
395
        tag_signer: facts.tag_signer,
396
        tag_signature: facts.tag_signature,
397
        since,
398
        changes: facts.changes,
399
        authors: facts.authors,
400
        assets: asset_rows,
401
        audit: vec![],
402
        generated_ms: db::now_ms(),
403
    };
404
    t.audit = audit(&t);
405
    Ok(Some(t))
406
}
407
408
/// The audit: every claim the report makes, judged.
409
pub fn audit(t: &ReleaseTrust) -> Vec<Check> {
410
    let mut out = Vec::new();
411
    let check = |verdict, title: String, detail: String| Check { verdict, title, detail };
412
    let signer = t.tag_signer.as_ref().map(|k| if k.name.is_empty() { k.key[..12].to_string() } else { k.name.clone() });
413
    out.push(match t.tag_signature.as_str() {
414
        "valid" => check(Verdict::Pass, format!("Tag {} is signed", t.tag), format!("by {}", signer.unwrap_or_default())),
415
        "unsigned" => check(
416
            Verdict::Warn,
417
            format!("Tag {} is not signed", t.tag),
418
            "Create tags with a key (`oxy identity create`) so they carry a signed attestation.".into(),
419
        ),
420
        "revoked" => check(Verdict::Fail, format!("Tag {} is signed by a revoked key", t.tag), signer.unwrap_or_default()),
421
        other => check(Verdict::Fail, format!("Tag {}'s signature does not verify", t.tag), other.to_string()),
422
    });
edcef275 Andy McCall ↶ 423
    // The heads once, here, rather than on every asset's line (oxygenhub#93).
424
    let short = |h: &String| h[..12.min(h.len())].to_string();
425
    out.push(match t.heads.len() {
426
        1 => check(Verdict::Pass, "The tagged state is one change".into(), short(&t.heads[0])),
427
        n => check(Verdict::Pass, format!("The tagged state has {n} heads"), t.heads.iter().map(short).collect::<Vec<_>>().join(" ")),
428
    });
df940d75 Andy McCall ↶ 429
    let sum = |f: fn(&AuthorTrust) -> usize| t.authors.iter().map(f).sum::<usize>();
430
    let (unsigned, invalid, revoked) = (sum(|a| a.unsigned), sum(|a| a.invalid), sum(|a| a.revoked));
431
    let scope = match &t.since {
432
        Some(p) => format!("since {p}"),
433
        None => "in the release".to_string(),
434
    };
435
    out.push(if invalid > 0 || revoked > 0 {
436
        check(
437
            Verdict::Fail,
438
            format!("{} of {} changes {scope} fail authentication", invalid + revoked, t.changes),
439
            format!("{invalid} with an invalid signature, {revoked} by revoked keys"),
440
        )
441
    } else if unsigned > 0 {
442
        check(
443
            Verdict::Warn,
444
            format!("{unsigned} of {} changes {scope} are unsigned", t.changes),
445
            "Changes are authenticated when their author signs or seals them on push (Oxygen spec §14.4).".into(),
446
        )
447
    } else {
448
        let what = match t.changes {
449
            1 => format!("The one change {scope} is authenticated"),
450
            n => format!("All {n} changes {scope} are authenticated"),
451
        };
452
        let by = match t.authors.len() {
453
            1 => "by one author".to_string(),
454
            n => format!("by {n} authors"),
455
        };
456
        check(Verdict::Pass, what, by)
457
    });
458
    if t.assets.is_empty() {
459
        out.push(check(Verdict::Warn, "The release has no assets".into(), "Nothing to trace to a build.".into()));
460
    }
461
    for a in &t.assets {
462
        match &a.build {
463
            None => out.push(check(
464
                Verdict::Warn,
465
                format!("{}: no build found", a.name),
466
                "No passed OxygenFlow job of this repository produced these bytes; it was uploaded by hand.".into(),
467
            )),
468
            Some(b) => {
469
                out.push(match (&b.receipt, &b.receipt_problem, b.runner_revoked, b.runner_known) {
470
                    (None, ..) => check(
471
                        Verdict::Warn,
472
                        format!("{}: built by run #{} {}, without a signed receipt", a.name, b.run, b.job),
473
                        "The runner did not sign its receipt, or the hub did not keep it.".into(),
474
                    ),
475
                    (Some(_), Some(p), ..) => check(Verdict::Fail, format!("{}: the signed receipt does not verify", a.name), p.clone()),
476
                    (Some(_), None, true, _) => {
477
                        check(Verdict::Fail, format!("{}: the receipt's runner key was revoked", a.name), String::new())
478
                    }
479
                    (Some(_), None, false, known) => check(
480
                        if known { Verdict::Pass } else { Verdict::Warn },
481
                        format!("{}: signed receipt from run #{} {}", a.name, b.run, b.job),
482
                        format!(
483
                            "signed by {}{}",
484
                            b.runner.as_ref().map(|k| k.name.as_str()).unwrap_or(""),
24472413 Andy McCall ↶ 485
                            match (&b.certified_for, known) {
486
                                (Some(s), _) => format!(", a short-lived key this hub certified for {s}"),
487
                                (None, true) => ", a runner key of this hub".to_string(),
488
                                (None, false) => "; that key is not one this hub's runners use".to_string(),
489
                            }
df940d75 Andy McCall ↶ 490
                        ),
491
                    ),
492
                });
493
                out.push(if b.same_state_as_tag {
edcef275 Andy McCall ↶ 494
                    check(Verdict::Pass, format!("{}: built from the tagged state", a.name), format!("by run #{}", b.run))
df940d75 Andy McCall ↶ 495
                } else {
edcef275 Andy McCall ↶ 496
                    let heads: Vec<String> = b.heads.split('+').map(|h| h[..12.min(h.len())].to_string()).collect();
497
                    let built = match heads.len() {
498
                        0 => "nothing".to_string(),
499
                        1 => heads[0].clone(),
500
                        n if n <= 4 => format!("{n} heads {}", heads.join(" ")),
501
                        n => format!("{n} heads {} … {}", heads[0], heads[n - 1]),
502
                    };
df940d75 Andy McCall ↶ 503
                    check(
504
                        Verdict::Warn,
505
                        format!("{}: built from another state than the tag's", a.name),
edcef275 Andy McCall ↶ 506
                        format!("run #{} built {built}", b.run),
df940d75 Andy McCall ↶ 507
                    )
508
                });
509
                let pinned = b.rootfs.len() == 64 && b.rootfs.bytes().all(|c| c.is_ascii_hexdigit()) && !b.environment.is_empty();
510
                out.push(if pinned {
511
                    check(Verdict::Pass, format!("{}: pinned environment", a.name), format!("{} rootfs {}", b.runtime, &b.rootfs[..12]))
512
                } else {
513
                    check(Verdict::Warn, format!("{}: environment not pinned by hash", a.name), b.rootfs.clone())
514
                });
515
            }
516
        }
517
    }
518
    out
519
}
520
bf5101d3 Andy McCall ↶ 521
/// The report as a graph: authors, the tagged state, the builds (when any
522
/// job built an asset) and the assets, as inline SVG drawn at its own size.
523
/// Each node carries a badge: a lock where the claim is signed and checked,
524
/// `!` where it is not (unsigned, uploaded by hand), `✘` where it fails;
525
/// its second line says why, and its title says it in full (oxygenhub#79).
df940d75 Andy McCall ↶ 526
pub fn graph(t: &ReleaseTrust) -> String {
bf5101d3 Andy McCall ↶ 527
    const W: f64 = 220.0;
528
    const H: f64 = 40.0;
529
    const GAP: f64 = 10.0;
530
    const COL: f64 = W + 48.0;
531
    struct Node {
532
        col: usize,
533
        row: usize,
534
        title: String,
535
        sub: String,
536
        class: &'static str,
537
        tip: String,
538
    }
df940d75 Andy McCall ↶ 539
    let esc = crate::render::escape;
bf5101d3 Andy McCall ↶ 540
    let mut nodes: Vec<Node> = Vec::new();
df940d75 Andy McCall ↶ 541
    let mut edges: Vec<(usize, usize, bool)> = Vec::new();
bf5101d3 Andy McCall ↶ 542
    let any_build = t.assets.iter().any(|a| a.build.is_some());
543
    let asset_col = if any_build { 3 } else { 2 };
df940d75 Andy McCall ↶ 544
    let authors: Vec<usize> = t
545
        .authors
546
        .iter()
547
        .take(12)
548
        .enumerate()
549
        .map(|(i, a)| {
550
            let name = if a.who.name.is_empty() { a.who.key[..12].to_string() } else { a.who.name.clone() };
bf5101d3 Andy McCall ↶ 551
            let (class, why) = if a.invalid + a.revoked > 0 {
552
                ("fail", format!("{} invalid or revoked", a.invalid + a.revoked))
553
            } else if a.unsigned > 0 {
554
                ("warn", format!("{} of {} unsigned", a.unsigned, a.changes))
555
            } else {
556
                ("pass", "all signed".to_string())
557
            };
558
            let linked = if a.who.account.is_some() { "key linked to an account" } else { "key not linked to an account" };
559
            nodes.push(Node {
560
                col: 0,
561
                row: i,
562
                title: name.clone(),
563
                sub: format!("{} change{} · {why}", a.changes, if a.changes == 1 { "" } else { "s" }),
564
                class,
565
                tip: format!("{name}: {} changes, {} signed, {} sealed, {} unsigned; {linked}", a.changes, a.signed, a.sealed, a.unsigned),
566
            });
df940d75 Andy McCall ↶ 567
            nodes.len() - 1
568
        })
569
        .collect();
bf5101d3 Andy McCall ↶ 570
    let signer = t.tag_signer.as_ref().map(|k| k.name.clone()).unwrap_or_default();
571
    let (tag_class, tag_sub) = match t.tag_signature.as_str() {
572
        "valid" => ("pass", format!("signed by {signer}")),
573
        "unsigned" => ("warn", "unsigned".to_string()),
574
        other => ("fail", other.to_string()),
df940d75 Andy McCall ↶ 575
    };
bf5101d3 Andy McCall ↶ 576
    nodes.push(Node {
577
        col: 1,
578
        row: 0,
579
        title: format!("tag {}", t.tag),
580
        sub: tag_sub.clone(),
581
        class: tag_class,
582
        tip: format!("tag {}: {} changes; {tag_sub}", t.tag, t.changes),
583
    });
df940d75 Andy McCall ↶ 584
    let tag = nodes.len() - 1;
585
    for a in authors {
586
        edges.push((a, tag, true));
587
    }
588
    let mut builds: HashMap<(i64, String), usize> = HashMap::new();
bf5101d3 Andy McCall ↶ 589
    let mut build_rows = 0;
df940d75 Andy McCall ↶ 590
    for (i, a) in t.assets.iter().enumerate() {
591
        let build = a.build.as_ref().map(|b| {
592
            *builds.entry((b.run, b.job.clone())).or_insert_with(|| {
bf5101d3 Andy McCall ↶ 593
                let runner = b.runner.as_ref().map(|r| r.name.clone()).unwrap_or_default();
594
                let (class, why) = match (&b.receipt, &b.receipt_problem) {
595
                    (Some(_), None) => ("pass", format!("receipt verified · {runner}")),
596
                    (Some(_), Some(p)) => ("fail", p.clone()),
597
                    _ => ("warn", "no signed receipt".to_string()),
df940d75 Andy McCall ↶ 598
                };
bf5101d3 Andy McCall ↶ 599
                nodes.push(Node {
600
                    col: 2,
601
                    row: build_rows,
602
                    title: format!("run #{} {}", b.run, b.job),
603
                    sub: why.clone(),
df940d75 Andy McCall ↶ 604
                    class,
bf5101d3 Andy McCall ↶ 605
                    tip: format!(
606
                        "run #{} job {}: {why}{}",
607
                        b.run,
608
                        b.job,
609
                        if b.same_state_as_tag { ", from the tagged state" } else { ", from another state than the tag's" }
610
                    ),
611
                });
612
                build_rows += 1;
df940d75 Andy McCall ↶ 613
                edges.push((tag, nodes.len() - 1, b.same_state_as_tag));
614
                nodes.len() - 1
615
            })
616
        });
bf5101d3 Andy McCall ↶ 617
        let size = crate::render::bytes(a.size as u64);
618
        let (class, why) = match &a.build {
619
            Some(b) if b.receipt.is_some() && b.receipt_problem.is_none() => ("pass", "attested build"),
620
            Some(_) => ("warn", "built, not attested"),
621
            None => ("warn", "uploaded by hand"),
622
        };
623
        nodes.push(Node {
624
            col: asset_col,
625
            row: i,
626
            title: a.name.clone(),
627
            sub: format!("{size} · {why}"),
628
            class,
629
            tip: format!("{}: {size}, {why}", a.name),
630
        });
df940d75 Andy McCall ↶ 631
        if let Some(b) = build {
632
            edges.push((b, nodes.len() - 1, true));
633
        }
634
    }
bf5101d3 Andy McCall ↶ 635
    let x = |n: &Node| 1.0 + n.col as f64 * COL;
636
    let y = |n: &Node| 1.0 + n.row as f64 * (H + GAP);
637
    let width = 2.0 + asset_col as f64 * COL + W;
638
    let height = nodes.iter().map(y).fold(0.0, f64::max) + H + 2.0;
639
    let mut svg = format!(
640
        r#"<svg class="trust-graph" width="{width}" height="{height}" viewBox="0 0 {width} {height}" role="img" aria-label="Release trust graph">"#
641
    );
df940d75 Andy McCall ↶ 642
    for (a, b, solid) in &edges {
bf5101d3 Andy McCall ↶ 643
        let (x1, y1) = (x(&nodes[*a]) + W, y(&nodes[*a]) + H / 2.0);
644
        let (x2, y2) = (x(&nodes[*b]), y(&nodes[*b]) + H / 2.0);
df940d75 Andy McCall ↶ 645
        let mx = (x1 + x2) / 2.0;
646
        svg.push_str(&format!(
647
            r#"<path class="edge{}" d="M{x1},{y1} C{mx},{y1} {mx},{y2} {x2},{y2}"/>"#,
648
            if *solid { "" } else { " dashed" }
649
        ));
650
    }
bf5101d3 Andy McCall ↶ 651
    for n in &nodes {
652
        let (nx, ny) = (x(n), y(n));
653
        // The badge, in a circle at the node's right.
654
        let (cx, cy) = (nx + W - 16.0, ny + H / 2.0);
655
        let badge = match n.class {
656
            // A padlock: the shackle, then the body.
657
            "pass" => format!(
658
                r#"<path class="shackle" d="M{},{} v-3 a3.5,3.5 0 0 1 7,0 v3"/><rect class="lock" x="{}" y="{}" width="10" height="7.5" rx="1.5"/>"#,
659
                cx - 3.5,
660
                cy - 0.5,
661
                cx - 5.0,
662
                cy - 0.5
663
            ),
664
            "warn" => format!(r#"<text class="mark" x="{cx}" y="{}" text-anchor="middle">!</text>"#, cy + 4.0),
665
            _ => format!(r#"<text class="mark" x="{cx}" y="{}" text-anchor="middle">✘</text>"#, cy + 4.0),
666
        };
df940d75 Andy McCall ↶ 667
        svg.push_str(&format!(
bf5101d3 Andy McCall ↶ 668
            r#"<g class="node {}"><title>{}</title><rect x="{nx}" y="{ny}" width="{W}" height="{H}" rx="6"/><circle class="badge" cx="{cx}" cy="{cy}" r="10"/>{badge}<text x="{}" y="{}" class="t">{}</text><text x="{}" y="{}" class="s">{}</text></g>"#,
669
            n.class,
670
            esc(&n.tip),
671
            nx + 10.0,
672
            ny + 17.0,
673
            esc(&truncate(&n.title, 28)),
674
            nx + 10.0,
675
            ny + 31.0,
676
            esc(&truncate(&n.sub, 32)),
df940d75 Andy McCall ↶ 677
        ));
678
    }
679
    svg.push_str("</svg>");
680
    svg
681
}
682
683
fn truncate(s: &str, n: usize) -> String {
684
    if s.chars().count() <= n {
685
        s.to_string()
686
    } else {
687
        format!("{}…", s.chars().take(n - 1).collect::<String>())
688
    }
689
}
690
691
#[derive(Template)]
692
#[template(path = "release_trust.html")]
693
pub struct ReleaseTrustPage {
694
    shell: Shell,
695
    repo: RepoShell,
696
    t: ReleaseTrust,
697
    graph: String,
698
}
699
700
#[derive(Deserialize, Default)]
701
pub struct TrustQuery {
702
    #[serde(default)]
703
    format: Option<String>,
704
}
705
706
/// `GET /{owner}/{name}/releases/trust/{*tag}`: the page, or with
707
/// `?format=json` the report as a download.
708
pub async fn page(
709
    State(app): State<Shared>,
710
    viewer: Viewer,
711
    Path((owner, name, tag)): Path<(String, String, String)>,
712
    Query(q): Query<TrustQuery>,
713
) -> Result<Response, Error> {
714
    let shell = Shell::new(&app, &format!("/{owner}/{name}/releases/trust/{tag}"), &viewer);
715
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
716
    let t =
717
        report(&app, &repo, &row, &tag).await.map_err(|m| Error::bad(shell.clone(), m))?.ok_or_else(|| Error::not_found(shell.clone()))?;
718
    if q.format.as_deref() == Some("json") {
719
        let file: String = tag.chars().map(|c| if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') { c } else { '-' }).collect();
720
        return Ok((
721
            [
722
                (axum::http::header::CONTENT_TYPE, "application/json".to_string()),
723
                (axum::http::header::CONTENT_DISPOSITION, format!("attachment; filename=\"{}-{file}-trust.json\"", row.name)),
724
            ],
725
            serde_json::to_string_pretty(&t).unwrap_or_default(),
726
        )
727
            .into_response());
728
    }
729
    let graph = graph(&t);
730
    Ok(Page(ReleaseTrustPage { shell, repo: RepoShell::new(&app, &row, "releases").with_role(role), t, graph }).into_response())
731
}