1use 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#[derive(Debug, Clone)]
43pub struct InstallResult {
44 pub destination: PathBuf,
46 pub publication_warning: Option<String>,
50}
51
52pub fn install_bundle(
62 config: &Config,
63 label: &str,
64 bytes: &[u8],
65 guard: &StateDirectoryLock,
66) -> Result<InstallResult> {
67 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 let destination = config.bundle_destination(label)?;
85
86 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 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 let mut candidate = store.transaction();
116 candidate.advance_from_bundle(&bundle)?;
117 candidate.snapshot(label, &bundle)?;
118
119 store.commit(candidate)?;
123
124 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 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 _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 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 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 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 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 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}