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