use anyhow::{Context, Result, bail, ensure};
use cdk_rsx_compat::{PRODUCER_SCOPE, eligible_scope, hex};
use flate2::read::GzDecoder;
use serde::Deserialize;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use std::{
collections::{BTreeMap, BTreeSet},
fs::{self, File},
io::{self, Read, Write},
path::{Path, PathBuf},
};
use walkdir::WalkDir;
const ALIAS_FORMAT: &str = "cdk-rsx-compat-aliases-v1";
const INVENTORY_FORMAT: &str = "cdk-rsx-policy-inputs-v1";
const MAX_ENTRIES: usize = 16_384;
const MAX_DOCUMENT_BYTES: usize = 8 * 1024 * 1024;
const TARGETS: [&str; 2] = ["wasm32-unknown-unknown", "wasm64-unknown-unknown"];
const CRATES_IO: [&str; 2] = [
"registry+https://github.com/rust-lang/crates.io-index",
"sparse+https://index.crates.io/",
];
const SDK_REPOSITORY: &str = "https://github.com/3V-Interactive/cdk-rsx";
const PACKAGE_SCOPES: &str = include_str!("../compat/packages.toml");
pub(crate) const APPROVED_ALIASES: &[u8] = include_bytes!("../compat/approved-aliases.json");
pub(crate) struct Admission {
pub(crate) context: String,
pub(crate) context_inputs: Value,
pub(crate) tooling: String,
pub(crate) tooling_inputs: Value,
pub(crate) package_roots: BTreeMap<PathBuf, String>,
pub(crate) package_records: Value,
pub(crate) aliases: Value,
pub(crate) inputs: BTreeSet<PathBuf>,
target: String,
}
impl Admission {
pub(crate) fn inventory(&self, wasm: &[u8]) -> Result<Value> {
let inventory = cdk_rsx_wasm::compatibility(wasm)?;
validate_inventory(&inventory, &self.aliases, &self.context, &self.target)
}
}
pub(crate) fn materialize_aliases(target: &Path, bytes: &[u8]) -> Result<PathBuf> {
let key = digest(bytes);
let lock_id = format!("[\"compatibility-aliases\", \"{key}\"]");
let lock_name = format!("{}.lock", digest(lock_id.as_bytes()));
let _lock = crate::cargo::lock(target, &lock_name)?;
let directory = target.join(".cdk-rsx-compat-aliases");
ensure!(
!directory.is_symlink(),
"compatibility alias cache cannot be a symlink: {}",
directory.display()
);
fs::create_dir_all(&directory)?;
let path = directory.join(format!("{key}.json"));
if !path.exists() && !path.is_symlink() {
let mut temporary = tempfile::Builder::new()
.prefix(".publish-")
.tempfile_in(&directory)?;
temporary.write_all(bytes)?;
match temporary.persist_noclobber(&path) {
Ok(_) => {}
Err(error) if error.error.kind() == io::ErrorKind::AlreadyExists => {}
Err(error) => return Err(error.error.into()),
}
}
ensure!(
!path.is_symlink() && path.is_file() && read_document_bytes(&path)? == bytes,
"compatibility alias cache differs from its digest: {}",
path.display()
);
Ok(path)
}
#[derive(Deserialize)]
struct CargoGraph {
workspace_root: PathBuf,
packages: Vec<CargoPackage>,
resolve: CargoResolve,
}
#[derive(Deserialize)]
struct CargoPackage {
id: String,
name: String,
version: String,
source: Option<String>,
repository: Option<String>,
manifest_path: PathBuf,
targets: Vec<CargoTarget>,
}
#[derive(Deserialize)]
struct CargoTarget {
kind: Vec<String>,
}
#[derive(Deserialize)]
struct CargoResolve {
nodes: Vec<CargoNode>,
}
#[derive(Deserialize)]
struct CargoNode {
id: String,
features: Vec<String>,
dependencies: Vec<String>,
}
#[derive(Deserialize)]
struct CargoLock {
package: Vec<LockedPackage>,
}
#[derive(Deserialize)]
struct LockedPackage {
name: String,
version: String,
source: Option<String>,
checksum: Option<String>,
}
pub(crate) fn prepare(
metadata: &Value,
target: &str,
rustflags: &[String],
compiler: &crate::cargo::Compiler,
archives: Option<&Path>,
candidate: Option<&Path>,
excluded: &[PathBuf],
) -> Result<Admission> {
let cargo_home = &compiler.home;
let compiler = &compiler.version;
ensure!(
TARGETS.contains(&target),
"unsupported compatibility target {target}"
);
let graph = CargoGraph::deserialize(metadata).context("resolved Cargo metadata")?;
let lock_path = graph.workspace_root.join("Cargo.lock").canonicalize()?;
let lock = toml::from_str::<CargoLock>(&fs::read_to_string(&lock_path)?)?;
let packages: BTreeMap<_, _> = graph.packages.iter().map(|p| (p.id.as_str(), p)).collect();
let nodes: BTreeMap<_, _> = graph
.resolve
.nodes
.iter()
.map(|n| (n.id.as_str(), n))
.collect();
ensure!(
nodes
.values()
.all(|node| packages.contains_key(node.id.as_str())
&& node
.dependencies
.iter()
.all(|dep| nodes.contains_key(dep.as_str()))),
"Cargo resolution refers to a missing package"
);
let locked: BTreeMap<_, _> = lock
.package
.iter()
.filter_map(|p| {
p.source.as_deref().map(|source| {
(
(p.name.as_str(), p.version.as_str(), source),
p.checksum.as_deref(),
)
})
})
.collect();
let scopes = toml::from_str::<BTreeMap<String, String>>(PACKAGE_SCOPES)?;
let mut inputs = BTreeSet::from([lock_path]);
let mut package_roots = BTreeMap::new();
let mut package_records = Vec::new();
let mut registry_packages = Vec::new();
let mut closure = Vec::new();
for node in nodes.values() {
let package = packages[node.id.as_str()];
let mut features = node.features.clone();
features.sort();
closure
.push(json!({"name": package.name, "version": package.version, "features": features}));
let Some(source) = package.source.as_deref() else {
continue;
};
let lock_key = (package.name.as_str(), package.version.as_str(), source);
let checksum = *locked
.get(&lock_key)
.with_context(|| format!("{} is missing from Cargo.lock", package.name))?;
if source.starts_with("registry+") || source.starts_with("sparse+") {
check_digest(checksum.context("missing locked registry checksum")?)?;
}
let mut deps: Vec<_> = node
.dependencies
.iter()
.map(|id| identity(packages[id.as_str()]))
.collect();
deps.sort_by_cached_key(canonical_bytes);
registry_packages.push(json!({
"name": package.name, "version": package.version, "source": source,
"checksum": checksum, "features": features, "dependencies": deps,
}));
let Some(scope) = scopes.get(&package.name) else {
continue;
};
if !CRATES_IO.contains(&source) || package.repository.as_deref() != Some(SDK_REPOSITORY) {
continue;
}
let checksum = checksum.context("missing locked SDK package checksum")?;
let file_name = format!("{}-{}.crate", package.name, package.version);
let Some(archive) = find_archive(cargo_home, archives, &file_name, checksum)? else {
continue;
};
let manifest = package.manifest_path.canonicalize()?;
ensure!(
manifest == package.manifest_path,
"noncanonical SDK manifest {}",
package.manifest_path.display()
);
let directory = manifest
.parent()
.context("SDK manifest lacks package directory")?;
inputs.extend(verify_package_source(directory, &archive)?);
inputs.insert(archive.clone());
ensure!(
package_roots
.insert(directory.to_owned(), scope.clone())
.is_none(),
"duplicate SDK package owner {}",
directory.display()
);
package_records.push(json!({
"name": package.name, "version": package.version, "source": source,
"archive": {"path": archive, "bytes": archive.metadata()?.len(), "sha256": checksum},
"scope": scope, "root": directory,
}));
}
let local_tools = local_tooling(&packages, &nodes, excluded, &mut inputs)?;
registry_packages.sort_by_cached_key(canonical_bytes);
package_records.sort_by_cached_key(canonical_bytes);
closure.sort_by_cached_key(canonical_bytes);
let tooling_inputs = json!({
"format": "cdk-rsx-cli-tooling-v1", "cli_version": env!("CARGO_PKG_VERSION"),
"cli_recipe": env!("CDK_RSX_CLI_RECIPE"),
"registry_packages": registry_packages, "local_producers": local_tools,
});
let tooling = digest(&canonical_bytes(&tooling_inputs));
let flags: Vec<_> = rustflags
.iter()
.map(|flag| {
if flag.starts_with("--remap-path-prefix=") {
format!(
"--remap-path-prefix=<source>={}",
flag.rsplit_once('=').unwrap().1
)
} else {
flag.clone()
}
})
.collect();
let context_inputs = json!({
"format": "cdk-rsx-compat-context-v1", "target": target,
"rustflags": flags, "compiler": compiler, "tooling": tooling, "packages": closure,
});
let context = digest(&canonical_bytes(&context_inputs));
let approved = rows(&parse_document(APPROVED_ALIASES)?, ALIAS_FORMAT)?;
let mut aliases = approved.into_values().collect::<Vec<_>>();
if let Some(candidate) = candidate {
let candidate = candidate.canonicalize()?;
let additional = validate_aliases(&load_document(&candidate)?)?;
aliases.extend(rows(&additional, ALIAS_FORMAT)?.into_values());
inputs.insert(candidate);
}
let aliases = validate_aliases(&json!({"format": ALIAS_FORMAT, "entries": aliases}))?;
Ok(Admission {
context,
context_inputs,
tooling,
tooling_inputs,
package_roots,
package_records: Value::Array(package_records),
aliases,
inputs,
target: target.into(),
})
}
fn identity(package: &CargoPackage) -> Value {
json!({"name": package.name, "version": package.version, "source": package.source})
}
fn local_tooling(
packages: &BTreeMap<&str, &CargoPackage>,
nodes: &BTreeMap<&str, &CargoNode>,
excluded: &[PathBuf],
inputs: &mut BTreeSet<PathBuf>,
) -> Result<Vec<Value>> {
let mut pending = nodes
.values()
.filter(|node| {
let package = packages[node.id.as_str()];
package.source.is_none()
&& (matches!(package.name.as_str(), "cdk-rsx-memory-abi" | "cdk-rsx-wasm")
|| package
.targets
.iter()
.any(|target| target.kind.iter().any(|kind| kind == "proc-macro")))
})
.map(|node| node.id.as_str())
.collect::<Vec<_>>();
let mut visited = BTreeSet::new();
let mut records = Vec::new();
while let Some(id) = pending.pop() {
if !visited.insert(id) {
continue;
}
let package = packages[id];
if package.source.is_some() {
continue;
}
let node = nodes[id];
pending.extend(node.dependencies.iter().map(String::as_str));
let manifest = package.manifest_path.canonicalize()?;
let dir = manifest
.parent()
.context("local producer manifest lacks package directory")?;
let mut files = Vec::new();
for entry in WalkDir::new(dir)
.sort_by_file_name()
.into_iter()
.filter_entry(|entry| {
let path = entry.path();
!excluded.iter().any(|root| path.starts_with(root))
&& (entry.depth() == 0
|| !matches!(
entry.file_name().to_str(),
Some(
".git"
| ".rustup"
| ".cargo-home"
| "node_modules"
| "target"
| "tmp"
)
))
})
{
let entry = entry?;
ensure!(
!entry.file_type().is_symlink(),
"symlink in local producer inputs {}",
entry.path().display()
);
if entry.file_type().is_file() {
let path = entry.path();
inputs.insert(path.to_owned());
files.push(json!({
"name": path.strip_prefix(dir)?, "sha256": file_sha(path)?, "bytes": path.metadata()?.len(),
}));
}
}
let mut deps: Vec<_> = node
.dependencies
.iter()
.map(|id| identity(packages[id.as_str()]))
.collect();
deps.sort_by_cached_key(canonical_bytes);
let mut features = node.features.clone();
features.sort();
records.push(json!({
"package": identity(package), "features": features, "dependencies": deps, "files": files,
}));
}
records.sort_by_cached_key(canonical_bytes);
Ok(records)
}
fn find_archive(
home: &Path,
explicit: Option<&Path>,
filename: &str,
checksum: &str,
) -> Result<Option<PathBuf>> {
let candidates = if let Some(root) = explicit {
let path = root.join(filename);
ensure!(
path.is_file(),
"locked SDK package archive is missing: {}",
path.display()
);
vec![path]
} else {
let root = home.join("registry/cache");
match fs::read_dir(root) {
Ok(dirs) => {
let mut candidates = Vec::new();
for dir in dirs {
let path = dir?.path().join(filename);
if path.is_file() {
candidates.push(path);
}
}
candidates.sort();
candidates
}
Err(error) if error.kind() == io::ErrorKind::NotFound => Vec::new(),
Err(error) => return Err(error.into()),
}
};
for path in &candidates {
if file_sha(path)? == checksum {
return Ok(Some(path.canonicalize()?));
}
}
if let Some(first) = candidates.first() {
bail!(
"SDK package archive checksum differs from Cargo.lock: {}",
first.display()
);
}
Ok(None)
}
fn verify_package_source(directory: &Path, archive: &Path) -> Result<BTreeSet<PathBuf>> {
let stem = archive
.file_stem()
.and_then(|name| name.to_str())
.context("SDK archive has invalid name")?;
let mut bundle = tar::Archive::new(GzDecoder::new(File::open(archive)?));
let mut files = BTreeSet::new();
for entry in bundle.entries()? {
let mut entry = entry?;
let kind = entry.header().entry_type();
let name = entry.path_bytes();
let name = std::str::from_utf8(&name)?;
let name = if kind.is_dir() {
name.strip_suffix('/').unwrap_or(name)
} else {
name
};
let mut parts = name.split('/');
ensure!(
parts.next() == Some(stem) && (kind.is_dir() || kind.is_file()),
"invalid SDK package archive entry {name:?}"
);
let mut path = directory.to_owned();
for part in parts {
ensure!(
!matches!(part, "" | "." | ".."),
"invalid SDK package archive path {name:?}"
);
path.push(part);
}
if kind.is_dir() {
continue;
}
ensure!(
path != directory
&& path.is_file()
&& path.canonicalize()? == path
&& files.insert(path.clone()),
"invalid SDK source entry {}",
path.display()
);
ensure!(
reader_sha(&mut entry)? == file_sha(&path)?,
"SDK package source differs from its locked archive: {}",
path.display()
);
}
ensure!(
files.contains(&directory.join("Cargo.toml")),
"SDK archive lacks Cargo.toml: {}",
archive.display()
);
let mut actual = BTreeSet::new();
for entry in WalkDir::new(directory) {
let entry = entry?;
ensure!(
!entry.file_type().is_symlink(),
"symlink in SDK package source {}",
entry.path().display()
);
if entry.file_type().is_dir() {
continue;
}
let path = entry.into_path();
if path.parent() == Some(directory)
&& matches!(
path.file_name().and_then(|p| p.to_str()),
Some(".cargo-ok" | ".cargo-checksum.json")
)
{
continue;
}
actual.insert(path);
}
ensure!(
actual == files,
"SDK package files differ from its locked archive: {}",
directory.display()
);
Ok(files)
}
pub(crate) fn digest(bytes: &[u8]) -> String {
hex(Sha256::digest(bytes).into())
}
fn file_sha(path: &Path) -> Result<String> {
reader_sha(&mut File::open(path).with_context(|| format!("read {}", path.display()))?)
}
fn reader_sha(input: &mut impl Read) -> Result<String> {
let mut digest = Sha256::new();
io::copy(input, &mut digest)?;
Ok(hex(digest.finalize().into()))
}
fn check_digest(value: &str) -> Result<()> {
ensure!(
value.len() == 64
&& value
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),
"expected lowercase SHA-256 digest"
);
Ok(())
}
#[derive(Deserialize, serde::Serialize, PartialEq, Eq, Clone)]
#[serde(deny_unknown_fields)]
struct Row {
context: String,
scope: String,
raw: String,
identity: String,
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct Document {
format: String,
entries: Vec<Row>,
}
type Rows = BTreeMap<(String, String, String), Row>;
fn rows(value: &Value, format: &str) -> Result<Rows> {
let document = Document::deserialize(value).context("invalid compatibility document")?;
ensure!(
document.format == format,
"expected compatibility format {format}"
);
ensure!(
document.entries.len() <= MAX_ENTRIES,
"compatibility entry bound exceeded"
);
let mut found = BTreeMap::new();
for row in document.entries {
ensure!(
eligible_scope(&row.scope),
"ineligible compatibility scope {}",
row.scope
);
for hash in [&row.context, &row.raw, &row.identity] {
check_digest(hash)?;
}
let key = (row.context.clone(), row.scope.clone(), row.raw.clone());
if let Some(previous) = found.insert(key, row.clone()) {
ensure!(
previous == row,
"conflicting compatibility identity for {}",
row.scope
);
}
}
Ok(found)
}
pub(crate) fn validate_aliases(value: &Value) -> Result<Value> {
let entries = rows(value, ALIAS_FORMAT)?;
for row in entries.values() {
ensure!(
row.context.bytes().any(|b| b != b'0'),
"alias context cannot use the unqualified zero sentinel"
);
let target = (row.context.clone(), row.scope.clone(), row.identity.clone());
ensure!(
entries
.get(&target)
.is_none_or(|next| next.identity == row.identity),
"compatibility aliases cannot chain"
);
}
Ok(json!({"format": ALIAS_FORMAT, "entries": entries.into_values().collect::<Vec<_>>()}))
}
pub(crate) fn validate_inventory(
value: &Value,
aliases: &Value,
context: &str,
target: &str,
) -> Result<Value> {
ensure!(
TARGETS.contains(&target),
"unsupported compatibility target {target}"
);
check_digest(context)?;
ensure!(
context.bytes().any(|b| b != b'0'),
"unqualified inventory context"
);
let entries = rows(value, INVENTORY_FORMAT)?;
let approved = rows(&validate_aliases(aliases)?, ALIAS_FORMAT)?;
let compiler = format!("compiler/{target}");
let mut has_compiler = false;
let mut has_producer = false;
for (key, row) in &entries {
ensure!(
row.context == context,
"actual Wasm context differs from the canonical build"
);
let expected = approved
.get(key)
.map(|row| row.identity.as_str())
.unwrap_or(&row.raw);
ensure!(
row.identity == expected,
"actual Wasm identity differs from exact alias payload for {}",
row.scope
);
if row.scope.starts_with("compiler/") {
ensure!(
row.scope == compiler,
"actual Wasm inventory contains a different compiler target"
);
has_compiler = true;
}
has_producer |= row.scope == PRODUCER_SCOPE;
}
ensure!(
has_compiler && has_producer,
"rooted artifact lacks compiler or source-policy inventory"
);
Ok(json!({"format": INVENTORY_FORMAT, "entries": entries.into_values().collect::<Vec<_>>()}))
}
pub(crate) fn canonical_bytes(value: &Value) -> Vec<u8> {
fn write(value: &Value, out: &mut String) {
match value {
Value::Object(object) => {
out.push('{');
let sorted: BTreeMap<_, _> = object.iter().collect();
for (i, (key, value)) in sorted.into_iter().enumerate() {
if i != 0 {
out.push(',')
}
string(key, out);
out.push(':');
write(value, out);
}
out.push('}');
}
Value::Array(values) => {
out.push('[');
for (i, value) in values.iter().enumerate() {
if i != 0 {
out.push(',')
}
write(value, out);
}
out.push(']');
}
Value::String(value) => string(value, out),
value => out.push_str(&value.to_string()),
}
}
fn string(value: &str, out: &mut String) {
use std::fmt::Write;
for ch in serde_json::to_string(value)
.expect("JSON string serialization")
.chars()
{
if ch < '\u{7f}' {
out.push(ch);
} else {
for unit in ch.encode_utf16(&mut [0; 2]) {
write!(out, "\\u{unit:04x}").unwrap();
}
}
}
}
let mut out = String::new();
write(value, &mut out);
out.push('\n');
out.into_bytes()
}
pub(crate) fn load_document(path: &Path) -> Result<Value> {
let bytes = read_document_bytes(path)?;
parse_document(&bytes).with_context(|| format!("invalid document {}", path.display()))
}
pub(crate) fn read_document_bytes(path: &Path) -> Result<Vec<u8>> {
let mut bytes = Vec::new();
File::open(path)
.with_context(|| format!("read {}", path.display()))?
.take((MAX_DOCUMENT_BYTES + 1) as u64)
.read_to_end(&mut bytes)?;
ensure!(
bytes.len() <= MAX_DOCUMENT_BYTES,
"document exceeds byte bound: {}",
path.display()
);
Ok(bytes)
}
pub(crate) fn parse_document(bytes: &[u8]) -> Result<Value> {
use serde::de::{Error, MapAccess, SeqAccess, Visitor};
struct Strict(Value);
struct ReadStrict;
impl<'de> Deserialize<'de> for Strict {
fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
de.deserialize_any(ReadStrict).map(Strict)
}
}
impl<'de> Visitor<'de> for ReadStrict {
type Value = Value;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a JSON value")
}
fn visit_map<M: MapAccess<'de>>(self, mut map: M) -> Result<Value, M::Error> {
let mut fields = serde_json::Map::new();
while let Some((key, Strict(value))) = map.next_entry::<String, Strict>()? {
if fields.insert(key.clone(), value).is_some() {
return Err(M::Error::custom(format_args!(
"duplicate JSON field {key:?}"
)));
}
}
Ok(Value::Object(fields))
}
fn visit_seq<S: SeqAccess<'de>>(self, mut seq: S) -> Result<Value, S::Error> {
let mut array = Vec::new();
while let Some(Strict(value)) = seq.next_element()? {
array.push(value);
}
Ok(Value::Array(array))
}
fn visit_bool<E: Error>(self, value: bool) -> Result<Value, E> {
Ok(value.into())
}
fn visit_i64<E: Error>(self, value: i64) -> Result<Value, E> {
Ok(value.into())
}
fn visit_u64<E: Error>(self, value: u64) -> Result<Value, E> {
Ok(value.into())
}
fn visit_f64<E: Error>(self, value: f64) -> Result<Value, E> {
serde_json::Number::from_f64(value)
.map(Value::Number)
.ok_or_else(|| E::custom("invalid JSON number"))
}
fn visit_str<E: Error>(self, value: &str) -> Result<Value, E> {
Ok(value.into())
}
fn visit_unit<E: Error>(self) -> Result<Value, E> {
Ok(Value::Null)
}
}
ensure!(
bytes.len() <= MAX_DOCUMENT_BYTES,
"compatibility document exceeds byte bound"
);
Ok(serde_json::from_slice::<Strict>(bytes)?.0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn canonical_aliases_and_strict_receipt_json() -> Result<()> {
let canonical = canonical_bytes(&validate_aliases(&parse_document(APPROVED_ALIASES)?)?);
assert_eq!(APPROVED_ALIASES, canonical);
assert_eq!(
canonical_bytes(&json!({"é": "🚀", "a": "\u{7f}"})),
b"{\"a\":\"\\u007f\",\"\\u00e9\":\"\\ud83d\\ude80\"}\n"
);
assert!(parse_document(br#"{"meta":{"x":true,"x":false}}"#).is_err());
Ok(())
}
#[test]
fn content_addressed_aliases_reuse_the_same_file_and_reject_changes() -> Result<()> {
let target = tempfile::tempdir()?;
let first = materialize_aliases(target.path(), APPROVED_ALIASES)?;
assert_eq!(first, materialize_aliases(target.path(), APPROVED_ALIASES)?);
fs::write(&first, b"changed")?;
assert!(materialize_aliases(target.path(), APPROVED_ALIASES).is_err());
assert_eq!(fs::read(first)?, b"changed");
Ok(())
}
#[test]
fn archive_matches_the_complete_resolved_source() -> Result<()> {
let temporary = tempfile::tempdir()?;
let source = temporary.path().join("source");
fs::create_dir(&source)?;
fs::write(
source.join("Cargo.toml"),
b"[package]\nname = \"example\"\n",
)?;
fs::write(source.join("lib.rs"), b"pub fn run() {}\n")?;
fs::write(source.join(".cargo-ok"), b"")?;
let path = temporary.path().join("example-1.0.0.crate");
let encoder =
flate2::write::GzEncoder::new(File::create(&path)?, flate2::Compression::fast());
let mut archive = tar::Builder::new(encoder);
for name in ["Cargo.toml", "lib.rs"] {
archive.append_path_with_name(source.join(name), format!("example-1.0.0/{name}"))?;
}
archive.into_inner()?.finish()?;
assert_eq!(verify_package_source(&source, &path)?.len(), 2);
fs::write(source.join("untracked.rs"), b"")?;
assert!(verify_package_source(&source, &path).is_err());
fs::remove_file(source.join("untracked.rs"))?;
fs::write(source.join("lib.rs"), b"pub fn changed() {}\n")?;
assert!(verify_package_source(&source, &path).is_err());
Ok(())
}
}