Skip to main content

openszigno_verify/
codes.rs

1//! Stable check codes, statuses, and verdicts.
2//!
3//! Codes are stable strings that never change meaning. A consumer must treat an
4//! unknown code as blocking unless its status is `passed`.
5//!
6//! [`CheckCode`], [`CheckStatus`] and [`Verdict`] are `#[non_exhaustive]`.
7//! New check codes are emitted as the verifier learns to check more things, and
8//! adding one is a normal, additive change here rather than a semver break, so
9//! a downstream `match` on any of the three must carry a wildcard arm. Handle
10//! the unknown arm conservatively: an unrecognised code or status is not a
11//! passing one, and an unrecognised verdict is not `valid`. Read a code's
12//! stable string with [`CheckCode::as_str`] and enumerate the codes this build
13//! knows with [`CheckCode::ALL`].
14
15use serde::Serialize;
16
17/// The outcome of one check.
18///
19/// `unknown` means the tool could not determine the answer; it is never a
20/// substitute for `failed`, because "I do not know" and "this is forged" are
21/// different statements.
22///
23/// The enum is `#[non_exhaustive]`: match it with a wildcard arm and treat an
24/// unrecognised status as blocking.
25///
26/// `info` is the one status that does not block: it exists so that a check
27/// which only *reports* something — a certificate's loosely filled
28/// `extendedKeyUsage`, the presence of a claimed signing time — can be emitted
29/// without pretending the tool failed to determine anything. Every other
30/// non-`passed` status keeps the verdict below `valid`, which is what makes
31/// "`unknown` always blocks" true without exception.
32#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
33#[serde(rename_all = "snake_case")]
34#[non_exhaustive]
35pub enum CheckStatus {
36    Passed,
37    Failed,
38    Skipped,
39    Unknown,
40    /// Purely informational, and deliberately non-blocking.
41    Info,
42}
43
44impl CheckStatus {
45    pub const fn as_str(self) -> &'static str {
46        match self {
47            Self::Passed => "passed",
48            Self::Failed => "failed",
49            Self::Skipped => "skipped",
50            Self::Unknown => "unknown",
51            Self::Info => "info",
52        }
53    }
54
55    /// Whether this status keeps the verdict below `valid`.
56    pub const fn blocks(self) -> bool {
57        matches!(self, Self::Failed | Self::Skipped | Self::Unknown)
58    }
59}
60
61/// The ETSI EN 319 102-1 status vocabulary, minus the states this phase cannot
62/// reach.
63///
64/// The enum is `#[non_exhaustive]`: match it with a wildcard arm and treat an
65/// unrecognised verdict as not `valid`.
66#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize)]
67#[serde(rename_all = "snake_case")]
68#[non_exhaustive]
69pub enum Verdict {
70    /// TOTAL-PASSED.
71    Valid,
72    /// INDETERMINATE.
73    Indeterminate,
74    /// TOTAL-FAILED.
75    Invalid,
76}
77
78impl Verdict {
79    pub const fn as_str(self) -> &'static str {
80        match self {
81            Self::Valid => "valid",
82            Self::Indeterminate => "indeterminate",
83            Self::Invalid => "invalid",
84        }
85    }
86
87    /// The worse of two verdicts: `invalid` is worse than `indeterminate`,
88    /// which is worse than `valid`.
89    pub fn worst(self, other: Self) -> Self {
90        if other > self { other } else { self }
91    }
92}
93
94macro_rules! check_codes {
95    ($( $variant:ident => $text:literal ),* $(,)?) => {
96        /// Every check code this crate can emit.
97        ///
98        /// The enum is `#[non_exhaustive]`, because a release that learns to
99        /// check something new emits a new code for it. Match it with a
100        /// wildcard arm, and treat an unknown code as blocking unless the
101        /// [`CheckStatus`] beside it is `passed`. [`CheckCode::ALL`] lists
102        /// every code the build in use knows.
103        #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
104        #[serde(into = "&'static str")]
105        #[non_exhaustive]
106        pub enum CheckCode { $( $variant, )* }
107
108        impl CheckCode {
109            pub const fn as_str(self) -> &'static str {
110                match self { $( Self::$variant => $text, )* }
111            }
112
113            /// Every code, for documentation and test coverage.
114            pub const ALL: &'static [Self] = &[ $( Self::$variant, )* ];
115        }
116    };
117}
118
119check_codes! {
120    // Dossier level.
121    NoSignatures => "no_signatures",
122    SignatureCountWithinLimits => "signature_count_within_limits",
123    SignatureLimitExceeded => "signature_limit_exceeded",
124    SignaturesUnsupported => "signatures_unsupported",
125
126    // Document coverage: which modelled documents a signature actually covers.
127    DocumentsAllCovered => "documents_all_covered",
128    DocumentsUncovered => "documents_uncovered",
129    DocumentsCoverageUndetermined => "documents_coverage_undetermined",
130
131    // Stage A: structure and policy.
132    SigStructure => "sig_structure",
133    SigStructureInvalid => "sig_structure_invalid",
134    SigPlacement => "sig_placement",
135    SigPlacementInvalid => "sig_placement_invalid",
136    C14nMethodAllowed => "c14n_method_allowed",
137    C14nUnsupported => "c14n_unsupported",
138    SignatureAlgorithmAllowed => "signature_algorithm_allowed",
139    DigestAlgorithmAllowed => "digest_algorithm_allowed",
140    AlgorithmRejected => "algorithm_rejected",
141    AlgorithmLegacyAllowed => "algorithm_legacy_allowed",
142    TransformsAllowed => "transforms_allowed",
143    TransformNotAllowed => "transform_not_allowed",
144    ReferencesSameDocument => "references_same_document",
145    ReferenceExternal => "reference_external",
146    ReferencesResolve => "references_resolve",
147    ReferenceUnresolved => "reference_unresolved",
148    ReferenceScopeComplete => "reference_scope_complete",
149    ReferenceScopeIncomplete => "reference_scope_incomplete",
150    ReferenceScopeUnknown => "reference_scope_unknown",
151
152    // Countersignatures: ETSI EN 319 132-1 clause 5.2.7 (TS 101903 clause
153    // 7.2.4) for the nested form, and the e-dossier specification's own
154    // `es:SignatureProfile/es:Type` form.
155    CountersignatureBindingOk => "countersignature_binding_ok",
156    CountersignatureBindingMissing => "countersignature_binding_missing",
157    CountersignatureBindingMismatch => "countersignature_binding_mismatch",
158    NestedSignaturesUnsupported => "nested_signatures_unsupported",
159
160    // Stage B: the XMLDSig cryptographic core.
161    ReferenceDigestOk => "reference_digest_ok",
162    ReferenceDigestMismatch => "reference_digest_mismatch",
163    SignedInfoCanonicalization => "signedinfo_canonicalization",
164    SignedInfoCanonicalizationFailed => "signedinfo_canonicalization_failed",
165    SignatureValueOk => "signature_value_ok",
166    SignatureValueInvalid => "signature_value_invalid",
167
168    // Stage C: XAdES qualifying properties.
169    XadesPresent => "xades_present",
170    XadesAbsent => "xades_absent",
171    XadesNotValidated => "xades_not_validated",
172    XadesExtraQualifyingProperties => "xades_extra_qualifying_properties",
173    XadesSigningCertificateBound => "xades_signing_certificate_bound",
174    XadesSigningCertificateMismatch => "xades_signing_certificate_mismatch",
175    XadesSigningCertificateAbsent => "xades_signing_certificate_absent",
176    XadesSignaturePolicyImplied => "xades_signature_policy_implied",
177    XadesSignaturePolicyExplicit => "xades_signature_policy_explicit",
178
179    // Stage D: certificate path.
180    SigningCertificateAvailable => "signing_certificate_available",
181    SigningCertificateMissing => "signing_certificate_missing",
182    SigningTimePresent => "signing_time_present",
183    CertMalformed => "cert_malformed",
184    CertPathOk => "cert_path_ok",
185    CertPathUnknown => "cert_path_unknown",
186    CertPathUntrusted => "cert_path_untrusted",
187    CertPathSearchExhausted => "cert_path_search_exhausted",
188    CertPathLengthExceeded => "cert_path_length_exceeded",
189    CertExpired => "cert_expired",
190    CertNotYetValid => "cert_not_yet_valid",
191    CertSignatureInvalid => "cert_signature_invalid",
192    CertAlgorithmRejected => "cert_algorithm_rejected",
193    CertKeyUsageInvalid => "cert_key_usage_invalid",
194    CertKeyUsageAdvisory => "cert_key_usage_advisory",
195    CertBasicConstraintsInvalid => "cert_basic_constraints_invalid",
196    CertNameConstraintViolation => "cert_name_constraint_violation",
197    CertUnsupportedCriticalExtension => "cert_unsupported_critical_extension",
198
199    // Stage E: revocation.
200    RevocationPolicy => "revocation_policy",
201    RevocationNotChecked => "revocation_not_checked",
202    RevocationOk => "revocation_ok",
203    CertRevoked => "cert_revoked",
204    CertRevokedAfterValidationTime => "cert_revoked_after_validation_time",
205    RevocationStatusUnknown => "revocation_status_unknown",
206    RevocationStatusUnknownByResponder => "revocation_status_unknown_by_responder",
207    RevocationDataStale => "revocation_data_stale",
208    RevocationDataInvalid => "revocation_data_invalid",
209    OcspResponderTrusted => "ocsp_responder_trusted",
210    RevocationSourcesDisagree => "revocation_sources_disagree",
211    OnlineFetchFailed => "online_fetch_failed",
212
213    // Trusted lists (ETSI TS 119 612).
214    TrustListLoaded => "trust_list_loaded",
215    TrustListUnverified => "trust_list_unverified",
216    TrustListSignatureOk => "trust_list_signature_ok",
217    TrustListSignatureInvalid => "trust_list_signature_invalid",
218    TrustListSignerMismatch => "trust_list_signer_mismatch",
219    TrustListSignerUnqualified => "trust_list_signer_unqualified",
220    TrustListServiceNotGranted => "trust_list_service_not_granted",
221    CertificateQualified => "certificate_qualified",
222    CertificateNotQualified => "certificate_not_qualified",
223    CertificateQualifiedUnknown => "certificate_qualified_unknown",
224
225    // Stage F: RFC 3161 signature timestamps.
226    SignatureTimestampPresent => "signature_timestamp_present",
227    SignatureTimestampAbsent => "signature_timestamp_absent",
228    TimestampNotChecked => "timestamp_not_checked",
229    TimestampTokenParsed => "timestamp_token_parsed",
230    TimestampImprintOk => "timestamp_imprint_ok",
231    TimestampImprintMismatch => "timestamp_imprint_mismatch",
232    TimestampSignatureOk => "timestamp_signature_ok",
233    TimestampSignatureInvalid => "timestamp_signature_invalid",
234    TimestampTsaCertificateOk => "timestamp_tsa_certificate_ok",
235    TimestampTsaCertificateInvalid => "timestamp_tsa_certificate_invalid",
236    TimestampTsaPathOk => "timestamp_tsa_path_ok",
237    TimestampTsaPathUntrusted => "timestamp_tsa_path_untrusted",
238    TimestampTsaPathUnknown => "timestamp_tsa_path_unknown",
239    TimestampBeforeSigningTime => "timestamp_before_signing_time",
240    TimestampVerified => "timestamp_verified",
241    ArchiveTimestampPresent => "archive_timestamp_present",
242
243    // Dossier-level and document-level `es:TimeStamp` (M3).
244    DossierTimestampVerified => "dossier_timestamp_verified",
245    DossierTimestampInvalid => "dossier_timestamp_invalid",
246    DossierTimestampNotChecked => "dossier_timestamp_not_checked",
247    DocumentTimestampVerified => "document_timestamp_verified",
248    DocumentTimestampInvalid => "document_timestamp_invalid",
249    DocumentTimestampNotChecked => "document_timestamp_not_checked",
250}
251
252impl From<CheckCode> for &'static str {
253    fn from(code: CheckCode) -> Self {
254        code.as_str()
255    }
256}
257
258/// One emitted check.
259#[derive(Clone, Debug, Serialize)]
260pub struct Check {
261    pub code: CheckCode,
262    pub status: CheckStatus,
263    /// Human text. Never stable, and never contains payload content, input
264    /// paths, or signer data.
265    pub message: String,
266}
267
268impl Check {
269    pub fn new(code: CheckCode, status: CheckStatus, message: impl Into<String>) -> Self {
270        Self {
271            code,
272            status,
273            message: message.into(),
274        }
275    }
276
277    pub fn passed(code: CheckCode, message: impl Into<String>) -> Self {
278        Self::new(code, CheckStatus::Passed, message)
279    }
280
281    pub fn failed(code: CheckCode, message: impl Into<String>) -> Self {
282        Self::new(code, CheckStatus::Failed, message)
283    }
284
285    pub fn skipped(code: CheckCode, message: impl Into<String>) -> Self {
286        Self::new(code, CheckStatus::Skipped, message)
287    }
288
289    pub fn unknown(code: CheckCode, message: impl Into<String>) -> Self {
290        Self::new(code, CheckStatus::Unknown, message)
291    }
292
293    /// A check that reports rather than decides. It never blocks a verdict.
294    pub fn info(code: CheckCode, message: impl Into<String>) -> Self {
295        Self::new(code, CheckStatus::Info, message)
296    }
297}
298
299impl CheckCode {
300    /// Whether this code reports a revocation answer.
301    ///
302    /// Revocation is folded into a verdict once, at the signature level, so a
303    /// timestamp token's own summary must not fold it in a second time — and a
304    /// token whose TSA's revocation status is merely *unknown* still proves
305    /// when the signature existed.
306    pub const fn is_revocation(self) -> bool {
307        matches!(
308            self,
309            Self::RevocationPolicy
310                | Self::RevocationNotChecked
311                | Self::RevocationOk
312                | Self::CertRevoked
313                | Self::CertRevokedAfterValidationTime
314                | Self::RevocationStatusUnknown
315                | Self::RevocationStatusUnknownByResponder
316                | Self::RevocationDataStale
317                | Self::RevocationDataInvalid
318                | Self::OcspResponderTrusted
319                | Self::OnlineFetchFailed
320        )
321    }
322}
323
324/// Fold a list of checks into a verdict.
325///
326/// One `failed` makes the verdict `invalid`. Anything that is neither `passed`
327/// nor `info` keeps it below `valid`. The function is monotone: adding a check
328/// can only lower the verdict.
329pub fn verdict_of(checks: &[Check]) -> Verdict {
330    let mut verdict = Verdict::Valid;
331    for check in checks {
332        verdict = verdict.worst(match check.status {
333            CheckStatus::Passed | CheckStatus::Info => Verdict::Valid,
334            CheckStatus::Failed => Verdict::Invalid,
335            CheckStatus::Skipped | CheckStatus::Unknown => Verdict::Indeterminate,
336        });
337    }
338    verdict
339}