From eb018d0798cece5e8af60ef3df06d70f04cbf221 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 18 Nov 2026 16:15:28 -0500 Subject: [PATCH] pdf-forms-w15: net change of 1 commits - pdf-forms-w15: written (committed by the lead: the run's own commit failed while gpg was locked after a reboot) --- .../ui-egui/src/tools/sign_ui/cert_viewer.rs | 195 +++++++ crates/ui-egui/src/tools/sign_ui/panel.rs | 516 +++++++++--------- crates/ui-egui/tests/it/trust_signer.rs | 4 +- 3 files changed, 448 insertions(+), 267 deletions(-) create mode 100644 crates/ui-egui/src/tools/sign_ui/cert_viewer.rs diff --git a/crates/ui-egui/src/tools/sign_ui/cert_viewer.rs b/crates/ui-egui/src/tools/sign_ui/cert_viewer.rs new file mode 100644 index 0000000000..2a2f28feea --- /dev/null +++ b/crates/ui-egui/src/tools/sign_ui/cert_viewer.rs @@ -0,0 +1,195 @@ +//! The Certificate Viewer dialog: the chain as a tree, and the selected certificate's tabs. + +use craft::behavior::{DisplayOrder, ItemSource, Selection, SelectionChange}; +use craft::ui::buttons::Button; +use craft::ui::contract::{Bind, CollectionEvent, SelectMode, Show as _, ShowCollection as _, ShowContainer as _}; +use craft::ui::dialog::Dialog; +use craft::ui::display::Text; +use craft::ui::form::Field; +use craft::ui::layout_components::{Row, Stack}; +use craft::ui::list::{List, ListRow}; +use craft::ui::runtime::env::Label; +use craft::ui::sections::{DialogRole, FooterButton}; +use craft::ui::tabs::{Tab, TabKind, TabStrip}; +use craft::ui::text::SelectableText; + +use super::panel::{CertTab, CertViewer, hex, key_usage}; +use super::{Certificate, PdfCraftApp, sign}; + +/// Opens the viewer on `chain` (the signer first), with the signer selected. +pub(crate) fn open(app: &mut PdfCraftApp, chain: Vec) { + app.cert_viewer = Some(CertViewer { chain, selected: 0, tab: CertTab::Summary }); +} + +/// The chain as a tree, root first: the entry at `at` is the certificate `len - 1 - at` of the chain, `at` levels +/// below the root, and every group is open. +struct Chain { + len: usize, +} + +impl DisplayOrder for Chain { + fn len(&self) -> usize { + self.len + } + + fn key(&self, at: usize) -> usize { + self.len - 1 - at + } + + fn index_of(&self, key: &usize) -> Option { + (*key < self.len).then(|| self.len - 1 - key) + } + + fn depth(&self, at: usize) -> usize { + at + } + + fn has_children(&self, at: usize) -> bool { + at + 1 < self.len + } + + fn open(&self, _at: usize) -> bool { + true + } +} + +impl ItemSource for Chain {} + +/// The tabs, in order. +struct Tabs; + +const TABS: [CertTab; 3] = [CertTab::Summary, CertTab::Details, CertTab::Trust]; + +impl DisplayOrder for Tabs { + fn len(&self) -> usize { + TABS.len() + } + + fn key(&self, at: usize) -> CertTab { + TABS[at] + } +} + +impl ItemSource for Tabs {} + +fn tab_label(tab: CertTab) -> &'static str { + match tab { + CertTab::Summary => tl!("Summary"), + CertTab::Details => tl!("Details"), + CertTab::Trust => tl!("Trust"), + } +} + +/// The name and value rows of the Summary and Details tabs. +fn rows(tab: CertTab, c: &Certificate) -> Vec<(&'static str, String)> { + match tab { + CertTab::Summary => vec![ + ("Issued to", c.subject.display()), + ("Issued by", c.issuer.display()), + ("Valid from", c.not_before.to_string()), + ("Valid to", c.not_after.to_string()), + ("Intended usage", c.key_usage.map(key_usage).unwrap_or_else(|| tl!("Any").to_string())), + ], + CertTab::Details => vec![ + ("Version", "3".into()), + ("Serial number", c.serial_hex()), + ("Issuer", c.issuer.display()), + ("Subject", c.subject.display()), + ("Validity starts", c.not_before.to_string()), + ("Validity ends", c.not_after.to_string()), + ("Public key", c.public_key.describe()), + ("Basic constraints", tl!(if c.is_ca { "Certificate authority" } else { "End entity" }).to_string()), + ("Key usage", c.key_usage.map(key_usage).unwrap_or_else(|| tl!("Not present").to_string())), + ("Self-signed", if c.is_self_signed() { tl!("Yes").to_string() } else { tl!("No").to_string() }), + ("SHA-1 digest", hex(&sign::keys::DigestAlg::Sha1.digest(&[&c.raw]))), + ("SHA-256 digest", hex(&sign::keys::DigestAlg::Sha256.digest(&[&c.raw]))), + ], + CertTab::Trust => Vec::new(), + } +} + +/// The viewer's content: the chain beside the selected certificate's tabs. A request to trust the selected +/// certificate goes to `trust`. +fn body(ui: &mut egui::Ui, v: &mut CertViewer, trusted: &[Certificate], trust: &mut Option) { + Text::new(tl!("This dialog shows the details of a certificate and its chain.")).show(ui); + Row::new().show(ui, |ui, _| { + let len = v.chain.len(); + let mut selection = Selection::single(v.selected); + let out = List::::new(tl!("Certificate chain")) + .tree(true) + .select(SelectMode::Single) + .natural_height(true) + .selection(Bind::bound(&mut selection)) + .show_items(ui, &Chain { len }, &mut |key, _| { + let name = v.chain.get(*key).map(Certificate::display_name).unwrap_or_default(); + let row = ListRow::new(name).depth(len - 1 - key); + if *key > 0 { row.group(true) } else { row } + }); + for event in &out.events { + if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event + && let Some(key) = keys.last() + { + v.selected = *key; + } + } + let Some(c) = v.chain.get(v.selected).cloned() else { return }; + Stack::new().show(ui, |ui, _| { + let out = TabStrip::new(tl!("Certificate details")).kind(TabKind::Text).shown(v.tab).show_items(ui, &Tabs, &mut |tab, _| Tab::new(tab_label(*tab))); + for event in out.response.events { + if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event + && let Some(tab) = keys.into_iter().last() + { + v.tab = tab; + } + } + match v.tab { + CertTab::Trust => { + let is_trusted = trusted.iter().any(|x| x.raw == c.raw); + let anchored = v.chain.iter().any(|x| trusted.iter().any(|y| y.raw == x.raw)); + Text::new(if is_trusted { + tl!("This certificate is in your list of trusted certificates.") + } else if anchored { + tl!("This certificate is trusted through a certificate above it in the chain.") + } else { + tl!("This certificate is not trusted. Signatures made with it show an unknown identity.") + }) + .show(ui); + if !is_trusted && Button::new(tl!("Add to Trusted Certificates")).show(ui).clicked() { + *trust = Some(c.clone()); + } + } + tab => { + for (key, value) in rows(tab, &c) { + let name: Label = tl_ctx!("certificate", key).into(); + Field::new(name.clone()).show(ui, |ui, _| { + SelectableText::new(name.clone(), &value).multiline().show(ui); + }); + } + } + } + }); + }); +} + +/// Shows the Certificate Viewer while the app holds one. Export… keeps it open; OK, Escape and the close action +/// drop it. +pub(crate) fn show(app: &mut PdfCraftApp, ui: &mut egui::Ui) { + let trusted = app.session.trusted_certificates().to_vec(); + let Some(v) = app.cert_viewer.as_mut() else { return }; + v.selected = v.selected.min(v.chain.len().saturating_sub(1)); + let mut trust = None; + let shown = Dialog::new(tl!("Certificate Viewer")) + .buttons([FooterButton::new(tl!("Export…"), DialogRole::Other).stays_open(true), FooterButton::new(tl!("OK"), DialogRole::Accept)]) + .show(ui, |ui, _| body(ui, v, &trusted, &mut trust)); + let export = if shown.output.picked == Some(0) { v.chain.get(v.selected).cloned() } else { None }; + let close = shown.output.closed.is_some(); + if let Some(c) = trust { + app.trust_certificate(c); + } + if let Some(c) = export { + app.export_certificate(&c); + } + if close { + app.cert_viewer = None; + } +} diff --git a/crates/ui-egui/src/tools/sign_ui/panel.rs b/crates/ui-egui/src/tools/sign_ui/panel.rs index 269855875b..ab3f52884b 100644 --- a/crates/ui-egui/src/tools/sign_ui/panel.rs +++ b/crates/ui-egui/src/tools/sign_ui/panel.rs @@ -1,10 +1,21 @@ -use super::dialog::title; -use super::{Align, Certificate, Color32, Layout, SignatureInfo, SignatureStatus, Tokens, icons, sign, theme, widgets}; +use std::cell::RefCell; -/// The message bar for signed documents: (icon, colour, template, argument). +use craft::behavior::{DisplayOrder, IconId, ItemSource}; +use craft::theme::variant::Tone; +use craft::ui::buttons::{Button, Link}; +use craft::ui::contract::{CollectionEvent, Show as _, ShowCollection as _, ShowContainer as _}; +use craft::ui::layout_components::Stack; +use craft::ui::list::{List, ListRow, OpenSet, RowInk}; +use craft::ui::notices::Notice; +use craft::ui::primitives::IconSpec; +use craft::ui::runtime::env::Label; + +use super::{Certificate, SignatureInfo, SignatureStatus, sign}; + +/// The message bar for signed documents: (icon, tone, template, argument). /// The template renders through [`crate::i18n::tr_fmt`] at the call site, so the bar follows /// the UI language; names inside `argument` stay as they are. -pub(crate) fn banner(sigs: &[SignatureInfo]) -> Option<(&'static str, Color32, &'static str, String)> { +pub(crate) fn banner(sigs: &[SignatureInfo]) -> Option<(&'static str, Tone, &'static str, String)> { let signed: Vec<&SignatureInfo> = sigs.iter().filter(|s| s.signed).collect(); if signed.is_empty() { return None; @@ -23,35 +34,30 @@ pub(crate) fn banner(sigs: &[SignatureInfo]) -> Option<(&'static str, Color32, & }; crate::i18n::fmt(tl!(template), &[("who", &who), ("issuer", issuer)]) }); - return Some(("badge-check", Color32::from_rgb(0x14, 0x73, 0xE6), "Certified by {by}", by.unwrap_or_default())); + return Some(("badge-check", Tone::Info, "Certified by {by}", by.unwrap_or_default())); } Some(if signed.iter().any(|s| s.status == SignatureStatus::Invalid) { - ("circle-x", Color32::from_rgb(0xD7, 0x37, 0x3F), "At least one signature is invalid.", String::new()) + ("circle-x", Tone::Bad, "At least one signature is invalid.", String::new()) } else if signed.iter().all(|s| s.status == SignatureStatus::Valid) { - ("circle-check", Color32::from_rgb(0x2D, 0x9D, 0x78), "Signed and all signatures are valid.", String::new()) + ("circle-check", Tone::Good, "Signed and all signatures are valid.", String::new()) } else { - ("triangle-alert", Color32::from_rgb(0xE6, 0x86, 0x19), "At least one signature has problems.", String::new()) + ("triangle-alert", Tone::Warn, "At least one signature has problems.", String::new()) }) } -fn status_icon(s: &SignatureInfo) -> (&'static str, Color32) { - if !s.signed { - return ("pen-line", Color32::from_gray(0x80)); - } - signature_status_style(s.status) -} - /// One look per signature verdict, shared by the Signatures panel and the page badges so /// the two can't drift apart. -pub(crate) fn signature_status_style(status: SignatureStatus) -> (&'static str, Color32) { - // The colours the regenerated status layers draw with, so the page and the panel agree. - let [r, g, b] = sign::status_rgb(status); - let icon = match status { - SignatureStatus::Valid => "circle-check", - SignatureStatus::Unknown => "triangle-alert", - SignatureStatus::Invalid => "circle-x", - }; - (icon, Color32::from_rgb(r, g, b)) +pub(crate) fn status_tone(status: SignatureStatus) -> (IconId, Tone) { + match status { + SignatureStatus::Valid => (IconId::new("circle-check"), Tone::Good), + SignatureStatus::Unknown => (IconId::new("triangle-alert"), Tone::Warn), + SignatureStatus::Invalid => (IconId::new("circle-x"), Tone::Bad), + } +} + +/// The look of a signature's head row: its verdict, or the pen of a field nobody has signed. +fn head_look(s: &SignatureInfo) -> (IconId, Tone) { + if s.signed { status_tone(s.status) } else { (IconId::new("pen-line"), Tone::Neutral) } } /// What the Signatures panel asks the app to do. @@ -70,150 +76,232 @@ pub enum PanelAction { ViewCertificate(Vec), } -/// The Signatures panel body. -pub(crate) fn panel(ui: &mut egui::Ui, t: &Tokens, sigs: &[SignatureInfo], expanded: &mut Vec) -> Option { - let mut action = None; - ui.horizontal(|ui| { - if widgets::pill_button(ui, tl!("Validate all"), false).clicked() { - action = Some(PanelAction::Validate); - } - }); - ui.add_space(6.0); - if sigs.is_empty() { - ui.add_space(24.0); - ui.vertical_centered(|ui| { - ui.add(icons::image("signature", 32.0, t.text_faint)); - ui.add_space(6.0); - ui.label(egui::RichText::new(tl!("This document has no signatures.")).color(t.text_muted)); - }); - return action; +/// A row of the Signatures tree: a signature's head, or one line of what its open head shows. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +enum SigRow { + Head(String), + Line(String, usize), +} + +/// One line under an open head. +enum Child { + /// The unsigned field's "Sign this field…" button. + Sign, + /// The verdict sentence. + Status, + /// One finding of the validation, already in the panel's language. + Detail(String), + /// The "Signature Details" heading. + Heading, + /// A detail's name and value. + Pair(&'static str, String), + /// The field's page, as a link that goes there. + Page(usize), + /// The buttons under the details. + Buttons, +} + +/// The lines under the head of `s`, in the order they show. +fn children(s: &SignatureInfo) -> Vec { + if !s.signed { + return vec![Child::Sign]; } - let mut ordered: Vec<&SignatureInfo> = sigs.iter().collect(); - ordered.sort_by_key(|s| (!s.signed, s.revision)); - for s in ordered { - let open = expanded.contains(&s.field); - let (icon, color) = status_icon(s); - let (template, name) = match (s.signed, s.certify.is_some(), s.signer.as_deref()) { - (false, ..) => ("Unsigned signature field: {name}", s.field.as_str()), - (true, true, Some(signer)) => ("Rev. {rev}: Certified by {name}", signer), - (true, true, None) => ("Rev. {rev}: Certified by an unknown signer", ""), - (true, false, Some(signer)) => ("Rev. {rev}: Signed by {name}", signer), - (true, false, None) => ("Rev. {rev}: Signed by an unknown signer", ""), - }; - let head = crate::i18n::fmt(tl!(template), &[("rev", &s.revision.to_string()), ("name", name)]); - let resp = ui - .horizontal(|ui| { - let chevron = if open { "chevron-down" } else { "chevron-right" }; - let toggle = icons::button(ui, chevron, 20.0, false, if open { "Collapse" } else { "Expand" }).clicked(); - ui.add(icons::image(icon, 16.0, color)); - let l = ui.add(egui::Label::new(egui::RichText::new(&head).font(theme::semibold(12.5)).color(t.text)).sense(egui::Sense::click())); - toggle || l.clicked() + let mut lines = vec![Child::Status]; + // Each detail is a whole sentence of ours plus what the signature itself says; said in the + // panel's language, with the signature's own words left as they are. + lines.extend(s.details.iter().map(|d| Child::Detail(d.said(&crate::i18n::words).to_string()))); + lines.push(Child::Heading); + if let Some(r) = &s.reason { + lines.push(Child::Pair("Reason", r.clone())); + } + if let Some(l) = &s.location { + lines.push(Child::Pair("Location", l.clone())); + } + if let Some(d) = &s.date { + lines.push(Child::Pair("Signing time", sign::pdf::display_date(d))); + } + if let Some(a) = &s.algorithm { + lines.push(Child::Pair("Algorithm", a.clone())); + } + if let Some(c) = &s.certificate { + lines.push(Child::Pair("Signer", c.subject.display())); + lines.push(Child::Pair("Issued by", c.issuer.display())); + lines.push(Child::Pair("Valid", format!("{} to {}", c.not_before, c.not_after))); + } + lines.push(match s.page { + Some(p) => Child::Page(p), + None => Child::Pair("Field", s.field.clone()), + }); + lines.push(Child::Buttons); + lines +} + +/// The rows the tree shows: every head, and the lines of the heads that are open. +struct Rows<'a> { + entries: Vec<(SigRow, usize, bool)>, + open: &'a OpenSet, +} + +impl DisplayOrder for Rows<'_> { + fn len(&self) -> usize { + self.entries.len() + } + + fn key(&self, at: usize) -> SigRow { + self.entries[at].0.clone() + } + + fn depth(&self, at: usize) -> usize { + self.entries[at].1 + } + + fn has_children(&self, at: usize) -> bool { + self.entries[at].2 + } + + fn open(&self, at: usize) -> bool { + match &self.entries[at].0 { + SigRow::Head(field) => self.open.is_open(field), + SigRow::Line(..) => false, + } + } +} + +impl ItemSource for Rows<'_> {} + +/// The head row of a signature: the revision and signer, the verdict as its icon. +fn head_row(s: &SignatureInfo, open: bool) -> ListRow<'static> { + let (template, name) = match (s.signed, s.certify.is_some(), s.signer.as_deref()) { + (false, ..) => ("Unsigned signature field: {name}", s.field.as_str()), + (true, true, Some(signer)) => ("Rev. {rev}: Certified by {name}", signer), + (true, true, None) => ("Rev. {rev}: Certified by an unknown signer", ""), + (true, false, Some(signer)) => ("Rev. {rev}: Signed by {name}", signer), + (true, false, None) => ("Rev. {rev}: Signed by an unknown signer", ""), + }; + let head = crate::i18n::fmt(tl!(template), &[("rev", &s.revision.to_string()), ("name", name)]); + let (icon, tone) = head_look(s); + ListRow::new(head).depth(0).group(open).strong(true).icon(IconSpec::svg(icon)).tone(tone) +} + +/// One line under a head. The buttons and the page link put what they ask for in `action`. +fn line_row<'a>(s: &SignatureInfo, child: &Child, action: &'a RefCell>) -> ListRow<'a> { + let row = |label: Label| ListRow::new(label).depth(1); + match child { + Child::Sign => { + let field = s.field.clone(); + row(Label::Empty).accessible_name(tl!("Sign this field…")).below(Button::new(tl!("Sign this field…")), move |out| { + if out.clicked() { + *action.borrow_mut() = Some(PanelAction::Sign(field)); + } }) - .inner; - if resp { - if open { - expanded.retain(|f| f != &s.field); - } else { - expanded.push(s.field.clone()); + } + Child::Status => row( + match s.status { + SignatureStatus::Valid => tl!("Signature is valid:"), + SignatureStatus::Unknown => tl!("Signature validity is UNKNOWN:"), + SignatureStatus::Invalid => tl!("Signature is INVALID:"), } - } - if !open { - continue; - } - egui::Frame::NONE.inner_margin(egui::Margin { left: 44, right: 4, top: 2, bottom: 8 }).show(ui, |ui| { - ui.spacing_mut().item_spacing.y = 3.0; - if !s.signed { - if widgets::pill_button(ui, tl!("Sign this field…"), true).clicked() { - action = Some(PanelAction::Sign(s.field.clone())); + .into(), + ) + .strong(true), + Child::Detail(line) => row(format!("• {line}").into()).ink(RowInk::Muted), + Child::Heading => row(tl!("Signature Details").into()).section_heading(), + Child::Pair(key, value) => row(tl!(*key).into()).trailing(value.clone()), + Child::Page(p) => { + let text = crate::i18n::fmt(tl!("Field: {field} on page {p}"), &[("field", &s.field), ("p", &(p + 1).to_string())]); + let p = *p; + row(Label::Empty).accessible_name(text.clone()).below(Link::new(text), move |out| { + if out.clicked() { + *action.borrow_mut() = Some(PanelAction::GoTo(p)); } - return; - } - ui.label( - egui::RichText::new(match s.status { - SignatureStatus::Valid => tl!("Signature is valid:"), - SignatureStatus::Unknown => tl!("Signature validity is UNKNOWN:"), - SignatureStatus::Invalid => tl!("Signature is INVALID:"), - }) - .font(theme::semibold(12.0)), - ); - for detail in &s.details { - // Each detail is a whole sentence of ours plus what the signature itself says; said - // here in the panel's language, with the signature's own words left as they are. - let line = detail.said(&crate::i18n::words); - ui.add(egui::Label::new(egui::RichText::new(format!("• {line}")).font(theme::regular(11.5)).color(t.text_muted)).wrap()); - } - ui.add_space(4.0); - ui.label(egui::RichText::new(tl!("Signature Details")).font(theme::semibold(12.0))); - let row = |ui: &mut egui::Ui, k: &str, v: &str| { - ui.add(egui::Label::new(egui::RichText::new(format!("{}: {v}", tl!(k))).font(theme::regular(11.5))).wrap()); - }; - if let Some(r) = &s.reason { - row(ui, "Reason", r); - } - if let Some(l) = &s.location { - row(ui, "Location", l); - } - if let Some(d) = &s.date { - row(ui, "Signing time", &sign::pdf::display_date(d)); - } - if let Some(a) = &s.algorithm { - row(ui, "Algorithm", a); - } - if let Some(c) = &s.certificate { - row(ui, "Signer", &c.subject.display()); - row(ui, "Issued by", &c.issuer.display()); - row(ui, "Valid", &format!("{} to {}", c.not_before, c.not_after)); - } - match s.page { - Some(p) => { - let link = ui.add( - egui::Label::new( - egui::RichText::new(crate::i18n::fmt( - tl!("Field: {field} on page {p}"), - &[("field", &s.field), ("p", &(p + 1).to_string())], - )) - .font(theme::regular(11.5)) - .color(t.accent_text) - .underline(), - ) - .sense(egui::Sense::click()), - ); - if link.clicked() { - action = Some(PanelAction::GoTo(p)); + }) + } + Child::Buttons => { + let mut row = row(Label::Empty).accessible_name(tl!("Signature actions")); + // Trust exactly the signer shown above (s.certificate), not the chain top the + // document embedded: trusting an issuer or root is a separate, explicit step in + // the Certificate Viewer's Trust tab, which names that certificate. + if let Some(c) = s.certificate.as_ref() + && s.status == SignatureStatus::Unknown + { + let c = c.clone(); + row = row.below(Button::new(tl!("Add to trusted certificates")), move |out| { + if out.clicked() { + *action.borrow_mut() = Some(PanelAction::Trust(Box::new(c))); } - } - None => row(ui, "Field", &s.field), + }); } - ui.add_space(4.0); - ui.horizontal_wrapped(|ui| { - // Trust exactly the signer shown above (s.certificate), not the chain top the - // document embedded: trusting an issuer or root is a separate, explicit step in - // the Certificate Viewer's Trust tab, which names that certificate. - if let Some(c) = s.certificate.as_ref() - && s.status == SignatureStatus::Unknown - && ui.button(tl!("Add to trusted certificates")).clicked() - { - action = Some(PanelAction::Trust(Box::new(c.clone()))); - } - if ui.button(tl!("View signed version")).clicked() { - action = Some(PanelAction::ViewSigned { len: s.signed_len, revision: s.revision }); - } - if let Some(c) = &s.certificate - && ui.button(tl!("Show certificate…")).clicked() - { - let mut chain = vec![c.clone()]; - chain.extend(s.chain.iter().filter(|x| x.raw != c.raw).cloned()); - action = Some(PanelAction::ViewCertificate(chain)); - } - if let Some(c) = &s.certificate - && ui.button(tl!("Export certificate…")).clicked() - { - action = Some(PanelAction::ExportCertificate(Box::new(c.clone()))); + let (len, revision) = (s.signed_len, s.revision); + row = row.below(Button::new(tl!("View signed version")), move |out| { + if out.clicked() { + *action.borrow_mut() = Some(PanelAction::ViewSigned { len, revision }); } }); - }); + if let Some(c) = &s.certificate { + let mut chain = vec![c.clone()]; + chain.extend(s.chain.iter().filter(|x| x.raw != c.raw).cloned()); + row = row.below(Button::new(tl!("Show certificate…")), move |out| { + if out.clicked() { + *action.borrow_mut() = Some(PanelAction::ViewCertificate(chain)); + } + }); + let c = c.clone(); + row = row.below(Button::new(tl!("Export certificate…")), move |out| { + if out.clicked() { + *action.borrow_mut() = Some(PanelAction::ExportCertificate(Box::new(c))); + } + }); + } + row + } } - action +} + +/// The Signatures panel body. +pub(crate) fn panel(ui: &mut egui::Ui, sigs: &[SignatureInfo], open: &mut OpenSet) -> Option { + let action = RefCell::new(None); + Stack::new().show(ui, |ui, _| { + if Button::new(tl!("Validate all")).show(ui).clicked() { + *action.borrow_mut() = Some(PanelAction::Validate); + } + if sigs.is_empty() { + Notice::new(Tone::Info, tl!("This document has no signatures.")).show(ui); + return; + } + let mut ordered: Vec<(&SignatureInfo, Vec)> = sigs.iter().map(|s| (s, children(s))).collect(); + ordered.sort_by_key(|(s, _)| (!s.signed, s.revision)); + let heads: Vec = ordered.iter().map(|(s, _)| SigRow::Head(s.field.clone())).collect(); + let fields: Vec = ordered.iter().map(|(s, _)| s.field.clone()).collect(); + let mut entries = Vec::new(); + for (s, lines) in &ordered { + entries.push((SigRow::Head(s.field.clone()), 0, true)); + if open.is_open(&s.field) { + entries.extend((0..lines.len()).map(|i| (SigRow::Line(s.field.clone(), i), 1, false))); + } + } + let rows = Rows { entries, open }; + let find = |field: &str| ordered.iter().find(|(s, _)| s.field == field); + let out = List::::new(tl!("Signatures")).tree(true).natural_height(true).show_items(ui, &rows, &mut |key, _| match key { + SigRow::Head(field) => match find(field) { + Some((s, _)) => head_row(s, rows.open.is_open(field)), + None => ListRow::new(Label::Empty), + }, + SigRow::Line(field, i) => match find(field).and_then(|(s, lines)| lines.get(*i).map(|c| (s, c))) { + Some((s, child)) => line_row(s, child, &action), + None => ListRow::new(Label::Empty), + }, + }); + let _ = heads; + // Alt on a disclosure opens or closes every head; the lines are no groups and never report it. + for event in &out.events { + if let CollectionEvent::Open(change) = event + && let SigRow::Head(field) = &change.key + { + open.apply(field, change.open, change.all, fields.iter()); + } + } + }); + action.into_inner() } /// Certificate Viewer: a chain (the end certificate first) and the tab shown. @@ -224,18 +312,18 @@ pub struct CertViewer { pub tab: CertTab, } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum CertTab { Summary, Details, Trust, } -fn hex(bytes: &[u8]) -> String { +pub(super) fn hex(bytes: &[u8]) -> String { bytes.iter().map(|b| format!("{b:02X}")).collect::>().join(" ") } -fn key_usage(bits: u16) -> String { +pub(super) fn key_usage(bits: u16) -> String { const NAMES: [&str; 9] = [ "Digital Signature", "Non-Repudiation", @@ -251,110 +339,6 @@ fn key_usage(bits: u16) -> String { if used.is_empty() { tl!("None").into() } else { used.join(", ") } } -/// What the viewer asks for. -pub(crate) enum CertAction { - Trust(Box), - Export(Box), -} - -/// The Certificate Viewer dialog: the chain on the left, the selected certificate's tabs. -pub(crate) fn cert_viewer(ui: &mut egui::Ui, v: &mut CertViewer, trusted: &[Certificate], t: &Tokens) -> (bool, Option) { - title(ui, "Certificate Viewer"); - ui.label(egui::RichText::new(tl!("This dialog shows the details of a certificate and its chain.")).color(t.text_muted)); - ui.add_space(8.0); - let mut action = None; - v.selected = v.selected.min(v.chain.len().saturating_sub(1)); - ui.horizontal_top(|ui| { - // The chain, root at the top (as Acrobat shows it). - ui.vertical(|ui| { - ui.set_width(200.0); - for (depth, i) in (0..v.chain.len()).rev().enumerate() { - let c = &v.chain[i]; - ui.horizontal(|ui| { - ui.add_space(depth as f32 * 12.0); - if ui.selectable_label(v.selected == i, c.display_name()).clicked() { - v.selected = i; - } - }); - } - }); - ui.add_space(16.0); - ui.vertical(|ui| { - ui.set_width(440.0); - let Some(c) = v.chain.get(v.selected).cloned() else { return }; - ui.horizontal(|ui| { - for (tab, label) in [(CertTab::Summary, tl!("Summary")), (CertTab::Details, tl!("Details")), (CertTab::Trust, tl!("Trust"))] { - if widgets::pill_button(ui, label, v.tab == tab).clicked() { - v.tab = tab; - } - } - }); - ui.add_space(8.0); - let grid = |ui: &mut egui::Ui, rows: Vec<(&str, String)>| { - egui::Grid::new(("cert-rows", v.tab as u8)).num_columns(2).spacing([12.0, 5.0]).show(ui, |ui| { - for (k, val) in rows { - ui.label(egui::RichText::new(tl_ctx!("certificate", k)).color(t.text_muted)); - ui.add(egui::Label::new(val).wrap()); - ui.end_row(); - } - }); - }; - match v.tab { - CertTab::Summary => grid( - ui, - vec![ - ("Issued to", c.subject.display()), - ("Issued by", c.issuer.display()), - ("Valid from", c.not_before.to_string()), - ("Valid to", c.not_after.to_string()), - ("Intended usage", c.key_usage.map(key_usage).unwrap_or_else(|| tl!("Any").to_string())), - ], - ), - CertTab::Details => grid( - ui, - vec![ - ("Version", "3".into()), - ("Serial number", c.serial_hex()), - ("Issuer", c.issuer.display()), - ("Subject", c.subject.display()), - ("Validity starts", c.not_before.to_string()), - ("Validity ends", c.not_after.to_string()), - ("Public key", c.public_key.describe()), - ("Basic constraints", tl!(if c.is_ca { "Certificate authority" } else { "End entity" }).to_string()), - ("Key usage", c.key_usage.map(key_usage).unwrap_or_else(|| tl!("Not present").to_string())), - ("Self-signed", if c.is_self_signed() { tl!("Yes").to_string() } else { tl!("No").to_string() }), - ("SHA-1 digest", hex(&sign::keys::DigestAlg::Sha1.digest(&[&c.raw]))), - ("SHA-256 digest", hex(&sign::keys::DigestAlg::Sha256.digest(&[&c.raw]))), - ], - ), - CertTab::Trust => { - let is_trusted = trusted.iter().any(|x| x.raw == c.raw); - let anchored = v.chain.iter().any(|x| trusted.iter().any(|y| y.raw == x.raw)); - ui.label(if is_trusted { - tl!("This certificate is in your list of trusted certificates.") - } else if anchored { - tl!("This certificate is trusted through a certificate above it in the chain.") - } else { - tl!("This certificate is not trusted. Signatures made with it show an unknown identity.") - }); - ui.add_space(8.0); - if !is_trusted && widgets::pill_button(ui, tl!("Add to Trusted Certificates"), false).clicked() { - action = Some(CertAction::Trust(Box::new(c.clone()))); - } - } - } - ui.add_space(8.0); - if widgets::pill_button(ui, tl!("Export…"), false).clicked() { - action = Some(CertAction::Export(Box::new(c.clone()))); - } - }); - }); - ui.add_space(10.0); - let mut close = false; - ui.horizontal(|ui| ui.with_layout(Layout::right_to_left(Align::Center), |ui| close = widgets::pill_button(ui, tl!("OK"), true).clicked())); - (close, action) -} - /// The text of an exported certificate (`.cer`, PEM). pub fn certificate_pem(c: &Certificate) -> String { sign::x509::to_pem(c) diff --git a/crates/ui-egui/tests/it/trust_signer.rs b/crates/ui-egui/tests/it/trust_signer.rs index c7a2ad739f..b4e4f2b126 100644 --- a/crates/ui-egui/tests/it/trust_signer.rs +++ b/crates/ui-egui/tests/it/trust_signer.rs @@ -75,8 +75,10 @@ fn one_click_trust_stores_the_displayed_signer_not_the_embedded_root() { (signer, root) }; - // Expand the signature row and use the one-click trust button. + // Open the signature row (a click picks it, Right opens a tree row) and use the one-click trust button. h.get_by_label_contains("Signed by").click(); + h.run_steps(1); + h.key_press(egui::Key::ArrowRight); h.run_steps(2); h.get_by_label("Add to trusted certificates").click(); h.run_steps(3);