diff --git a/crates/sign/src/pdf/locks.rs b/crates/sign/src/pdf/locks.rs index 60d0b613a3..f318a94961 100644 --- a/crates/sign/src/pdf/locks.rs +++ b/crates/sign/src/pdf/locks.rs @@ -5,12 +5,14 @@ //! //! 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, or a second field -//! under its name, is a change as well. +//! 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; +use std::collections::{BTreeMap, HashSet as NameSet}; -use super::listing::{Field, MAX_ENTRIES, MAX_FIELD_NAME_BYTES, MAX_FIELDS, MAX_NAME_BYTES, text}; +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`). @@ -21,29 +23,39 @@ enum Action { Exclude, } -/// One lock: its action and the fully qualified names it lists. +/// One lock: its action and the fully qualified names it lists, exactly as written. #[derive(Clone, Debug, PartialEq, Eq)] struct Rule { action: Action, - names: Vec, + names: NameSet, } impl Rule { - /// Whether the rule locks field `name`. A listed name also covers the fields below it - /// (`address` covers `address.city`). - fn locks(&self, name: &str) -> bool { - let listed = || self.names.iter().any(|x| name == x || name.strip_prefix(x.as_str()).is_some_and(|r| r.starts_with('.'))); + /// 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 { + let mut listed: Vec = 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 => true, - Action::Include => listed(), - Action::Exclude => !listed(), + 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; -/// Deepest field tree walked. Real forms nest a few levels. +/// 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; @@ -59,8 +71,20 @@ pub(super) enum Locked { 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 { + 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, or it lists more names than are read. +/// 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 { let action = match d.name(b"Action") { Some(b"All") => Action::All, @@ -68,26 +92,24 @@ fn rule(doc: &Document, d: &Dict) -> Result { Some(b"Exclude") => Action::Exclude, _ => return Err(()), }; - let listed = d.get(b"Fields").map(|f| doc.resolve(f)); - let listed = listed.as_deref().and_then(Object::as_array).map(Vec::as_slice).unwrap_or_default(); + 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() - .filter_map(|n| match &*doc.resolve(n) { - Object::String(s) => Some(s.to_text()), - Object::Name(n) => Some(String::from_utf8_lossy(n).into_owned()), - _ => None, - }) - .map(|s| s.trim_matches('\0').trim().to_owned()) - .filter(|s| !s.is_empty()) - .collect(); + let names = listed.iter().map(|n| exact_name(&doc.resolve(n)).ok_or(())).collect::>()?; 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. +/// 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, ()> { let mut out = Vec::new(); if let Some(lock) = field.dict.get(b"Lock").map(|l| old.resolve(l)) { @@ -98,42 +120,60 @@ fn rules(old: &Document, field: &Field, value: &Dict) -> Result, ()> { } } let refs = value.get(b"Reference").map(|r| old.resolve(r)); - for r in refs.as_deref().and_then(Object::as_array).into_iter().flatten() { + 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 Some(rd) = r.as_dict() else { continue }; + let rd = r.as_dict().ok_or(())?; if rd.name(b"TransformMethod") != Some(b"FieldMDP") { continue; } - let params = rd.get(b"TransformParams").map(|p| old.resolve(p)); - match params.as_deref().and_then(Object::as_dict) { - Some(p) => out.push(rule(old, p)?), - // A FieldMDP reference that does not say what it locks is a lock that can't be read. - None => return Err(()), + // 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. +/// `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 locked: Vec<&String> = before.fields.keys().filter(|name| **name != field.name && rules.iter().any(|r| r.locks(name))).collect(); + 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, @@ -141,11 +181,43 @@ pub(super) fn locked_fields(doc: &Document, old: &Document, field: &Field, value } } } + // 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, and the one above it. +/// 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, } @@ -156,16 +228,28 @@ struct Entry { widgets: Vec, } -/// Every field of a form by fully qualified name, terminal or not, in walk order. +/// 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, nodes: Vec, fields: BTreeMap>, } +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
{ - let mut form = Form { nodes: Vec::new(), fields: BTreeMap::new() }; + 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 { @@ -174,6 +258,7 @@ fn form_fields(doc: &Document) -> Option { _ => return None, }; let top = af.get(b"Fields").map(|f| doc.resolve(f)); + form.acroform = Some(af); let top: Vec = match top.as_deref() { None | Some(Object::Null) => return Some(form), Some(Object::Array(a)) => a.clone(), @@ -181,15 +266,12 @@ fn form_fields(doc: &Document) -> Option { }; let (mut fields_left, mut entries_left, mut names_left) = (MAX_FIELDS, MAX_ENTRIES, MAX_NAME_BYTES); let mut seen: HashSet = HashSet::new(); - let mut stack: Vec<(Object, String, Option, usize)> = Vec::new(); - if top.len() > MAX_ENTRIES { - return None; - } - entries_left -= top.len(); + let mut stack: Vec<(Object, Option, usize)> = Vec::new(); + entries_left = entries_left.checked_sub(top.len())?; for f in top.into_iter().rev() { - stack.push((f, String::new(), None, 0)); + stack.push((f, None, 0)); } - while let Some((o, prefix, parent, depth)) = stack.pop() { + while let Some((o, parent, depth)) = stack.pop() { if depth > MAX_FIELD_DEPTH { return None; } @@ -200,20 +282,23 @@ fn form_fields(doc: &Document) -> Option { } let Some(d) = doc.resolve(&o).as_dict().cloned() else { continue }; fields_left = fields_left.checked_sub(1)?; - let name = match (text(doc, &d, b"T"), prefix.is_empty()) { + 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, + (None, _) => prefix.to_owned(), }; if name.len() > MAX_FIELD_NAME_BYTES { return None; } - names_left = names_left.checked_sub(name.len())?; + // 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 = kids.as_deref().and_then(Object::as_array).cloned().unwrap_or_default(); entries_left = entries_left.checked_sub(kids.len())?; - form.nodes.push(Node { dict: d, parent }); + form.nodes.push(Node { name: name.clone(), dict: d, parent }); let mut widgets = Vec::new(); let mut sub = Vec::new(); for k in kids { @@ -228,7 +313,7 @@ fn form_fields(doc: &Document) -> Option { } } for k in sub.into_iter().rev() { - stack.push((k, name.clone(), Some(node), depth + 1)); + stack.push((k, Some(node), depth + 1)); } form.fields.entry(name).or_default().push(Entry { node, widgets }); } @@ -277,6 +362,16 @@ impl Same<'_> { 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 { + 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 { 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(); @@ -313,15 +408,17 @@ impl Same<'_> { if x == y && was.as_dict().is_some_and(|d| matches!(d.name(b"Type"), Some(b"Page" | b"Pages"))) { return Some(true); } - self.objects(&was, &is, depth) + // 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) + self.objects(&was, b, depth + 1) } (_, Object::Ref(y)) => { let is = self.doc.get(*y); - self.objects(a, &is, depth) + 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)), @@ -343,12 +440,6 @@ impl Same<'_> { } } -/// The names `rules` would lock among `names`, for the tests below. -#[cfg(test)] -fn locked_names<'a>(rules: &[Rule], names: &[&'a str]) -> Vec<&'a str> { - names.iter().copied().filter(|n| rules.iter().any(|r| r.locks(n))).collect() -} - #[cfg(test)] mod tests { use super::*; @@ -366,6 +457,23 @@ mod tests { 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> = 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) -> Field { let mut d = dict(vec![("FT", Object::name("Sig")), ("T", Object::String(PdfString::text("Approval")))]); if let Some(l) = lock { @@ -381,6 +489,14 @@ mod tests { dict(vec![("Type", Object::name("Sig")), ("Reference", Object::Array(vec![Object::Dict(reference)]))]) } + fn lock(entries: Vec<(&str, Object)>) -> Option { + Some(Object::Dict(dict(entries))) + } + + fn rules_of(doc: &Document, lock: Option, value: &Dict) -> Vec { + 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 @@ -400,27 +516,56 @@ mod tests { #[test] fn a_listed_name_covers_its_kids_only() { let doc = Document::new_empty(); - let lock = dict(vec![("Type", Object::name("SigFieldLock")), ("Action", Object::name("Include")), ("Fields", names(&["address"]))]); - let rules = rules_of(&doc, Some(Object::Dict(lock)), &dict(vec![])); + 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 odd = dict(vec![("Action", Object::name("Some"))]); - assert!(rules(&doc, &sig_field(Some(Object::Dict(odd))), &dict(vec![])).is_err()); - assert!(rules(&doc, &sig_field(Some(Object::Int(1))), &dict(vec![])).is_err()); + let err = |lock: Option, 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!(rules(&doc, &sig_field(None), &dict(vec![("Reference", Object::Array(vec![Object::Dict(bare)]))])).is_err()); + 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, and a DocMDP reference, lock nothing. + // 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())); } - fn rules_of(doc: &Document, lock: Option, value: &Dict) -> Vec { - rules(doc, &sig_field(lock), value).unwrap() + /// 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()); } } diff --git a/crates/sign/src/pdf/validate.rs b/crates/sign/src/pdf/validate.rs index 04099267a9..7c1a06fa26 100644 --- a/crates/sign/src/pdf/validate.rs +++ b/crates/sign/src/pdf/validate.rs @@ -275,18 +275,37 @@ 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).into_iter().find_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)) + // 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() }) - }); - match (old, signed) { + .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); + set_certification(&old, v, info); // The fields this signature locks, as the signed revision has them, against the - // document now (#6757). - locks = locked_fields(doc, &old, &field, &v); + // 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. + locks = match bound { + Some(_) => locked_fields(doc, &old, field, v), + 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 => { diff --git a/crates/sign/tests/it/field_locks.rs b/crates/sign/tests/it/field_locks.rs index 481558b829..88e9fe6b45 100644 --- a/crates/sign/tests/it/field_locks.rs +++ b/crates/sign/tests/it/field_locks.rs @@ -183,3 +183,83 @@ fn removing_or_shadowing_a_locked_field_changes_it() { }); assert_eq!(approval(&shadowed, &trust).status, Status::Invalid); } + +/// 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); +}