Skip to main content

hoike_core/
install.rs

1//! Offline, recoverable authenticated installation (design §S5, audit
2//! remediation F05).
3//!
4//! `install_bundle` turns an offline import into a real installation:
5//!
6//! 1. The input is authenticated under the configured trust policy — always,
7//!    even when the config permits unauthenticated demo *serving* — and
8//!    validated against the supported serving profile. The destination is
9//!    resolved from the selected CA label, never from a filename.
10//! 2. Existing state is opened strictly; rollback and predecessor continuity
11//!    are checked; changes are staged while retaining other labels'
12//!    committed snapshots.
13//! 3. The new immutable snapshot is written and fsynced, then the descriptor
14//!    (marks + snapshot references) is committed atomically. **That
15//!    descriptor commit is the installation commit point.**
16//! 4. The configured bundle path is published atomically *after* the commit.
17//!    If this convenience-path update fails, the result is still committed
18//!    and carries a `publication_warning` — never an error falsely claiming
19//!    no installation happened. Startup recovers from the committed
20//!    snapshot; retrying the identical import repairs the path.
21//!
22//! A failure before the descriptor commit leaves the old marks and the
23//! configured files intact. If the descriptor rename succeeds but its
24//! directory fsync fails, the outcome is indeterminate and is reported as
25//! [`CoreError::DurabilityUncertain`] instructing the operator to stop and
26//! reopen state — never as a claimed rollback. There is no two-file
27//! pseudo-transaction and no deletion of old recovery material before
28//! commitment.
29
30use std::path::PathBuf;
31
32use ahu::Bundle;
33use tracing::info;
34
35use crate::admission::{authenticate_bundle, validate_serving_profile};
36use crate::config::Config;
37use crate::error::{CoreError, Result};
38use crate::state::StateStore;
39use crate::storage::{StateDirectoryLock, write_atomic};
40
41/// The outcome of a successful [`install_bundle`].
42#[derive(Debug, Clone)]
43pub struct InstallResult {
44    /// The configured destination the bundle was installed for.
45    pub destination: PathBuf,
46    /// Set when the installation is committed but publishing the configured
47    /// bundle path failed afterwards. Startup still recovers the committed
48    /// snapshot; retrying the identical import repairs the path.
49    pub publication_warning: Option<String>,
50}
51
52/// Install an authenticated bundle for `label` into its configured
53/// destination, following the §S5 commit order.
54///
55/// `bytes` is the complete checked input: read the source once before
56/// calling this — everything published (snapshot and configured path) comes
57/// from these bytes, never from a re-read of the source path. `guard` must
58/// be the exclusive writer lock for `config.storage.state_db`; a running
59/// server holding that lock makes the caller fail before reaching this
60/// function.
61pub fn install_bundle(
62    config: &Config,
63    label: &str,
64    bytes: &[u8],
65    guard: &StateDirectoryLock,
66) -> Result<InstallResult> {
67    // The guard must protect the directory this configuration names, so a
68    // mismatched guard can never authorize writes elsewhere.
69    let state_dir = std::fs::canonicalize(&config.storage.state_db).map_err(|e| {
70        CoreError::Config(format!(
71            "cannot resolve state directory {}: {e}",
72            config.storage.state_db.display()
73        ))
74    })?;
75    if guard.state_dir() != state_dir {
76        return Err(CoreError::Config(format!(
77            "writer guard protects state directory {} but the configuration uses {}",
78            guard.state_dir().display(),
79            state_dir.display()
80        )));
81    }
82
83    // Target resolution (S5): the selected CA destination, nothing else.
84    let destination = config.bundle_destination(label)?;
85
86    // Authentication always runs — the demo serving flag never relaxes it.
87    let bundle = Bundle::from_bytes(bytes)?;
88    let now = std::time::SystemTime::now()
89        .duration_since(std::time::UNIX_EPOCH)
90        .map_err(|e| CoreError::Config(e.to_string()))?
91        .as_secs();
92    let verification = authenticate_bundle(&bundle, &config.storage, now)?;
93    validate_serving_profile(&bundle)?;
94
95    // Strict state open: a missing or incomplete state directory is an
96    // operator error (init-state / restore), never a fresh timeline.
97    let state_path = config.storage.state_db.join("state.json");
98    let mut store = StateStore::open(&state_path)?;
99    store.check_rollback(&bundle)?;
100    store.check_continuity(&bundle)?;
101
102    info!(
103        target: "audit",
104        event = "bundle_install",
105        ca = label,
106        producer = %bundle.manifest.producer_id,
107        epoch = bundle.manifest.ca_scopes.first().map(|s| s.epoch).unwrap_or(0),
108        signer = %verification.signer_sha256,
109        destination = %destination.display(),
110        "authenticated bundle installation starting"
111    );
112
113    // Stage: single-label installation preserves other labels' committed
114    // snapshots; only this label's reference is replaced.
115    let mut candidate = store.transaction();
116    candidate.advance_from_bundle(&bundle)?;
117    candidate.snapshot(label, &bundle)?;
118
119    // The descriptor commit is the installation commit point. A
120    // DurabilityUncertain error here is indeterminate by contract: the
121    // operator must stop and reopen state.
122    store.commit(candidate)?;
123
124    // Post-commit publication of the configured convenience path. Failure
125    // here must not be reported as an uncommitted rejection.
126    let publication_warning = match write_atomic(&destination, bytes) {
127        Ok(()) => None,
128        Err(error) => {
129            let warning = format!(
130                "installation for CA '{label}' is committed, but publishing the configured \
131                 bundle path {} failed: {error}. Startup recovers the committed snapshot; \
132                 retry this import to repair the path.",
133                destination.display()
134            );
135            info!(
136                target: "audit",
137                event = "bundle_install_publication_warning",
138                ca = label,
139                "committed installation with unpublished convenience path"
140            );
141            Some(warning)
142        }
143    };
144
145    info!(
146        target: "audit",
147        event = "bundle_install_committed",
148        ca = label,
149        epoch = bundle.manifest.ca_scopes.first().map(|s| s.epoch).unwrap_or(0),
150        "authenticated bundle installation committed"
151    );
152
153    Ok(InstallResult {
154        destination,
155        publication_warning,
156    })
157}
158
159#[cfg(test)]
160mod fault_tests {
161    //! State-owned fault injection at the four §S5 commit-order points.
162    //!
163    //! These unit tests run in-crate so the thread-local injection in
164    //! `storage::fault_injection` is compiled in; the integration suite in
165    //! `tests/installation.rs` covers the same order with natural
166    //! filesystem faults. Call indices within one `install_bundle` of a
167    //! fresh bundle: 0 = snapshot write, 1 = descriptor commit,
168    //! 2 = alias publication.
169
170    use super::*;
171    use crate::storage::fault_injection::{self, FaultMode};
172    use ahu::{
173        BundleBuilder, BundleType, CaScope, Completeness, Continuity, Integrity, Manifest,
174        ResponderId, ResponderIdType, Window,
175    };
176    use der::{Decode, Encode};
177    use p256::ecdsa::SigningKey;
178    use uuid::Uuid;
179
180    fn now() -> u64 {
181        std::time::SystemTime::now()
182            .duration_since(std::time::UNIX_EPOCH)
183            .unwrap()
184            .as_secs()
185    }
186
187    fn manifest(producer: &str, epoch: u64, ikh: [u8; 32]) -> Manifest {
188        Manifest {
189            format_version: 1,
190            bundle_id: Uuid::nil(),
191            producer_id: producer.into(),
192            created_at: now() - 1,
193            bundle_type: BundleType::Full,
194            ca_scopes: vec![CaScope {
195                hash_algorithm: vec![0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01],
196                issuer_name_hash: vec![0xAA; 32],
197                issuer_key_hash: ikh.to_vec(),
198                epoch,
199                responder_id: ResponderId {
200                    id_type: ResponderIdType::ByKey,
201                    value: vec![0xCC; 20],
202                },
203                responder_chain: None,
204                signature_algorithm: vec![0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x04, 0x03, 0x02],
205                completeness: Completeness::Partial,
206            }],
207            window: Window {
208                produced_at: now() - 1,
209                this_update_min: now() - 1,
210                next_update_min: now() + 3600,
211                next_update_max: now() + 3600,
212            },
213            integrity: Integrity {
214                index_digest: [0; 32],
215                data_digest: [0; 32],
216            },
217            entry_count: 0,
218            continuity: Continuity {
219                prev_manifest_digest: None,
220                base_manifest_digest: None,
221                chain_length: 0,
222            },
223            shard: None,
224            compression: None,
225            extensions: None,
226        }
227    }
228
229    struct Fixture {
230        /// Kept alive for the fixture's lifetime; never read directly.
231        _dir: tempfile::TempDir,
232        seal_key: SigningKey,
233        seal_cert: Vec<u8>,
234        config: Config,
235    }
236
237    impl Fixture {
238        fn new() -> Self {
239            let dir = tempfile::tempdir().unwrap();
240            let now = now();
241            let seal_key = SigningKey::from_bytes((&[7u8; 32]).into()).unwrap();
242            let mut cert = x509_cert::Certificate::from_der(
243                &hoike_sign::generate_seal_cert(&seal_key).unwrap(),
244            )
245            .unwrap();
246            let time = |seconds| {
247                x509_cert::time::Time::UtcTime(
248                    der::asn1::UtcTime::from_unix_duration(std::time::Duration::from_secs(seconds))
249                        .unwrap(),
250                )
251            };
252            cert.tbs_certificate.validity = x509_cert::time::Validity {
253                not_before: time(now - 60),
254                not_after: time(now + 3600),
255            };
256            use p256::ecdsa::signature::Signer;
257            let sig: p256::ecdsa::DerSignature =
258                seal_key.sign(&cert.tbs_certificate.to_der().unwrap());
259            cert.signature = der::asn1::BitString::from_bytes(sig.as_bytes()).unwrap();
260            let seal_cert = cert.to_der().unwrap();
261            std::fs::write(dir.path().join("signer.der"), &seal_cert).unwrap();
262
263            let config_path = dir.path().join("hoike.toml");
264            std::fs::write(
265                &config_path,
266                format!(
267                    "[server]\nmode = 'edge'\n[storage]\nbundle_dir = '{0}/bundles'\nstate_db = \
268                     '{0}/state'\nseal_signer_pins = ['{0}/signer.der']\n[[ca]]\nlabel = 'a'\n",
269                    dir.path().display()
270                ),
271            )
272            .unwrap();
273            let config = Config::from_file(&config_path).unwrap();
274            StateStore::initialize(&config.storage.state_db.join("state.json")).unwrap();
275            Self {
276                _dir: dir,
277                seal_key,
278                seal_cert,
279                config,
280            }
281        }
282
283        fn bundle(&self, epoch: u64) -> Vec<u8> {
284            let seal_key = hoike_sign::SealKey::EcdsaP256(self.seal_key.clone());
285            let seal_cert = self.seal_cert.clone();
286            let mut builder = BundleBuilder::new(manifest("fault-test", epoch, [0xBB; 32]));
287            builder.add_entry([epoch as u8; 32], format!("response-{epoch}").into_bytes());
288            builder
289                .build(move |m| {
290                    hoike_sign::create_cms_seal(m, &seal_key, &seal_cert)
291                        .map_err(|e| ahu::AhuError::SealInvalid(e.to_string()))
292                })
293                .unwrap()
294        }
295
296        fn install(&self, bytes: &[u8]) -> Result<InstallResult> {
297            let guard = StateDirectoryLock::acquire(&self.config.storage.state_db).unwrap();
298            install_bundle(&self.config, "a", bytes, &guard)
299        }
300
301        fn state_bytes(&self) -> Vec<u8> {
302            std::fs::read(self.config.storage.state_db.join("state.json")).unwrap()
303        }
304
305        fn destination_bytes(&self) -> Vec<u8> {
306            std::fs::read(self.config.storage.bundle_dir.join("a.ahu")).unwrap()
307        }
308
309        fn high_water(&self) -> Option<u64> {
310            StateStore::open(&self.config.storage.state_db.join("state.json"))
311                .unwrap()
312                .get_high_water("fault-test", &hex::encode([0xBB; 32]))
313        }
314    }
315
316    #[test]
317    fn snapshot_write_failure_preserves_committed_generation() {
318        let f = Fixture::new();
319        let first = f.bundle(1);
320        f.install(&first).unwrap();
321        let (old_state, old_destination) = (f.state_bytes(), f.destination_bytes());
322
323        fault_injection::set(0, FaultMode::BeforeRename);
324        let err = f.install(&f.bundle(2)).unwrap_err();
325        fault_injection::clear();
326        assert!(!err.to_string().contains("durability uncertain"), "{err}");
327        assert_eq!(f.state_bytes(), old_state);
328        assert_eq!(f.destination_bytes(), old_destination);
329        assert_eq!(f.high_water(), Some(1));
330    }
331
332    #[test]
333    fn descriptor_pre_rename_failure_preserves_committed_generation() {
334        let f = Fixture::new();
335        let first = f.bundle(1);
336        f.install(&first).unwrap();
337        let (old_state, old_destination) = (f.state_bytes(), f.destination_bytes());
338
339        // Call 1 is the descriptor commit; fail it after the temporary
340        // descriptor is written but before the rename.
341        fault_injection::set(1, FaultMode::BeforeRename);
342        let err = f.install(&f.bundle(2)).unwrap_err();
343        fault_injection::clear();
344        assert!(
345            !matches!(err, CoreError::DurabilityUncertain { .. }),
346            "a pre-rename failure is a plain failure: {err}"
347        );
348        assert_eq!(f.state_bytes(), old_state, "old marks must survive");
349        assert_eq!(f.destination_bytes(), old_destination);
350        assert_eq!(f.high_water(), Some(1));
351    }
352
353    #[test]
354    fn descriptor_post_rename_fsync_failure_is_indeterminate_not_rollback() {
355        let f = Fixture::new();
356        let first = f.bundle(1);
357        f.install(&first).unwrap();
358        let old_destination = f.destination_bytes();
359        let second = f.bundle(2);
360
361        fault_injection::set(1, FaultMode::DirFsyncAfterRename);
362        let err = f.install(&second).unwrap_err();
363        fault_injection::clear();
364
365        // The typed error, instructing the operator to stop and reopen —
366        // never a claim that nothing changed.
367        assert!(
368            matches!(err, CoreError::DurabilityUncertain { .. }),
369            "post-rename directory-fsync failure must be DurabilityUncertain: {err}"
370        );
371        assert!(err.to_string().contains("reopen"), "{err}");
372
373        // After reopen, state and snapshots are coherent: the rename did
374        // happen, so the new generation is committed, and nothing claimed a
375        // rollback or undid marks.
376        assert_eq!(f.high_water(), Some(2));
377        let reopened = StateStore::open(&f.config.storage.state_db.join("state.json")).unwrap();
378        assert!(
379            reopened
380                .active_bundles()
381                .get("a")
382                .is_some_and(|p| p.exists()),
383            "the committed snapshot must be present and referenced"
384        );
385        // The convenience path was never reached: it still holds the old
386        // generation, which startup recovers from (see the integration
387        // suite for the full recovery reload).
388        assert_eq!(f.destination_bytes(), old_destination);
389    }
390
391    #[test]
392    fn alias_publication_failure_returns_committed_warning() {
393        let f = Fixture::new();
394        let first = f.bundle(1);
395        f.install(&first).unwrap();
396
397        // Call 2 is the post-commit alias publication.
398        fault_injection::set(2, FaultMode::BeforeRename);
399        let committed = f.install(&f.bundle(2)).unwrap();
400        fault_injection::clear();
401
402        assert!(
403            committed.publication_warning.is_some(),
404            "a post-commit publication failure is a committed warning"
405        );
406        assert_eq!(f.high_water(), Some(2), "the installation is committed");
407        assert_eq!(
408            f.destination_bytes(),
409            first,
410            "the unpublished path keeps the previous generation"
411        );
412    }
413}