laminapdf-model 0.8.0

Typed views of a PDF document in Rust: pages, outline, document info, page labels, name trees and the structure tree, read tolerantly.
Documentation
//! What a signature field says before anyone signs it: the fields its signing locks (`/Lock`,
//! ISO 32000-2 §12.7.5.5, Table 236) and the constraints it puts on the signer (`/SV`, the seed
//! value dictionary, Table 234), read back from the field's own dictionary. Neither is
//! inherited.

use laminapdf_cos::{Dict, Object, Result};

use crate::document::Document;
use crate::values::{array_items, name_bytes_text, read_name, text_of};

/// Which fields a signature field's `/Lock` locks when the field is signed (Table 236's
/// `/Action`).
///
/// Added in 0.7.0.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LockAction {
    /// Every field of the form.
    All,
    /// The fields `/Fields` lists.
    Include,
    /// Every field but those `/Fields` lists.
    Exclude,
}

impl LockAction {
    /// Every action, in the order the standard lists them.
    ///
    /// Added in 0.7.0.
    pub const ALL: [Self; 3] = [Self::All, Self::Include, Self::Exclude];

    /// The action's name as the bindings spell it: `all`, `include` or `exclude`.
    ///
    /// Added in 0.7.0.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::All => "all",
            Self::Include => "include",
            Self::Exclude => "exclude",
        }
    }

    /// The action [`as_str`](Self::as_str) names.
    ///
    /// Added in 0.7.0.
    #[must_use]
    pub fn from_name(name: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|a| a.as_str() == name)
    }

    /// The action a `/Action` name (`All`, `Include` or `Exclude`) is.
    ///
    /// Added in 0.7.0.
    #[must_use]
    pub fn from_pdf_name(name: &[u8]) -> Option<Self> {
        Self::ALL.into_iter().find(|a| a.pdf_name().as_bytes() == name)
    }

    /// The PDF name the dictionary holds (`All`, `Include` or `Exclude`).
    ///
    /// Added in 0.7.0.
    #[must_use]
    pub const fn pdf_name(self) -> &'static str {
        match self {
            Self::All => "All",
            Self::Include => "Include",
            Self::Exclude => "Exclude",
        }
    }
}

/// A signature field's `/Lock` dictionary.
///
/// Added in 0.7.0.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SignatureLock {
    /// What `fields` means.
    pub action: LockAction,
    /// `/Fields`: fully qualified names; empty for [`LockAction::All`].
    pub fields: Vec<String>,
    /// `/P` (PDF 2.0): the changes a later revision may make once the field is signed, 1 to 3
    /// (the `DocMDP` values). It limits an approval signature too.
    pub permission: Option<u8>,
}

/// A seed value entry that `/SV`'s `/Ff` can make required (Table 234): the signer must follow
/// it rather than take it as a hint.
///
/// Added in 0.7.0.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SeedEntry {
    /// `/Filter`: the signature handler.
    Filter,
    /// `/SubFilter`: the signature formats.
    SubFilter,
    /// `/Reasons`: the reasons for signing.
    Reasons,
}

impl SeedEntry {
    /// Every entry that can be required, in bit order.
    ///
    /// Added in 0.7.0.
    pub const ALL: [Self; 3] = [Self::Filter, Self::SubFilter, Self::Reasons];

    /// The entry's name as the bindings spell it: `filter`, `subFilter` or `reasons`.
    ///
    /// Added in 0.7.0.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Filter => "filter",
            Self::SubFilter => "subFilter",
            Self::Reasons => "reasons",
        }
    }

    /// The entry [`as_str`](Self::as_str) names.
    ///
    /// Added in 0.7.0.
    #[must_use]
    pub fn from_name(name: &str) -> Option<Self> {
        Self::ALL.into_iter().find(|e| e.as_str() == name)
    }

    /// The entry's bit in `/SV`'s `/Ff` (Table 234): bit 1 for the filter, bit 2 for the
    /// sub-filter and bit 4 for the reasons (bit 3 is the dictionary's version).
    ///
    /// Added in 0.7.0.
    #[must_use]
    pub const fn flag(self) -> u32 {
        match self {
            Self::Filter => 1,
            Self::SubFilter => 1 << 1,
            Self::Reasons => 1 << 3,
        }
    }
}

/// A signature field's seed values (`/SV`): what a signer is asked, or required, to use.
///
/// Added in 0.7.0.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct SignatureSeed {
    /// `/Filter`: the signature handler's name, such as `Adobe.PPKLite`.
    pub filter: Option<String>,
    /// `/SubFilter`: the signature formats allowed, such as `ETSI.CAdES.detached`.
    pub sub_filters: Vec<String>,
    /// `/Reasons`: the reasons for signing the signer may give.
    pub reasons: Vec<String>,
    /// `/MDP /P`: 0 for an ordinary signature, 1 to 3 for a certification (an author signature)
    /// with that `DocMDP` permission.
    pub mdp: Option<u8>,
    /// The entries `/Ff` requires.
    pub required: Vec<SeedEntry>,
}

/// The `/Lock` dictionary `value` names; `None` when it isn't one. Read tolerantly, as the
/// planner reads a signed field's lock: an action this reader doesn't know, or a list it can't
/// read whole, is [`LockAction::All`], the strictest reading.
pub(super) fn read_lock(doc: &Document, value: Option<&Object>) -> Result<Option<SignatureLock>> {
    let Some(dict) = dict_of(doc, value)? else {
        return Ok(None);
    };
    let action = read_name(doc, dict.get("Action"))?
        .and_then(|name| LockAction::from_pdf_name(&name))
        .unwrap_or(LockAction::All);
    let listed = if action == LockAction::All {
        Some(Vec::new())
    } else {
        names(doc, dict.get("Fields"))?
    };
    let (action, fields) = match listed {
        Some(fields) => (action, fields),
        None => (LockAction::All, Vec::new()),
    };
    let permission = small_number(doc, dict.get("P"), 1..=3)?;
    Ok(Some(SignatureLock {
        action,
        fields,
        permission,
    }))
}

/// The seed value dictionary `value` names; `None` when it isn't one.
pub(super) fn read_seed(doc: &Document, value: Option<&Object>) -> Result<Option<SignatureSeed>> {
    let Some(dict) = dict_of(doc, value)? else {
        return Ok(None);
    };
    let filter = read_name(doc, dict.get("Filter"))?.map(|n| name_bytes_text(&n));
    let mut sub_filters = Vec::new();
    for item in array_items(doc, dict.get("SubFilter"))? {
        if let Some(name) = read_name(doc, Some(&item))? {
            sub_filters.push(name_bytes_text(&name));
        }
    }
    let mut reasons = Vec::new();
    for item in array_items(doc, dict.get("Reasons"))? {
        if let Some(reason) = doc.read(&item)?.as_deref().and_then(text_of) {
            reasons.push(reason);
        }
    }
    let mdp = match dict_of(doc, dict.get("MDP"))? {
        Some(mdp) => small_number(doc, mdp.get("P"), 0..=3)?,
        None => None,
    };
    let ff = match dict.get("Ff") {
        Some(ff) => doc.read(ff)?.and_then(|o| o.as_int()).unwrap_or(0),
        None => 0,
    };
    let required = SeedEntry::ALL
        .into_iter()
        .filter(|e| ff & i64::from(e.flag()) != 0)
        .collect();
    Ok(Some(SignatureSeed {
        filter,
        sub_filters,
        reasons,
        mdp,
        required,
    }))
}

/// The integer `value` resolves to when it is in `range` (a `/P`, a `/MDP /P`).
fn small_number(doc: &Document, value: Option<&Object>, range: std::ops::RangeInclusive<u8>) -> Result<Option<u8>> {
    let Some(value) = value else { return Ok(None) };
    Ok(doc
        .read(value)?
        .and_then(|o| o.as_int())
        .and_then(|n| u8::try_from(n).ok())
        .filter(|n| range.contains(n)))
}

/// The dictionary `value` resolves to.
fn dict_of(doc: &Document, value: Option<&Object>) -> Result<Option<Dict>> {
    let Some(value) = value else { return Ok(None) };
    Ok(doc.read(value)?.and_then(|o| o.as_dict().cloned()))
}

/// The text strings of the array `value` names; `None` when it isn't an array or an item is not
/// a text string.
fn names(doc: &Document, value: Option<&Object>) -> Result<Option<Vec<String>>> {
    let Some(value) = value else { return Ok(None) };
    let Some(list) = doc.read(value)? else {
        return Ok(None);
    };
    let Some(items) = list.as_array() else {
        return Ok(None);
    };
    let mut out = Vec::with_capacity(items.len());
    for item in items {
        match doc.read(item)?.as_deref().and_then(text_of) {
            Some(name) => out.push(name),
            None => return Ok(None),
        }
    }
    Ok(Some(out))
}

/// Whether `dict` is a signature dictionary (ISO 32000-2 §12.8.1, Table 255): `/Type /Sig` or
/// `/DocTimeStamp`, or, since `/Type` is optional, a `/ByteRange` array with a string
/// `/Contents`.
///
/// Added in 0.7.0.
#[must_use]
pub fn is_signature_dictionary(dict: &Dict) -> bool {
    matches!(dict.get_name("Type"), Some(b"Sig" | b"DocTimeStamp"))
        || (dict.get("ByteRange").and_then(Object::as_array).is_some()
            && matches!(dict.get("Contents"), Some(Object::String(_))))
}

#[cfg(test)]
mod tests {
    use super::*;

    /// What `next` knows is every variant: its match is exhaustive, so a new variant fails to
    /// build here until it is given its place in the chain, and the chain from the first variant
    /// must then be exactly `ALL`, in order. A variant left out of `ALL` fails this test.
    #[test]
    fn all_should_list_every_lock_action_once_in_declaration_order() {
        let next = |v: LockAction| match v {
            LockAction::All => Some(LockAction::Include),
            LockAction::Include => Some(LockAction::Exclude),
            LockAction::Exclude => None,
        };
        let mut chain = vec![LockAction::All];
        while let Some(more) = chain.last().and_then(|v| next(*v)) {
            chain.push(more);
        }
        assert_eq!(chain, LockAction::ALL);
    }

    /// As for the lock actions: the chain is exhaustive, and must equal `ALL`.
    #[test]
    fn all_should_list_every_seed_entry_once_in_declaration_order() {
        let next = |v: SeedEntry| match v {
            SeedEntry::Filter => Some(SeedEntry::SubFilter),
            SeedEntry::SubFilter => Some(SeedEntry::Reasons),
            SeedEntry::Reasons => None,
        };
        let mut chain = vec![SeedEntry::Filter];
        while let Some(more) = chain.last().and_then(|v| next(*v)) {
            chain.push(more);
        }
        assert_eq!(chain, SeedEntry::ALL);
    }

    #[test]
    fn from_pdf_name_should_read_every_action_and_nothing_else() {
        let read = LockAction::ALL.map(|a| LockAction::from_pdf_name(a.pdf_name().as_bytes()));
        assert_eq!(read, LockAction::ALL.map(Some));
        assert_eq!(LockAction::from_pdf_name(b"Some"), None);
    }

    #[test]
    fn a_signature_dictionary_needs_no_type() {
        let untyped: Dict = [
            ("ByteRange", Object::Array(vec![0.into(), 1.into(), 2.into(), 3.into()])),
            ("Contents", Object::String(laminapdf_cos::PdfString::hex(vec![0]))),
        ]
        .into_iter()
        .collect();
        let field: Dict = [("FT", Object::name("Sig"))].into_iter().collect();
        assert_eq!(
            (is_signature_dictionary(&untyped), is_signature_dictionary(&field)),
            (true, false)
        );
    }
}