Merge pull request #661 from wdunn001/craft-esign-upstream

craft-esign: e-sign contracts and the request-signatures dialog
This commit is contained in:
FredApps authored and GitHub committed 2026-11-18 16:19:16 +07:00
commit 01ffc9fbc7
13 files changed
+2212 -2

No files matched your search

Generated
+11
View File
@@ -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",
+1
View File
@@ -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" }
+19
View File
@@ -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 }
+63
View File
@@ -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<String>) -> Error {
Error::Malformed { what, detail: detail.into() }
}
pub fn invalid(what: &'static str, detail: impl Into<String>) -> 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<T> = std::result::Result<T, Error>;
+318
View File
@@ -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<Envelope>;
/// Send invitations and move the envelope to [`EnvelopeStatus::Sent`].
fn send(&self, envelope: &str) -> Result<Envelope>;
/// Current status, including per-recipient progress.
fn status(&self, envelope: &str) -> Result<Envelope>;
/// 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<CompletedDocument>;
/// 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<String> {
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<Vec<EnvelopeEvent>>;
}
/// 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<EsignCapability>;
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<Envelope> {
Err(Error::Unsupported("create"))
}
fn send(&self, _: &str) -> Result<Envelope> {
Err(Error::Unsupported("send"))
}
fn status(&self, _: &str) -> Result<Envelope> {
Err(Error::Unsupported("status"))
}
fn completed(&self, _: &str) -> Result<CompletedDocument> {
Err(Error::Unsupported("completed"))
}
}
impl EventIntake for RefuseAll {
fn verify_event(&self, _: &[(String, String)], _: &[u8]) -> Result<Vec<EnvelopeEvent>> {
Err(Error::Unsupported("webhooks"))
}
}
impl SigningService for RefuseAll {
fn id(&self) -> &str {
"refuse"
}
fn capabilities(&self) -> Vec<EsignCapability> {
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<Option<Vec<u8>>>,
}
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<Envelope> {
*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<Envelope> {
self.status(envelope)
}
fn status(&self, envelope: &str) -> Result<Envelope> {
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<CompletedDocument> {
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);
}
}
+186
View File
@@ -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<String>,
/// 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<String>,
pub document_etag: Option<String>,
pub recipients: Vec<Recipient>,
pub placements: Vec<FieldPlacement>,
/// `YYYY-MM-DD`. After this the envelope expires if still open.
pub expires: Option<String>,
}
/// 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<String>,
pub sender: Identity,
pub document_id: Option<String>,
pub document_etag: Option<String>,
/// SHA-256 of the document bytes at create time, lowercase hex.
pub content_sha256: String,
pub recipients: Vec<Recipient>,
pub placements: Vec<FieldPlacement>,
pub status: EnvelopeStatus,
pub expires: Option<String>,
/// RFC 3339.
pub created: Option<String>,
/// RFC 3339 when status became [`EnvelopeStatus::Completed`].
pub completed_at: Option<String>,
}
/// 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<u8>,
/// 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<u8>,
}
/// 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<String>,
/// RFC 3339.
pub at: Option<String>,
pub detail: Option<String>,
}
+6 -2
View File
@@ -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.
+92
View File
@@ -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<EnvelopeDraft>, document: Vec<u8>, 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<EsignCapability>,
responsible_party: String,
/// Whether a cloud account is attached so invitations can leave.
linked: bool,
},
Lookup(Vec<Contact>),
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<Answer, String>)>,
}
impl Replier {
pub(crate) fn new(seq: u64, tx: std::sync::mpsc::Sender<(u64, Result<Answer, String>)>) -> 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<String>) {
self.deliver(Err(reason.into()));
}
fn deliver(self, result: Result<Answer, String>) {
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);
}
+216
View File
@@ -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");
}
@@ -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"
);
}
File diff suppressed because it is too large. Load diff
+153
View File
@@ -0,0 +1,153 @@
//! Regression tests for the three gate items skylartaylor raised on PR #661,
//! reproduced against 0a937ef (storytold/craft-libs#661):
//! <https://gist.github.com/skylartaylor/c1108ecf20d63c5e3183947408ddab7a>.
//!
//! `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<Mutex<Vec<(Request, Replier)>>>);
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())
);
}
+2
View File
@@ -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;