diff --git a/Cargo.lock b/Cargo.lock index 4031c80f9..7220f81cf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1924,6 +1924,16 @@ dependencies = [ "zip 9.1.3", ] +[[package]] +name = "craft-esign" +version = "0.1.0" +dependencies = [ + "craft-cloud", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-evm" version = "0.1.0" @@ -3315,6 +3325,7 @@ name = "craft-ui" version = "0.1.0" dependencies = [ "craft-cloud", + "craft-esign", "craft-fonts-build", "craft-i18n", "eframe", diff --git a/Cargo.toml b/Cargo.toml index 63ab712f6..74b208820 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -95,6 +95,7 @@ craft-dpx = { path = "crates/dpx" } craft-dwg = { path = "crates/dwg" } craft-fcproj-format = { path = "crates/fcproj-format" } craft-ecproj-format = { path = "crates/ecproj-format" } +craft-esign = { path = "crates/esign" } craft-figma-rest = { path = "crates/figma-rest" } craft-exr = { path = "crates/exr" } craft-flags = { path = "crates/flags" } diff --git a/crates/esign/Cargo.toml b/crates/esign/Cargo.toml new file mode 100644 index 000000000..7a2efc324 --- /dev/null +++ b/crates/esign/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "craft-esign" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true +description = "What an e-sign service offers the Craft apps: envelopes, recipients and events as contracts, with no vendor and no IO" + +[lints] +workspace = true + +[dependencies] +craft-cloud = { workspace = true } +serde = { workspace = true } +thiserror = { workspace = true } + +[dev-dependencies] +serde_json = { workspace = true } diff --git a/crates/esign/src/error.rs b/crates/esign/src/error.rs new file mode 100644 index 000000000..fca354b45 --- /dev/null +++ b/crates/esign/src/error.rs @@ -0,0 +1,63 @@ +//! One error type for every e-sign contract. +//! +//! Cloud failures are wrapped so a host can surface sign-in and reachability +//! the same way it already does for files. The e-sign-only cases are the ones +//! a UI acts on differently: declined, voided, expired, identity check. + +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum Error { + /// Something the cloud contracts already classify. + #[error(transparent)] + Cloud(#[from] craft_cloud::Error), + + /// A recipient refused to sign. + #[error("declined: {0}")] + Declined(String), + + /// The sender voided the envelope. + #[error("voided: {0}")] + Voided(String), + + /// The envelope passed its deadline without completing. + #[error("expired: {0}")] + Expired(String), + + /// The provider rejected the signer's identity check. + #[error("identity check failed: {0}")] + IdentityCheck(String), + + /// The chosen provider refuses this request under its policy. + #[error("provider policy: {0}")] + ProviderPolicy(String), + + /// The service does not offer this at all. + #[error("this signing service does not support {0}")] + Unsupported(&'static str), + + /// The answer did not match the protocol. + #[error("malformed {what}: {detail}")] + Malformed { what: &'static str, detail: String }, + + /// A field the caller supplied could not be used safely. + #[error("invalid {what}: {detail}")] + Invalid { what: &'static str, detail: String }, +} + +impl Error { + pub fn malformed(what: &'static str, detail: impl Into) -> Error { + Error::Malformed { what, detail: detail.into() } + } + + pub fn invalid(what: &'static str, detail: impl Into) -> Error { + Error::Invalid { what, detail: detail.into() } + } + + /// Whether trying again could succeed without the user doing anything. + pub fn is_transient(&self) -> bool { + matches!(self, Error::Cloud(e) if e.is_transient()) + } +} + +pub type Result = std::result::Result; diff --git a/crates/esign/src/lib.rs b/crates/esign/src/lib.rs new file mode 100644 index 000000000..e9e6fa04b --- /dev/null +++ b/crates/esign/src/lib.rs @@ -0,0 +1,318 @@ +//! What an e-sign service has to offer the Craft apps, and nothing about who +//! provides it. +//! +//! An envelope is a ceremony: a document snapshot, a set of recipients, field +//! placements, and a status. The legal audit trail, identity checks and +//! invitation mail belong to the signing service. This crate only names the +//! contracts an app needs to create, send, watch and finish that ceremony. +//! +//! Nothing in this crate opens a socket. Each trait is implemented by a host +//! (CollabCraft, a desktop adapter, a test double) that brings its own +//! transport. No type here names a vendor. No type here knows about PDF +//! structure: a document is opaque bytes plus a content hash. +//! +//! This crate sits beside `craft-cloud`. It reuses [`craft_cloud::Identity`] +//! and the idea of a contact for autocomplete, but it does not extend +//! [`craft_cloud::Provider`] or [`craft_cloud::Capability`]. Signing is not +//! file access, and a signer role is not a share permission. + +#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] + +mod error; +mod types; + +pub use error::{Error, Result}; +pub use types::{ + CompletedDocument, Envelope, EnvelopeDraft, EnvelopeEvent, EnvelopeStatus, EsignCapability, FieldPlacement, Recipient, RecipientStatus, +}; + +/// Creating and driving envelopes. +/// +/// Methods that a minimal service may omit are defaulted to +/// [`Error::Unsupported`], the same pattern [`craft_cloud::Conversations`] +/// uses for optional cloud features. +pub trait Envelopes { + /// Create a draft from a document snapshot. + /// + /// `document` is the exact byte sequence the ceremony seals. The + /// implementation hashes it and stores `content_sha256` on the envelope. + /// `idempotency_key` makes a retried create return the same envelope. + fn create(&self, draft: &EnvelopeDraft, document: &[u8], idempotency_key: &str) -> Result; + + /// Send invitations and move the envelope to [`EnvelopeStatus::Sent`]. + fn send(&self, envelope: &str) -> Result; + + /// Current status, including per-recipient progress. + fn status(&self, envelope: &str) -> Result; + + /// The finished document and provider evidence. + /// + /// 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. + fn void(&self, _envelope: &str, _reason: &str) -> Result<()> { + Err(Error::Unsupported("void")) + } + + /// Nudge one recipient who has not signed yet. + fn remind(&self, _envelope: &str, _recipient: &str) -> Result<()> { + Err(Error::Unsupported("reminders")) + } + + /// A URL the recipient opens to sign inside the provider's UI. + fn signing_url(&self, _envelope: &str, _recipient: &str, _return_to: &str) -> Result { + Err(Error::Unsupported("embedded signing")) + } +} + +/// Turning provider webhooks into [`EnvelopeEvent`]s. +/// +/// Server-side only. A desktop host that implements [`Envelopes`] never needs +/// a webhook secret and need not implement this beyond refusing. +pub trait EventIntake { + /// Verify authenticity and parse zero or more events from one HTTP body. + fn verify_event(&self, headers: &[(String, String)], body: &[u8]) -> Result>; +} + +/// Everything one signing service can do. +/// +/// A service implements the capabilities it has and reports the rest as +/// absent, so a caller can hide void on a stub that only supports the happy +/// path rather than offering a control that fails on use. +pub trait SigningService: Envelopes + EventIntake { + /// A stable identifier, such as `stub` or `documenso`. Used in + /// configuration and logs, never shown to a user. + fn id(&self) -> &str; + + /// What this service actually supports. + fn capabilities(&self) -> Vec; + + fn supports(&self, capability: EsignCapability) -> bool { + self.capabilities().contains(&capability) + } + + /// The party that holds legal and compliance responsibility for the + /// ceremony. Shown to senders before they send (upstream #2315). + fn responsible_party(&self) -> String; +} + +#[cfg(test)] +mod tests { + use std::sync::Mutex; + + use super::*; + use craft_cloud::Identity; + + struct RefuseAll; + + impl Envelopes for RefuseAll { + fn create(&self, _: &EnvelopeDraft, _: &[u8], _: &str) -> Result { + Err(Error::Unsupported("create")) + } + + fn send(&self, _: &str) -> Result { + Err(Error::Unsupported("send")) + } + + fn status(&self, _: &str) -> Result { + Err(Error::Unsupported("status")) + } + + fn completed(&self, _: &str) -> Result { + Err(Error::Unsupported("completed")) + } + } + + impl EventIntake for RefuseAll { + fn verify_event(&self, _: &[(String, String)], _: &[u8]) -> Result> { + Err(Error::Unsupported("webhooks")) + } + } + + impl SigningService for RefuseAll { + fn id(&self) -> &str { + "refuse" + } + + fn capabilities(&self) -> Vec { + Vec::new() + } + + fn responsible_party(&self) -> String { + "nobody".into() + } + } + + #[test] + fn defaulted_methods_are_unsupported() { + let s = RefuseAll; + assert!(matches!(s.void("e", "x"), Err(Error::Unsupported("void")))); + assert!(matches!(s.remind("e", "r"), Err(Error::Unsupported("reminders")))); + assert!(matches!(s.signing_url("e", "r", "https://example"), Err(Error::Unsupported("embedded signing")))); + assert!(!s.supports(EsignCapability::Envelopes)); + assert_eq!(s.responsible_party(), "nobody"); + } + + #[test] + fn draft_round_trips_json() { + let draft = EnvelopeDraft { + title: "NDA".into(), + message: Some("please sign".into()), + sender: Identity { id: "u1".into(), display: "Ada".into(), email: Some("ada@example.com".into()), avatar: None }, + document_id: Some("doc-1".into()), + document_etag: Some("\"abc\"".into()), + recipients: vec![Recipient { + id: "r1".into(), + name: "Bob".into(), + email: "bob@example.com".into(), + role: "Signer".into(), + required: true, + status: RecipientStatus::Pending, + }], + placements: vec![FieldPlacement { + role: "Signer".into(), + page: 0, + x: 0.1, + y: 0.2, + w: 0.3, + h: 0.05, + kind: "signature".into(), + required: true, + }], + expires: Some("2026-12-31".into()), + }; + let json = serde_json::to_string(&draft).expect("serialize"); + let back: EnvelopeDraft = serde_json::from_str(&json).expect("deserialize"); + assert_eq!(back, draft); + } + + #[test] + fn cloud_errors_wrap_and_report_transient() { + let err = Error::from(craft_cloud::Error::Unreachable("down".into())); + assert!(err.is_transient()); + 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 new file mode 100644 index 000000000..08d42456e --- /dev/null +++ b/crates/esign/src/types.rs @@ -0,0 +1,186 @@ +//! The data the e-sign contracts pass around. +//! +//! Every type here is plain and vendor-neutral. A field that only means +//! something to one product belongs in that provider's crate. Nothing here +//! knows about PDF structure; a document is opaque bytes plus a content hash. + +use craft_cloud::Identity; +use serde::{Deserialize, Serialize}; + +/// What a signing service can do. +/// +/// Reported rather than assumed, so a caller hides void or remind on a service +/// that only supports create/send/status/completed. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EsignCapability { + /// Create, send, poll status, and fetch the completed document. + Envelopes, + /// Cancel an in-flight envelope. + Void, + /// Nudge a recipient who has not signed yet. + Reminders, + /// Return a URL the recipient opens to sign in the provider's UI. + EmbeddedSigning, + /// Accept provider webhooks and turn them into [`EnvelopeEvent`]s. + Webhooks, +} + +/// Where an envelope is in its life. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum EnvelopeStatus { + /// Created but not yet sent to recipients. + Draft, + /// At least one recipient still owes a signature. + Sent, + /// Every required recipient has signed. + Completed, + /// The sender cancelled it. + Voided, + /// A recipient declined. + Declined, + /// The deadline passed without completion. + Expired, +} + +/// What one recipient still owes, or has done. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RecipientStatus { + Pending, + Viewed, + Signed, + Declined, +} + +/// Who must sign, as the dialog and the service agree. +/// +/// Built from a [`craft_cloud::Contact`] by an explicit conversion at the host +/// boundary. Never a [`craft_cloud::ShareTarget`]: signing is not access. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Recipient { + /// Opaque handle the service wants back. + pub id: String, + /// What to show. A display name where there is one. + pub name: String, + /// Delivery address. Required for invitation mail. + pub email: String, + /// Signer role label, such as "Client" or "Countersign". Colours and + /// field placement key off this string within one envelope. + pub role: String, + /// Whether the envelope cannot complete without this person. + pub required: bool, + pub status: RecipientStatus, +} + +/// One signature (or initials / date) placement on the document. +/// +/// Coordinates are normalised page space: origin top-left, `x`/`y`/`w`/`h` in +/// `[0.0, 1.0]` of the page. The document implementation maps these onto its +/// own field model; this crate never sees PDF objects. +#[derive(Clone, Debug, Serialize, Deserialize)] +pub struct FieldPlacement { + /// Recipient role this field belongs to. + pub role: String, + /// Zero-based page index. + pub page: u32, + pub x: f32, + pub y: f32, + pub w: f32, + pub h: f32, + /// Machine-readable kind: `signature`, `initials`, `date`, `text`. + pub kind: String, + pub required: bool, +} + +impl PartialEq for FieldPlacement { + fn eq(&self, other: &Self) -> bool { + self.role == other.role + && self.page == other.page + && self.kind == other.kind + && self.required == other.required + && self.x.to_bits() == other.x.to_bits() + && self.y.to_bits() == other.y.to_bits() + && self.w.to_bits() == other.w.to_bits() + && self.h.to_bits() == other.h.to_bits() + } +} + +impl Eq for FieldPlacement {} + +/// What the caller wants to send, before the service assigns an id. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EnvelopeDraft { + /// Human title for the ceremony. + pub title: String, + /// Optional note shown to recipients. + pub message: Option, + /// Who is asking for signatures. Bound to the active account at send time. + pub sender: Identity, + /// Cloud document identity at the moment of the snapshot, when known. + pub document_id: Option, + pub document_etag: Option, + pub recipients: Vec, + pub placements: Vec, + /// `YYYY-MM-DD`. After this the envelope expires if still open. + pub expires: Option, +} + +/// An envelope the service knows about. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct Envelope { + pub id: String, + pub title: String, + pub message: Option, + pub sender: Identity, + pub document_id: Option, + pub document_etag: Option, + /// SHA-256 of the document bytes at create time, lowercase hex. + pub content_sha256: String, + pub recipients: Vec, + pub placements: Vec, + pub status: EnvelopeStatus, + pub expires: Option, + /// RFC 3339. + pub created: Option, + /// RFC 3339 when status became [`EnvelopeStatus::Completed`]. + pub completed_at: Option, +} + +/// 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, +} + +/// Something that happened to an envelope. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct EnvelopeEvent { + pub envelope_id: String, + /// Machine-readable kind: `sent`, `viewed`, `signed`, `declined`, `voided`, `completed`. + pub kind: String, + /// Recipient id when the event is about one person. + pub recipient_id: Option, + /// RFC 3339. + pub at: Option, + pub detail: Option, +} diff --git a/crates/ui/Cargo.toml b/crates/ui/Cargo.toml index ac5085cd9..cbb7b8dfe 100644 --- a/crates/ui/Cargo.toml +++ b/crates/ui/Cargo.toml @@ -19,9 +19,11 @@ log = "0.4" serde = { version = "1", features = ["derive"], optional = true } # Same version as epaint's, for reading a face's character map. skrifa = { version = "0.44", default-features = false, features = ["std"] } -# The vendor-neutral vocabulary the share dialog speaks. No IO and no -# vendor, so this stays buildable for the web. +# The vendor-neutral vocabulary the share and e-sign dialogs speak. No IO and +# no vendor, so this stays buildable for the web. craft-cloud = { workspace = true, optional = true } +# The e-sign contract the request-signatures dialog states its work through. +craft-esign = { workspace = true, optional = true } # The control channel's report of the cloud state. One serialiser here # rather than one per application. No IO and no vendor. serde_json = { workspace = true, optional = true } @@ -65,6 +67,8 @@ share = ["dep:craft-cloud"] # Open and Save against cloud storage. Needs the share dialog, which a # document's overflow menu and the Share split button both open. cloud = ["share", "dep:serde_json"] +# Request-signatures dialog. +esign = ["dep:craft-cloud", "dep:craft-esign"] [dev-dependencies] # serde: the IME tests read events that only the suite's egui fork has from JSON. diff --git a/crates/ui/src/esign/backend.rs b/crates/ui/src/esign/backend.rs new file mode 100644 index 000000000..8d80a18f4 --- /dev/null +++ b/crates/ui/src/esign/backend.rs @@ -0,0 +1,92 @@ +//! Where the e-sign dialog's work happens, which is never on the frame. +//! +//! Same shape as [`crate::share::ShareBackend`]: the dialog states what it +//! wants, something behind this trait does the waiting, and answers arrive on +//! a channel keyed by sequence number. + +use craft_cloud::Contact; +use craft_esign::{CompletedDocument, Envelope, EnvelopeDraft, EsignCapability}; + +/// One thing the dialog needs done. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Request { + /// What the signing service can actually do, and who is legally responsible. + Capabilities, + /// People matching what has been typed so far (cloud contacts). + Lookup { query: String, limit: usize }, + /// Create a draft from a document snapshot, then optionally send it. + Create { draft: Box, document: Vec, idempotency_key: String, send: bool }, + /// Current status of one envelope. + Status { envelope: String }, + /// Finished document bytes. + Completed { envelope: String }, + /// Cancel an in-flight envelope. + Void { envelope: String, reason: String }, + /// Nudge one recipient. + Remind { envelope: String, recipient: String }, +} + +/// What came back. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Answer { + Capabilities { + capabilities: Vec, + responsible_party: String, + /// Whether a cloud account is attached so invitations can leave. + linked: bool, + }, + Lookup(Vec), + Created(Envelope), + Status(Envelope), + Completed(CompletedDocument), + Voided { + envelope: String, + }, + Reminded { + envelope: String, + recipient: String, + }, +} + +/// Where one answer goes. +pub struct Replier { + seq: u64, + tx: std::sync::mpsc::Sender<(u64, Result)>, +} + +impl Replier { + pub(crate) fn new(seq: u64, tx: std::sync::mpsc::Sender<(u64, Result)>) -> Replier { + Replier { seq, tx } + } + + pub fn seq(&self) -> u64 { + self.seq + } + + pub fn dup(&self) -> Replier { + Replier { seq: self.seq, tx: self.tx.clone() } + } + + pub fn answer(self, answer: Answer) { + self.deliver(Ok(answer)); + } + + pub fn refuse(self, reason: impl Into) { + self.deliver(Err(reason.into())); + } + + fn deliver(self, result: Result) { + let _ = self.tx.send((self.seq, result)); + } +} + +impl std::fmt::Debug for Replier { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Replier").field("seq", &self.seq).finish() + } +} + +/// Somewhere a [`Request`] can run without blocking a frame. +pub trait EsignBackend { + fn submit(&self, request: Request, reply: Replier); +} diff --git a/crates/ui/src/esign/coderabbit_repro.rs b/crates/ui/src/esign/coderabbit_repro.rs new file mode 100644 index 000000000..c7c954002 --- /dev/null +++ b/crates/ui/src/esign/coderabbit_repro.rs @@ -0,0 +1,216 @@ +//! Regression tests for the CodeRabbit findings reviewed on PR #661, +//! reproduced against ef496161 (storytold/craft-libs#661). +//! +//! Reuses `review_repro`'s `Hold` backend and helpers: a test chooses when, +//! and in what order, a held request is answered. + +use craft_esign::{Envelope, EnvelopeStatus}; + +use super::review_repro::{Hold, envelope_for, ready, send, who}; +use super::*; + +/// Only one capabilities probe is ever outstanding for the current backend. +/// `set_backend` clears `caps_seq`, but a reply already in flight from the +/// backend being replaced keeps its old sequence number: it must not +/// overwrite capabilities, responsible or linked for the new backend when +/// it finally arrives. +#[test] +fn a_capabilities_reply_from_a_replaced_backend_does_not_overwrite_the_new_ones() { + let hold_a = Hold::default(); + let mut dialog = EsignDialog::default(); + dialog.set_backend(hold_a.clone()); + dialog.pump(0.0); + let (_, caps_a) = hold_a.take(|r| matches!(r, Request::Capabilities)); + + // The backend is replaced before A's capabilities probe answers. + let hold_b = Hold::default(); + dialog.set_backend(hold_b.clone()); + dialog.pump(0.1); + let (_, caps_b) = hold_b.take(|r| matches!(r, Request::Capabilities)); + + caps_b.answer(Answer::Capabilities { capabilities: vec![EsignCapability::Envelopes], responsible_party: "B".into(), linked: true }); + dialog.pump(0.2); + assert_eq!(dialog.responsible.as_deref(), Some("B")); + + // A's reply, from the replaced backend, arrives after B's already installed. + caps_a.answer(Answer::Capabilities { capabilities: vec![EsignCapability::Void], responsible_party: "A".into(), linked: false }); + dialog.pump(0.3); + + assert_eq!(dialog.responsible.as_deref(), Some("B"), "a stale Capabilities reply from a replaced backend overwrote the new backend's"); + assert!(dialog.linked, "a stale Capabilities reply from a replaced backend turned linked back off"); +} + +/// A document's revision changing is itself a context change: a reply for +/// the bytes under the old `document_etag` must not install under the new +/// one, even though the document id never changed. +#[test] +fn stale_create_reply_for_old_revision_is_dropped_after_reopen_with_new_etag() { + let (mut dialog, hold) = ready(); + dialog.open("doc-A".into(), "A.pdf".into(), Some("etag-1".into()), who("alice")); + send(&mut dialog, b"A bytes etag1"); + dialog.open("doc-A".into(), "A.pdf".into(), Some("etag-2".into()), who("alice")); + + let (_, create) = hold.take(|r| matches!(r, Request::Create { .. })); + create.answer(Answer::Created(envelope_for("doc-A", "alice"))); + dialog.pump(1.0); + + assert!( + dialog.envelope.is_none(), + "stale reply for etag-1 installed into the etag-2 opening: {:?}", + dialog.envelope.as_ref().map(|e| e.id.clone()) + ); +} + +/// `take_send_request` already handed the application doc-A's draft; the +/// dialog then reopens for doc-B before the application calls +/// `submit_request`. The reply this produces must still be tagged with +/// doc-A's context, not doc-B's. +#[test] +fn create_reply_for_a_request_taken_before_reopening_does_not_install_in_the_new_document() { + let (mut dialog, hold) = ready(); + dialog.open("doc-A".into(), "A.pdf".into(), None, who("alice")); + dialog.add_email("bob@example.com".into()); + dialog.queue_send(); + let out = dialog.take_send_request().expect("send produced a request"); + + // The dialog moves on before the application gets around to submitting + // what it already took. + dialog.open("doc-B".into(), "B.pdf".into(), None, who("alice")); + dialog.submit_request(Request::Create { + draft: Box::new(out.draft), + document: b"A bytes".to_vec(), + idempotency_key: out.idempotency_key, + send: true, + }); + + let (_, create) = hold.take(|r| matches!(r, Request::Create { .. })); + create.answer(Answer::Created(envelope_for("doc-A", "alice"))); + dialog.pump(1.0); + + assert!( + dialog.envelope.is_none(), + "doc-A's envelope, submitted after reopening doc-B, installed into doc-B's dialog: {:?}", + dialog.envelope.as_ref().map(|e| e.id.clone()) + ); +} + +/// An untaken `SendRequest` is specific to the context that queued it; it +/// must not survive into a reopened dialog for another document. +#[test] +fn an_untaken_send_request_does_not_survive_reopening_for_another_document() { + let (mut dialog, _hold) = ready(); + dialog.open("doc-A".into(), "A.pdf".into(), None, who("alice")); + dialog.add_email("bob@example.com".into()); + dialog.queue_send(); + + dialog.open("doc-B".into(), "B.pdf".into(), None, who("alice")); + + assert!(dialog.take_send_request().is_none(), "doc-B's dialog still held doc-A's untaken send request"); +} + +/// `note_create_result` is the synchronous twin of `submit_request`: an app +/// that handles create itself, rather than through the backend channel, +/// reports the outcome here. It must drop a result for a context the dialog +/// has already left, exactly as a channel reply would. +#[test] +fn note_create_result_for_a_previous_document_does_not_install_in_the_reopened_dialog() { + let (mut dialog, _hold) = ready(); + dialog.open("doc-A".into(), "A.pdf".into(), None, who("alice")); + dialog.add_email("bob@example.com".into()); + dialog.queue_send(); + let _out = dialog.take_send_request().expect("send produced a request"); + + dialog.open("doc-B".into(), "B.pdf".into(), None, who("alice")); + dialog.note_create_result(Ok(envelope_for("doc-A", "alice"))); + + assert!( + dialog.envelope.is_none(), + "doc-A's result, reported after reopening doc-B, installed into doc-B's dialog: {:?}", + dialog.envelope.as_ref().map(|e| e.id.clone()) + ); +} + +/// `Replier::dup` is the only way a backend can answer one sequence twice. +/// The dialog answers the first reply normally, but a second reply for the +/// same (already resolved) sequence must drop unconditionally, not reach +/// the match arms with no context left to check against. +#[test] +fn a_duplicated_answer_for_an_already_resolved_sequence_is_dropped() { + let (mut dialog, hold) = ready(); + dialog.open("doc-A".into(), "A.pdf".into(), None, who("alice")); + send(&mut dialog, b"A bytes"); + + let (_, create) = hold.take(|r| matches!(r, Request::Create { .. })); + let dup = create.dup(); + create.answer(Answer::Created(envelope_for("doc-A", "alice"))); + dialog.pump(1.0); + assert_eq!(dialog.envelope.as_ref().map(|e| e.id.clone()), Some("env-doc-A".to_owned()), "the first answer should have installed normally"); + + // The dialog moves on; a backend still holding `dup` from the first + // request answers it again. + dialog.open("doc-B".into(), "B.pdf".into(), None, who("alice")); + dup.answer(Answer::Created(envelope_for("doc-A", "alice"))); + dialog.pump(2.0); + + let shown = dialog.envelope.as_ref().and_then(|e| e.document_id.clone()); + assert!( + shown.is_none() || shown.as_deref() == Some("doc-B"), + "a duplicate answer for the first request reinstalled doc-A's envelope into doc-B's dialog: {shown:?}" + ); +} + +/// `busy` belongs to whichever operation is still pending. A lookup that +/// fails while a create is genuinely in flight must not report the create +/// as finished. +#[test] +fn a_failed_lookup_does_not_clear_busy_for_a_pending_create() { + 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, "queue_send should have left the dialog busy"); + + dialog.query = "ca".into(); + dialog.query_changed_at = 0.0; + dialog.maybe_lookup(1.0); + let (_, lookup) = hold.take(|r| matches!(r, Request::Lookup { .. })); + lookup.refuse("lookup failed"); + dialog.pump(2.0); + + assert!(dialog.busy, "a failed lookup cleared busy while the create for doc-A was still pending"); +} + +/// Two "Refresh status" clicks before either reply arrives race two +/// `Request::Status` calls. If the older one answers after the newer one +/// already installed, it must not overwrite the newer status. +#[test] +fn an_older_status_reply_does_not_overwrite_a_newer_one() { + let (mut dialog, hold) = ready(); + dialog.open("doc-A".into(), "A.pdf".into(), None, who("alice")); + send(&mut dialog, b"A bytes"); + let (_, create) = hold.take(|r| matches!(r, Request::Create { .. })); + create.answer(Answer::Created(envelope_for("doc-A", "alice"))); + dialog.pump(1.0); + let env_id = dialog.envelope.as_ref().expect("created").id.clone(); + + dialog.busy = true; + let seq1 = dialog.submit_in_context(Request::Status { envelope: env_id.clone() }); + dialog.pending_op_seq = Some(seq1); + dialog.status_seq = seq1; + dialog.busy = true; + let seq2 = dialog.submit_in_context(Request::Status { envelope: env_id.clone() }); + dialog.pending_op_seq = Some(seq2); + dialog.status_seq = seq2; + + let (_, status1) = hold.take(|r| matches!(r, Request::Status { .. })); + let (_, status2) = hold.take(|r| matches!(r, Request::Status { .. })); + + // The newer request (seq2) answers first. + status2.answer(Answer::Status(Envelope { status: EnvelopeStatus::Completed, ..envelope_for("doc-A", "alice") })); + dialog.pump(2.0); + assert_eq!(dialog.envelope.as_ref().map(|e| e.status), Some(EnvelopeStatus::Completed)); + + // The older request (seq1), issued first, answers last. + status1.answer(Answer::Status(Envelope { status: EnvelopeStatus::Sent, ..envelope_for("doc-A", "alice") })); + dialog.pump(3.0); + assert_eq!(dialog.envelope.as_ref().map(|e| e.status), Some(EnvelopeStatus::Completed), "an older status reply overwrote a newer one"); +} diff --git a/crates/ui/src/esign/coderabbit_round2_repro.rs b/crates/ui/src/esign/coderabbit_round2_repro.rs new file mode 100644 index 000000000..190ca1fa9 --- /dev/null +++ b/crates/ui/src/esign/coderabbit_round2_repro.rs @@ -0,0 +1,108 @@ +//! Regression tests for CodeRabbit's second review pass on PR #661, +//! reproduced against 1e84947c (storytold/craft-libs#661). +//! +//! Reuses `review_repro`'s `Hold` backend and helpers, the same as +//! `coderabbit_repro`. + +use craft_esign::{Envelope, EnvelopeStatus}; + +use super::review_repro::{Hold, envelope_for, ready, send, who}; +use super::*; + +/// A host can drive `Request::Status` through the public `submit_request` +/// path directly, not only through `status_panel`'s own "Refresh status" +/// button. That path must register `status_seq` too, or the reply it +/// produces fails the supersession guard added for the button's path and is +/// dropped. +#[test] +fn submit_request_for_a_public_status_submission_registers_status_seq() { + let (mut dialog, hold) = ready(); + dialog.open("doc-A".into(), "A.pdf".into(), None, who("alice")); + send(&mut dialog, b"A bytes"); + let (_, create) = hold.take(|r| matches!(r, Request::Create { .. })); + create.answer(Answer::Created(envelope_for("doc-A", "alice"))); + dialog.pump(1.0); + let env_id = dialog.envelope.as_ref().expect("created").id.clone(); + + dialog.submit_request(Request::Status { envelope: env_id }); + let (_, status) = hold.take(|r| matches!(r, Request::Status { .. })); + status.answer(Answer::Status(Envelope { status: EnvelopeStatus::Completed, ..envelope_for("doc-A", "alice") })); + dialog.pump(2.0); + + assert_eq!( + dialog.envelope.as_ref().map(|e| e.status), + Some(EnvelopeStatus::Completed), + "a Status reply submitted through the public submit_request path was dropped by the status_seq guard" + ); +} + +/// `available()` stops asking again once the service has reported +/// `Envelopes`, so a backend whose `linked` value changes out of band (the +/// user signs in after the dialog already probed) is never re-asked unless +/// something clears the cached capabilities. `reset_capabilities` is that +/// something, on the same backend instance. +#[test] +fn reset_capabilities_reprobes_the_same_backend_after_an_out_of_band_sign_in() { + let hold = Hold::default(); + let mut dialog = EsignDialog::default(); + dialog.set_backend(hold.clone()); + dialog.pump(0.0); + let (_, caps1) = hold.take(|r| matches!(r, Request::Capabilities)); + caps1.answer(Answer::Capabilities { capabilities: vec![EsignCapability::Envelopes], responsible_party: "Stub Signing".into(), linked: false }); + dialog.pump(0.1); + assert!(dialog.available()); + assert!(!dialog.linked); + + // Available is already true, so pump's own retry condition + // (`!available() && ...`) never fires again on its own, no matter how + // much time passes. + for t in 0..5 { + dialog.pump(0.2 + f64::from(t)); + } + + // The user signs in; nothing about the backend instance changes, so + // only an explicit reset asks again. + dialog.reset_capabilities(); + dialog.pump(1.0); + let (_, caps2) = hold.take(|r| matches!(r, Request::Capabilities)); + caps2.answer(Answer::Capabilities { capabilities: vec![EsignCapability::Envelopes], responsible_party: "Stub Signing".into(), linked: true }); + dialog.pump(1.1); + + assert!(dialog.linked, "reset_capabilities did not pick up the backend's new linked state"); +} + +/// The captured send context belongs only to the create submission that +/// answers a taken [`SendRequest`]. A status refresh submitted for the +/// current document while another document's send is still outstanding must +/// carry the current context, or `pump` drops its reply as belonging to the +/// abandoned send. +#[test] +fn status_for_the_current_document_is_not_consumed_by_an_outstanding_send_from_another() { + let (mut dialog, hold) = ready(); + + // Document A's send is taken by the app but never submitted: its captured + // context stays pending. The `send` helper would submit the create and + // consume that context, which is exactly what this test must avoid. + dialog.open("doc-A".into(), "A.pdf".into(), None, who("alice")); + dialog.add_email("bob@example.com".into()); + dialog.queue_send(); + let taken = dialog.take_send_request(); + assert!(taken.is_some(), "A's send request was taken, leaving its context pending"); + + // The dialog moves on to document B, which already has an envelope the + // host wants a status for. + dialog.open("doc-B".into(), "B.pdf".into(), None, who("alice")); + dialog.envelope = Some(envelope_for("doc-B", "alice")); + let env_id = dialog.envelope.as_ref().map(|e| e.id.clone()).unwrap_or_default(); + + dialog.submit_request(Request::Status { envelope: env_id }); + let (_, status) = hold.take(|r| matches!(r, Request::Status { .. })); + status.answer(Answer::Status(Envelope { status: EnvelopeStatus::Completed, ..envelope_for("doc-B", "alice") })); + dialog.pump(1.0); + + assert_eq!( + dialog.envelope.as_ref().map(|e| e.status), + Some(EnvelopeStatus::Completed), + "B's status reply was dropped because the status request consumed A's outstanding send context" + ); +} diff --git a/crates/ui/src/esign/mod.rs b/crates/ui/src/esign/mod.rs new file mode 100644 index 000000000..64087bbd5 --- /dev/null +++ b/crates/ui/src/esign/mod.rs @@ -0,0 +1,1037 @@ +//! Request-signatures dialog, the same one in every Craft app that sends PDFs. +//! +//! Nothing here opens a socket. Every call goes through [`EsignBackend`]. +//! 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; + +use craft_cloud::{Contact, Identity}; +use craft_esign::{Envelope, EnvelopeDraft, EnvelopeStatus, EsignCapability, FieldPlacement, Recipient, RecipientStatus}; +use egui::{Context, RichText, Ui}; + +mod backend; +#[cfg(test)] +mod coderabbit_repro; +#[cfg(test)] +mod coderabbit_round2_repro; +#[cfg(test)] +mod review_repro; + +pub use backend::{Answer, EsignBackend, Replier, Request}; + +/// How long after the last keystroke the dialog asks for matches. +pub const DEBOUNCE: Duration = Duration::from_millis(200); + +const MATCHES: usize = 8; +const MIN_QUERY: usize = 2; +const RETRY: f64 = 20.0; + +type Inbox = (u64, Result); + +/// What dialog state a reply belongs to: which document revision, under +/// which signed-in account, opened which time. 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. +/// +/// `opening` is bumped every time [`EsignDialog::open`] actually changes +/// something (document, revision or account). `document_etag` alone would +/// already separate two revisions of the same document id, but it cannot +/// separate "document A, closed, then A opened again" from the first +/// opening: both carry the same id and the same etag. `opening` does. +#[derive(Clone, Debug, PartialEq, Eq)] +struct EsignContext { + document_id: String, + document_etag: Option, + account: Option, + opening: u64, +} + +/// Every string the dialog shows. +#[derive(Clone, Debug)] +pub struct EsignLabels { + pub title: String, + pub recipients: String, + pub recipient_hint: String, + pub searching: String, + pub no_matches: String, + pub add_address: String, + pub role: String, + pub message: String, + pub send: String, + pub sending: String, + pub close: String, + pub loading: String, + pub responsible: String, + pub no_service: String, + pub sign_in_first: String, + pub need_recipient: String, + /// Shown instead of adding the person, when a search match has no email + /// address the provider can invite. + pub contact_missing_email: String, + pub status: String, + pub void: String, + pub remind: String, + pub download: String, + pub request: String, + /// Caption of the status panel's manual refresh action. + pub refresh: String, +} + +impl Default for EsignLabels { + fn default() -> EsignLabels { + EsignLabels { + title: "Request signatures".into(), + recipients: "Signers".into(), + recipient_hint: "Name or email".into(), + searching: "Searching…".into(), + no_matches: "No matches".into(), + add_address: "Add email address".into(), + role: "Role".into(), + message: "Message".into(), + send: "Send".into(), + sending: "Sending…".into(), + close: "Close".into(), + loading: "Loading…".into(), + responsible: "Signing is provided by {party}. That party holds legal and compliance responsibility for the ceremony.".into(), + no_service: "Signatures cannot be requested here.".into(), + sign_in_first: "Sign in to request signatures.".into(), + need_recipient: "Add at least one signer.".into(), + contact_missing_email: "This contact has no email address to invite.".into(), + status: "Status".into(), + void: "Void".into(), + remind: "Remind".into(), + download: "Download completed".into(), + request: "Request signatures".into(), + refresh: "Refresh status".into(), + } + } +} + +/// What the application must supply when the user presses Send. +/// +/// The dialog holds recipients and copy; the application owns the document +/// bytes and encodes them, then submits [`Request::Create`] through the backend. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct SendRequest { + pub draft: EnvelopeDraft, + pub idempotency_key: String, +} + +/// One Request signatures dialog. +pub struct EsignDialog { + open: bool, + labels: EsignLabels, + backend: Option>, + capabilities: Option>, + responsible: Option, + linked: bool, + asked_caps_at: Option, + caps_seq: Option, + draft_idempotency_key: Option, + seq: u64, + 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, + /// Sequences whose context has already been consulted once in + /// [`Self::pump`], bounded to the most recent entries. A backend that + /// answers the same sequence twice (via [`Replier::dup`]) has its second + /// answer dropped unconditionally instead of re-entering the match arms + /// with no context to check. + consumed: std::collections::HashSet, + consumed_order: std::collections::VecDeque, + /// The sequence that currently owns `busy`, if any. An answer (success or + /// failure) for any other sequence must not clear `busy` on its behalf. + pending_op_seq: Option, + /// The most recently issued `Request::Status` sequence. An older status + /// reply that arrives after a newer one has already installed is + /// superseded and dropped. + status_seq: u64, + /// How many times [`Self::open`] has actually changed something. Part of + /// [`EsignContext`]; see its docs. + opening: u64, + document_id: String, + document_etag: Option, + document_title: String, + sender: Option, + query: String, + query_changed_at: f64, + lookup_seq: u64, + last_lookup_query: String, + matches: Vec, + looking: bool, + recipients: Vec, + /// How many recipients have ever been added for the document currently + /// open, used to label the next one. Monotonic, not derived from the + /// current recipient count or roles in use: a count- or scan-based label + /// is free to repeat once the recipient holding it is removed, and a + /// freed role can then bind a new recipient to an old recipient's + /// placements. Reset in [`Self::open`] alongside `recipients`. + next_role_number: u32, + message: String, + placements: Vec, + busy: bool, + error: Option, + envelope: Option, + send_out: Option, + /// The context [`Self::queue_send`] captured for the still-outstanding + /// [`SendRequest`], consumed by [`Self::submit_request`] or + /// [`Self::note_create_result`] so a reply is tagged with the context the + /// send was queued under, not whatever context is current when the + /// application finally submits it. + pending_send_context: Option, + completed_bytes: Option>, + account_fingerprint: Option, +} + +impl Default for EsignDialog { + fn default() -> EsignDialog { + let (tx, rx) = std::sync::mpsc::channel(); + EsignDialog { + open: false, + labels: EsignLabels::default(), + backend: None, + capabilities: None, + responsible: None, + linked: false, + asked_caps_at: None, + caps_seq: None, + draft_idempotency_key: None, + seq: 0, + tx, + rx, + newest: 0, + contexts: HashMap::new(), + consumed: std::collections::HashSet::new(), + consumed_order: std::collections::VecDeque::new(), + pending_op_seq: None, + status_seq: 0, + opening: 0, + document_id: String::new(), + document_etag: None, + document_title: String::new(), + sender: None, + query: String::new(), + query_changed_at: 0.0, + lookup_seq: 0, + last_lookup_query: String::new(), + matches: Vec::new(), + looking: false, + recipients: Vec::new(), + next_role_number: 0, + message: String::new(), + placements: Vec::new(), + busy: false, + error: None, + envelope: None, + send_out: None, + pending_send_context: None, + completed_bytes: None, + account_fingerprint: None, + } + } +} + +/// A send operation id no other send in this process has used, from a random +/// start so one saved by an earlier process is unlikely to repeat either. +/// Mirrors `docking::model::fresh_window_id`: a counter kept on one +/// [`EsignDialog`] repeats across two dialog instances (two windows, or one +/// replaced after a document closes), and two sends sharing an idempotency +/// key have a conforming provider return the first envelope for the second. +fn fresh_send_id() -> u64 { + use std::hash::{BuildHasher, Hasher}; + use std::sync::OnceLock; + use std::sync::atomic::{AtomicU64, Ordering}; + static NEXT: OnceLock = OnceLock::new(); + let next = NEXT.get_or_init(|| AtomicU64::new(std::collections::hash_map::RandomState::new().build_hasher().finish() >> 1)); + next.fetch_add(1, Ordering::Relaxed) +} + +/// Whether the dialog stays open after one [`EsignDialog::show`] frame. +/// +/// `window_open` is egui's own title-bar close control; `dialog_open` is +/// whatever [`EsignDialog::ui`] already decided, such as a Close button. +/// Either one closing the dialog must stick: a plain `window_open` would +/// let the window's unchanged binding undo a Close button clicked inside +/// the same frame. +fn still_open(window_open: bool, dialog_open: bool) -> bool { + window_open && dialog_open +} + +impl EsignDialog { + pub fn new() -> EsignDialog { + EsignDialog::default() + } + + pub fn labels(mut self, labels: EsignLabels) -> EsignDialog { + self.labels = labels; + self + } + + pub fn set_backend(&mut self, backend: impl EsignBackend + 'static) { + self.backend = Some(Box::new(backend)); + self.reset_capabilities(); + } + + /// Probe the current backend again for capabilities and link state. + /// + /// `available()` never asks again once the service has reported + /// [`EsignCapability::Envelopes`]; the retry in [`Self::pump`] is for a + /// backend that is still unavailable, not for a `linked` value that is + /// stale after an out-of-band sign-in. Call this once that sign-in + /// completes on the backend already set, when replacing it with + /// [`Self::set_backend`] would be artificial. A reply still in flight + /// from the probe this replaces is dropped in [`Self::pump`] exactly as + /// one from a backend [`Self::set_backend`] already replaced is: + /// `caps_seq` is cleared here the same way. + pub fn reset_capabilities(&mut self) { + self.capabilities = None; + self.asked_caps_at = None; + self.caps_seq = None; + } + + /// False until the service reports [`EsignCapability::Envelopes`]. + pub fn available(&self) -> bool { + self.capabilities.as_ref().is_some_and(|c| c.contains(&EsignCapability::Envelopes)) + } + + pub fn is_open(&self) -> bool { + self.open + } + + /// Open for a document. `sender` is the active account identity. + pub fn open(&mut self, document_id: String, document_title: String, document_etag: Option, sender: Identity) { + let fingerprint = format!("{}@{}", sender.id, sender.email.as_deref().unwrap_or("")); + let account_changed = self.account_fingerprint.as_deref() != Some(fingerprint.as_str()); + let document_changed = self.document_id != document_id; + let revision_changed = self.document_etag != document_etag; + if account_changed || document_changed || revision_changed { + self.recipients.clear(); + self.next_role_number = 0; + self.message.clear(); + self.envelope = None; + self.completed_bytes = None; + self.error = None; + self.draft_idempotency_key = None; + // A's fields must never reappear as B's: see the Major finding + // this guards against. + self.placements.clear(); + // An untaken send request was built for the context being left; + // drop it so a later `take_send_request` cannot hand the + // application A's draft to submit under B's dialog. + // `pending_send_context`, captured once the request is taken, is + // deliberately left alone here: see its field doc. + self.send_out = None; + self.opening = self.opening.wrapping_add(1); + // 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.pending_op_seq = None; + } + self.account_fingerprint = Some(fingerprint); + self.document_id = document_id; + self.document_title = document_title; + self.document_etag = document_etag; + self.sender = Some(sender); + self.open = true; + self.query.clear(); + self.matches.clear(); + } + + pub fn close(&mut self) { + self.open = false; + } + + /// Field placements the app prepared (page-normalised). Replaces any prior set. + pub fn set_placements(&mut self, placements: Vec) { + self.placements = placements; + // Same reasoning as `add_contact`/`add_email`/removing a recipient: the + // fields a retried create would send have changed, so a key from + // before this call must not be reused for them. + self.draft_idempotency_key = None; + } + + /// What Send asked the application to encode and submit, if anything. + pub fn take_send_request(&mut self) -> Option { + self.send_out.take() + } + + /// Submit a request through the host backend (for example after the app + /// encoded document bytes for a [`SendRequest`], or a status refresh the + /// host drives itself rather than through [`Self::status_panel`]'s own + /// button). + /// + /// Tags the reply with the context [`Self::queue_send`] captured when it + /// built the [`SendRequest`] being submitted, not whatever context is + /// current now. The application can encode bytes, or the dialog can be + /// reopened for another document or account, before this runs; a reply + /// for a [`SendRequest`] built under a now-abandoned context must drop in + /// [`Self::pump`] exactly as one issued under that context would, not + /// install under whichever context happens to be current when this is + /// finally called. + pub fn submit_request(&mut self, request: Request) { + // The captured send context belongs to the create submission answering + // a taken [`SendRequest`], and to nothing else. A status refresh (or + // any other request) submitted while that send is still outstanding is + // the current document's business: tagging it with the old send's + // context would make `pump` drop its reply as stale. + let context = if matches!(request, Request::Create { .. }) { + self.pending_send_context.take().unwrap_or_else(|| self.current_context()) + } else { + self.current_context() + }; + // A public `Request::Status` submission is request-specific routing + // state too: without this, `pump`'s `status_seq` guard never sees + // this sequence and drops the reply that comes back for it. + let is_status = matches!(request, Request::Status { .. }); + let seq = self.submit(request); + self.contexts.insert(seq, context); + self.pending_op_seq = Some(seq); + if is_status { + self.status_seq = seq; + } + } + + /// Completed document bytes after a successful download request. + pub fn take_completed_bytes(&mut self) -> Option> { + self.completed_bytes.take() + } + + /// Tell the dialog create/send finished (or failed) after the app submitted. + /// + /// Gated the same way as [`Self::submit_request`]: when a context was + /// captured for the outstanding send, a result reported after the + /// dialog moved on to another document or account is dropped instead of + /// installing under the new context. + pub fn note_create_result(&mut self, result: Result) { + if let Some(context) = self.pending_send_context.take() + && context != self.current_context() + { + return; + } + self.busy = false; + self.pending_op_seq = None; + match result { + Ok(env) => { + self.envelope = Some(env); + self.error = None; + } + Err(reason) => self.error = Some(reason), + } + } + + fn submit(&mut self, request: Request) -> u64 { + self.seq = self.seq.saturating_add(1); + let seq = self.seq; + self.newest = seq; + if let Some(backend) = self.backend.as_ref() { + backend.submit(request, Replier::new(seq, self.tx.clone())); + } else { + let _ = self.tx.send((seq, Err("no e-sign backend".into()))); + } + seq + } + + /// The context (document revision plus account, plus which opening) a + /// reply must still match to install. See [`EsignContext`]. + fn current_context(&self) -> EsignContext { + EsignContext { + document_id: self.document_id.clone(), + document_etag: self.document_etag.clone(), + account: self.account_fingerprint.clone(), + opening: self.opening, + } + } + + /// 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 + } + + /// Remembers that `seq`'s context has already been consulted once in + /// [`Self::pump`], bounded to the most recently consulted sequences. A + /// backend that answers the same sequence twice (only possible through + /// [`Replier::dup`]) has its second answer dropped unconditionally, + /// instead of reaching the match arms with no context left to check. + fn remember_consumed(&mut self, seq: u64) { + const TRACKED: usize = 64; + if self.consumed_order.len() >= TRACKED + && let Some(oldest) = self.consumed_order.pop_front() + { + self.consumed.remove(&oldest); + } + self.consumed_order.push_back(seq); + self.consumed.insert(seq); + } + + fn pump(&mut self, now: f64) { + while let Ok((seq, result)) = self.rx.try_recv() { + let is_caps_reply = self.caps_seq == Some(seq); + if is_caps_reply { + self.caps_seq = None; + } + if self.consumed.contains(&seq) { + continue; + } + // A context-tagged reply installs only for the context that + // issued it; it drops silently for any other, including a + // document switch, a revision change 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) { + self.remember_consumed(seq); + if context != self.current_context() { + continue; + } + } + match result { + // Guarded by `is_caps_reply`, computed before the swap + // above cleared it: a reply from a backend `set_backend` + // already replaced carries a sequence that is not (or no + // longer) `caps_seq`, so it cannot overwrite capabilities, + // responsible or linked for the new backend. + Ok(Answer::Capabilities { capabilities, responsible_party, linked }) if is_caps_reply => { + self.capabilities = Some(capabilities); + self.responsible = Some(responsible_party); + self.linked = linked; + } + Ok(Answer::Lookup(contacts)) if seq == self.lookup_seq => { + self.matches = contacts; + self.looking = false; + } + Ok(Answer::Created(env)) => { + self.busy = false; + self.pending_op_seq = None; + self.envelope = Some(env); + self.error = None; + } + // Guarded by `status_seq`, the most recently issued status + // request: two "Refresh status" clicks in flight at once can + // answer out of order, and the older one must not overwrite + // state a newer one already installed. + Ok(Answer::Status(env)) if seq == self.status_seq => { + self.busy = false; + self.pending_op_seq = None; + self.envelope = Some(env); + self.error = None; + } + Ok(Answer::Completed(doc)) => { + self.busy = false; + self.pending_op_seq = None; + self.completed_bytes = Some(doc.bytes); + self.error = None; + } + Ok(Answer::Voided { .. }) => { + self.busy = false; + self.pending_op_seq = None; + if let Some(env) = self.envelope.as_mut() { + env.status = EnvelopeStatus::Voided; + } + } + Ok(Answer::Reminded { .. }) => { + self.busy = false; + self.pending_op_seq = None; + } + // Clears `busy` only when this failure belongs to the + // operation that currently owns it: a lookup failing (or a + // superseded status request failing) must not wrongly + // report a still-running create as finished. + Err(reason) => { + if self.pending_op_seq == Some(seq) { + self.busy = false; + self.pending_op_seq = None; + } + self.looking = false; + self.error = Some(reason); + } + _ => {} + } + } + + if self.backend.is_some() && self.caps_seq.is_none() { + let first = self.capabilities.is_none() && self.asked_caps_at.is_none(); + let retry = self.asked_caps_at.is_some_and(|asked| !self.available() && now - asked >= RETRY); + if first || retry { + self.asked_caps_at = Some(now); + self.caps_seq = Some(self.submit(Request::Capabilities)); + } + } + } + + fn maybe_lookup(&mut self, now: f64) { + if !self.open || self.query.len() < MIN_QUERY { + return; + } + if (now - self.query_changed_at) < DEBOUNCE.as_secs_f64() { + return; + } + if self.looking || self.last_lookup_query == self.query { + return; + } + self.looking = true; + self.last_lookup_query = self.query.clone(); + self.lookup_seq = self.submit_in_context(Request::Lookup { query: self.query.clone(), limit: MATCHES }); + } + + fn add_contact(&mut self, contact: Contact) { + // `Contact::id` is the provider's share identifier, decided by + // `target`, and is not promised to be an address: `craft_cloud` + // documents the two as distinct and warns against treating one as + // the other. Falling back to it here would hand the envelope create + // request a recipient email that is not an email. + let Some(email) = contact.email.clone() else { + self.error = Some(self.labels.contact_missing_email.clone()); + return; + }; + if self.recipients.iter().any(|r| r.email.eq_ignore_ascii_case(&email)) { + return; + } + let role = self.next_role(); + self.recipients.push(Recipient { id: contact.id, name: contact.name, email, role, required: true, status: RecipientStatus::Pending }); + self.draft_idempotency_key = None; + self.query.clear(); + self.matches.clear(); + } + + fn add_email(&mut self, email: String) { + let email = email.trim().to_string(); + if email.is_empty() || !email.contains('@') { + return; + } + if self.recipients.iter().any(|r| r.email.eq_ignore_ascii_case(&email)) { + return; + } + let role = self.next_role(); + self.recipients.push(Recipient { id: email.clone(), name: email.clone(), email, role, required: true, status: RecipientStatus::Pending }); + self.draft_idempotency_key = None; + self.query.clear(); + self.matches.clear(); + } + + /// A role label no recipient added for the document currently open has + /// held, including one since removed: see `next_role_number`'s doc. + fn next_role(&mut self) -> String { + self.next_role_number += 1; + format!("Signer {}", self.next_role_number) + } + + fn queue_send(&mut self) { + let Some(sender) = self.sender.clone() else { + self.error = Some(self.labels.sign_in_first.clone()); + return; + }; + if self.recipients.is_empty() { + self.error = Some(self.labels.need_recipient.clone()); + return; + } + if !self.linked { + self.error = Some(self.labels.sign_in_first.clone()); + return; + } + let draft = EnvelopeDraft { + title: if self.document_title.is_empty() { "Document".into() } else { self.document_title.clone() }, + message: if self.message.trim().is_empty() { None } else { Some(self.message.clone()) }, + sender, + document_id: if self.document_id.is_empty() { None } else { Some(self.document_id.clone()) }, + document_etag: self.document_etag.clone(), + recipients: self.recipients.clone(), + placements: self.placements.clone(), + expires: None, + }; + if self.draft_idempotency_key.is_none() { + self.draft_idempotency_key = Some(format!("esign-{}-{}", self.document_id, fresh_send_id())); + } + let idempotency_key = self.draft_idempotency_key.clone().unwrap_or_default(); + self.busy = true; + self.error = None; + self.send_out = Some(SendRequest { draft, idempotency_key }); + self.pending_send_context = Some(self.current_context()); + } + + /// Draw the dialog when open. Call every frame (even when closed) so + /// capability probes and inbox pumping continue. + pub fn show(&mut self, ctx: &Context) { + let now = ctx.input(|i| i.time); + self.pump(now); + if self.open { + self.maybe_lookup(now); + } + if !self.open { + return; + } + + let mut open = self.open; + let labels = self.labels.clone(); + egui::Window::new(&labels.title).open(&mut open).resizable(true).default_width(420.0).show(ctx, |ui| { + self.ui(ui); + }); + // `open` reflects only the window's own title-bar close control; + // `self.ui` may already have set `self.open` to false from one of + // its own Close buttons. Either closing the dialog must stick, so + // reopening it takes a fresh `Self::open` call either way. + self.open = still_open(open, self.open); + } + + fn ui(&mut self, ui: &mut Ui) { + if let Some(err) = &self.error { + ui.colored_label(ui.visuals().error_fg_color, err); + ui.add_space(4.0); + } + + if !self.available() { + ui.label(if self.capabilities.is_none() { self.labels.loading.as_str() } else { self.labels.no_service.as_str() }); + return; + } + + if let Some(party) = &self.responsible { + ui.label(RichText::new(self.labels.responsible.replace("{party}", party)).small()); + ui.add_space(6.0); + } + + if let Some(env) = self.envelope.clone() { + self.status_panel(ui, &env); + return; + } + + if !self.linked { + // Send is disabled below without saying why; the compose form is + // the one place an unlinked user sees before reaching it. + ui.label(&self.labels.sign_in_first); + ui.add_space(4.0); + } + + ui.label(RichText::new(&self.document_title).strong()); + ui.add_space(4.0); + + ui.label(&self.labels.recipients); + let response = ui.add(egui::TextEdit::singleline(&mut self.query).hint_text(&self.labels.recipient_hint)); + if response.changed() { + self.query_changed_at = ui.input(|i| i.time); + self.matches.clear(); + self.looking = false; + self.lookup_seq = 0; + self.last_lookup_query.clear(); + } + if self.looking { + ui.spinner(); + ui.label(&self.labels.searching); + } else if self.query.len() >= MIN_QUERY && self.matches.is_empty() { + ui.horizontal(|ui| { + ui.label(&self.labels.no_matches); + if ui.button(&self.labels.add_address).clicked() { + self.add_email(self.query.clone()); + } + }); + } + for contact in self.matches.clone() { + let label = match &contact.email { + Some(email) => format!("{} <{}>", contact.name, email), + None => contact.name.clone(), + }; + if ui.selectable_label(false, label).clicked() { + self.add_contact(contact); + } + } + + ui.add_space(4.0); + let mut remove: Option = None; + for (i, recipient) in self.recipients.iter().enumerate() { + ui.horizontal(|ui| { + ui.label(format!("{} — {}", recipient.name, recipient.email)); + ui.label(RichText::new(&recipient.role).small()); + if ui.small_button("×").clicked() { + remove = Some(i); + } + }); + } + if let Some(i) = remove { + self.recipients.remove(i); + self.draft_idempotency_key = None; + // A placement keyed to the removed recipient's role would + // otherwise ride along in the next draft matching no recipient. + let live_roles: std::collections::HashSet<&str> = self.recipients.iter().map(|r| r.role.as_str()).collect(); + self.placements.retain(|p| live_roles.contains(p.role.as_str())); + } + + ui.add_space(6.0); + ui.label(&self.labels.message); + let message = ui.add(egui::TextEdit::multiline(&mut self.message).desired_rows(3)); + if message.changed() { + self.draft_idempotency_key = None; + } + + ui.add_space(8.0); + ui.horizontal(|ui| { + let can_send = !self.busy && self.linked && !self.recipients.is_empty(); + if ui.add_enabled(can_send, egui::Button::new(if self.busy { &self.labels.sending } else { &self.labels.send })).clicked() { + self.queue_send(); + } + if ui.button(&self.labels.close).clicked() { + self.open = false; + } + }); + } + + fn status_panel(&mut self, ui: &mut Ui, env: &Envelope) { + ui.label(RichText::new(&env.title).strong()); + ui.label(format!("{}: {:?}", self.labels.status, env.status)); + for r in &env.recipients { + ui.label(format!("{} — {:?} ({})", r.name, r.status, r.role)); + } + ui.add_space(8.0); + ui.horizontal(|ui| { + let caps = self.capabilities.clone().unwrap_or_default(); + if caps.contains(&EsignCapability::Reminders) + && ui.add_enabled(!self.busy, egui::Button::new(&self.labels.remind)).clicked() + && let Some(r) = env.recipients.iter().find(|r| r.status == RecipientStatus::Pending) + { + self.busy = true; + let seq = self.submit_in_context(Request::Remind { envelope: env.id.clone(), recipient: r.id.clone() }); + self.pending_op_seq = Some(seq); + } + 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 seq = self.submit_in_context(Request::Void { envelope: env.id.clone(), reason: "voided by sender".into() }); + self.pending_op_seq = Some(seq); + } + if env.status == EnvelopeStatus::Completed && ui.add_enabled(!self.busy, egui::Button::new(&self.labels.download)).clicked() { + self.busy = true; + let seq = self.submit_in_context(Request::Completed { envelope: env.id.clone() }); + self.pending_op_seq = Some(seq); + } + if ui.button(&self.labels.close).clicked() { + self.open = false; + } + }); + if ui.button(&self.labels.refresh).clicked() { + self.busy = true; + let seq = self.submit_in_context(Request::Status { envelope: env.id.clone() }); + self.pending_op_seq = Some(seq); + self.status_seq = seq; + } + } +} + +/// Split button that opens the request-signatures dialog. +/// +/// `open` is called when the primary action is chosen. The chevron offers +/// status refresh when an envelope id is known. +pub fn request_button(ui: &mut Ui, labels: &EsignLabels, available: bool, menu: &[crate::menu::MenuItem]) -> Option { + if !available { + return None; + } + let menu_labels = crate::menu::MenuLabels::default(); + crate::menu::split(ui, &labels.request, menu, &menu_labels) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{Arc, Mutex}; + + struct Capture { + last: Mutex>, + } + + impl EsignBackend for Arc { + fn submit(&self, request: Request, reply: Replier) { + *self.last.lock().expect("lock") = Some(request); + reply.answer(Answer::Capabilities { + capabilities: vec![EsignCapability::Envelopes, EsignCapability::Void], + responsible_party: "Stub Signing".into(), + linked: true, + }); + } + } + + #[test] + fn available_after_capabilities() { + let capture = Arc::new(Capture { last: Mutex::new(None) }); + let mut dialog = EsignDialog::default(); + dialog.set_backend(capture); + let ctx = Context::default(); + dialog.show(&ctx); + dialog.show(&ctx); + assert!(dialog.available()); + assert_eq!(dialog.responsible.as_deref(), Some("Stub Signing")); + } + + #[test] + fn send_request_needs_recipient_and_sender() { + let mut dialog = EsignDialog { + linked: true, + sender: Some(Identity { id: "u".into(), display: "Ada".into(), email: Some("ada@example.com".into()), avatar: None }), + ..Default::default() + }; + dialog.queue_send(); + assert!(dialog.take_send_request().is_none()); + dialog.add_email("bob@example.com".into()); + dialog.queue_send(); + let req = dialog.take_send_request().expect("send"); + assert_eq!(req.draft.recipients.len(), 1); + assert_eq!(req.draft.recipients[0].email, "bob@example.com"); + } + + /// The texts egui drew, walking into `Shape::Vec` groups the way widgets nest them. Same + /// pattern as `docking::native_tests::texts`. + fn texts(shapes: &[egui::epaint::ClippedShape]) -> Vec { + fn walk(shape: &egui::Shape, out: &mut Vec) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, out)), + egui::Shape::Text(text) => out.push(text.galley.text().to_owned()), + _ => {} + } + } + let mut out = Vec::new(); + shapes.iter().for_each(|clipped| walk(&clipped.shape, &mut out)); + out + } + + #[test] + fn compose_form_shows_sign_in_message_when_not_linked() { + let mut dialog = + EsignDialog { capabilities: Some(vec![EsignCapability::Envelopes]), document_title: "A.pdf".into(), linked: false, ..Default::default() }; + let ctx = Context::default(); + let mut full = ctx.run_ui(egui::RawInput::default(), |ui| dialog.ui(ui)); + full.textures_delta.clear(); + let shown = texts(&full.shapes); + assert!(shown.iter().any(|t| t == &dialog.labels.sign_in_first), "sign-in message not shown for an unlinked account: {shown:?}"); + } + + fn ada() -> Identity { + Identity { id: "u".into(), display: "Ada".into(), email: Some("ada@example.com".into()), avatar: None } + } + + fn placement() -> FieldPlacement { + FieldPlacement { role: "Signer".into(), page: 0, x: 0.1, y: 0.2, w: 0.3, h: 0.05, kind: "signature".into(), required: true } + } + + #[test] + fn add_contact_rejects_a_contact_with_no_email() { + let mut dialog = EsignDialog::default(); + let contact = Contact { + id: "share-id-123".into(), + target: craft_cloud::ShareTarget::User("share-id-123".into()), + name: "Mallory".into(), + email: None, + avatar: None, + is_group: false, + }; + dialog.add_contact(contact); + assert!(dialog.recipients.is_empty(), "a contact with no email became a recipient: {:?}", dialog.recipients); + assert_eq!(dialog.error.as_deref(), Some(dialog.labels.contact_missing_email.as_str())); + } + + #[test] + fn set_placements_invalidates_the_idempotency_key() { + let mut dialog = EsignDialog { linked: true, sender: Some(ada()), ..Default::default() }; + dialog.add_email("bob@example.com".into()); + dialog.queue_send(); + let first = dialog.take_send_request().expect("first send").idempotency_key; + + dialog.set_placements(vec![placement()]); + dialog.queue_send(); + let second = dialog.take_send_request().expect("second send").idempotency_key; + + assert_ne!(first, second, "changing placements kept the old idempotency key: {first}"); + } + + #[test] + fn placements_do_not_survive_a_document_change() { + let mut dialog = EsignDialog::default(); + dialog.open("doc-A".into(), "A.pdf".into(), None, ada()); + dialog.set_placements(vec![placement()]); + + dialog.open("doc-B".into(), "B.pdf".into(), None, ada()); + + assert!(dialog.placements.is_empty(), "doc-B inherited doc-A's placements: {:?}", dialog.placements); + } + + #[test] + fn queue_send_keys_are_unique_across_dialog_instances() { + fn send_key(doc: &str) -> String { + let mut dialog = EsignDialog { linked: true, sender: Some(ada()), document_id: doc.into(), ..Default::default() }; + dialog.add_email("bob@example.com".into()); + dialog.queue_send(); + dialog.take_send_request().expect("send").idempotency_key + } + let a = send_key("doc-A"); + let b = send_key("doc-A"); + assert_ne!(a, b, "two fresh dialog instances for the same document produced the same idempotency key: {a}"); + } + + #[test] + fn recipient_roles_never_repeat_after_a_removal() { + let mut dialog = EsignDialog::default(); + dialog.add_email("a@example.com".into()); + dialog.add_email("b@example.com".into()); + dialog.recipients.remove(0); + dialog.add_email("c@example.com".into()); + + let roles: Vec<&str> = dialog.recipients.iter().map(|r| r.role.as_str()).collect(); + assert_eq!(roles.len(), 2, "{roles:?}"); + assert_ne!(roles[0], roles[1], "B and C were both assigned the same role after A was removed: {roles:?}"); + } + + #[test] + fn still_open_requires_both_the_window_and_the_dialog_to_agree() { + // A Close button inside `ui` already set `self.open` to false; the + // window's own close control was not used. + assert!(!still_open(true, false), "an internal Close click was undone by the window's unchanged open binding"); + // The title-bar close control was used; nothing inside set it false. + assert!(!still_open(false, true)); + // Neither closed it. + assert!(still_open(true, true)); + } + + fn envelope_stub() -> Envelope { + Envelope { + id: "env-1".into(), + title: "Contract".into(), + message: None, + sender: ada(), + document_id: None, + document_etag: None, + content_sha256: String::new(), + recipients: Vec::new(), + placements: Vec::new(), + status: EnvelopeStatus::Sent, + expires: None, + created: None, + completed_at: None, + } + } + + #[test] + fn refresh_status_caption_is_localized() { + let labels = EsignLabels { refresh: "Actualizar estado".into(), ..EsignLabels::default() }; + let mut dialog = + EsignDialog { capabilities: Some(vec![EsignCapability::Envelopes]), labels, envelope: Some(envelope_stub()), ..Default::default() }; + let ctx = Context::default(); + let mut full = ctx.run_ui(egui::RawInput::default(), |ui| dialog.ui(ui)); + full.textures_delta.clear(); + let shown = texts(&full.shapes); + assert!(shown.iter().any(|t| t == "Actualizar estado"), "refresh caption is not localized: {shown:?}"); + assert!(!shown.iter().any(|t| t == "Refresh status"), "hardcoded English caption still shown: {shown:?}"); + } +} diff --git a/crates/ui/src/esign/review_repro.rs b/crates/ui/src/esign/review_repro.rs new file mode 100644 index 000000000..c9780d7e5 --- /dev/null +++ b/crates/ui/src/esign/review_repro.rs @@ -0,0 +1,153 @@ +//! 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::*; + +/// Reused by `coderabbit_repro`, the regression tests for the CodeRabbit +/// findings reviewed on the same pull request. +#[derive(Clone, Default)] +pub(super) 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`. + pub(super) 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) + } +} + +pub(super) fn who(id: &str) -> Identity { + Identity { id: id.into(), display: id.into(), email: Some(format!("{id}@example.com")), avatar: None } +} + +pub(super) 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. +pub(super) 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. +pub(super) 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()) + ); +} diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs index 0c6d42740..a1c091ff1 100644 --- a/crates/ui/src/lib.rs +++ b/crates/ui/src/lib.rs @@ -15,6 +15,8 @@ pub mod cloud; pub mod combo; pub mod direction; pub mod docking; +#[cfg(feature = "esign")] +pub mod esign; mod focus; pub mod fonts; pub mod icons;