OXYGENHUB
# d7e2c2754807 oxygenhub / crates / hub / src / web / release_trust.rs
30.5 KiB · Rust · last changed Release trust counts receipts by keys this hub certified 18 days ago source blame history raw
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,
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).
72
    pub runner_known: bool,
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>,
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
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
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
        }
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()
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).
208
    receipts: HashMap<String, KeptReceipt>,
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.
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
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
                    };
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));
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
    }
335
    let known_runner_keys: Vec<String> = db::runners::keys(&app.db).await.unwrap_or_default();
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();
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);
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),
371
                runner_known: kept.as_ref().is_some_and(|(k, ..)| known_runner_keys.contains(&k.key)) || certified_for.is_some(),
372
                certified_for,
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()),
377
                runner_revoked: kept.as_ref().is_some_and(|(_, _, rv, ..)| *rv),
378
                signed_receipt: kept.map(|(_, _, _, hex, _)| hex),
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
    });
423
    let sum = |f: fn(&AuthorTrust) -> usize| t.authors.iter().map(f).sum::<usize>();
424
    let (unsigned, invalid, revoked) = (sum(|a| a.unsigned), sum(|a| a.invalid), sum(|a| a.revoked));
425
    let scope = match &t.since {
426
        Some(p) => format!("since {p}"),
427
        None => "in the release".to_string(),
428
    };
429
    out.push(if invalid > 0 || revoked > 0 {
430
        check(
431
            Verdict::Fail,
432
            format!("{} of {} changes {scope} fail authentication", invalid + revoked, t.changes),
433
            format!("{invalid} with an invalid signature, {revoked} by revoked keys"),
434
        )
435
    } else if unsigned > 0 {
436
        check(
437
            Verdict::Warn,
438
            format!("{unsigned} of {} changes {scope} are unsigned", t.changes),
439
            "Changes are authenticated when their author signs or seals them on push (Oxygen spec §14.4).".into(),
440
        )
441
    } else {
442
        let what = match t.changes {
443
            1 => format!("The one change {scope} is authenticated"),
444
            n => format!("All {n} changes {scope} are authenticated"),
445
        };
446
        let by = match t.authors.len() {
447
            1 => "by one author".to_string(),
448
            n => format!("by {n} authors"),
449
        };
450
        check(Verdict::Pass, what, by)
451
    });
452
    if t.assets.is_empty() {
453
        out.push(check(Verdict::Warn, "The release has no assets".into(), "Nothing to trace to a build.".into()));
454
    }
455
    for a in &t.assets {
456
        match &a.build {
457
            None => out.push(check(
458
                Verdict::Warn,
459
                format!("{}: no build found", a.name),
460
                "No passed OxygenFlow job of this repository produced these bytes; it was uploaded by hand.".into(),
461
            )),
462
            Some(b) => {
463
                out.push(match (&b.receipt, &b.receipt_problem, b.runner_revoked, b.runner_known) {
464
                    (None, ..) => check(
465
                        Verdict::Warn,
466
                        format!("{}: built by run #{} {}, without a signed receipt", a.name, b.run, b.job),
467
                        "The runner did not sign its receipt, or the hub did not keep it.".into(),
468
                    ),
469
                    (Some(_), Some(p), ..) => check(Verdict::Fail, format!("{}: the signed receipt does not verify", a.name), p.clone()),
470
                    (Some(_), None, true, _) => {
471
                        check(Verdict::Fail, format!("{}: the receipt's runner key was revoked", a.name), String::new())
472
                    }
473
                    (Some(_), None, false, known) => check(
474
                        if known { Verdict::Pass } else { Verdict::Warn },
475
                        format!("{}: signed receipt from run #{} {}", a.name, b.run, b.job),
476
                        format!(
477
                            "signed by {}{}",
478
                            b.runner.as_ref().map(|k| k.name.as_str()).unwrap_or(""),
479
                            match (&b.certified_for, known) {
480
                                (Some(s), _) => format!(", a short-lived key this hub certified for {s}"),
481
                                (None, true) => ", a runner key of this hub".to_string(),
482
                                (None, false) => "; that key is not one this hub's runners use".to_string(),
483
                            }
484
                        ),
485
                    ),
486
                });
487
                out.push(if b.same_state_as_tag {
488
                    check(
489
                        Verdict::Pass,
490
                        format!("{}: built from the tagged state", a.name),
491
                        t.heads.iter().map(|h| &h[..12]).collect::<Vec<_>>().join("+"),
492
                    )
493
                } else {
494
                    check(
495
                        Verdict::Warn,
496
                        format!("{}: built from another state than the tag's", a.name),
497
                        format!("run #{} built {}", b.run, b.heads.split('+').map(|h| &h[..12.min(h.len())]).collect::<Vec<_>>().join("+")),
498
                    )
499
                });
500
                let pinned = b.rootfs.len() == 64 && b.rootfs.bytes().all(|c| c.is_ascii_hexdigit()) && !b.environment.is_empty();
501
                out.push(if pinned {
502
                    check(Verdict::Pass, format!("{}: pinned environment", a.name), format!("{} rootfs {}", b.runtime, &b.rootfs[..12]))
503
                } else {
504
                    check(Verdict::Warn, format!("{}: environment not pinned by hash", a.name), b.rootfs.clone())
505
                });
506
            }
507
        }
508
    }
509
    out
510
}
511
512
/// The report as a graph: authors, the tagged state, the builds (when any
513
/// job built an asset) and the assets, as inline SVG drawn at its own size.
514
/// Each node carries a badge: a lock where the claim is signed and checked,
515
/// `!` where it is not (unsigned, uploaded by hand), `✘` where it fails;
516
/// its second line says why, and its title says it in full (oxygenhub#79).
517
pub fn graph(t: &ReleaseTrust) -> String {
518
    const W: f64 = 220.0;
519
    const H: f64 = 40.0;
520
    const GAP: f64 = 10.0;
521
    const COL: f64 = W + 48.0;
522
    struct Node {
523
        col: usize,
524
        row: usize,
525
        title: String,
526
        sub: String,
527
        class: &'static str,
528
        tip: String,
529
    }
530
    let esc = crate::render::escape;
531
    let mut nodes: Vec<Node> = Vec::new();
532
    let mut edges: Vec<(usize, usize, bool)> = Vec::new();
533
    let any_build = t.assets.iter().any(|a| a.build.is_some());
534
    let asset_col = if any_build { 3 } else { 2 };
535
    let authors: Vec<usize> = t
536
        .authors
537
        .iter()
538
        .take(12)
539
        .enumerate()
540
        .map(|(i, a)| {
541
            let name = if a.who.name.is_empty() { a.who.key[..12].to_string() } else { a.who.name.clone() };
542
            let (class, why) = if a.invalid + a.revoked > 0 {
543
                ("fail", format!("{} invalid or revoked", a.invalid + a.revoked))
544
            } else if a.unsigned > 0 {
545
                ("warn", format!("{} of {} unsigned", a.unsigned, a.changes))
546
            } else {
547
                ("pass", "all signed".to_string())
548
            };
549
            let linked = if a.who.account.is_some() { "key linked to an account" } else { "key not linked to an account" };
550
            nodes.push(Node {
551
                col: 0,
552
                row: i,
553
                title: name.clone(),
554
                sub: format!("{} change{} · {why}", a.changes, if a.changes == 1 { "" } else { "s" }),
555
                class,
556
                tip: format!("{name}: {} changes, {} signed, {} sealed, {} unsigned; {linked}", a.changes, a.signed, a.sealed, a.unsigned),
557
            });
558
            nodes.len() - 1
559
        })
560
        .collect();
561
    let signer = t.tag_signer.as_ref().map(|k| k.name.clone()).unwrap_or_default();
562
    let (tag_class, tag_sub) = match t.tag_signature.as_str() {
563
        "valid" => ("pass", format!("signed by {signer}")),
564
        "unsigned" => ("warn", "unsigned".to_string()),
565
        other => ("fail", other.to_string()),
566
    };
567
    nodes.push(Node {
568
        col: 1,
569
        row: 0,
570
        title: format!("tag {}", t.tag),
571
        sub: tag_sub.clone(),
572
        class: tag_class,
573
        tip: format!("tag {}: {} changes; {tag_sub}", t.tag, t.changes),
574
    });
575
    let tag = nodes.len() - 1;
576
    for a in authors {
577
        edges.push((a, tag, true));
578
    }
579
    let mut builds: HashMap<(i64, String), usize> = HashMap::new();
580
    let mut build_rows = 0;
581
    for (i, a) in t.assets.iter().enumerate() {
582
        let build = a.build.as_ref().map(|b| {
583
            *builds.entry((b.run, b.job.clone())).or_insert_with(|| {
584
                let runner = b.runner.as_ref().map(|r| r.name.clone()).unwrap_or_default();
585
                let (class, why) = match (&b.receipt, &b.receipt_problem) {
586
                    (Some(_), None) => ("pass", format!("receipt verified · {runner}")),
587
                    (Some(_), Some(p)) => ("fail", p.clone()),
588
                    _ => ("warn", "no signed receipt".to_string()),
589
                };
590
                nodes.push(Node {
591
                    col: 2,
592
                    row: build_rows,
593
                    title: format!("run #{} {}", b.run, b.job),
594
                    sub: why.clone(),
595
                    class,
596
                    tip: format!(
597
                        "run #{} job {}: {why}{}",
598
                        b.run,
599
                        b.job,
600
                        if b.same_state_as_tag { ", from the tagged state" } else { ", from another state than the tag's" }
601
                    ),
602
                });
603
                build_rows += 1;
604
                edges.push((tag, nodes.len() - 1, b.same_state_as_tag));
605
                nodes.len() - 1
606
            })
607
        });
608
        let size = crate::render::bytes(a.size as u64);
609
        let (class, why) = match &a.build {
610
            Some(b) if b.receipt.is_some() && b.receipt_problem.is_none() => ("pass", "attested build"),
611
            Some(_) => ("warn", "built, not attested"),
612
            None => ("warn", "uploaded by hand"),
613
        };
614
        nodes.push(Node {
615
            col: asset_col,
616
            row: i,
617
            title: a.name.clone(),
618
            sub: format!("{size} · {why}"),
619
            class,
620
            tip: format!("{}: {size}, {why}", a.name),
621
        });
622
        if let Some(b) = build {
623
            edges.push((b, nodes.len() - 1, true));
624
        }
625
    }
626
    let x = |n: &Node| 1.0 + n.col as f64 * COL;
627
    let y = |n: &Node| 1.0 + n.row as f64 * (H + GAP);
628
    let width = 2.0 + asset_col as f64 * COL + W;
629
    let height = nodes.iter().map(y).fold(0.0, f64::max) + H + 2.0;
630
    let mut svg = format!(
631
        r#"<svg class="trust-graph" width="{width}" height="{height}" viewBox="0 0 {width} {height}" role="img" aria-label="Release trust graph">"#
632
    );
633
    for (a, b, solid) in &edges {
634
        let (x1, y1) = (x(&nodes[*a]) + W, y(&nodes[*a]) + H / 2.0);
635
        let (x2, y2) = (x(&nodes[*b]), y(&nodes[*b]) + H / 2.0);
636
        let mx = (x1 + x2) / 2.0;
637
        svg.push_str(&format!(
638
            r#"<path class="edge{}" d="M{x1},{y1} C{mx},{y1} {mx},{y2} {x2},{y2}"/>"#,
639
            if *solid { "" } else { " dashed" }
640
        ));
641
    }
642
    for n in &nodes {
643
        let (nx, ny) = (x(n), y(n));
644
        // The badge, in a circle at the node's right.
645
        let (cx, cy) = (nx + W - 16.0, ny + H / 2.0);
646
        let badge = match n.class {
647
            // A padlock: the shackle, then the body.
648
            "pass" => format!(
649
                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"/>"#,
650
                cx - 3.5,
651
                cy - 0.5,
652
                cx - 5.0,
653
                cy - 0.5
654
            ),
655
            "warn" => format!(r#"<text class="mark" x="{cx}" y="{}" text-anchor="middle">!</text>"#, cy + 4.0),
656
            _ => format!(r#"<text class="mark" x="{cx}" y="{}" text-anchor="middle">✘</text>"#, cy + 4.0),
657
        };
658
        svg.push_str(&format!(
659
            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>"#,
660
            n.class,
661
            esc(&n.tip),
662
            nx + 10.0,
663
            ny + 17.0,
664
            esc(&truncate(&n.title, 28)),
665
            nx + 10.0,
666
            ny + 31.0,
667
            esc(&truncate(&n.sub, 32)),
668
        ));
669
    }
670
    svg.push_str("</svg>");
671
    svg
672
}
673
674
fn truncate(s: &str, n: usize) -> String {
675
    if s.chars().count() <= n {
676
        s.to_string()
677
    } else {
678
        format!("{}…", s.chars().take(n - 1).collect::<String>())
679
    }
680
}
681
682
#[derive(Template)]
683
#[template(path = "release_trust.html")]
684
pub struct ReleaseTrustPage {
685
    shell: Shell,
686
    repo: RepoShell,
687
    t: ReleaseTrust,
688
    graph: String,
689
}
690
691
#[derive(Deserialize, Default)]
692
pub struct TrustQuery {
693
    #[serde(default)]
694
    format: Option<String>,
695
}
696
697
/// `GET /{owner}/{name}/releases/trust/{*tag}`: the page, or with
698
/// `?format=json` the report as a download.
699
pub async fn page(
700
    State(app): State<Shared>,
701
    viewer: Viewer,
702
    Path((owner, name, tag)): Path<(String, String, String)>,
703
    Query(q): Query<TrustQuery>,
704
) -> Result<Response, Error> {
705
    let shell = Shell::new(&app, &format!("/{owner}/{name}/releases/trust/{tag}"), &viewer);
706
    let (repo, row, role) = lookup(&app, &shell, &viewer, &owner, &name).await?;
707
    let t =
708
        report(&app, &repo, &row, &tag).await.map_err(|m| Error::bad(shell.clone(), m))?.ok_or_else(|| Error::not_found(shell.clone()))?;
709
    if q.format.as_deref() == Some("json") {
710
        let file: String = tag.chars().map(|c| if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') { c } else { '-' }).collect();
711
        return Ok((
712
            [
713
                (axum::http::header::CONTENT_TYPE, "application/json".to_string()),
714
                (axum::http::header::CONTENT_DISPOSITION, format!("attachment; filename=\"{}-{file}-trust.json\"", row.name)),
715
            ],
716
            serde_json::to_string_pretty(&t).unwrap_or_default(),
717
        )
718
            .into_response());
719
    }
720
    let graph = graph(&t);
721
    Ok(Page(ReleaseTrustPage { shell, repo: RepoShell::new(&app, &row, "releases").with_role(role), t, graph }).into_response())
722
}