Skip to main content

clm_rust_core/
hash_config.rs

1#![allow(unused_imports)]
2use super::*;
3
4/// Configuration policy for hash algorithm selection and collision handling.
5///
6/// This struct governs:
7/// - Which algorithm is used for **new** content (`active_algorithm`)
8/// - How many collisions trigger an automatic upgrade (`collision_threshold`)
9/// - The order of fallback algorithms if the active one is compromised
10///
11/// The config is stored in a global `OnceLock` and can be loaded from a
12/// configuration file or environment variable at startup.
13#[derive(Debug, Clone)]
14pub struct HashConfig {
15    /// Algorithm prefix for new content (e.g. `"blake3:"`, `"sha256:"`).
16    pub active_algorithm: &'static str,
17    /// Number of collisions before triggering an upgrade.
18    pub collision_threshold: u32,
19    /// Ordered list of fallback algorithm prefixes.
20    /// If the active algorithm is compromised, the first available fallback
21    /// becomes the new active algorithm.
22    pub fallback_order: Vec<&'static str>,
23}
24
25impl Default for HashConfig {
26    fn default() -> Self {
27        Self {
28            active_algorithm: DEFAULT_HASH_PREFIX,
29            collision_threshold: DEFAULT_COLLISION_THRESHOLD,
30            fallback_order: vec![DEFAULT_HASH_PREFIX, SHA256_HASH_PREFIX],
31        }
32    }
33}
34
35pub(super) fn normalize_prefix(value: &str) -> &'static str {
36    let normalized = value.trim().trim_end_matches(':').to_lowercase();
37    Box::leak(format!("{}:", normalized).into_boxed_str())
38}
39
40impl HashConfig {
41    /// Load hash configuration from environment variables.
42    ///
43    /// Checks in order:
44    /// 1. `CLM_HASH_CONFIG`: `active_algorithm|collision_threshold|fallback1,fallback2,...`
45    ///    Example: `blake3:|2|blake3:,sha256:`
46    /// 2. `CLM_HASH_ALGO` / `MCARD_HASH_ALGORITHM`: simple string override (e.g. `blake3` or `sha256`)
47    ///
48    /// If unset, returns the central BLAKE3 default. Unsupported configured names are preserved;
49    /// write operations reject them through `raw_hash_bytes_for` instead of silently downgrading.
50    pub fn from_env() -> Self {
51        let configured = std::env::var("CLM_HASH_CONFIG")
52            .ok()
53            .filter(|raw| !raw.trim().is_empty())
54            .map(|raw| Self::parse_config(&raw))
55            .or_else(|| {
56                std::env::var("CLM_HASH_ALGO")
57                    .or_else(|_| std::env::var("MCARD_HASH_ALGORITHM"))
58                    .ok()
59                    .filter(|algo| !algo.trim().is_empty())
60                    .map(|algo| {
61                        let prefix = normalize_prefix(&algo);
62                        Self {
63                            active_algorithm: prefix,
64                            collision_threshold: DEFAULT_COLLISION_THRESHOLD,
65                            fallback_order: vec![prefix, SHA256_HASH_PREFIX],
66                        }
67                    })
68            });
69
70        let Some(config) = configured else {
71            return Self::default();
72        };
73        config
74    }
75
76    pub(super) fn parse_config(raw: &str) -> Self {
77        let parts: Vec<&str> = raw.splitn(3, '|').collect();
78        if parts.len() < 2 {
79            return Self::default();
80        }
81        let active = if parts[0].is_empty() {
82            DEFAULT_HASH_PREFIX
83        } else {
84            normalize_prefix(parts[0])
85        };
86        let threshold = parts[1].parse::<u32>().unwrap_or(DEFAULT_COLLISION_THRESHOLD);
87        let fallbacks: Vec<&'static str> = if parts.len() == 3 && !parts[2].is_empty() {
88            parts[2]
89                .split(',')
90                .map(|s| if s.is_empty() { DEFAULT_HASH_PREFIX } else { normalize_prefix(s) })
91                .collect()
92        } else {
93            vec![active]
94        };
95        Self {
96            active_algorithm: active,
97            collision_threshold: threshold,
98            fallback_order: fallbacks,
99        }
100    }
101}
102
103pub(super) fn global_config() -> &'static HashConfig {
104    static CONFIG: OnceLock<HashConfig> = OnceLock::new();
105    CONFIG.get_or_init(HashConfig::from_env)
106}
107
108/// Get the current hash configuration.
109pub fn config() -> &'static HashConfig {
110    global_config()
111}
112
113// ── Prefix-based dispatch (Step 3) ────────────────────────────────────────
114
115/// Extract the algorithm prefix from a stored hash string.
116///
117/// Returns `Some(prefix)` if the string contains a `:` separator,
118/// `None` if there is no prefix (assumed to be the default algorithm).
119pub fn extract_prefix(prefixed: &str) -> Option<&str> {
120    prefixed.find(':').map(|pos| &prefixed[..=pos])
121}
122
123/// Verify a stored hash against content by dispatching to the correct provider.
124///
125/// This function parses the algorithm prefix from `stored_hash`, looks up
126/// the corresponding provider in the registry, and checks whether the
127/// content matches.
128///
129/// Returns `Ok(())` if the hash matches, `Err(message)` if it doesn't
130/// or the provider is unknown.
131pub fn verify_hash(stored_hash: &str, content: &[u8]) -> Result<(), String> {
132    let prefix = extract_prefix(stored_hash).unwrap_or(DEFAULT_HASH_PREFIX);
133    let reg = global_registry().lock().unwrap();
134    let provider = reg.get(prefix).ok_or_else(|| {
135        format!("Unknown hash algorithm prefix: {} (registered: {:?})", prefix, reg.algorithms())
136    })?;
137    let computed = provider.hash(content);
138    let stored_raw = strip_prefix(stored_hash);
139    if computed == stored_raw {
140        Ok(())
141    } else {
142        Err(format!(
143            "Hash mismatch: expected {}..., got {}...",
144            &stored_raw[..stored_raw.len().min(16)],
145            &computed[..computed.len().min(16)]
146        ))
147    }
148}
149
150// ── Collision detection (Step 5) ──────────────────────────────────────────
151
152/// Result of a collision check.
153#[derive(Debug, Clone, PartialEq, Eq)]
154pub enum CollisionCheckResult {
155    /// No collision — the hash is unique.
156    NoCollision,
157    /// Collision detected — the same hash already exists with different content.
158    Collision { hash: String, collision_count: u32 },
159    /// Threshold exceeded — the active algorithm should be upgraded.
160    ThresholdExceeded {
161        hash: String,
162        collision_count: u32,
163        recommended_algorithm: &'static str,
164    },
165}
166
167/// Check whether a hash collision has occurred and whether the threshold
168/// for algorithm upgrade has been exceeded.
169///
170/// Callers should invoke this *before* inserting a new card into the database.
171/// If `existing_content` is `Some` and differs from `new_content`, a collision
172/// is recorded. When the collision count for the active algorithm reaches
173/// `config().collision_threshold`, a `ThresholdExceeded` result is returned
174/// with the recommended fallback algorithm.
175pub fn check_collision(
176    hash: &str,
177    new_content: &[u8],
178    existing_content: Option<&[u8]>,
179    collision_count: u32,
180) -> CollisionCheckResult {
181    match existing_content {
182        None => CollisionCheckResult::NoCollision,
183        Some(existing) if existing == new_content => CollisionCheckResult::NoCollision,
184        Some(_) => {
185            let count = collision_count + 1;
186            let cfg = config();
187            if count >= cfg.collision_threshold {
188                // Find the first fallback that isn't the current active algorithm
189                let recommended = cfg
190                    .fallback_order
191                    .iter()
192                    .find(|&&algo| algo != cfg.active_algorithm)
193                    .copied()
194                    .unwrap_or(cfg.active_algorithm);
195                CollisionCheckResult::ThresholdExceeded {
196                    hash: hash.to_string(),
197                    collision_count: count,
198                    recommended_algorithm: recommended,
199                }
200            } else {
201                CollisionCheckResult::Collision {
202                    hash: hash.to_string(),
203                    collision_count: count,
204                }
205            }
206        }
207    }
208}
209
210// ── Convenience functions (delegate to the active provider) ──────────────
211
212/// Compute the raw hex digest of bytes using the active provider (no prefix).
213///
214/// This is the canonical "common function signature" shared with Python's
215/// `clm_hash_string`: `fn(content: &[u8]) -> String`.
216pub fn raw_hash_bytes(content: &[u8]) -> String {
217    let reg = global_registry().lock().unwrap();
218    reg.active(config().active_algorithm).hash(content)
219}
220
221/// Compute a raw digest with an explicit algorithm, failing instead of substituting a default.
222pub fn raw_hash_bytes_for(algorithm: &str, content: &[u8]) -> Result<String, String> {
223    let normalized = algorithm.trim().trim_end_matches(':').to_lowercase();
224    let prefix = format!("{}:", normalized);
225    let reg = global_registry().lock().map_err(|e| e.to_string())?;
226    let provider = reg.get(&prefix).ok_or_else(|| {
227        format!("Unsupported hash algorithm: {} (registered: {:?})", normalized, reg.algorithms())
228    })?;
229    Ok(provider.hash(content))
230}
231
232/// Compute the raw hex digest of a string using the active provider (no prefix).
233pub fn raw_hash_string(s: &str) -> String {
234    raw_hash_bytes(s.as_bytes())
235}
236
237/// Compute the raw digest as a 32-byte array using the active provider.
238///
239/// Used by Merkle tree and type lattice code that needs the raw bytes
240/// rather than a hex string.
241pub fn raw_hash_bytes_32(content: &[u8]) -> [u8; 32] {
242    let reg = global_registry().lock().unwrap();
243    reg.active(config().active_algorithm).hash_bytes(content)
244}
245
246/// Compute the prefixed hash of bytes (e.g. `"sha256:<hex>"`).
247pub fn prefixed_hash_bytes(content: &[u8]) -> String {
248    let reg = global_registry().lock().unwrap();
249    let provider = reg.active(config().active_algorithm);
250    format!("{}{}", provider.prefix(), provider.hash(content))
251}
252
253/// Compute the prefixed hash of a string (e.g. `"sha256:<hex>"`).
254pub fn prefixed_hash_string(s: &str) -> String {
255    prefixed_hash_bytes(s.as_bytes())
256}
257
258/// Prepend the active algorithm prefix to an already-computed raw hex digest.
259pub fn prefixed(raw_hex: &str) -> String {
260    format!("{}{}", config().active_algorithm, raw_hex)
261}
262
263/// Strip a known algorithm prefix from a hash string.
264///
265/// If the hash starts with a known algorithm prefix (or any `<algo>:` pattern),
266/// the unprefixed hex is returned. Otherwise the input is returned as-is.
267pub fn strip_prefix(prefixed: &str) -> &str {
268    // Try the active algorithm prefix first
269    let active = config().active_algorithm;
270    if let Some(rest) = prefixed.strip_prefix(active) {
271        return rest;
272    }
273    // Try the default prefix
274    if let Some(rest) = prefixed.strip_prefix(DEFAULT_HASH_PREFIX) {
275        return rest;
276    }
277    // Generic fallback: strip any `<algo>:` prefix
278    if let Some(pos) = prefixed.find(':')
279        && pos + 1 < prefixed.len() {
280            return &prefixed[pos + 1..];
281        }
282    prefixed
283}
284
285/// Returns the default hash provider (currently `Blake3Provider`).
286///
287/// Kept for backward compatibility — prefer `raw_hash_bytes` / `raw_hash_string`.
288pub fn default_provider() -> impl HashProvider {
289    Blake3Provider
290}
291
292// ── Content-equivalence operator (Gap 2) ──────────────────────────────────
293
294/// Check whether two hashes point to the same content in the CAS.
295///
296/// This is the Rust equivalent of the shell `clm_content_equivalent` operator.
297/// Two hashes generated by different algorithms (e.g. `sha256:abc` and
298/// `sha512:def`) will never match as strings, but they may point to the same
299/// underlying content. This function resolves both hashes to their stored
300/// content and compares the raw bytes.
301///
302/// Returns `Ok(true)` if both hashes exist and point to identical content,
303/// `Ok(false)` if they differ or one is not found, `Err` on DB error.
304#[cfg(feature = "native")]
305pub fn content_equivalent(
306    conn: &rusqlite::Connection,
307    hash_a: &str,
308    hash_b: &str,
309) -> Result<bool, String> {
310    if hash_a == hash_b {
311        return Ok(true);
312    }
313    let content_a = lookup_content(conn, hash_a);
314    let content_b = lookup_content(conn, hash_b);
315    match (content_a, content_b) {
316        (Some(a), Some(b)) => Ok(a == b),
317        _ => Ok(false),
318    }
319}
320
321/// Resolve a stored row by reference, accepting either the bare digest or a qualified form.
322///
323/// The digest column holds bare hex (DEC-12); references that leave a row are qualified. A
324/// lookup therefore tries the reference as given, then its unprefixed form, so both a legacy
325/// prefixed row and a canonical bare row resolve.
326#[cfg(feature = "native")]
327pub(super) fn lookup_content(conn: &rusqlite::Connection, reference: &str) -> Option<Vec<u8>> {
328    let raw = strip_prefix(reference);
329    let mut candidates = vec![reference];
330    if raw != reference {
331        candidates.push(raw);
332    }
333    for candidate in candidates {
334        if let Ok(content) = conn.query_row(
335            "SELECT content FROM card WHERE hash = ?",
336            rusqlite::params![candidate],
337            |row| row.get::<_, Vec<u8>>(0),
338        ) {
339            return Some(content);
340        }
341    }
342    None
343}
344
345// ── Handle migration lifecycle (Gap 3) ────────────────────────────────────
346
347/// Migrate a handle to use a different hash algorithm.
348///
349/// This is the Rust equivalent of the shell `clm_migrate_handle_hash` operator.
350/// It resolves the handle to its current hash, retrieves the content from the
351/// CAS, computes a new hash under the target algorithm, and transactionally
352/// inserts the new card, records handle history, and updates the handle pointer.
353///
354/// # Arguments
355/// * `conn` - SQLite connection to the content_memory database.
356/// * `handle` - The handle name to migrate (e.g. `"test:migration_handle"`).
357/// * `target_algo` - Target algorithm prefix (e.g. `"sha256:"`, `"custom-1024:"`).
358///   Must be a registered provider.
359///
360/// Returns `Ok(new_hash)` on success, `Err(message)` on failure.
361#[cfg(feature = "native")]
362pub fn migrate_handle_hash(
363    conn: &mut rusqlite::Connection,
364    handle: &str,
365    target_algo: &str,
366) -> Result<String, String> {
367    // Validate target algorithm is registered
368    {
369        let reg = global_registry().lock().unwrap();
370        if reg.get(target_algo).is_none() {
371            return Err(format!(
372                "Unsupported target algorithm: '{}' (registered: {:?})",
373                target_algo,
374                reg.algorithms()
375            ));
376        }
377    }
378
379    // 1. Resolve the handle to its current, possibly-qualified reference.
380    let current_hash: String = conn
381        .query_row(
382            "SELECT current_hash FROM handle_registry WHERE handle = ?",
383            rusqlite::params![handle],
384            |row| row.get(0),
385        )
386        .map_err(|_| format!("Handle '{}' not found in handle_registry", handle))?;
387
388    // 2. Retrieve the exact existing content preimage.
389    let content: Vec<u8> = lookup_content(conn, &current_hash)
390        .ok_or_else(|| format!("Content not found in CAS for hash '{}'", current_hash))?;
391
392    // 3. Create a fresh self-verifying record under the requested provider.
393    let now_utc = chrono::Utc::now().to_rfc3339();
394    let record = crate::layer0::mcard_record::MCardRecord::create_at(
395        &content,
396        Some(target_algo),
397        Some(&now_utc),
398        "UTC",
399    )?;
400    if !matches!(
401        crate::layer0::mcard_record::verify_record(&record),
402        crate::layer0::mcard_record::RecordVerification::DeclaredOk { .. }
403    ) {
404        return Err("hash migration produced an invalid self-verifying record".to_string());
405    }
406    let new_hash = format!("{}{}", target_algo.trim_end_matches(':').to_lowercase() + ":", record.hash);
407
408    // 4. Transactional update with retry for WAL lock contention.
409
410    let max_attempts = 3;
411    let mut last_err = String::new();
412    for attempt in 0..max_attempts {
413        let tx = match conn.transaction() {
414            Ok(tx) => tx,
415            Err(e) => {
416                last_err = e.to_string();
417                std::thread::sleep(std::time::Duration::from_millis(200));
418                continue;
419            }
420        };
421        let result = (|| {
422            tx.execute(
423                "INSERT OR IGNORE INTO card (hash, content, g_time) VALUES (?, ?, ?)",
424                rusqlite::params![&record.hash, &record.content, &record.g_time],
425            )
426            .map_err(|e| e.to_string())?;
427            tx.execute(
428                "INSERT INTO handle_history (handle, previous_hash, changed_at) VALUES (?, ?, ?)",
429                rusqlite::params![handle, &current_hash, &now_utc],
430            )
431            .map_err(|e| e.to_string())?;
432            tx.execute(
433                "UPDATE handle_registry SET current_hash = ?, updated_at = ? WHERE handle = ?",
434                rusqlite::params![&new_hash, &now_utc, handle],
435            )
436            .map_err(|e| e.to_string())?;
437            tx.commit().map_err(|e| e.to_string())
438        })();
439
440        match result {
441            Ok(()) => return Ok(new_hash),
442            Err(e) => {
443                last_err = e;
444                if attempt + 1 < max_attempts {
445                    std::thread::sleep(std::time::Duration::from_millis(200));
446                }
447            }
448        }
449    }
450
451    Err(format!("Transaction failed after {} attempts: {}", max_attempts, last_err))
452}
453