Merge pull request #622 from thorstenhirsch/feat/sign-ca-checks-and-trust-sets

M9: opt-in trust lists (a file of CA certificates, such as the EU Trusted Lists)
This commit is contained in:
FredApps
2026-12-02 06:31:41 +01:00
committed by GitHub
19 changed files with 577 additions and 92 deletions
+42 -4
View File
@@ -2,6 +2,8 @@
//! document, and manage trusted certificates. Rectangles are points from the top-left of the
//! displayed page.
use std::io::Read;
use pdfcraft_engine::js::SignEvent;
use pdfcraft_engine::sign::{self, Certificate, DigitalId, Modification, Name, PrivateKey};
use pdfcraft_engine::{SignOptions, SignatureInfo, SignatureStatus};
@@ -9,6 +11,9 @@ use serde_json::{Value, json};
use crate::{Args, Automation, Result, ToolError, failed, write_atomic};
/// The name the EU Trusted List file is loaded under (`sign_trust eu_trusted_list`).
const EU_LIST: &str = "EU Trusted List";
fn bad(m: impl Into<String>) -> ToolError {
ToolError::InvalidArgs(m.into())
}
@@ -377,8 +382,10 @@ impl Automation {
}
pub(crate) fn sign_trust(&mut self, a: &Args) -> Result<Value> {
let mut certs: Vec<Certificate> =
if a.opt_bool("clear")?.unwrap_or(false) { Vec::new() } else { self.session.trusted_certificates().to_vec() };
// Every argument is read and checked first, so a bad one changes nothing, and the changes
// are applied together: the open documents are revalidated once, not once per change.
let clear = a.opt_bool("clear")?.unwrap_or(false);
let mut certs: Vec<Certificate> = if clear { Vec::new() } else { self.session.trusted_certificates().to_vec() };
// Which certificates are already in, by their bytes: a set, so a bundle of many distinct
// certificates isn't compared against every one before it.
let mut known: std::collections::HashSet<Vec<u8>> = certs.iter().map(|c| c.raw.clone()).collect();
@@ -391,6 +398,7 @@ impl Automation {
.map(|p| p.as_str().map(str::to_string).ok_or_else(|| bad("paths must be strings")))
.collect::<Result<_>>()?,
};
let certs_changed = clear || !paths.is_empty();
for p in paths {
let path = self.resolve(&p, false)?;
let bytes = crate::read_input(&path)?;
@@ -407,7 +415,37 @@ impl Automation {
}
}
}
self.session.set_trusted_certificates(certs);
Ok(json!({ "trusted": self.session.trusted_certificates().iter().map(cert_json).collect::<Vec<_>>() }))
// The trust list, off until asked for. `None`: not mentioned, left alone.
let eu_list = match a.get("eu_trusted_list") {
None => None,
Some(Value::Bool(false) | Value::Null) => Some(None),
Some(Value::String(p)) => {
let path = self.resolve(p, false)?;
// One byte more than allowed is read, so an oversize file (or one that grows, or a
// device) is refused by `from_bytes` instead of being read whole.
let mut bytes = Vec::new();
std::fs::File::open(&path)
.and_then(|f| f.take(sign::trust::MAX_LIST_BYTES as u64 + 1).read_to_end(&mut bytes))
.map_err(|e| failed(format!("{}: {e}", path.display())))?;
Some(Some(sign::trust::TrustList::from_bytes(EU_LIST, &bytes).map_err(failed)?))
}
Some(_) => return Err(bad("eu_trusted_list must be the path of a trust list file, or false")),
};
if certs_changed || eu_list.is_some() {
self.session.update_trust(|trust| {
if certs_changed {
trust.certs = certs;
}
match eu_list {
Some(Some(list)) => trust.add_list(list),
Some(None) => trust.remove_list(EU_LIST),
None => {}
}
});
}
Ok(json!({
"trusted": self.session.trusted_certificates().iter().map(cert_json).collect::<Vec<_>>(),
"trust_lists": self.session.trust_lists().iter().map(|l| json!({ "name": l.name, "certificates": l.certs.len() })).collect::<Vec<_>>(),
}))
}
}
+2 -2
View File
@@ -1086,8 +1086,8 @@ pub fn tools() -> Vec<ToolDef> {
}),
&["doc", "id", "out"],
)),
t("sign_trust", "Trust certificates", "Add certificates (.cer/.crt/.pem/.der, a .p7b/.p7c bundle, or the certificates in a .p12 with `password`) to the trusted certificates used to validate signatures, or clear the list (clear: true). Every open document is revalidated. Returns the trusted list.").with(schema(
json!({ "paths": { "type": "array", "items": { "type": "string" } }, "password": { "type": "string" }, "clear": { "type": "boolean" } }),
t("sign_trust", "Trust certificates", "Add certificates (.cer/.crt/.pem/.der, a .p7b/.p7c bundle, or the certificates in a .p12 with `password`) to the trusted certificates used to validate signatures, or clear the list (clear: true). `eu_trusted_list` loads a trust list kept apart from them, off until asked for: the path of a file of CA certificates (DER one after the other, or PEM; the EU Trusted Lists' qualified CAs, say), whose CAs may vouch for signers but never for a time-stamp authority; false removes it. The changes of one call are applied together, or not at all if an argument is bad, and every open document is revalidated once. Returns the trusted list and the loaded trust lists.").with(schema(
json!({ "paths": { "type": "array", "items": { "type": "string" } }, "password": { "type": "string" }, "clear": { "type": "boolean" }, "eu_trusted_list": { "type": ["string", "boolean"] } }),
&[],
)),
t("comment_mark", "Mark a comment with a checkmark", "Mark or unmark a comment with a checkmark (Acrobat: Mark with checkmark), recorded as a private reply. Undoable.").with(schema(
+53
View File
@@ -9025,6 +9025,59 @@ fn optimizing_discards_an_embedded_search_index_through_tools() {
assert_eq!(piece_info("small.pdf"), ["Illustrator"]);
}
#[test]
fn a_trust_list_is_off_until_loaded_through_sign_trust() {
let dir = workdir("trust_list");
let mut a = auto(&dir);
ok(&mut a, "sign_id_create", json!({ "name": "Ada Lovelace", "country": "GB", "key": "p256", "password": "secret12", "path": "ada.p12" }));
let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
ok(&mut a, "sign_document", json!({ "doc": doc, "id": "ada.p12", "password": "secret12", "out": "signed.pdf" }));
let status = |a: &mut Automation| ok(a, "sign_list", json!({ "doc": doc }))["signatures"][0]["status"].as_str().unwrap().to_string();
assert_eq!(status(&mut a), "unknown", "nothing trusted by default");
// Default: no list.
let t = ok(&mut a, "sign_trust", json!({}));
assert_eq!(t["trust_lists"].as_array().map(Vec::len), Some(0));
// A trust list file (the certificate as DER), loaded by path.
let ada = pdfcraft_engine::sign::pkcs12::open(&std::fs::read(dir.join("ada.p12")).unwrap(), "secret12").unwrap();
std::fs::write(dir.join("list.der"), &ada.certificate.raw).unwrap();
let t = ok(&mut a, "sign_trust", json!({ "eu_trusted_list": "list.der" }));
assert_eq!(t["trust_lists"][0]["name"], "EU Trusted List");
assert_eq!(t["trust_lists"][0]["certificates"], 1);
assert_eq!(t["trusted"].as_array().unwrap().len(), 0, "the list is kept apart from the user's certificates");
assert_eq!(status(&mut a), "valid");
// Bad input is refused and leaves the list as it was.
std::fs::write(dir.join("junk.der"), b"not certificates").unwrap();
assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": "junk.der" })), Err(ToolError::Failed(_))));
assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": "missing.der" })), Err(ToolError::Failed(_))));
// A file over the size limit (sparse, so cheap) is refused without being read whole.
let big = std::fs::File::create(dir.join("big.der")).unwrap();
big.set_len(pdfcraft_engine::sign::trust::MAX_LIST_BYTES as u64 + 1).unwrap();
assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": "big.der" })), Err(ToolError::Failed(_))));
assert!(matches!(a.call("sign_trust", &json!({ "eu_trusted_list": 5 })), Err(ToolError::InvalidArgs(_))));
assert!(a.call("sign_trust", &json!({ "eu_trusted_list": "../outside.der" })).is_err(), "paths stay inside the root");
assert_eq!(status(&mut a), "valid");
// Removing it makes the signer unknown again.
assert_eq!(ok(&mut a, "sign_trust", json!({ "eu_trusted_list": false }))["trust_lists"].as_array().map(Vec::len), Some(0));
assert_eq!(status(&mut a), "unknown");
// One call can change everything at once (and revalidates once).
let t = ok(&mut a, "sign_trust", json!({ "paths": ["ada.p12"], "password": "secret12", "eu_trusted_list": "list.der" }));
assert_eq!((t["trusted"].as_array().map(Vec::len), t["trust_lists"].as_array().map(Vec::len)), (Some(1), Some(1)));
// A bad argument changes nothing, not even what came before it in the same call.
ok(&mut a, "sign_trust", json!({ "clear": true, "eu_trusted_list": false }));
for bad in [
json!({ "paths": ["ada.p12"], "password": "secret12", "eu_trusted_list": "junk.der" }),
json!({ "paths": ["ada.p12"], "password": "secret12", "eu_trusted_list": 5 }),
] {
assert!(a.call("sign_trust", &bad).is_err(), "{bad}");
let t = ok(&mut a, "sign_trust", json!({}));
assert_eq!((t["trusted"].as_array().map(Vec::len), t["trust_lists"].as_array().map(Vec::len)), (Some(0), Some(0)), "{bad}");
}
assert_eq!(status(&mut a), "unknown");
}
#[test]
fn optimizing_through_tools() {
let dir = workdir("optimize");
+5 -1
View File
@@ -37,10 +37,14 @@ pub struct Session {
/// injected time AS local time and zeroes the zone, so injecting only it leaves either the
/// local dates or the UTC ones wrong by the zone's offset.
utc_offset: Option<fn() -> i64>,
/// Certificates trusted for signing (Acrobat: Trusted Certificates).
/// What is trusted for signing: the user's certificates (Acrobat: Trusted Certificates) and the
/// trust lists they loaded.
pub(crate) trust: Arc<TrustStore>,
/// The words signature status layers are drawn with, in the interface language.
pub(crate) captions: Arc<StatusCaptions>,
/// How often every open document's signatures were validated again after a trust change.
#[cfg(test)]
pub(crate) revalidations: usize,
/// Preferences ▸ JavaScript ▸ Enable Acrobat JavaScript, inverted (on by default).
pub(crate) js_off: bool,
/// Preferences ▸ Date format, when not the default (see [`dates`]).
+37 -4
View File
@@ -252,11 +252,44 @@ impl Session {
&self.trust.certs
}
/// Replace the trusted certificates, revalidate every open document's signatures,
/// and rebuild its display copy and renderer to match (working file untouched,
/// generation/dirty unchanged: trust alone is not an edit).
/// Change the trust store, revalidate every open document's signatures, and rebuild its
/// display copy and renderer to match (working file untouched, generation/dirty unchanged:
/// trust alone is not an edit). This happens once, however many changes `change` makes:
/// revalidating runs chain building and signature verification for every signature, against
/// every certificate of every trust list.
pub fn update_trust(&mut self, change: impl FnOnce(&mut TrustStore)) {
let mut trust = (*self.trust).clone();
change(&mut trust);
self.trust = Arc::new(trust);
self.revalidate_signatures();
}
/// Replace the trusted certificates (see [`Session::update_trust`]).
pub fn set_trusted_certificates(&mut self, certs: Vec<pdfcraft_sign::Certificate>) {
self.trust = Arc::new(TrustStore { certs });
self.update_trust(|trust| trust.certs = certs);
}
/// The trust lists the user loaded (e.g. the EU Trusted Lists' qualified CAs), none by default.
/// They are not part of [`Session::trusted_certificates`].
pub fn trust_lists(&self) -> &[pdfcraft_sign::trust::TrustList] {
&self.trust.lists
}
/// Load `list` (replacing a list of the same name) and revalidate every open document.
pub fn add_trust_list(&mut self, list: pdfcraft_sign::trust::TrustList) {
self.update_trust(|trust| trust.add_list(list));
}
/// Remove the trust list called `name` and revalidate every open document.
pub fn remove_trust_list(&mut self, name: &str) {
self.update_trust(|trust| trust.remove_list(name));
}
fn revalidate_signatures(&mut self) {
#[cfg(test)]
{
self.revalidations += 1;
}
for doc in &mut self.docs {
Self::revalidate(doc, self.trust.clone());
}
+25
View File
@@ -5844,6 +5844,31 @@ fn reading_colors_set_and_invalidated() {
assert!(!s.set_reading_colors(DocId(u64::MAX), ReadingColors::WHITE_ON_BLACK));
}
#[test]
fn several_trust_changes_revalidate_the_open_documents_once() {
let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap();
let cert = sign::pkcs12::open(&p12, "test").unwrap().certificate;
let mut s = Session::default();
// Each setter changes one thing and revalidates.
s.set_trusted_certificates(vec![cert.clone()]);
s.set_trusted_certificates(Vec::new());
assert_eq!(s.revalidations, 2);
// One `update_trust` changes any number of things and revalidates once.
let list = sign::trust::TrustList::from_bytes("Test list", &cert.raw).unwrap();
s.update_trust(|trust| {
trust.certs = vec![cert.clone()];
trust.add_list(list.clone());
});
assert_eq!(s.revalidations, 3);
assert_eq!((s.trusted_certificates().len(), s.trust_lists().len()), (1, 1));
// A list loaded again under its name replaces itself; removing it by that name takes it back.
s.add_trust_list(list);
assert_eq!(s.trust_lists().len(), 1);
s.remove_trust_list("Test list");
assert!(s.trust_lists().is_empty());
assert_eq!(s.revalidations, 5);
}
#[test]
fn signing_saving_trusting_and_commenting_afterwards() {
let p12 = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/../sign/tests/data/ec-p256.p12")).unwrap();
+9
View File
@@ -114,6 +114,15 @@ needs a prompt to open is listed and asks at signing (issue #179).
- **Weak algorithms still validate, and say so.** SHA-1 and RIPEMD-160 signatures are common in
documents signed years ago, so they validate (new signatures never use SHA-1), but the signature's
details say that the algorithm is weak and shouldn't be relied on.
- **Trust is the user's decision.** Only the user's own list (`TrustStore::certs`) is trusted by
default. A trust list the user loads from a file (`sign_trust eu_trusted_list`, the EU Trusted
Lists' qualified CAs, say) is kept apart from it (`TrustStore::lists`), off until loaded, and
named in the details when it vouches. Nothing of the kind is embedded. A list vouches for
signers, never for a time-stamp authority: trusted time comes from the user's own certificates.
- **Not Adobe's list.** Adobe's AATL is not used: Adobe-authored data outside the closed list in
AGENTS.md §1.1 needs the owner's explicit approval, and the EU Trusted Lists (and, planned, the
operating system's store) cover the same ground. A signer that chains only to an AATL root stays
"unknown" until the user trusts that root.
- **Validation algorithms:** digests SHA-1, SHA-224/256/384/512, SHA-512/224, SHA-512/256,
SHA3-224/256/384/512 and RIPEMD-160. RSA PKCS #1 v1.5 and RSASSA-PSS (the hash, MGF1 hash and
salt length the signature declares), ECDSA on P-256, P-384, P-521, brainpoolP256r1, P384r1 and
+3 -2
View File
@@ -21,6 +21,7 @@ pub mod pkcs12;
pub mod revocation;
pub mod status_layers;
pub mod timestamp;
pub mod trust;
#[cfg(target_os = "windows")]
pub mod windows;
pub mod x509;
@@ -29,8 +30,8 @@ pub use der::Time;
pub use graphic::Graphic;
pub use keys::{DigestAlg, PrivateKey, PublicKey};
pub use pdf::{
Appearance, AppearanceLabels, Detail, DigestCache, Fill, Modification, SignOptions, SignatureInfo, Status, TrustStore, WORDINGS, Words,
has_signatures, in_english, kind, list as signatures, sign, sign_with_timestamp, timestamp_document, validate,
Appearance, AppearanceLabels, Detail, DigestCache, Fill, Modification, SignOptions, SignatureInfo, Status, TrustSource, TrustStore, WORDINGS,
Words, has_signatures, in_english, kind, list as signatures, sign, sign_with_timestamp, timestamp_document, validate,
};
pub use pkcs12::DigitalId;
pub use status_layers::{StatusCaptions, has_status_layers, show_status_layers, status_rgb};
+1 -1
View File
@@ -40,7 +40,7 @@ pub use listing::{DigestCache, list, list_cached};
pub(crate) use listing::{walk_sig_fields, widget_shown};
pub(crate) use signing::fmt;
pub use signing::{Appearance, AppearanceLabels, SignOptions, display_date, has_signatures, sign, sign_with_timestamp, timestamp_document};
pub use types::{Detail, Fill, Modification, Status, TrustStore, WORDINGS, Words, in_english, kind};
pub use types::{Detail, Fill, Modification, Status, TrustSource, TrustStore, WORDINGS, Words, in_english, kind};
pub(crate) use validate::signature_contents;
pub use validate::validate;
#[cfg(test)]
+45 -3
View File
@@ -1,12 +1,52 @@
use super::Certificate;
/// Certificates the user trusts for signing (Acrobat: Trusted Certificates).
/// Certificates trusted for signing (Acrobat: Trusted Certificates). Only `certs`, the user's own
/// list, is trusted by default; a trust list has to be loaded.
#[derive(Clone, Debug, Default)]
pub struct TrustStore {
pub certs: Vec<Certificate>,
/// Lists of CA certificates the user loaded (e.g. the EU Trusted Lists' qualified CAs). They
/// vouch for signers, never for a time-stamp authority: trusted time comes from `certs` alone.
pub lists: Vec<crate::trust::TrustList>,
}
/// Why a certificate in a chain is trusted.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TrustSource {
/// The user's own list of trusted certificates.
User,
/// The named list the user loaded.
List(String),
}
impl TrustStore {
/// Load `list`, replacing a list of the same name. A list is known by its own name, so
/// [`remove_list`](Self::remove_list) takes back exactly what was loaded.
pub fn add_list(&mut self, list: crate::trust::TrustList) {
self.remove_list(&list.name);
self.lists.push(list);
}
/// Remove the list called `name`, if one is loaded.
pub fn remove_list(&mut self, name: &str) {
self.lists.retain(|l| l.name != name);
}
/// Every certificate that can anchor a signer's chain: the user's, then the loaded lists'.
pub(super) fn anchors(&self) -> impl Iterator<Item = &Certificate> + Clone {
self.certs.iter().chain(self.lists.iter().flat_map(|l| l.certs.iter()))
}
/// What makes `c` trusted to vouch for a signer, if anything. The user's own list wins.
pub fn source_of(&self, c: &Certificate) -> Option<TrustSource> {
if self.trusts(c) {
Some(TrustSource::User)
} else {
self.lists.iter().find(|l| l.certs.iter().any(|t| t.raw == c.raw)).map(|l| TrustSource::List(l.name.clone()))
}
}
/// Whether the user's own list holds `c`. Only that vouches for a time-stamp authority.
pub(super) fn trusts(&self, c: &Certificate) -> bool {
self.certs.iter().any(|t| t.raw == c.raw)
}
@@ -92,8 +132,9 @@ pub enum Fill {
/// A value out of the signature itself — a time, the evidence a revocation came from — written
/// as it stands, the way a certificate's name or date is.
Value(String),
/// Two certificates' own names, for the wording that says one was not used to vouch for the
/// other. They go in the order the wording puts its two holes in, which a language may reverse.
/// Two names, for the wording with two holes: that one certificate was not used to vouch for
/// another, or which trust list vouched through which certificate. They go in the order the
/// wording puts its two holes in, which a language may reverse.
Names(String, String),
}
@@ -199,6 +240,7 @@ pub const WORDINGS: &[&str] = &[
"The certificate of {} was not valid at the time of signing, so it is not used to vouch for {}.",
"The signer's identity is unknown because it has not been included in your list of trusted certificates and none of its parent certificates are trusted certificates.",
"The signer's identity is valid.",
"Its certificate chains to {} in the trust list “{}”.",
"The signature includes an embedded timestamp.",
"Signing time is from the clock on the signer's computer.",
// What the signature's own timestamp token proves, if it carries one.
+9 -5
View File
@@ -1,7 +1,7 @@
use super::changes::classify_changes;
use super::listing::{DigestCache, Field, list, nums, sig_fields, text};
use super::locks::{Locked, locked_fields};
use super::types::{Detail, Fill, Modification, Status, TrustStore, kind};
use super::types::{Detail, Fill, Modification, Status, TrustSource, TrustStore, kind};
use super::{
Certificate, Dict, DigestAlg, Document, HashSet, ObjRef, Object, SignError, SignatureInfo, SignedData, Time, build_chain, build_chain_noted,
};
@@ -337,13 +337,13 @@ fn finish_validation(context: SignatureValidation<'_>, verified: VerifiedSignatu
let SignatureValidation { doc, bytes, trust, info, cache, .. } = context;
let VerifiedSignature { covered, certificate: cert, embedded, cms_time, unverified_time } = verified;
info.signing_time = cms_time.or_else(|| info.date.as_deref().and_then(Time::from_pdf));
let mut pool = embedded.to_vec();
pool.extend(trust.certs.iter().cloned());
// The time the chain is judged at: trusted timestamp, else the signer's claimed time.
let at = info.timestamp_time.or(info.signing_time);
let (chain, refused) = build_chain_noted(&cert, &pool, at);
let (chain, refused) = build_chain_noted(&cert, embedded.iter().chain(trust.anchors()), at);
let chain: Vec<Certificate> = chain.into_iter().cloned().collect();
let trusted = chain.iter().any(|c| trust.trusts(c));
// The first trusted certificate going up the chain, and what makes it trusted.
let anchor = chain.iter().find_map(|c| trust.source_of(c).map(|s| (c.display_name(), s)));
let trusted = anchor.is_some();
info.chain = chain;
info.certificate = Some(cert.clone());
if let Some(why) = refused
@@ -474,6 +474,10 @@ fn finish_validation(context: SignatureValidation<'_>, verified: VerifiedSignatu
}
} else {
info.details.push(Detail::plain("The signer's identity is valid."));
// Which list vouched, when one did: the user's own list is the plain case and says nothing.
if let Some((root, TrustSource::List(list))) = anchor {
info.details.push(Detail::of("Its certificate chains to {} in the trust list “{}”.", Fill::Names(root, list)));
}
if !problems && !revoked {
info.status = Status::Valid;
}
+141
View File
@@ -0,0 +1,141 @@
//! Trust lists: sets of CA certificates the user loads from a file, kept apart from the
//! certificates they trust themselves.
//!
//! Nothing here is trusted unless the user loads it (`TrustStore::lists`): which authorities a PDF
//! reader vouches for is the user's decision, not ours, so no list is embedded in PdfCraft. The
//! first intended source is the EU Trusted Lists' qualified CA services. Chain building
//! ([`crate::x509::build_chain`]) still applies to a list: a certificate in it only vouches for what
//! a chain of CA certificates under it leads to.
//!
//! An entry that is not a CA stays in the list (the national lists file a few OCSP responder and
//! time-stamp certificates under their CA services, so refusing them would refuse the real
//! lists). It can issue nothing in chain building and vouches only for itself, which the signer
//! checks of [`crate::x509::Certificate::signing_problem`] still judge.
//!
//! A list vouches for signers. It never vouches for a time-stamp authority: a CA that is trusted
//! to issue signing certificates is not thereby a source of trusted time, so trusted time still
//! comes only from the user's own certificates.
//!
//! Adobe's AATL is not used in any form: Adobe-authored data outside the closed list in AGENTS.md §1.1
//! needs the owner's explicit approval, and the EU Trusted Lists cover the same ground.
use std::sync::Arc;
use crate::SignError;
use crate::der::Tlv;
use crate::x509::Certificate;
/// Certificates as DER one after the other. A certificate that doesn't parse (a key type PdfCraft
/// doesn't read, say) is skipped. Bytes that aren't a DER element at all, as in a file cut short,
/// are an error, so a damaged list doesn't load as a smaller one without a word.
fn parse_concatenated(mut rest: &[u8]) -> Result<Vec<Certificate>, SignError> {
let mut out = Vec::new();
while !rest.iter().all(u8::is_ascii_whitespace) {
let Ok((t, r)) = Tlv::parse(rest) else {
return Err(SignError::Malformed(format!("the trust list is damaged after {} certificates ({} bytes left)", out.len(), rest.len())));
};
if let Ok(c) = Certificate::parse(t.raw) {
out.push(c);
}
rest = r;
}
Ok(out)
}
/// The most a list file may hold: far above the roughly 1.5 MB of the EU qualified CAs.
pub const MAX_LIST_BYTES: usize = 32 << 20;
/// A named set of trusted CA certificates the user loaded from a file, e.g. "EU Trusted List".
#[derive(Clone, Debug)]
pub struct TrustList {
pub name: String,
pub certs: Arc<Vec<Certificate>>,
}
impl TrustList {
/// A list from a file's bytes: certificates as DER one after the other, or a PEM bundle.
/// Certificates that don't parse are skipped; a file with none, a damaged one, or one over
/// [`MAX_LIST_BYTES`], is an error.
pub fn from_bytes(name: &str, bytes: &[u8]) -> Result<TrustList, SignError> {
if bytes.len() > MAX_LIST_BYTES {
return Err(SignError::Malformed(format!("trust list over {} MiB", MAX_LIST_BYTES >> 20)));
}
let mut certs = if bytes.first() == Some(&0x30) && !crate::x509::is_pem(bytes) {
parse_concatenated(bytes)?
} else {
crate::x509::load_certificates(bytes)?
};
let mut seen = std::collections::HashSet::new();
certs.retain(|c| seen.insert(c.raw.clone()));
if certs.is_empty() {
return Err(SignError::Malformed("no certificates in the trust list".into()));
}
Ok(TrustList { name: name.to_string(), certs: Arc::new(certs) })
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A few self-made certificates to load: the lists are tested without any real CA's data.
fn certificates(n: usize) -> Vec<Vec<u8>> {
(0..n)
.map(|i| {
let key = crate::PrivateKey::generate_p256().unwrap();
let name = crate::x509::Name::build(&format!("List Test {i}"), "", "Trust Tests", "", "US");
let alg = key.preferred_digest();
let sig_alg = key.signature_algorithm(alg);
let tbs = crate::der::seq(&[
&crate::der::uint(&[1 + i as u8]),
&sig_alg,
&name.raw,
&crate::der::seq(&[
&crate::der::Time { year: 2020, month: 1, day: 1, hour: 0, minute: 0, second: 0 }.encode(),
&crate::der::Time { year: 2040, month: 1, day: 1, hour: 0, minute: 0, second: 0 }.encode(),
]),
&name.raw,
&key.public_key().spki(),
]);
let signature = key.sign(alg, &tbs).unwrap();
crate::der::seq(&[&tbs, &sig_alg, &crate::der::bit_string(&signature)])
})
.collect()
}
#[test]
fn a_list_reads_concatenated_der_and_rejects_garbage() {
let certs = certificates(3);
let file = certs.concat();
let list = TrustList::from_bytes("Test list", &file).unwrap();
assert_eq!((list.name.as_str(), list.certs.len()), ("Test list", 3));
// The same as a PEM bundle.
let pem: String = list.certs.iter().map(crate::x509::to_pem).collect();
assert_eq!(TrustList::from_bytes("pem", pem.as_bytes()).unwrap().certs.len(), 3);
assert!(TrustList::from_bytes("none", b"not certificates").is_err());
assert!(TrustList::from_bytes("none", &[]).is_err());
assert!(TrustList::from_bytes("big", &vec![0x30; MAX_LIST_BYTES + 1]).is_err());
// A file cut short is refused, not loaded as the certificates before the cut.
assert!(TrustList::from_bytes("cut", &file[..file.len() - 5]).is_err());
// Whitespace after the last certificate is not damage.
let spaced = [file.as_slice(), b"\n"].concat();
assert_eq!(TrustList::from_bytes("spaced", &spaced).unwrap().certs.len(), 3);
// PEM that follows a note starting with "0" (the first byte DER starts with) is still PEM.
let noted = format!("0 certificates have been revoked in this bundle\n{pem}");
assert_eq!(TrustList::from_bytes("noted", noted.as_bytes()).unwrap().certs.len(), 3);
// A PEM bundle cut short is refused too, wherever the cut falls: in the last block, or
// right after the last complete one.
let blocks: Vec<String> = list.certs.iter().map(crate::x509::to_pem).collect();
let cut_inside = format!("{}{}", blocks[0], &blocks[1][..blocks[1].len() / 2]);
assert!(TrustList::from_bytes("cut pem", cut_inside.as_bytes()).is_err());
let cut_after = format!("{}{}-----BEGIN CERTIFICATE-----\n", blocks[0], blocks[1]);
assert!(TrustList::from_bytes("cut pem", cut_after.as_bytes()).is_err());
// So is a block that begins before the one before it ended.
let head: String = blocks[0].lines().take(2).map(|l| format!("{l}\n")).collect();
let spliced = format!("{head}{}", blocks[1]);
assert!(TrustList::from_bytes("spliced", spliced.as_bytes()).is_err());
// A certificate listed twice, even apart, is one entry.
let repeated = [certs[0].clone(), certs[1].clone(), certs[0].clone()].concat();
assert_eq!(TrustList::from_bytes("dups", &repeated).unwrap().certs.len(), 2);
}
}
+22 -4
View File
@@ -569,7 +569,7 @@ pub fn subject_of(raw: &[u8]) -> Option<Name> {
/// `pathLenConstraint` allows the CA certificates below it, and (when `at` is given) it was valid
/// then. Stops at a self-signed certificate. Certificates embedded in a document are in `pool`
/// too, so an ordinary end-entity certificate must never be accepted as an issuer.
pub fn build_chain<'a>(leaf: &'a Certificate, pool: &'a [Certificate], at: Option<Time>) -> Vec<&'a Certificate> {
pub fn build_chain<'a>(leaf: &'a Certificate, pool: impl IntoIterator<Item = &'a Certificate> + Clone, at: Option<Time>) -> Vec<&'a Certificate> {
build_chain_noted(leaf, pool, at).0
}
@@ -579,7 +579,11 @@ pub fn build_chain<'a>(leaf: &'a Certificate, pool: &'a [Certificate], at: Optio
/// The reason is a whole sentence of ours, listed in [`WORDINGS`](crate::pdf::WORDINGS), with the two
/// certificates' own names put in afterwards, so an interface reading in another language says it in
/// it.
pub fn build_chain_noted<'a>(leaf: &'a Certificate, pool: &'a [Certificate], at: Option<Time>) -> (Vec<&'a Certificate>, Option<Detail>) {
pub fn build_chain_noted<'a>(
leaf: &'a Certificate,
pool: impl IntoIterator<Item = &'a Certificate> + Clone,
at: Option<Time>,
) -> (Vec<&'a Certificate>, Option<Detail>) {
let mut chain = vec![leaf];
let mut refused = None;
while chain.len() < 10 {
@@ -591,7 +595,11 @@ pub fn build_chain_noted<'a>(leaf: &'a Certificate, pool: &'a [Certificate], at:
let below = chain.len() - 1;
let mut found = None;
let mut digest = None;
for c in pool.iter().filter(|c| c.subject.raw == last.issuer.raw && !chain.contains(c) && last.signed_by_cached(&c.public_key, &mut digest)) {
for c in pool
.clone()
.into_iter()
.filter(|c| c.subject.raw == last.issuer.raw && !chain.contains(c) && last.signed_by_cached(&c.public_key, &mut digest))
{
// Each reason is a whole sentence, not a phrase stitched into one: a language puts the
// two names where it needs them.
let why = if !c.may_issue() {
@@ -622,11 +630,17 @@ pub fn build_chain_noted<'a>(leaf: &'a Certificate, pool: &'a [Certificate], at:
(chain, refused)
}
/// Whether `bytes` hold PEM. PEM may start with explanatory text, even text that begins with a
/// "0" (0x30), which is also the first byte of every DER certificate.
pub(crate) fn is_pem(bytes: &[u8]) -> bool {
bytes.windows(10).any(|w| w == b"-----BEGIN")
}
/// Certificates from a file: DER, or PEM with one or more `CERTIFICATE` blocks (`.cer`, `.crt`,
/// `.pem`, Acrobat's `.fdf`-free exports), or a PKCS #7 bundle (`.p7b`, `.p7c`) in DER or as a
/// PEM `PKCS7`/`CMS` block, as Windows, Acrobat and certificate authorities export chains.
pub fn load_certificates(bytes: &[u8]) -> Result<Vec<Certificate>, SignError> {
if bytes.first() == Some(&0x30) {
if bytes.first() == Some(&0x30) && !is_pem(bytes) {
// One DER certificate, else a DER bundle; a file that is neither reports the
// certificate's error, the common case.
return match Certificate::parse(bytes) {
@@ -640,6 +654,10 @@ pub fn load_certificates(bytes: &[u8]) -> Result<Vec<Certificate>, SignError> {
let mut block: Option<(&str, String)> = None;
for line in text.lines().map(str::trim) {
if let Some(label) = line.strip_prefix("-----BEGIN ").and_then(|l| l.strip_suffix("-----")) {
// A block that begins before the open one ended is a file cut short or spliced.
if block.is_some() {
return Err(SignError::Malformed("a PEM block is not closed".into()));
}
block = matches!(label, "CERTIFICATE" | "PKCS7" | "CMS").then(|| (label, String::new()));
} else if let Some(label) = line.strip_prefix("-----END ").and_then(|l| l.strip_suffix("-----")) {
// An END that doesn't close the open block ends nothing.
+114 -1
View File
@@ -189,7 +189,7 @@ fn verdict(leaf: Party, embedded: Vec<Certificate>, anchor: &Certificate) -> (St
let doc = Document::open(Arc::new(fixture())).unwrap();
let opts = SignOptions { page: 0, rect: None, date: "D:20260601120000Z".into(), ..SignOptions::default() };
let signed = pdfcraft_sign::sign(&doc, &id, &opts).unwrap();
let trust = TrustStore { certs: vec![anchor.clone()] };
let trust = TrustStore { certs: vec![anchor.clone()], ..TrustStore::default() };
let s = signatures(&Document::open(Arc::new(signed.clone())).unwrap(), &signed, &trust).into_iter().rfind(|s| s.signed).unwrap();
// The details as they read in English; what an interface says in another language is checked in
// `tests/it/pdf.rs`.
@@ -362,3 +362,116 @@ fn an_issuer_with_an_unprocessed_critical_extension_does_not_vouch() {
let pool = [i.cert.clone(), constrained_root.cert.clone()];
assert_eq!(names(&build_chain(&l.cert, &pool, None)), ["Leaf", "Under Constrained Root", "Name Constrained Root"]);
}
/// Like `verdict`, but with a whole `TrustStore`.
fn verdict_with(leaf: Party, embedded: Vec<Certificate>, trust: &TrustStore) -> (Status, Vec<String>) {
let id = DigitalId { key: leaf.key, certificate: leaf.cert, chain: embedded, friendly_name: None };
let doc = Document::open(Arc::new(fixture())).unwrap();
let opts = SignOptions { page: 0, rect: None, date: "D:20260601120000Z".into(), ..SignOptions::default() };
let signed = pdfcraft_sign::sign(&doc, &id, &opts).unwrap();
let s = signatures(&Document::open(Arc::new(signed.clone())).unwrap(), &signed, trust).into_iter().rfind(|s| s.signed).unwrap();
(s.status, s.details.iter().map(|d| d.message.clone()).collect())
}
#[test]
fn a_trust_list_is_off_by_default_and_named_when_it_vouches() {
use pdfcraft_sign::trust::TrustList;
let r = root();
let i = ca("Issuing CA", &r, None);
let leaf = |cn: &str| end_entity(cn, &i);
let list = TrustList::from_bytes("Test List", &r.cert.raw).unwrap();
// Nothing is trusted unless asked for.
let none = TrustStore::default();
assert!(none.lists.is_empty() && none.certs.is_empty());
let (status, details) = verdict_with(leaf("Signer A"), vec![i.cert.clone()], &none);
assert_eq!(status, Status::Unknown, "{details:?}");
// With the list loaded, the same signature is valid and says which list vouched.
let with_list = TrustStore { lists: vec![list.clone()], ..TrustStore::default() };
let (status, details) = verdict_with(leaf("Signer B"), vec![i.cert.clone()], &with_list);
assert_eq!(status, Status::Valid, "{details:?}");
assert!(details.iter().any(|d| d.contains("Test List")), "{details:?}");
// The user's own list wins over a loaded one that holds the same certificate.
let both = TrustStore { certs: vec![r.cert.clone()], lists: vec![list.clone()] };
assert_eq!(both.source_of(&r.cert), Some(pdfcraft_sign::TrustSource::User));
assert_eq!(with_list.source_of(&r.cert), Some(pdfcraft_sign::TrustSource::List("Test List".into())));
assert_eq!(none.source_of(&r.cert), None);
// A list does not make a subscriber a CA: the forged identity stays unknown.
let subscriber = end_entity("Ordinary Subscriber", &r);
let forged = end_entity("Forged Identity", &subscriber);
let (status, details) = verdict_with(forged, vec![subscriber.cert.clone()], &with_list);
assert_eq!(status, Status::Unknown, "{details:?}");
}
/// A time-stamp authority that answers in-process, with whatever certificate it is given.
struct Stamper {
key: PrivateKey,
cert: Certificate,
time: Time,
}
impl pdfcraft_sign::TimestampAuthority for Stamper {
fn timestamp(&self, request: &[u8]) -> Result<Vec<u8>, pdfcraft_sign::SignError> {
let q = pdfcraft_sign::timestamp::parse_request(request)?;
pdfcraft_sign::timestamp::respond(
pdfcraft_sign::timestamp::TimestampSigner {
key: &self.key,
certificate: &self.cert,
chain: &[],
digest: pdfcraft_sign::DigestAlg::Sha256,
},
pdfcraft_sign::timestamp::TimestampIssuance { query: &q, policy: "1.2.3.4", generation_time: self.time, serial: 7 },
)
}
}
#[test]
fn a_list_vouches_for_a_signer_whose_file_carries_only_its_leaf_and_never_for_a_time_stamp_authority() {
use pdfcraft_sign::trust::TrustList;
// The shape of a CAdES signature under a qualified service (#775): the list holds the issuing
// CA (not a root), the CMS embeds only the leaf, and the time-stamp authority is not the user's.
let r = root();
let i = ca("Issuing CA", &r, None);
let leaf = end_entity("Signer", &i);
// A real time-stamp authority: its certificate is issued for time stamping (RFC 3161 §2.3).
let tsa = issue(
"Some Stamper",
Some(&root()),
FOREVER,
&[basic_constraints(false, None), key_usage(DIGITAL_SIGNATURE), extended_key_usage(&["1.3.6.1.5.5.7.3.8"])],
);
let stamped_at = time(2026);
let stamper = Stamper { key: tsa.key, cert: tsa.cert.clone(), time: stamped_at };
let id = DigitalId { key: leaf.key, certificate: leaf.cert, chain: Vec::new(), friendly_name: None };
let doc = Document::open(Arc::new(fixture())).unwrap();
let opts = SignOptions { page: 0, rect: None, date: "D:20260601120000Z".into(), ..SignOptions::default() };
let signed = pdfcraft_sign::sign_with_timestamp(&doc, &id, &opts, &stamper).unwrap();
let check =
|trust: &TrustStore| signatures(&Document::open(Arc::new(signed.clone())).unwrap(), &signed, trust).into_iter().rfind(|s| s.signed).unwrap();
let said = |s: &pdfcraft_sign::SignatureInfo, what: &str| s.details.iter().any(|d| d.message.contains(what));
// Nothing loaded: unknown.
let s = check(&TrustStore::default());
assert_eq!(s.status, Status::Unknown, "{:?}", s.details);
// The list with the issuing CA completes the chain the file leaves out: valid, and named.
let list = TrustList::from_bytes("Test List", &i.cert.raw).unwrap();
let s = check(&TrustStore { lists: vec![list.clone()], ..TrustStore::default() });
assert_eq!(s.status, Status::Valid, "{:?}", s.details);
assert!(said(&s, "trust list “Test List”"), "{:?}", s.details);
assert!(s.timestamp && s.timestamp_time.is_none(), "{:?}", s.details);
// A list that holds the authority's own certificate does not make its time trusted.
let both = TrustList::from_bytes("Both", &[i.cert.raw.clone(), tsa.cert.raw.clone()].concat()).unwrap();
let s = check(&TrustStore { lists: vec![both], ..TrustStore::default() });
assert_eq!(s.status, Status::Valid, "{:?}", s.details);
assert_eq!(s.timestamp_time, None, "{:?}", s.details);
assert!(said(&s, "unverified timestamp"), "{:?}", s.details);
// The user's own certificate for the authority is their decision, and it does.
let s = check(&TrustStore { certs: vec![tsa.cert.clone()], lists: vec![list] });
assert_eq!((s.status, s.timestamp_time), (Status::Valid, Some(stamped_at)), "{:?}", s.details);
}
+1 -1
View File
@@ -116,7 +116,7 @@ fn byte_range(added: &[u8], alg: pdfcraft_cos::Algorithm) -> [usize; 4] {
#[test]
fn signed_encrypted_documents_cover_their_earlier_revision() {
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
for alg in ALL_ALGORITHMS {
let base = protected(alg, -1);
let doc = open_pw(&base, None);
+62 -58
View File
@@ -108,7 +108,7 @@ fn signing_then_validating_with_and_without_trust() {
assert!(sigs.iter().any(|s| s.field == "Approval" && !s.signed));
// Trusting the signer (or its root) makes it valid.
let anchor = id.chain.first().cloned().unwrap_or_else(|| id.certificate.clone());
let trusted = signatures(&doc, &signed, &TrustStore { certs: vec![anchor] });
let trusted = signatures(&doc, &signed, &TrustStore { certs: vec![anchor], ..TrustStore::default() });
let s = trusted.iter().find(|s| s.signed).unwrap();
assert_eq!(s.status, Status::Valid, "{file}: {:?}", s.details);
assert_eq!(s.chain.len(), if file == "chain.p12" { 2 } else { 1 });
@@ -273,7 +273,7 @@ fn an_indirect_annots_array_is_judged_by_the_annotations_it_gains() {
let annots_ref = |bytes: &[u8]| open(bytes).get(page).as_dict().and_then(|d| d.get(b"Annots").and_then(Object::as_ref));
let annots = annots_ref(&unsigned).unwrap();
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let first = pdfcraft_sign::sign(&open(&unsigned), &id, &opts()).unwrap();
let second = pdfcraft_sign::sign(&open(&first), &id, &SignOptions { rect: Some([20.0, 160.0, 220.0, 210.0]), ..opts() }).unwrap();
assert_eq!(annots_ref(&second), Some(annots), "the signer kept the page's array indirect");
@@ -330,7 +330,7 @@ fn an_indirect_annots_array_is_judged_by_the_annotations_it_gains() {
#[test]
fn removing_a_widget_from_an_inline_annots_array_is_not_a_comment_change() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let page = pdfcraft_cos::ObjRef { num: 3, generation: 0 };
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &opts()).unwrap();
let inline = open(&signed).get(page).as_dict().and_then(|d| d.get(b"Annots").cloned()).unwrap();
@@ -445,7 +445,7 @@ fn change_text(doc: &mut Document) {
#[test]
fn later_changes_are_classified_under_the_signature_permissions() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();
// Approval signature: comments are permitted, rewriting page content is not.
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &opts()).unwrap();
@@ -485,7 +485,7 @@ fn later_changes_are_classified_under_the_signature_permissions() {
/// Certify `fixture` with "no changes allowed" (DocMDP P=1).
fn certified_p1() -> (DigitalId, TrustStore, Vec<u8>) {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify: Some(1), ..opts() }).unwrap();
(id, trust, signed)
}
@@ -565,7 +565,7 @@ fn certification_of(perms: &str) -> pdfcraft_sign::SignatureInfo {
b"<< /Type /Sig /Filter /Adobe.PPKLite /SubFilter /adbe.pkcs7.detached /Reference [<< /Type /SigRef /TransformMethod /DocMDP /TransformParams << /Type /TransformParams /P 1 /V /1.2 >> >>] >>",
b"<< /Type /Sig /Filter /Adobe.PPKLite /SubFilter /adbe.pkcs7.detached >>",
]);
signatures(&open(&bytes), &bytes, &TrustStore { certs: Vec::new() }).into_iter().find(|s| s.field == "Approval").unwrap()
signatures(&open(&bytes), &bytes, &TrustStore::default()).into_iter().find(|s| s.field == "Approval").unwrap()
}
/// Only the signature the catalog's `/Perms /DocMDP` names certifies the document: a DocMDP
@@ -900,14 +900,14 @@ fn signing_with_a_timestamp_embeds_a_verified_rfc3161_token() {
let signed = pdfcraft_sign::sign_with_timestamp(&open(&fixture()), &id, &opts(), &tsa).unwrap();
assert!(signed.starts_with(&fixture()), "still an incremental update");
let anchor = id.chain.first().cloned().unwrap_or_else(|| id.certificate.clone());
let trust = TrustStore { certs: vec![anchor.clone(), tsa.id.certificate.clone()] };
let trust = TrustStore { certs: vec![anchor.clone(), tsa.id.certificate.clone()], ..TrustStore::default() };
let s = signatures(&open(&signed), &signed, &trust).into_iter().find(|s| s.signed).unwrap();
assert_eq!(s.status, Status::Valid, "{:?}", s.details);
assert!(s.timestamp, "{:?}", s.details);
assert_eq!(s.timestamp_time, Some(tsa.time), "the token's generation time, verified over the signature value");
assert!(s.details.iter().any(|d| d.message.contains("trusted time")), "{:?}", s.details);
// A trusted signer with an untrusted TSA: still valid, but the token's time is unverified.
let s = signatures(&open(&signed), &signed, &TrustStore { certs: vec![anchor] }).into_iter().find(|s| s.signed).unwrap();
let s = signatures(&open(&signed), &signed, &TrustStore { certs: vec![anchor], ..TrustStore::default() }).into_iter().find(|s| s.signed).unwrap();
assert_eq!(s.status, Status::Valid, "{:?}", s.details);
assert!(s.timestamp);
assert_eq!(s.timestamp_time, None);
@@ -935,7 +935,7 @@ fn a_document_timestamp_covers_the_file_and_validates() {
let tsa = TestTsa { id: tsa_id(), time: Time { year: 2026, month: 10, day: 6, hour: 12, minute: 0, second: 0 } };
let stamped = pdfcraft_sign::timestamp_document(&open(&fixture()), &tsa, "D:20261006120000Z").unwrap();
assert!(stamped.starts_with(&fixture()), "an incremental update");
let trust_tsa = TrustStore { certs: vec![tsa.id.certificate.clone()] };
let trust_tsa = TrustStore { certs: vec![tsa.id.certificate.clone()], ..TrustStore::default() };
let s = signatures(&open(&stamped), &stamped, &trust_tsa).into_iter().find(|s| s.doc_timestamp).unwrap();
assert!(s.doc_timestamp && s.timestamp);
assert_eq!(s.sub_filter.as_deref(), Some("ETSI.RFC3161"));
@@ -953,7 +953,7 @@ fn a_document_timestamp_covers_the_file_and_validates() {
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &opts()).unwrap();
let both = pdfcraft_sign::timestamp_document(&open(&signed), &tsa, "D:20261006130000Z").unwrap();
let all = signatures(&open(&both), &both, &TrustStore { certs: vec![tsa.id.certificate.clone()] });
let all = signatures(&open(&both), &both, &TrustStore { certs: vec![tsa.id.certificate.clone()], ..TrustStore::default() });
let field = all.iter().find(|s| s.signed && !s.doc_timestamp).unwrap();
let allowed = match &field.modification {
Modification::Allowed(k) => k,
@@ -976,7 +976,7 @@ fn cached_discovery_still_validates_current_timestamp_bytes_ranges_and_trust() {
let bytes = pdfcraft_sign::timestamp_document(&source, &tsa, "D:20261006120000Z").unwrap();
let doc = open(&bytes);
let cache = pdfcraft_sign::DigestCache::default();
let trusted = TrustStore { certs: vec![tsa.id.certificate.clone()] };
let trusted = TrustStore { certs: vec![tsa.id.certificate.clone()], ..TrustStore::default() };
let check = |doc: &Document, bytes: &[u8], trust: &TrustStore| {
let listed = pdfcraft_sign::pdf::list_cached(doc, bytes, trust, &cache);
assert_eq!(listed.len(), 1);
@@ -1008,7 +1008,7 @@ fn cached_discovery_still_validates_current_timestamp_bytes_ranges_and_trust() {
#[test]
fn ltv_writers_may_declare_the_esic_extension_but_not_change_a_signed_one() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();
let ext = |base: &[u8], level: i64| {
let mut esic = pdfcraft_cos::Dict::new();
@@ -1082,7 +1082,7 @@ fn sign_then_ltv_then_timestamp_makes_a_b_lta_file() {
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &opts()).unwrap();
let ltv = dss::embed(&open(&signed), &Evidence { certs: vec![id.certificate.raw.clone()], ocsps: Vec::new(), crls: Vec::new() }).unwrap();
let lta = pdfcraft_sign::timestamp_document(&open(&ltv), &tsa, "D:20261006120000Z").unwrap();
let all = signatures(&open(&lta), &lta, &TrustStore { certs: vec![tsa.id.certificate.clone()] });
let all = signatures(&open(&lta), &lta, &TrustStore { certs: vec![tsa.id.certificate.clone()], ..TrustStore::default() });
assert_eq!(all.iter().filter(|s| s.signed).count(), 2);
let field = all.iter().find(|s| s.signed && !s.doc_timestamp).unwrap();
assert_eq!(field.status, Status::Unknown);
@@ -1106,7 +1106,7 @@ fn what_was_removed_before_signing_is_not_signed() {
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
let tsa = TestTsa { id: tsa_id(), time: Time { year: 2026, month: 10, day: 6, hour: 12, minute: 0, second: 0 } };
let anchor = id.chain.first().cloned().unwrap_or_else(|| id.certificate.clone());
let trust = TrustStore { certs: vec![anchor, tsa.id.certificate.clone()] };
let trust = TrustStore { certs: vec![anchor, tsa.id.certificate.clone()], ..TrustStore::default() };
let text = |s: &str| Object::String(PdfString::literal(s.as_bytes().to_vec()));
let dict = |entries: &[(&str, Object)]| {
let mut d = Dict::new();
@@ -1201,7 +1201,7 @@ fn validates_a_signature_made_by_openssl() {
assert!(s.signing_time.is_some_and(|t| t.year == 2026), "from the CMS signing-time attribute");
assert!(!s.visible);
let rsa = pdfcraft_sign::Certificate::parse(&pkcs12::open(&data("rsa-aes.p12"), "test").unwrap().certificate.raw).unwrap();
let s = signatures(&doc, &bytes, &TrustStore { certs: vec![rsa] }).into_iter().next().unwrap();
let s = signatures(&doc, &bytes, &TrustStore { certs: vec![rsa], ..TrustStore::default() }).into_iter().next().unwrap();
assert_eq!(s.status, Status::Valid, "{:?}", s.details);
// A later comment is allowed for this approval signature.
let edited = edit_after(&bytes, add_comment);
@@ -1270,7 +1270,7 @@ fn signing_with_keychain_identities() {
for id in &ids {
assert!(id.key.is_external());
let signed = pdfcraft_sign::sign(&open(&fixture()), id, &opts()).unwrap();
let trusted = signatures(&open(&signed), &signed, &TrustStore { certs: vec![id.certificate.clone()] });
let trusted = signatures(&open(&signed), &signed, &TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() });
let s = trusted.iter().find(|s| s.signed).unwrap();
assert_eq!(s.status, Status::Valid, "{:?}", s.details);
}
@@ -1420,7 +1420,7 @@ fn xfa_page_swap(doc: &mut Document) {
#[test]
fn a_later_field_with_the_same_name_does_not_inherit_the_signature() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { field: Some("Approval".into()), ..opts() }).unwrap();
let edited = edit_after(&signed, |doc| {
let root = doc.root().unwrap();
@@ -1463,7 +1463,7 @@ fn a_later_field_with_the_same_name_does_not_inherit_the_signature() {
#[test]
fn toggling_needs_rendering_is_a_structure_change() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();
let certified = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify: Some(1), ..opts() }).unwrap();
assert_eq!(check(&certified).status, Status::Valid);
@@ -1479,7 +1479,7 @@ fn toggling_needs_rendering_is_a_structure_change() {
#[test]
fn declaring_a_form_xfa_does_not_excuse_replacing_the_pages() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();
for certify in [None, Some(2), Some(3)] {
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify, ..opts() }).unwrap();
@@ -1515,7 +1515,7 @@ fn rewrite_stream(num: u32, body: &'static [u8]) -> impl FnOnce(&mut Document) {
#[test]
fn rewriting_a_certified_forms_xfa_data_is_a_form_fill() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();
let certified = pdfcraft_sign::sign(&open(&xfa_fixture()), &id, &SignOptions { certify: Some(2), ..opts() }).unwrap();
assert_eq!(check(&certified).status, Status::Valid);
@@ -1580,7 +1580,8 @@ fn validates_signatures_written_with_ber_indefinite_lengths() {
ber.resize((b - a) / 2, 0);
signed[a..b].copy_from_slice(hex(&ber).as_bytes());
let anchor = id.certificate.clone();
let s = signatures(&open(&signed), &signed, &TrustStore { certs: vec![anchor] }).into_iter().find(|s| s.signed).unwrap();
let s =
signatures(&open(&signed), &signed, &TrustStore { certs: vec![anchor], ..TrustStore::default() }).into_iter().find(|s| s.signed).unwrap();
assert_eq!(s.status, Status::Valid, "{file}: {:?}", s.details);
assert!(s.details.iter().any(|d| d.message.contains("BER")), "the tolerance is reported: {:?}", s.details);
// Tampering is still caught: the digest check is not relaxed.
@@ -1637,7 +1638,7 @@ const MESSAGE_DIGEST: &str = "1.2.840.113549.1.9.4";
#[test]
fn signed_attributes_must_bind_the_document() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &opts()).unwrap();
let (a, b) = contents_span(&signed);
let digest = pdfcraft_sign::DigestAlg::Sha256.digest(&[&signed[..a - 1], &signed[b + 1..]]);
@@ -1792,7 +1793,7 @@ const LEVELS: [Option<u8>; 4] = [None, Some(1), Some(2), Some(3)];
/// reasons, while the untouched file stays valid.
fn assert_refused_at_every_level(base: &[u8], kind: &str, attack: impl Fn(&mut Document)) {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();
for certify in LEVELS {
let signed = pdfcraft_sign::sign(&open(base), &id, &SignOptions { certify, ..opts() }).unwrap();
@@ -2008,7 +2009,7 @@ fn the_forms_signed_fields_are_not_dropped_after_signing() {
id: pkcs12::open(&data("rsa-aes.p12"), "test").unwrap(),
time: Time { year: 2026, month: 10, day: 6, hour: 12, minute: 0, second: 0 },
};
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let signed = pdfcraft_sign::sign(&open(&fixture_with_indirect_acroform()), &id, &opts()).unwrap();
let stamped = pdfcraft_sign::timestamp_document(&open(&signed), &tsa, "D:20261006120000Z").unwrap();
let mut failures = Vec::new();
@@ -2098,7 +2099,7 @@ fn the_catalogs_own_xmp_stream_may_still_be_rewritten_after_signing() {
// document's XMP, and rewriting it is allowed at every level.
let base = fixture_with_stream_7("/Metadata 7 0 R", false, "/Type /Metadata /Subtype /XML", b"<x:xmpmeta/>");
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
for certify in LEVELS {
let signed = pdfcraft_sign::sign(&open(&base), &id, &SignOptions { certify, ..opts() }).unwrap();
let edited = edit_after(&signed, |doc| {
@@ -2129,7 +2130,7 @@ fn fixture_with_dss() -> (Vec<u8>, u32, u32) {
#[test]
fn a_signed_store_may_grow_but_not_lose_or_swap_entries() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();
let (base, certs, vri) = fixture_with_dss();
for certify in LEVELS {
@@ -2164,7 +2165,7 @@ fn a_signed_store_may_grow_but_not_lose_or_swap_entries() {
#[test]
fn a_form_xobject_relabelled_metadata_is_not_a_metadata_change() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let signed = pdfcraft_sign::sign(&open(&fixture_with_xobject()), &id, &opts()).unwrap();
let relabel = |doc: &mut Document| {
let mut d = pdfcraft_cos::Dict::new();
@@ -2212,7 +2213,7 @@ fn a_form_xobject_relabelled_as_file_plumbing_is_still_judged() {
// drawn Form XObject rewritten after signing and labelled /ObjStm or /XRef still shows its
// new content (the renderer ignores /Type), so it must not be skipped.
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
for certify in LEVELS {
let signed = pdfcraft_sign::sign(&open(&fixture_with_xobject()), &id, &SignOptions { certify, ..opts() }).unwrap();
for label in ["ObjStm", "XRef"] {
@@ -2290,7 +2291,7 @@ fn a_signed_page_relabelled_or_stripped_of_type_is_still_page_content() {
// Positive control: an ordinary /Info /ModDate bump on the signed revision's own information
// dictionary stays a permitted metadata change.
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
for certify in LEVELS {
let signed = pdfcraft_sign::sign(&open(&fixture_with_info()), &id, &SignOptions { certify, ..opts() }).unwrap();
let bumped = edit_after(&signed, |doc| {
@@ -2331,7 +2332,7 @@ fn a_revoked_certificate_stays_invalid_when_it_was_also_expired_at_signing() {
let crl = self_crl(&id, t(2039), t(2041), t(2039));
let ltv = dss::embed(&open(&signed), &Evidence { certs: Vec::new(), ocsps: Vec::new(), crls: vec![crl] }).unwrap();
let anchor = id.chain.first().cloned().unwrap_or_else(|| id.certificate.clone());
for trust in [TrustStore::default(), TrustStore { certs: vec![anchor] }] {
for trust in [TrustStore::default(), TrustStore { certs: vec![anchor], ..TrustStore::default() }] {
let s = signatures(&open(&ltv), &ltv, &trust).into_iter().find(|s| s.signed && !s.doc_timestamp).unwrap();
assert!(s.details.iter().any(|d| d.message.contains("not valid at the time of signing")), "{:?}", s.details);
assert_eq!(s.status, Status::Invalid, "{:?}", s.details);
@@ -2346,7 +2347,7 @@ fn a_revocation_behind_many_dss_entries_is_not_reported_valid() {
let t = |year| Time { year, month: 1, day: 1, hour: 0, minute: 0, second: 0 };
let crl = self_crl(&id, t(2026), t(2027), Time { year: 2026, month: 6, day: 1, hour: 8, minute: 0, second: 0 });
let anchor = id.chain.first().cloned().unwrap_or_else(|| id.certificate.clone());
let trust = TrustStore { certs: vec![anchor] };
let trust = TrustStore { certs: vec![anchor], ..TrustStore::default() };
// `/CRLs`: the revoking CRL after `benign` other entries; `repeated` lists one stream for all of them.
let status = |benign: usize, repeated: bool| {
let ltv = edit_after(&signed, |doc| {
@@ -2379,14 +2380,17 @@ fn an_untrusted_timestamp_does_not_set_the_validation_time() {
let late = SignOptions { date: "D:20400101120000Z".into(), ..opts() };
let signed = pdfcraft_sign::sign_with_timestamp(&open(&fixture()), &id, &late, &tsa).unwrap();
let anchor = id.chain.first().cloned().unwrap_or_else(|| id.certificate.clone());
let s = signatures(&open(&signed), &signed, &TrustStore { certs: vec![anchor.clone()] }).into_iter().find(|s| s.signed).unwrap();
let s = signatures(&open(&signed), &signed, &TrustStore { certs: vec![anchor.clone()], ..TrustStore::default() })
.into_iter()
.find(|s| s.signed)
.unwrap();
assert_ne!(s.status, Status::Valid, "{:?}", s.details);
assert_eq!(s.timestamp_time, None, "an untrusted token's time is not a trusted time");
assert!(s.details.iter().any(|d| d.message.contains("not valid at the time of signing")), "{:?}", s.details);
assert!(!s.details.iter().any(|d| d.message.contains("trusted time")), "{:?}", s.details);
assert!(s.details.iter().any(|d| d.message.contains("unverified timestamp")), "{:?}", s.details);
// Trusting the TSA makes its time authoritative: the certificate was valid then.
let trust = TrustStore { certs: vec![anchor, tsa.id.certificate.clone()] };
let trust = TrustStore { certs: vec![anchor, tsa.id.certificate.clone()], ..TrustStore::default() };
let s = signatures(&open(&signed), &signed, &trust).into_iter().find(|s| s.signed).unwrap();
assert_eq!(s.timestamp_time, Some(tsa.time));
assert_eq!(s.status, Status::Valid, "{:?}", s.details);
@@ -2513,7 +2517,7 @@ fn signing_with_windows_store_identities() {
assert!(now.status.success());
options.date = format!("D:{}Z", String::from_utf8(now.stdout).unwrap().trim());
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &options).unwrap();
let validated = signatures(&open(&signed), &signed, &TrustStore { certs: vec![id.certificate.clone()] });
let validated = signatures(&open(&signed), &signed, &TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() });
let signature = validated.iter().find(|s| s.signed).unwrap();
assert_eq!(signature.status, Status::Valid, "{:?}", signature.details);
assert_eq!(signature.modification, Modification::None);
@@ -2583,7 +2587,7 @@ fn a_windows_store_identity_signs_with_its_issuers() {
assert!(now.status.success());
options.date = format!("D:{}Z", String::from_utf8(now.stdout).unwrap().trim());
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &options).unwrap();
let validated = signatures(&open(&signed), &signed, &TrustStore { certs: vec![anchor] });
let validated = signatures(&open(&signed), &signed, &TrustStore { certs: vec![anchor], ..TrustStore::default() });
let signature = validated.iter().find(|s| s.signed).unwrap();
assert_eq!(signature.status, Status::Valid, "{:?}", signature.details);
assert_eq!(signature.signer.as_deref(), Some(signer.as_str()));
@@ -2632,7 +2636,7 @@ fn fixture_timestamped_in_a_field(tsa: &TestTsa) -> Vec<u8> {
fn a_document_timestamp_held_by_a_signature_field_is_checked_as_a_timestamp() {
let tsa = TestTsa { id: tsa_id(), time: Time { year: 2026, month: 10, day: 6, hour: 12, minute: 0, second: 0 } };
let stamped = fixture_timestamped_in_a_field(&tsa);
let trust = TrustStore { certs: vec![tsa.id.certificate.clone()] };
let trust = TrustStore { certs: vec![tsa.id.certificate.clone()], ..TrustStore::default() };
let all = signatures(&open(&stamped), &stamped, &trust);
let stamps: Vec<_> = all.iter().filter(|s| s.signed).collect();
assert_eq!(stamps.len(), 1, "listed once, not as field and as standalone: {:?}", all.iter().map(|s| &s.field).collect::<Vec<_>>());
@@ -2665,7 +2669,7 @@ fn a_field_timestamp_from_a_trusted_tsa_outside_its_validity_is_not_valid() {
time: Time { year: 2020, month: 1, day: 1, hour: 0, minute: 0, second: 0 },
};
let stamped = fixture_timestamped_in_a_field(&tsa);
let trust = TrustStore { certs: vec![tsa.id.certificate.clone()] };
let trust = TrustStore { certs: vec![tsa.id.certificate.clone()], ..TrustStore::default() };
let s = signatures(&open(&stamped), &stamped, &trust).into_iter().find(|s| s.signed).unwrap();
assert!(s.doc_timestamp);
assert_eq!(s.status, Status::Unknown, "{:?}", s.details);
@@ -2717,7 +2721,7 @@ fn validates_the_legacy_adbe_x509_rsa_sha1_format() {
let weak = "This signature uses SHA-1, a weak hash algorithm: collisions in it have been demonstrated. It still validates because many documents signed years ago use it, but it should not be relied on.";
assert_eq!(s.details.iter().filter(|d| d.message == weak).count(), 1, "{:?}", s.details);
assert!(s.details.iter().any(|d| d.message.contains("legacy adbe.x509.rsa_sha1 format")), "{:?}", s.details);
let trusted = TrustStore { certs: vec![id.certificate.clone()] };
let trusted = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let s = signatures(&open(&pdf), &pdf, &trusted).into_iter().find(|s| s.signed).unwrap();
assert_eq!(s.status, Status::Valid, "{:?}", s.details);
// One changed byte inside the signed range.
@@ -2757,7 +2761,7 @@ fn protected_with(alg: pdfcraft_cos::Algorithm, user: &str, permissions: i32) ->
fn a_user_password_document_keeps_its_earlier_signature_valid_when_counter_signed() {
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
let id2 = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone(), id2.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone(), id2.certificate.clone()], ..TrustStore::default() };
for alg in ALL_ALGORITHMS {
let base = protected_with(alg, "secret", -1);
assert!(Document::open_with_password(Arc::new(base.clone()), None).is_err(), "{alg:?}: the file asks for its password");
@@ -2796,7 +2800,7 @@ const ALL_ALGORITHMS: [pdfcraft_cos::Algorithm; 4] =
fn encrypted_documents_are_signed_with_an_unencrypted_contents() {
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
let id2 = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone(), id2.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone(), id2.certificate.clone()], ..TrustStore::default() };
for alg in ALL_ALGORITHMS {
let base = protected(alg, -1);
let doc = open_pw(&base, None);
@@ -2843,7 +2847,7 @@ fn encrypted_documents_are_signed_with_an_unencrypted_contents() {
#[test]
fn an_encrypted_documents_signature_graphic_is_encrypted_with_it() {
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
for alg in ALL_ALGORITHMS {
let base = protected(alg, -1);
let signed = pdfcraft_sign::sign(&open_pw(&base, None), &id, &SignOptions { graphic: Some(picture(true)), ..opts() }).unwrap();
@@ -2865,7 +2869,7 @@ fn an_encrypted_documents_signature_graphic_is_encrypted_with_it() {
#[test]
fn encrypted_documents_are_signed_only_as_their_permissions_allow() {
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let base = protected(pdfcraft_cos::Algorithm::Aes256, FILL_AND_SIGN_ONLY);
let user = open_pw(&base, None);
let refused = |r: Result<Vec<u8>, SignError>, what: &str| match r {
@@ -2910,7 +2914,7 @@ fn encrypted_documents_take_a_document_timestamp() {
let base = protected(pdfcraft_cos::Algorithm::Aes128, FILL_AND_SIGN_ONLY);
let stamped = pdfcraft_sign::timestamp_document(&open_pw(&base, None), &tsa, "D:20261006120000Z").unwrap();
assert!(stamped.starts_with(&base));
let s = signatures(&open_pw(&stamped, None), &stamped, &TrustStore { certs: vec![tsa.id.certificate.clone()] })
let s = signatures(&open_pw(&stamped, None), &stamped, &TrustStore { certs: vec![tsa.id.certificate.clone()], ..TrustStore::default() })
.into_iter()
.find(|s| s.doc_timestamp)
.unwrap();
@@ -3020,7 +3024,7 @@ fn visible_appearance_draws_central_european_characters_with_embedded_font() {
assert!(fonts.contains(b"PCFull0"), "appearance should reference the embedded font: {fonts:?}");
// Verify signature validation still passes.
let doc = open(&signed);
let trust = TrustStore { certs: vec![luka_id.certificate.clone()] };
let trust = TrustStore { certs: vec![luka_id.certificate.clone()], ..TrustStore::default() };
let s = signatures(&doc, &signed, &trust).into_iter().find(|s| s.signed).unwrap();
assert_eq!(s.status, Status::Valid);
assert_eq!(s.reason.as_deref(), Some("Podpisano s potrdilom"));
@@ -3177,7 +3181,7 @@ fn xref_entry(offset: usize) -> String {
#[test]
fn a_cross_reference_entry_the_reader_sets_aside_does_not_hide_new_page_content() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
for certify in LEVELS {
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify, ..opts() }).unwrap();
// Where the signed revision keeps the page's content stream.
@@ -3209,7 +3213,7 @@ fn a_cross_reference_entry_the_reader_sets_aside_does_not_hide_new_page_content(
#[test]
fn a_cross_reference_entry_that_misses_its_object_is_not_an_unchanged_object() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &opts()).unwrap();
// A copy of the signed content, named by an entry two bytes into its `4 0 obj` header.
let edited = append_content_revision(&signed, "Contract text", |new| format!("4 1\n{}", xref_entry(new + 2)));
@@ -3256,7 +3260,7 @@ fn append_revision(signed: &[u8], bodies: &[&str], trailer_extra: &str, xref: im
#[test]
fn an_unlisted_object_body_or_an_entry_that_points_at_no_object_is_not_permitted() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let text = "BT /F1 14 Tf 20 250 Td (Forged text) Tj ET";
let forged = format!("4 0 obj\n<< /Length {} >>\nstream\n{text}\nendstream\nendobj\n", text.len());
let unused = "60 0 obj\n(unused)\nendobj\n";
@@ -3371,7 +3375,7 @@ fn append_signature_with_unlisted_xref_stream(signed: &[u8], xref_num: u32, anno
#[test]
fn a_cross_reference_stream_without_a_row_for_itself_is_no_unlisted_body() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
for certify in [Some(2), None] {
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify, ..opts() }).unwrap();
let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.field == "Signature1").unwrap();
@@ -3506,7 +3510,7 @@ fn rewritten_page_resources_are_page_content_whatever_keys_they_carry() {
// content draws, so it is not page content (it is still an unclassified change, refused as
// "other", as before).
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let signed = pdfcraft_sign::sign(&open(&fixture_with_indirect_resources()), &id, &SignOptions { certify: Some(3), ..opts() }).unwrap();
let grown = edit_after(&signed, |doc| {
let f = courier(doc);
@@ -3534,7 +3538,7 @@ fn switching_the_trailer_to_another_signed_catalog_is_not_permitted() {
],
);
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let signed = pdfcraft_sign::sign(&open(&base), &id, &SignOptions { field: Some("Approval".into()), rect: None, ..opts() }).unwrap();
let s = signatures(&open(&signed), &signed, &trust).into_iter().find(|s| s.signed).unwrap();
assert_eq!(s.status, Status::Valid, "{:?}", s.details);
@@ -3551,13 +3555,13 @@ fn switching_the_trailer_to_another_signed_catalog_is_not_permitted() {
fn a_timestamp_from_a_certificate_not_issued_for_time_stamping_is_not_trusted_time() {
let tsa = TestTsa { id: tsa_id_with(&["1.3.6.1.5.5.7.3.4"]), time: Time { year: 2026, month: 10, day: 6, hour: 12, minute: 0, second: 0 } };
let stamped = pdfcraft_sign::timestamp_document(&open(&fixture()), &tsa, "D:20261006120000Z").unwrap();
let trust = TrustStore { certs: vec![tsa.id.certificate.clone()] };
let trust = TrustStore { certs: vec![tsa.id.certificate.clone()], ..TrustStore::default() };
let s = signatures(&open(&stamped), &stamped, &trust).into_iter().find(|s| s.doc_timestamp).unwrap();
assert_eq!(s.status, Status::Unknown, "{:?}", s.details);
assert!(s.details.iter().any(|d| d.message.contains("not issued for time stamping")), "{:?}", s.details);
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
let signed = pdfcraft_sign::sign_with_timestamp(&open(&fixture()), &id, &opts(), &tsa).unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone(), tsa.id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone(), tsa.id.certificate.clone()], ..TrustStore::default() };
let s = signatures(&open(&signed), &signed, &trust).into_iter().find(|s| s.signed).unwrap();
assert!(s.timestamp);
assert_eq!(s.timestamp_time, None, "{:?}", s.details);
@@ -3570,7 +3574,7 @@ fn a_timestamp_from_a_certificate_not_issued_for_time_stamping_is_not_trusted_ti
#[test]
fn freeing_a_signed_object_or_rewriting_the_signed_widget_is_a_page_content_change() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let check = |bytes: &[u8]| signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &opts()).unwrap();
let freed = check(&edit_after(&signed, |doc| doc.free(pdfcraft_cos::ObjRef { num: 5, generation: 0 })));
@@ -3595,7 +3599,7 @@ fn freeing_a_signed_object_or_rewriting_the_signed_widget_is_a_page_content_chan
#[test]
fn signing_a_field_with_a_null_value_after_another_signature_keeps_the_first_valid() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let first = pdfcraft_sign::sign(&open(&fixture()), &id, &opts()).unwrap();
let second = pdfcraft_sign::sign(&open(&first), &id, &SignOptions { field: Some("Approval".into()), ..opts() }).unwrap();
let all = signatures(&open(&second), &second, &trust);
@@ -3681,7 +3685,7 @@ fn signed_catalog_and_page_tree_keep_their_role_when_relabelled_or_dropped() {
#[test]
fn signed_signature_objects_and_byte_ranges_are_read_from_the_signed_revision() {
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify: Some(1), ..opts() }).unwrap();
let sig_ref = open(&signed)
.object_numbers()
@@ -3738,7 +3742,7 @@ fn signed_signature_objects_and_byte_ranges_are_read_from_the_signed_revision()
fn certify_level_one_forbids_adding_signature_fields_or_counter_signing() {
let id = pkcs12::open(&data("ec-p256.p12"), "test").unwrap();
let tsa = TestTsa { id: tsa_id(), time: Time { year: 2026, month: 10, day: 6, hour: 12, minute: 0, second: 0 } };
let trust = TrustStore { certs: vec![id.certificate.clone(), tsa.id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone(), tsa.id.certificate.clone()], ..TrustStore::default() };
let certified_p1 = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify: Some(1), ..opts() }).unwrap();
let counter_p1 = pdfcraft_sign::sign(&open(&certified_p1), &id, &SignOptions { field: Some("Approval".into()), ..opts() }).unwrap();
let first_p1 = signatures(&open(&counter_p1), &counter_p1, &trust).into_iter().find(|s| s.field == "Signature1").unwrap();
@@ -3779,7 +3783,7 @@ fn certify_level_one_forbids_adding_signature_fields_or_counter_signing() {
#[test]
fn fields_sharing_a_signature_value_are_listed_with_one_verdict() {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let signed = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { field: Some("Approval".into()), ..opts() }).unwrap();
let v = open(&signed).get(pdfcraft_cos::ObjRef { num: 6, generation: 0 }).as_dict().and_then(|d| d.get(b"V").cloned()).unwrap();
let shared = edit_after(&signed, |doc| {
@@ -3811,7 +3815,7 @@ fn the_catalogs_perms_do_not_change_under_no_changes() {
// /Perms names the certification signature (DocMDP). Under P=1 nothing may change, so a later
// revision that drops it, or points it elsewhere, breaks the certification.
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let certified = pdfcraft_sign::sign(&open(&fixture()), &id, &SignOptions { certify: Some(1), ..opts() }).unwrap();
let elsewhere = dict_of(vec![("DocMDP", oref(5))]);
for (how, perms) in [("dropped", None), ("pointed elsewhere", Some(Object::Dict(elsewhere)))] {
@@ -78,7 +78,7 @@ fn opts(certify: u8) -> SignOptions {
/// The certification signature of `bytes`, which must be refused.
fn assert_refused(bytes: &[u8]) {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let s = signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed).unwrap();
assert!(matches!(s.modification, Modification::Disallowed(_)) && s.status != Status::Valid, "main returns {:?}, {:?}", s.status, s.modification);
}
+1 -1
View File
@@ -69,7 +69,7 @@ fn edit_after(signed: &[u8], f: impl FnOnce(&mut Document)) -> Vec<u8> {
/// The certification signature of `bytes`: its status and modification verdict.
fn verdict(bytes: &[u8]) -> (Status, Modification) {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let trust = TrustStore { certs: vec![id.certificate.clone()] };
let trust = TrustStore { certs: vec![id.certificate.clone()], ..TrustStore::default() };
let s = signatures(&open(bytes), bytes, &trust).into_iter().find(|s| s.signed && s.certify.is_some()).unwrap();
(s.status, s.modification)
}
+4 -4
View File
@@ -6526,11 +6526,11 @@ title = "EU Trusted Lists"
area = "H"
tier = "P2"
milestone = "M9"
status = "planned"
status = "partial"
commands = []
tools = []
evidence = []
notes = ""
tools = ["sign_trust"]
evidence = ["crates/sign/src/trust.rs::a_list_reads_concatenated_der_and_rejects_garbage", "crates/sign/tests/it/chain.rs::a_trust_list_is_off_by_default_and_named_when_it_vouches", "crates/sign/tests/it/chain.rs::a_list_vouches_for_a_signer_whose_file_carries_only_its_leaf_and_never_for_a_time_stamp_authority", "crates/automation/tests/it/automation.rs::a_trust_list_is_off_until_loaded_through_sign_trust"]
notes = "A trust list is a file of CA certificates (DER one after the other, or PEM) that the user loads with sign_trust eu_trusted_list: nothing is embedded, it is off until loaded and kept apart from the user's own certificates, a damaged file is refused, and the details name the list that vouched. Chains through it still need CA certificates all the way (basicConstraints, keyCertSign, path length, validity) and the signer's own certificate must allow signing. A list vouches for signers, never for a time-stamp authority. Missing: building the EU file from the Trusted Lists (planned as an xtask), qualified time-stamp services (TSA/QTST), withdrawn services at the signing time, XML signature checks of the lists, a UI switch and keeping the choice between sessions. Adobe's AATL is not used (Adobe-authored data outside the closed list in AGENTS.md section 1.1 needs the owner's approval)"
[[feature]]
id = "sign.os-trust"