use std::hash::{Hash, Hasher};
use std::io::Write;
use std::path::Path;
use sha2::{Digest, Sha256};
use wasmtime::component::Component;
use wasmtime::Engine;
use crate::Error;
pub fn digest(bytes: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(bytes);
hex::encode(hasher.finalize())
}
struct Sha256Hasher(Sha256);
impl Hasher for Sha256Hasher {
fn write(&mut self, bytes: &[u8]) {
self.0.update(bytes);
}
fn finish(&self) -> u64 {
unreachable!("Sha256Hasher is write-only — read the digest via finalize_hex")
}
}
impl Sha256Hasher {
fn finalize_hex(self) -> String {
hex::encode(self.0.finalize())
}
}
pub(crate) fn compat_hash(engine: &Engine) -> String {
let mut hasher = Sha256Hasher(Sha256::new());
engine.precompile_compatibility_hash().hash(&mut hasher);
hasher.finalize_hex()
}
pub(crate) fn is_valid_digest(s: &str) -> bool {
s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}
pub(crate) fn cache_file_name(engine: &Engine, digest: &str) -> String {
format!("{digest}-{}.cwasm", compat_hash(engine))
}
pub(crate) fn load_cwasm(
engine: &Engine,
cache_dir: &Path,
digest: &str,
) -> Result<Component, Error> {
if !is_valid_digest(digest) {
return Err(Error::Corrupt(
"invalid cache digest: expected 64 lowercase hex characters".into(),
));
}
let bytes = std::fs::read(cache_dir.join(cache_file_name(engine, digest)))?;
unsafe { Ok(Component::deserialize(engine, &bytes)?) }
}
pub(crate) fn atomic_write(dir: &Path, dest: &Path, bytes: &[u8]) -> Result<(), Error> {
std::fs::create_dir_all(dir)?;
let mut tmp = tempfile::NamedTempFile::new_in(dir)?;
tmp.write_all(bytes)?;
tmp.as_file().sync_all()?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
tmp.as_file()
.set_permissions(std::fs::Permissions::from_mode(0o644))?;
}
tmp.persist(dest).map_err(std::io::Error::from)?;
Ok(())
}
pub(crate) fn compile(
engine: &Engine,
wasm_bytes: &[u8],
cache_dir: &Path,
) -> Result<(Component, String, bool), Error> {
let digest = digest(wasm_bytes);
let cached = cache_dir.join(cache_file_name(engine, &digest));
if cached.exists() {
match load_cwasm(engine, cache_dir, &digest) {
Ok(component) => return Ok((component, digest, false)),
Err(e) => {
tracing::warn!(
path = %cached.display(),
error = %e,
"stale or corrupt .cwasm cache entry, recompiling"
);
}
}
}
let component = Component::new(engine, wasm_bytes)?;
Ok((component, digest, true))
}
pub(crate) fn persist_cwasm(
component: &Component,
engine: &Engine,
cache_dir: &Path,
digest: &str,
) -> Result<usize, Error> {
let dest = cache_dir.join(cache_file_name(engine, digest));
let serialized = component.serialize()?;
atomic_write(cache_dir, &dest, &serialized)?;
Ok(serialized.len())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sandbox::build_engine;
const TEST_GUEST_WASM: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/tests/fixtures/test_guest.wasm"
));
fn load_or_compile(
engine: &Engine,
wasm_bytes: &[u8],
cache_dir: &Path,
) -> Result<Component, Error> {
let (component, digest, fresh) = compile(engine, wasm_bytes, cache_dir)?;
if fresh {
persist_cwasm(&component, engine, cache_dir, &digest)?;
}
Ok(component)
}
#[test]
fn second_load_hits_the_cwasm_warm_path() {
let engine = build_engine().expect("build engine");
let dir = tempfile::tempdir().expect("tempdir");
let _first = load_or_compile(&engine, TEST_GUEST_WASM, dir.path()).expect("cold compile");
let digest = digest(TEST_GUEST_WASM);
let cwasm_path = dir.path().join(cache_file_name(&engine, &digest));
assert!(cwasm_path.exists());
let before = std::fs::metadata(&cwasm_path).unwrap().modified().unwrap();
let _second = load_or_compile(&engine, TEST_GUEST_WASM, dir.path()).expect("warm load");
let after = std::fs::metadata(&cwasm_path).unwrap().modified().unwrap();
assert_eq!(before, after, "warm load must not rewrite the .cwasm");
let _third = load_cwasm(&engine, dir.path(), &digest).expect("load_cwasm");
}
#[test]
fn recovers_from_corrupt_cwasm() {
let engine = build_engine().expect("build engine");
let dir = tempfile::tempdir().expect("tempdir");
let digest = digest(TEST_GUEST_WASM);
let cwasm_path = dir.path().join(cache_file_name(&engine, &digest));
std::fs::write(&cwasm_path, b"not a real cwasm file").expect("write garbage");
let _component = load_or_compile(&engine, TEST_GUEST_WASM, dir.path())
.expect("must recompile over a corrupt cache entry");
let _reloaded =
load_cwasm(&engine, dir.path(), &digest).expect("recompiled entry should load");
}
#[test]
fn load_cwasm_rejects_malformed_digest() {
let engine = build_engine().expect("build engine");
let dir = tempfile::tempdir().expect("tempdir");
for bad in [
"",
"short",
"../../etc/passwd",
"UPPERCASE0000000000000000000000000000000000000000000000000000",
&"a".repeat(63),
&"a".repeat(65),
] {
assert!(
load_cwasm(&engine, dir.path(), bad).is_err(),
"expected digest {bad:?} to be rejected"
);
}
}
}