fix(sign): a change to a field a signature locks invalidates it (#6757)

## What this changes

Fixes #6757.

Validation read only DocMDP references. A signature field's `/Lock` (ISO 32000-2 §12.7.5.5) and the FieldMDP references in its value (§12.8.2.4) were ignored. So changing a locked field after an approval signature read as a permitted form fill, and the signature stayed **Valid**.

After this change:
- `crates/sign/src/pdf/locks.rs` (new) reads both from the **signed revision**: `All`, `Include` and `Exclude`. A listed name also covers the fields below it, so `address` covers `address.city` but not `addressee`. Both sources count, because signers write one or the other or both.
- The locked fields are compared between the signed revision and the document as it is now. That covers each field's dictionary and every dictionary above it (an inherited `/V` is its value too), plus its widgets. Tree links (`/Kids`, `/Parent`, `/P`) are left out of the comparison, and a page is compared by reference only, because adding an annotation rewrites it.
- A locked field that changed, disappeared, or gained a second field under its name adds the new change kind `kind::LOCKED_FIELD` ("locked field") to a **Disallowed** modification. The signature is then Invalid, whatever `classify_changes` called the change.
- A lock that is present but can't be read (an unknown `/Action`, a FieldMDP reference with no parameters, a non-dictionary `/Lock`), or a form too large to compare within the listing's caps, leaves the signature **Unknown**, never Valid. The detail is the existing "The signature could not be checked ({})." wording.
- New fields added under a locked field, and the form's `/NeedAppearances` (plus `/DA`, `/DR` and `/Q` when a locked field has no appearance of its own), count as changes to it. The signature's own field is compared when its lock covers it.
- `classify_changes` and `changes.rs` are unchanged. The check is wired in `finish_validation` (`validate.rs`).
- `parity`: `sign.field-mdp` moves from `planned` to `partial`, with what's still missing.

Related: #4809 makes *filling* refuse locked fields in PdfCraft's own form UI. The `sign` crate can't depend on `forms`, so this PR doesn't share its `signature_locks`. The lock reading follows the same rules (action, prefix matching, both sources) independently, and the two can be merged into one reader later. The two PRs touch different files.

## How you verified it

Run locally (Windows), scoped to `pdfcraft-sign`:

- [x] `cargo fmt --check -p pdfcraft-sign`
- [x] `cargo clippy -p pdfcraft-sign --all-targets -- -D warnings`: clean
- [x] `cargo test -p pdfcraft-sign --no-fail-fast`: integration 154 passed. Lib 120 passed, 1 failed: `shared_annotation_arrays_are_judged_in_bounded_time` (20 s limit) took 25 to 34 s. That test calls `classify_changes` directly, which this PR doesn't touch, and it fails the same way on unmodified `origin/main` on this machine (42 s), which was heavily loaded. CI should settle it.
- [x] `cargo xtask parity`: ok
- [x] Rerun on 78a860fda (head, includes a38542ab1 and the catalog fix from review): `cargo fmt --check -p pdfcraft-sign`, `cargo clippy -p pdfcraft-sign --all-targets -- -D warnings` (clean), `cargo test -p pdfcraft-sign` (lib 122 passed, including the timing test this time; integration 154 passed).
- [ ] `cargo xtask layers` / `assets`: not run (no crate boundary or asset touched)

**Tests.** `crates/sign/tests/it/field_locks.rs` signs a form with an approval signature whose field carries a `/Lock`, then appends an update:
- `changing_a_field_the_signature_locks_invalidates_it`: `Include [amount]`. Changing `amount`'s `/V`, its `/V` and `/AP`, or only its appearance stream makes the signature Invalid with `locked field`. Changing the unlocked `note` stays Valid (form fill).
- `exclude_locks_every_field_it_does_not_name`, `all_locks_every_field`, `a_locked_parent_locks_its_kids`, `removing_or_shadowing_a_locked_field_changes_it`.
- From review (fd11fcb6c), each seen failing on the first commit: `a_reference_cycle_in_a_locked_field_ends` (overflowed the stack), `an_all_lock_covers_the_signatures_own_widget`, `a_new_field_below_a_locked_one_changes_it`, `the_form_defaults_a_locked_field_is_drawn_with_are_locked_too` and `an_unreadable_lock_leaves_a_later_fill_unknown`.
- Control: `without_a_lock_the_same_change_is_a_form_fill`.
- Unit tests in `locks.rs`: a FieldMDP reference in the signature value locks fields, names cover kids only and match exactly as written, an unreadable lock (bad `/Fields` or `/Reference`, too many locks) is "unchecked" rather than "no lock".

I watched them fail: before the fix, 5 of the 6 integration tests failed (all reported Valid, as the issue describes) and the control passed. With the `locked_fields` call reverted once, the same 5 went red again.

## Never-crash

- [x] No new `unwrap`/`expect`/`panic!`/`unreachable!`/`todo!` outside tests
- [x] No input-derived indexing. The field walk keeps a seen-set and uses the listing's caps (`MAX_FIELDS`, `MAX_ENTRIES`, `MAX_NAME_BYTES`, `MAX_FIELD_NAME_BYTES`) plus a depth limit of 64. The comparison is bounded to 2^18 visited objects, every reference followed counts toward the depth limit, and reference pairs are memoised, so cycles end. Lock matching is one set lookup per node per lock, with at most 16 locks. Hitting any cap gives Unknown, not Valid.
- [x] No `unsafe`

## Provenance

- [x] No assets
- [x] Behaviour from ISO 32000-2 (§12.7.5.5, §12.8.2.4) and the issue's trace

## Parity and reach

- [x] `sign.field-mdp` → `partial`. Notes say what's missing: writing a lock when signing, refusing to fill a locked field (#4809), and the `/Lock /P` permissions.
- [x] Reachable headlessly: `sign_list` reports the verdict and the modification kinds.

## Anything a reviewer should look at first

- **`All` locks other signature fields too.** Signing a second, still-empty signature field after a signature with `Action /All` counts as a change to a locked field, so the first signature becomes Invalid. That is how I read §12.7.5.5, where the lock names fields and a signature field is one. If you'd rather exempt signing an empty signature field, it's a one-line filter in `locked_fields`.
- **The comparison is strict.** Any change to a locked field's dictionaries or widgets counts, including a re-encoded but identical appearance stream. I chose to err toward Invalid on these.
- **New change kind.** `kind::LOCKED_FIELD` is in `kind::ALL`, so interfaces will look up a new word ("locked field"). It shows in English until craft-i18n translates it.
This commit is contained in:
Michael Higgins
2026-11-18 16:34:54 +07:00
committed by GitHub
parent 0293facd77
commit d5bcb41099
7 changed files with 1041 additions and 16 deletions
+1
View File
@@ -25,6 +25,7 @@ use crate::x509::{Certificate, build_chain, build_chain_noted};
mod changes;
mod listing;
mod locks;
mod signing;
mod types;
mod validate;
+704
View File
@@ -0,0 +1,704 @@
//! Fields a signature locks: its field's `/Lock` (ISO 32000-2 §12.7.5.5, Table 236) and the
//! FieldMDP transform in its value's `/Reference` (§12.8.2.4). Signers write either or both. Once
//! the field is signed, a change to a field the lock names breaks the signature, whatever the
//! change would count as otherwise (#6757).
//!
//! The locks are read from the signed revision, and the locked fields are compared between that
//! revision and the document as it is now: each field's dictionary and the ones above it (an
//! inherited `/V` is its value too), and its widgets. A field that is gone, a second field under
//! its name, or a new field under a locked one is a change as well, and so is a change to the
//! form-wide appearance inputs a locked field is drawn from. A lock that is there but can't be
//! read, or a form too large to compare, is unchecked: never "no lock".
use std::collections::{BTreeMap, HashSet as NameSet};
use super::listing::{Field, MAX_ENTRIES, MAX_FIELD_NAME_BYTES, MAX_FIELDS, MAX_NAME_BYTES};
use super::{Dict, Document, HashSet, ObjRef, Object};
/// What a lock covers (`/Action`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Action {
All,
Include,
Exclude,
}
/// One lock: its action and the fully qualified names it lists, exactly as written.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Rule {
action: Action,
names: NameSet<String>,
}
impl Rule {
/// Which of `form`'s nodes the rule locks, by node. A listed name also covers the fields below
/// it (`address` covers `address.city`): a node is listed when its name is, or its parent is.
/// Parents come before their kids in a walk, so one pass decides every node, each by one look
/// at its own name.
fn locks(&self, form: &Form) -> Vec<bool> {
let mut listed: Vec<bool> = Vec::with_capacity(form.nodes.len());
for n in &form.nodes {
let above = n.parent.and_then(|p| listed.get(p).copied()).unwrap_or(false);
listed.push(above || self.names.contains(&n.name));
}
match self.action {
Action::All => vec![true; listed.len()],
Action::Include => listed,
Action::Exclude => listed.into_iter().map(|l| !l).collect(),
}
}
}
/// Most names one lock lists; real locks name a handful.
const MAX_LOCK_NAMES: usize = MAX_FIELDS;
/// Most locks read for one signature: its `/Lock` and its FieldMDP references. Real signatures
/// carry one or two; each one costs a pass over the form's names.
const MAX_RULES: usize = 16;
/// Deepest field tree walked, and deepest nesting (references included) compared. Real forms nest
/// a few levels.
const MAX_FIELD_DEPTH: usize = 64;
/// Most objects one comparison visits, for all the locked fields of one signature together.
const MAX_COMPARED: usize = 1 << 18;
/// What comparing a signature's locked fields found.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Locked {
/// The signature locks no field, or none it locks changed.
Kept,
/// A field it locks changed.
Changed,
/// It locks fields, but a cap or a lock that can't be read kept them from being compared.
Unchecked,
}
/// A field name or a name in a lock's `/Fields`, exactly as written: a text string decoded, or a
/// name's bytes. Nothing is trimmed, so `address ` and `address` stay two names, as the file has
/// them.
fn exact_name(o: &Object) -> Option<String> {
match o {
Object::String(s) => Some(s.to_text()),
Object::Name(n) => Some(String::from_utf8_lossy(n).into_owned()),
_ => None,
}
}
/// A lock dictionary (`/Lock`) or FieldMDP transform parameters. `Err` when it is there but can't
/// be read: its action is not one of the three, an `Include` or `Exclude` has no readable
/// `/Fields` array, a name in it is not a string, or it lists more names than are read.
fn rule(doc: &Document, d: &Dict) -> Result<Rule, ()> {
let action = match d.name(b"Action") {
Some(b"All") => Action::All,
Some(b"Include") => Action::Include,
Some(b"Exclude") => Action::Exclude,
_ => return Err(()),
};
if action == Action::All {
return Ok(Rule { action, names: NameSet::new() });
}
// An Include read as naming nothing would lock nothing, and an Exclude read so would lock
// everything: neither is what an unreadable list says.
let listed = d.get(b"Fields").map(|f| doc.resolve(f)).ok_or(())?;
let listed = listed.as_array().ok_or(())?;
if listed.len() > MAX_LOCK_NAMES {
return Err(());
}
let names = listed.iter().map(|n| exact_name(&doc.resolve(n)).ok_or(())).collect::<Result<_, _>>()?;
Ok(Rule { action, names })
}
/// The locks of signature field `field`, whose value is `value`, both as the signed revision `old`
/// has them. `Err` when one is there but can't be read: a `/Lock` or `/Reference` of the wrong
/// type, a reference that is not a dictionary, a FieldMDP reference without parameters, or more
/// locks than are read.
fn rules(old: &Document, field: &Field, value: &Dict) -> Result<Vec<Rule>, ()> {
let mut out = Vec::new();
if let Some(lock) = field.dict.get(b"Lock").map(|l| old.resolve(l)) {
match &*lock {
Object::Dict(d) => out.push(rule(old, d)?),
Object::Null => {}
_ => return Err(()),
}
}
let refs = value.get(b"Reference").map(|r| old.resolve(r));
let refs: &[Object] = match refs.as_deref() {
None | Some(Object::Null) => &[],
Some(Object::Array(a)) => a,
// A single reference dictionary where an array belongs may still be a FieldMDP lock.
Some(_) => return Err(()),
};
for r in refs {
let r = old.resolve(r);
let rd = r.as_dict().ok_or(())?;
if rd.name(b"TransformMethod") != Some(b"FieldMDP") {
continue;
}
// A FieldMDP reference that does not say what it locks is a lock that can't be read.
let params = rd.get(b"TransformParams").map(|p| old.resolve(p)).ok_or(())?;
out.push(rule(old, params.as_dict().ok_or(())?)?);
if out.len() > MAX_RULES {
return Err(());
}
}
Ok(out)
}
/// Whether any field the signature in `field` (signed with `value`) locks in the signed revision
/// `old` is different in `doc`, the document as it is now. The signature's own field is one of
/// them when its lock covers it: its value is the signature, which is checked anyway, but its
/// widgets are what a reader sees of it.
pub(super) fn locked_fields(doc: &Document, old: &Document, field: &Field, value: &Dict) -> Locked {
let Ok(rules) = rules(old, field, value) else { return Locked::Unchecked };
if rules.is_empty() {
return Locked::Kept;
}
let Some(before) = form_fields(old) else { return Locked::Unchecked };
let mut locked_nodes = vec![false; before.nodes.len()];
for rule in &rules {
for (l, r) in locked_nodes.iter_mut().zip(rule.locks(&before)) {
*l |= r;
}
}
// A name is locked when a node under it is; nodes sharing a name share their ancestors' names.
let is_locked = |entries: &[Entry]| entries.iter().any(|e| locked_nodes.get(e.node).copied().unwrap_or(false));
let locked: Vec<&String> = before.fields.iter().filter(|(_, e)| is_locked(e)).map(|(n, _)| n).collect();
if locked.is_empty() {
return Locked::Kept;
}
let Some(now) = form_fields(doc) else { return Locked::Unchecked };
let mut same = Same { old, doc, left: MAX_COMPARED, assumed: HashSet::new() };
let mut drawn_from_form = false;
for name in locked {
let (Some(was), Some(is)) = (before.fields.get(name), now.fields.get(name)) else { return Locked::Changed };
if was.len() != is.len() {
return Locked::Changed;
}
for (w, i) in was.iter().zip(is) {
drawn_from_form |= before.lacks_appearance(w);
match same.field(&before, w, &now, i) {
Some(true) => {}
Some(false) => return Locked::Changed,
None => return Locked::Unchecked,
}
}
}
// A field added since, below a field that was locked, changes that field: its kids are part
// of it. A field added anywhere else is not one the signature saw, so it locks nothing.
for n in &now.nodes {
if before.fields.contains_key(&n.name) {
continue;
}
let mut up = n.parent;
while let Some(p) = up.and_then(|p| now.nodes.get(p)) {
if let Some(entries) = before.fields.get(&p.name) {
if is_locked(entries) {
return Locked::Changed;
}
break;
}
up = p.parent;
}
}
// What the form says about drawing fields: whether a reader redraws every field
// (/NeedAppearances), and, for a locked field with no appearance of its own, the defaults it
// is drawn with.
let mut keys: Vec<&[u8]> = vec![b"NeedAppearances"];
if drawn_from_form {
keys.extend([b"DA".as_slice(), b"DR", b"Q"]);
}
for k in keys {
match same.entry(before.acroform.as_ref().and_then(|a| a.get(k)), now.acroform.as_ref().and_then(|a| a.get(k))) {
Some(true) => {}
Some(false) => return Locked::Changed,
None => return Locked::Unchecked,
}
}
Locked::Kept
}
/// One field dictionary in a walk of the form: its fully qualified name, and the one above it.
struct Node {
name: String,
dict: Dict,
parent: Option<usize>,
}
/// One field under its fully qualified name: its node, and its widgets apart from it.
struct Entry {
node: usize,
widgets: Vec<Dict>,
}
/// Every field of a form by fully qualified name, terminal or not, in walk order (a parent before
/// its kids), and the form dictionary itself.
struct Form {
acroform: Option<Dict>,
nodes: Vec<Node>,
fields: BTreeMap<String, Vec<Entry>>,
}
impl Form {
/// Whether field `e` has a widget with no appearance of its own, which a reader draws from the
/// form's defaults: a separate widget without `/AP`, or a field that is its own widget.
fn lacks_appearance(&self, e: &Entry) -> bool {
let has_ap = |d: &Dict| d.get(b"AP").is_some_and(|ap| !matches!(ap, Object::Null));
let merged = self.nodes.get(e.node).map(|n| &n.dict).filter(|d| e.widgets.is_empty() && !d.contains(b"Kids"));
merged.is_some_and(|d| !has_ap(d)) || e.widgets.iter().any(|w| !has_ap(w))
}
}
/// The fields of `doc`'s form, or `None` when a cap stopped the walk (a field it did not read may
/// be one a lock names). The caps are the signature listing's.
fn form_fields(doc: &Document) -> Option<Form> {
let mut form = Form { acroform: None, nodes: Vec::new(), fields: BTreeMap::new() };
let Some(root) = doc.root() else { return Some(form) };
let Some(af) = doc.get(root).as_dict().and_then(|c| c.get(b"AcroForm")).map(|a| doc.resolve(a)) else { return Some(form) };
let af = match &*af {
Object::Dict(d) => d.clone(),
Object::Null => return Some(form),
_ => return None,
};
let top = af.get(b"Fields").map(|f| doc.resolve(f));
form.acroform = Some(af);
let top: Vec<Object> = match top.as_deref() {
None | Some(Object::Null) => return Some(form),
Some(Object::Array(a)) => a.clone(),
Some(_) => return None,
};
let (mut fields_left, mut entries_left, mut names_left) = (MAX_FIELDS, MAX_ENTRIES, MAX_NAME_BYTES);
let mut seen: HashSet<ObjRef> = HashSet::new();
let mut stack: Vec<(Object, Option<usize>, usize)> = Vec::new();
entries_left = entries_left.checked_sub(top.len())?;
for f in top.into_iter().rev() {
stack.push((f, None, 0));
}
while let Some((o, parent, depth)) = stack.pop() {
if depth > MAX_FIELD_DEPTH {
return None;
}
if let Some(r) = o.as_ref()
&& !seen.insert(r)
{
continue;
}
let Some(d) = doc.resolve(&o).as_dict().cloned() else { continue };
fields_left = fields_left.checked_sub(1)?;
let prefix = parent.and_then(|p| form.nodes.get(p)).map_or("", |p| p.name.as_str());
let part = d.get(b"T").and_then(|t| exact_name(&doc.resolve(t)));
let name = match (part, prefix.is_empty()) {
(Some(p), true) => p,
(Some(p), false) => format!("{prefix}.{p}"),
(None, _) => prefix.to_owned(),
};
if name.len() > MAX_FIELD_NAME_BYTES {
return None;
}
// Counted twice: each name is kept by its node and as a key.
names_left = names_left.checked_sub(name.len().saturating_mul(2))?;
let node = form.nodes.len();
let kids = d.get(b"Kids").map(|k| doc.resolve(k));
let kids: Vec<Object> = kids.as_deref().and_then(Object::as_array).cloned().unwrap_or_default();
entries_left = entries_left.checked_sub(kids.len())?;
form.nodes.push(Node { name: name.clone(), dict: d, parent });
let mut widgets = Vec::new();
let mut sub = Vec::new();
for k in kids {
let kd = doc.resolve(&k);
let Some(kd) = kd.as_dict() else { continue };
// Kids with a /T are fields, and so are those with kids of their own; the others are
// this field's widgets.
if kd.contains(b"T") || kd.contains(b"Kids") {
sub.push(k);
} else {
widgets.push(kd.clone());
}
}
for k in sub.into_iter().rev() {
stack.push((k, Some(node), depth + 1));
}
form.fields.entry(name).or_default().push(Entry { node, widgets });
}
Some(form)
}
/// Entries a field's own dictionary is compared without: the tree's links, which change when a
/// field is added beside it or a widget's page gains an annotation, and say nothing of the field.
const FIELD_LINKS: &[&[u8]] = &[b"Kids", b"Parent", b"P"];
/// Compares objects of the signed revision with those of the document now, resolving references
/// in each, within [`MAX_COMPARED`] objects.
struct Same<'a> {
old: &'a Document,
doc: &'a Document,
left: usize,
/// Pairs of references being compared or found the same, so a cycle ends.
assumed: HashSet<(ObjRef, ObjRef)>,
}
impl Same<'_> {
/// Whether field `was` of the signed revision's form `before` is unchanged as `is` in `now`:
/// its dictionary and each above it, and its widgets. `None` when the comparison ran past its cap.
fn field(&mut self, before: &Form, was: &Entry, now: &Form, is: &Entry) -> Option<bool> {
let (mut a, mut b) = (Some(was.node), Some(is.node));
loop {
match (a.and_then(|i| before.nodes.get(i)), b.and_then(|i| now.nodes.get(i))) {
(None, None) => break,
(Some(x), Some(y)) => {
if !self.dicts(&x.dict, &y.dict, FIELD_LINKS, 0)? {
return Some(false);
}
(a, b) = (x.parent, y.parent);
}
_ => return Some(false),
}
}
if was.widgets.len() != is.widgets.len() {
return Some(false);
}
for (x, y) in was.widgets.iter().zip(&is.widgets) {
if !self.dicts(x, y, FIELD_LINKS, 0)? {
return Some(false);
}
}
Some(true)
}
/// [`Same::objects`] for an entry that may be absent: both absent, or both present and the
/// same.
fn entry(&mut self, a: Option<&Object>, b: Option<&Object>) -> Option<bool> {
match (a, b) {
(None, None) => Some(true),
(Some(a), Some(b)) => self.objects(a, b, 0),
_ => Some(false),
}
}
fn dicts(&mut self, a: &Dict, b: &Dict, skip: &[&[u8]], depth: usize) -> Option<bool> {
fn keys<'d>(d: &'d Dict, skip: &[&[u8]]) -> Vec<&'d [u8]> {
let mut k: Vec<&[u8]> = d.iter().map(|(k, _)| k.as_slice()).filter(|k| !skip.contains(k)).collect();
k.sort_unstable();
k
}
if keys(a, skip) != keys(b, skip) {
return Some(false);
}
for (k, v) in a.iter().filter(|(k, _)| !skip.contains(&k.as_slice())) {
let Some(w) = b.get(k) else { return Some(false) };
if !self.objects(v, w, depth + 1)? {
return Some(false);
}
}
Some(true)
}
/// Object equality across the two revisions: references resolved in their own revision,
/// dictionaries regardless of key order, a string by its bytes, a number by its value, and
/// stream data byte for byte as stored. A page, the page tree and the catalog are compared by
/// reference only, since every annotation or field added rewrites them.
fn objects(&mut self, a: &Object, b: &Object, depth: usize) -> Option<bool> {
self.left = self.left.checked_sub(1)?;
if depth > MAX_FIELD_DEPTH {
return None;
}
match (a, b) {
(Object::Ref(x), Object::Ref(y)) => {
if !self.assumed.insert((*x, *y)) {
return Some(true);
}
let (was, is) = (self.old.get(*x), self.doc.get(*y));
// The document's own structure is compared by reference: a page, the page tree, and
// the catalog, which a FieldMDP reference's /Data names (ISO 32000-2 Table 256) and
// which holds the whole form, so a field added anywhere would otherwise read as a
// change to a locked one. The catalog is the signed revision's /Root, with or
// without its /Type.
let structural =
Some(*x) == self.old.root() || was.as_dict().is_some_and(|d| matches!(d.name(b"Type"), Some(b"Page" | b"Pages" | b"Catalog")));
if x == y && structural {
return Some(true);
}
// Each reference followed counts as a level, so a chain of references (or a
// cycle of them on one side only) ends at the depth cap.
self.objects(&was, &is, depth + 1)
}
(Object::Ref(x), _) => {
let was = self.old.get(*x);
self.objects(&was, b, depth + 1)
}
(_, Object::Ref(y)) => {
let is = self.doc.get(*y);
self.objects(a, &is, depth + 1)
}
(Object::String(x), Object::String(y)) => Some(x.bytes == y.bytes),
(Object::Int(i), Object::Real(r)) | (Object::Real(r), Object::Int(i)) => Some(r.fract() == 0.0 && *r as i128 == i128::from(*i)),
(Object::Dict(x), Object::Dict(y)) => self.dicts(x, y, &[], depth),
(Object::Stream(x), Object::Stream(y)) => Some(x.raw == y.raw && self.dicts(&x.dict, &y.dict, &[], depth)?),
(Object::Array(x), Object::Array(y)) => {
if x.len() != y.len() {
return Some(false);
}
for (v, w) in x.iter().zip(y) {
if !self.objects(v, w, depth + 1)? {
return Some(false);
}
}
Some(true)
}
_ => Some(a == b),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use pdfcraft_cos::PdfString;
fn dict(entries: Vec<(&str, Object)>) -> Dict {
let mut d = Dict::new();
for (k, v) in entries {
d.set(k.as_bytes().to_vec(), v);
}
d
}
fn names(n: &[&str]) -> Object {
Object::Array(n.iter().map(|s| Object::String(PdfString::text(s))).collect())
}
/// A form of fields named `names`, each below the one named by its name up to the last dot.
fn form_of(names: &[&str]) -> Form {
let mut form = Form { acroform: None, nodes: Vec::new(), fields: BTreeMap::new() };
for n in names {
let parent = n.rsplit_once('.').and_then(|(up, _)| names.iter().position(|x| *x == up));
form.nodes.push(Node { name: (*n).to_owned(), dict: Dict::new(), parent });
}
form
}
/// The names `rules` lock among `names`.
fn locked_names<'a>(rules: &[Rule], names: &[&'a str]) -> Vec<&'a str> {
let form = form_of(names);
let by_rule: Vec<Vec<bool>> = rules.iter().map(|r| r.locks(&form)).collect();
names.iter().enumerate().filter(|(i, _)| by_rule.iter().any(|l| l[*i])).map(|(_, n)| *n).collect()
}
fn sig_field(lock: Option<Object>) -> Field {
let mut d = dict(vec![("FT", Object::name("Sig")), ("T", Object::String(PdfString::text("Approval")))]);
if let Some(l) = lock {
d.set(b"Lock".to_vec(), l);
}
Field { name: "Approval".into(), r: None, dict: d, widgets: Vec::new() }
}
fn field_mdp(action: &str, fields: &[&str]) -> Dict {
let params = dict(vec![("Type", Object::name("TransformParams")), ("Action", Object::name(action)), ("Fields", names(fields))]);
let reference =
dict(vec![("Type", Object::name("SigRef")), ("TransformMethod", Object::name("FieldMDP")), ("TransformParams", Object::Dict(params))]);
dict(vec![("Type", Object::name("Sig")), ("Reference", Object::Array(vec![Object::Dict(reference)]))])
}
fn lock(entries: Vec<(&str, Object)>) -> Option<Object> {
Some(Object::Dict(dict(entries)))
}
fn rules_of(doc: &Document, lock: Option<Object>, value: &Dict) -> Vec<Rule> {
rules(doc, &sig_field(lock), value).unwrap()
}
const ALL_NAMES: &[&str] = &["amount", "note", "address", "address.city", "addressee"];
/// A FieldMDP reference in the signature value locks as a `/Lock` on its field does: the
/// signers that write only one of them are read either way.
#[test]
fn a_fieldmdp_reference_in_the_value_locks_fields() {
let doc = Document::new_empty();
let rules = rules(&doc, &sig_field(None), &field_mdp("Include", &["amount"])).unwrap();
assert_eq!(locked_names(&rules, ALL_NAMES), ["amount"]);
let rules = rules_of(&doc, None, &field_mdp("Exclude", &["note", "address"]));
assert_eq!(locked_names(&rules, ALL_NAMES), ["amount", "addressee"]);
let rules = rules_of(&doc, None, &field_mdp("All", &[]));
assert_eq!(locked_names(&rules, ALL_NAMES), ALL_NAMES);
}
/// A lock's names cover the fields below them, never a field that merely starts the same.
#[test]
fn a_listed_name_covers_its_kids_only() {
let doc = Document::new_empty();
let l = lock(vec![("Type", Object::name("SigFieldLock")), ("Action", Object::name("Include")), ("Fields", names(&["address"]))]);
let rules = rules_of(&doc, l, &dict(vec![]));
assert_eq!(locked_names(&rules, ALL_NAMES), ["address", "address.city"]);
}
/// Names are matched exactly as written: a lock on `address ` (with its space) covers the field
/// of that name and its kids, and not `address`.
#[test]
fn names_match_as_written() {
let doc = Document::new_empty();
let l = lock(vec![("Action", Object::name("Include")), ("Fields", names(&["address "]))]);
let rules = rules_of(&doc, l, &dict(vec![]));
assert_eq!(locked_names(&rules, &["address", "address.city", "address ", "address .city"]), ["address ", "address .city"]);
}
/// A lock that is there but can't be read leaves the signature's locks unknown, never "none".
#[test]
fn an_unreadable_lock_is_not_no_lock() {
let doc = Document::new_empty();
let err = |lock: Option<Object>, value: Dict| rules(&doc, &sig_field(lock), &value).is_err();
assert!(err(lock(vec![("Action", Object::name("Some"))]), dict(vec![])));
assert!(err(Some(Object::Int(1)), dict(vec![])));
// An Include or Exclude whose names can't be read: missing, not an array, or not strings.
for action in ["Include", "Exclude"] {
assert!(err(lock(vec![("Action", Object::name(action))]), dict(vec![])), "{action} without /Fields");
let one = dict(vec![("amount", Object::Int(1))]);
assert!(err(lock(vec![("Action", Object::name(action)), ("Fields", Object::Dict(one))]), dict(vec![])), "{action} /Fields not an array");
let mixed = Object::Array(vec![Object::String(PdfString::text("amount")), Object::Int(7)]);
assert!(err(lock(vec![("Action", Object::name(action)), ("Fields", mixed)]), dict(vec![])), "{action} with a name that is not one");
}
// A FieldMDP reference without parameters, a reference that is not a dictionary, and a
// single reference dictionary where the array belongs.
let bare = dict(vec![("TransformMethod", Object::name("FieldMDP"))]);
assert!(err(None, dict(vec![("Reference", Object::Array(vec![Object::Dict(bare)]))])));
assert!(err(None, dict(vec![("Reference", Object::Array(vec![Object::Int(3)]))])));
let one = field_mdp("All", &[]).get(b"Reference").and_then(Object::as_array).cloned().unwrap();
assert!(err(None, dict(vec![("Reference", one[0].clone())])));
assert_eq!(locked_fields(&doc, &doc, &sig_field(Some(Object::Int(1))), &dict(vec![])), Locked::Unchecked);
// No lock at all, an All lock without /Fields, and a DocMDP reference read fine.
assert!(!err(lock(vec![("Action", Object::name("All"))]), dict(vec![])));
let docmdp = dict(vec![("TransformMethod", Object::name("DocMDP"))]);
assert_eq!(rules(&doc, &sig_field(None), &dict(vec![("Reference", Object::Array(vec![Object::Dict(docmdp)]))])), Ok(Vec::new()));
}
/// A classic-xref PDF of `objs`, numbered from 1, with object 1 as the catalog.
fn write_pdf(objs: &[&str]) -> Vec<u8> {
let mut out = b"%PDF-1.7
"
.to_vec();
let mut offsets = Vec::new();
for (i, o) in objs.iter().enumerate() {
offsets.push(out.len());
out.extend_from_slice(
format!(
"{} 0 obj
{o}
endobj
",
i + 1
)
.as_bytes(),
);
}
let xref = out.len();
out.extend_from_slice(
format!(
"xref
0 {}
0000000000 65535 f
",
objs.len() + 1
)
.as_bytes(),
);
for o in offsets {
out.extend_from_slice(
format!(
"{o:010} 00000 n
"
)
.as_bytes(),
);
}
out.extend_from_slice(
format!(
"trailer
<< /Size {} /Root 1 0 R >>
startxref
{xref}
%%EOF
",
objs.len() + 1
)
.as_bytes(),
);
out
}
fn open(bytes: Vec<u8>) -> Document {
Document::open(std::sync::Arc::new(bytes)).unwrap()
}
/// `doc` with `edit` saved as one more revision, read back.
fn revised(doc: &Document, edit: impl FnOnce(&mut Document)) -> Document {
let mut doc = doc.clone();
edit(&mut doc);
let options = pdfcraft_cos::SaveOptions { object_streams: false, ..pdfcraft_cos::SaveOptions::default() };
open(pdfcraft_cos::write_incremental(&doc, &options).unwrap())
}
fn at(num: u32) -> ObjRef {
ObjRef { num, generation: 0 }
}
/// From review on #6763: a FieldMDP reference's `/Data` points at the catalog (ISO 32000-2
/// Table 256). A lock that covers the signature's own field compares its value, reference and
/// all, and the catalog holds the form: adding a signature in a new field afterwards rewrites
/// the form, which is not a change to the locked field. The catalog is compared by reference,
/// as pages are. Its own field's appearance is still compared.
#[test]
fn a_reference_to_the_catalog_is_not_followed_into_the_form() {
let lock = "/Action /Include /Fields [(Signature2)]";
let old = open(write_pdf(&[
"<< /Type /Catalog /Pages 2 0 R /AcroForm 7 0 R >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Annots [4 0 R] >>",
&format!(
"<< /Type /Annot /Subtype /Widget /FT /Sig /T (Signature2) /Rect [0 0 100 50] /P 3 0 R /F 4 /V 5 0 R /AP << /N 6 0 R >> /Lock << /Type /SigFieldLock {lock} >> >>"
),
&format!(
"<< /Type /Sig /SubFilter /adbe.pkcs7.detached /ByteRange [0 10 20 10] /Contents <00> /Reference [<< /Type /SigRef /TransformMethod /FieldMDP /TransformParams << /Type /TransformParams {lock} /V /1.2 >> /Data 1 0 R >>] >>"
),
"<< /Type /XObject /Subtype /Form /BBox [0 0 100 50] /Length 0 >>
stream
endstream",
"<< /Fields [4 0 R] /SigFlags 3 >>",
]));
let field = super::super::listing::sig_fields(&old).into_iter().find(|f| f.name == "Signature2").unwrap();
let value = field.signature(&old).unwrap();
// A second signature in a new top-level field, and the form's resources rewritten.
let signed_again = revised(&old, |doc| {
let mut v = Dict::new();
v.set(b"Type".to_vec(), Object::name("Sig"));
v.set(b"Contents".to_vec(), Object::String(PdfString::literal(vec![0])));
let v = doc.add(Object::Dict(v));
let mut w = Dict::new();
w.set(b"Type".to_vec(), Object::name("Annot"));
w.set(b"Subtype".to_vec(), Object::name("Widget"));
w.set(b"FT".to_vec(), Object::name("Sig"));
w.set(b"T".to_vec(), Object::String(PdfString::text("Signature1")));
w.set(b"Rect".to_vec(), Object::Array(vec![Object::Int(0); 4]));
w.set(b"P".to_vec(), Object::Ref(at(3)));
w.set(b"V".to_vec(), Object::Ref(v));
let w = doc.add(Object::Dict(w));
doc.update_dict(at(7), |form| {
form.set(b"Fields".to_vec(), Object::Array(vec![Object::Ref(at(4)), Object::Ref(w)]));
form.set(b"DR".to_vec(), Object::Dict(dict(vec![("Font", Object::Dict(Dict::new()))])));
})
.unwrap();
doc.update_dict(at(3), |page| page.set(b"Annots".to_vec(), Object::Array(vec![Object::Ref(at(4)), Object::Ref(w)]))).unwrap();
});
assert_eq!(locked_fields(&signed_again, &old, &field, &value), Locked::Kept);
// The locked field's own widget repainted is still a change.
let repainted = revised(&old, |doc| {
doc.update_dict(at(4), |w| w.set(b"AP".to_vec(), Object::Dict(dict(vec![("N", Object::Null)])))).unwrap();
});
assert_eq!(locked_fields(&repainted, &old, &field, &value), Locked::Changed);
}
/// More locks than are read is a lock that can't be read.
#[test]
fn too_many_locks_are_unchecked() {
let doc = Document::new_empty();
let one = field_mdp("All", &[]).get(b"Reference").and_then(Object::as_array).cloned().unwrap();
let many = vec![one[0].clone(); MAX_RULES + 1];
assert!(rules(&doc, &sig_field(None), &dict(vec![("Reference", Object::Array(many))])).is_err());
}
}
+5 -1
View File
@@ -40,12 +40,16 @@ pub mod kind {
pub const STRUCTURE: &str = "document structure";
pub const PAGES: &str = "pages added or removed";
pub const OTHER: &str = "other changes";
/// A change to a field the signature locks (its field's `/Lock`, or a FieldMDP reference in its
/// value), whatever else the change would count as.
pub const LOCKED_FIELD: &str = "locked field";
/// Not a change but the reason there is nothing to compare: the signed revision itself could not
/// be read, or does not hold the signature, so what came after it cannot be allowed.
pub const UNREADABLE: &str = "the signed version could not be read";
/// Every word above, for an interface to translate.
pub const ALL: &[&str] = &[PAGE_CONTENT, FORM_FILL, COMMENTS, SIGNATURE, SECURITY_STORE, METADATA, LINKS, STRUCTURE, PAGES, OTHER, UNREADABLE];
pub const ALL: &[&str] =
&[PAGE_CONTENT, FORM_FILL, COMMENTS, SIGNATURE, SECURITY_STORE, METADATA, LINKS, STRUCTURE, PAGES, OTHER, LOCKED_FIELD, UNREADABLE];
}
/// Changes made after signing.
+61 -11
View File
@@ -1,6 +1,7 @@
use super::changes::classify_changes;
use super::listing::{DigestCache, list, nums, sig_fields, text};
use super::types::{Detail, Fill, Modification, Status, TrustStore};
use super::locks::{Locked, locked_fields};
use super::types::{Detail, Fill, Modification, Status, TrustStore, kind};
use super::{
Certificate, Dict, DigestAlg, Document, HashSet, ObjRef, Object, SignError, SignatureInfo, SignedData, Time, build_chain, build_chain_noted,
};
@@ -21,6 +22,11 @@ struct VerifiedSignature<'a> {
unverified_time: Option<Time>,
}
/// Most signature fields whose locks are compared for a signature that is not listed under any of
/// the fields ending its signed revision; past it the locks are left undecided. Each costs a walk of
/// the form, and a real revision ends with one signature.
const MAX_UNBOUND_CANDIDATES: usize = 4;
/// Validate one signature dictionary.
pub fn validate(doc: &Document, bytes: &[u8], trust: &TrustStore, field: &str) -> Option<SignatureInfo> {
list(doc, bytes, trust).into_iter().find(|s| s.field == field)
@@ -265,6 +271,7 @@ fn finish_validation(context: SignatureValidation<'_>, verified: VerifiedSignatu
let revocation = check_dss_revocation(doc, signer.as_ref(), &at, info);
let revoked = revocation == DssRevocation::Revoked;
// Changes after signing.
let mut locks = Locked::Kept;
info.modification = if covered == bytes.len() || bytes[covered..].iter().all(|b| b.is_ascii_whitespace() || *b == 0) {
Modification::None
} else {
@@ -273,16 +280,47 @@ fn finish_validation(context: SignatureValidation<'_>, verified: VerifiedSignatu
// revision that holds no such signature does not say which permissions apply, so what
// came after it is judged as when the revision cannot be read: not permitted.
let old = cache.revision(doc, bytes, covered);
let signed = old.as_ref().and_then(|old| {
sig_fields(old)
.iter()
.filter_map(|f| f.signature(old))
.find(|v| nums(old, v, b"ByteRange").is_some_and(|b| b.len() == 4 && b[2] + b[3] == covered as f64))
});
match (old, signed) {
(Some(old), Some(v)) => {
set_certification(&old, &v, info);
classify_changes(doc, Some(old), info.certify)
// Every field of the signed revision whose signature ends it; the one this signature is
// listed under, when it is there, is the one it was made in.
let mut ending: Vec<_> = old
.as_ref()
.map(|old| {
sig_fields(old)
.into_iter()
.filter_map(|f| {
let v = f.signature(old)?;
nums(old, &v, b"ByteRange").is_some_and(|b| b.len() == 4 && b[2] + b[3] == covered as f64).then_some((f, v))
})
.collect()
})
.unwrap_or_default();
let bound = ending.iter().position(|(f, _)| f.name == info.field);
let candidates = match bound {
Some(i) => vec![ending.swap_remove(i)],
None => std::mem::take(&mut ending),
};
match (old, candidates.first()) {
(Some(old), Some((field, v))) => {
set_certification(&old, v, info);
// The fields this signature locks, as the signed revision has them, against the
// document now (#6757). Its locks are its own field's: when that field is not
// among those ending the revision, any of them could be it, so a lock on any of
// them leaves the check undecided rather than borrowing another field's. Each
// candidate costs a walk of the form, so past a few the check is undecided too.
locks = match bound {
Some(_) => locked_fields(doc, &old, field, v),
None if candidates.len() > MAX_UNBOUND_CANDIDATES => Locked::Unchecked,
None if candidates.iter().any(|(f, v)| locked_fields(doc, &old, f, v) != Locked::Kept) => Locked::Unchecked,
None => Locked::Kept,
};
match classify_changes(doc, Some(old), info.certify) {
Modification::Allowed(_) if locks == Locked::Changed => Modification::Disallowed(vec![kind::LOCKED_FIELD]),
Modification::Disallowed(mut kinds) if locks == Locked::Changed => {
kinds.push(kind::LOCKED_FIELD);
Modification::Disallowed(kinds)
}
m => m,
}
}
_ => classify_changes(doc, None, info.certify),
}
@@ -306,6 +344,18 @@ fn finish_validation(context: SignatureValidation<'_>, verified: VerifiedSignatu
problems = true;
}
}
// A lock that could not be read or compared proves nothing either way: the changes may touch
// a field it locks, so the signature is not Valid.
if locks == Locked::Unchecked && !problems {
info.details.push(Detail::of(
"The signature could not be checked ({}).",
Fill::Reason("the fields this signature locks could not all be compared with the signed version".into()),
));
if !revoked {
info.status = Status::Unknown;
}
problems = true;
}
if revocation == DssRevocation::Incomplete {
if !problems {
info.status = Status::Unknown;
+265
View File
@@ -0,0 +1,265 @@
//! Fields a signature locks (ISO 32000-2 §12.7.5.5 `/Lock`, §12.8.2.4 FieldMDP): a change made
//! after signing to a field the signature locks is not a permitted form fill (#6757).
use std::sync::Arc;
use pdfcraft_cos::{Document, ObjRef, Object, PdfString, SaveOptions, Stream, write_incremental};
use pdfcraft_sign::{Modification, SignOptions, Status, TrustStore, kind, pkcs12, signatures};
fn data(name: &str) -> Vec<u8> {
std::fs::read(format!("{}/tests/data/{name}", env!("CARGO_MANIFEST_DIR"))).unwrap()
}
fn open(b: &[u8]) -> Document {
Document::open(Arc::new(b.to_vec())).unwrap()
}
/// A classic-xref PDF of `objs`, numbered from 1, with object 1 as the catalog.
fn write_pdf(objs: &[&str]) -> Vec<u8> {
let mut out = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (i, o) in objs.iter().enumerate() {
offsets.push(out.len());
out.extend_from_slice(format!("{} 0 obj\n{o}\nendobj\n", i + 1).as_bytes());
}
let xref = out.len();
out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes());
for o in offsets {
out.extend_from_slice(format!("{o:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes());
out
}
const AMOUNT: u32 = 6;
const AMOUNT_AP: u32 = 7;
const NOTE: u32 = 8;
const CITY: u32 = 11;
/// A form with signature field "Approval" (object 5) carrying `lock` as its `/Lock`, a text field
/// "amount" with an appearance, a text field "note", and a field "address" whose kid is
/// "address.city".
fn form(lock: &str) -> Vec<u8> {
write_pdf(&[
"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R 6 0 R 8 0 R 10 0 R] >> >>",
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 300] /Annots [5 0 R 6 0 R 8 0 R 11 0 R] >>",
"<< >>",
&format!("<< /Type /Annot /Subtype /Widget /FT /Sig /T (Approval) /Rect [150 20 280 70] /P 3 0 R /F 4 {lock} >>"),
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (amount) /V (100) /Rect [20 200 120 220] /P 3 0 R /F 4 /AP << /N 7 0 R >> >>",
"<< /Type /XObject /Subtype /Form /BBox [0 0 100 20] /Length 26 >>\nstream\nBT /Helv 10 Tf (100) Tj ET\nendstream",
"<< /Type /Annot /Subtype /Widget /FT /Tx /T (note) /V (hello) /Rect [20 170 120 190] /P 3 0 R /F 4 >>",
"<< >>",
"<< /FT /Tx /T (address) /Kids [11 0 R] >>",
"<< /Type /Annot /Subtype /Widget /T (city) /Parent 10 0 R /V (Leeds) /Rect [20 140 120 160] /P 3 0 R /F 4 >>",
])
}
/// `form(lock)` signed in its "Approval" field as an approval signature, and the trust that
/// makes that signature Valid.
fn signed(lock: &str) -> (Vec<u8>, TrustStore) {
let id = pkcs12::open(&data("rsa-aes.p12"), "test").unwrap();
let opts = SignOptions { field: Some("Approval".into()), date: "D:20261002120000+01'00'".into(), ..SignOptions::default() };
let bytes = pdfcraft_sign::sign(&open(&form(lock)), &id, &opts).unwrap();
let mut trust = TrustStore::default();
trust.certs.push(id.certificate.clone());
(bytes, trust)
}
fn approval(bytes: &[u8], trust: &TrustStore) -> pdfcraft_sign::SignatureInfo {
signatures(&open(bytes), bytes, trust).into_iter().find(|s| s.field == "Approval").unwrap()
}
fn edit_after(signed: &[u8], f: impl FnOnce(&mut Document)) -> Vec<u8> {
let mut doc = open(signed);
f(&mut doc);
write_incremental(&doc, &SaveOptions { object_streams: false, ..SaveOptions::default() }).unwrap()
}
fn r(num: u32) -> ObjRef {
ObjRef { num, generation: 0 }
}
/// Fill text field `num` with `value`, as a form filler does.
fn fill(num: u32, value: &str) -> impl FnOnce(&mut Document) {
let value = value.to_owned();
move |doc| doc.update_dict(r(num), |d| d.set(b"V".to_vec(), Object::String(PdfString::text(&value)))).unwrap()
}
/// Repaint "amount" without touching its value.
fn repaint_amount(doc: &mut Document) {
let body = b"BT /Helv 10 Tf (999999) Tj ET".to_vec();
let mut d = pdfcraft_cos::Dict::new();
d.set(b"Type".to_vec(), Object::name("XObject"));
d.set(b"Subtype".to_vec(), Object::name("Form"));
d.set(b"BBox".to_vec(), Object::Array(vec![Object::Int(0), Object::Int(0), Object::Int(100), Object::Int(20)]));
d.set(b"Length".to_vec(), Object::Int(body.len() as i64));
doc.set(r(AMOUNT_AP), Object::Stream(Stream::from_raw(d, body)));
}
fn assert_locked(s: &pdfcraft_sign::SignatureInfo, what: &str) {
assert_eq!(s.status, Status::Invalid, "{what}: {:?}", s.details);
assert!(matches!(&s.modification, Modification::Disallowed(k) if k.contains(&kind::LOCKED_FIELD)), "{what}: {:?}", s.modification);
}
fn assert_fill_allowed(s: &pdfcraft_sign::SignatureInfo, what: &str) {
assert_eq!((s.status, s.modification.clone()), (Status::Valid, Modification::Allowed(vec![kind::FORM_FILL])), "{what}: {:?}", s.details);
}
const INCLUDE_AMOUNT: &str = "/Lock << /Type /SigFieldLock /Action /Include /Fields [(amount)] >>";
#[test]
fn changing_a_field_the_signature_locks_invalidates_it() {
let (bytes, trust) = signed(INCLUDE_AMOUNT);
assert_eq!(approval(&bytes, &trust).status, Status::Valid);
assert_locked(&approval(&edit_after(&bytes, fill(AMOUNT, "999999")), &trust), "value and appearance");
let both = edit_after(&bytes, |doc| {
fill(AMOUNT, "999999")(doc);
repaint_amount(doc);
});
assert_locked(&approval(&both, &trust), "value and appearance");
assert_locked(&approval(&edit_after(&bytes, repaint_amount), &trust), "appearance only");
// A field the lock does not name is filled as before.
assert_fill_allowed(&approval(&edit_after(&bytes, fill(NOTE, "changed")), &trust), "unlocked note");
}
#[test]
fn without_a_lock_the_same_change_is_a_form_fill() {
let (bytes, trust) = signed("");
assert_fill_allowed(&approval(&edit_after(&bytes, fill(AMOUNT, "999999")), &trust), "no lock");
}
#[test]
fn exclude_locks_every_field_it_does_not_name() {
let (bytes, trust) = signed("/Lock << /Type /SigFieldLock /Action /Exclude /Fields [(note)] >>");
assert_locked(&approval(&edit_after(&bytes, fill(AMOUNT, "1")), &trust), "amount under Exclude [note]");
assert_fill_allowed(&approval(&edit_after(&bytes, fill(NOTE, "changed")), &trust), "note under Exclude [note]");
}
#[test]
fn all_locks_every_field() {
let (bytes, trust) = signed("/Lock << /Type /SigFieldLock /Action /All >>");
assert_locked(&approval(&edit_after(&bytes, fill(NOTE, "changed")), &trust), "note under All");
assert_locked(&approval(&edit_after(&bytes, fill(CITY, "York")), &trust), "address.city under All");
}
/// A name in `/Fields` locks the fields below it too: "address" covers "address.city".
#[test]
fn a_locked_parent_locks_its_kids() {
let (bytes, trust) = signed("/Lock << /Type /SigFieldLock /Action /Include /Fields [(address)] >>");
assert_locked(&approval(&edit_after(&bytes, fill(CITY, "York")), &trust), "address.city under Include [address]");
assert_fill_allowed(&approval(&edit_after(&bytes, fill(AMOUNT, "1")), &trust), "amount under Include [address]");
}
/// Removing a locked field, or adding a second field under its name, changes it too.
#[test]
fn removing_or_shadowing_a_locked_field_changes_it() {
let (bytes, trust) = signed(INCLUDE_AMOUNT);
let removed = edit_after(&bytes, |doc| {
let root = doc.root().unwrap();
doc.update_dict(root, |c| {
if let Some(Object::Dict(form)) = c.get_mut(b"AcroForm") {
form.set(b"Fields".to_vec(), Object::Array(vec![Object::Ref(r(5)), Object::Ref(r(NOTE)), Object::Ref(r(10))]));
}
})
.unwrap();
});
assert_locked(&approval(&removed, &trust), "amount removed from the form");
let shadowed = edit_after(&bytes, |doc| {
let mut d = pdfcraft_cos::Dict::new();
d.set(b"FT".to_vec(), Object::name("Tx"));
d.set(b"T".to_vec(), Object::String(PdfString::text("amount")));
d.set(b"V".to_vec(), Object::String(PdfString::text("999999")));
let twin = doc.add(Object::Dict(d));
let root = doc.root().unwrap();
doc.update_dict(root, |c| {
if let Some(Object::Dict(form)) = c.get_mut(b"AcroForm")
&& let Some(Object::Array(fields)) = form.get_mut(b"Fields")
{
fields.push(Object::Ref(twin));
}
})
.unwrap();
});
assert_locked(&approval(&shadowed, &trust), "a second field named amount");
}
/// A locked field's value replaced by a cycle of references is compared within a bound: the
/// signature is not Valid, and validation returns (it overflowed the stack before).
#[test]
fn a_reference_cycle_in_a_locked_field_ends() {
let (bytes, trust) = signed(INCLUDE_AMOUNT);
let cyclic = edit_after(&bytes, |doc| {
let (a, b) = (doc.add(Object::Null), doc.add(Object::Null));
doc.set(a, Object::Ref(b));
doc.set(b, Object::Ref(a));
doc.update_dict(r(AMOUNT), |d| d.set(b"V".to_vec(), Object::Ref(a))).unwrap();
});
assert_ne!(approval(&cyclic, &trust).status, Status::Valid);
}
/// A lock that covers every field covers the signature's own field: repainting its widget after
/// signing is a change to a locked field.
#[test]
fn an_all_lock_covers_the_signatures_own_widget() {
let (bytes, trust) = signed("/Lock << /Type /SigFieldLock /Action /All >>");
let repainted = edit_after(&bytes, |doc| {
let body = b"0 0 1 rg 0 0 130 50 re f".to_vec();
let mut d = pdfcraft_cos::Dict::new();
d.set(b"Type".to_vec(), Object::name("XObject"));
d.set(b"Subtype".to_vec(), Object::name("Form"));
d.set(b"BBox".to_vec(), Object::Array(vec![Object::Int(0), Object::Int(0), Object::Int(130), Object::Int(50)]));
d.set(b"Length".to_vec(), Object::Int(body.len() as i64));
let ap = doc.add(Object::Stream(Stream::from_raw(d, body)));
let mut n = pdfcraft_cos::Dict::new();
n.set(b"N".to_vec(), Object::Ref(ap));
doc.update_dict(r(5), |w| w.set(b"AP".to_vec(), Object::Dict(n))).unwrap();
});
assert_locked(&approval(&repainted, &trust), "the signature's own widget under All");
}
/// A field added below a locked field changes it: "address" gains "address.postcode".
#[test]
fn a_new_field_below_a_locked_one_changes_it() {
let (bytes, trust) = signed("/Lock << /Type /SigFieldLock /Action /Include /Fields [(address)] >>");
let grown = edit_after(&bytes, |doc| {
let mut d = pdfcraft_cos::Dict::new();
d.set(b"T".to_vec(), Object::String(PdfString::text("postcode")));
d.set(b"Parent".to_vec(), Object::Ref(r(10)));
d.set(b"V".to_vec(), Object::String(PdfString::text("LS1")));
let kid = doc.add(Object::Dict(d));
doc.update_dict(r(10), |p| {
if let Some(Object::Array(kids)) = p.get_mut(b"Kids") {
kids.push(Object::Ref(kid));
}
})
.unwrap();
});
assert_locked(&approval(&grown, &trust), "a kid added under a locked field");
}
/// A locked field with no appearance of its own is drawn from the form's defaults, so changing
/// the form's /DA changes how it looks.
#[test]
fn the_form_defaults_a_locked_field_is_drawn_with_are_locked_too() {
let (bytes, trust) = signed("/Lock << /Type /SigFieldLock /Action /Include /Fields [(note)] >>");
let restyled = edit_after(&bytes, |doc| {
let root = doc.root().unwrap();
doc.update_dict(root, |c| {
if let Some(Object::Dict(form)) = c.get_mut(b"AcroForm") {
form.set(b"DA".to_vec(), Object::String(PdfString::literal("/Helv 40 Tf 1 0 0 rg")));
}
})
.unwrap();
});
assert_locked(&approval(&restyled, &trust), "the form's /DA for a field drawn from it");
}
/// An Include lock whose names can't be read locks an unknown set of fields: a later fill leaves
/// the signature Unknown, never Valid.
#[test]
fn an_unreadable_lock_leaves_a_later_fill_unknown() {
let (bytes, trust) = signed("/Lock << /Type /SigFieldLock /Action /Include /Fields (amount) >>");
let s = approval(&edit_after(&bytes, fill(AMOUNT, "999999")), &trust);
assert_eq!(s.status, Status::Unknown, "{:?}", s.details);
}
+1
View File
@@ -6,6 +6,7 @@ mod chain;
mod cms;
mod crypto;
mod encrypted_signing;
mod field_locks;
mod pdf;
mod revision_classification;
mod signed_structure;
+4 -4
View File
@@ -6340,11 +6340,11 @@ title = "Field locks (FieldMDP)"
area = "H"
tier = "P1"
milestone = "M9"
status = "planned"
status = "partial"
commands = []
tools = []
evidence = []
notes = ""
tools = ["sign_list"]
evidence = ["crates/sign/tests/it/field_locks.rs::changing_a_field_the_signature_locks_invalidates_it", "crates/sign/tests/it/field_locks.rs::exclude_locks_every_field_it_does_not_name", "crates/sign/src/pdf/locks.rs::a_fieldmdp_reference_in_the_value_locks_fields"]
notes = "validation reads a signed field's /Lock and the FieldMDP references in its value (All, Include, Exclude; a listed name covers the fields below it) from the signed revision; a later change to a locked field or its widgets makes the signature invalid (modification: locked field), and a lock that can't be read or compared leaves it unknown. Not yet: writing a lock when signing, refusing to fill a locked field, and the /Lock /P permissions"
[[feature]]
id = "sign.document-timestamp"