diff --git a/crates/esign/src/lib.rs b/crates/esign/src/lib.rs index 4efb15116..e9e6fa04b 100644 --- a/crates/esign/src/lib.rs +++ b/crates/esign/src/lib.rs @@ -47,7 +47,11 @@ pub trait Envelopes { /// The finished document and provider evidence. /// - /// Fails unless status is [`EnvelopeStatus::Completed`]. + /// Fails unless status is [`EnvelopeStatus::Completed`]. The returned + /// [`CompletedDocument`] carries both the original document's content + /// digest and the signed artifact's digest, computed honestly rather + /// than copied from one another: the implementation must not assume the + /// provider's sealing left the bytes unchanged. fn completed(&self, envelope: &str) -> Result; /// Cancel an in-flight envelope. @@ -99,6 +103,8 @@ pub trait SigningService: Envelopes + EventIntake { #[cfg(test)] mod tests { + use std::sync::Mutex; + use super::*; use craft_cloud::Identity; @@ -192,4 +198,121 @@ mod tests { let err = Error::Declined("no".into()); assert!(!err.is_transient()); } + + /// A non-cryptographic stand-in for a content digest. Good enough to + /// prove two byte strings differ; this crate takes no hashing + /// dependency, since hashing the document is an adapter's job. + fn fake_digest(bytes: &[u8]) -> String { + use std::hash::{Hash, Hasher}; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + bytes.hash(&mut hasher); + format!("{:016x}", hasher.finish()) + } + + /// An honest in-process double for [`Envelopes`]. It keeps the exact + /// bytes `create` was given, and on `completed` returns a "signed" + /// artifact built by appending a stub provider seal to those bytes, so + /// `original_content_sha256` and `signed_content_sha256` are computed + /// from genuinely different byte strings, the way a real provider's + /// sealing would produce them, rather than one copied from the other. + struct Double { + document: Mutex>>, + } + + impl Double { + fn new() -> Double { + Double { document: Mutex::new(None) } + } + } + + impl Envelopes for Double { + fn create(&self, draft: &EnvelopeDraft, document: &[u8], _idempotency_key: &str) -> Result { + *self.document.lock().expect("lock") = Some(document.to_vec()); + Ok(Envelope { + id: "env-double".into(), + title: draft.title.clone(), + message: draft.message.clone(), + sender: draft.sender.clone(), + document_id: draft.document_id.clone(), + document_etag: draft.document_etag.clone(), + content_sha256: fake_digest(document), + recipients: draft.recipients.clone(), + placements: draft.placements.clone(), + status: EnvelopeStatus::Draft, + expires: draft.expires.clone(), + created: None, + completed_at: None, + }) + } + + fn send(&self, envelope: &str) -> Result { + self.status(envelope) + } + + fn status(&self, envelope: &str) -> Result { + let document = self.document.lock().expect("lock").clone().unwrap_or_default(); + Ok(Envelope { + id: envelope.into(), + title: "Double".into(), + message: None, + sender: Identity { id: "u1".into(), display: "Ada".into(), email: None, avatar: None }, + document_id: None, + document_etag: None, + content_sha256: fake_digest(&document), + recipients: Vec::new(), + placements: Vec::new(), + status: EnvelopeStatus::Completed, + expires: None, + created: None, + completed_at: None, + }) + } + + fn completed(&self, envelope: &str) -> Result { + let original = self.document.lock().expect("lock").clone().unwrap_or_default(); + let mut signed = original.clone(); + signed.extend_from_slice(b"\0provider-seal"); + Ok(CompletedDocument { + envelope_id: envelope.into(), + bytes: signed.clone(), + original_content_sha256: fake_digest(&original), + signed_content_sha256: fake_digest(&signed), + evidence: b"certificate-of-completion".to_vec(), + }) + } + } + + /// RFC-0021's evidence guarantee: `CompletedDocument` carries the + /// original document's digest and the signed artifact's digest as two + /// distinct, honestly computed fields, and they differ when the + /// provider's sealing changes the bytes. + #[test] + fn completed_document_keeps_original_and_signed_digests_distinct() { + let double = Double::new(); + let draft = EnvelopeDraft { + title: "Contract".into(), + message: None, + sender: Identity { id: "u1".into(), display: "Ada".into(), email: None, avatar: None }, + document_id: Some("doc-1".into()), + document_etag: None, + recipients: Vec::new(), + placements: Vec::new(), + expires: None, + }; + let original_bytes = b"the original document bytes"; + let envelope = double.create(&draft, original_bytes, "idem-1").expect("create"); + let completed = double.completed(&envelope.id).expect("completed"); + + assert_eq!(completed.original_content_sha256, fake_digest(original_bytes)); + assert_ne!(completed.bytes, original_bytes, "the signed artifact's bytes differ from the original"); + assert_eq!(completed.signed_content_sha256, fake_digest(&completed.bytes)); + assert_ne!( + completed.original_content_sha256, completed.signed_content_sha256, + "sealing changed the bytes, so the two digests must not be conflated" + ); + + let json = serde_json::to_string(&completed).expect("serialize"); + let back: CompletedDocument = serde_json::from_str(&json).expect("deserialize"); + assert_eq!(back, completed); + } } diff --git a/crates/esign/src/types.rs b/crates/esign/src/types.rs index c75f99a67..08d42456e 100644 --- a/crates/esign/src/types.rs +++ b/crates/esign/src/types.rs @@ -149,11 +149,25 @@ pub struct Envelope { } /// The finished document plus whatever evidence the provider returns. +/// +/// Carries two digests as distinct fields, never conflated: the original +/// document's content digest and the returned signed artifact's digest. The +/// two are the same hash family as [`Envelope::content_sha256`] and can +/// differ in value. A provider's sealing (a certificate page, flattening, a +/// visible audit stamp) can change the signed bytes relative to the document +/// the envelope was created from, so a caller must not assume `bytes` hashes +/// back to `original_content_sha256`. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct CompletedDocument { pub envelope_id: String, /// Signed document bytes. Opaque to this crate. pub bytes: Vec, + /// SHA-256 of the original document bytes the envelope was created from, + /// lowercase hex. Matches the envelope's own `content_sha256`. + pub original_content_sha256: String, + /// SHA-256 of `bytes`, the returned signed artifact, lowercase hex. May + /// differ from `original_content_sha256`; see the struct's docs. + pub signed_content_sha256: String, /// Provider evidence (certificate of completion, audit export, …). pub evidence: Vec, } diff --git a/crates/ui/src/esign/mod.rs b/crates/ui/src/esign/mod.rs index 7bfd017fa..c9f404583 100644 --- a/crates/ui/src/esign/mod.rs +++ b/crates/ui/src/esign/mod.rs @@ -4,6 +4,7 @@ //! Nothing here blocks: answers arrive on a channel and are read once per //! frame. Signing is not sharing: recipients are never [`craft_cloud::ShareTarget`]s. +use std::collections::HashMap; use std::sync::mpsc::{Receiver, Sender}; use std::time::Duration; @@ -12,6 +13,8 @@ use craft_esign::{Envelope, EnvelopeDraft, EnvelopeStatus, EsignCapability, Fiel use egui::{Context, RichText, Ui}; mod backend; +#[cfg(test)] +mod review_repro; pub use backend::{Answer, EsignBackend, Replier, Request}; @@ -24,6 +27,17 @@ const RETRY: f64 = 20.0; type Inbox = (u64, Result); +/// What dialog state a reply belongs to: which document, under which +/// signed-in account. A reply installs only when this still matches the +/// dialog's current context; see [`EsignDialog::submit_in_context`] and +/// [`EsignDialog::pump`]. Deliberately excludes incidental UI state such as +/// search text, which changes without the dialog meaning something new. +#[derive(Clone, Debug, PartialEq, Eq)] +struct EsignContext { + document_id: String, + account: Option, +} + /// Every string the dialog shows. #[derive(Clone, Debug)] pub struct EsignLabels { @@ -103,6 +117,9 @@ pub struct EsignDialog { tx: Sender, rx: Receiver, newest: u64, + /// Context (document plus account) each in-flight context-sensitive + /// request was issued under. Consulted, then removed, in [`Self::pump`]. + contexts: HashMap, document_id: String, document_etag: Option, document_title: String, @@ -141,6 +158,7 @@ impl Default for EsignDialog { tx, rx, newest: 0, + contexts: HashMap::new(), document_id: String::new(), document_etag: None, document_title: String::new(), @@ -202,6 +220,10 @@ impl EsignDialog { self.completed_bytes = None; self.error = None; self.draft_idempotency_key = None; + // Any job still in flight was issued for the context being left. + // Its reply will be dropped in `pump` (context no longer + // matches), so nothing will ever clear `busy` on its behalf. + self.busy = false; } self.account_fingerprint = Some(fingerprint); self.document_id = document_id; @@ -230,7 +252,7 @@ impl EsignDialog { /// Submit a request through the host backend (for example after the app /// encoded document bytes for a [`SendRequest`]). pub fn submit_request(&mut self, request: Request) { - let _ = self.submit(request); + let _ = self.submit_in_context(request); } /// Completed document bytes after a successful download request. @@ -262,19 +284,38 @@ impl EsignDialog { seq } + /// The context (document plus account) a reply must still match to install. + fn current_context(&self) -> EsignContext { + EsignContext { document_id: self.document_id.clone(), account: self.account_fingerprint.clone() } + } + + /// Like [`Self::submit`], but tags the request with the dialog's current + /// context. Everything that acts on one envelope (create, status, + /// completed, void, remind) goes through here. Capabilities does not: + /// it is answered before a document is ever opened and stays valid + /// across documents and accounts. Lookup does: a contact search issued + /// before a reopen must not populate the reopened dialog either. + fn submit_in_context(&mut self, request: Request) -> u64 { + let seq = self.submit(request); + self.contexts.insert(seq, self.current_context()); + seq + } + fn pump(&mut self, now: f64) { while let Ok((seq, result)) = self.rx.try_recv() { if self.caps_seq == Some(seq) { self.caps_seq = None; } - if seq < self.newest && !matches!(result, Ok(Answer::Capabilities { .. })) { - // Stale lookup or status; keep capabilities even if older. - if !matches!(&result, Ok(Answer::Lookup(_))) { - continue; - } - if seq != self.lookup_seq { - continue; - } + // A context-tagged reply installs only for the context that + // issued it; it drops silently for any other, including a + // document switch or an account switch. Typing in the signer + // search bumps `newest` and is not a context change, so it no + // longer gates a create/status/completed/void/remind reply: the + // rule here is context equality, nothing else. + if let Some(context) = self.contexts.remove(&seq) + && context != self.current_context() + { + continue; } match result { Ok(Answer::Capabilities { capabilities, responsible_party, linked }) => { @@ -336,7 +377,7 @@ impl EsignDialog { } self.looking = true; self.last_lookup_query = self.query.clone(); - self.lookup_seq = self.submit(Request::Lookup { query: self.query.clone(), limit: MATCHES }); + self.lookup_seq = self.submit_in_context(Request::Lookup { query: self.query.clone(), limit: MATCHES }); } fn add_contact(&mut self, contact: Contact) { @@ -521,18 +562,18 @@ impl EsignDialog { && let Some(r) = env.recipients.iter().find(|r| r.status == RecipientStatus::Pending) { self.busy = true; - let _ = self.submit(Request::Remind { envelope: env.id.clone(), recipient: r.id.clone() }); + let _ = self.submit_in_context(Request::Remind { envelope: env.id.clone(), recipient: r.id.clone() }); } if caps.contains(&EsignCapability::Void) && env.status == EnvelopeStatus::Sent && ui.add_enabled(!self.busy, egui::Button::new(&self.labels.void)).clicked() { self.busy = true; - let _ = self.submit(Request::Void { envelope: env.id.clone(), reason: "voided by sender".into() }); + let _ = self.submit_in_context(Request::Void { envelope: env.id.clone(), reason: "voided by sender".into() }); } if env.status == EnvelopeStatus::Completed && ui.add_enabled(!self.busy, egui::Button::new(&self.labels.download)).clicked() { self.busy = true; - let _ = self.submit(Request::Completed { envelope: env.id.clone() }); + let _ = self.submit_in_context(Request::Completed { envelope: env.id.clone() }); } if ui.button(&self.labels.close).clicked() { self.open = false; @@ -540,7 +581,7 @@ impl EsignDialog { }); if ui.button("Refresh status").clicked() { self.busy = true; - let _ = self.submit(Request::Status { envelope: env.id.clone() }); + let _ = self.submit_in_context(Request::Status { envelope: env.id.clone() }); } } } diff --git a/crates/ui/src/esign/review_repro.rs b/crates/ui/src/esign/review_repro.rs new file mode 100644 index 000000000..452fdfefc --- /dev/null +++ b/crates/ui/src/esign/review_repro.rs @@ -0,0 +1,151 @@ +//! Regression tests for the three gate items skylartaylor raised on PR #661, +//! reproduced against 0a937ef (storytold/craft-libs#661): +//! . +//! +//! `Hold` is a backend that keeps every request and its `Replier` so a test +//! chooses when, and in what order, the service answers. + +use std::sync::{Arc, Mutex}; + +use craft_cloud::Identity; +use craft_esign::{Envelope, EnvelopeStatus, EsignCapability}; + +use super::*; + +#[derive(Clone, Default)] +struct Hold(Arc>>); + +impl EsignBackend for Hold { + fn submit(&self, request: Request, reply: Replier) { + self.0.lock().unwrap().push((request, reply)); + } +} + +impl Hold { + /// Takes the oldest held request matching `pick`. + fn take(&self, pick: impl Fn(&Request) -> bool) -> (Request, Replier) { + let mut held = self.0.lock().unwrap(); + let i = held.iter().position(|(r, _)| pick(r)).expect("request was submitted"); + held.remove(i) + } +} + +fn who(id: &str) -> Identity { + Identity { id: id.into(), display: id.into(), email: Some(format!("{id}@example.com")), avatar: None } +} + +fn envelope_for(doc: &str, sender: &str) -> Envelope { + Envelope { + id: format!("env-{doc}"), + title: format!("Contract {doc}"), + message: None, + sender: who(sender), + document_id: Some(doc.into()), + document_etag: None, + content_sha256: String::new(), + recipients: Vec::new(), + placements: Vec::new(), + status: EnvelopeStatus::Sent, + expires: None, + created: None, + completed_at: None, + } +} + +/// A dialog with a held backend whose capabilities probe has been answered. +fn ready() -> (EsignDialog, Hold) { + let hold = Hold::default(); + let mut dialog = EsignDialog::default(); + dialog.set_backend(hold.clone()); + dialog.pump(0.0); // submits Capabilities + let (_, caps) = hold.take(|r| matches!(r, Request::Capabilities)); + caps.answer(Answer::Capabilities { + capabilities: vec![EsignCapability::Envelopes, EsignCapability::Void], + responsible_party: "Stub Signing".into(), + linked: true, + }); + dialog.pump(0.1); + assert!(dialog.available()); + (dialog, hold) +} + +/// The app's Send path: queue_send -> take_send_request -> submit Create. +fn send(dialog: &mut EsignDialog, doc_bytes: &[u8]) { + dialog.add_email("bob@example.com".into()); + dialog.queue_send(); + let out = dialog.take_send_request().expect("Send produced a request"); + dialog.submit_request(Request::Create { + draft: Box::new(out.draft), + document: doc_bytes.to_vec(), + idempotency_key: out.idempotency_key, + send: true, + }); +} + +/// Gate item 1 (document variant): the dialog is reopened for document B +/// while document A's create is in flight. A's late reply carries document +/// A's context and must not be installed as document B's envelope. +#[test] +fn review_h5_reply_for_previous_document_is_installed_after_reopen() { + let (mut dialog, hold) = ready(); + dialog.open("doc-A".into(), "A.pdf".into(), None, who("alice")); + send(&mut dialog, b"A bytes"); + dialog.open("doc-B".into(), "B.pdf".into(), None, who("alice")); + + let (_, create_a) = hold.take(|r| matches!(r, Request::Create { .. })); + create_a.answer(Answer::Created(envelope_for("doc-A", "alice"))); + dialog.pump(1.0); + + let shown = dialog.envelope.as_ref().and_then(|e| e.document_id.clone()); + assert!( + shown.is_none() || shown.as_deref() == Some("doc-B"), + "dialog is open for doc-B but shows the envelope for {shown:?} (status panel: Void/Remind act on it); busy={}", + dialog.busy + ); +} + +/// Gate item 1 (account variant): reopened for the same document under +/// another signed-in account. Alice's envelope must never render for +/// mallory. +#[test] +fn review_h5_reply_for_previous_account_is_installed_after_account_switch() { + let (mut dialog, hold) = ready(); + dialog.open("doc-A".into(), "A.pdf".into(), None, who("alice")); + send(&mut dialog, b"A bytes"); + dialog.open("doc-A".into(), "A.pdf".into(), None, who("mallory")); + + let (_, create) = hold.take(|r| matches!(r, Request::Create { .. })); + create.answer(Answer::Created(envelope_for("doc-A", "alice"))); + dialog.pump(1.0); + + let shown = dialog.envelope.as_ref().map(|e| e.sender.id.clone()); + assert!(shown.is_none() || shown.as_deref() == Some("mallory"), "dialog now belongs to mallory but shows alice's envelope: sender={shown:?}"); +} + +/// Gate item 2: Send is in flight; the user types in the signer search box +/// (a lookup is submitted, which used to bump the old staleness counter). +/// The create reply then arrives for the same context and must still +/// install: typing in a search box is not a context change. +#[test] +fn review_n1_create_reply_dropped_after_a_lookup_leaves_dialog_busy() { + let (mut dialog, hold) = ready(); + dialog.open("doc-A".into(), "A.pdf".into(), None, who("alice")); + send(&mut dialog, b"A bytes"); + assert!(dialog.busy); + + dialog.query = "ca".into(); // typed after pressing Send + dialog.query_changed_at = 1.0; + dialog.maybe_lookup(2.0); + + let (_, create) = hold.take(|r| matches!(r, Request::Create { .. })); + create.answer(Answer::Created(envelope_for("doc-A", "alice"))); + for t in 0..10 { + dialog.pump(3.0 + f64::from(t)); + } + assert!( + !dialog.busy && dialog.envelope.is_some(), + "provider created env-doc-A but dialog busy={} envelope={:?} (reply dropped as stale)", + dialog.busy, + dialog.envelope.as_ref().map(|e| e.id.clone()) + ); +}