Skip to main content

openszigno_author/
lib.rs

1//! Deterministic authoring of Microsec e-Szignó dossiers.
2//!
3//! This crate is the writer side of openSzigno. It builds an unsigned
4//! `es:Dossier` in the default e-Szignó 3.0 namespace, in the shape
5//! [`openszigno_core`] parses, and [`sign`] adds the two things that can be
6//! written into one afterwards: a signature, and a container `es:TimeStamp`.
7//! It reads no file, opens no socket and consults no clock, and it verifies
8//! nothing whatever: a dossier it produces is not evidence of anything.
9//!
10//! The one exception is the `encrypt` transform: when a [`DossierSpec`]
11//! names recipients, a document's payload is written as a CMS
12//! `EnvelopedData` addressed to them, which is what
13//! `openszigno extract --decrypt-key` reads back. Encrypting says who can
14//! read a document and nothing about who wrote it.
15//!
16//! Two properties are load-bearing:
17//!
18//! - **Determinism.** The same [`DossierSpec`] always renders the same bytes,
19//!   **unless it asks for encryption**. Element order, indentation, and
20//!   identifiers are fixed, the identifiers are positional (`obj0`,
21//!   `profile0`, ...), and the creation date comes from the caller. A content
22//!   key, an initialisation vector, and key-transport padding must be
23//!   unpredictable, so a spec carrying an [`Encryption`] renders different
24//!   bytes on every run by design.
25//! - **Readability by the reader.** Every bound [`Limits`] places on a dossier
26//!   is checked while building, and every document title is checked against
27//!   the rules `openszigno extract` applies before it writes a file, so a
28//!   dossier this crate returns is one the rest of the tool can list, decode,
29//!   and extract.
30
31mod archive;
32mod encrypt;
33mod error;
34mod mime;
35mod render;
36pub mod sign;
37mod title;
38
39use base64::{Engine as _, engine::general_purpose::STANDARD};
40use openszigno_core::{Limits, MimeType};
41use serde::Serialize;
42use unicode_normalization::UnicodeNormalization;
43
44pub use encrypt::{Encryption, KeyTransport, Recipient};
45pub use error::{Error, ErrorCode};
46pub use mime::{NESTED_DOSSIER_EXTENSION, NESTED_DOSSIER_MEDIA_TYPE, NESTED_DOSSIER_SUBTYPE};
47pub use render::{DOCUMENT_CATEGORY, DOSSIER_CATEGORY};
48pub use title::{TitleRejection, check_title, declarable_extension};
49
50/// The longest dossier title accepted. It is metadata, not a filename, so the
51/// filename rules do not apply to it; only the XML ones do.
52const MAX_DOSSIER_TITLE_BYTES: usize = 1024;
53
54/// One document to place in a dossier.
55#[derive(Clone, Debug)]
56pub struct DocumentSpec {
57    /// The `es:Title`, which is also the name `extract` writes the payload
58    /// under. It must pass [`check_title`].
59    pub title: String,
60    /// The `type/subtype` to declare. `None` derives it from the title's
61    /// extension, and is refused when nothing is registered for it.
62    pub media_type: Option<String>,
63    /// The document's bytes, exactly as they must come back out.
64    pub bytes: Vec<u8>,
65    /// Store the payload as `zip -> base64` instead of `base64`.
66    pub compress: bool,
67    /// Encrypt the payload for the dossier's recipients, when it has any.
68    ///
69    /// Set per document rather than per dossier because an embedded dossier
70    /// is written in the clear: see [`DossierSpec::encryption`].
71    pub encrypt: bool,
72}
73
74/// The dossier to build.
75#[derive(Clone, Debug)]
76pub struct DossierSpec {
77    /// The `es:Title` of the dossier itself.
78    pub title: String,
79    /// The creation date written for the dossier and for every document, as
80    /// the caller formatted it. This crate never reads a clock.
81    pub created: String,
82    /// The documents, in the order they are written.
83    pub documents: Vec<DocumentSpec>,
84    /// Who every [`DocumentSpec::encrypt`] document is encrypted for, or
85    /// `None` to write every payload in the clear.
86    ///
87    /// A spec that carries this renders different bytes on every run; see the
88    /// determinism note on this crate.
89    pub encryption: Option<Encryption>,
90}
91
92/// One document as it was written.
93#[derive(Clone, Debug, Serialize)]
94pub struct BuiltDocument {
95    pub index: usize,
96    pub title: String,
97    pub mime_type: MimeType,
98    /// The declared `SourceSize`, which is the decoded length.
99    pub source_size: u64,
100    pub transforms: Vec<String>,
101    /// Whether the declared type marks this document as an embedded dossier,
102    /// under the same rule the reader applies.
103    pub nested_dossier: bool,
104    /// Whether the payload was written as a CMS `EnvelopedData`, so that only
105    /// a recipient's private key can read it back. It says nothing about who
106    /// wrote the document.
107    pub encrypted: bool,
108    /// The `ds:Object` `Id` the profile points at, which is also the
109    /// `extract --document` selector for it.
110    pub object_ref: String,
111}
112
113/// A finished dossier: the bytes to write, and what went into them.
114#[derive(Clone, Debug)]
115pub struct BuiltDossier {
116    pub bytes: Vec<u8>,
117    pub documents: Vec<BuiltDocument>,
118}
119
120/// The same rule [`openszigno_core`] applies when it decides that a document
121/// holds another dossier.
122fn is_nested_dossier(mime: &MimeType) -> bool {
123    mime.essence().eq_ignore_ascii_case(&format!(
124        "{NESTED_DOSSIER_MEDIA_TYPE}/{NESTED_DOSSIER_SUBTYPE}"
125    )) || mime
126        .extension
127        .as_deref()
128        .is_some_and(|extension| extension.eq_ignore_ascii_case(NESTED_DOSSIER_EXTENSION))
129}
130
131/// Check the dossier's own title: it is XML text, so it may hold anything a
132/// document title may hold plus the filename-only refusals, but it may not be
133/// empty and may not carry a control character.
134fn check_dossier_title(title: &str) -> Result<(), Error> {
135    let unusable = |reason: &str| {
136        Error::new(
137            ErrorCode::InvalidDossierTitle,
138            format!("the dossier title {reason}"),
139        )
140    };
141    if title.trim().is_empty() {
142        return Err(unusable("must not be empty"));
143    }
144    if title.len() > MAX_DOSSIER_TITLE_BYTES {
145        return Err(unusable(&format!(
146            "must be at most {MAX_DOSSIER_TITLE_BYTES} bytes"
147        )));
148    }
149    if title
150        .chars()
151        .any(|character| character.is_control() || character == '\u{feff}')
152    {
153        return Err(unusable("must not hold a control character"));
154    }
155    Ok(())
156}
157
158/// The one composition every title is written in: NFC, exactly what the
159/// extraction sanitizer normalises a filename to.
160fn canonical(title: &str) -> String {
161    title.nfc().collect()
162}
163
164/// Turn a title rejection into the error the caller sees. The message says
165/// which document and why, and never echoes the title itself.
166fn title_error(index: usize, rejection: TitleRejection) -> Error {
167    let reason = match rejection {
168        TitleRejection::UnsafeTitle => {
169            "is empty, too long, or holds a character that hides, reorders, or escapes"
170        }
171        TitleRejection::UnsafePath => "is not a single plain filename",
172        TitleRejection::ReservedName => "uses a reserved device name",
173    };
174    Error::new(
175        ErrorCode::UnsafeDocumentTitle,
176        format!(
177            "document {index} title {reason}; extraction would refuse it, so it is \
178             refused here"
179        ),
180    )
181}
182
183/// Encode one document's payload, applying the transforms it asked for.
184///
185/// Returns the Base64 text and the transform chain, in the forward order the
186/// profile declares (`zip? -> encrypt? -> base64`), which is the order the
187/// specification fixes and the reader reverses.
188/// `title` is the canonical title, the one written to `es:Title`, because it
189/// is also the name the ZIP member carries: the raw title would put a
190/// different string in the archive than in the profile, and `extract` names
191/// the file from the archive member.
192fn encode(
193    index: usize,
194    title: &str,
195    document: &DocumentSpec,
196    encryption: Option<&Encryption>,
197    limits: &Limits,
198) -> Result<(String, Vec<String>), Error> {
199    if document.bytes.len() as u64 > limits.max_decoded_document_bytes {
200        return Err(Error::new(
201            ErrorCode::DecodedTooLarge,
202            format!(
203                "document {index} is larger than the {} byte limit",
204                limits.max_decoded_document_bytes
205            ),
206        ));
207    }
208    let mut transforms = Vec::with_capacity(3);
209    let mut payload = if document.compress {
210        transforms.push("zip".to_owned());
211        archive::compress(title, &document.bytes, limits)?
212    } else {
213        document.bytes.clone()
214    };
215    // The encryption wraps whatever the ZIP step produced, so under `--zip`
216    // the plaintext of the CMS message is the archive and the reader expands
217    // it after decrypting.
218    if let Some(encryption) = encryption.filter(|_| document.encrypt) {
219        transforms.push("encrypt".to_owned());
220        payload = encrypt::envelope(&payload, encryption)?;
221    }
222    transforms.push("base64".to_owned());
223    let encoded = STANDARD.encode(&payload);
224    if encoded.len() > limits.max_base64_chars {
225        return Err(Error::new(
226            ErrorCode::DecodedTooLarge,
227            format!(
228                "document {index} encodes to more than the {} Base64 character limit",
229                limits.max_base64_chars
230            ),
231        ));
232    }
233    Ok((encoded, transforms))
234}
235
236/// Build a dossier from `spec`, within `limits`.
237///
238/// Every check happens before anything is rendered, so a refusal produces no
239/// partial output. The returned bytes parse under the same limits.
240pub fn build(spec: &DossierSpec, limits: &Limits) -> Result<BuiltDossier, Error> {
241    check_dossier_title(&spec.title)?;
242    if spec.documents.is_empty() {
243        return Err(Error::new(
244            ErrorCode::NoDocuments,
245            "a dossier needs at least one document",
246        ));
247    }
248    if spec.documents.len() > limits.max_documents {
249        return Err(Error::new(
250            ErrorCode::TooManyDocuments,
251            format!("a dossier holds at most {} documents", limits.max_documents),
252        ));
253    }
254
255    let mut total: u64 = 0;
256    let mut documents = Vec::with_capacity(spec.documents.len());
257    let mut payloads = Vec::with_capacity(spec.documents.len());
258    for (index, document) in spec.documents.iter().enumerate() {
259        let title = document.title.trim();
260        check_title(title).map_err(|rejection| title_error(index, rejection))?;
261        // One canonical composition, the same one the extraction sanitizer
262        // writes a filename in, so the title in the dossier and the name the
263        // payload comes back out under are the same string.
264        let title = canonical(title);
265        let mime_type = mime::mime_for(&title, document.media_type.as_deref())?;
266        total = total.saturating_add(document.bytes.len() as u64);
267        if total > limits.max_total_decoded_bytes {
268            return Err(Error::new(
269                ErrorCode::TotalSizeLimit,
270                format!(
271                    "the documents total more than the {} byte limit",
272                    limits.max_total_decoded_bytes
273                ),
274            ));
275        }
276        let (payload, transforms) =
277            encode(index, &title, document, spec.encryption.as_ref(), limits)?;
278        payloads.push(payload);
279        documents.push(BuiltDocument {
280            index,
281            title,
282            source_size: document.bytes.len() as u64,
283            encrypted: transforms.iter().any(|transform| transform == "encrypt"),
284            transforms,
285            nested_dossier: is_nested_dossier(&mime_type),
286            mime_type,
287            object_ref: format!("obj{index}"),
288        });
289    }
290
291    let profile_ids: Vec<String> = (0..documents.len())
292        .map(|index| format!("profile{index}"))
293        .collect();
294    let rendered: Vec<render::RenderedDocument<'_>> = documents
295        .iter()
296        .enumerate()
297        .map(|(index, document)| render::RenderedDocument {
298            title: &document.title,
299            created: &spec.created,
300            mime_type: &document.mime_type,
301            source_size: document.source_size,
302            transforms: &document.transforms,
303            object_id: &document.object_ref,
304            profile_id: &profile_ids[index],
305            payload: &payloads[index],
306        })
307        .collect();
308    Ok(BuiltDossier {
309        bytes: render::dossier(&canonical(spec.title.trim()), &spec.created, &rendered),
310        documents,
311    })
312}
313
314#[cfg(test)]
315mod tests;