Skip to main content

hoike_core/
state.rs

1use std::collections::HashMap;
2use std::path::{Path, PathBuf};
3
4use serde::{Deserialize, Serialize};
5use sha2::{Digest, Sha256};
6use tracing::info;
7
8use crate::error::{CoreError, Result};
9use ahu::Bundle;
10
11/// Maximum allowed epoch jump from the current high-water mark.
12/// Prevents a poisoned bundle with epoch = u64::MAX from permanently
13/// locking out a CA. Kept as defense-in-depth even with CMS seal
14/// verification, since seal trust-anchor enforcement is optional.
15pub const MAX_EPOCH_JUMP: u64 = 10_000;
16
17#[derive(Debug, Clone, Serialize, Deserialize, Default)]
18struct PersistedState {
19    high_water_marks: HashMap<String, u64>,
20    manifest_digests: HashMap<String, String>,
21    /// Immutable bundle snapshots committed with the rollback marks.
22    #[serde(default)]
23    active_bundles: HashMap<String, PathBuf>,
24}
25
26impl PersistedState {
27    fn make_key(producer_id: &str, issuer_key_hash_hex: &str) -> String {
28        format!("{producer_id}:{issuer_key_hash_hex}")
29    }
30}
31
32#[derive(Clone)]
33pub struct StateStore {
34    path: PathBuf,
35    state: PersistedState,
36    staged: bool,
37}
38
39impl StateStore {
40    /// Open existing state, strictly (F04).
41    ///
42    /// Missing or malformed state is an error, never a silently fresh
43    /// timeline: forgetting recorded high-water marks would let an older
44    /// bundle be served again. Valid legacy JSON is preserved. Committed
45    /// snapshots must exist, match their content digest, and carry rollback
46    /// marks — incomplete committed state is a recovery failure.
47    pub fn open(path: &Path) -> Result<Self> {
48        let contents = std::fs::read_to_string(path).map_err(|e| {
49            CoreError::StateStore(format!(
50                "cannot open state file {}: {e}. State is never created implicitly; \
51                 run `hoike init-state` to initialize a new state directory, or restore \
52                 the state file together with its committed snapshots",
53                path.display()
54            ))
55        })?;
56        let state: PersistedState = serde_json::from_str(&contents).map_err(|e| {
57            CoreError::StateStore(format!(
58                "failed to parse state file {}: {e}. Restore the state directory from \
59                 backup; this release has no automatic recovery and no reset escape hatch",
60                path.display()
61            ))
62        })?;
63        validate_persisted(&state, path)?;
64        Ok(StateStore {
65            path: path.to_path_buf(),
66            state,
67            staged: false,
68        })
69    }
70
71    /// Explicitly initialize a fresh state directory (F04).
72    ///
73    /// Initialization is the operator's acknowledgment that this directory is
74    /// new. It refuses an existing state file and refuses a directory holding
75    /// any recovery material (snapshots, cookies, unknown files) so a partial
76    /// restore can never be silently reset. Only the writer lock file is
77    /// ignored when checking emptiness. Creating the directory does not by
78    /// itself authorize resetting it.
79    pub fn initialize(path: &Path) -> Result<Self> {
80        if path.exists() {
81            return Err(CoreError::StateStore(format!(
82                "refusing to initialize {}: state file already exists — existing state is \
83                 never reset; restore marks and snapshots together to recover",
84                path.display()
85            )));
86        }
87        let dir = path
88            .parent()
89            .filter(|p| !p.as_os_str().is_empty())
90            .unwrap_or(Path::new("."));
91        if dir.exists() {
92            // Any content besides the writer lock file is recovery material:
93            // a partial restore must never be silently reset.
94            let entries = std::fs::read_dir(dir).map_err(|e| {
95                CoreError::StateStore(format!(
96                    "failed to inspect state directory {}: {e}",
97                    dir.display()
98                ))
99            })?;
100            for entry in entries {
101                let entry = entry.map_err(|e| {
102                    CoreError::StateStore(format!(
103                        "failed to inspect state directory {}: {e}",
104                        dir.display()
105                    ))
106                })?;
107                if entry.file_name() != crate::storage::WRITER_LOCK_FILE {
108                    return Err(CoreError::StateStore(format!(
109                        "refusing to initialize state in {}: directory already contains \
110                         '{}' — restore state and recovery material together instead of \
111                         re-initializing",
112                        dir.display(),
113                        entry.file_name().to_string_lossy()
114                    )));
115                }
116            }
117        } else {
118            std::fs::create_dir_all(dir).map_err(|e| {
119                CoreError::StateStore(format!(
120                    "failed to create state directory {}: {e}",
121                    dir.display()
122                ))
123            })?;
124        }
125        let store = StateStore {
126            path: path.to_path_buf(),
127            state: PersistedState::default(),
128            staged: false,
129        };
130        store.persist()?;
131        info!(path = %path.display(), "initialized fresh state directory");
132        Ok(store)
133    }
134
135    pub fn get_high_water(&self, producer_id: &str, issuer_key_hash_hex: &str) -> Option<u64> {
136        let key = PersistedState::make_key(producer_id, issuer_key_hash_hex);
137        self.state.high_water_marks.get(&key).copied()
138    }
139
140    pub fn get_manifest_digest(
141        &self,
142        producer_id: &str,
143        issuer_key_hash_hex: &str,
144    ) -> Option<[u8; 32]> {
145        let key = PersistedState::make_key(producer_id, issuer_key_hash_hex);
146        self.state.manifest_digests.get(&key).and_then(|hex_str| {
147            let bytes = hex::decode(hex_str).ok()?;
148            <[u8; 32]>::try_from(bytes.as_slice()).ok()
149        })
150    }
151
152    pub fn advance(
153        &mut self,
154        producer_id: &str,
155        issuer_key_hash_hex: &str,
156        epoch: u64,
157        manifest_digest: [u8; 32],
158    ) -> Result<()> {
159        let mut next = self.clone();
160        let key = PersistedState::make_key(producer_id, issuer_key_hash_hex);
161        let current = next.state.high_water_marks.get(&key).copied();
162        if current.is_none_or(|current| epoch > current) {
163            next.state.high_water_marks.insert(key.clone(), epoch);
164            next.state
165                .manifest_digests
166                .insert(key, hex::encode(manifest_digest));
167            if !self.staged {
168                next.persist()?;
169            }
170            self.state = next.state;
171        }
172        Ok(())
173    }
174
175    /// Stage a transaction candidate against this store (design §S5).
176    ///
177    /// A single-label installation stages into the candidate while
178    /// **preserving** other labels' committed snapshots. Callers performing
179    /// a full working-set reload must call [`Self::clear_active_bundles`]
180    /// explicitly, so the reload builds a replacement working set instead of
181    /// merging into whatever was committed before.
182    pub(crate) fn transaction(&self) -> Self {
183        let mut candidate = self.clone();
184        candidate.staged = true;
185        candidate
186    }
187
188    /// Drop all committed snapshot references: a full reload replaces the
189    /// whole working set rather than merging into it.
190    pub(crate) fn clear_active_bundles(&mut self) {
191        self.state.active_bundles.clear();
192    }
193
194    pub(crate) fn commit(&mut self, candidate: Self) -> Result<()> {
195        candidate.persist()?;
196        self.state = candidate.state;
197        // Only collect after the new descriptor is durable. In-flight requests
198        // hold heap bundles; an unlinked prior snapshot cannot change their data.
199        let dir = self
200            .path
201            .parent()
202            .unwrap_or(Path::new("."))
203            .join("generations");
204        if let Ok(files) = std::fs::read_dir(&dir) {
205            for file in files.flatten() {
206                let path = file.path();
207                let generated = path.extension().is_some_and(|ext| ext == "ahu")
208                    && path
209                        .file_stem()
210                        .and_then(|s| s.to_str())
211                        .is_some_and(|s| s.len() == 64 && s.bytes().all(|b| b.is_ascii_hexdigit()));
212                if generated
213                    && !self
214                        .state
215                        .active_bundles
216                        .values()
217                        .any(|active| active == &path)
218                {
219                    if let Err(error) = std::fs::remove_file(&path) {
220                        tracing::warn!(%error, "could not remove obsolete generation snapshot");
221                    }
222                }
223            }
224        }
225        Ok(())
226    }
227
228    pub(crate) fn active_bundles(&self) -> &HashMap<String, PathBuf> {
229        &self.state.active_bundles
230    }
231
232    /// Persist immutable content before the descriptor that references it.
233    pub(crate) fn snapshot(&mut self, label: &str, bundle: &Bundle) -> Result<()> {
234        let bytes = bundle.to_bytes()?;
235        let digest = hex::encode(Sha256::digest(&bytes));
236        let dir = self
237            .path
238            .parent()
239            .unwrap_or(Path::new("."))
240            .join("generations");
241        std::fs::create_dir_all(&dir)?;
242        let path = dir.join(format!("{digest}.ahu"));
243        // Existing blobs are verified, never trusted solely by their filename.
244        if !path.exists() || std::fs::read(&path)? != bytes {
245            crate::storage::write_atomic(&path, &bytes)?;
246        }
247        self.state.active_bundles.insert(label.to_owned(), path);
248        Ok(())
249    }
250
251    pub fn check_rollback(&self, bundle: &Bundle) -> Result<()> {
252        let producer_id = &bundle.manifest.producer_id;
253        let manifest_digest: [u8; 32] = Sha256::digest(&bundle.manifest_bytes).into();
254        for scope in &bundle.manifest.ca_scopes {
255            let ikh = hex::encode(&scope.issuer_key_hash);
256            if let Some(hw) = self.get_high_water(producer_id, &ikh) {
257                // A strictly older epoch is always a rollback.
258                if scope.epoch < hw {
259                    return Err(CoreError::EpochRollback {
260                        scope: format!("{}:{}", producer_id, &ikh[..16.min(ikh.len())]),
261                        epoch: scope.epoch,
262                        high_water: hw,
263                    });
264                }
265                // Re-loading at the current high-water epoch is legitimate only
266                // when it is the *same* bundle (identical manifest digest) — e.g.
267                // a process restart reloading its own state. A *different* bundle
268                // at the same epoch is a fork/rollback attack and is rejected.
269                if scope.epoch == hw
270                    && self.get_manifest_digest(producer_id, &ikh) != Some(manifest_digest)
271                {
272                    return Err(CoreError::EpochRollback {
273                        scope: format!("{}:{}", producer_id, &ikh[..16.min(ikh.len())]),
274                        epoch: scope.epoch,
275                        high_water: hw,
276                    });
277                }
278                let jump = scope.epoch - hw;
279                if jump > MAX_EPOCH_JUMP {
280                    return Err(CoreError::EpochJumpTooLarge {
281                        scope: format!("{}:{}", producer_id, &ikh[..16.min(ikh.len())]),
282                        epoch: scope.epoch,
283                        high_water: hw,
284                        jump,
285                        max_jump: MAX_EPOCH_JUMP,
286                    });
287                }
288            }
289        }
290        Ok(())
291    }
292
293    pub fn check_continuity(&self, bundle: &Bundle) -> Result<()> {
294        if let Some(prev_digest) = &bundle.manifest.continuity.prev_manifest_digest {
295            let producer_id = &bundle.manifest.producer_id;
296            for scope in &bundle.manifest.ca_scopes {
297                let ikh = hex::encode(&scope.issuer_key_hash);
298                if let Some(recorded) = self.get_manifest_digest(producer_id, &ikh) {
299                    let digest: [u8; 32] = Sha256::digest(&bundle.manifest_bytes).into();
300                    let identical = self.get_high_water(producer_id, &ikh) == Some(scope.epoch)
301                        && digest == recorded;
302                    if !identical && *prev_digest != recorded {
303                        return Err(CoreError::ForkDetected {
304                            scope: format!("{}:{}", producer_id, &ikh[..16.min(ikh.len())]),
305                        });
306                    }
307                }
308            }
309        }
310        Ok(())
311    }
312
313    pub fn advance_from_bundle(&mut self, bundle: &Bundle) -> Result<()> {
314        let mut candidate = self.clone();
315        candidate.staged = true;
316        let digest: [u8; 32] = Sha256::digest(&bundle.manifest_bytes).into();
317        for scope in &bundle.manifest.ca_scopes {
318            candidate.advance(
319                &bundle.manifest.producer_id,
320                &hex::encode(&scope.issuer_key_hash),
321                scope.epoch,
322                digest,
323            )?;
324        }
325        if !self.staged {
326            candidate.persist()?;
327        }
328        self.state = candidate.state;
329        Ok(())
330    }
331
332    fn persist(&self) -> Result<()> {
333        let json = serde_json::to_vec_pretty(&self.state)
334            .map_err(|e| CoreError::StateStore(format!("failed to serialize state: {e}")))?;
335        crate::storage::write_atomic(&self.path, &json)
336    }
337}
338
339/// Validate persisted state before it is trusted (F04).
340///
341/// High-water marks and manifest digests are written as pairs, so a record on
342/// one side without its counterpart is a torn write. Every committed snapshot
343/// must exist, hash to the digest in its filename, and have its scopes covered
344/// by a high-water mark at or above the snapshot's epoch — a missing record
345/// referenced by a committed snapshot is recovery failure, not a new scope.
346fn validate_persisted(state: &PersistedState, path: &Path) -> Result<()> {
347    for (key, digest_hex) in &state.manifest_digests {
348        let decoded = hex::decode(digest_hex).map_err(|e| {
349            CoreError::StateStore(format!(
350                "state file {}: manifest digest for '{key}' is not valid hex: {e}",
351                path.display()
352            ))
353        })?;
354        if decoded.len() != 32 {
355            return Err(CoreError::StateStore(format!(
356                "state file {}: manifest digest for '{key}' has {} bytes, expected 32",
357                path.display(),
358                decoded.len()
359            )));
360        }
361        if !state.high_water_marks.contains_key(key) {
362            return Err(CoreError::StateStore(format!(
363                "state file {}: manifest digest for '{key}' has no high-water record — \
364                 restore marks and snapshots together",
365                path.display()
366            )));
367        }
368    }
369    for key in state.high_water_marks.keys() {
370        if !state.manifest_digests.contains_key(key) {
371            return Err(CoreError::StateStore(format!(
372                "state file {}: high-water mark for '{key}' has no manifest digest record — \
373                 restore marks and snapshots together",
374                path.display()
375            )));
376        }
377    }
378    for (label, snapshot) in &state.active_bundles {
379        let bytes = std::fs::read(snapshot).map_err(|e| {
380            CoreError::StateStore(format!(
381                "committed snapshot for '{label}' is missing: {} ({e}) — restore marks and \
382                 snapshots together; do not re-initialize",
383                snapshot.display()
384            ))
385        })?;
386        let digest_hex = snapshot
387            .file_stem()
388            .and_then(|s| s.to_str())
389            .ok_or_else(|| {
390                CoreError::StateStore(format!(
391                    "committed snapshot for '{label}' has a malformed name: {}",
392                    snapshot.display()
393                ))
394            })?;
395        let expected = hex::decode(digest_hex).map_err(|e| {
396            CoreError::StateStore(format!(
397                "committed snapshot for '{label}' has a non-digest name: {e}"
398            ))
399        })?;
400        let actual: [u8; 32] = Sha256::digest(&bytes).into();
401        if actual.as_slice() != expected.as_slice() {
402            return Err(CoreError::StateStore(format!(
403                "committed snapshot for '{label}' does not match its digest name: {}",
404                snapshot.display()
405            )));
406        }
407        let bundle = Bundle::from_bytes(&bytes).map_err(|e| {
408            CoreError::StateStore(format!(
409                "committed snapshot for '{label}' is unreadable: {e}",
410            ))
411        })?;
412        for scope in &bundle.manifest.ca_scopes {
413            let key = PersistedState::make_key(
414                &bundle.manifest.producer_id,
415                &hex::encode(&scope.issuer_key_hash),
416            );
417            match state.high_water_marks.get(&key) {
418                Some(hw) if *hw >= scope.epoch => {}
419                other => {
420                    return Err(CoreError::StateStore(format!(
421                        "committed snapshot '{label}' records scope at epoch {} with \
422                         high-water {:?} — incomplete committed state requires recovery",
423                        scope.epoch, other
424                    )));
425                }
426            }
427        }
428    }
429    Ok(())
430}