Skip to main content

ifc_template_catalog/
runtime.rs

1//! Catalogs supplied at runtime, checked against their pinned digests.
2//!
3//! A host that leaves the catalog out of its binary (the npm package does,
4//! to keep 1.4 MB out of every browser download) ships the per-edition
5//! snapshot files instead and hands their bytes to [`install`]. The bytes
6//! must hash to the edition's pin ([`snapshot::pinned_sha256`]) or to the
7//! container's ([`snapshot::CONTAINER_SHA256`]); anything else is refused, so
8//! a runtime catalog is the same data the embedded one is.
9//!
10//! Installed catalogs live for the process (for a WebAssembly module, for
11//! the module instance). [`load_catalog`] reads them like
12//! [`crate::embedded::load_catalog`] reads the embedded ones, in the
13//! official or the corrected profile, and refuses an edition not installed
14//! yet with [`RuntimeCatalogError::NotInstalled`].
15//!
16//! [`snapshot::pinned_sha256`]: crate::snapshot::pinned_sha256
17//! [`snapshot::CONTAINER_SHA256`]: crate::snapshot::CONTAINER_SHA256
18
19use std::sync::OnceLock;
20
21use sha2::{Digest, Sha256};
22use thiserror::Error;
23
24use crate::catalog::{Catalog, CatalogProfile};
25use crate::definition::CatalogEdition;
26use crate::overlay::{corrected_patches, PatchError};
27use crate::snapshot::{self, ArchiveError};
28
29static IFC2X3_TC1: OnceLock<Catalog> = OnceLock::new();
30static IFC4_ADD2_TC1: OnceLock<Catalog> = OnceLock::new();
31static IFC4X3_ADD2: OnceLock<Catalog> = OnceLock::new();
32static IFC4_ADD2_TC1_CORRECTED: OnceLock<Result<Catalog, PatchError>> = OnceLock::new();
33static IFC4X3_ADD2_CORRECTED: OnceLock<Result<Catalog, PatchError>> = OnceLock::new();
34
35fn official_slot(edition: CatalogEdition) -> &'static OnceLock<Catalog> {
36    match edition {
37        CatalogEdition::Ifc2x3Tc1 => &IFC2X3_TC1,
38        CatalogEdition::Ifc4Add2Tc1 => &IFC4_ADD2_TC1,
39        CatalogEdition::Ifc4x3Add2 => &IFC4X3_ADD2,
40    }
41}
42
43/// Check `bytes` against `edition`'s pinned SHA-256, or the container's,
44/// and decode that edition. Nothing is installed.
45pub fn decode_verified(
46    edition: CatalogEdition,
47    bytes: &[u8],
48) -> Result<Catalog, RuntimeCatalogError> {
49    verify(edition, bytes)?;
50    Ok(snapshot::decode_edition(bytes, edition)?)
51}
52
53/// Install `edition` from snapshot bytes: its per-edition file, or the
54/// container. The bytes are checked against the pin before anything is
55/// decoded. Installing an edition already installed is a no-op that still
56/// checks the bytes.
57pub fn install(edition: CatalogEdition, bytes: &[u8]) -> Result<(), RuntimeCatalogError> {
58    let slot = official_slot(edition);
59    if slot.get().is_some() {
60        // Still refuse bytes that are not the pinned snapshot.
61        verify(edition, bytes)?;
62        return Ok(());
63    }
64    let catalog = decode_verified(edition, bytes)?;
65    // A concurrent install of the same pinned bytes may have won; it
66    // installed the same catalog.
67    let _ = slot.set(catalog);
68    Ok(())
69}
70
71fn verify(edition: CatalogEdition, bytes: &[u8]) -> Result<(), RuntimeCatalogError> {
72    let actual: String = Sha256::digest(bytes)
73        .iter()
74        .map(|byte| format!("{byte:02x}"))
75        .collect();
76    let expected = snapshot::pinned_sha256(edition);
77    if actual == expected || actual == snapshot::CONTAINER_SHA256 {
78        Ok(())
79    } else {
80        Err(RuntimeCatalogError::DigestMismatch {
81            edition,
82            expected,
83            actual,
84        })
85    }
86}
87
88/// Whether `edition` has been installed.
89pub fn is_installed(edition: CatalogEdition) -> bool {
90    official_slot(edition).get().is_some()
91}
92
93/// An installed catalog in `profile`: [`CatalogProfile::Official`], or
94/// [`CatalogProfile::Corrected`] for the editions with a built-in overlay
95/// (IFC4 ADD2 TC1, IFC4X3 ADD2), derived once and cached.
96pub fn load_catalog(
97    edition: CatalogEdition,
98    profile: CatalogProfile,
99) -> Result<Catalog, RuntimeCatalogError> {
100    let official = official_slot(edition)
101        .get()
102        .cloned()
103        .ok_or(RuntimeCatalogError::NotInstalled(edition))?;
104    match profile {
105        CatalogProfile::Official => Ok(official),
106        CatalogProfile::Corrected => {
107            let slot = match edition {
108                CatalogEdition::Ifc4Add2Tc1 => &IFC4_ADD2_TC1_CORRECTED,
109                CatalogEdition::Ifc4x3Add2 => &IFC4X3_ADD2_CORRECTED,
110                _ => return Err(RuntimeCatalogError::UnavailableEdition(edition)),
111            };
112            slot.get_or_init(|| {
113                official.with_patches(CatalogProfile::Corrected, &corrected_patches(edition))
114            })
115            .clone()
116            .map_err(RuntimeCatalogError::Patch)
117        }
118        _ => Err(RuntimeCatalogError::UnsupportedProfile(profile)),
119    }
120}
121
122/// Why a runtime catalog cannot be installed or read.
123#[derive(Debug, Clone, PartialEq, Eq, Error)]
124#[non_exhaustive]
125pub enum RuntimeCatalogError {
126    /// The bytes are not the pinned snapshot of this edition or the pinned
127    /// container: a different edition's file, another version, or a
128    /// damaged download.
129    #[error(
130        "the {edition:?} catalog bytes have SHA-256 {actual}; the pinned snapshot has {expected}"
131    )]
132    DigestMismatch {
133        /// The edition the bytes were offered for.
134        edition: CatalogEdition,
135        /// The edition's pinned per-edition SHA-256.
136        expected: &'static str,
137        /// The offered bytes' SHA-256.
138        actual: String,
139    },
140    /// The pinned bytes failed to decode (a build whose decoder disagrees
141    /// with its own pins).
142    #[error(transparent)]
143    Archive(#[from] ArchiveError),
144    /// No catalog of this edition has been installed yet.
145    #[error("no {0:?} catalog is installed; install its snapshot first")]
146    NotInstalled(CatalogEdition),
147    /// The edition has no built-in corrected profile (IFC2X3 TC1).
148    #[error("no corrected profile for {0:?}")]
149    UnavailableEdition(CatalogEdition),
150    /// Only the official and corrected profiles are loaded this way.
151    #[error("runtime loading does not construct {0:?} profiles")]
152    UnsupportedProfile(CatalogProfile),
153    /// Applying the built-in correction ledger failed.
154    #[error(transparent)]
155    Patch(#[from] PatchError),
156}