Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions crates/common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ dirs = { workspace = true }
futures = { workspace = true }
sha2 = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = ["rt", "time", "process"] }
tokio-util = { version = "0.7", features = ["compat"] }
tokio = { workspace = true, features = ["fs", "io-util", "rt", "time", "process"] }
tokio-util = { version = "0.7", features = ["compat", "io"] }
url = { workspace = true }
152 changes: 150 additions & 2 deletions crates/common/src/sha256.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,127 @@

use std::path::Path;

use sha2::{Digest, Sha256};
use sha2::{Digest as _, Sha256};

/// A digest value in text form. The text may be a hex string
/// or may be prefixed with a scheme (e.g. `sha256:...`).
Comment on lines +7 to +8

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would strongly encourage storing only the prefixed form and using explicit methods to convert to/from unprefixed. I think most of the advantage of having a wrapper type like this comes from getting the same behavior out of it no matter where it was constructed.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That was my original thought but I found some places where we didn't seem to have a prefix - but that may be because we were using strings inconsistently rather than of necessity, it depends if they were coming from an external source or not. I'll look over the places we do that (which this at least makes a bit more findable) and see if we can fix them up. Thanks!

///
/// The type does not validate that the value conforms to any
/// specific digest format, but it does guarantee that the value
/// is restricted to the expected character set.
#[derive(Debug)]
pub struct Digest {
repr: String,
}

impl TryFrom<String> for Digest {
type Error = anyhow::Error;

fn try_from(value: String) -> anyhow::Result<Self> {
fn is_alpha(candidate: &str) -> bool {
candidate.chars().all(|c| c.is_alphanumeric())
}

let is_digest = match value.split_once(':') {
Some((scheme, rest)) => is_alpha(scheme) && is_alpha(rest),
None => is_alpha(&value),
};
if is_digest {
Ok(Self { repr: value })
} else {
Err(anyhow::anyhow!("Invalid digest {value}"))
}
}
}

impl TryFrom<&str> for Digest {
type Error = anyhow::Error;

fn try_from(value: &str) -> anyhow::Result<Self> {
value.to_string().try_into()
}
}

impl TryFrom<&String> for Digest {
type Error = anyhow::Error;

fn try_from(value: &String) -> anyhow::Result<Self> {
value.to_string().try_into()
}
}

impl std::fmt::Display for Digest {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.repr)
}
}

impl PartialEq<Self> for Digest {
fn eq(&self, other: &Self) -> bool {
self.repr == other.repr
}
}

impl PartialEq<String> for Digest {
fn eq(&self, other: &String) -> bool {
&self.repr == other
}
}

impl PartialEq<&Digest> for String {
fn eq(&self, other: &&Digest) -> bool {
self == &other.repr
}
}

impl AsRef<str> for Digest {
fn as_ref(&self) -> &str {
&self.repr
}
}

impl From<Digest> for String {
fn from(value: Digest) -> Self {
value.repr
}
}

impl Digest {
/// A form of the digest which is safe to append to an operating system directory path
#[cfg(windows)]
pub fn safe_name(&self) -> impl AsRef<str> {
self.repr.replace(':', "_")
}

/// A form of the digest which is safe to append to an operating system directory path
#[cfg(not(windows))]
pub fn safe_name(&self) -> impl AsRef<str> {
&self.repr
}
}

/// Return the hex SHA-256 digest of the given bytes.
pub fn hex_digest_from_bytes(bytes: impl AsRef<[u8]>) -> String {
let digest = Sha256::digest(bytes);
format!("{digest:x}")
}

/// Return the SHA-256 digest of the given bytes.
pub fn digest_from_bytes(bytes: impl AsRef<[u8]>) -> Digest {
// We can skip validation because `hex_digit_from_bytes` is safe
Digest {
repr: format!("sha256:{}", hex_digest_from_bytes(bytes)),
}
}

/// Return the SHA-256 digest of the given bytes.
pub fn digest_from_bytes_unprefixed(bytes: impl AsRef<[u8]>) -> Digest {
// We can skip validation because `hex_digit_from_bytes` is safe
Digest {
repr: hex_digest_from_bytes(bytes),
}
}

/// Return the hex SHA-256 digest of the given file.
pub fn hex_digest_from_file(path: impl AsRef<Path>) -> std::io::Result<String> {
let mut file = std::fs::File::open(path)?;
Expand All @@ -18,6 +131,13 @@ pub fn hex_digest_from_file(path: impl AsRef<Path>) -> std::io::Result<String> {
let digest = hasher.finalize();
Ok(format!("{digest:x}"))
}
/// Return the SHA-256 digest of the given file.
pub fn digest_from_file(path: impl AsRef<Path>) -> std::io::Result<Digest> {
// We can skip validation because `hex_digit_from_bytes` is safe
Ok(Digest {
repr: format!("sha256:{}", hex_digest_from_file(path)?),
})
}

#[cfg(test)]
mod tests {
Expand All @@ -32,16 +152,44 @@ mod tests {
hex,
"a5a2729ffa0eeacc15323a9168807c72d18d1cb375dbde899c44d6803dad2b19"
);
let digest = digest_from_bytes("spin");
assert_eq!(
digest.as_ref(),
"sha256:a5a2729ffa0eeacc15323a9168807c72d18d1cb375dbde899c44d6803dad2b19"
);
let digest = digest_from_bytes_unprefixed("spin");
assert_eq!(
digest.as_ref(),
"a5a2729ffa0eeacc15323a9168807c72d18d1cb375dbde899c44d6803dad2b19"
);
}

#[test]
fn test_hex_digest_from_file() {
let mut f = tempfile::NamedTempFile::new().unwrap();
write!(&mut f, "spin").unwrap();
let hex = hex_digest_from_file(f.into_temp_path()).unwrap();
let hex = hex_digest_from_file(f.path()).unwrap();
assert_eq!(
hex,
"a5a2729ffa0eeacc15323a9168807c72d18d1cb375dbde899c44d6803dad2b19"
);
let digest = digest_from_file(f.path()).unwrap();
assert_eq!(
digest.as_ref(),
"sha256:a5a2729ffa0eeacc15323a9168807c72d18d1cb375dbde899c44d6803dad2b19"
);
}

#[test]
fn test_digest_cannot_contain_eeeevil_characters() {
Digest::try_from("12345abcd").expect("alphanumeric should be valid for digest");
Digest::try_from("sha123:12345abcd")
.expect("schemed alphanumeric should be valid for digest");
Digest::try_from("/crimes").expect_err("/ should be invalid for digest");
Digest::try_from("sha/123:123456abcd").expect_err("/ should be invalid in scheme");
Digest::try_from("sha123:123456/abcd").expect_err("/ should be invalid in value");
Digest::try_from(".").expect_err(". should be invalid for digest");
Digest::try_from("sha123:..").expect_err(".. should be invalid for digest");
Digest::try_from("sha123:../crimes").expect_err(".. should be invalid for digest");
}
}
9 changes: 6 additions & 3 deletions crates/environments/src/environment/env_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,8 @@ async fn load_world_from_registry(
.read()
.await
.package_digest(registry, world_name.package())
&& let Ok(cache_file) = cache.wasm_file(digest)
&& let Ok(digest) = digest.try_into()
&& let Ok(cache_file) = cache.wasm_file(&digest)
&& let Ok(bytes) = tokio::fs::read(&cache_file).await
{
return CandidateWorld::from_package_bytes(world_name, bytes);
Expand Down Expand Up @@ -341,7 +342,7 @@ async fn load_world_from_registry(
.with_context(|| format!("Failed to get {} from registry", world_name.package()))?
.to_vec();

let digest = release.content_digest.to_string();
let digest = release.content_digest.to_string().try_into()?;
_ = cache.write_wasm(&bytes, &digest).await; // Failure to cache is not fatal
lockfile
.write()
Expand All @@ -365,7 +366,8 @@ async fn load_world_from_oci_ref(
.read()
.await
.package_digest(reference, world_name.package())
&& let Ok(cache_file) = cache.wasm_file(digest)
&& let Ok(digest) = digest.try_into()
&& let Ok(cache_file) = cache.wasm_file(&digest)
&& let Ok(bytes) = tokio::fs::read(&cache_file).await
{
return CandidateWorld::from_package_bytes(world_name, bytes);
Expand Down Expand Up @@ -397,6 +399,7 @@ async fn load_world_from_oci_ref(
.to_vec();

if let Some(digest) = data.digest {
let digest = digest.try_into()?;
_ = cache.write_wasm(&bytes, &digest).await; // Failure to cache is not fatal
lockfile
.write()
Expand Down
2 changes: 1 addition & 1 deletion crates/environments/src/environment/lockfile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ impl TargetEnvironmentLockfile {
&mut self,
registry: &str,
package: &wit_parser::PackageName,
digest: &str,
digest: &spin_common::sha256::Digest,
) {
match self.0.get_mut(registry) {
Some(ds) => {
Expand Down
59 changes: 21 additions & 38 deletions crates/loader/src/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

use anyhow::{Context, Result, ensure};
use spin_common::fs::write_file_atomically_stream;
use spin_common::sha256::Digest;

use std::{
path::PathBuf,
Expand Down Expand Up @@ -60,39 +61,31 @@ impl Cache {
}

/// Return the path to a wasm file given its digest.
pub fn wasm_file(&self, digest: impl AsRef<str>) -> Result<PathBuf> {
pub fn wasm_file(&self, digest: &Digest) -> Result<PathBuf> {
// Check the expected wasm directory first; else check the data directory as a fallback.
// (Layers with unknown media types are currently saved to the data directory in client.pull())
// This adds a bit of futureproofing for fetching wasm layers with different/updated media types
// (see WASM_LAYER_MEDIA_TYPE, which is subject to change in future versions).
let mut path = self.wasm_path(&digest);
let mut path = self.wasm_path(digest);
if !path.exists() {
path = self.data_path(&digest);
path = self.data_path(digest);
if !is_wasm(&path)? {
anyhow::bail!("cached data for digest {} is not Wasm", digest.as_ref());
anyhow::bail!("cached data for digest {digest} is not Wasm");
}
}
ensure!(
path.exists(),
"cannot find wasm file for digest {}",
digest.as_ref()
);
ensure!(path.exists(), "cannot find wasm file for digest {digest}");
Ok(path)
}

/// Return the path to a data file given its digest.
pub fn data_file(&self, digest: impl AsRef<str>) -> Result<PathBuf> {
let path = self.data_path(&digest);
ensure!(
path.exists(),
"cannot find data file for digest {}",
digest.as_ref()
);
pub fn data_file(&self, digest: &Digest) -> Result<PathBuf> {
let path = self.data_path(digest);
ensure!(path.exists(), "cannot find data file for digest {digest}");
Ok(path)
}

/// Write the contents in the cache's wasm directory.
pub async fn write_wasm(&self, bytes: impl AsRef<[u8]>, digest: impl AsRef<str>) -> Result<()> {
pub async fn write_wasm(&self, bytes: impl AsRef<[u8]>, digest: &Digest) -> Result<()> {
self.ensure_dirs().await?;
write_file_atomically(&self.wasm_path(digest), bytes.as_ref()).await?;
Ok(())
Expand All @@ -102,15 +95,15 @@ impl Cache {
pub async fn write_wasm_stream(
&self,
bytes: impl futures::Stream<Item = Result<bytes::Bytes, std::io::Error>> + Unpin,
digest: impl AsRef<str>,
digest: &Digest,
) -> Result<()> {
self.ensure_dirs().await?;
write_file_atomically_stream(&self.wasm_path(digest), bytes).await?;
Ok(())
}

/// Write the contents in the cache's data directory.
pub async fn write_data(&self, bytes: impl AsRef<[u8]>, digest: impl AsRef<str>) -> Result<()> {
pub async fn write_data(&self, bytes: impl AsRef<[u8]>, digest: &Digest) -> Result<()> {
self.ensure_dirs().await?;
write_file_atomically(&self.data_path(digest), bytes.as_ref()).await?;
Ok(())
Expand All @@ -120,21 +113,21 @@ impl Cache {
pub async fn write_data_stream(
&self,
bytes: impl futures::Stream<Item = Result<bytes::Bytes, std::io::Error>> + Unpin,
digest: impl AsRef<str>,
digest: &Digest,
) -> Result<()> {
self.ensure_dirs().await?;
write_file_atomically_stream(&self.data_path(digest), bytes).await?;
Ok(())
}

/// The path of contents in the cache's wasm directory, which may or may not exist.
pub fn wasm_path(&self, digest: impl AsRef<str>) -> PathBuf {
self.wasm_dir().join(safe_name(digest).as_ref())
pub fn wasm_path(&self, digest: &Digest) -> PathBuf {
self.wasm_dir().join(digest.safe_name().as_ref())
}

/// The path of contents in the cache's wasm directory, which may or may not exist.
pub fn data_path(&self, digest: impl AsRef<str>) -> PathBuf {
self.data_dir().join(safe_name(digest).as_ref())
pub fn data_path(&self, digest: &Digest) -> PathBuf {
self.data_dir().join(digest.safe_name().as_ref())
}

/// Ensure the expected configuration directories are found in the root.
Expand Down Expand Up @@ -196,19 +189,9 @@ fn is_wasm(path: &std::path::Path) -> std::io::Result<bool> {
}
}

#[cfg(windows)]
fn safe_name(digest: impl AsRef<str>) -> impl AsRef<std::path::Path> {
digest.as_ref().replace(':', "_")
}

#[cfg(not(windows))]
fn safe_name(digest: impl AsRef<str>) -> impl AsRef<str> {
digest
}

#[cfg(test)]
mod test {
use spin_common::sha256::hex_digest_from_bytes;
use spin_common::sha256::digest_from_bytes;

use super::*;

Expand All @@ -218,12 +201,12 @@ mod test {
let cache = Cache::new(Some(temp_dir.path().to_owned())).await?;

let wasm = "Wasm".as_bytes();
let digest = format!("sha256:{}", hex_digest_from_bytes(wasm));
let digest = digest_from_bytes(wasm);
cache.write_wasm(wasm, &digest).await?;
assert_eq!(wasm, std::fs::read(cache.wasm_path(&digest))?);

let data = "hello".as_bytes();
let digest = format!("sha256:{}", hex_digest_from_bytes(data));
let digest = digest_from_bytes(data);
cache.write_data(data, &digest).await?;
assert_eq!(data, std::fs::read(cache.data_path(&digest))?);

Expand All @@ -236,7 +219,7 @@ mod test {
let cache = Cache::new(Some(temp_dir.path().to_owned())).await?;

let wasm = "Wasm".as_bytes();
let digest = format!("sha256:{}", hex_digest_from_bytes(wasm));
let digest = digest_from_bytes(wasm);
// Writing the same content again replaces it in place.
cache.write_wasm(wasm, &digest).await?;
cache.write_wasm(wasm, &digest).await?;
Expand Down
Loading
Loading