Skip to main content

openszigno_core/
model.rs

1use serde::Serialize;
2
3use crate::{DecodeOutcome, Error, KNOWN_COMPATIBLE_NAMESPACES};
4
5/// Resource limits applied while parsing and decoding a dossier.
6///
7/// Every limit except `max_total_decoded_bytes` is enforced by this crate.
8/// `max_total_decoded_bytes` bounds the aggregate of all decoded documents and
9/// must be enforced by the caller that decodes more than one document (the
10/// CLI does so during extraction), because `decode_document` works on one
11/// document at a time.
12#[derive(Clone, Debug, Serialize)]
13pub struct Limits {
14    /// Maximum size of the raw dossier file in bytes.
15    pub max_input_bytes: u64,
16    /// Maximum number of `es:Document` elements.
17    pub max_documents: usize,
18    /// Maximum number of Base64 characters in one payload after whitespace
19    /// removal.
20    pub max_base64_chars: usize,
21    /// Maximum decoded size of one document in bytes.
22    pub max_decoded_document_bytes: u64,
23    /// Maximum aggregate decoded size across all documents; enforced by the
24    /// caller, not by this crate.
25    pub max_total_decoded_bytes: u64,
26    /// Maximum number of members in a `zip` transform archive. The e-dossier
27    /// format stores exactly one member, so this is a defence-in-depth bound.
28    pub max_zip_members: usize,
29    /// Maximum expanded size of the ZIP member in bytes.
30    pub max_zip_expanded_bytes: u64,
31    /// Maximum expanded/compressed ratio, checked on actual decoded bytes.
32    pub max_zip_compression_ratio: u64,
33    /// Maximum XML element nesting depth, checked before tree construction.
34    pub max_xml_depth: usize,
35    /// Maximum number of XML elements, checked before tree construction and
36    /// again by the parser's own node limit.
37    pub max_xml_nodes: usize,
38}
39
40impl Default for Limits {
41    fn default() -> Self {
42        Self {
43            max_input_bytes: 64 * 1024 * 1024,
44            max_documents: 256,
45            max_base64_chars: 96 * 1024 * 1024,
46            max_decoded_document_bytes: 64 * 1024 * 1024,
47            max_total_decoded_bytes: 256 * 1024 * 1024,
48            max_zip_members: 16,
49            max_zip_expanded_bytes: 64 * 1024 * 1024,
50            max_zip_compression_ratio: 100,
51            max_xml_depth: 128,
52            max_xml_nodes: 1_000_000,
53        }
54    }
55}
56
57/// How a dossier is parsed: the resource limits and the namespaces whose
58/// `Dossier` root element is accepted.
59///
60/// The default accepts [`KNOWN_COMPATIBLE_NAMESPACES`] only. A caller may add
61/// further namespaces, but a dossier in an unlisted namespace stays a
62/// `wrong_root` error rather than a best-effort parse.
63#[derive(Clone, Debug)]
64pub struct ParseOptions {
65    pub limits: Limits,
66    pub allowed_namespaces: Vec<String>,
67}
68
69impl Default for ParseOptions {
70    fn default() -> Self {
71        Self {
72            limits: Limits::default(),
73            allowed_namespaces: KNOWN_COMPATIBLE_NAMESPACES
74                .iter()
75                .map(|namespace| (*namespace).to_owned())
76                .collect(),
77        }
78    }
79}
80
81impl ParseOptions {
82    /// The known-compatible namespaces with caller-chosen limits.
83    pub fn with_limits(limits: Limits) -> Self {
84        Self {
85            limits,
86            ..Self::default()
87        }
88    }
89
90    pub(crate) fn allows(&self, namespace: &str) -> bool {
91        self.allowed_namespaces
92            .iter()
93            .any(|allowed| allowed == namespace)
94    }
95}
96
97/// Stable machine-readable categories of non-fatal structural findings.
98///
99/// These describe a dossier that parsed but does not conform to the default
100/// profile. They never change an exit status by themselves.
101#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
102#[serde(rename_all = "snake_case")]
103pub enum StructuralWarningCode {
104    DanglingObjref,
105    DocumentWithoutProfile,
106    SourceSizeMissing,
107    CreationDateMissing,
108    SignatureInventoryTruncated,
109}
110
111impl StructuralWarningCode {
112    pub const fn as_str(self) -> &'static str {
113        match self {
114            Self::DanglingObjref => "dangling_objref",
115            Self::DocumentWithoutProfile => "document_without_profile",
116            Self::SourceSizeMissing => "source_size_missing",
117            Self::CreationDateMissing => "creation_date_missing",
118            Self::SignatureInventoryTruncated => "signature_inventory_truncated",
119        }
120    }
121}
122
123/// One non-fatal structural finding. The message never contains a title, a
124/// path, or payload content.
125#[derive(Clone, Debug, Serialize)]
126pub struct StructuralWarning {
127    pub code: StructuralWarningCode,
128    pub message: String,
129}
130
131#[derive(Clone, Debug, Serialize)]
132pub struct MimeType {
133    pub media_type: String,
134    pub subtype: String,
135    pub extension: Option<String>,
136    pub charset: Option<String>,
137}
138
139impl MimeType {
140    pub fn essence(&self) -> String {
141        format!("{}/{}", self.media_type, self.subtype)
142    }
143}
144
145#[derive(Clone, Debug, Serialize)]
146pub struct Document {
147    pub index: usize,
148    pub title: String,
149    pub creation_date: String,
150    pub mime_type: MimeType,
151    /// The declared decoded size, or `None` when the profile omits
152    /// `SourceSize`. Some company-court dossiers do.
153    pub source_size: Option<u64>,
154    pub object_ref: String,
155    pub transforms: Vec<String>,
156    /// The declared type marks this document as an embedded dossier.
157    pub nested_dossier: bool,
158    #[serde(skip)]
159    pub(crate) payload: String,
160}
161
162/// The largest number of `ds:Signature` elements the inventory describes.
163/// Beyond it the inventory is truncated and `signature_inventory_truncated`
164/// is reported; `signatures_present` still counts every signature.
165pub const MAX_INVENTORIED_SIGNATURES: usize = 64;
166/// The largest number of `es:TimeStamp` elements the inventory describes.
167pub const MAX_INVENTORIED_TIMESTAMPS: usize = 64;
168/// The largest number of `ds:Reference` URIs listed for one signature.
169pub const MAX_INVENTORIED_REFERENCE_URIS: usize = 16;
170/// The largest number of XAdES qualifying-property names listed for one
171/// signature.
172pub const MAX_INVENTORIED_XADES_PROPERTIES: usize = 32;
173/// The largest number of distinct digest algorithms listed for one signature.
174pub const MAX_INVENTORIED_DIGEST_METHODS: usize = 16;
175/// The largest number of `xades:ClaimedRole` values listed for one signature.
176pub const MAX_INVENTORIED_CLAIMED_ROLES: usize = 8;
177/// The largest number of characters of one claimed role that is echoed.
178pub const MAX_INVENTORIED_CLAIMED_ROLE_CHARS: usize = 128;
179
180/// Where a `ds:Signature` sits in the dossier.
181#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
182#[serde(rename_all = "snake_case")]
183pub enum SignaturePlacement {
184    /// Inside one `es:Document`; `document_index` names it.
185    Document,
186    /// A direct child of the root `es:Dossier`.
187    Dossier,
188    /// Inside another `ds:Signature`, a countersignature in practice.
189    NestedInSignature,
190    /// Anywhere else. The format does not say what such a signature covers.
191    Other,
192}
193
194impl SignaturePlacement {
195    pub const fn as_str(self) -> &'static str {
196        match self {
197            Self::Document => "document",
198            Self::Dossier => "dossier",
199            Self::NestedInSignature => "nested_in_signature",
200            Self::Other => "other",
201        }
202    }
203}
204
205/// Where an `es:TimeStamp` sits in the dossier.
206#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
207#[serde(rename_all = "snake_case")]
208pub enum TimestampPlacement {
209    /// A direct child of the root `es:Dossier`.
210    Dossier,
211    /// A direct child of one `es:Document`; `document_index` names it.
212    Document,
213    /// Anywhere else.
214    Other,
215}
216
217impl TimestampPlacement {
218    pub const fn as_str(self) -> &'static str {
219        match self {
220            Self::Dossier => "dossier",
221            Self::Document => "document",
222            Self::Other => "other",
223        }
224    }
225}
226
227/// How many evidence elements one signature carries. These are **element
228/// counts only**: nothing inside a certificate, CRL, OCSP response, or
229/// timestamp token is decoded, and carrying evidence says nothing about
230/// whether it is valid or even parsable.
231#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Serialize)]
232pub struct SignatureEvidence {
233    /// `xades:EncapsulatedX509Certificate` elements.
234    pub certificates: usize,
235    /// `xades:EncapsulatedCRLValue` elements.
236    pub crls: usize,
237    /// `xades:EncapsulatedOCSPValue` elements.
238    pub ocsp_responses: usize,
239    /// `xades:SignatureTimeStamp` elements.
240    pub signature_timestamps: usize,
241    /// `xades:ArchiveTimeStamp` elements.
242    pub archive_timestamps: usize,
243}
244
245/// One `ds:Signature`, as the XML claims it.
246///
247/// Every field is unverified claimed metadata read at parse time. No
248/// cryptography is performed, no certificate is decoded, and no reference is
249/// resolved or dereferenced. A dossier can claim anything here.
250#[derive(Clone, Debug, Serialize)]
251pub struct SignatureSummary {
252    /// The `Id` attribute, when it is present and looks like an ID.
253    pub id: Option<String>,
254    pub placement: SignaturePlacement,
255    /// The index of the enclosing document, for `document` placement.
256    pub document_index: Option<usize>,
257    /// The `Id` of the enclosing signature, for `nested_in_signature`.
258    pub parent_signature_id: Option<String>,
259    /// `ds:CanonicalizationMethod/@Algorithm`, as declared.
260    pub canonicalization_method: Option<String>,
261    /// `ds:SignatureMethod/@Algorithm`, as declared.
262    pub signature_method: Option<String>,
263    /// The distinct `ds:DigestMethod/@Algorithm` values of the references, in
264    /// document order.
265    pub digest_methods: Vec<String>,
266    /// Every `ds:Reference` in `ds:SignedInfo` is counted.
267    pub reference_count: usize,
268    /// Same-document reference URIs only, bounded to
269    /// [`MAX_INVENTORIED_REFERENCE_URIS`]. Nothing is ever resolved or read.
270    pub reference_uris: Vec<String>,
271    /// The namespace of the `xades:QualifyingProperties` element, when the
272    /// signature carries one in a recognised XAdES namespace.
273    pub xades_namespace: Option<String>,
274    /// The local names of the signed and unsigned qualifying properties that
275    /// are present, in document order and bounded to
276    /// [`MAX_INVENTORIED_XADES_PROPERTIES`]. Presence only: a property is
277    /// never validated, and its content is not read.
278    pub xades_properties: Vec<String>,
279    /// The `xades:ClaimedRole` values of `xades:SignerRole` or
280    /// `xades:SignerRoleV2`, as text, bounded to
281    /// [`MAX_INVENTORIED_CLAIMED_ROLES`] entries of at most
282    /// [`MAX_INVENTORIED_CLAIMED_ROLE_CHARS`] characters each.
283    ///
284    /// A claim like any other: the role is what the signature says about
285    /// itself, and Hungarian AVDH material carries the citizen's asserted
286    /// identity here. Nothing is validated, and the field is left out of the
287    /// JSON entirely when the signature claims no role.
288    #[serde(skip_serializing_if = "Vec::is_empty")]
289    pub claimed_roles: Vec<String>,
290    pub evidence: SignatureEvidence,
291    /// The `xades:SigningTime` text, trimmed and otherwise unparsed. It is
292    /// what the signature claims, not when anything happened.
293    pub claimed_signing_time: Option<String>,
294    /// `ds:X509Certificate` elements under `ds:KeyInfo`. A count; no
295    /// certificate is decoded.
296    pub key_info_certificates: usize,
297}
298
299/// One container `es:TimeStamp`, as the XML claims it. Unverified, like every
300/// other part of the inventory.
301#[derive(Clone, Debug, Serialize)]
302pub struct TimestampSummary {
303    pub placement: TimestampPlacement,
304    /// The index of the enclosing document, for `document` placement.
305    pub document_index: Option<usize>,
306    /// `xades:Include` children, counted. None is ever resolved.
307    pub include_count: usize,
308    /// Whether a non-empty `xades:EncapsulatedTimeStamp` is present. The token
309    /// is neither decoded nor verified.
310    pub has_token: bool,
311}
312
313#[derive(Clone, Debug, Serialize)]
314pub struct Dossier {
315    pub title: String,
316    pub category: Option<String>,
317    /// The declared creation date, or `None` when the `DossierProfile`
318    /// omits `CreationDate`. Some company-court dossiers do.
319    pub creation_date: Option<String>,
320    pub namespace: String,
321    pub xml_encoding: String,
322    pub documents: Vec<Document>,
323    pub signatures_present: usize,
324    pub timestamps_present: usize,
325    /// The bounded, unverified inventory of every `ds:Signature`, in document
326    /// order. Claimed metadata only; see [`SignatureSummary`].
327    pub signatures: Vec<SignatureSummary>,
328    /// The bounded, unverified inventory of every container `es:TimeStamp`, in
329    /// document order. Claimed metadata only; see [`TimestampSummary`].
330    pub timestamps: Vec<TimestampSummary>,
331    /// Non-fatal deviations from the default profile, in source order.
332    pub warnings: Vec<StructuralWarning>,
333}
334
335impl Dossier {
336    pub fn decode_document(&self, index: usize, limits: &Limits) -> Result<DecodeOutcome, Error> {
337        crate::decode::decode_document(
338            self.documents.get(index).ok_or_else(|| {
339                Error::new(
340                    crate::ErrorCode::InvalidAttribute,
341                    "document index is out of range",
342                )
343            })?,
344            limits,
345        )
346    }
347}