From e182c7e3de2f578768131d8445db21bf0a8fa7dc Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Thu, 21 May 2026 16:53:23 -0700 Subject: [PATCH 01/33] Scaffold stellar contract verify with metadata extraction. --- FULL_HELP_DOCS.md | 25 + .../src/commands/contract/build/verifiable.rs | 2 +- cmd/soroban-cli/src/commands/contract/mod.rs | 10 + .../src/commands/contract/verify.rs | 442 ++++++++++++++++++ 4 files changed, 478 insertions(+), 1 deletion(-) create mode 100644 cmd/soroban-cli/src/commands/contract/verify.rs diff --git a/FULL_HELP_DOCS.md b/FULL_HELP_DOCS.md index f5b1b7dab5..3068a7f562 100644 --- a/FULL_HELP_DOCS.md +++ b/FULL_HELP_DOCS.md @@ -99,6 +99,7 @@ Tools for smart contract developers - `optimize` — ⚠️ Deprecated, use `build --optimize`. Optimize a WASM file - `read` — Print the current value of a contract-data ledger entry - `restore` — Restore an evicted value for a contract-data legder entry +- `verify` — Verify that a contract's WASM reproduces from the build metadata it records, per SEP-58. Either pass a contract id/alias via `--id` (the WASM is fetched from the network) or a local file via `--wasm` ## `stellar contract asset` @@ -1162,6 +1163,30 @@ If no keys are specificed the contract itself is restored. - `--inclusion-fee ` — Maximum fee amount for transaction inclusion, in stroops. 1 stroop = 0.0000001 xlm. Defaults to 100 if no arg, env, or config value is provided - `--build-only` — Build the transaction and only write the base64 xdr to stdout +## `stellar contract verify` + +Verify that a contract's WASM reproduces from the build metadata it records, per SEP-58. Either pass a contract id/alias via `--id` (the WASM is fetched from the network) or a local file via `--wasm` + +**Usage:** `stellar contract verify [OPTIONS]` + +###### **Global Options:** + +- `--config-dir ` — Location of config directory. By default, it uses `$XDG_CONFIG_HOME/stellar` if set, falling back to `~/.config/stellar` otherwise. Contains configuration files, aliases, and other persistent settings + +###### **Options:** + +- `--id ` — Contract id or alias to fetch the WASM from the network +- `--wasm ` — Local WASM file to verify, instead of fetching from the network +- `--tarball-url ` — Local tarball file or http(s) URL to use as the source when the WASM's recorded SEP-58 metadata has only `tarball_sha256` (no `tarball_url`). Accepts http(s) URLs or local file paths +- `--trust` — Bypass interactive confirmation when the WASM's bldimg is not in the default trust list, or when the source is a tarball (tarballs are never default-trusted) + +###### **RPC Options:** + +- `--rpc-url ` — RPC server endpoint +- `--rpc-header ` — RPC Header(s) to include in requests to the RPC provider, example: "X-API-Key: abc123". Multiple headers can be added by passing the option multiple times +- `--network-passphrase ` — Network passphrase to sign the transaction sent to the rpc server +- `-n`, `--network ` — Name of network to use from config + ## `stellar doctor` Diagnose and troubleshoot CLI and network issues diff --git a/cmd/soroban-cli/src/commands/contract/build/verifiable.rs b/cmd/soroban-cli/src/commands/contract/build/verifiable.rs index 9baea2cdf3..1fee860a2d 100644 --- a/cmd/soroban-cli/src/commands/contract/build/verifiable.rs +++ b/cmd/soroban-cli/src/commands/contract/build/verifiable.rs @@ -350,7 +350,7 @@ fn resolve_archive(cmd: &Cmd, source_root: &Path, print: &Print) -> Result Regex { +pub(crate) fn bldimg_regex() -> Regex { Regex::new(r"^(?:localhost(?::\d+)?|[^\s@/]*[.:][^\s@/]*)/[^\s@]+@sha256:[0-9a-f]{64}$") .unwrap() } diff --git a/cmd/soroban-cli/src/commands/contract/mod.rs b/cmd/soroban-cli/src/commands/contract/mod.rs index ee140be938..b7fcb58bba 100644 --- a/cmd/soroban-cli/src/commands/contract/mod.rs +++ b/cmd/soroban-cli/src/commands/contract/mod.rs @@ -17,6 +17,7 @@ pub mod read; pub mod restore; pub mod spec_verify; pub mod upload; +pub mod verify; use crate::{commands::global, print::Print, utils::deprecate_message}; @@ -104,6 +105,11 @@ pub enum Cmd { // run as part of `contract build` so for a general user this is not needed. #[command(name = "spec-verify", hide = true)] SpecVerify(spec_verify::Cmd), + + /// Verify that a contract's WASM reproduces from the build metadata it + /// records, per SEP-58. Either pass a contract id/alias via `--id` (the + /// WASM is fetched from the network) or a local file via `--wasm`. + Verify(verify::Cmd), } #[derive(thiserror::Error, Debug)] @@ -161,6 +167,9 @@ pub enum Error { #[error(transparent)] SpecVerify(#[from] spec_verify::Error), + + #[error(transparent)] + Verify(#[from] verify::Error), } impl Cmd { @@ -210,6 +219,7 @@ impl Cmd { Cmd::Read(read) => read.run().await?, Cmd::Restore(restore) => restore.run(global_args).await?, Cmd::SpecVerify(spec_verify) => spec_verify.run(global_args)?, + Cmd::Verify(verify) => verify.run(global_args).await?, } Ok(()) } diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs new file mode 100644 index 0000000000..2ed91e7c8e --- /dev/null +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -0,0 +1,442 @@ +use std::path::PathBuf; + +use clap::Parser; +use soroban_spec_tools::contract::Spec; +use stellar_xdr::curr::{ScMetaEntry, ScMetaV0}; + +use crate::{ + commands::{ + contract::build::verifiable::{ + bldimg_regex, source_repo_regex, source_rev_regex, tarball_sha256_regex, + tarball_url_regex, + }, + global, + }, + config::{self, locator, network}, + print::Print, + wasm, +}; + +#[derive(Parser, Debug, Clone)] +#[group(skip)] +pub struct Cmd { + /// Contract id or alias to fetch the WASM from the network. + #[arg(long = "id", env = "STELLAR_CONTRACT_ID", conflicts_with = "wasm")] + pub contract_id: Option, + + /// Local WASM file to verify, instead of fetching from the network. + #[arg(long)] + pub wasm: Option, + + /// Local tarball file or http(s) URL to use as the source when the WASM's + /// recorded SEP-58 metadata has only `tarball_sha256` (no `tarball_url`). + /// Accepts http(s) URLs or local file paths. + #[arg(long)] + pub tarball_url: Option, + + /// Bypass interactive confirmation when the WASM's bldimg is not in the + /// default trust list, or when the source is a tarball (tarballs are + /// never default-trusted). + #[arg(long)] + pub trust: bool, + + #[command(flatten)] + pub locator: locator::Args, + + #[command(flatten)] + pub network: network::Args, +} + +#[derive(thiserror::Error, Debug)] +pub enum Error { + #[error("must pass exactly one of --id or --wasm")] + MissingInput, + + #[error("reading wasm {0}: {1}")] + ReadWasm(PathBuf, std::io::Error), + + #[error(transparent)] + Network(#[from] network::Error), + + #[error(transparent)] + Locator(#[from] locator::Error), + + #[error(transparent)] + Wasm(#[from] wasm::Error), + + #[error(transparent)] + SpecTools(#[from] soroban_spec_tools::contract::Error), + + #[error("the WASM has no contractmetav0 custom section")] + NoMeta, + + #[error("the WASM's contractmetav0 does not record a `bldimg` entry; cannot verify")] + MissingBldimg, + + #[error("the WASM's contractmetav0 does not record any SEP-58 source-identification entry (source_repo+source_rev, tarball_url, or tarball_sha256); cannot verify")] + MissingSourceId, + + #[error( + "the WASM's `{field}` value {value:?} does not match the SEP-58 format regex `{regex}`" + )] + MetaFormat { + field: &'static str, + value: String, + regex: &'static str, + }, + + #[error("the WASM records `source_rev` but not `source_repo`; SEP-58 requires both together")] + SourceRevWithoutRepo, +} + +/// SEP-58 metadata extracted from a contract's `contractmetav0` section. +/// +/// `cliver` is intentionally not captured: the rebuild container re-injects it, +/// so verify's job is to ensure the rebuild's cliver matches the original's +/// (which it will when `bldimg` resolves to the same container). +#[derive(Debug, Clone)] +pub struct ExtractedMetadata { + pub bldimg: String, + pub source_repo: Option, + pub source_rev: Option, + pub tarball_url: Option, + pub tarball_sha256: Option, + pub bldopts: Vec, +} + +impl Cmd { + pub async fn run(&self, _global_args: &global::Args) -> Result<(), Error> { + let print = Print::new(false); + + let wasm_bytes = self.fetch_wasm().await?; + let meta = extract_metadata(&wasm_bytes)?; + + print.infoln(format!("bldimg: {}", meta.bldimg)); + if let Some(v) = &meta.source_repo { + print.infoln(format!("source_repo: {v}")); + } + if let Some(v) = &meta.source_rev { + print.infoln(format!("source_rev: {v}")); + } + if let Some(v) = &meta.tarball_url { + print.infoln(format!("tarball_url: {v}")); + } + if let Some(v) = &meta.tarball_sha256 { + print.infoln(format!("tarball_sha256: {v}")); + } + if !meta.bldopts.is_empty() { + print.infoln(format!("bldopt entries ({}):", meta.bldopts.len())); + for o in &meta.bldopts { + print.blankln(format!(" • {o}")); + } + } + + Ok(()) + } + + async fn fetch_wasm(&self) -> Result, Error> { + match (&self.contract_id, &self.wasm) { + (Some(id), None) => { + let network = self.network.get(&self.locator)?; + let resolved = + id.resolve_contract_id(&self.locator, &network.network_passphrase)?; + Ok(wasm::fetch_from_contract(&resolved, &network).await?) + } + (None, Some(path)) => std::fs::read(path).map_err(|e| Error::ReadWasm(path.clone(), e)), + _ => Err(Error::MissingInput), + } + } +} + +/// Walk the WASM's `contractmetav0` entries and pull out the SEP-58 fields we +/// need to drive a rebuild. Errors when `bldimg` is absent or when no source +/// identification is recorded, since neither has a sensible default. +pub fn extract_metadata(wasm: &[u8]) -> Result { + let spec = Spec::new(wasm)?; + if spec.meta.is_empty() { + return Err(Error::NoMeta); + } + + let mut bldimg: Option = None; + let mut source_repo: Option = None; + let mut source_rev: Option = None; + let mut tarball_url: Option = None; + let mut tarball_sha256: Option = None; + let mut bldopts: Vec = Vec::new(); + + for entry in &spec.meta { + let ScMetaEntry::ScMetaV0(ScMetaV0 { key, val }) = entry; + let k = key.to_string(); + let v = val.to_string(); + match k.as_str() { + "bldimg" => bldimg = Some(v), + "source_repo" => source_repo = Some(v), + "source_rev" => source_rev = Some(v), + "tarball_url" => tarball_url = Some(v), + "tarball_sha256" => tarball_sha256 = Some(v), + "bldopt" => bldopts.push(v), + _ => {} // cliver and any user --meta are intentionally ignored + } + } + + let bldimg = bldimg.ok_or(Error::MissingBldimg)?; + if !bldimg_regex().is_match(&bldimg) { + return Err(Error::MetaFormat { + field: "bldimg", + value: bldimg, + regex: BLDIMG_REGEX_STR, + }); + } + + if let Some(v) = &source_rev { + if !source_rev_regex().is_match(v) { + return Err(Error::MetaFormat { + field: "source_rev", + value: v.clone(), + regex: SOURCE_REV_REGEX_STR, + }); + } + } + if let Some(v) = &source_repo { + if !source_repo_regex().is_match(v) { + return Err(Error::MetaFormat { + field: "source_repo", + value: v.clone(), + regex: SOURCE_REPO_REGEX_STR, + }); + } + } + if let Some(v) = &tarball_url { + if !tarball_url_regex().is_match(v) { + return Err(Error::MetaFormat { + field: "tarball_url", + value: v.clone(), + regex: TARBALL_URL_REGEX_STR, + }); + } + } + if let Some(v) = &tarball_sha256 { + if !tarball_sha256_regex().is_match(v) { + return Err(Error::MetaFormat { + field: "tarball_sha256", + value: v.clone(), + regex: TARBALL_SHA256_REGEX_STR, + }); + } + } + + // SEP-58 lists `source_repo+source_rev` as a conformant combination. We + // refuse `source_rev` without `source_repo` here so the user sees a + // pointed error rather than a downstream "can't clone repo" surprise. + if source_rev.is_some() && source_repo.is_none() { + return Err(Error::SourceRevWithoutRepo); + } + + if source_repo.is_none() + && source_rev.is_none() + && tarball_url.is_none() + && tarball_sha256.is_none() + { + return Err(Error::MissingSourceId); + } + + Ok(ExtractedMetadata { + bldimg, + source_repo, + source_rev, + tarball_url, + tarball_sha256, + bldopts, + }) +} + +// These mirror the regex strings used in verifiable.rs. They're kept here only +// so `Error::MetaFormat` can render the regex back to the user as part of the +// error message. The actual matching uses the helpers from verifiable.rs. +const BLDIMG_REGEX_STR: &str = + r"^(?:localhost(?::\d+)?|[^\s@/]*[.:][^\s@/]*)/[^\s@]+@sha256:[0-9a-f]{64}$"; +const SOURCE_REV_REGEX_STR: &str = r"^[0-9a-f]{40}$"; +const SOURCE_REPO_REGEX_STR: &str = r"^(https?://\S+|github:[^/\s]+/[^/\s]+)$"; +const TARBALL_URL_REGEX_STR: &str = r"^https?://\S+$"; +const TARBALL_SHA256_REGEX_STR: &str = r"^[0-9a-f]{64}$"; + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + use stellar_xdr::curr::{Limited, Limits, ScMetaEntry, ScMetaV0, WriteXdr}; + + fn make_wasm_with_meta(entries: &[(&str, &str)]) -> Vec { + let xdr = encode_meta(entries); + let mut wasm = empty_wasm_module(); + wasm_gen::write_custom_section(&mut wasm, "contractmetav0", &xdr); + wasm + } + + fn empty_wasm_module() -> Vec { + // Minimal valid WASM: magic + version, no sections. + vec![0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00] + } + + fn encode_meta(entries: &[(&str, &str)]) -> Vec { + let mut buf = Vec::new(); + let mut writer = Limited::new(Cursor::new(&mut buf), Limits::none()); + for (k, v) in entries { + ScMetaEntry::ScMetaV0(ScMetaV0 { + key: (*k).to_string().try_into().unwrap(), + val: (*v).to_string().try_into().unwrap(), + }) + .write_xdr(&mut writer) + .unwrap(); + } + buf + } + + fn good_bldimg() -> String { + format!("docker.io/stellar/stellar-cli@sha256:{}", "a".repeat(64)) + } + + #[test] + fn extract_metadata_happy_path_git_source() { + let wasm = make_wasm_with_meta(&[ + ("bldimg", &good_bldimg()), + ("source_repo", "https://github.com/foo/bar"), + ("source_rev", &"b".repeat(40)), + ("bldopt", "--locked"), + ("bldopt", "--meta=home_domain=fnando.com"), + ("home_domain", "fnando.com"), + ("cliver", "26.0.0#abcdef"), + ]); + let meta = extract_metadata(&wasm).unwrap(); + assert_eq!(meta.bldimg, good_bldimg()); + assert_eq!( + meta.source_repo.as_deref(), + Some("https://github.com/foo/bar") + ); + assert_eq!(meta.source_rev.as_deref(), Some("b".repeat(40).as_str())); + assert_eq!( + meta.bldopts, + vec![ + "--locked".to_string(), + "--meta=home_domain=fnando.com".to_string() + ] + ); + assert!(meta.tarball_url.is_none()); + assert!(meta.tarball_sha256.is_none()); + } + + #[test] + fn extract_metadata_happy_path_tarball_pair() { + let wasm = make_wasm_with_meta(&[ + ("bldimg", &good_bldimg()), + ("tarball_url", "https://example.com/src.tar.gz"), + ("tarball_sha256", &"f".repeat(64)), + ("bldopt", "--locked"), + ]); + let meta = extract_metadata(&wasm).unwrap(); + assert_eq!( + meta.tarball_url.as_deref(), + Some("https://example.com/src.tar.gz") + ); + assert_eq!( + meta.tarball_sha256.as_deref(), + Some("f".repeat(64).as_str()) + ); + assert!(meta.source_repo.is_none()); + assert!(meta.source_rev.is_none()); + } + + #[test] + fn extract_metadata_missing_bldimg_errors() { + let wasm = make_wasm_with_meta(&[ + ("source_repo", "https://github.com/foo/bar"), + ("source_rev", &"b".repeat(40)), + ]); + let err = extract_metadata(&wasm).unwrap_err(); + assert!(matches!(err, Error::MissingBldimg)); + } + + #[test] + fn extract_metadata_missing_source_id_errors() { + let wasm = make_wasm_with_meta(&[("bldimg", &good_bldimg())]); + let err = extract_metadata(&wasm).unwrap_err(); + assert!(matches!(err, Error::MissingSourceId)); + } + + #[test] + fn extract_metadata_source_rev_without_repo_errors() { + let wasm = + make_wasm_with_meta(&[("bldimg", &good_bldimg()), ("source_rev", &"b".repeat(40))]); + let err = extract_metadata(&wasm).unwrap_err(); + assert!(matches!(err, Error::SourceRevWithoutRepo)); + } + + #[test] + fn extract_metadata_bad_bldimg_format_errors() { + let wasm = make_wasm_with_meta(&[ + ("bldimg", "stellar/stellar-cli@sha256:abc"), // implicit hub + short + ("source_repo", "https://github.com/foo/bar"), + ("source_rev", &"b".repeat(40)), + ]); + let err = extract_metadata(&wasm).unwrap_err(); + assert!(matches!( + err, + Error::MetaFormat { + field: "bldimg", + .. + } + )); + } + + #[test] + fn extract_metadata_bad_source_rev_format_errors() { + let wasm = make_wasm_with_meta(&[ + ("bldimg", &good_bldimg()), + ("source_repo", "https://github.com/foo/bar"), + ("source_rev", "not-a-sha"), + ]); + let err = extract_metadata(&wasm).unwrap_err(); + assert!(matches!( + err, + Error::MetaFormat { + field: "source_rev", + .. + } + )); + } + + #[test] + fn extract_metadata_bad_tarball_sha256_format_errors() { + let wasm = make_wasm_with_meta(&[("bldimg", &good_bldimg()), ("tarball_sha256", "abc")]); + let err = extract_metadata(&wasm).unwrap_err(); + assert!(matches!( + err, + Error::MetaFormat { + field: "tarball_sha256", + .. + } + )); + } + + #[test] + fn extract_metadata_ignores_cliver_and_user_meta() { + let wasm = make_wasm_with_meta(&[ + ("bldimg", &good_bldimg()), + ("source_repo", "https://github.com/foo/bar"), + ("source_rev", &"b".repeat(40)), + ("cliver", "26.0.0#abcdef"), + ("home_domain", "fnando.com"), + ("author", "alice"), + ]); + let meta = extract_metadata(&wasm).unwrap(); + // cliver and user meta land in neither bldopts nor source-ids. + assert!(meta.bldopts.is_empty()); + } + + #[test] + fn extract_metadata_empty_meta_errors() { + let wasm = empty_wasm_module(); // no contractmetav0 section + let err = extract_metadata(&wasm).unwrap_err(); + assert!(matches!(err, Error::NoMeta)); + } +} From 2df7217f48c3ee7284bc7e443c73dfdd98e465b7 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Thu, 21 May 2026 17:04:26 -0700 Subject: [PATCH 02/33] Add trust gates to stellar contract verify. --- .../src/commands/contract/verify.rs | 220 ++++++++++++++++++ 1 file changed, 220 insertions(+) diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index 2ed91e7c8e..af2ffbda66 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -1,6 +1,8 @@ +use std::io::{IsTerminal, Write}; use std::path::PathBuf; use clap::Parser; +use regex::Regex; use soroban_spec_tools::contract::Spec; use stellar_xdr::curr::{ScMetaEntry, ScMetaV0}; @@ -87,6 +89,70 @@ pub enum Error { #[error("the WASM records `source_rev` but not `source_repo`; SEP-58 requires both together")] SourceRevWithoutRepo, + + #[error("{kind} {value:?} is not in the default trust list, and stdin is not a terminal so we can't ask. Re-run with --trust to proceed.")] + TrustRequired { kind: TrustKind, value: String }, + + #[error("user declined to trust the {kind}; aborting")] + TrustDeclined { kind: TrustKind }, + + #[error("reading stdin: {0}")] + Stdin(std::io::Error), +} + +/// What kind of source is being trust-checked. Affects the default-trust +/// decision and shapes the prompt + error wording. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TrustKind { + Bldimg, + Tarball, +} + +impl std::fmt::Display for TrustKind { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + TrustKind::Bldimg => write!(f, "bldimg"), + TrustKind::Tarball => write!(f, "tarball"), + } + } +} + +/// Resolution of a single trust check before any I/O happens. Pure function of +/// the input — the run() side decides what to do with each variant. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TrustDecision { + /// The value matches the default trust list for its kind. Proceed silently. + Trusted, + /// The value is not trusted by default, but `--trust` was passed. Proceed + /// (and the caller may want to log). + Overridden, + /// Not trusted; the caller must prompt (TTY) or fail (non-TTY). + NeedsConfirmation, +} + +/// SEP-58 places no defaults on which images are trustworthy; we hardcode the +/// canonical `docker.io/stellar/stellar-cli` repo (digest-pinned) as the only +/// default-trusted image. Any other image — including mirrors and forks — +/// requires explicit confirmation. +const TRUSTED_BLDIMG_REGEX_STR: &str = r"^docker\.io/stellar/stellar-cli@sha256:[0-9a-f]{64}$"; + +fn trusted_bldimg_regex() -> Regex { + Regex::new(TRUSTED_BLDIMG_REGEX_STR).unwrap() +} + +/// Pure trust decision; no I/O. Tarball sources are never default-trusted. +pub fn trust_decision(value: &str, kind: TrustKind, trust_flag: bool) -> TrustDecision { + let default_trusted = match kind { + TrustKind::Bldimg => trusted_bldimg_regex().is_match(value), + TrustKind::Tarball => false, + }; + if default_trusted { + TrustDecision::Trusted + } else if trust_flag { + TrustDecision::Overridden + } else { + TrustDecision::NeedsConfirmation + } } /// SEP-58 metadata extracted from a contract's `contractmetav0` section. @@ -131,9 +197,27 @@ impl Cmd { } } + // bldimg trust check is always required. + require_trust(self.trust, TrustKind::Bldimg, &meta.bldimg, &print)?; + + // Tarball source: trust the URL we will actually fetch from (either the + // value the WASM recorded, or the user's `--tarball-url` override). + if let Some(url) = self.effective_tarball_url(&meta) { + require_trust(self.trust, TrustKind::Tarball, &url, &print)?; + } + Ok(()) } + /// The tarball URL we'll actually retrieve from: the cli override if set, + /// otherwise the value recorded in the WASM. Returns `None` for git-source + /// builds (which aren't trust-checked here). + fn effective_tarball_url(&self, meta: &ExtractedMetadata) -> Option { + self.tarball_url + .clone() + .or_else(|| meta.tarball_url.clone()) + } + async fn fetch_wasm(&self) -> Result, Error> { match (&self.contract_id, &self.wasm) { (Some(id), None) => { @@ -250,6 +334,64 @@ pub fn extract_metadata(wasm: &[u8]) -> Result { }) } +/// Apply the trust decision: silent-OK, log-and-OK on override, or +/// prompt-vs-fail on `NeedsConfirmation` depending on whether stdin is a TTY. +fn require_trust( + trust_flag: bool, + kind: TrustKind, + value: &str, + print: &Print, +) -> Result<(), Error> { + match trust_decision(value, kind, trust_flag) { + TrustDecision::Trusted => Ok(()), + TrustDecision::Overridden => { + print.warnln(format!( + "trusting {kind} {value} because --trust was passed" + )); + Ok(()) + } + TrustDecision::NeedsConfirmation => { + if !std::io::stdin().is_terminal() { + return Err(Error::TrustRequired { + kind, + value: value.to_string(), + }); + } + confirm_interactively(kind, value) + } + } +} + +fn confirm_interactively(kind: TrustKind, value: &str) -> Result<(), Error> { + let prompt = match kind { + TrustKind::Bldimg => format!( + "Image {value} is not in the default trust list (only docker.io/stellar/stellar-cli is trusted by default)." + ), + TrustKind::Tarball => format!( + "Tarball source {value} is not trusted by default. Tarballs always require confirmation." + ), + }; + eprintln!("{prompt}"); + eprint!("Trust this {kind} and continue? [y/N] "); + std::io::stderr().flush().ok(); + let mut line = String::new(); + std::io::stdin() + .read_line(&mut line) + .map_err(Error::Stdin)?; + if parse_yes(&line) { + Ok(()) + } else { + Err(Error::TrustDeclined { kind }) + } +} + +/// Accepts y / Y / yes / YES / Yes (case-insensitive). Anything else, including +/// the empty string, is "no" — trust prompts default to declined. +pub fn parse_yes(answer: &str) -> bool { + let a = answer.trim(); + a.eq_ignore_ascii_case("y") || a.eq_ignore_ascii_case("yes") +} + // These mirror the regex strings used in verifiable.rs. They're kept here only // so `Error::MetaFormat` can render the regex back to the user as part of the // error message. The actual matching uses the helpers from verifiable.rs. @@ -439,4 +581,82 @@ mod tests { let err = extract_metadata(&wasm).unwrap_err(); assert!(matches!(err, Error::NoMeta)); } + + #[test] + fn trust_decision_bldimg_canonical_is_trusted() { + let img = format!("docker.io/stellar/stellar-cli@sha256:{}", "a".repeat(64)); + assert_eq!( + trust_decision(&img, TrustKind::Bldimg, false), + TrustDecision::Trusted + ); + assert_eq!( + trust_decision(&img, TrustKind::Bldimg, true), + TrustDecision::Trusted + ); + } + + #[test] + fn trust_decision_bldimg_other_registry_needs_confirmation() { + let img = format!("ghcr.io/stellar/stellar-cli@sha256:{}", "a".repeat(64)); + assert_eq!( + trust_decision(&img, TrustKind::Bldimg, false), + TrustDecision::NeedsConfirmation + ); + assert_eq!( + trust_decision(&img, TrustKind::Bldimg, true), + TrustDecision::Overridden + ); + } + + #[test] + fn trust_decision_bldimg_other_repo_on_dockerhub_needs_confirmation() { + // Same registry but different repo (fork) — not trusted. + let img = format!("docker.io/fnando/stellar-cli@sha256:{}", "a".repeat(64)); + assert_eq!( + trust_decision(&img, TrustKind::Bldimg, false), + TrustDecision::NeedsConfirmation + ); + } + + #[test] + fn trust_decision_tarball_always_needs_confirmation() { + assert_eq!( + trust_decision( + "https://github.com/foo/bar.tar.gz", + TrustKind::Tarball, + false + ), + TrustDecision::NeedsConfirmation + ); + assert_eq!( + trust_decision("/local/foo.tar.gz", TrustKind::Tarball, false), + TrustDecision::NeedsConfirmation + ); + } + + #[test] + fn trust_decision_tarball_override_with_trust() { + assert_eq!( + trust_decision( + "https://github.com/foo/bar.tar.gz", + TrustKind::Tarball, + true + ), + TrustDecision::Overridden + ); + } + + #[test] + fn parse_yes_accepts_all_case_variants() { + for yes in ["y", "Y", "yes", "YES", "Yes", "yEs", " y ", "yes\n"] { + assert!(parse_yes(yes), "{yes:?} should be yes"); + } + } + + #[test] + fn parse_yes_rejects_anything_else() { + for no in ["", "n", "N", "no", "NO", "x", "yup", "yeah", " "] { + assert!(!parse_yes(no), "{no:?} should not be yes"); + } + } } From 8ad2ff88bb0f8da26b61d0b5dae06ceb2c36f55f Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Thu, 21 May 2026 17:10:40 -0700 Subject: [PATCH 03/33] Materialize source for stellar contract verify. --- cmd/soroban-cli/Cargo.toml | 3 +- .../src/commands/contract/build/verifiable.rs | 4 +- .../src/commands/contract/verify.rs | 408 +++++++++++------- 3 files changed, 251 insertions(+), 164 deletions(-) diff --git a/cmd/soroban-cli/Cargo.toml b/cmd/soroban-cli/Cargo.toml index 9cf393047c..d08065ae36 100644 --- a/cmd/soroban-cli/Cargo.toml +++ b/cmd/soroban-cli/Cargo.toml @@ -114,6 +114,7 @@ futures-util = "0.3.30" futures = "0.3.30" home = "0.5.9" flate2 = "1.0.30" +tar = "0.4.46" bytesize = "1.3.0" humantime = "2.1.0" phf = { version = "0.11.2", features = ["macros"] } @@ -128,8 +129,8 @@ keyring = { version = "3", features = ["apple-native", "windows-native", "sync-s whoami = "1.5.2" serde_with = "3.11.0" rustc_version = "0.4.1" -tar = "0.4.40" ignore = "0.4.26" +walkdir = "2.5.0" [build-dependencies] crate-git-revision = "0.0.9" diff --git a/cmd/soroban-cli/src/commands/contract/build/verifiable.rs b/cmd/soroban-cli/src/commands/contract/build/verifiable.rs index 1fee860a2d..21584d4941 100644 --- a/cmd/soroban-cli/src/commands/contract/build/verifiable.rs +++ b/cmd/soroban-cli/src/commands/contract/build/verifiable.rs @@ -355,11 +355,11 @@ pub(crate) fn bldimg_regex() -> Regex { .unwrap() } -fn source_sha256_regex() -> Regex { +pub(crate) fn source_sha256_regex() -> Regex { Regex::new(r"^[0-9a-f]{64}$").unwrap() } -fn source_uri_regex() -> Regex { +pub(crate) fn source_uri_regex() -> Regex { Regex::new(r"^[a-zA-Z][a-zA-Z0-9+.-]*:\S+$").unwrap() } diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index af2ffbda66..616b843725 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -1,16 +1,16 @@ use std::io::{IsTerminal, Write}; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use clap::Parser; use regex::Regex; +use sha2::{Digest, Sha256}; use soroban_spec_tools::contract::Spec; use stellar_xdr::curr::{ScMetaEntry, ScMetaV0}; use crate::{ commands::{ contract::build::verifiable::{ - bldimg_regex, source_repo_regex, source_rev_regex, tarball_sha256_regex, - tarball_url_regex, + bldimg_regex, source_uri_regex, source_sha256_regex }, global, }, @@ -30,11 +30,11 @@ pub struct Cmd { #[arg(long)] pub wasm: Option, - /// Local tarball file or http(s) URL to use as the source when the WASM's - /// recorded SEP-58 metadata has only `tarball_sha256` (no `tarball_url`). + /// Local source code file or http(s) URL to use as the source when the WASM's + /// recorded SEP-58 metadata has only `source_sha256` (no `source_uri`). /// Accepts http(s) URLs or local file paths. #[arg(long)] - pub tarball_url: Option, + pub source_uri: Option, /// Bypass interactive confirmation when the WASM's bldimg is not in the /// default trust list, or when the source is a tarball (tarballs are @@ -75,8 +75,8 @@ pub enum Error { #[error("the WASM's contractmetav0 does not record a `bldimg` entry; cannot verify")] MissingBldimg, - #[error("the WASM's contractmetav0 does not record any SEP-58 source-identification entry (source_repo+source_rev, tarball_url, or tarball_sha256); cannot verify")] - MissingSourceId, + #[error("the WASM's contractmetav0 does not record a `source_sha256` entry; cannot verify")] + MissingSourceSha256, #[error( "the WASM's `{field}` value {value:?} does not match the SEP-58 format regex `{regex}`" @@ -87,9 +87,6 @@ pub enum Error { regex: &'static str, }, - #[error("the WASM records `source_rev` but not `source_repo`; SEP-58 requires both together")] - SourceRevWithoutRepo, - #[error("{kind} {value:?} is not in the default trust list, and stdin is not a terminal so we can't ask. Re-run with --trust to proceed.")] TrustRequired { kind: TrustKind, value: String }, @@ -98,6 +95,30 @@ pub enum Error { #[error("reading stdin: {0}")] Stdin(std::io::Error), + + #[error("the WASM records only `source_sha256` (no `source_uri`). Pass `--source-uri URL_OR_PATH` to provide retrieval.")] + SourceUriRequired, + + #[error("downloading {url}: {source}")] + SourceDownload { url: String, source: reqwest::Error }, + + #[error("reading local source code {path}: {source}")] + SourceRead { + path: PathBuf, + source: std::io::Error, + }, + + #[error("source code sha256 mismatch: expected {expected}, got {actual}")] + SourceHashMismatch { expected: String, actual: String }, + + #[error("extracting source code into {path}: {source}")] + SourceExtract { + path: PathBuf, + source: std::io::Error, + }, + + #[error("creating tempdir: {0}")] + TempDir(std::io::Error), } /// What kind of source is being trust-checked. Affects the default-trust @@ -163,10 +184,8 @@ pub fn trust_decision(value: &str, kind: TrustKind, trust_flag: bool) -> TrustDe #[derive(Debug, Clone)] pub struct ExtractedMetadata { pub bldimg: String, - pub source_repo: Option, - pub source_rev: Option, - pub tarball_url: Option, - pub tarball_sha256: Option, + pub source_uri: Option, + pub source_sha256: Option, pub bldopts: Vec, } @@ -178,18 +197,15 @@ impl Cmd { let meta = extract_metadata(&wasm_bytes)?; print.infoln(format!("bldimg: {}", meta.bldimg)); - if let Some(v) = &meta.source_repo { - print.infoln(format!("source_repo: {v}")); - } - if let Some(v) = &meta.source_rev { - print.infoln(format!("source_rev: {v}")); - } - if let Some(v) = &meta.tarball_url { - print.infoln(format!("tarball_url: {v}")); + + if let Some(v) = &meta.source_uri { + print.infoln(format!("source_uri: {v}")); } - if let Some(v) = &meta.tarball_sha256 { - print.infoln(format!("tarball_sha256: {v}")); + + if let Some(v) = &meta.source_sha256 { + print.infoln(format!("source_sha256: {v}")); } + if !meta.bldopts.is_empty() { print.infoln(format!("bldopt entries ({}):", meta.bldopts.len())); for o in &meta.bldopts { @@ -201,21 +217,33 @@ impl Cmd { require_trust(self.trust, TrustKind::Bldimg, &meta.bldimg, &print)?; // Tarball source: trust the URL we will actually fetch from (either the - // value the WASM recorded, or the user's `--tarball-url` override). - if let Some(url) = self.effective_tarball_url(&meta) { + // value the WASM recorded, or the user's `--source-uri` override). + if let Some(url) = self.effective_source_uri(&meta) { require_trust(self.trust, TrustKind::Tarball, &url, &print)?; } + // Materialize the recorded source into a tempdir so the next step + // (the rebuild — to land in a follow-up commit) can bind-mount it. + // The TempDir keeps the directory alive only for this scope; the + // rebuild needs to happen before we return. + let workdir = tempfile::TempDir::new().map_err(Error::TempDir)?; + materialize_source(&meta, self.source_uri.as_deref(), workdir.path(), &print).await?; + print.checkln(format!( + "Source materialized at {}", + workdir.path().display() + )); + Ok(()) } /// The tarball URL we'll actually retrieve from: the cli override if set, - /// otherwise the value recorded in the WASM. Returns `None` for git-source - /// builds (which aren't trust-checked here). - fn effective_tarball_url(&self, meta: &ExtractedMetadata) -> Option { - self.tarball_url + /// otherwise the value recorded in the WASM. Returns `None` when neither + /// records a `source_uri` (only `source_sha256` is set), in which case + /// there's nothing to trust-check here. + fn effective_source_uri(&self, meta: &ExtractedMetadata) -> Option { + self.source_uri .clone() - .or_else(|| meta.tarball_url.clone()) + .or_else(|| meta.source_uri.clone()) } async fn fetch_wasm(&self) -> Result, Error> { @@ -233,8 +261,8 @@ impl Cmd { } /// Walk the WASM's `contractmetav0` entries and pull out the SEP-58 fields we -/// need to drive a rebuild. Errors when `bldimg` is absent or when no source -/// identification is recorded, since neither has a sensible default. +/// need to drive a rebuild. Errors when `bldimg` or `source_sha256` is absent, +/// since neither has a sensible default. `source_uri` is optional. pub fn extract_metadata(wasm: &[u8]) -> Result { let spec = Spec::new(wasm)?; if spec.meta.is_empty() { @@ -242,10 +270,8 @@ pub fn extract_metadata(wasm: &[u8]) -> Result { } let mut bldimg: Option = None; - let mut source_repo: Option = None; - let mut source_rev: Option = None; - let mut tarball_url: Option = None; - let mut tarball_sha256: Option = None; + let mut source_uri: Option = None; + let mut source_sha256: Option = None; let mut bldopts: Vec = Vec::new(); for entry in &spec.meta { @@ -254,10 +280,8 @@ pub fn extract_metadata(wasm: &[u8]) -> Result { let v = val.to_string(); match k.as_str() { "bldimg" => bldimg = Some(v), - "source_repo" => source_repo = Some(v), - "source_rev" => source_rev = Some(v), - "tarball_url" => tarball_url = Some(v), - "tarball_sha256" => tarball_sha256 = Some(v), + "source_uri" => source_uri = Some(v), + "source_sha256" => source_sha256 = Some(v), "bldopt" => bldopts.push(v), _ => {} // cliver and any user --meta are intentionally ignored } @@ -272,64 +296,33 @@ pub fn extract_metadata(wasm: &[u8]) -> Result { }); } - if let Some(v) = &source_rev { - if !source_rev_regex().is_match(v) { - return Err(Error::MetaFormat { - field: "source_rev", - value: v.clone(), - regex: SOURCE_REV_REGEX_STR, - }); - } - } - if let Some(v) = &source_repo { - if !source_repo_regex().is_match(v) { - return Err(Error::MetaFormat { - field: "source_repo", - value: v.clone(), - regex: SOURCE_REPO_REGEX_STR, - }); - } - } - if let Some(v) = &tarball_url { - if !tarball_url_regex().is_match(v) { + if let Some(v) = &source_uri { + if !source_uri_regex().is_match(v) { return Err(Error::MetaFormat { - field: "tarball_url", + field: "source_uri", value: v.clone(), - regex: TARBALL_URL_REGEX_STR, + regex: SOURCE_URL_REGEX_STR, }); } } - if let Some(v) = &tarball_sha256 { - if !tarball_sha256_regex().is_match(v) { + if let Some(v) = &source_sha256 { + if !source_sha256_regex().is_match(v) { return Err(Error::MetaFormat { - field: "tarball_sha256", + field: "source_sha256", value: v.clone(), - regex: TARBALL_SHA256_REGEX_STR, + regex: SOURCE_SHA256_REGEX_STR, }); } } - // SEP-58 lists `source_repo+source_rev` as a conformant combination. We - // refuse `source_rev` without `source_repo` here so the user sees a - // pointed error rather than a downstream "can't clone repo" surprise. - if source_rev.is_some() && source_repo.is_none() { - return Err(Error::SourceRevWithoutRepo); - } - - if source_repo.is_none() - && source_rev.is_none() - && tarball_url.is_none() - && tarball_sha256.is_none() - { - return Err(Error::MissingSourceId); + if source_sha256.is_none() { + return Err(Error::MissingSourceSha256); } Ok(ExtractedMetadata { bldimg, - source_repo, - source_rev, - tarball_url, - tarball_sha256, + source_uri, + source_sha256, bldopts, }) } @@ -392,15 +385,101 @@ pub fn parse_yes(answer: &str) -> bool { a.eq_ignore_ascii_case("y") || a.eq_ignore_ascii_case("yes") } +/// Materialize the recorded source tree into `target`. Picks the path based on +/// what the WASM recorded: +/// - source_uri (with optional sha256) → download/read, optional sha-check, +/// extract via `tar` +/// - source_sha256 only → require `--source-uri` on the cli and use it as +/// the retrieval channel +/// +/// `source_uri_override` is the cli's `--source-uri` flag value; when set, it +/// wins over whatever the WASM recorded, and may be an http(s) URL or a local +/// file path. +async fn materialize_source( + meta: &ExtractedMetadata, + source_uri_override: Option<&str>, + target: &Path, + print: &Print, +) -> Result<(), Error> { + let tarball_source = source_uri_override + .map(str::to_string) + .or_else(|| meta.source_uri.clone()); + let Some(source) = tarball_source else { + // No source_uri anywhere — only source_sha256 is set. + return Err(Error::SourceUriRequired); + }; + + print.infoln(format!("Fetching source code from {source}")); + let bytes = fetch_tarball_bytes(&source).await?; + + if let Some(expected) = &meta.source_sha256 { + verify_source_sha256(&bytes, expected)?; + print.checkln("source code sha256 matches"); + } + extract_tarball(&bytes, target)?; + Ok(()) +} + +/// Retrieve the tarball bytes. `source` is either an `http(s)://` URL or a +/// local file path. The split is by prefix, not by attempting both — keeps +/// behavior predictable. +async fn fetch_tarball_bytes(source: &str) -> Result, Error> { + if source.starts_with("http://") || source.starts_with("https://") { + let resp = reqwest::get(source) + .await + .map_err(|e| Error::SourceDownload { + url: source.to_string(), + source: e, + })?; + let bytes = resp + .error_for_status() + .map_err(|e| Error::SourceDownload { + url: source.to_string(), + source: e, + })? + .bytes() + .await + .map_err(|e| Error::SourceDownload { + url: source.to_string(), + source: e, + })?; + Ok(bytes.to_vec()) + } else { + std::fs::read(source).map_err(|e| Error::SourceRead { + path: PathBuf::from(source), + source: e, + }) + } +} + +fn verify_source_sha256(bytes: &[u8], expected: &str) -> Result<(), Error> { + let actual = format!("{:x}", Sha256::digest(bytes)); + if actual.eq_ignore_ascii_case(expected) { + Ok(()) + } else { + Err(Error::SourceHashMismatch { + expected: expected.to_string(), + actual, + }) + } +} + +fn extract_tarball(bytes: &[u8], target: &Path) -> Result<(), Error> { + let gz = flate2::read::GzDecoder::new(bytes); + let mut archive = tar::Archive::new(gz); + archive.unpack(target).map_err(|e| Error::SourceExtract { + path: target.to_path_buf(), + source: e, + }) +} + // These mirror the regex strings used in verifiable.rs. They're kept here only // so `Error::MetaFormat` can render the regex back to the user as part of the // error message. The actual matching uses the helpers from verifiable.rs. const BLDIMG_REGEX_STR: &str = r"^(?:localhost(?::\d+)?|[^\s@/]*[.:][^\s@/]*)/[^\s@]+@sha256:[0-9a-f]{64}$"; -const SOURCE_REV_REGEX_STR: &str = r"^[0-9a-f]{40}$"; -const SOURCE_REPO_REGEX_STR: &str = r"^(https?://\S+|github:[^/\s]+/[^/\s]+)$"; -const TARBALL_URL_REGEX_STR: &str = r"^https?://\S+$"; -const TARBALL_SHA256_REGEX_STR: &str = r"^[0-9a-f]{64}$"; +const SOURCE_URL_REGEX_STR: &str = r"^https?://\S+$"; +const SOURCE_SHA256_REGEX_STR: &str = r"^[0-9a-f]{64}$"; #[cfg(test)] mod tests { @@ -438,62 +517,28 @@ mod tests { format!("docker.io/stellar/stellar-cli@sha256:{}", "a".repeat(64)) } - #[test] - fn extract_metadata_happy_path_git_source() { - let wasm = make_wasm_with_meta(&[ - ("bldimg", &good_bldimg()), - ("source_repo", "https://github.com/foo/bar"), - ("source_rev", &"b".repeat(40)), - ("bldopt", "--locked"), - ("bldopt", "--meta=home_domain=fnando.com"), - ("home_domain", "fnando.com"), - ("cliver", "26.0.0#abcdef"), - ]); - let meta = extract_metadata(&wasm).unwrap(); - assert_eq!(meta.bldimg, good_bldimg()); - assert_eq!( - meta.source_repo.as_deref(), - Some("https://github.com/foo/bar") - ); - assert_eq!(meta.source_rev.as_deref(), Some("b".repeat(40).as_str())); - assert_eq!( - meta.bldopts, - vec![ - "--locked".to_string(), - "--meta=home_domain=fnando.com".to_string() - ] - ); - assert!(meta.tarball_url.is_none()); - assert!(meta.tarball_sha256.is_none()); - } - #[test] fn extract_metadata_happy_path_tarball_pair() { let wasm = make_wasm_with_meta(&[ ("bldimg", &good_bldimg()), - ("tarball_url", "https://example.com/src.tar.gz"), - ("tarball_sha256", &"f".repeat(64)), + ("source_uri", "https://example.com/src.tar.gz"), + ("source_sha256", &"f".repeat(64)), ("bldopt", "--locked"), ]); let meta = extract_metadata(&wasm).unwrap(); assert_eq!( - meta.tarball_url.as_deref(), + meta.source_uri.as_deref(), Some("https://example.com/src.tar.gz") ); assert_eq!( - meta.tarball_sha256.as_deref(), + meta.source_sha256.as_deref(), Some("f".repeat(64).as_str()) ); - assert!(meta.source_repo.is_none()); - assert!(meta.source_rev.is_none()); } #[test] fn extract_metadata_missing_bldimg_errors() { - let wasm = make_wasm_with_meta(&[ - ("source_repo", "https://github.com/foo/bar"), - ("source_rev", &"b".repeat(40)), - ]); + let wasm = make_wasm_with_meta(&[("source_sha256", &"b".repeat(64))]); let err = extract_metadata(&wasm).unwrap_err(); assert!(matches!(err, Error::MissingBldimg)); } @@ -502,23 +547,14 @@ mod tests { fn extract_metadata_missing_source_id_errors() { let wasm = make_wasm_with_meta(&[("bldimg", &good_bldimg())]); let err = extract_metadata(&wasm).unwrap_err(); - assert!(matches!(err, Error::MissingSourceId)); - } - - #[test] - fn extract_metadata_source_rev_without_repo_errors() { - let wasm = - make_wasm_with_meta(&[("bldimg", &good_bldimg()), ("source_rev", &"b".repeat(40))]); - let err = extract_metadata(&wasm).unwrap_err(); - assert!(matches!(err, Error::SourceRevWithoutRepo)); + assert!(matches!(err, Error::MissingSourceSha256)); } #[test] fn extract_metadata_bad_bldimg_format_errors() { let wasm = make_wasm_with_meta(&[ ("bldimg", "stellar/stellar-cli@sha256:abc"), // implicit hub + short - ("source_repo", "https://github.com/foo/bar"), - ("source_rev", &"b".repeat(40)), + ("source_sha256", &"b".repeat(64)), ]); let err = extract_metadata(&wasm).unwrap_err(); assert!(matches!( @@ -531,30 +567,13 @@ mod tests { } #[test] - fn extract_metadata_bad_source_rev_format_errors() { - let wasm = make_wasm_with_meta(&[ - ("bldimg", &good_bldimg()), - ("source_repo", "https://github.com/foo/bar"), - ("source_rev", "not-a-sha"), - ]); + fn extract_metadata_bad_source_sha256_format_errors() { + let wasm = make_wasm_with_meta(&[("bldimg", &good_bldimg()), ("source_sha256", "abc")]); let err = extract_metadata(&wasm).unwrap_err(); assert!(matches!( err, Error::MetaFormat { - field: "source_rev", - .. - } - )); - } - - #[test] - fn extract_metadata_bad_tarball_sha256_format_errors() { - let wasm = make_wasm_with_meta(&[("bldimg", &good_bldimg()), ("tarball_sha256", "abc")]); - let err = extract_metadata(&wasm).unwrap_err(); - assert!(matches!( - err, - Error::MetaFormat { - field: "tarball_sha256", + field: "source_sha256", .. } )); @@ -564,8 +583,7 @@ mod tests { fn extract_metadata_ignores_cliver_and_user_meta() { let wasm = make_wasm_with_meta(&[ ("bldimg", &good_bldimg()), - ("source_repo", "https://github.com/foo/bar"), - ("source_rev", &"b".repeat(40)), + ("source_sha256", &"b".repeat(64)), ("cliver", "26.0.0#abcdef"), ("home_domain", "fnando.com"), ("author", "alice"), @@ -659,4 +677,72 @@ mod tests { assert!(!parse_yes(no), "{no:?} should not be yes"); } } + + #[test] + fn verify_source_sha256_matches() { + let bytes = b"hello, sep-58"; + let digest = format!("{:x}", Sha256::digest(bytes)); + verify_source_sha256(bytes, &digest).unwrap(); + // Case-insensitive: SEP-58 mandates lowercase but be lenient on input. + verify_source_sha256(bytes, &digest.to_ascii_uppercase()).unwrap(); + } + + #[test] + fn verify_source_sha256_mismatch_errors() { + let bytes = b"hello, sep-58"; + let bogus = "0".repeat(64); + let err = verify_source_sha256(bytes, &bogus).unwrap_err(); + assert!(matches!(err, Error::SourceHashMismatch { .. })); + } + + /// Build a tiny in-memory tar.gz with a single file and confirm extraction + /// drops the file at the expected path. Exercises the pure-Rust pipeline + /// (no shelling out, so this passes on Windows too). + #[test] + fn extract_tarball_unpacks_into_target() { + use flate2::write::GzEncoder; + use flate2::Compression; + use std::io::Write; + + let mut tar_bytes = Vec::new(); + { + let mut builder = tar::Builder::new(&mut tar_bytes); + let payload = b"contents"; + let mut header = tar::Header::new_gnu(); + header.set_path("hello.txt").unwrap(); + header.set_size(payload.len() as u64); + header.set_mode(0o644); + header.set_cksum(); + builder.append(&header, &payload[..]).unwrap(); + builder.finish().unwrap(); + } + + let mut gz = Vec::new(); + { + let mut enc = GzEncoder::new(&mut gz, Compression::default()); + enc.write_all(&tar_bytes).unwrap(); + enc.finish().unwrap(); + } + + let dir = tempfile::TempDir::new().unwrap(); + extract_tarball(&gz, dir.path()).unwrap(); + let extracted = std::fs::read(dir.path().join("hello.txt")).unwrap(); + assert_eq!(extracted, b"contents"); + } + + #[tokio::test] + async fn materialize_source_errors_when_only_source_sha256() { + let meta = ExtractedMetadata { + bldimg: good_bldimg(), + source_uri: None, + source_sha256: Some("f".repeat(64)), + bldopts: Vec::new(), + }; + let dir = tempfile::TempDir::new().unwrap(); + let print = Print::new(true); + let err = materialize_source(&meta, None, dir.path(), &print) + .await + .unwrap_err(); + assert!(matches!(err, Error::SourceUriRequired)); + } } From 5164cf2fea84c6d9d743d2aebd69ef8f7d9c8322 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Thu, 21 May 2026 17:16:43 -0700 Subject: [PATCH 04/33] Rebuild and byte-compare in stellar contract verify. --- Cargo.lock | 1 + FULL_HELP_DOCS.md | 1 + .../src/commands/contract/build/verifiable.rs | 4 +- .../src/commands/contract/verify.rs | 306 +++++++++++++++++- 4 files changed, 304 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index aba5091f09..48a80191f2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5465,6 +5465,7 @@ dependencies = [ "tracing-subscriber", "ulid", "url", + "walkdir", "wasm-gen", "wasm-opt", "wasmparser 0.116.1", diff --git a/FULL_HELP_DOCS.md b/FULL_HELP_DOCS.md index 3068a7f562..6106b81fd0 100644 --- a/FULL_HELP_DOCS.md +++ b/FULL_HELP_DOCS.md @@ -1179,6 +1179,7 @@ Verify that a contract's WASM reproduces from the build metadata it records, per - `--wasm ` — Local WASM file to verify, instead of fetching from the network - `--tarball-url ` — Local tarball file or http(s) URL to use as the source when the WASM's recorded SEP-58 metadata has only `tarball_sha256` (no `tarball_url`). Accepts http(s) URLs or local file paths - `--trust` — Bypass interactive confirmation when the WASM's bldimg is not in the default trust list, or when the source is a tarball (tarballs are never default-trusted) +- `-d`, `--docker-host ` — Optional argument to override the default docker host. This is useful when you are using a non-standard docker host path for your Docker-compatible container runtime, e.g. Docker Desktop defaults to $HOME/.docker/run/docker.sock instead of /var/run/docker.sock ###### **RPC Options:** diff --git a/cmd/soroban-cli/src/commands/contract/build/verifiable.rs b/cmd/soroban-cli/src/commands/contract/build/verifiable.rs index 21584d4941..d5f226b098 100644 --- a/cmd/soroban-cli/src/commands/contract/build/verifiable.rs +++ b/cmd/soroban-cli/src/commands/contract/build/verifiable.rs @@ -527,7 +527,7 @@ fn build_metadata_args(image_ref: &str, ids: &SourceIds, bldopts: &[String]) -> out } -fn compose_container_args(forwarded: &[String], metadata: &[String]) -> Vec { +pub(crate) fn compose_container_args(forwarded: &[String], metadata: &[String]) -> Vec { let mut args = vec!["contract".to_string(), "build".to_string()]; args.extend_from_slice(forwarded); args.extend_from_slice(metadata); @@ -862,7 +862,7 @@ async fn wait_for_termination_signal() { } #[allow(clippy::too_many_arguments)] -async fn run_in_container( +pub(crate) async fn run_in_container( image_ref: &str, workspace_root: &Path, container_cmds: &[Vec], diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index 616b843725..be9078e2d8 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -9,8 +9,9 @@ use stellar_xdr::curr::{ScMetaEntry, ScMetaV0}; use crate::{ commands::{ + container, contract::build::verifiable::{ - bldimg_regex, source_uri_regex, source_sha256_regex + self, bldimg_regex, source_sha256_regex, source_uri_regex, }, global, }, @@ -47,6 +48,9 @@ pub struct Cmd { #[command(flatten)] pub network: network::Args, + + #[command(flatten)] + pub container_args: container::shared::Args, } #[derive(thiserror::Error, Debug)] @@ -119,6 +123,35 @@ pub enum Error { #[error("creating tempdir: {0}")] TempDir(std::io::Error), + + #[error(transparent)] + Verifiable(#[from] verifiable::Error), + + #[error(transparent)] + Bollard(#[from] bollard::errors::Error), + + #[error(transparent)] + DockerConnection(#[from] container::shared::Error), + + #[error("could not find a rebuilt WASM under {target}")] + NoRebuiltWasm { target: PathBuf }, + + #[error("multiple rebuilt WASMs under {target}; pass --package=... in the bldopt entries to disambiguate. Found: {found}")] + AmbiguousRebuiltWasm { target: PathBuf, found: String }, + + #[error("reading rebuilt wasm {path}: {source}")] + ReadRebuilt { + path: PathBuf, + source: std::io::Error, + }, + + #[error("verification failed: rebuilt bytes do not match the original.\n original: {original_size} bytes, sha256={original_hash}\n rebuilt: {rebuilt_size} bytes, sha256={rebuilt_hash}")] + VerificationMismatch { + original_hash: String, + original_size: usize, + rebuilt_hash: String, + rebuilt_size: usize, + }, } /// What kind of source is being trust-checked. Affects the default-trust @@ -222,10 +255,9 @@ impl Cmd { require_trust(self.trust, TrustKind::Tarball, &url, &print)?; } - // Materialize the recorded source into a tempdir so the next step - // (the rebuild — to land in a follow-up commit) can bind-mount it. - // The TempDir keeps the directory alive only for this scope; the - // rebuild needs to happen before we return. + // Materialize the recorded source into a tempdir so the rebuild can + // bind-mount it. TempDir lives across the rebuild + comparison and + // cleans up on drop. let workdir = tempfile::TempDir::new().map_err(Error::TempDir)?; materialize_source(&meta, self.source_uri.as_deref(), workdir.path(), &print).await?; print.checkln(format!( @@ -233,7 +265,46 @@ impl Cmd { workdir.path().display() )); - Ok(()) + // Rebuild in the recorded bldimg. + let docker = self.container_args.connect_to_docker(&print).await?; + verifiable::pull_image(&docker, &meta.bldimg, &print).await?; + let container_cmd = build_container_command(&meta); + verifiable::run_in_container( + &meta.bldimg, + workdir.path(), + &[container_cmd], + &[], + &docker, + &print, + false, + ) + .await?; + + // Locate the rebuilt WASM. The cargo target dir lives under the bind- + // mounted /source, which we mapped to `workdir`. + let rebuilt_path = find_rebuilt_wasm(workdir.path(), &meta)?; + let rebuilt = std::fs::read(&rebuilt_path).map_err(|e| Error::ReadRebuilt { + path: rebuilt_path.clone(), + source: e, + })?; + + // Compare. + let original_hash = format!("{:x}", Sha256::digest(&wasm_bytes)); + let rebuilt_hash = format!("{:x}", Sha256::digest(&rebuilt)); + if original_hash == rebuilt_hash && wasm_bytes.len() == rebuilt.len() { + print.checkln(format!( + "verified: {} bytes, sha256={original_hash}", + wasm_bytes.len() + )); + Ok(()) + } else { + Err(Error::VerificationMismatch { + original_hash, + original_size: wasm_bytes.len(), + rebuilt_hash, + rebuilt_size: rebuilt.len(), + }) + } } /// The tarball URL we'll actually retrieve from: the cli override if set, @@ -473,6 +544,108 @@ fn extract_tarball(bytes: &[u8], target: &Path) -> Result<(), Error> { }) } +/// Compose the argv we hand to the container's `stellar contract build` so +/// that: +/// - the bldopts from the original build become flags (each entry is one +/// token, ready for clap), AND +/// - bldimg / source-ids / bldopt are re-recorded as `--meta` entries so +/// the rebuilt WASM has identical metadata to the original. +/// +/// cliver is intentionally not re-injected — the container's stellar adds it +/// automatically, and it will match the original's iff `bldimg` resolves to +/// the same container. +fn build_container_command(meta: &ExtractedMetadata) -> Vec { + let mut forwarded: Vec = meta.bldopts.clone(); + let mut metadata: Vec = Vec::new(); + + let mut push_meta = |k: &str, v: &str| { + metadata.push("--meta".to_string()); + metadata.push(format!("{k}={v}")); + }; + push_meta("bldimg", &meta.bldimg); + if let Some(v) = &meta.source_uri { + push_meta("source_uri", v); + } + if let Some(v) = &meta.source_sha256 { + push_meta("source_sha256", v); + } + for o in &meta.bldopts { + push_meta("bldopt", o); + } + + // `--locked` is always sent — even if the original somehow lacked it (a + // non-conformant build), the verifier insists on a locked rebuild so + // dependency drift can't move bytes underneath us. + if !forwarded.iter().any(|a| a == "--locked") { + forwarded.insert(0, "--locked".to_string()); + } + + verifiable::compose_container_args(&forwarded, &metadata) +} + +/// Locate the rebuilt WASM under `workdir`. The container writes to +/// `/target/wasm32v1-none/release/.wasm` (or `wasm32-unknown-unknown/release` +/// for older toolchains; check both). If a `--package=` bldopt was +/// recorded, prefer that file. +fn find_rebuilt_wasm(workdir: &Path, meta: &ExtractedMetadata) -> Result { + let preferred_pkg = meta + .bldopts + .iter() + .find_map(|opt| opt.strip_prefix("--package=").map(|s| s.replace('-', "_"))); + + let candidates = [ + workdir.join("target/wasm32v1-none/release"), + workdir.join("target/wasm32-unknown-unknown/release"), + ]; + + let mut found: Vec = Vec::new(); + for dir in &candidates { + if !dir.is_dir() { + continue; + } + for entry in std::fs::read_dir(dir).map_err(|e| Error::ReadRebuilt { + path: dir.clone(), + source: e, + })? { + let p = entry + .map_err(|e| Error::ReadRebuilt { + path: dir.clone(), + source: e, + })? + .path(); + if p.extension().and_then(|s| s.to_str()) == Some("wasm") { + found.push(p); + } + } + } + + if let Some(pkg) = &preferred_pkg { + let want = format!("{pkg}.wasm"); + if let Some(p) = found.iter().find(|p| { + p.file_name() + .and_then(|s| s.to_str()) + .is_some_and(|n| n == want) + }) { + return Ok(p.clone()); + } + } + + match found.len() { + 0 => Err(Error::NoRebuiltWasm { + target: workdir.join("target"), + }), + 1 => Ok(found.into_iter().next().unwrap()), + _ => Err(Error::AmbiguousRebuiltWasm { + target: workdir.join("target"), + found: found + .iter() + .map(|p| p.display().to_string()) + .collect::>() + .join(", "), + }), + } +} + // These mirror the regex strings used in verifiable.rs. They're kept here only // so `Error::MetaFormat` can render the regex back to the user as part of the // error message. The actual matching uses the helpers from verifiable.rs. @@ -745,4 +918,125 @@ mod tests { .unwrap_err(); assert!(matches!(err, Error::SourceUriRequired)); } + + #[test] + fn build_container_command_replays_bldopts_and_re_records_meta() { + let meta = ExtractedMetadata { + bldimg: good_bldimg(), + source_uri: Some("https://github.com/foo/bar".to_string()), + source_sha256: Some("b".repeat(64)), + bldopts: vec![ + "--locked".to_string(), + "--meta=home_domain=fnando.com".to_string(), + "--optimize".to_string(), + ], + }; + let cmd = build_container_command(&meta); + + // Subcommand prefix. + assert_eq!(&cmd[..2], &["contract".to_string(), "build".to_string()]); + + // Bldopts are forwarded verbatim as flags to the inner `stellar contract build`. + assert!(cmd.contains(&"--locked".to_string())); + assert!(cmd.contains(&"--meta=home_domain=fnando.com".to_string())); + assert!(cmd.contains(&"--optimize".to_string())); + + // bldimg and source-ids are re-recorded as `--meta`. + assert!(cmd + .windows(2) + .any(|w| w[0] == "--meta" && w[1] == format!("bldimg={}", good_bldimg()))); + assert!(cmd + .windows(2) + .any(|w| w[0] == "--meta" && w[1] == "source_uri=https://github.com/foo/bar")); + + // Every bldopt is also re-recorded as a `bldopt=` meta so the rebuilt + // WASM mirrors the original's entries. + assert!(cmd + .windows(2) + .any(|w| w[0] == "--meta" && w[1] == "bldopt=--locked")); + } + + #[test] + fn build_container_command_injects_locked_when_missing() { + // A non-conformant origin might not have --locked in bldopts. Verify + // forces it anyway so dependency drift cannot move bytes. + let meta = ExtractedMetadata { + bldimg: good_bldimg(), + source_uri: Some("https://github.com/foo/bar".to_string()), + source_sha256: Some("b".repeat(64)), + bldopts: vec!["--meta=author=alice".to_string()], + }; + let cmd = build_container_command(&meta); + let locked_count = cmd.iter().filter(|s| *s == "--locked").count(); + assert_eq!( + locked_count, 1, + "expected exactly one --locked, got {locked_count} in {cmd:?}" + ); + } + + #[test] + fn find_rebuilt_wasm_picks_single() { + let dir = tempfile::TempDir::new().unwrap(); + let release = dir.path().join("target/wasm32v1-none/release"); + std::fs::create_dir_all(&release).unwrap(); + std::fs::write(release.join("hello.wasm"), b"x").unwrap(); + + let meta = ExtractedMetadata { + bldimg: good_bldimg(), + source_uri: Some("https://github.com/foo/bar".to_string()), + source_sha256: Some("b".repeat(64)), + bldopts: vec![], + }; + let p = find_rebuilt_wasm(dir.path(), &meta).unwrap(); + assert!(p.ends_with("hello.wasm")); + } + + #[test] + fn find_rebuilt_wasm_disambiguates_by_package() { + let dir = tempfile::TempDir::new().unwrap(); + let release = dir.path().join("target/wasm32v1-none/release"); + std::fs::create_dir_all(&release).unwrap(); + std::fs::write(release.join("hello.wasm"), b"x").unwrap(); + std::fs::write(release.join("other_thing.wasm"), b"x").unwrap(); + + let meta = ExtractedMetadata { + bldimg: good_bldimg(), + source_uri: Some("https://github.com/foo/bar".to_string()), + source_sha256: Some("b".repeat(64)), + bldopts: vec!["--package=other-thing".to_string()], + }; + let p = find_rebuilt_wasm(dir.path(), &meta).unwrap(); + assert!(p.ends_with("other_thing.wasm")); + } + + #[test] + fn find_rebuilt_wasm_errors_when_ambiguous_without_package() { + let dir = tempfile::TempDir::new().unwrap(); + let release = dir.path().join("target/wasm32v1-none/release"); + std::fs::create_dir_all(&release).unwrap(); + std::fs::write(release.join("hello.wasm"), b"x").unwrap(); + std::fs::write(release.join("other.wasm"), b"x").unwrap(); + + let meta = ExtractedMetadata { + bldimg: good_bldimg(), + source_uri: Some("https://github.com/foo/bar".to_string()), + source_sha256: Some("b".repeat(64)), + bldopts: vec![], + }; + let err = find_rebuilt_wasm(dir.path(), &meta).unwrap_err(); + assert!(matches!(err, Error::AmbiguousRebuiltWasm { .. })); + } + + #[test] + fn find_rebuilt_wasm_errors_when_none() { + let dir = tempfile::TempDir::new().unwrap(); + let meta = ExtractedMetadata { + bldimg: good_bldimg(), + source_uri: Some("https://github.com/foo/bar".to_string()), + source_sha256: Some("b".repeat(64)), + bldopts: vec![], + }; + let err = find_rebuilt_wasm(dir.path(), &meta).unwrap_err(); + assert!(matches!(err, Error::NoRebuiltWasm { .. })); + } } From 63d0d331233797c43c4da426e913d805c47390a9 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Thu, 21 May 2026 17:29:59 -0700 Subject: [PATCH 05/33] Use direct --docker-host field on contract verify. --- FULL_HELP_DOCS.md | 2 +- cmd/soroban-cli/src/commands/contract/verify.rs | 12 ++++++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/FULL_HELP_DOCS.md b/FULL_HELP_DOCS.md index 6106b81fd0..0853bbb6a9 100644 --- a/FULL_HELP_DOCS.md +++ b/FULL_HELP_DOCS.md @@ -1179,7 +1179,7 @@ Verify that a contract's WASM reproduces from the build metadata it records, per - `--wasm ` — Local WASM file to verify, instead of fetching from the network - `--tarball-url ` — Local tarball file or http(s) URL to use as the source when the WASM's recorded SEP-58 metadata has only `tarball_sha256` (no `tarball_url`). Accepts http(s) URLs or local file paths - `--trust` — Bypass interactive confirmation when the WASM's bldimg is not in the default trust list, or when the source is a tarball (tarballs are never default-trusted) -- `-d`, `--docker-host ` — Optional argument to override the default docker host. This is useful when you are using a non-standard docker host path for your Docker-compatible container runtime, e.g. Docker Desktop defaults to $HOME/.docker/run/docker.sock instead of /var/run/docker.sock +- `-d`, `--docker-host ` — Override the default docker host used by the rebuild ###### **RPC Options:** diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index be9078e2d8..56ffbe5f49 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -43,14 +43,15 @@ pub struct Cmd { #[arg(long)] pub trust: bool, + /// Override the default docker host used by the rebuild. + #[arg(short = 'd', long, env = "DOCKER_HOST")] + pub docker_host: Option, + #[command(flatten)] pub locator: locator::Args, #[command(flatten)] pub network: network::Args, - - #[command(flatten)] - pub container_args: container::shared::Args, } #[derive(thiserror::Error, Debug)] @@ -266,7 +267,10 @@ impl Cmd { )); // Rebuild in the recorded bldimg. - let docker = self.container_args.connect_to_docker(&print).await?; + let docker_args = container::shared::Args { + docker_host: self.docker_host.clone(), + }; + let docker = docker_args.connect_to_docker(&print).await?; verifiable::pull_image(&docker, &meta.bldimg, &print).await?; let container_cmd = build_container_command(&meta); verifiable::run_in_container( From cb21dc9f97d46d7b232b05d580c59e1547705a8d Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Thu, 21 May 2026 17:34:24 -0700 Subject: [PATCH 06/33] Use question and warn emojis on trust prompt. --- cmd/soroban-cli/src/commands/contract/verify.rs | 10 +++++----- cmd/soroban-cli/src/print.rs | 1 + 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index 56ffbe5f49..cd789cd85b 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -425,13 +425,13 @@ fn require_trust( value: value.to_string(), }); } - confirm_interactively(kind, value) + confirm_interactively(kind, value, print) } } } -fn confirm_interactively(kind: TrustKind, value: &str) -> Result<(), Error> { - let prompt = match kind { +fn confirm_interactively(kind: TrustKind, value: &str, print: &Print) -> Result<(), Error> { + let context = match kind { TrustKind::Bldimg => format!( "Image {value} is not in the default trust list (only docker.io/stellar/stellar-cli is trusted by default)." ), @@ -439,8 +439,8 @@ fn confirm_interactively(kind: TrustKind, value: &str) -> Result<(), Error> { "Tarball source {value} is not trusted by default. Tarballs always require confirmation." ), }; - eprintln!("{prompt}"); - eprint!("Trust this {kind} and continue? [y/N] "); + print.warnln(context); + print.question(format!("Trust this {kind} and continue? [y/N] ")); std::io::stderr().flush().ok(); let mut line = String::new(); std::io::stdin() diff --git a/cmd/soroban-cli/src/print.rs b/cmd/soroban-cli/src/print.rs index 995a45a78f..e2a1a88864 100644 --- a/cmd/soroban-cli/src/print.rs +++ b/cmd/soroban-cli/src/print.rs @@ -160,6 +160,7 @@ create_print_functions!(event, eventln, "📅"); create_print_functions!(blank, blankln, " "); create_print_functions!(gear, gearln, "⚙️"); create_print_functions!(dir, dirln, "📁"); +create_print_functions!(question, questionln, "❓"); #[cfg(test)] mod tests { From ee1196139d581fe431bbe87cdd79e51462b7b90d Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Thu, 21 May 2026 17:45:03 -0700 Subject: [PATCH 07/33] Respect --verbose and --quiet on contract verify. --- cmd/soroban-cli/src/commands/contract/verify.rs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index cd789cd85b..f3c6182610 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -224,8 +224,8 @@ pub struct ExtractedMetadata { } impl Cmd { - pub async fn run(&self, _global_args: &global::Args) -> Result<(), Error> { - let print = Print::new(false); + pub async fn run(&self, global_args: &global::Args) -> Result<(), Error> { + let print = Print::new(global_args.quiet); let wasm_bytes = self.fetch_wasm().await?; let meta = extract_metadata(&wasm_bytes)?; @@ -280,7 +280,7 @@ impl Cmd { &[], &docker, &print, - false, + global_args.verbose || global_args.very_verbose, ) .await?; @@ -292,11 +292,13 @@ impl Cmd { source: e, })?; - // Compare. + // Compare. The final result is always shown, even under `--quiet`, + // via a dedicated Print that ignores the quiet flag. + let result_print = Print::new(false); let original_hash = format!("{:x}", Sha256::digest(&wasm_bytes)); let rebuilt_hash = format!("{:x}", Sha256::digest(&rebuilt)); if original_hash == rebuilt_hash && wasm_bytes.len() == rebuilt.len() { - print.checkln(format!( + result_print.checkln(format!( "verified: {} bytes, sha256={original_hash}", wasm_bytes.len() )); From c0fd99ecd93a598a9db3c4e288c706b2935ee2fe Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Thu, 21 May 2026 17:47:42 -0700 Subject: [PATCH 08/33] Force trust prompts visible even under --quiet. --- cmd/soroban-cli/src/commands/contract/verify.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index f3c6182610..b5121e35fb 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -427,12 +427,15 @@ fn require_trust( value: value.to_string(), }); } - confirm_interactively(kind, value, print) + confirm_interactively(kind, value) } } } -fn confirm_interactively(kind: TrustKind, value: &str, print: &Print) -> Result<(), Error> { +fn confirm_interactively(kind: TrustKind, value: &str) -> Result<(), Error> { + // Trust prompts must be visible even under `--quiet` so the user can see + // what they're agreeing to. Use a dedicated Print that ignores the flag. + let print = Print::new(false); let context = match kind { TrustKind::Bldimg => format!( "Image {value} is not in the default trust list (only docker.io/stellar/stellar-cli is trusted by default)." From 525724aa629f1f80b8eab0bec7285ce809c74ca9 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Thu, 21 May 2026 17:48:32 -0700 Subject: [PATCH 09/33] Capitalize Verified result line. --- cmd/soroban-cli/src/commands/contract/verify.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index b5121e35fb..ce13d8bb9b 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -299,7 +299,7 @@ impl Cmd { let rebuilt_hash = format!("{:x}", Sha256::digest(&rebuilt)); if original_hash == rebuilt_hash && wasm_bytes.len() == rebuilt.len() { result_print.checkln(format!( - "verified: {} bytes, sha256={original_hash}", + "Verified: {} bytes, sha256={original_hash}", wasm_bytes.len() )); Ok(()) From 519f4aa96310d6d9d140bcda3afc2031ca602cb0 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Thu, 21 May 2026 19:43:08 -0700 Subject: [PATCH 10/33] Capitalize info, warn, and check messages on contract verify. --- cmd/soroban-cli/src/commands/contract/verify.rs | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index ce13d8bb9b..4e0139b656 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -230,18 +230,16 @@ impl Cmd { let wasm_bytes = self.fetch_wasm().await?; let meta = extract_metadata(&wasm_bytes)?; - print.infoln(format!("bldimg: {}", meta.bldimg)); - + print.infoln(format!("Build image: {}", meta.bldimg)); if let Some(v) = &meta.source_uri { - print.infoln(format!("source_uri: {v}")); + print.infoln(format!("Source URI: {v}")); } - if let Some(v) = &meta.source_sha256 { - print.infoln(format!("source_sha256: {v}")); + print.infoln(format!("Source SHA-256: {v}")); } if !meta.bldopts.is_empty() { - print.infoln(format!("bldopt entries ({}):", meta.bldopts.len())); + print.infoln(format!("Build options ({}):", meta.bldopts.len())); for o in &meta.bldopts { print.blankln(format!(" • {o}")); } @@ -416,7 +414,7 @@ fn require_trust( TrustDecision::Trusted => Ok(()), TrustDecision::Overridden => { print.warnln(format!( - "trusting {kind} {value} because --trust was passed" + "Trusting {kind} {value} because --trust was passed" )); Ok(()) } @@ -491,10 +489,9 @@ async fn materialize_source( print.infoln(format!("Fetching source code from {source}")); let bytes = fetch_tarball_bytes(&source).await?; - if let Some(expected) = &meta.source_sha256 { verify_source_sha256(&bytes, expected)?; - print.checkln("source code sha256 matches"); + print.checkln("Source SHA-256 matches"); } extract_tarball(&bytes, target)?; Ok(()) From 4894a02f31591852451069019a4c73c217d59ec5 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Thu, 21 May 2026 20:21:48 -0700 Subject: [PATCH 11/33] Expand github:user/repo source_repo before git clone. --- .../src/commands/contract/verify.rs | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index 4e0139b656..92f9b2df82 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -925,6 +925,37 @@ mod tests { assert!(matches!(err, Error::SourceUriRequired)); } + #[test] + fn expand_source_repo_rewrites_github_shorthand() { + assert_eq!( + expand_source_repo("github:foo/bar"), + "https://github.com/foo/bar" + ); + } + + #[test] + fn expand_source_repo_passes_through_https() { + assert_eq!( + expand_source_repo("https://github.com/foo/bar"), + "https://github.com/foo/bar" + ); + assert_eq!( + expand_source_repo("https://gitlab.com/foo/bar.git"), + "https://gitlab.com/foo/bar.git" + ); + } + + #[test] + fn expand_source_repo_does_not_expand_malformed_github() { + // Missing the `/repo` suffix; the regex won't match so we pass through. + assert_eq!(expand_source_repo("github:foo"), "github:foo"); + // Extra path component; same. + assert_eq!( + expand_source_repo("github:foo/bar/baz"), + "github:foo/bar/baz" + ); + } + #[test] fn build_container_command_replays_bldopts_and_re_records_meta() { let meta = ExtractedMetadata { From 3f012ee12ebdbb1d36f3e974f11ba322bb624356 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Thu, 21 May 2026 20:22:45 -0700 Subject: [PATCH 12/33] Validate retrieval channel before trust prompts. --- cmd/soroban-cli/src/commands/contract/verify.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index 92f9b2df82..a21de68308 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -245,6 +245,15 @@ impl Cmd { } } + // Catch the no-retrieval-channel case before any trust prompts so a + // doomed run errors immediately instead of asking the user to trust + // an image we won't end up using. + let has_git_source = meta.source_repo.is_some() && meta.source_rev.is_some(); + let has_tarball_url = self.tarball_url.is_some() || meta.tarball_url.is_some(); + if !has_git_source && !has_tarball_url { + return Err(Error::TarballUrlRequired); + } + // bldimg trust check is always required. require_trust(self.trust, TrustKind::Bldimg, &meta.bldimg, &print)?; From f8e39601da6eb2a55bc9a5752585a00bf25a0d66 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Fri, 22 May 2026 00:04:09 -0700 Subject: [PATCH 13/33] Anchor verify rebuilt-wasm search at manifest-path parent. --- .../src/commands/contract/verify.rs | 22 +++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index a21de68308..14361436f5 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -608,9 +608,23 @@ fn find_rebuilt_wasm(workdir: &Path, meta: &ExtractedMetadata) -> Result = Vec::new(); @@ -647,11 +661,11 @@ fn find_rebuilt_wasm(workdir: &Path, meta: &ExtractedMetadata) -> Result Err(Error::NoRebuiltWasm { - target: workdir.join("target"), + target: target_base.join("target"), }), 1 => Ok(found.into_iter().next().unwrap()), _ => Err(Error::AmbiguousRebuiltWasm { - target: workdir.join("target"), + target: target_base.join("target"), found: found .iter() .map(|p| p.display().to_string()) From df0ad61f472900b4b069baf68788348280acdf76 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Fri, 22 May 2026 00:04:39 -0700 Subject: [PATCH 14/33] Add stellar contract verify integration tests. --- cmd/crates/soroban-test/tests/it/main.rs | 1 + cmd/crates/soroban-test/tests/it/verify.rs | 190 +++++++++++++++++++++ 2 files changed, 191 insertions(+) create mode 100644 cmd/crates/soroban-test/tests/it/verify.rs diff --git a/cmd/crates/soroban-test/tests/it/main.rs b/cmd/crates/soroban-test/tests/it/main.rs index 9a54b41d31..201c9ba3a8 100644 --- a/cmd/crates/soroban-test/tests/it/main.rs +++ b/cmd/crates/soroban-test/tests/it/main.rs @@ -14,4 +14,5 @@ mod plugin; mod rpc_provider; mod strkey; mod util; +mod verify; mod version; diff --git a/cmd/crates/soroban-test/tests/it/verify.rs b/cmd/crates/soroban-test/tests/it/verify.rs new file mode 100644 index 0000000000..a9a14ec4ea --- /dev/null +++ b/cmd/crates/soroban-test/tests/it/verify.rs @@ -0,0 +1,190 @@ +//! End-to-end tests for `stellar contract verify`. +//! +//! These exercise the full pipeline: build a contract verifiably against a +//! pinned bldimg + pinned source_repo, then verify the resulting wasm matches. +//! The "happy path" tests require docker + network access to GitHub + the +//! pinned bldimg pullable from Docker Hub. They are always-run by convention +//! (per the project's "no #[ignore]" rule) — failures there flag a regression +//! or pinned-resource drift loudly. +//! +//! Fixture pins: +//! - bldimg: `docker.io/fnando/stellar-cli-experimental@sha256:85e76e…`. +//! TODO: swap to `docker.io/stellar/stellar-cli@sha256:<…>` once +//! `stellar/stellar-cli-docker` publishes a canonical tag matching the +//! cli version under test. +//! - source_repo + source_rev: a specific commit on +//! `stellar/soroban-examples`. The `hello_world` contract there is the +//! smallest, most-stable example; we build just that with `--package`. + +use gix::progress::Discard; +use predicates::prelude::{predicate, PredicateBooleanExt}; +use soroban_test::TestEnv; +use std::path::PathBuf; +use std::sync::atomic::AtomicBool; + +const PINNED_BLDIMG: &str = + "docker.io/fnando/stellar-cli-experimental@sha256:85e76eae8bf9f47ba94391214b76f8fa2b9d7b28171774dfafaf5b8d613a74d3"; +const PINNED_SOURCE_REPO: &str = "github:stellar/soroban-examples"; +const PINNED_SOURCE_REV: &str = "7b168174ae1268dab91a0190d80a94ab7ff41b59"; +/// `soroban-examples` has no root `Cargo.toml` — each example is its own +/// crate in a subdirectory. The cli's source-root resolver anchors the +/// bind-mount + the recorded bldopt to the clone root, so the manifest-path +/// stays portable as `hello_world/Cargo.toml` regardless of where the user +/// invoked from. +const PINNED_MANIFEST_PATH: &str = "hello_world/Cargo.toml"; + +/// Build a verifiable wasm for the pinned hello-world example and write it to +/// `/out/soroban_hello_world_contract.wasm`. Returns the on-disk path. +fn build_verifiable_hello_world(sandbox: &TestEnv) -> PathBuf { + let out_dir = sandbox.dir().join("out"); + std::fs::create_dir_all(&out_dir).unwrap(); + sandbox + .new_assert_cmd("contract") + .arg("build") + .arg("--verifiable") + .arg("--image") + .arg(PINNED_BLDIMG) + .arg("--source-repo") + .arg(PINNED_SOURCE_REPO) + .arg("--source-rev") + .arg(PINNED_SOURCE_REV) + .arg("--manifest-path") + .arg(PINNED_MANIFEST_PATH) + .arg("--out-dir") + .arg(&out_dir) + .current_dir(prepared_source_tree(sandbox)) + .assert() + .success(); + out_dir.join("soroban_hello_world_contract.wasm") +} + +/// Materialize the pinned `stellar/soroban-examples` source tree at `/soroban-examples` +/// so the verifiable build has a workspace_root to bind-mount into the +/// container. The host's source tree is what the bldimg actually compiles; +/// `source_repo` + `source_rev` recorded into the wasm only tell a future +/// verifier where to fetch from. We clone via gix to stay shell-free. +fn prepared_source_tree(sandbox: &TestEnv) -> PathBuf { + let dir = sandbox.dir().join("soroban-examples"); + if dir.exists() { + return dir; + } + // Mirror what the cli's `verify::clone_git_source` does — same gix call + // sequence, same flags — so the test exercises the production code path + // a third-party verifier would hit. + let interrupt = AtomicBool::new(false); + let mut prepare = gix::prepare_clone_bare("https://github.com/stellar/soroban-examples", &dir) + .expect("prepare_clone_bare"); + let (repo, _) = prepare.fetch_only(Discard, &interrupt).expect("fetch_only"); + let oid = gix::ObjectId::from_hex(PINNED_SOURCE_REV.as_bytes()).expect("rev hex"); + let object = repo.find_object(oid).expect("find_object"); + let commit = object.peel_to_commit().expect("peel_to_commit"); + let tree_id = commit.tree_id().expect("tree_id"); + let index = gix::index::State::from_tree( + &tree_id, + &repo.objects, + gix::validate::path::component::Options::default(), + ) + .expect("from_tree"); + let mut index_file = gix::index::File::from_state(index, dir.join(".git").join("index")); + gix::worktree::state::checkout( + &mut index_file, + &dir, + repo.objects.clone().into_arc().expect("into_arc"), + &Discard, + &Discard, + &interrupt, + gix::worktree::state::checkout::Options { + destination_is_initially_empty: true, + overwrite_existing: true, + ..Default::default() + }, + ) + .expect("checkout"); + dir +} + +/// Happy path: build a verifiable wasm, then verify it from the local file. +/// Asserts the cli prints `Verified:` on stdout (or stderr; we accept either +/// via `predicates`). +#[test] +fn verify_wasm_succeeds_for_freshly_built_verifiable_wasm() { + let sandbox = TestEnv::default(); + let wasm = build_verifiable_hello_world(&sandbox); + + sandbox + .new_assert_cmd("contract") + .arg("verify") + .arg("--wasm") + .arg(&wasm) + .arg("--trust") + .assert() + .success() + .stderr(predicate::str::contains("Verified:")); +} + +/// Build verifiable → upload to local network → verify by --id. Exercises +/// the wasm::fetch_from_contract path through the verify command. +#[tokio::test] +async fn verify_id_succeeds_after_upload() { + let sandbox = TestEnv::new(); + let wasm = build_verifiable_hello_world(&sandbox); + let wasm_str = wasm.to_string_lossy().to_string(); + + // Upload (cheaper than full deploy; verify only needs the wasm bytes, which + // upload puts on-ledger under a known hash). `--id` accepts a contract id + // OR an alias OR (via wasm_hash) any thing the network can resolve to wasm. + // The deploy path is what gives us a contract id we can pass to --id. + let id = sandbox + .new_assert_cmd("contract") + .arg("deploy") + .arg("--wasm") + .arg(&wasm_str) + .arg("--alias") + .arg("verify_e2e") + .arg("--ignore-checks") + .assert() + .success() + .stdout(predicate::str::is_empty().not()) + .get_output() + .stdout + .clone(); + let id = String::from_utf8(id).unwrap().trim().to_string(); + + sandbox + .new_assert_cmd("contract") + .arg("verify") + .arg("--id") + .arg(&id) + .arg("--trust") + .assert() + .success() + .stderr(predicate::str::contains("Verified:")); +} + +/// Flip a byte in a verifiable wasm and confirm `contract verify` reports the +/// mismatch (different hashes). +#[test] +fn verify_wasm_fails_on_tampered_bytes() { + let sandbox = TestEnv::default(); + let wasm = build_verifiable_hello_world(&sandbox); + + // Tamper: corrupt a byte somewhere in the middle of the WASM. The custom + // section that holds contractmetav0 is near the end; flipping a code byte + // changes the bytes-under-comparison without invalidating the WASM enough + // to break the cli's metadata parse. + let mut bytes = std::fs::read(&wasm).unwrap(); + let mid = bytes.len() / 2; + bytes[mid] = bytes[mid].wrapping_add(1); + let tampered = sandbox.dir().join("tampered.wasm"); + std::fs::write(&tampered, &bytes).unwrap(); + + sandbox + .new_assert_cmd("contract") + .arg("verify") + .arg("--wasm") + .arg(&tampered) + .arg("--trust") + .assert() + .failure() + .stderr(predicate::str::contains("verification failed")); +} From 872e1c473ce3825ae2721b89da63dd905b416826 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Fri, 22 May 2026 00:22:10 -0700 Subject: [PATCH 15/33] Add tarball-sha256 + local --tarball-url verify test. --- Cargo.lock | 2 + Cargo.toml | 2 + cmd/crates/soroban-test/Cargo.toml | 2 + cmd/crates/soroban-test/tests/it/verify.rs | 163 ++++++++---------- cmd/soroban-cli/Cargo.toml | 4 +- .../src/commands/contract/verify.rs | 40 +---- 6 files changed, 82 insertions(+), 131 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 48a80191f2..8bae8aaa89 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5696,6 +5696,7 @@ dependencies = [ "assert_cmd", "assert_fs", "ed25519-dalek", + "flate2", "fs_extra", "hex", "home", @@ -5715,6 +5716,7 @@ dependencies = [ "stellar-ledger", "stellar-rpc-client", "stellar-strkey 0.0.16", + "tar", "test-case", "testcontainers", "thiserror 1.0.69", diff --git a/Cargo.toml b/Cargo.toml index 676da683f7..8f5f94dce2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -86,6 +86,8 @@ escape-bytes = "0.1.1" hex = "0.4.3" itertools = "0.10.0" async-trait = "0.1.76" +tar = "0.4.46" +flate2 = "1.0.30" serde-aux = "4.1.2" serde_json = "1.0.82" serde = "1.0.82" diff --git a/cmd/crates/soroban-test/Cargo.toml b/cmd/crates/soroban-test/Cargo.toml index f89fc70668..d7226fcf4d 100644 --- a/cmd/crates/soroban-test/Cargo.toml +++ b/cmd/crates/soroban-test/Cargo.toml @@ -55,6 +55,8 @@ tracing = "0.1.40" tracing-subscriber = "0.3.18" httpmock = { workspace = true } reqwest = { workspace = true } +tar = { workspace = true } +flate2 = { workspace = true } [features] default = [] diff --git a/cmd/crates/soroban-test/tests/it/verify.rs b/cmd/crates/soroban-test/tests/it/verify.rs index a9a14ec4ea..3337db9958 100644 --- a/cmd/crates/soroban-test/tests/it/verify.rs +++ b/cmd/crates/soroban-test/tests/it/verify.rs @@ -1,41 +1,54 @@ //! End-to-end tests for `stellar contract verify`. //! -//! These exercise the full pipeline: build a contract verifiably against a -//! pinned bldimg + pinned source_repo, then verify the resulting wasm matches. -//! The "happy path" tests require docker + network access to GitHub + the -//! pinned bldimg pullable from Docker Hub. They are always-run by convention -//! (per the project's "no #[ignore]" rule) — failures there flag a regression -//! or pinned-resource drift loudly. +//! Pipeline, entirely through the cli (no git/network clone needed): +//! 1. `contract init` scaffolds a workspace + `hello-world` contract. +//! 2. `contract build --verifiable` builds it against a pinned bldimg and +//! records `source_sha256` in the wasm's SEP-58 metadata. +//! 3. `contract archive` regenerates the *same* source tarball (same +//! `build_source_archive` the verifiable build used), so its sha256 matches +//! the recorded `source_sha256`. +//! 4. `contract verify --source-uri ` materializes the source, +//! rebuilds in the bldimg, and byte-compares. //! -//! Fixture pins: +//! The happy-path tests require docker + the pinned bldimg pullable from Docker +//! Hub. They are always-run by convention (per the project's "no #[ignore]" +//! rule) — failures there flag a regression or pinned-resource drift loudly. +//! +//! Fixture pin: //! - bldimg: `docker.io/fnando/stellar-cli-experimental@sha256:85e76e…`. //! TODO: swap to `docker.io/stellar/stellar-cli@sha256:<…>` once //! `stellar/stellar-cli-docker` publishes a canonical tag matching the //! cli version under test. -//! - source_repo + source_rev: a specific commit on -//! `stellar/soroban-examples`. The `hello_world` contract there is the -//! smallest, most-stable example; we build just that with `--package`. -use gix::progress::Discard; use predicates::prelude::{predicate, PredicateBooleanExt}; use soroban_test::TestEnv; -use std::path::PathBuf; -use std::sync::atomic::AtomicBool; +use std::path::{Path, PathBuf}; const PINNED_BLDIMG: &str = "docker.io/fnando/stellar-cli-experimental@sha256:85e76eae8bf9f47ba94391214b76f8fa2b9d7b28171774dfafaf5b8d613a74d3"; -const PINNED_SOURCE_REPO: &str = "github:stellar/soroban-examples"; -const PINNED_SOURCE_REV: &str = "7b168174ae1268dab91a0190d80a94ab7ff41b59"; -/// `soroban-examples` has no root `Cargo.toml` — each example is its own -/// crate in a subdirectory. The cli's source-root resolver anchors the -/// bind-mount + the recorded bldopt to the clone root, so the manifest-path -/// stays portable as `hello_world/Cargo.toml` regardless of where the user -/// invoked from. -const PINNED_MANIFEST_PATH: &str = "hello_world/Cargo.toml"; -/// Build a verifiable wasm for the pinned hello-world example and write it to -/// `/out/soroban_hello_world_contract.wasm`. Returns the on-disk path. -fn build_verifiable_hello_world(sandbox: &TestEnv) -> PathBuf { +/// Scaffold a workspace with the default `hello-world` contract under +/// `/proj`. The scaffolded tree is not a git repo, so the verifiable +/// build archives the working directory directly. +fn init_project(sandbox: &TestEnv) -> PathBuf { + let proj = sandbox.dir().join("proj"); + sandbox + .new_assert_cmd("contract") + .arg("init") + .arg(&proj) + .assert() + .success(); + proj +} + +/// Build the scaffolded contract verifiably and generate the matching source +/// archive. Returns `(wasm_path, archive_path)`. +/// +/// The archive is produced *after* the verifiable build on purpose: the build's +/// host-side `cargo metadata` writes `Cargo.lock` into the workspace, and +/// `contract archive` then captures that same tree — so the archive's sha256 +/// equals the `source_sha256` the build recorded into the wasm. +fn build_and_archive(sandbox: &TestEnv, proj: &Path) -> (PathBuf, PathBuf) { let out_dir = sandbox.dir().join("out"); std::fs::create_dir_all(&out_dir).unwrap(); sandbox @@ -44,96 +57,57 @@ fn build_verifiable_hello_world(sandbox: &TestEnv) -> PathBuf { .arg("--verifiable") .arg("--image") .arg(PINNED_BLDIMG) - .arg("--source-repo") - .arg(PINNED_SOURCE_REPO) - .arg("--source-rev") - .arg(PINNED_SOURCE_REV) - .arg("--manifest-path") - .arg(PINNED_MANIFEST_PATH) .arg("--out-dir") .arg(&out_dir) - .current_dir(prepared_source_tree(sandbox)) + .current_dir(proj) + .assert() + .success(); + + let archive = sandbox.dir().join("source.tar.gz"); + sandbox + .new_assert_cmd("contract") + .arg("archive") + .arg("--out-file") + .arg(&archive) + .current_dir(proj) .assert() .success(); - out_dir.join("soroban_hello_world_contract.wasm") -} -/// Materialize the pinned `stellar/soroban-examples` source tree at `/soroban-examples` -/// so the verifiable build has a workspace_root to bind-mount into the -/// container. The host's source tree is what the bldimg actually compiles; -/// `source_repo` + `source_rev` recorded into the wasm only tell a future -/// verifier where to fetch from. We clone via gix to stay shell-free. -fn prepared_source_tree(sandbox: &TestEnv) -> PathBuf { - let dir = sandbox.dir().join("soroban-examples"); - if dir.exists() { - return dir; - } - // Mirror what the cli's `verify::clone_git_source` does — same gix call - // sequence, same flags — so the test exercises the production code path - // a third-party verifier would hit. - let interrupt = AtomicBool::new(false); - let mut prepare = gix::prepare_clone_bare("https://github.com/stellar/soroban-examples", &dir) - .expect("prepare_clone_bare"); - let (repo, _) = prepare.fetch_only(Discard, &interrupt).expect("fetch_only"); - let oid = gix::ObjectId::from_hex(PINNED_SOURCE_REV.as_bytes()).expect("rev hex"); - let object = repo.find_object(oid).expect("find_object"); - let commit = object.peel_to_commit().expect("peel_to_commit"); - let tree_id = commit.tree_id().expect("tree_id"); - let index = gix::index::State::from_tree( - &tree_id, - &repo.objects, - gix::validate::path::component::Options::default(), - ) - .expect("from_tree"); - let mut index_file = gix::index::File::from_state(index, dir.join(".git").join("index")); - gix::worktree::state::checkout( - &mut index_file, - &dir, - repo.objects.clone().into_arc().expect("into_arc"), - &Discard, - &Discard, - &interrupt, - gix::worktree::state::checkout::Options { - destination_is_initially_empty: true, - overwrite_existing: true, - ..Default::default() - }, - ) - .expect("checkout"); - dir + (out_dir.join("hello_world.wasm"), archive) } -/// Happy path: build a verifiable wasm, then verify it from the local file. -/// Asserts the cli prints `Verified:` on stdout (or stderr; we accept either -/// via `predicates`). +/// Happy path: build a verifiable wasm, then verify it from the local file, +/// handing the cli the matching source archive via `--source-uri`. Asserts the +/// cli prints `Verified:` on stderr. #[test] fn verify_wasm_succeeds_for_freshly_built_verifiable_wasm() { let sandbox = TestEnv::default(); - let wasm = build_verifiable_hello_world(&sandbox); + let proj = init_project(&sandbox); + let (wasm, archive) = build_and_archive(&sandbox, &proj); sandbox .new_assert_cmd("contract") .arg("verify") .arg("--wasm") .arg(&wasm) + .arg("--source-uri") + .arg(&archive) .arg("--trust") .assert() .success() .stderr(predicate::str::contains("Verified:")); } -/// Build verifiable → upload to local network → verify by --id. Exercises -/// the wasm::fetch_from_contract path through the verify command. +/// Build verifiable → upload to local network → verify by `--id`. Exercises the +/// `wasm::fetch_from_contract` path through the verify command. #[tokio::test] async fn verify_id_succeeds_after_upload() { let sandbox = TestEnv::new(); - let wasm = build_verifiable_hello_world(&sandbox); + let proj = init_project(&sandbox); + let (wasm, archive) = build_and_archive(&sandbox, &proj); let wasm_str = wasm.to_string_lossy().to_string(); - // Upload (cheaper than full deploy; verify only needs the wasm bytes, which - // upload puts on-ledger under a known hash). `--id` accepts a contract id - // OR an alias OR (via wasm_hash) any thing the network can resolve to wasm. - // The deploy path is what gives us a contract id we can pass to --id. + // Deploy gives us a contract id `--id` can resolve to the on-ledger wasm. let id = sandbox .new_assert_cmd("contract") .arg("deploy") @@ -155,6 +129,8 @@ async fn verify_id_succeeds_after_upload() { .arg("verify") .arg("--id") .arg(&id) + .arg("--source-uri") + .arg(&archive) .arg("--trust") .assert() .success() @@ -162,16 +138,15 @@ async fn verify_id_succeeds_after_upload() { } /// Flip a byte in a verifiable wasm and confirm `contract verify` reports the -/// mismatch (different hashes). +/// mismatch. The flipped byte is in the middle (code) so the trailing +/// `contractmetav0` section still parses; the rebuild reproduces the original +/// bytes, and the byte comparison fails. #[test] fn verify_wasm_fails_on_tampered_bytes() { let sandbox = TestEnv::default(); - let wasm = build_verifiable_hello_world(&sandbox); + let proj = init_project(&sandbox); + let (wasm, archive) = build_and_archive(&sandbox, &proj); - // Tamper: corrupt a byte somewhere in the middle of the WASM. The custom - // section that holds contractmetav0 is near the end; flipping a code byte - // changes the bytes-under-comparison without invalidating the WASM enough - // to break the cli's metadata parse. let mut bytes = std::fs::read(&wasm).unwrap(); let mid = bytes.len() / 2; bytes[mid] = bytes[mid].wrapping_add(1); @@ -183,6 +158,8 @@ fn verify_wasm_fails_on_tampered_bytes() { .arg("verify") .arg("--wasm") .arg(&tampered) + .arg("--source-uri") + .arg(&archive) .arg("--trust") .assert() .failure() diff --git a/cmd/soroban-cli/Cargo.toml b/cmd/soroban-cli/Cargo.toml index d08065ae36..213076bf26 100644 --- a/cmd/soroban-cli/Cargo.toml +++ b/cmd/soroban-cli/Cargo.toml @@ -113,8 +113,8 @@ rust-embed = { version = "8.2.0", features = ["debug-embed"] } futures-util = "0.3.30" futures = "0.3.30" home = "0.5.9" -flate2 = "1.0.30" -tar = "0.4.46" +flate2 = { workspace = true } +tar = { workspace = true } bytesize = "1.3.0" humantime = "2.1.0" phf = { version = "0.11.2", features = ["macros"] } diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index 14361436f5..324f0968df 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -247,11 +247,10 @@ impl Cmd { // Catch the no-retrieval-channel case before any trust prompts so a // doomed run errors immediately instead of asking the user to trust - // an image we won't end up using. - let has_git_source = meta.source_repo.is_some() && meta.source_rev.is_some(); - let has_tarball_url = self.tarball_url.is_some() || meta.tarball_url.is_some(); - if !has_git_source && !has_tarball_url { - return Err(Error::TarballUrlRequired); + // an image we won't end up using. With only `source_sha256` recorded + // and no `--source-uri` override, there's nowhere to fetch from. + if self.effective_source_uri(&meta).is_none() { + return Err(Error::SourceUriRequired); } // bldimg trust check is always required. @@ -948,37 +947,6 @@ mod tests { assert!(matches!(err, Error::SourceUriRequired)); } - #[test] - fn expand_source_repo_rewrites_github_shorthand() { - assert_eq!( - expand_source_repo("github:foo/bar"), - "https://github.com/foo/bar" - ); - } - - #[test] - fn expand_source_repo_passes_through_https() { - assert_eq!( - expand_source_repo("https://github.com/foo/bar"), - "https://github.com/foo/bar" - ); - assert_eq!( - expand_source_repo("https://gitlab.com/foo/bar.git"), - "https://gitlab.com/foo/bar.git" - ); - } - - #[test] - fn expand_source_repo_does_not_expand_malformed_github() { - // Missing the `/repo` suffix; the regex won't match so we pass through. - assert_eq!(expand_source_repo("github:foo"), "github:foo"); - // Extra path component; same. - assert_eq!( - expand_source_repo("github:foo/bar/baz"), - "github:foo/bar/baz" - ); - } - #[test] fn build_container_command_replays_bldopts_and_re_records_meta() { let meta = ExtractedMetadata { From 1d3902e626413a3525e56af654ee040b8981e262 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Fri, 22 May 2026 00:29:59 -0700 Subject: [PATCH 16/33] Move verify integration tests into integration tier. --- cmd/crates/soroban-test/tests/it/integration/contract/mod.rs | 1 + .../soroban-test/tests/it/{ => integration/contract}/verify.rs | 0 cmd/crates/soroban-test/tests/it/main.rs | 1 - 3 files changed, 1 insertion(+), 1 deletion(-) rename cmd/crates/soroban-test/tests/it/{ => integration/contract}/verify.rs (100%) diff --git a/cmd/crates/soroban-test/tests/it/integration/contract/mod.rs b/cmd/crates/soroban-test/tests/it/integration/contract/mod.rs index 5e5f4b7a00..a8ba22da21 100644 --- a/cmd/crates/soroban-test/tests/it/integration/contract/mod.rs +++ b/cmd/crates/soroban-test/tests/it/integration/contract/mod.rs @@ -1,2 +1,3 @@ mod fetch; mod info_hash; +mod verify; diff --git a/cmd/crates/soroban-test/tests/it/verify.rs b/cmd/crates/soroban-test/tests/it/integration/contract/verify.rs similarity index 100% rename from cmd/crates/soroban-test/tests/it/verify.rs rename to cmd/crates/soroban-test/tests/it/integration/contract/verify.rs diff --git a/cmd/crates/soroban-test/tests/it/main.rs b/cmd/crates/soroban-test/tests/it/main.rs index 201c9ba3a8..9a54b41d31 100644 --- a/cmd/crates/soroban-test/tests/it/main.rs +++ b/cmd/crates/soroban-test/tests/it/main.rs @@ -14,5 +14,4 @@ mod plugin; mod rpc_provider; mod strkey; mod util; -mod verify; mod version; From 4e21de4182856ef08f8e3cd5ce55bc798bba97d0 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Fri, 22 May 2026 01:24:02 -0700 Subject: [PATCH 17/33] Restrict permissions on materialized verify source. --- cmd/soroban-cli/src/commands/contract/verify.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index 324f0968df..1c0c8d3b42 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -125,6 +125,12 @@ pub enum Error { #[error("creating tempdir: {0}")] TempDir(std::io::Error), + #[error("hardening permissions on {path}: {source}")] + ChmodMaterialized { + path: PathBuf, + source: std::io::Error, + }, + #[error(transparent)] Verifiable(#[from] verifiable::Error), @@ -502,6 +508,16 @@ async fn materialize_source( print.checkln("Source SHA-256 matches"); } extract_tarball(&bytes, target)?; + + // Tighten the freshly materialized tree to 0o700 / 0o600 before docker + // sees it. Uses the same per-path helper the cli already applies to its + // config dirs (one source of truth for what "hardened" means). + crate::config::locator::enforce_hardened_tree(target).map_err(|e| { + Error::ChmodMaterialized { + path: target.to_path_buf(), + source: e, + } + })?; Ok(()) } From de2fc1594e9a7c471788db16f87e5f8b0e1b86a8 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Wed, 17 Jun 2026 15:28:12 -0700 Subject: [PATCH 18/33] Share build logic and fix contract verify rebuild. --- Cargo.lock | 2 - cmd/crates/soroban-test/Cargo.toml | 2 - .../commands/contract/build/source_archive.rs | 35 +++ .../src/commands/contract/build/verifiable.rs | 32 +-- .../src/commands/contract/verify.rs | 226 +++++++++--------- 5 files changed, 154 insertions(+), 143 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8bae8aaa89..48a80191f2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5696,7 +5696,6 @@ dependencies = [ "assert_cmd", "assert_fs", "ed25519-dalek", - "flate2", "fs_extra", "hex", "home", @@ -5716,7 +5715,6 @@ dependencies = [ "stellar-ledger", "stellar-rpc-client", "stellar-strkey 0.0.16", - "tar", "test-case", "testcontainers", "thiserror 1.0.69", diff --git a/cmd/crates/soroban-test/Cargo.toml b/cmd/crates/soroban-test/Cargo.toml index d7226fcf4d..f89fc70668 100644 --- a/cmd/crates/soroban-test/Cargo.toml +++ b/cmd/crates/soroban-test/Cargo.toml @@ -55,8 +55,6 @@ tracing = "0.1.40" tracing-subscriber = "0.3.18" httpmock = { workspace = true } reqwest = { workspace = true } -tar = { workspace = true } -flate2 = { workspace = true } [features] default = [] diff --git a/cmd/soroban-cli/src/commands/contract/build/source_archive.rs b/cmd/soroban-cli/src/commands/contract/build/source_archive.rs index b266cc81c4..0b69f98b52 100644 --- a/cmd/soroban-cli/src/commands/contract/build/source_archive.rs +++ b/cmd/soroban-cli/src/commands/contract/build/source_archive.rs @@ -19,6 +19,7 @@ use std::{ use ignore::WalkBuilder; +use crate::config::{data, locator::enforce_hardened_tree}; use crate::print::Print; /// Names that usually shouldn't end up in a source archive — VCS metadata of @@ -74,6 +75,9 @@ pub enum Error { #[error("could not extract source archive: {0}")] ArchiveExtract(std::io::Error), + + #[error(transparent)] + Data(#[from] data::Error), } /// The source tree's root: always the current working directory. The archive is @@ -301,6 +305,37 @@ pub(crate) fn unpack_targz(bytes: &[u8], dest: &Path) -> Result<(), Error> { .map_err(Error::ArchiveExtract) } +/// Create a fresh temp directory, unpack the gzipped source tarball `bytes` into +/// it, harden its permissions, and return the guard (the tree lives at its +/// `path()`). Shared by `build --verifiable` (builds from the extracted copy) +/// and `verify` (rebuilds from it); `prefix` names the dir so the two are +/// distinguishable on disk. +/// +/// The temp dir is created under `/tmp`, NOT the OS temp dir: on macOS +/// `$TMPDIR` lives under /var/folders, which container VMs (Docker Desktop, +/// Colima, …) don't share by default, so a bind mount of it would be empty +/// inside the container. The data dir lives under the user's home, which is +/// shared. Corralling every extraction under a single `tmp/` keeps a leftover +/// from an interrupted run isolated in one obviously-disposable place rather +/// than loose alongside `archives/`. +pub(crate) fn extract_into_hardened_tempdir( + bytes: &[u8], + prefix: &str, +) -> Result { + let base = data::data_local_dir()?.join("tmp"); + std::fs::create_dir_all(&base).map_err(|source| Error::ArchiveWrite { + path: base.clone(), + source, + })?; + let tmp = tempfile::Builder::new() + .prefix(prefix) + .tempdir_in(&base) + .map_err(Error::ArchiveExtract)?; + unpack_targz(bytes, tmp.path())?; + enforce_hardened_tree(tmp.path()).map_err(Error::ArchiveExtract)?; + Ok(tmp) +} + #[cfg(test)] mod tests { use super::*; diff --git a/cmd/soroban-cli/src/commands/contract/build/verifiable.rs b/cmd/soroban-cli/src/commands/contract/build/verifiable.rs index d5f226b098..c47be14c96 100644 --- a/cmd/soroban-cli/src/commands/contract/build/verifiable.rs +++ b/cmd/soroban-cli/src/commands/contract/build/verifiable.rs @@ -12,7 +12,7 @@ use crate::{ container::shared::{self, Error as ConnectionError}, global, }, - config::{data, locator::enforce_hardened_tree}, + config::data, print::Print, }; @@ -258,9 +258,9 @@ fn resolve_workspace_root(cmd: &Cmd) -> Result { /// `--source-sha256` or computed from the generated archive). `source_uri` is /// `Some` only when the user passed `--source-uri`. #[derive(Debug, Default, Clone)] -struct SourceIds { - source_uri: Option, - source_sha256: Option, +pub(crate) struct SourceIds { + pub(crate) source_uri: Option, + pub(crate) source_sha256: Option, } /// Format-validate the user-supplied source flags. Both are optional under @@ -325,23 +325,7 @@ fn resolve_archive(cmd: &Cmd, source_root: &Path, print: &Print) -> Result Vec { +pub(crate) fn build_metadata_args( + image_ref: &str, + ids: &SourceIds, + bldopts: &[String], +) -> Vec { let mut out = Vec::new(); let push = |out: &mut Vec, key: &str, val: &str| { diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index 1c0c8d3b42..680a3fd4e6 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -10,8 +10,9 @@ use stellar_xdr::curr::{ScMetaEntry, ScMetaV0}; use crate::{ commands::{ container, - contract::build::verifiable::{ - self, bldimg_regex, source_sha256_regex, source_uri_regex, + contract::build::{ + source_archive, + verifiable::{self, bldimg_regex, source_sha256_regex, source_uri_regex}, }, global, }, @@ -116,20 +117,17 @@ pub enum Error { #[error("source code sha256 mismatch: expected {expected}, got {actual}")] SourceHashMismatch { expected: String, actual: String }, - #[error("extracting source code into {path}: {source}")] + #[error("reading extracted source at {path}: {source}")] SourceExtract { path: PathBuf, source: std::io::Error, }, - #[error("creating tempdir: {0}")] - TempDir(std::io::Error), + #[error("source archive at {path} does not contain exactly one top-level directory (found {count}); SEP-58 requires the source be wrapped in a single directory")] + SourceArchiveLayout { path: PathBuf, count: usize }, - #[error("hardening permissions on {path}: {source}")] - ChmodMaterialized { - path: PathBuf, - source: std::io::Error, - }, + #[error(transparent)] + SourceArchive(#[from] source_archive::Error), #[error(transparent)] Verifiable(#[from] verifiable::Error), @@ -269,10 +267,9 @@ impl Cmd { } // Materialize the recorded source into a tempdir so the rebuild can - // bind-mount it. TempDir lives across the rebuild + comparison and + // bind-mount it. The TempDir lives across the rebuild + comparison and // cleans up on drop. - let workdir = tempfile::TempDir::new().map_err(Error::TempDir)?; - materialize_source(&meta, self.source_uri.as_deref(), workdir.path(), &print).await?; + let workdir = materialize_source(&meta, self.source_uri.as_deref(), &print).await?; print.checkln(format!( "Source materialized at {}", workdir.path().display() @@ -284,12 +281,18 @@ impl Cmd { }; let docker = docker_args.connect_to_docker(&print).await?; verifiable::pull_image(&docker, &meta.bldimg, &print).await?; - let container_cmd = build_container_command(&meta); + let (container_cmd, env) = build_container_command(&meta); + + // SEP-58 requires the source be wrapped in a single top-level directory + // (the cli names it `source/`, but the spec doesn't fix the name), so + // the build's working tree is that wrapper dir under `workdir`. + let source_root = locate_extracted_source_root(workdir.path())?; + verifiable::run_in_container( &meta.bldimg, - workdir.path(), + &source_root, &[container_cmd], - &[], + &env, &docker, &print, global_args.verbose || global_args.very_verbose, @@ -297,8 +300,8 @@ impl Cmd { .await?; // Locate the rebuilt WASM. The cargo target dir lives under the bind- - // mounted /source, which we mapped to `workdir`. - let rebuilt_path = find_rebuilt_wasm(workdir.path(), &meta)?; + // mounted /source, which we mapped to `source_root`. + let rebuilt_path = find_rebuilt_wasm(&source_root, &meta)?; let rebuilt = std::fs::read(&rebuilt_path).map_err(|e| Error::ReadRebuilt { path: rebuilt_path.clone(), source: e, @@ -330,9 +333,7 @@ impl Cmd { /// records a `source_uri` (only `source_sha256` is set), in which case /// there's nothing to trust-check here. fn effective_source_uri(&self, meta: &ExtractedMetadata) -> Option { - self.source_uri - .clone() - .or_else(|| meta.source_uri.clone()) + self.source_uri.clone().or_else(|| meta.source_uri.clone()) } async fn fetch_wasm(&self) -> Result, Error> { @@ -477,22 +478,19 @@ pub fn parse_yes(answer: &str) -> bool { a.eq_ignore_ascii_case("y") || a.eq_ignore_ascii_case("yes") } -/// Materialize the recorded source tree into `target`. Picks the path based on -/// what the WASM recorded: -/// - source_uri (with optional sha256) → download/read, optional sha-check, -/// extract via `tar` -/// - source_sha256 only → require `--source-uri` on the cli and use it as -/// the retrieval channel +/// Materialize the recorded source tree into a fresh, permission-hardened +/// tempdir and return the guard. The retrieval channel is the cli's +/// `--source-uri` flag (when set) or the WASM's recorded `source_uri`; either +/// may be an http(s) URL or a local file path. When the bytes are present, the +/// optional `source_sha256` is checked before extraction. /// -/// `source_uri_override` is the cli's `--source-uri` flag value; when set, it -/// wins over whatever the WASM recorded, and may be an http(s) URL or a local -/// file path. +/// Extraction (under the data dir, hardened) is shared with `build +/// --verifiable` via `source_archive::extract_into_hardened_tempdir`. async fn materialize_source( meta: &ExtractedMetadata, source_uri_override: Option<&str>, - target: &Path, print: &Print, -) -> Result<(), Error> { +) -> Result { let tarball_source = source_uri_override .map(str::to_string) .or_else(|| meta.source_uri.clone()); @@ -507,18 +505,10 @@ async fn materialize_source( verify_source_sha256(&bytes, expected)?; print.checkln("Source SHA-256 matches"); } - extract_tarball(&bytes, target)?; - - // Tighten the freshly materialized tree to 0o700 / 0o600 before docker - // sees it. Uses the same per-path helper the cli already applies to its - // config dirs (one source of truth for what "hardened" means). - crate::config::locator::enforce_hardened_tree(target).map_err(|e| { - Error::ChmodMaterialized { - path: target.to_path_buf(), - source: e, - } - })?; - Ok(()) + Ok(source_archive::extract_into_hardened_tempdir( + &bytes, + "verify-src-", + )?) } /// Retrieve the tarball bytes. `source` is either an `http(s)://` URL or a @@ -565,44 +555,71 @@ fn verify_source_sha256(bytes: &[u8], expected: &str) -> Result<(), Error> { } } -fn extract_tarball(bytes: &[u8], target: &Path) -> Result<(), Error> { - let gz = flate2::read::GzDecoder::new(bytes); - let mut archive = tar::Archive::new(gz); - archive.unpack(target).map_err(|e| Error::SourceExtract { - path: target.to_path_buf(), - source: e, - }) +/// SEP-58 requires the source archive wrap everything in a single top-level +/// directory (the cli names it `source/`, but the spec leaves the name open), +/// so after extraction the build tree is that lone directory under `workdir`. +/// Return it, erroring if the archive doesn't have exactly one top-level dir. +fn locate_extracted_source_root(workdir: &Path) -> Result { + let mut dirs: Vec = std::fs::read_dir(workdir) + .map_err(|source| Error::SourceExtract { + path: workdir.to_path_buf(), + source, + })? + .filter_map(|entry| entry.ok().map(|e| e.path())) + .filter(|p| p.is_dir()) + .collect(); + + match dirs.len() { + 1 => Ok(dirs.remove(0)), + count => Err(Error::SourceArchiveLayout { + path: workdir.to_path_buf(), + count, + }), + } } -/// Compose the argv we hand to the container's `stellar contract build` so -/// that: +/// Compose the argv we hand to the container's `stellar contract build`, plus +/// the env vars to apply via docker `-e`, so that: /// - the bldopts from the original build become flags (each entry is one /// token, ready for clap), AND /// - bldimg / source-ids / bldopt are re-recorded as `--meta` entries so /// the rebuilt WASM has identical metadata to the original. /// +/// `--env=` bldopts are NOT forwarded as build flags: the original build +/// applied them via docker `-e` (recording them as `bldopt` only), so we replay +/// them the same way. The recorded value is shell-escaped, so we unescape it +/// back to a raw `NAME=VALUE` for docker `-e`. They're still re-recorded as +/// `bldopt` meta so the rebuilt WASM's metadata matches the original. +/// /// cliver is intentionally not re-injected — the container's stellar adds it /// automatically, and it will match the original's iff `bldimg` resolves to /// the same container. -fn build_container_command(meta: &ExtractedMetadata) -> Vec { - let mut forwarded: Vec = meta.bldopts.clone(); - let mut metadata: Vec = Vec::new(); - - let mut push_meta = |k: &str, v: &str| { - metadata.push("--meta".to_string()); - metadata.push(format!("{k}={v}")); - }; - push_meta("bldimg", &meta.bldimg); - if let Some(v) = &meta.source_uri { - push_meta("source_uri", v); - } - if let Some(v) = &meta.source_sha256 { - push_meta("source_sha256", v); - } +fn build_container_command(meta: &ExtractedMetadata) -> (Vec, Vec) { + let mut forwarded: Vec = Vec::new(); + let mut env: Vec = Vec::new(); for o in &meta.bldopts { - push_meta("bldopt", o); + if let Some(rest) = o.strip_prefix("--env=") { + // The bldopt value is shell-escaped (e.g. `--env=B='a b'`); shell-split + // it back to a single raw `NAME=VALUE` token for docker `-e`. + if let Some(kv) = + shlex::split(rest).and_then(|mut v| (v.len() == 1).then(|| v.remove(0))) + { + env.push(kv); + } + } else { + forwarded.push(o.clone()); + } } + // Re-record bldimg / source-ids / every bldopt as `--meta`, reusing the + // exact composition `build --verifiable` used, so the rebuilt WASM's + // metadata matches the original byte-for-byte. + let ids = verifiable::SourceIds { + source_uri: meta.source_uri.clone(), + source_sha256: meta.source_sha256.clone(), + }; + let metadata = verifiable::build_metadata_args(&meta.bldimg, &ids, &meta.bldopts); + // `--locked` is always sent — even if the original somehow lacked it (a // non-conformant build), the verifier insists on a locked rebuild so // dependency drift can't move bytes underneath us. @@ -610,7 +627,10 @@ fn build_container_command(meta: &ExtractedMetadata) -> Vec { forwarded.insert(0, "--locked".to_string()); } - verifiable::compose_container_args(&forwarded, &metadata) + ( + verifiable::compose_container_args(&forwarded, &metadata), + env, + ) } /// Locate the rebuilt WASM under `workdir`. The container writes to @@ -747,10 +767,7 @@ mod tests { meta.source_uri.as_deref(), Some("https://example.com/src.tar.gz") ); - assert_eq!( - meta.source_sha256.as_deref(), - Some("f".repeat(64).as_str()) - ); + assert_eq!(meta.source_sha256.as_deref(), Some("f".repeat(64).as_str())); } #[test] @@ -912,41 +929,6 @@ mod tests { assert!(matches!(err, Error::SourceHashMismatch { .. })); } - /// Build a tiny in-memory tar.gz with a single file and confirm extraction - /// drops the file at the expected path. Exercises the pure-Rust pipeline - /// (no shelling out, so this passes on Windows too). - #[test] - fn extract_tarball_unpacks_into_target() { - use flate2::write::GzEncoder; - use flate2::Compression; - use std::io::Write; - - let mut tar_bytes = Vec::new(); - { - let mut builder = tar::Builder::new(&mut tar_bytes); - let payload = b"contents"; - let mut header = tar::Header::new_gnu(); - header.set_path("hello.txt").unwrap(); - header.set_size(payload.len() as u64); - header.set_mode(0o644); - header.set_cksum(); - builder.append(&header, &payload[..]).unwrap(); - builder.finish().unwrap(); - } - - let mut gz = Vec::new(); - { - let mut enc = GzEncoder::new(&mut gz, Compression::default()); - enc.write_all(&tar_bytes).unwrap(); - enc.finish().unwrap(); - } - - let dir = tempfile::TempDir::new().unwrap(); - extract_tarball(&gz, dir.path()).unwrap(); - let extracted = std::fs::read(dir.path().join("hello.txt")).unwrap(); - assert_eq!(extracted, b"contents"); - } - #[tokio::test] async fn materialize_source_errors_when_only_source_sha256() { let meta = ExtractedMetadata { @@ -955,11 +937,8 @@ mod tests { source_sha256: Some("f".repeat(64)), bldopts: Vec::new(), }; - let dir = tempfile::TempDir::new().unwrap(); let print = Print::new(true); - let err = materialize_source(&meta, None, dir.path(), &print) - .await - .unwrap_err(); + let err = materialize_source(&meta, None, &print).await.unwrap_err(); assert!(matches!(err, Error::SourceUriRequired)); } @@ -973,9 +952,11 @@ mod tests { "--locked".to_string(), "--meta=home_domain=fnando.com".to_string(), "--optimize".to_string(), + "--env=A=1".to_string(), + "--env=B='this is very nice'".to_string(), ], }; - let cmd = build_container_command(&meta); + let (cmd, env) = build_container_command(&meta); // Subcommand prefix. assert_eq!(&cmd[..2], &["contract".to_string(), "build".to_string()]); @@ -985,6 +966,14 @@ mod tests { assert!(cmd.contains(&"--meta=home_domain=fnando.com".to_string())); assert!(cmd.contains(&"--optimize".to_string())); + // `--env=` bldopts are applied via docker `-e` (unescaped), never + // forwarded as build flags. + assert!(!cmd.iter().any(|a| a.starts_with("--env="))); + assert_eq!( + env, + vec!["A=1".to_string(), "B=this is very nice".to_string()] + ); + // bldimg and source-ids are re-recorded as `--meta`. assert!(cmd .windows(2) @@ -993,11 +982,14 @@ mod tests { .windows(2) .any(|w| w[0] == "--meta" && w[1] == "source_uri=https://github.com/foo/bar")); - // Every bldopt is also re-recorded as a `bldopt=` meta so the rebuilt - // WASM mirrors the original's entries. + // Every bldopt — including the `--env=` ones — is re-recorded as a + // `bldopt=` meta so the rebuilt WASM mirrors the original's entries. assert!(cmd .windows(2) .any(|w| w[0] == "--meta" && w[1] == "bldopt=--locked")); + assert!(cmd + .windows(2) + .any(|w| w[0] == "--meta" && w[1] == "bldopt=--env=A=1")); } #[test] @@ -1010,7 +1002,7 @@ mod tests { source_sha256: Some("b".repeat(64)), bldopts: vec!["--meta=author=alice".to_string()], }; - let cmd = build_container_command(&meta); + let (cmd, _env) = build_container_command(&meta); let locked_count = cmd.iter().filter(|s| *s == "--locked").count(); assert_eq!( locked_count, 1, From eb6ddd0c3696c9437339c3292b17c36ec9f6d9b8 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Wed, 17 Jun 2026 15:37:33 -0700 Subject: [PATCH 19/33] Add --wasm-hash to stellar contract verify. --- FULL_HELP_DOCS.md | 3 +- .../src/commands/contract/verify.rs | 47 +++++++++++++------ 2 files changed, 35 insertions(+), 15 deletions(-) diff --git a/FULL_HELP_DOCS.md b/FULL_HELP_DOCS.md index 0853bbb6a9..41820062e0 100644 --- a/FULL_HELP_DOCS.md +++ b/FULL_HELP_DOCS.md @@ -1177,7 +1177,8 @@ Verify that a contract's WASM reproduces from the build metadata it records, per - `--id ` — Contract id or alias to fetch the WASM from the network - `--wasm ` — Local WASM file to verify, instead of fetching from the network -- `--tarball-url ` — Local tarball file or http(s) URL to use as the source when the WASM's recorded SEP-58 metadata has only `tarball_sha256` (no `tarball_url`). Accepts http(s) URLs or local file paths +- `--wasm-hash ` — WASM hash (hex) to fetch the WASM from the network +- `--source-uri ` — Local source code file or http(s) URL to use as the source when the WASM's recorded SEP-58 metadata has only `source_sha256` (no `source_uri`). Accepts http(s) URLs or local file paths - `--trust` — Bypass interactive confirmation when the WASM's bldimg is not in the default trust list, or when the source is a tarball (tarballs are never default-trusted) - `-d`, `--docker-host ` — Override the default docker host used by the rebuild diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index 680a3fd4e6..65065ee1f6 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -5,7 +5,7 @@ use clap::Parser; use regex::Regex; use sha2::{Digest, Sha256}; use soroban_spec_tools::contract::Spec; -use stellar_xdr::curr::{ScMetaEntry, ScMetaV0}; +use stellar_xdr::{Hash, ScMetaEntry, ScMetaV0}; use crate::{ commands::{ @@ -25,13 +25,21 @@ use crate::{ #[group(skip)] pub struct Cmd { /// Contract id or alias to fetch the WASM from the network. - #[arg(long = "id", env = "STELLAR_CONTRACT_ID", conflicts_with = "wasm")] + #[arg( + long = "id", + env = "STELLAR_CONTRACT_ID", + conflicts_with_all = ["wasm", "wasm_hash"] + )] pub contract_id: Option, /// Local WASM file to verify, instead of fetching from the network. - #[arg(long)] + #[arg(long, conflicts_with = "wasm_hash")] pub wasm: Option, + /// WASM hash (hex) to fetch the WASM from the network. + #[arg(long = "wasm-hash")] + pub wasm_hash: Option, + /// Local source code file or http(s) URL to use as the source when the WASM's /// recorded SEP-58 metadata has only `source_sha256` (no `source_uri`). /// Accepts http(s) URLs or local file paths. @@ -57,9 +65,12 @@ pub struct Cmd { #[derive(thiserror::Error, Debug)] pub enum Error { - #[error("must pass exactly one of --id or --wasm")] + #[error("must pass exactly one of --id, --wasm, or --wasm-hash")] MissingInput, + #[error("invalid wasm hash {0:?}: expected 64 hex characters")] + InvalidWasmHash(String), + #[error("reading wasm {0}: {1}")] ReadWasm(PathBuf, std::io::Error), @@ -337,16 +348,24 @@ impl Cmd { } async fn fetch_wasm(&self) -> Result, Error> { - match (&self.contract_id, &self.wasm) { - (Some(id), None) => { - let network = self.network.get(&self.locator)?; - let resolved = - id.resolve_contract_id(&self.locator, &network.network_passphrase)?; - Ok(wasm::fetch_from_contract(&resolved, &network).await?) - } - (None, Some(path)) => std::fs::read(path).map_err(|e| Error::ReadWasm(path.clone(), e)), - _ => Err(Error::MissingInput), + // Clap keeps these three mutually exclusive, so at most one is set. + if let Some(path) = &self.wasm { + return std::fs::read(path).map_err(|e| Error::ReadWasm(path.clone(), e)); + } + if let Some(id) = &self.contract_id { + let network = self.network.get(&self.locator)?; + let resolved = id.resolve_contract_id(&self.locator, &network.network_passphrase)?; + return Ok(wasm::fetch_from_contract(&resolved, &network).await?); + } + if let Some(wasm_hash) = &self.wasm_hash { + let network = self.network.get(&self.locator)?; + let bytes: [u8; 32] = hex::decode(wasm_hash) + .ok() + .and_then(|b| b.try_into().ok()) + .ok_or_else(|| Error::InvalidWasmHash(wasm_hash.clone()))?; + return Ok(wasm::fetch_from_wasm_hash(Hash(bytes), &network).await?); } + Err(Error::MissingInput) } } @@ -722,7 +741,7 @@ const SOURCE_SHA256_REGEX_STR: &str = r"^[0-9a-f]{64}$"; mod tests { use super::*; use std::io::Cursor; - use stellar_xdr::curr::{Limited, Limits, ScMetaEntry, ScMetaV0, WriteXdr}; + use stellar_xdr::{Limited, Limits, ScMetaEntry, ScMetaV0, WriteXdr}; fn make_wasm_with_meta(entries: &[(&str, &str)]) -> Vec { let xdr = encode_meta(entries); From 5ffd7acfcf1502fdd870e4f95a4d9a6064525d0d Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Thu, 18 Jun 2026 20:58:18 -0700 Subject: [PATCH 20/33] Stop requiring source hash when setting source URI. --- FULL_HELP_DOCS.md | 65 +------------------ cmd/crates/soroban-test/tests/it/build.rs | 30 ++++++++- .../src/commands/contract/build.rs | 13 ++-- 3 files changed, 35 insertions(+), 73 deletions(-) diff --git a/FULL_HELP_DOCS.md b/FULL_HELP_DOCS.md index 41820062e0..eac80cf8f8 100644 --- a/FULL_HELP_DOCS.md +++ b/FULL_HELP_DOCS.md @@ -369,18 +369,6 @@ To view the commands that will be executed, without executing them, use the --pr **Usage:** `stellar contract build [OPTIONS]` -###### **Container Options:** - -- `-d`, `--docker-host ` — Optional argument to override the default docker host. This is useful when you are using a non-standard docker host path for your Docker-compatible container runtime, e.g. Docker Desktop defaults to $HOME/.docker/run/docker.sock instead of /var/run/docker.sock -- `--engine ` — Container engine to use [default: docker] - - Possible values: - - `docker`: Docker, or any Docker-compatible CLI - - `apple-container`: Apple's `container` CLI (macOS 26+, Apple silicon) - -- `--cpus ` — Limit the number of CPUs available to the container, e.g. `2`. A whole number: Apple's `container` engine does not accept fractional CPUs -- `--memory ` — Limit the memory available to the container, e.g. `2g` or `512m` - ###### **Features:** - `--features ` — Build with the list of features activated, space or comma separated @@ -420,12 +408,13 @@ To view the commands that will be executed, without executing them, use the --pr - `--print-commands-only` — Print commands to build without executing them -###### **Verifiable Options:** +###### **Verifiable:** - `--verifiable` — Build inside a trusted Docker container and record SEP-58 metadata (`bldimg`, `source_uri`, `source_sha256`, `bldopt`) so the resulting WASM can be reproduced and verified by third parties. Implies `--locked`. Requires a clean git working tree - `--image ` — Override the auto-selected container image used by `--verifiable`. Must be digest-pinned, e.g. `docker.io/stellar/stellar-cli@sha256:...`. Tag-only refs are rejected because SEP-58 requires content addressing - `--source-sha256 ` — SEP-58 source identification: SHA-256 of the source archive (recorded as the `source_sha256` meta entry). Optional with `--verifiable`: the archive is always generated and its SHA-256 computed for you. When supplied it's treated as a pin — the build fails if it doesn't match the generated archive -- `--source-uri ` — SEP-58 source identification: URI where the source can be obtained, e.g. `https://example.com/src.tar.gz` (recorded as the `source_uri` meta entry). Optional; when set it must accompany `--source-sha256` +- `--source-uri ` — SEP-58 source identification: URI where the source can be obtained, e.g. `https://example.com/src.tar.gz` (recorded as the `source_uri` meta entry). Optional with `--verifiable`; the recorded `source_sha256` is computed from the generated archive, unless `--source-sha256` is explicitly set +- `-d`, `--docker-host ` — Override the default docker host used by `--verifiable` ## `stellar contract extend` @@ -1722,8 +1711,6 @@ Start local networks in containers - `logs` — Get logs from a running network container - `start` — Start a container running a Stellar node, RPC, API, and friendbot (faucet) - `stop` — Stop a network container started with `stellar container start` -- `use` — Set the default container engine used by `stellar container` commands -- `unset` — Unset the default container engine defined previously with `container use ` ## `stellar container logs` @@ -1740,11 +1727,6 @@ Get logs from a running network container ###### **Options:** - `-d`, `--docker-host ` — Optional argument to override the default docker host. This is useful when you are using a non-standard docker host path for your Docker-compatible container runtime, e.g. Docker Desktop defaults to $HOME/.docker/run/docker.sock instead of /var/run/docker.sock -- `--engine ` — Container engine to use [default: docker] - - Possible values: - - `docker`: Docker, or any Docker-compatible CLI - - `apple-container`: Apple's `container` CLI (macOS 26+, Apple silicon) ## `stellar container start` @@ -1767,14 +1749,6 @@ By default, when starting a testnet container, without any optional arguments, i ###### **Options:** - `-d`, `--docker-host ` — Optional argument to override the default docker host. This is useful when you are using a non-standard docker host path for your Docker-compatible container runtime, e.g. Docker Desktop defaults to $HOME/.docker/run/docker.sock instead of /var/run/docker.sock -- `--engine ` — Container engine to use [default: docker] - - Possible values: - - `docker`: Docker, or any Docker-compatible CLI - - `apple-container`: Apple's `container` CLI (macOS 26+, Apple silicon) - -- `--cpus ` — Limit the number of CPUs available to the container, e.g. `2`. A whole number: Apple's `container` engine does not accept fractional CPUs -- `--memory ` — Limit the memory available to the container, e.g. `2g` or `512m` - `--name ` — Optional argument to specify the container name - `-l`, `--limits ` — Optional argument to specify the limits for the local network only - `-p`, `--ports-mapping ` — Argument to specify the `HOST_PORT:CONTAINER_PORT` mapping @@ -1799,39 +1773,6 @@ Stop a network container started with `stellar container start` ###### **Options:** - `-d`, `--docker-host ` — Optional argument to override the default docker host. This is useful when you are using a non-standard docker host path for your Docker-compatible container runtime, e.g. Docker Desktop defaults to $HOME/.docker/run/docker.sock instead of /var/run/docker.sock -- `--engine ` — Container engine to use [default: docker] - - Possible values: - - `docker`: Docker, or any Docker-compatible CLI - - `apple-container`: Apple's `container` CLI (macOS 26+, Apple silicon) - -## `stellar container use` - -Set the default container engine used by `stellar container` commands - -**Usage:** `stellar container use [OPTIONS] ` - -###### **Arguments:** - -- `` — Container engine to use by default - - Possible values: - - `docker`: Docker, or any Docker-compatible CLI - - `apple-container`: Apple's `container` CLI (macOS 26+, Apple silicon) - -###### **Global Options:** - -- `--config-dir ` — Location of config directory. By default, it uses `$XDG_CONFIG_HOME/stellar` if set, falling back to `~/.config/stellar` otherwise. Contains configuration files, aliases, and other persistent settings - -## `stellar container unset` - -Unset the default container engine defined previously with `container use ` - -**Usage:** `stellar container unset [OPTIONS]` - -###### **Global Options:** - -- `--config-dir ` — Location of config directory. By default, it uses `$XDG_CONFIG_HOME/stellar` if set, falling back to `~/.config/stellar` otherwise. Contains configuration files, aliases, and other persistent settings ## `stellar config` diff --git a/cmd/crates/soroban-test/tests/it/build.rs b/cmd/crates/soroban-test/tests/it/build.rs index 6d1ba0290c..f636d7fdd5 100644 --- a/cmd/crates/soroban-test/tests/it/build.rs +++ b/cmd/crates/soroban-test/tests/it/build.rs @@ -1319,8 +1319,6 @@ fn verifiable_source_uri_format_errors() { .arg("--verifiable") .arg("--image") .arg(ZERO_DIGEST) - .arg("--source-sha256") - .arg("a".repeat(64)) .arg("--source-uri") .arg("not a uri") .assert() @@ -1328,6 +1326,34 @@ fn verifiable_source_uri_format_errors() { .stderr(predicate::str::contains("source_uri format")); } +// `--source-uri` does not require `--source-sha256`: the archive is generated +// and its source_sha256 computed regardless, so a source-uri-only build gets +// past validation and writes the archive (then fails reaching a real image). +#[test] +fn verifiable_source_uri_without_sha256_is_allowed() { + let sandbox = TestEnv::default(); + let (_temp, workspace) = fresh_workspace(); + git_in(&workspace, &["init", "-q", "-b", "main"]); + git_in(&workspace, &["add", "-A"]); + git_in(&workspace, &["commit", "-q", "-m", "init"]); + + sandbox + .new_assert_cmd("contract") + .current_dir(workspace.join("contracts").join("add")) + .arg("build") + .arg("--verifiable") + .arg("--image") + .arg(ZERO_DIGEST) + .arg("--source-uri") + .arg("https://example.com/src.tar.gz") + .assert() + .failure() + .stderr( + predicate::str::contains("Wrote source archive") + .and(predicate::str::contains("source_sha256")), + ); +} + // A dirty git tree is a hard fail under `--verifiable` (the recorded // source_sha256 would not describe the bytes built). #[test] diff --git a/cmd/soroban-cli/src/commands/contract/build.rs b/cmd/soroban-cli/src/commands/contract/build.rs index b52bf057ed..dc4f387c0f 100644 --- a/cmd/soroban-cli/src/commands/contract/build.rs +++ b/cmd/soroban-cli/src/commands/contract/build.rs @@ -123,15 +123,10 @@ pub struct Cmd { #[arg(long, requires = "verifiable", help_heading = HEADING_VERIFIABLE)] pub source_sha256: Option, - /// SEP-58 source identification: URI where the source can be obtained, e.g. - /// `https://example.com/src.tar.gz` (recorded as the `source_uri` meta - /// entry). Optional; when set it must accompany `--source-sha256`. - #[arg( - long, - requires = "verifiable", - requires = "source_sha256", - help_heading = HEADING_VERIFIABLE - )] + /// entry). Optional with `--verifiable`; the recorded `source_sha256` is + /// computed from the generated archive, unless `--source-sha256` is + /// explicitly set. + #[arg(long, requires = "verifiable", help_heading = HEADING_VERIFIABLE)] pub source_uri: Option, #[command(flatten)] From 54291d5ec962ab013913f834b9456ca34fd6b959 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Wed, 8 Jul 2026 11:39:45 -0300 Subject: [PATCH 21/33] Skip --locked when verifying against older images. --- .../src/commands/contract/verify.rs | 48 +++++++++++++++---- 1 file changed, 40 insertions(+), 8 deletions(-) diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index 65065ee1f6..cc239a44fd 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -292,7 +292,13 @@ impl Cmd { }; let docker = docker_args.connect_to_docker(&print).await?; verifiable::pull_image(&docker, &meta.bldimg, &print).await?; - let (container_cmd, env) = build_container_command(&meta); + + // `--locked` was only added to `contract build` in cli 25.2.0. The + // recorded bldimg may be older (and still valid), so probe it before + // forcing `--locked` — passing an unknown flag would fail the rebuild. + let supports_locked = + verifiable::probe_supports_locked(&meta.bldimg, &docker, &print).await; + let (container_cmd, env) = build_container_command(&meta, supports_locked); // SEP-58 requires the source be wrapped in a single top-level directory // (the cli names it `source/`, but the spec doesn't fix the name), so @@ -613,7 +619,14 @@ fn locate_extracted_source_root(workdir: &Path) -> Result { /// cliver is intentionally not re-injected — the container's stellar adds it /// automatically, and it will match the original's iff `bldimg` resolves to /// the same container. -fn build_container_command(meta: &ExtractedMetadata) -> (Vec, Vec) { +/// +/// `supports_locked`: whether the recorded bldimg's `contract build` accepts +/// `--locked` (added in cli 25.2.0). When false the flag is never injected, so +/// a rebuild against an older image doesn't fail on an unknown argument. +fn build_container_command( + meta: &ExtractedMetadata, + supports_locked: bool, +) -> (Vec, Vec) { let mut forwarded: Vec = Vec::new(); let mut env: Vec = Vec::new(); for o in &meta.bldopts { @@ -639,10 +652,11 @@ fn build_container_command(meta: &ExtractedMetadata) -> (Vec, Vec Date: Wed, 8 Jul 2026 12:15:54 -0300 Subject: [PATCH 22/33] Find rebuilt contract in workspace target folders. --- .../src/commands/contract/verify.rs | 249 ++++++++++++------ 1 file changed, 174 insertions(+), 75 deletions(-) diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index cc239a44fd..de356b8fee 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -1,3 +1,4 @@ +use std::collections::HashSet; use std::io::{IsTerminal, Write}; use std::path::{Path, PathBuf}; @@ -6,6 +7,7 @@ use regex::Regex; use sha2::{Digest, Sha256}; use soroban_spec_tools::contract::Spec; use stellar_xdr::{Hash, ScMetaEntry, ScMetaV0}; +use walkdir::WalkDir; use crate::{ commands::{ @@ -305,6 +307,20 @@ impl Cmd { // the build's working tree is that wrapper dir under `workdir`. let source_root = locate_extracted_source_root(workdir.path())?; + // Snapshot any WASM artifacts already present in the materialized source + // *before* the rebuild. A conformant source archive ships no build + // output, so anything here was planted; excluding these from the post- + // build search stops an attacker from smuggling a pre-built binary into + // the tarball to masquerade as the rebuild's output and spoof a match. + let preexisting_wasms: HashSet = + collect_release_wasms(&source_root).into_iter().collect(); + if !preexisting_wasms.is_empty() { + print.warnln(format!( + "Ignoring {} pre-existing WASM artifact(s) in the source; only freshly rebuilt output is trusted", + preexisting_wasms.len() + )); + } + verifiable::run_in_container( &meta.bldimg, &source_root, @@ -318,7 +334,7 @@ impl Cmd { // Locate the rebuilt WASM. The cargo target dir lives under the bind- // mounted /source, which we mapped to `source_root`. - let rebuilt_path = find_rebuilt_wasm(&source_root, &meta)?; + let rebuilt_path = find_rebuilt_wasm(&source_root, &meta, &preexisting_wasms)?; let rebuilt = std::fs::read(&rebuilt_path).map_err(|e| Error::ReadRebuilt { path: rebuilt_path.clone(), source: e, @@ -666,55 +682,55 @@ fn build_container_command( ) } -/// Locate the rebuilt WASM under `workdir`. The container writes to -/// `/target/wasm32v1-none/release/.wasm` (or `wasm32-unknown-unknown/release` -/// for older toolchains; check both). If a `--package=` bldopt was -/// recorded, prefer that file. -fn find_rebuilt_wasm(workdir: &Path, meta: &ExtractedMetadata) -> Result { +/// The two wasm release-output suffixes cargo may write to, newest first. +/// Older toolchains build for `wasm32-unknown-unknown`; current ones use +/// `wasm32v1-none`. The match is deliberately the 2-component `/release` +/// tail rather than `target//release`: cargo's target dir is not fixed +/// at `target/` (it can be relocated via `--target-dir`, `CARGO_TARGET_DIR`, or +/// `build.target-dir`), but the `/release/` layout beneath it is +/// stable. Matching the tail also excludes intermediate artifacts under +/// `release/deps/`, whose parent ends with `release/deps`, not `.../release`. +const WASM_RELEASE_SUFFIXES: [&str; 2] = + ["wasm32v1-none/release", "wasm32-unknown-unknown/release"]; + +/// Walk `root` and return every `*.wasm` sitting directly in a +/// `/release` output directory. The target dir's location is not fixed +/// relative to the crate manifest — in a Cargo workspace it lives at the +/// workspace root, which may be any ancestor of the `--manifest-path` crate — +/// so we search the whole tree rather than guess where it is. +fn collect_release_wasms(root: &Path) -> Vec { + WalkDir::new(root) + .into_iter() + .filter_map(Result::ok) + .map(walkdir::DirEntry::into_path) + .filter(|p| p.extension().and_then(|s| s.to_str()) == Some("wasm")) + .filter(|p| { + p.parent() + .is_some_and(|parent| WASM_RELEASE_SUFFIXES.iter().any(|s| parent.ends_with(s))) + }) + .collect() +} + +/// Locate the WASM produced by the container's rebuild under `source_root`. +/// +/// Only artifacts *created by this rebuild* are eligible: any `*.wasm` present +/// before the build (captured in `preexisting`) is excluded, so a pre-built +/// binary planted in the source archive can't masquerade as the rebuild output. +/// If a `--package=` bldopt was recorded, prefer that file. +fn find_rebuilt_wasm( + source_root: &Path, + meta: &ExtractedMetadata, + preexisting: &HashSet, +) -> Result { let preferred_pkg = meta .bldopts .iter() .find_map(|opt| opt.strip_prefix("--package=").map(|s| s.replace('-', "_"))); - // Cargo's `target/` lives next to the manifest's workspace root, which - // may be a subdirectory of `workdir` when `--manifest-path=…` was - // recorded (e.g. `hello_world/Cargo.toml` in a multi-crate repo). Anchor - // the search at the manifest's parent dir, falling back to `workdir`. - let target_base = meta - .bldopts - .iter() - .find_map(|opt| { - opt.strip_prefix("--manifest-path=") - .and_then(|p| Path::new(p).parent().map(Path::to_path_buf)) - .filter(|p| !p.as_os_str().is_empty()) - }) - .map_or_else(|| workdir.to_path_buf(), |sub| workdir.join(sub)); - - let candidates = [ - target_base.join("target/wasm32v1-none/release"), - target_base.join("target/wasm32-unknown-unknown/release"), - ]; - - let mut found: Vec = Vec::new(); - for dir in &candidates { - if !dir.is_dir() { - continue; - } - for entry in std::fs::read_dir(dir).map_err(|e| Error::ReadRebuilt { - path: dir.clone(), - source: e, - })? { - let p = entry - .map_err(|e| Error::ReadRebuilt { - path: dir.clone(), - source: e, - })? - .path(); - if p.extension().and_then(|s| s.to_str()) == Some("wasm") { - found.push(p); - } - } - } + let found: Vec = collect_release_wasms(source_root) + .into_iter() + .filter(|p| !preexisting.contains(p)) + .collect(); if let Some(pkg) = &preferred_pkg { let want = format!("{pkg}.wasm"); @@ -729,11 +745,11 @@ fn find_rebuilt_wasm(workdir: &Path, meta: &ExtractedMetadata) -> Result Err(Error::NoRebuiltWasm { - target: target_base.join("target"), + target: source_root.to_path_buf(), }), 1 => Ok(found.into_iter().next().unwrap()), _ => Err(Error::AmbiguousRebuiltWasm { - target: target_base.join("target"), + target: source_root.to_path_buf(), found: found .iter() .map(|p| p.display().to_string()) @@ -1061,6 +1077,15 @@ mod tests { ); } + fn meta_with_bldopts(bldopts: Vec) -> ExtractedMetadata { + ExtractedMetadata { + bldimg: good_bldimg(), + source_uri: Some("https://github.com/foo/bar".to_string()), + source_sha256: Some("b".repeat(64)), + bldopts, + } + } + #[test] fn find_rebuilt_wasm_picks_single() { let dir = tempfile::TempDir::new().unwrap(); @@ -1068,13 +1093,8 @@ mod tests { std::fs::create_dir_all(&release).unwrap(); std::fs::write(release.join("hello.wasm"), b"x").unwrap(); - let meta = ExtractedMetadata { - bldimg: good_bldimg(), - source_uri: Some("https://github.com/foo/bar".to_string()), - source_sha256: Some("b".repeat(64)), - bldopts: vec![], - }; - let p = find_rebuilt_wasm(dir.path(), &meta).unwrap(); + let meta = meta_with_bldopts(vec![]); + let p = find_rebuilt_wasm(dir.path(), &meta, &HashSet::new()).unwrap(); assert!(p.ends_with("hello.wasm")); } @@ -1086,13 +1106,8 @@ mod tests { std::fs::write(release.join("hello.wasm"), b"x").unwrap(); std::fs::write(release.join("other_thing.wasm"), b"x").unwrap(); - let meta = ExtractedMetadata { - bldimg: good_bldimg(), - source_uri: Some("https://github.com/foo/bar".to_string()), - source_sha256: Some("b".repeat(64)), - bldopts: vec!["--package=other-thing".to_string()], - }; - let p = find_rebuilt_wasm(dir.path(), &meta).unwrap(); + let meta = meta_with_bldopts(vec!["--package=other-thing".to_string()]); + let p = find_rebuilt_wasm(dir.path(), &meta, &HashSet::new()).unwrap(); assert!(p.ends_with("other_thing.wasm")); } @@ -1104,26 +1119,110 @@ mod tests { std::fs::write(release.join("hello.wasm"), b"x").unwrap(); std::fs::write(release.join("other.wasm"), b"x").unwrap(); - let meta = ExtractedMetadata { - bldimg: good_bldimg(), - source_uri: Some("https://github.com/foo/bar".to_string()), - source_sha256: Some("b".repeat(64)), - bldopts: vec![], - }; - let err = find_rebuilt_wasm(dir.path(), &meta).unwrap_err(); + let meta = meta_with_bldopts(vec![]); + let err = find_rebuilt_wasm(dir.path(), &meta, &HashSet::new()).unwrap_err(); assert!(matches!(err, Error::AmbiguousRebuiltWasm { .. })); } #[test] fn find_rebuilt_wasm_errors_when_none() { let dir = tempfile::TempDir::new().unwrap(); - let meta = ExtractedMetadata { - bldimg: good_bldimg(), - source_uri: Some("https://github.com/foo/bar".to_string()), - source_sha256: Some("b".repeat(64)), - bldopts: vec![], - }; - let err = find_rebuilt_wasm(dir.path(), &meta).unwrap_err(); + let meta = meta_with_bldopts(vec![]); + let err = find_rebuilt_wasm(dir.path(), &meta, &HashSet::new()).unwrap_err(); assert!(matches!(err, Error::NoRebuiltWasm { .. })); } + + #[test] + fn find_rebuilt_wasm_finds_target_at_workspace_root() { + // In a Cargo workspace the `target/` dir sits at the workspace root, not + // next to the crate manifest. The search must still find it when + // `--manifest-path` points deep into a subdirectory (the bug that + // motivated the tree walk). + let dir = tempfile::TempDir::new().unwrap(); + let release = dir.path().join("target/wasm32v1-none/release"); + std::fs::create_dir_all(&release).unwrap(); + std::fs::write(release.join("blocked_message_lib.wasm"), b"x").unwrap(); + std::fs::create_dir_all( + dir.path() + .join("contracts/message-libs/blocked-message-lib/src"), + ) + .unwrap(); + + let meta = meta_with_bldopts(vec![ + "--manifest-path=contracts/message-libs/blocked-message-lib/Cargo.toml".to_string(), + "--package=blocked-message-lib".to_string(), + ]); + let p = find_rebuilt_wasm(dir.path(), &meta, &HashSet::new()).unwrap(); + assert!(p.ends_with("blocked_message_lib.wasm")); + } + + #[test] + fn find_rebuilt_wasm_finds_relocated_target_dir() { + // The output dir need not be named `target/` (e.g. CARGO_TARGET_DIR). + // The `/release/` tail is what's stable, so a renamed dir is + // still found. + let dir = tempfile::TempDir::new().unwrap(); + let release = dir.path().join("custom-out/wasm32-unknown-unknown/release"); + std::fs::create_dir_all(&release).unwrap(); + std::fs::write(release.join("hello.wasm"), b"x").unwrap(); + + let meta = meta_with_bldopts(vec![]); + let p = find_rebuilt_wasm(dir.path(), &meta, &HashSet::new()).unwrap(); + assert!(p.ends_with("hello.wasm")); + } + + #[test] + fn find_rebuilt_wasm_ignores_release_deps_artifacts() { + // Intermediate wasms under `release/deps/` are not the final artifact + // and must not be matched. + let dir = tempfile::TempDir::new().unwrap(); + let release = dir.path().join("target/wasm32v1-none/release"); + let deps = release.join("deps"); + std::fs::create_dir_all(&deps).unwrap(); + std::fs::write(release.join("hello.wasm"), b"x").unwrap(); + std::fs::write(deps.join("hello-abc123.wasm"), b"x").unwrap(); + + let meta = meta_with_bldopts(vec![]); + let p = find_rebuilt_wasm(dir.path(), &meta, &HashSet::new()).unwrap(); + assert!(p.ends_with("hello.wasm")); + } + + #[test] + fn find_rebuilt_wasm_excludes_preexisting_injected_wasm() { + // An attacker ships a pre-built wasm at the output path. It's captured + // in the pre-build snapshot and excluded, so it can't spoof a match — + // leaving no eligible rebuild output. + let dir = tempfile::TempDir::new().unwrap(); + let release = dir.path().join("target/wasm32v1-none/release"); + std::fs::create_dir_all(&release).unwrap(); + let injected = release.join("hello.wasm"); + std::fs::write(&injected, b"x").unwrap(); + + let preexisting: HashSet = collect_release_wasms(dir.path()).into_iter().collect(); + assert!(preexisting.contains(&injected)); + + let meta = meta_with_bldopts(vec![]); + let err = find_rebuilt_wasm(dir.path(), &meta, &preexisting).unwrap_err(); + assert!(matches!(err, Error::NoRebuiltWasm { .. })); + } + + #[test] + fn find_rebuilt_wasm_keeps_freshly_built_alongside_preexisting() { + // A pre-existing wasm is excluded, but a genuinely new one built next to + // it is still found — no false ambiguity. + let dir = tempfile::TempDir::new().unwrap(); + let release = dir.path().join("target/wasm32v1-none/release"); + std::fs::create_dir_all(&release).unwrap(); + let old = release.join("stale.wasm"); + std::fs::write(&old, b"x").unwrap(); + + let preexisting: HashSet = collect_release_wasms(dir.path()).into_iter().collect(); + + // The rebuild then produces a fresh artifact. + std::fs::write(release.join("hello.wasm"), b"x").unwrap(); + + let meta = meta_with_bldopts(vec![]); + let p = find_rebuilt_wasm(dir.path(), &meta, &preexisting).unwrap(); + assert!(p.ends_with("hello.wasm")); + } } From 8a11c08bf2710db9fa3b31a6d6a5612c0e50a411 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Wed, 8 Jul 2026 12:25:18 -0300 Subject: [PATCH 23/33] Strip shell quotes from build options when rebuilding. --- .../src/commands/contract/verify.rs | 52 +++++++++++++++---- 1 file changed, 43 insertions(+), 9 deletions(-) diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index de356b8fee..712a45c6d7 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -646,16 +646,21 @@ fn build_container_command( let mut forwarded: Vec = Vec::new(); let mut env: Vec = Vec::new(); for o in &meta.bldopts { - if let Some(rest) = o.strip_prefix("--env=") { - // The bldopt value is shell-escaped (e.g. `--env=B='a b'`); shell-split - // it back to a single raw `NAME=VALUE` token for docker `-e`. - if let Some(kv) = - shlex::split(rest).and_then(|mut v| (v.len() == 1).then(|| v.remove(0))) - { - env.push(kv); - } + // Every recorded bldopt is shell-escaped at the source (see + // `build_forwarded_args` in verifiable.rs) so it's valid shell on its + // own — e.g. `--meta=source_repo='github:foo'` or `--env=B='a b'`. The + // single-package rebuild hands argv straight to `stellar` with no shell, + // so unescape each bldopt back to the one raw argv token the original + // build used; otherwise the quoting leaks into the value (a quoted + // `--meta` value even shifts the WASM's byte size via XDR alignment). + let token = shlex::split(o) + .and_then(|mut v| (v.len() == 1).then(|| v.remove(0))) + .unwrap_or_else(|| o.clone()); + if let Some(kv) = token.strip_prefix("--env=") { + // Applied via docker `-e` as a raw `NAME=VALUE`, never forwarded. + env.push(kv.to_string()); } else { - forwarded.push(o.clone()); + forwarded.push(token); } } @@ -1041,6 +1046,35 @@ mod tests { .any(|w| w[0] == "--meta" && w[1] == "bldopt=--env=A=1")); } + #[test] + fn build_container_command_unescapes_quoted_meta_bldopt() { + // Recorded bldopts are shell-escaped at the source, so a `--meta` value + // with a `:` (or spaces) is stored quoted. Verify must unescape it back + // to the raw argv token — otherwise the literal quotes leak into the + // meta value and the rebuilt WASM differs from the original. + let meta = ExtractedMetadata { + bldimg: good_bldimg(), + source_uri: Some("https://github.com/foo/bar".to_string()), + source_sha256: Some("b".repeat(64)), + bldopts: vec![ + "--meta=source_repo='github:LayerZero-Labs/monorepo-external'".to_string(), + ], + }; + let (cmd, _env) = build_container_command(&meta, true); + // The forwarded build flag is unescaped (no literal quotes reach clap). + assert!( + cmd.contains(&"--meta=source_repo=github:LayerZero-Labs/monorepo-external".to_string()), + "quotes must be stripped from the forwarded --meta, got {cmd:?}" + ); + // The re-recorded `bldopt=` meta keeps the original escaped form verbatim + // so the rebuilt WASM's bldopt entry matches the original byte-for-byte. + assert!( + cmd.windows(2).any(|w| w[0] == "--meta" + && w[1] == "bldopt=--meta=source_repo='github:LayerZero-Labs/monorepo-external'"), + "the bldopt meta must round-trip the escaped original, got {cmd:?}" + ); + } + #[test] fn build_container_command_injects_locked_when_missing() { // A non-conformant origin might not have --locked in bldopts. Verify From 557918a39ce2a8625f254839b170be8212d61d42 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Wed, 8 Jul 2026 12:28:43 -0300 Subject: [PATCH 24/33] Add --keep to save build files for debugging. --- FULL_HELP_DOCS.md | 1 + .../src/commands/contract/verify.rs | 56 +++++++++++++++---- 2 files changed, 46 insertions(+), 11 deletions(-) diff --git a/FULL_HELP_DOCS.md b/FULL_HELP_DOCS.md index eac80cf8f8..facb71bb91 100644 --- a/FULL_HELP_DOCS.md +++ b/FULL_HELP_DOCS.md @@ -1170,6 +1170,7 @@ Verify that a contract's WASM reproduces from the build metadata it records, per - `--source-uri ` — Local source code file or http(s) URL to use as the source when the WASM's recorded SEP-58 metadata has only `source_sha256` (no `source_uri`). Accepts http(s) URLs or local file paths - `--trust` — Bypass interactive confirmation when the WASM's bldimg is not in the default trust list, or when the source is a tarball (tarballs are never default-trusted) - `-d`, `--docker-host ` — Override the default docker host used by the rebuild +- `--keep` — Keep the materialized source and rebuild output instead of deleting them on exit, and print the path. Useful for debugging a byte mismatch (e.g. diffing the rebuilt WASM's metadata against the original) ###### **RPC Options:** diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index 712a45c6d7..a73ae92d17 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -58,6 +58,12 @@ pub struct Cmd { #[arg(short = 'd', long, env = "DOCKER_HOST")] pub docker_host: Option, + /// Keep the materialized source and rebuild output instead of deleting them + /// on exit, and print the path. Useful for debugging a byte mismatch (e.g. + /// diffing the rebuilt WASM's metadata against the original). + #[arg(long)] + pub keep: bool, + #[command(flatten)] pub locator: locator::Args, @@ -280,32 +286,57 @@ impl Cmd { } // Materialize the recorded source into a tempdir so the rebuild can - // bind-mount it. The TempDir lives across the rebuild + comparison and - // cleans up on drop. + // bind-mount it. Normally the TempDir cleans up on drop; with `--keep` + // we persist it (below) so a mismatch can be inspected afterwards. let workdir = materialize_source(&meta, self.source_uri.as_deref(), &print).await?; print.checkln(format!( "Source materialized at {}", workdir.path().display() )); + let result = self + .rebuild_and_verify(workdir.path(), &meta, &wasm_bytes, global_args, &print) + .await; + + // Persist the build tree when asked — regardless of the outcome, so a + // byte mismatch (or a rebuild error) can be debugged against the kept + // source and rebuilt WASM. Otherwise it cleans up on drop here. + if self.keep { + let kept = workdir.keep(); + Print::new(false).infoln(format!("Kept build directory at {}", kept.display())); + } + + result + } + + /// Rebuild the contract in the recorded `bldimg` and compare the freshly + /// built WASM against the original. Split out from `run` so the caller owns + /// the `TempDir` and can keep or drop it after this returns (see `--keep`). + async fn rebuild_and_verify( + &self, + workdir: &Path, + meta: &ExtractedMetadata, + wasm_bytes: &[u8], + global_args: &global::Args, + print: &Print, + ) -> Result<(), Error> { // Rebuild in the recorded bldimg. let docker_args = container::shared::Args { docker_host: self.docker_host.clone(), }; - let docker = docker_args.connect_to_docker(&print).await?; - verifiable::pull_image(&docker, &meta.bldimg, &print).await?; + let docker = docker_args.connect_to_docker(print).await?; + verifiable::pull_image(&docker, &meta.bldimg, print).await?; // `--locked` was only added to `contract build` in cli 25.2.0. The // recorded bldimg may be older (and still valid), so probe it before // forcing `--locked` — passing an unknown flag would fail the rebuild. - let supports_locked = - verifiable::probe_supports_locked(&meta.bldimg, &docker, &print).await; - let (container_cmd, env) = build_container_command(&meta, supports_locked); + let supports_locked = verifiable::probe_supports_locked(&meta.bldimg, &docker, print).await; + let (container_cmd, env) = build_container_command(meta, supports_locked); // SEP-58 requires the source be wrapped in a single top-level directory // (the cli names it `source/`, but the spec doesn't fix the name), so // the build's working tree is that wrapper dir under `workdir`. - let source_root = locate_extracted_source_root(workdir.path())?; + let source_root = locate_extracted_source_root(workdir)?; // Snapshot any WASM artifacts already present in the materialized source // *before* the rebuild. A conformant source archive ships no build @@ -327,23 +358,26 @@ impl Cmd { &[container_cmd], &env, &docker, - &print, + print, global_args.verbose || global_args.very_verbose, ) .await?; // Locate the rebuilt WASM. The cargo target dir lives under the bind- // mounted /source, which we mapped to `source_root`. - let rebuilt_path = find_rebuilt_wasm(&source_root, &meta, &preexisting_wasms)?; + let rebuilt_path = find_rebuilt_wasm(&source_root, meta, &preexisting_wasms)?; let rebuilt = std::fs::read(&rebuilt_path).map_err(|e| Error::ReadRebuilt { path: rebuilt_path.clone(), source: e, })?; + if self.keep { + print.infoln(format!("Rebuilt WASM at {}", rebuilt_path.display())); + } // Compare. The final result is always shown, even under `--quiet`, // via a dedicated Print that ignores the quiet flag. let result_print = Print::new(false); - let original_hash = format!("{:x}", Sha256::digest(&wasm_bytes)); + let original_hash = format!("{:x}", Sha256::digest(wasm_bytes)); let rebuilt_hash = format!("{:x}", Sha256::digest(&rebuilt)); if original_hash == rebuilt_hash && wasm_bytes.len() == rebuilt.len() { result_print.checkln(format!( From 4d82b0a09f9bd46d865edc5e4bbb59a9ff711c78 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Wed, 8 Jul 2026 12:37:54 -0300 Subject: [PATCH 25/33] Show the source file actually used when overriding. --- .../src/commands/contract/verify.rs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index a73ae92d17..dff64c64ec 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -254,8 +254,22 @@ impl Cmd { let meta = extract_metadata(&wasm_bytes)?; print.infoln(format!("Build image: {}", meta.bldimg)); - if let Some(v) = &meta.source_uri { - print.infoln(format!("Source URI: {v}")); + // Report the source we'll actually fetch from. When `--source-uri` + // overrides the recorded value, show the override (and the recorded + // value it replaces) so the line isn't misleading. + match (&self.source_uri, &meta.source_uri) { + (Some(override_uri), Some(recorded)) => { + print.infoln(format!( + "Source URI: {override_uri} (overrides recorded {recorded})" + )); + } + (Some(override_uri), None) => { + print.infoln(format!("Source URI: {override_uri} (override)")); + } + (None, Some(recorded)) => { + print.infoln(format!("Source URI: {recorded}")); + } + (None, None) => {} } if let Some(v) = &meta.source_sha256 { print.infoln(format!("Source SHA-256: {v}")); From a65557a92b4b12c0948a42db2465b92560875d63 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Thu, 9 Jul 2026 15:58:46 -0300 Subject: [PATCH 26/33] Reject unknown source formats. --- .../src/commands/contract/verify.rs | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index dff64c64ec..a747f236d2 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -7,6 +7,7 @@ use regex::Regex; use sha2::{Digest, Sha256}; use soroban_spec_tools::contract::Spec; use stellar_xdr::{Hash, ScMetaEntry, ScMetaV0}; +use url::Url; use walkdir::WalkDir; use crate::{ @@ -121,6 +122,9 @@ pub enum Error { #[error("reading stdin: {0}")] Stdin(std::io::Error), + #[error("source {uri:?} has an unsupported format; accepted formats are {formats}")] + UnsupportedSourceFormat { uri: String, formats: String }, + #[error("the WASM records only `source_sha256` (no `source_uri`). Pass `--source-uri URL_OR_PATH` to provide retrieval.")] SourceUriRequired, @@ -588,6 +592,8 @@ async fn materialize_source( return Err(Error::SourceUriRequired); }; + validate_source_format(&source)?; + print.infoln(format!("Fetching source code from {source}")); let bytes = fetch_tarball_bytes(&source).await?; if let Some(expected) = &meta.source_sha256 { @@ -600,6 +606,45 @@ async fn materialize_source( )?) } +/// Extensions we accept for a source archive: the archive is always a gzipped +/// tarball (see `source_archive`), so only these name it. Checked +/// case-insensitively against the source's basename. +const RECOGNIZED_SOURCE_EXTENSIONS: &[&str] = &[".tar.gz", ".tgz"]; + +/// The last path segment of `source`, whether it's a URL or a local path. Try +/// parsing as a URL first (so query strings and fragments are dropped); if that +/// fails, `source` is a local path, so fall back to `Path::file_name`. +fn source_basename(source: &str) -> String { + if let Ok(url) = Url::parse(source) { + return url + .path_segments() + .and_then(|mut segments| segments.next_back()) + .unwrap_or_default() + .to_string(); + } + Path::new(source) + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default() +} + +/// Reject a `--source-uri` (or recorded `source_uri`) whose basename doesn't end +/// in a recognized archive extension, before we bother fetching it, naming the +/// formats we accept. +fn validate_source_format(source: &str) -> Result<(), Error> { + let basename = source_basename(source).to_ascii_lowercase(); + if RECOGNIZED_SOURCE_EXTENSIONS + .iter() + .any(|ext| basename.ends_with(ext)) + { + return Ok(()); + } + Err(Error::UnsupportedSourceFormat { + uri: source.to_string(), + formats: RECOGNIZED_SOURCE_EXTENSIONS.join(", "), + }) +} + /// Retrieve the tarball bytes. `source` is either an `http(s)://` URL or a /// local file path. The split is by prefix, not by attempting both — keeps /// behavior predictable. @@ -1307,4 +1352,41 @@ mod tests { let p = find_rebuilt_wasm(dir.path(), &meta, &preexisting).unwrap(); assert!(p.ends_with("hello.wasm")); } + + #[test] + fn source_basename_strips_url_query_and_fragment() { + assert_eq!( + source_basename("https://example.com/path/src.tar.gz?token=abc#frag"), + "src.tar.gz" + ); + assert_eq!(source_basename("https://example.com/a/b/x.tgz"), "x.tgz"); + } + + #[test] + fn source_basename_handles_local_paths() { + assert_eq!(source_basename("/tmp/foo/src.tar.gz"), "src.tar.gz"); + assert_eq!(source_basename("./relative/src.tgz"), "src.tgz"); + assert_eq!(source_basename("src.tar.gz"), "src.tar.gz"); + } + + #[test] + fn validate_source_format_accepts_recognized_extensions() { + validate_source_format("https://example.com/src.tar.gz").unwrap(); + validate_source_format("/tmp/src.tgz").unwrap(); + // Case-insensitive. + validate_source_format("SRC.TAR.GZ").unwrap(); + } + + #[test] + fn validate_source_format_rejects_unknown_formats() { + for source in [ + "https://example.com/src.zip", + "/tmp/src.rar", + "src", + "src.gz", + ] { + let err = validate_source_format(source).unwrap_err(); + assert!(matches!(err, Error::UnsupportedSourceFormat { .. })); + } + } } From 0c23e77da72465b983bf63b8500bc9743fb06c40 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Thu, 9 Jul 2026 16:21:07 -0300 Subject: [PATCH 27/33] Support zip files as verifiable build sources. --- Cargo.toml | 1 + cmd/soroban-cli/Cargo.toml | 1 + .../commands/contract/build/source_archive.rs | 118 +++++++++++++++++- .../src/commands/contract/build/verifiable.rs | 6 +- .../src/commands/contract/verify.rs | 110 ++++++++-------- 5 files changed, 177 insertions(+), 59 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 8f5f94dce2..2f49a06d45 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -88,6 +88,7 @@ itertools = "0.10.0" async-trait = "0.1.76" tar = "0.4.46" flate2 = "1.0.30" +zip = { version = "8.6.0", default-features = false, features = ["deflate"] } serde-aux = "4.1.2" serde_json = "1.0.82" serde = "1.0.82" diff --git a/cmd/soroban-cli/Cargo.toml b/cmd/soroban-cli/Cargo.toml index 213076bf26..a682bc74f8 100644 --- a/cmd/soroban-cli/Cargo.toml +++ b/cmd/soroban-cli/Cargo.toml @@ -115,6 +115,7 @@ futures = "0.3.30" home = "0.5.9" flate2 = { workspace = true } tar = { workspace = true } +zip = { workspace = true } bytesize = "1.3.0" humantime = "2.1.0" phf = { version = "0.11.2", features = ["macros"] } diff --git a/cmd/soroban-cli/src/commands/contract/build/source_archive.rs b/cmd/soroban-cli/src/commands/contract/build/source_archive.rs index 0b69f98b52..682e911d3f 100644 --- a/cmd/soroban-cli/src/commands/contract/build/source_archive.rs +++ b/cmd/soroban-cli/src/commands/contract/build/source_archive.rs @@ -76,10 +76,53 @@ pub enum Error { #[error("could not extract source archive: {0}")] ArchiveExtract(std::io::Error), + #[error("could not extract source archive: {0}")] + ZipExtract(zip::result::ZipError), + #[error(transparent)] Data(#[from] data::Error), } +/// Container formats we can extract a source tree from. This only concerns how +/// the tree is packed for transport; the tree itself is always wrapped in a +/// single top-level directory (SEP-58), which callers check after extraction. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum ArchiveFormat { + /// Gzipped tarball — what `build --verifiable` produces. + TarGz, + /// Zip archive. + Zip, +} + +/// Recognized archive extensions and the format each maps to, matched +/// case-insensitively as a suffix of the archive's filename. Single source of +/// truth for both format detection and the "accepted formats" error text. +const ARCHIVE_EXTENSIONS: &[(&str, ArchiveFormat)] = &[ + (".tar.gz", ArchiveFormat::TarGz), + (".tgz", ArchiveFormat::TarGz), + (".zip", ArchiveFormat::Zip), +]; + +impl ArchiveFormat { + /// The format named by `filename`'s extension, or `None` if unrecognized. + pub(crate) fn from_filename(filename: &str) -> Option { + let lower = filename.to_ascii_lowercase(); + ARCHIVE_EXTENSIONS + .iter() + .find(|(ext, _)| lower.ends_with(ext)) + .map(|(_, format)| *format) + } + + /// Comma-separated list of accepted extensions, for error messages. + pub(crate) fn recognized_extensions() -> String { + ARCHIVE_EXTENSIONS + .iter() + .map(|(ext, _)| *ext) + .collect::>() + .join(", ") + } +} + /// The source tree's root: always the current working directory. The archive is /// rooted there as-is — we do NOT search upward for a git repository or anchor on /// `--manifest-path`'s directory, since for a workspace member the build needs @@ -305,11 +348,20 @@ pub(crate) fn unpack_targz(bytes: &[u8], dest: &Path) -> Result<(), Error> { .map_err(Error::ArchiveExtract) } -/// Create a fresh temp directory, unpack the gzipped source tarball `bytes` into -/// it, harden its permissions, and return the guard (the tree lives at its -/// `path()`). Shared by `build --verifiable` (builds from the extracted copy) -/// and `verify` (rebuilds from it); `prefix` names the dir so the two are -/// distinguishable on disk. +/// Unpack a zip archive into `dest`. `ZipArchive::extract` sanitizes each +/// entry's path (dropping anything that would escape `dest`), so a hostile +/// archive can't write outside the tempdir. +pub(crate) fn unpack_zip(bytes: &[u8], dest: &Path) -> Result<(), Error> { + zip::ZipArchive::new(std::io::Cursor::new(bytes)) + .and_then(|mut archive| archive.extract(dest)) + .map_err(Error::ZipExtract) +} + +/// Create a fresh temp directory, unpack the source archive `bytes` (in the +/// given `format`) into it, harden its permissions, and return the guard (the +/// tree lives at its `path()`). Shared by `build --verifiable` (builds from the +/// extracted copy) and `verify` (rebuilds from it); `prefix` names the dir so +/// the two are distinguishable on disk. /// /// The temp dir is created under `/tmp`, NOT the OS temp dir: on macOS /// `$TMPDIR` lives under /var/folders, which container VMs (Docker Desktop, @@ -321,6 +373,7 @@ pub(crate) fn unpack_targz(bytes: &[u8], dest: &Path) -> Result<(), Error> { pub(crate) fn extract_into_hardened_tempdir( bytes: &[u8], prefix: &str, + format: ArchiveFormat, ) -> Result { let base = data::data_local_dir()?.join("tmp"); std::fs::create_dir_all(&base).map_err(|source| Error::ArchiveWrite { @@ -331,7 +384,10 @@ pub(crate) fn extract_into_hardened_tempdir( .prefix(prefix) .tempdir_in(&base) .map_err(Error::ArchiveExtract)?; - unpack_targz(bytes, tmp.path())?; + match format { + ArchiveFormat::TarGz => unpack_targz(bytes, tmp.path())?, + ArchiveFormat::Zip => unpack_zip(bytes, tmp.path())?, + } enforce_hardened_tree(tmp.path()).map_err(Error::ArchiveExtract)?; Ok(tmp) } @@ -342,6 +398,56 @@ mod tests { use crate::config::locator::enforce_hardened_tree; use sha2::{Digest, Sha256}; + #[test] + fn archive_format_from_filename() { + assert_eq!( + ArchiveFormat::from_filename("src.tar.gz"), + Some(ArchiveFormat::TarGz) + ); + assert_eq!( + ArchiveFormat::from_filename("SRC.TGZ"), + Some(ArchiveFormat::TarGz) + ); + assert_eq!( + ArchiveFormat::from_filename("src.zip"), + Some(ArchiveFormat::Zip) + ); + assert_eq!(ArchiveFormat::from_filename("src.rar"), None); + assert_eq!(ArchiveFormat::from_filename("src"), None); + // The listed extensions are exactly what the error surfaces. + assert_eq!( + ArchiveFormat::recognized_extensions(), + ".tar.gz, .tgz, .zip" + ); + } + + #[test] + fn unpack_zip_round_trips() { + use std::io::Write; + // Build a small zip with a single top-level `source/` dir. + let mut buf = Vec::new(); + { + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(&mut buf)); + let opts: zip::write::FileOptions<'_, ()> = zip::write::FileOptions::default(); + zip.start_file("source/Cargo.toml", opts).unwrap(); + zip.write_all(b"# crate").unwrap(); + zip.start_file("source/src/lib.rs", opts).unwrap(); + zip.write_all(b"// code").unwrap(); + zip.finish().unwrap(); + } + + let dest = tempfile::TempDir::new().unwrap(); + unpack_zip(&buf, dest.path()).unwrap(); + assert_eq!( + std::fs::read(dest.path().join("source/Cargo.toml")).unwrap(), + b"# crate" + ); + assert_eq!( + std::fs::read(dest.path().join("source/src/lib.rs")).unwrap(), + b"// code" + ); + } + #[test] fn is_warned_matches_names_and_dotted_suffixes() { use std::ffi::OsStr; diff --git a/cmd/soroban-cli/src/commands/contract/build/verifiable.rs b/cmd/soroban-cli/src/commands/contract/build/verifiable.rs index c47be14c96..331fd6baa4 100644 --- a/cmd/soroban-cli/src/commands/contract/build/verifiable.rs +++ b/cmd/soroban-cli/src/commands/contract/build/verifiable.rs @@ -325,7 +325,11 @@ fn resolve_archive(cmd: &Cmd, source_root: &Path, print: &Print) -> Result, /// Bypass interactive confirmation when the WASM's bldimg is not in the - /// default trust list, or when the source is a tarball (tarballs are - /// never default-trusted). + /// default trust list, or when the source is provided as an archive (source + /// archives are never default-trusted). #[arg(long)] pub trust: bool, @@ -187,14 +187,14 @@ pub enum Error { #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum TrustKind { Bldimg, - Tarball, + SourceArchive, } impl std::fmt::Display for TrustKind { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { TrustKind::Bldimg => write!(f, "bldimg"), - TrustKind::Tarball => write!(f, "tarball"), + TrustKind::SourceArchive => write!(f, "source archive"), } } } @@ -222,11 +222,11 @@ fn trusted_bldimg_regex() -> Regex { Regex::new(TRUSTED_BLDIMG_REGEX_STR).unwrap() } -/// Pure trust decision; no I/O. Tarball sources are never default-trusted. +/// Pure trust decision; no I/O. Source archives are never default-trusted. pub fn trust_decision(value: &str, kind: TrustKind, trust_flag: bool) -> TrustDecision { let default_trusted = match kind { TrustKind::Bldimg => trusted_bldimg_regex().is_match(value), - TrustKind::Tarball => false, + TrustKind::SourceArchive => false, }; if default_trusted { TrustDecision::Trusted @@ -297,10 +297,10 @@ impl Cmd { // bldimg trust check is always required. require_trust(self.trust, TrustKind::Bldimg, &meta.bldimg, &print)?; - // Tarball source: trust the URL we will actually fetch from (either the + // Source archive: trust the URL we will actually fetch from (either the // value the WASM recorded, or the user's `--source-uri` override). if let Some(url) = self.effective_source_uri(&meta) { - require_trust(self.trust, TrustKind::Tarball, &url, &print)?; + require_trust(self.trust, TrustKind::SourceArchive, &url, &print)?; } // Materialize the recorded source into a tempdir so the rebuild can @@ -360,7 +360,7 @@ impl Cmd { // *before* the rebuild. A conformant source archive ships no build // output, so anything here was planted; excluding these from the post- // build search stops an attacker from smuggling a pre-built binary into - // the tarball to masquerade as the rebuild's output and spoof a match. + // the archive to masquerade as the rebuild's output and spoof a match. let preexisting_wasms: HashSet = collect_release_wasms(&source_root).into_iter().collect(); if !preexisting_wasms.is_empty() { @@ -413,7 +413,7 @@ impl Cmd { } } - /// The tarball URL we'll actually retrieve from: the cli override if set, + /// The source archive URL we'll actually retrieve from: the cli override if set, /// otherwise the value recorded in the WASM. Returns `None` when neither /// records a `source_uri` (only `source_sha256` is set), in which case /// there's nothing to trust-check here. @@ -546,8 +546,8 @@ fn confirm_interactively(kind: TrustKind, value: &str) -> Result<(), Error> { TrustKind::Bldimg => format!( "Image {value} is not in the default trust list (only docker.io/stellar/stellar-cli is trusted by default)." ), - TrustKind::Tarball => format!( - "Tarball source {value} is not trusted by default. Tarballs always require confirmation." + TrustKind::SourceArchive => format!( + "Source archive {value} is not trusted by default. Source archives always require confirmation." ), }; print.warnln(context); @@ -584,18 +584,18 @@ async fn materialize_source( source_uri_override: Option<&str>, print: &Print, ) -> Result { - let tarball_source = source_uri_override + let resolved_source = source_uri_override .map(str::to_string) .or_else(|| meta.source_uri.clone()); - let Some(source) = tarball_source else { + let Some(source) = resolved_source else { // No source_uri anywhere — only source_sha256 is set. return Err(Error::SourceUriRequired); }; - validate_source_format(&source)?; + let format = resolve_source_format(&source)?; print.infoln(format!("Fetching source code from {source}")); - let bytes = fetch_tarball_bytes(&source).await?; + let bytes = fetch_source_bytes(&source).await?; if let Some(expected) = &meta.source_sha256 { verify_source_sha256(&bytes, expected)?; print.checkln("Source SHA-256 matches"); @@ -603,14 +603,10 @@ async fn materialize_source( Ok(source_archive::extract_into_hardened_tempdir( &bytes, "verify-src-", + format, )?) } -/// Extensions we accept for a source archive: the archive is always a gzipped -/// tarball (see `source_archive`), so only these name it. Checked -/// case-insensitively against the source's basename. -const RECOGNIZED_SOURCE_EXTENSIONS: &[&str] = &[".tar.gz", ".tgz"]; - /// The last path segment of `source`, whether it's a URL or a local path. Try /// parsing as a URL first (so query strings and fragments are dropped); if that /// fails, `source` is a local path, so fall back to `Path::file_name`. @@ -628,27 +624,23 @@ fn source_basename(source: &str) -> String { .unwrap_or_default() } -/// Reject a `--source-uri` (or recorded `source_uri`) whose basename doesn't end -/// in a recognized archive extension, before we bother fetching it, naming the -/// formats we accept. -fn validate_source_format(source: &str) -> Result<(), Error> { - let basename = source_basename(source).to_ascii_lowercase(); - if RECOGNIZED_SOURCE_EXTENSIONS - .iter() - .any(|ext| basename.ends_with(ext)) - { - return Ok(()); - } - Err(Error::UnsupportedSourceFormat { - uri: source.to_string(), - formats: RECOGNIZED_SOURCE_EXTENSIONS.join(", "), +/// Determine the archive format from a `--source-uri` (or recorded `source_uri`) +/// by its basename, rejecting sources whose extension we don't recognize before +/// we bother fetching them, naming the formats we accept. +fn resolve_source_format(source: &str) -> Result { + let basename = source_basename(source); + source_archive::ArchiveFormat::from_filename(&basename).ok_or_else(|| { + Error::UnsupportedSourceFormat { + uri: source.to_string(), + formats: source_archive::ArchiveFormat::recognized_extensions(), + } }) } -/// Retrieve the tarball bytes. `source` is either an `http(s)://` URL or a -/// local file path. The split is by prefix, not by attempting both — keeps +/// Retrieve the source archive bytes. `source` is either an `http(s)://` URL or +/// a local file path. The split is by prefix, not by attempting both — keeps /// behavior predictable. -async fn fetch_tarball_bytes(source: &str) -> Result, Error> { +async fn fetch_source_bytes(source: &str) -> Result, Error> { if source.starts_with("http://") || source.starts_with("https://") { let resp = reqwest::get(source) .await @@ -902,7 +894,7 @@ mod tests { } #[test] - fn extract_metadata_happy_path_tarball_pair() { + fn extract_metadata_happy_path_source_pair() { let wasm = make_wasm_with_meta(&[ ("bldimg", &good_bldimg()), ("source_uri", "https://example.com/src.tar.gz"), @@ -1018,27 +1010,27 @@ mod tests { } #[test] - fn trust_decision_tarball_always_needs_confirmation() { + fn trust_decision_source_archive_always_needs_confirmation() { assert_eq!( trust_decision( "https://github.com/foo/bar.tar.gz", - TrustKind::Tarball, + TrustKind::SourceArchive, false ), TrustDecision::NeedsConfirmation ); assert_eq!( - trust_decision("/local/foo.tar.gz", TrustKind::Tarball, false), + trust_decision("/local/foo.tar.gz", TrustKind::SourceArchive, false), TrustDecision::NeedsConfirmation ); } #[test] - fn trust_decision_tarball_override_with_trust() { + fn trust_decision_source_archive_override_with_trust() { assert_eq!( trust_decision( "https://github.com/foo/bar.tar.gz", - TrustKind::Tarball, + TrustKind::SourceArchive, true ), TrustDecision::Overridden @@ -1370,22 +1362,36 @@ mod tests { } #[test] - fn validate_source_format_accepts_recognized_extensions() { - validate_source_format("https://example.com/src.tar.gz").unwrap(); - validate_source_format("/tmp/src.tgz").unwrap(); + fn resolve_source_format_accepts_recognized_extensions() { + use source_archive::ArchiveFormat; + assert_eq!( + resolve_source_format("https://example.com/src.tar.gz").unwrap(), + ArchiveFormat::TarGz + ); + assert_eq!( + resolve_source_format("/tmp/src.tgz").unwrap(), + ArchiveFormat::TarGz + ); + assert_eq!( + resolve_source_format("https://example.com/src.zip?token=abc").unwrap(), + ArchiveFormat::Zip + ); // Case-insensitive. - validate_source_format("SRC.TAR.GZ").unwrap(); + assert_eq!( + resolve_source_format("SRC.TAR.GZ").unwrap(), + ArchiveFormat::TarGz + ); } #[test] - fn validate_source_format_rejects_unknown_formats() { + fn resolve_source_format_rejects_unknown_formats() { for source in [ - "https://example.com/src.zip", - "/tmp/src.rar", + "https://example.com/src.rar", + "/tmp/src.7z", "src", "src.gz", ] { - let err = validate_source_format(source).unwrap_err(); + let err = resolve_source_format(source).unwrap_err(); assert!(matches!(err, Error::UnsupportedSourceFormat { .. })); } } From d702bc0865a91e589b4ba5b76544b8350699e0a0 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Thu, 9 Jul 2026 17:33:25 -0300 Subject: [PATCH 28/33] Reject duplicate build metadata when verifying. --- .../src/commands/contract/verify.rs | 54 +++++++++++++++++-- 1 file changed, 51 insertions(+), 3 deletions(-) diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index 31f8057e86..1bd037791f 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -101,6 +101,9 @@ pub enum Error { #[error("the WASM's contractmetav0 does not record a `bldimg` entry; cannot verify")] MissingBldimg, + #[error("the WASM's contractmetav0 records more than one `{field}` entry; refusing to verify (which value applies is ambiguous)")] + DuplicateMeta { field: &'static str }, + #[error("the WASM's contractmetav0 does not record a `source_sha256` entry; cannot verify")] MissingSourceSha256, @@ -457,14 +460,28 @@ pub fn extract_metadata(wasm: &[u8]) -> Result { let mut source_sha256: Option = None; let mut bldopts: Vec = Vec::new(); + // Each of these SEP-58 fields must appear at most once. Reject duplicates + // rather than silently taking the last: two `bldimg` entries (say a benign + // one to fool inspection and a second the cli would actually trust and + // rebuild in) would be a verification-bypass vector, and the same ambiguity + // applies to the `source_uri`/`source_sha256` that pin what gets rebuilt. + let set_once = + |slot: &mut Option, field: &'static str, v: String| -> Result<(), Error> { + if slot.is_some() { + return Err(Error::DuplicateMeta { field }); + } + *slot = Some(v); + Ok(()) + }; + for entry in &spec.meta { let ScMetaEntry::ScMetaV0(ScMetaV0 { key, val }) = entry; let k = key.to_string(); let v = val.to_string(); match k.as_str() { - "bldimg" => bldimg = Some(v), - "source_uri" => source_uri = Some(v), - "source_sha256" => source_sha256 = Some(v), + "bldimg" => set_once(&mut bldimg, "bldimg", v)?, + "source_uri" => set_once(&mut source_uri, "source_uri", v)?, + "source_sha256" => set_once(&mut source_sha256, "source_sha256", v)?, "bldopt" => bldopts.push(v), _ => {} // cliver and any user --meta are intentionally ignored } @@ -916,6 +933,37 @@ mod tests { assert!(matches!(err, Error::MissingBldimg)); } + #[test] + fn extract_metadata_duplicate_bldimg_errors() { + // A second bldimg — e.g. a benign one to fool inspection plus one the + // cli would actually trust and rebuild in — must be rejected outright. + let other = format!("docker.io/attacker/evil@sha256:{}", "b".repeat(64)); + let wasm = make_wasm_with_meta(&[ + ("bldimg", &good_bldimg()), + ("bldimg", &other), + ("source_sha256", &"f".repeat(64)), + ]); + let err = extract_metadata(&wasm).unwrap_err(); + assert!(matches!(err, Error::DuplicateMeta { field: "bldimg" })); + } + + #[test] + fn extract_metadata_duplicate_source_ids_error() { + for field in ["source_uri", "source_sha256"] { + let wasm = make_wasm_with_meta(&[ + ("bldimg", &good_bldimg()), + ("source_sha256", &"f".repeat(64)), + (field, "https://example.com/a.tar.gz"), + (field, "https://example.com/b.tar.gz"), + ]); + let err = extract_metadata(&wasm).unwrap_err(); + assert!( + matches!(err, Error::DuplicateMeta { field: f } if f == field), + "expected DuplicateMeta for {field}, got {err:?}" + ); + } + } + #[test] fn extract_metadata_missing_source_id_errors() { let wasm = make_wasm_with_meta(&[("bldimg", &good_bldimg())]); From d72a03968902afa8acece10718a3cd9de7056644 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Thu, 9 Jul 2026 18:29:50 -0300 Subject: [PATCH 29/33] Replay recorded metadata in order when verifying. --- .../src/commands/contract/verify.rs | 238 +++++++++++++----- 1 file changed, 171 insertions(+), 67 deletions(-) diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index 1bd037791f..90b23b0ddc 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -240,17 +240,33 @@ pub fn trust_decision(value: &str, kind: TrustKind, trust_flag: bool) -> TrustDe } } -/// SEP-58 metadata extracted from a contract's `contractmetav0` section. +/// Meta keys the rebuild regenerates on its own, so verify must not replay them +/// — re-passing one as `--meta` would write it twice and break byte-equality. +/// `cliver` is re-injected by the container's CLI; `rsver`/`rssdkver` are +/// re-embedded by the SDK when the source is recompiled. Everything else is +/// replayed verbatim (see `ExtractedMetadata::meta_entries`). +const REGENERATED_META_KEYS: &[&str] = &["cliver", "rsver", "rssdkver"]; + +/// SEP-58 metadata read from a contract's `contractmetav0` section. /// -/// `cliver` is intentionally not captured: the rebuild container re-injects it, -/// so verify's job is to ensure the rebuild's cliver matches the original's -/// (which it will when `bldimg` resolves to the same container). +/// Verify reproduces the section by *replaying* what the WASM records rather +/// than reconstructing it from `build`'s ordering rules: `meta_entries` holds +/// every recorded entry, in the exact order it appears in the WASM, so the +/// rebuild's metadata matches byte-for-byte no matter how (or by what tool) the +/// original was produced — including WASMs authored by hand per SEP-58. The +/// entries the rebuild regenerates itself (`REGENERATED_META_KEYS`) are excluded. +/// +/// The typed fields (`bldimg`, `source_uri`, `source_sha256`, `bldopts`) are +/// pulled out of the same entries only to *drive* the rebuild — pick the image, +/// trust-check, fetch the source, and derive the forwarded build flags. They are +/// not re-added to the `--meta` list; the replay of `meta_entries` covers them. #[derive(Debug, Clone)] pub struct ExtractedMetadata { pub bldimg: String, pub source_uri: Option, pub source_sha256: Option, pub bldopts: Vec, + pub meta_entries: Vec<(String, String)>, } impl Cmd { @@ -446,9 +462,12 @@ impl Cmd { } } -/// Walk the WASM's `contractmetav0` entries and pull out the SEP-58 fields we -/// need to drive a rebuild. Errors when `bldimg` or `source_sha256` is absent, -/// since neither has a sensible default. `source_uri` is optional. +/// Walk the WASM's `contractmetav0` entries. Every entry is captured, in order, +/// into `meta_entries` for verbatim replay — except the keys the rebuild +/// regenerates itself (`REGENERATED_META_KEYS`). The SEP-58 fields that drive +/// the rebuild are pulled out of the same walk. Errors when `bldimg` or +/// `source_sha256` is absent, since neither has a sensible default; `source_uri` +/// is optional. pub fn extract_metadata(wasm: &[u8]) -> Result { let spec = Spec::new(wasm)?; if spec.meta.is_empty() { @@ -459,6 +478,7 @@ pub fn extract_metadata(wasm: &[u8]) -> Result { let mut source_uri: Option = None; let mut source_sha256: Option = None; let mut bldopts: Vec = Vec::new(); + let mut meta_entries: Vec<(String, String)> = Vec::new(); // Each of these SEP-58 fields must appear at most once. Reject duplicates // rather than silently taking the last: two `bldimg` entries (say a benign @@ -478,12 +498,24 @@ pub fn extract_metadata(wasm: &[u8]) -> Result { let ScMetaEntry::ScMetaV0(ScMetaV0 { key, val }) = entry; let k = key.to_string(); let v = val.to_string(); + + // Entries the rebuild re-creates on its own are never replayed; passing + // them as `--meta` would duplicate them and break byte-equality. + if REGENERATED_META_KEYS.contains(&k.as_str()) { + continue; + } + + // Record every other entry verbatim, in order, to replay as `--meta`. + // The typed fields below are additionally pulled out to drive the + // rebuild, but the replayed metadata always comes from `meta_entries`. + meta_entries.push((k.clone(), v.clone())); + match k.as_str() { "bldimg" => set_once(&mut bldimg, "bldimg", v)?, "source_uri" => set_once(&mut source_uri, "source_uri", v)?, "source_sha256" => set_once(&mut source_sha256, "source_sha256", v)?, "bldopt" => bldopts.push(v), - _ => {} // cliver and any user --meta are intentionally ignored + _ => {} // user meta: carried in meta_entries for replay } } @@ -524,6 +556,7 @@ pub fn extract_metadata(wasm: &[u8]) -> Result { source_uri, source_sha256, bldopts, + meta_entries, }) } @@ -722,21 +755,25 @@ fn locate_extracted_source_root(workdir: &Path) -> Result { } /// Compose the argv we hand to the container's `stellar contract build`, plus -/// the env vars to apply via docker `-e`, so that: -/// - the bldopts from the original build become flags (each entry is one -/// token, ready for clap), AND -/// - bldimg / source-ids / bldopt are re-recorded as `--meta` entries so -/// the rebuilt WASM has identical metadata to the original. +/// the env vars to apply via docker `-e`. +/// +/// The metadata is *replayed*, not reconstructed: every entry the WASM records +/// (`meta.meta_entries`, already stripped of the keys the rebuild regenerates) +/// is re-emitted as a `--meta key=value` in its original order, so the rebuilt +/// `contractmetav0` mirrors the source WASM regardless of how it was produced. +/// This keeps verify independent of `build`'s ordering rules and lets it verify +/// WASMs authored by hand per SEP-58. /// -/// `--env=` bldopts are NOT forwarded as build flags: the original build -/// applied them via docker `-e` (recording them as `bldopt` only), so we replay -/// them the same way. The recorded value is shell-escaped, so we unescape it -/// back to a raw `NAME=VALUE` for docker `-e`. They're still re-recorded as -/// `bldopt` meta so the rebuilt WASM's metadata matches the original. +/// The `bldopt` entries additionally drive the *build flags*: each is forwarded +/// as a flag to the inner `contract build`, with two exceptions — +/// - `--env=` bldopts are applied via docker `-e` (as the original build did), +/// not forwarded. They're shell-escaped at the source, so we unescape back +/// to a raw `NAME=VALUE`. +/// - `--meta=` bldopts are NOT forwarded: the metadata they produced is +/// already a standalone entry in `meta_entries` and replayed above, so +/// forwarding them too would write the value twice. /// -/// cliver is intentionally not re-injected — the container's stellar adds it -/// automatically, and it will match the original's iff `bldimg` resolves to -/// the same container. +/// Both are still re-recorded — via their `bldopt=` entry in `meta_entries`. /// /// `supports_locked`: whether the recorded bldimg's `contract build` accepts /// `--locked` (added in cli 25.2.0). When false the flag is never injected, so @@ -753,40 +790,43 @@ fn build_container_command( // own — e.g. `--meta=source_repo='github:foo'` or `--env=B='a b'`. The // single-package rebuild hands argv straight to `stellar` with no shell, // so unescape each bldopt back to the one raw argv token the original - // build used; otherwise the quoting leaks into the value (a quoted - // `--meta` value even shifts the WASM's byte size via XDR alignment). + // build used; otherwise the quoting leaks into the value. let token = shlex::split(o) .and_then(|mut v| (v.len() == 1).then(|| v.remove(0))) .unwrap_or_else(|| o.clone()); if let Some(kv) = token.strip_prefix("--env=") { // Applied via docker `-e` as a raw `NAME=VALUE`, never forwarded. env.push(kv.to_string()); + } else if token.starts_with("--meta=") { + // The metadata this produced is replayed from `meta_entries`; + // forwarding it as a flag too would write the value twice. } else { forwarded.push(token); } } - // Re-record bldimg / source-ids / every bldopt as `--meta`, reusing the - // exact composition `build --verifiable` used, so the rebuilt WASM's - // metadata matches the original byte-for-byte. - let ids = verifiable::SourceIds { - source_uri: meta.source_uri.clone(), - source_sha256: meta.source_sha256.clone(), - }; - let metadata = verifiable::build_metadata_args(&meta.bldimg, &ids, &meta.bldopts); - // When the image supports it, `--locked` is forced — even if the original // somehow lacked it (a non-conformant build) — so the verifier insists on a // locked rebuild and dependency drift can't move bytes underneath us. Older - // images (< cli 25.2.0) reject the flag, so it's omitted there. + // images (< cli 25.2.0) reject the flag, so it's omitted there. Forcing it + // only affects the build (determinism); it isn't recorded as metadata, so it + // doesn't perturb the rebuilt `contractmetav0`. if supports_locked && !forwarded.iter().any(|a| a == "--locked") { forwarded.insert(0, "--locked".to_string()); } - ( - verifiable::compose_container_args(&forwarded, &metadata), - env, - ) + // Replay every recorded meta entry verbatim, in the WASM's own order, so the + // rebuilt section matches the original byte-for-byte. + let mut metadata: Vec = Vec::new(); + for (k, v) in &meta.meta_entries { + metadata.push("--meta".to_string()); + metadata.push(format!("{k}={v}")); + } + + let mut args = vec!["contract".to_string(), "build".to_string()]; + args.extend(forwarded); + args.extend(metadata); + (args, env) } /// The two wasm release-output suffixes cargo may write to, newest first. @@ -1001,17 +1041,30 @@ mod tests { } #[test] - fn extract_metadata_ignores_cliver_and_user_meta() { + fn extract_metadata_captures_user_meta_and_drops_regenerated_keys() { let wasm = make_wasm_with_meta(&[ ("bldimg", &good_bldimg()), ("source_sha256", &"b".repeat(64)), ("cliver", "26.0.0#abcdef"), + ("rsver", "1.93.0"), + ("rssdkver", "23.0.0"), ("home_domain", "fnando.com"), ("author", "alice"), ]); let meta = extract_metadata(&wasm).unwrap(); - // cliver and user meta land in neither bldopts nor source-ids. + // User meta is not a bldopt or source-id, but it IS captured for replay. assert!(meta.bldopts.is_empty()); + // The rebuild regenerates cliver/rsver/rssdkver, so they're excluded; + // every other entry is captured verbatim, in order, for replay. + assert_eq!( + meta.meta_entries, + vec![ + ("bldimg".to_string(), good_bldimg()), + ("source_sha256".to_string(), "b".repeat(64)), + ("home_domain".to_string(), "fnando.com".to_string()), + ("author".to_string(), "alice".to_string()), + ] + ); } #[test] @@ -1123,6 +1176,7 @@ mod tests { source_uri: None, source_sha256: Some("f".repeat(64)), bldopts: Vec::new(), + meta_entries: Vec::new(), }; let print = Print::new(true); let err = materialize_source(&meta, None, &print).await.unwrap_err(); @@ -1130,7 +1184,31 @@ mod tests { } #[test] - fn build_container_command_replays_bldopts_and_re_records_meta() { + fn build_container_command_replays_meta_in_order_and_forwards_build_flags() { + // The recorded entries as they'd appear in the WASM (cliver/rsver/etc. + // already excluded by extract_metadata). build_container_command must + // replay these verbatim, in order, and derive the build flags from the + // `bldopt=` entries. + let meta_entries = vec![ + ("bldimg".to_string(), good_bldimg()), + ( + "source_uri".to_string(), + "https://github.com/foo/bar".to_string(), + ), + ("source_sha256".to_string(), "b".repeat(64)), + ("home_domain".to_string(), "fnando.com".to_string()), + ("bldopt".to_string(), "--locked".to_string()), + ( + "bldopt".to_string(), + "--meta=home_domain=fnando.com".to_string(), + ), + ("bldopt".to_string(), "--optimize".to_string()), + ("bldopt".to_string(), "--env=A=1".to_string()), + ( + "bldopt".to_string(), + "--env=B='this is very nice'".to_string(), + ), + ]; let meta = ExtractedMetadata { bldimg: good_bldimg(), source_uri: Some("https://github.com/foo/bar".to_string()), @@ -1142,17 +1220,22 @@ mod tests { "--env=A=1".to_string(), "--env=B='this is very nice'".to_string(), ], + meta_entries: meta_entries.clone(), }; let (cmd, env) = build_container_command(&meta, true); // Subcommand prefix. assert_eq!(&cmd[..2], &["contract".to_string(), "build".to_string()]); - // Bldopts are forwarded verbatim as flags to the inner `stellar contract build`. + // Build-affecting bldopts are forwarded as flags to the inner build. assert!(cmd.contains(&"--locked".to_string())); - assert!(cmd.contains(&"--meta=home_domain=fnando.com".to_string())); assert!(cmd.contains(&"--optimize".to_string())); + // `--meta=` bldopts are NOT forwarded as flags: the value is replayed as + // its own standalone `home_domain` entry below, so forwarding it too + // would write it twice. + assert!(!cmd.iter().any(|a| a.starts_with("--meta="))); + // `--env=` bldopts are applied via docker `-e` (unescaped), never // forwarded as build flags. assert!(!cmd.iter().any(|a| a.starts_with("--env="))); @@ -1161,30 +1244,26 @@ mod tests { vec!["A=1".to_string(), "B=this is very nice".to_string()] ); - // bldimg and source-ids are re-recorded as `--meta`. - assert!(cmd - .windows(2) - .any(|w| w[0] == "--meta" && w[1] == format!("bldimg={}", good_bldimg()))); - assert!(cmd - .windows(2) - .any(|w| w[0] == "--meta" && w[1] == "source_uri=https://github.com/foo/bar")); - - // Every bldopt — including the `--env=` ones — is re-recorded as a - // `bldopt=` meta so the rebuilt WASM mirrors the original's entries. - assert!(cmd - .windows(2) - .any(|w| w[0] == "--meta" && w[1] == "bldopt=--locked")); - assert!(cmd + // The `--meta` list is the recorded entries replayed verbatim, in the + // exact order the WASM records them. + let replayed: Vec<(String, String)> = cmd .windows(2) - .any(|w| w[0] == "--meta" && w[1] == "bldopt=--env=A=1")); + .filter(|w| w[0] == "--meta") + .map(|w| { + let (k, v) = w[1].split_once('=').unwrap(); + (k.to_string(), v.to_string()) + }) + .collect(); + assert_eq!(replayed, meta_entries); } #[test] - fn build_container_command_unescapes_quoted_meta_bldopt() { - // Recorded bldopts are shell-escaped at the source, so a `--meta` value - // with a `:` (or spaces) is stored quoted. Verify must unescape it back - // to the raw argv token — otherwise the literal quotes leak into the - // meta value and the rebuilt WASM differs from the original. + fn build_container_command_replays_meta_bldopt_verbatim_without_forwarding() { + // A `--meta=` bldopt is shell-escaped at the source (a value with a `:` + // or spaces is stored quoted). Verify must NOT forward it as a build + // flag — the value reaches the rebuilt WASM through the standalone + // `source_repo` entry — and the `bldopt=` entry itself is replayed + // verbatim so its escaped form round-trips byte-for-byte. let meta = ExtractedMetadata { bldimg: good_bldimg(), source_uri: Some("https://github.com/foo/bar".to_string()), @@ -1192,15 +1271,34 @@ mod tests { bldopts: vec![ "--meta=source_repo='github:LayerZero-Labs/monorepo-external'".to_string(), ], + meta_entries: vec![ + ( + "source_repo".to_string(), + "github:LayerZero-Labs/monorepo-external".to_string(), + ), + ( + "bldopt".to_string(), + "--meta=source_repo='github:LayerZero-Labs/monorepo-external'".to_string(), + ), + ], }; let (cmd, _env) = build_container_command(&meta, true); - // The forwarded build flag is unescaped (no literal quotes reach clap). + + // No `--meta=` bldopt is forwarded as a build flag. assert!( - cmd.contains(&"--meta=source_repo=github:LayerZero-Labs/monorepo-external".to_string()), - "quotes must be stripped from the forwarded --meta, got {cmd:?}" + !cmd.iter().any(|a| a.starts_with("--meta=")), + "--meta bldopts must not be forwarded, got {cmd:?}" ); - // The re-recorded `bldopt=` meta keeps the original escaped form verbatim - // so the rebuilt WASM's bldopt entry matches the original byte-for-byte. + + // The standalone entry carries the unescaped value to the rebuild. + assert!( + cmd.windows(2).any(|w| w[0] == "--meta" + && w[1] == "source_repo=github:LayerZero-Labs/monorepo-external"), + "the standalone meta entry must be replayed, got {cmd:?}" + ); + + // The `bldopt=` entry keeps the original escaped form verbatim so the + // rebuilt WASM's bldopt entry matches the original byte-for-byte. assert!( cmd.windows(2).any(|w| w[0] == "--meta" && w[1] == "bldopt=--meta=source_repo='github:LayerZero-Labs/monorepo-external'"), @@ -1217,6 +1315,10 @@ mod tests { source_uri: Some("https://github.com/foo/bar".to_string()), source_sha256: Some("b".repeat(64)), bldopts: vec!["--meta=author=alice".to_string()], + meta_entries: vec![ + ("author".to_string(), "alice".to_string()), + ("bldopt".to_string(), "--meta=author=alice".to_string()), + ], }; let (cmd, _env) = build_container_command(&meta, true); let locked_count = cmd.iter().filter(|s| *s == "--locked").count(); @@ -1236,6 +1338,7 @@ mod tests { source_uri: Some("https://github.com/foo/bar".to_string()), source_sha256: Some("b".repeat(64)), bldopts: vec!["--optimize".to_string()], + meta_entries: vec![("bldopt".to_string(), "--optimize".to_string())], }; let (cmd, _env) = build_container_command(&meta, false); assert!( @@ -1250,6 +1353,7 @@ mod tests { source_uri: Some("https://github.com/foo/bar".to_string()), source_sha256: Some("b".repeat(64)), bldopts, + meta_entries: Vec::new(), } } From e71431f12d76b56386eb1a0fd2a0d7e8956c6100 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Thu, 9 Jul 2026 18:55:08 -0300 Subject: [PATCH 30/33] Skip source metadata when verifying a contract. --- .../src/commands/contract/verify.rs | 242 +++++++++++++----- 1 file changed, 182 insertions(+), 60 deletions(-) diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index 90b23b0ddc..c7218439db 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -1,12 +1,11 @@ use std::collections::HashSet; -use std::io::{IsTerminal, Write}; +use std::io::{Cursor, IsTerminal, Write}; use std::path::{Path, PathBuf}; use clap::Parser; use regex::Regex; use sha2::{Digest, Sha256}; -use soroban_spec_tools::contract::Spec; -use stellar_xdr::{Hash, ScMetaEntry, ScMetaV0}; +use stellar_xdr::{Hash, Limited, Limits, ReadXdr, ScMetaEntry, ScMetaV0}; use url::Url; use walkdir::WalkDir; @@ -92,8 +91,8 @@ pub enum Error { #[error(transparent)] Wasm(#[from] wasm::Error), - #[error(transparent)] - SpecTools(#[from] soroban_spec_tools::contract::Error), + #[error("parsing the WASM's contract metadata: {0}")] + MetaParse(String), #[error("the WASM has no contractmetav0 custom section")] NoMeta, @@ -240,21 +239,29 @@ pub fn trust_decision(value: &str, kind: TrustKind, trust_flag: bool) -> TrustDe } } -/// Meta keys the rebuild regenerates on its own, so verify must not replay them -/// — re-passing one as `--meta` would write it twice and break byte-equality. -/// `cliver` is re-injected by the container's CLI; `rsver`/`rssdkver` are -/// re-embedded by the SDK when the source is recompiled. Everything else is -/// replayed verbatim (see `ExtractedMetadata::meta_entries`). +/// Best-effort list of meta keys the rebuild regenerates on its own, used only +/// as a *fallback* when verify can't localize the CLI-injected section (no +/// `cliver` marker — see `extract_metadata`). `cliver` is re-injected by the +/// container's CLI; `rsver`/`rssdkver` are re-embedded by the SDK on recompile. +/// The normal path partitions by custom section instead, which also catches +/// arbitrary source-embedded keys (e.g. a `contractmeta!` `Description`) that +/// no fixed list could enumerate. const REGENERATED_META_KEYS: &[&str] = &["cliver", "rsver", "rssdkver"]; -/// SEP-58 metadata read from a contract's `contractmetav0` section. +/// The `cliver` entry the CLI stamps into the section it injects; its presence +/// marks that section as the CLI-injected one (see `extract_metadata`). +const CLIVER_KEY: &str = "cliver"; + +/// Metadata read from a contract's `contractmetav0` custom sections (SEP-46). /// /// Verify reproduces the section by *replaying* what the WASM records rather /// than reconstructing it from `build`'s ordering rules: `meta_entries` holds -/// every recorded entry, in the exact order it appears in the WASM, so the +/// the CLI-injected entries, in the exact order the WASM records them, so the /// rebuild's metadata matches byte-for-byte no matter how (or by what tool) the -/// original was produced — including WASMs authored by hand per SEP-58. The -/// entries the rebuild regenerates itself (`REGENERATED_META_KEYS`) are excluded. +/// original was produced. The entries the rebuild regenerates itself — the +/// SDK/compile-emitted section (`rsver`, `rssdkver`, and any `contractmeta!` +/// keys such as `Description`) and the CLI's own `cliver` — are excluded, so +/// they aren't written twice. /// /// The typed fields (`bldimg`, `source_uri`, `source_sha256`, `bldopts`) are /// pulled out of the same entries only to *drive* the rebuild — pick the image, @@ -462,29 +469,92 @@ impl Cmd { } } -/// Walk the WASM's `contractmetav0` entries. Every entry is captured, in order, -/// into `meta_entries` for verbatim replay — except the keys the rebuild -/// regenerates itself (`REGENERATED_META_KEYS`). The SEP-58 fields that drive -/// the rebuild are pulled out of the same walk. Errors when `bldimg` or -/// `source_sha256` is absent, since neither has a sensible default; `source_uri` -/// is optional. +/// Read the WASM's `contractmetav0` custom sections *separately*, preserving +/// both the per-section grouping and the entry order within each. `Spec::meta` +/// concatenates every section into one flat list; keeping them apart is what +/// lets verify tell the SDK/compile-emitted metadata (its own section) from the +/// CLI-injected metadata (a separate section appended by `inject_meta`), so it +/// replays only the latter. SEP-46 permits multiple same-named sections and +/// fixes their concatenation order, so this grouping is well-defined. +fn read_meta_sections(wasm: &[u8]) -> Result>, Error> { + let mut sections = Vec::new(); + for payload in wasmparser::Parser::new(0).parse_all(wasm) { + let payload = payload.map_err(|e| Error::MetaParse(e.to_string()))?; + if let wasmparser::Payload::CustomSection(reader) = payload { + if reader.name() == "contractmetav0" { + sections.push(parse_meta_entries(reader.data())?); + } + } + } + Ok(sections) +} + +/// Decode one `contractmetav0` section's XDR into `(key, value)` pairs, in order. +fn parse_meta_entries(data: &[u8]) -> Result, Error> { + let mut read = Limited::new(Cursor::new(data), Limits::none()); + ScMetaEntry::read_xdr_iter(&mut read) + .map(|entry| { + entry.map(|ScMetaEntry::ScMetaV0(ScMetaV0 { key, val })| { + (key.to_string(), val.to_string()) + }) + }) + .collect::, _>>() + .map_err(|e| Error::MetaParse(e.to_string())) +} + +/// Read the WASM's contract metadata and split out what verify must replay from +/// what the rebuild regenerates on its own. +/// +/// The rebuild re-creates the SDK/compile-emitted metadata (`rsver`, `rssdkver`, +/// and any `contractmeta!` keys) by recompiling the source, and the container's +/// CLI re-injects `cliver`. Replaying any of those as `--meta` would write them +/// twice and break byte-equality. `inject_meta` puts `cliver` plus the user's +/// `--meta` into its own `contractmetav0` section, so the section containing +/// `cliver` *is* the CLI-injected set — everything verify must replay, and +/// nothing the rebuild produces for free. We therefore replay that section +/// (minus `cliver`) and ignore the rest. +/// +/// Fallback: a WASM with no `cliver` (an ancient CLI, or one authored by hand +/// per SEP-46) has no marked section to localize, so we replay every entry +/// except the keys we know are regenerated (`REGENERATED_META_KEYS`). +/// +/// Errors when `bldimg` or `source_sha256` is absent, since neither has a +/// sensible default; `source_uri` is optional. pub fn extract_metadata(wasm: &[u8]) -> Result { - let spec = Spec::new(wasm)?; - if spec.meta.is_empty() { + let sections = read_meta_sections(wasm)?; + if sections.iter().all(Vec::is_empty) { return Err(Error::NoMeta); } + // The CLI-injected section is the one carrying `cliver`; replay it minus + // `cliver`. Absent that marker, fall back to a key-name filter over every + // section. + let cli_section = sections + .iter() + .position(|s| s.iter().any(|(k, _)| k == CLIVER_KEY)); + let meta_entries: Vec<(String, String)> = match cli_section { + Some(i) => sections[i] + .iter() + .filter(|(k, _)| k != CLIVER_KEY) + .cloned() + .collect(), + None => sections + .into_iter() + .flatten() + .filter(|(k, _)| !REGENERATED_META_KEYS.contains(&k.as_str())) + .collect(), + }; + let mut bldimg: Option = None; let mut source_uri: Option = None; let mut source_sha256: Option = None; let mut bldopts: Vec = Vec::new(); - let mut meta_entries: Vec<(String, String)> = Vec::new(); - // Each of these SEP-58 fields must appear at most once. Reject duplicates - // rather than silently taking the last: two `bldimg` entries (say a benign - // one to fool inspection and a second the cli would actually trust and - // rebuild in) would be a verification-bypass vector, and the same ambiguity - // applies to the `source_uri`/`source_sha256` that pin what gets rebuilt. + // Each of these fields must appear at most once. Reject duplicates rather + // than silently taking the last: two `bldimg` entries (say a benign one to + // fool inspection and a second the cli would actually trust and rebuild in) + // would be a verification-bypass vector, and the same ambiguity applies to + // the `source_uri`/`source_sha256` that pin what gets rebuilt. let set_once = |slot: &mut Option, field: &'static str, v: String| -> Result<(), Error> { if slot.is_some() { @@ -494,27 +564,14 @@ pub fn extract_metadata(wasm: &[u8]) -> Result { Ok(()) }; - for entry in &spec.meta { - let ScMetaEntry::ScMetaV0(ScMetaV0 { key, val }) = entry; - let k = key.to_string(); - let v = val.to_string(); - - // Entries the rebuild re-creates on its own are never replayed; passing - // them as `--meta` would duplicate them and break byte-equality. - if REGENERATED_META_KEYS.contains(&k.as_str()) { - continue; - } - - // Record every other entry verbatim, in order, to replay as `--meta`. - // The typed fields below are additionally pulled out to drive the - // rebuild, but the replayed metadata always comes from `meta_entries`. - meta_entries.push((k.clone(), v.clone())); - + // The typed fields are pulled out of the very entries we replay, so the + // rebuild is driven by exactly the metadata that gets re-recorded. + for (k, v) in &meta_entries { match k.as_str() { - "bldimg" => set_once(&mut bldimg, "bldimg", v)?, - "source_uri" => set_once(&mut source_uri, "source_uri", v)?, - "source_sha256" => set_once(&mut source_sha256, "source_sha256", v)?, - "bldopt" => bldopts.push(v), + "bldimg" => set_once(&mut bldimg, "bldimg", v.clone())?, + "source_uri" => set_once(&mut source_uri, "source_uri", v.clone())?, + "source_sha256" => set_once(&mut source_sha256, "source_sha256", v.clone())?, + "bldopt" => bldopts.push(v.clone()), _ => {} // user meta: carried in meta_entries for replay } } @@ -921,9 +978,18 @@ mod tests { use stellar_xdr::{Limited, Limits, ScMetaEntry, ScMetaV0, WriteXdr}; fn make_wasm_with_meta(entries: &[(&str, &str)]) -> Vec { - let xdr = encode_meta(entries); + make_wasm_with_sections(&[entries]) + } + + /// Build a WASM with one `contractmetav0` custom section per slice, in order + /// — mirroring how the SDK/compile step and the CLI's `inject_meta` each + /// append their own section. + fn make_wasm_with_sections(sections: &[&[(&str, &str)]]) -> Vec { let mut wasm = empty_wasm_module(); - wasm_gen::write_custom_section(&mut wasm, "contractmetav0", &xdr); + for entries in sections { + let xdr = encode_meta(entries); + wasm_gen::write_custom_section(&mut wasm, "contractmetav0", &xdr); + } wasm } @@ -1041,32 +1107,88 @@ mod tests { } #[test] - fn extract_metadata_captures_user_meta_and_drops_regenerated_keys() { + fn extract_metadata_replays_only_cli_section() { + // Real layout: the SDK/compile step emits its own section (a + // `contractmeta!` `Description`, plus rsver/rssdkver), then the CLI + // appends a second section holding cliver + the user `--meta`. Verify + // must replay only the CLI section (minus cliver); the source-embedded + // section is regenerated by recompiling, so replaying it would duplicate + // those entries and break byte-equality (the bug this fixes). + let wasm = make_wasm_with_sections(&[ + // SDK / compile-emitted section. + &[ + ("Description", "A hello world contract"), + ("key1", "val1"), + ("key2", "val2"), + ("rsver", "1.96.0"), + ("rssdkver", "26.1.0#abcdef"), + ], + // CLI-injected section. + &[ + ("cliver", "27.0.0#abcdef"), + ("bldimg", &good_bldimg()), + ("source_sha256", &"b".repeat(64)), + ("bldopt", "--locked"), + ("home_domain", "fnando.com"), + ], + ]); + let meta = extract_metadata(&wasm).unwrap(); + assert_eq!(meta.bldopts, vec!["--locked".to_string()]); + // Only the CLI section is replayed, in order, with cliver stripped. + // Nothing from the source-embedded section leaks in. + assert_eq!( + meta.meta_entries, + vec![ + ("bldimg".to_string(), good_bldimg()), + ("source_sha256".to_string(), "b".repeat(64)), + ("bldopt".to_string(), "--locked".to_string()), + ("home_domain".to_string(), "fnando.com".to_string()), + ] + ); + } + + #[test] + fn extract_metadata_fallback_filters_regenerated_keys_without_cliver() { + // No cliver anywhere (ancient CLI or hand-authored per SEP-46): there's + // no marked section to localize, so replay everything except the keys we + // know the rebuild regenerates. let wasm = make_wasm_with_meta(&[ + ("rsver", "1.96.0"), + ("rssdkver", "26.1.0#abcdef"), ("bldimg", &good_bldimg()), ("source_sha256", &"b".repeat(64)), - ("cliver", "26.0.0#abcdef"), - ("rsver", "1.93.0"), - ("rssdkver", "23.0.0"), ("home_domain", "fnando.com"), - ("author", "alice"), ]); let meta = extract_metadata(&wasm).unwrap(); - // User meta is not a bldopt or source-id, but it IS captured for replay. - assert!(meta.bldopts.is_empty()); - // The rebuild regenerates cliver/rsver/rssdkver, so they're excluded; - // every other entry is captured verbatim, in order, for replay. assert_eq!( meta.meta_entries, vec![ ("bldimg".to_string(), good_bldimg()), ("source_sha256".to_string(), "b".repeat(64)), ("home_domain".to_string(), "fnando.com".to_string()), - ("author".to_string(), "alice".to_string()), ] ); } + #[test] + fn extract_metadata_ignores_duplicate_key_in_source_embedded_section() { + // A `contractmeta!` entry that happens to reuse a reserved key (here a + // second `bldimg`) lives in the source-embedded section, which verify + // ignores — so it neither trips duplicate-rejection nor overrides the + // real, CLI-recorded bldimg used to drive (and trust-check) the rebuild. + let evil = format!("docker.io/attacker/evil@sha256:{}", "e".repeat(64)); + let wasm = make_wasm_with_sections(&[ + &[("bldimg", &evil), ("rsver", "1.96.0")], + &[ + ("cliver", "27.0.0#abcdef"), + ("bldimg", &good_bldimg()), + ("source_sha256", &"b".repeat(64)), + ], + ]); + let meta = extract_metadata(&wasm).unwrap(); + assert_eq!(meta.bldimg, good_bldimg()); + } + #[test] fn extract_metadata_empty_meta_errors() { let wasm = empty_wasm_module(); // no contractmetav0 section From da0b601dbca8f2493960193a954a0e549311bcb7 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Thu, 9 Jul 2026 19:36:05 -0300 Subject: [PATCH 31/33] Fall back to the last metadata block when verifying. --- .../src/commands/contract/verify.rs | 97 +++++++++++++------ 1 file changed, 65 insertions(+), 32 deletions(-) diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index c7218439db..df531c6d6e 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -239,13 +239,14 @@ pub fn trust_decision(value: &str, kind: TrustKind, trust_flag: bool) -> TrustDe } } -/// Best-effort list of meta keys the rebuild regenerates on its own, used only -/// as a *fallback* when verify can't localize the CLI-injected section (no -/// `cliver` marker — see `extract_metadata`). `cliver` is re-injected by the -/// container's CLI; `rsver`/`rssdkver` are re-embedded by the SDK on recompile. -/// The normal path partitions by custom section instead, which also catches -/// arbitrary source-embedded keys (e.g. a `contractmeta!` `Description`) that -/// no fixed list could enumerate. +/// Meta keys the rebuild regenerates on its own, so verify must never replay +/// them — re-passing one would write it twice and break byte-equality. `cliver` +/// is re-injected by the container's CLI; `rsver`/`rssdkver` are re-embedded by +/// the SDK on recompile. The section split in `extract_metadata` already keeps +/// the SDK's own section out; this filter is applied to the chosen section as a +/// final guard (chiefly for a degenerate single-section WASM). Source-embedded +/// keys with arbitrary names (e.g. a `contractmeta!` `Description`) are handled +/// by the section split, which no fixed list could enumerate. const REGENERATED_META_KEYS: &[&str] = &["cliver", "rsver", "rssdkver"]; /// The `cliver` entry the CLI stamps into the section it injects; its presence @@ -514,9 +515,10 @@ fn parse_meta_entries(data: &[u8]) -> Result, Error> { /// nothing the rebuild produces for free. We therefore replay that section /// (minus `cliver`) and ignore the rest. /// -/// Fallback: a WASM with no `cliver` (an ancient CLI, or one authored by hand -/// per SEP-46) has no marked section to localize, so we replay every entry -/// except the keys we know are regenerated (`REGENERATED_META_KEYS`). +/// Fallback: a WASM with no `cliver` (a pre-v23.2.0 CLI never wrote one, and a +/// WASM may be hand-authored per SEP-46) has no marked section, so we take the +/// last non-empty section instead — `inject_meta` always appends after the +/// compile-emitted sections, so the CLI section is always last. /// /// Errors when `bldimg` or `source_sha256` is absent, since neither has a /// sensible default; `source_uri` is optional. @@ -526,24 +528,24 @@ pub fn extract_metadata(wasm: &[u8]) -> Result { return Err(Error::NoMeta); } - // The CLI-injected section is the one carrying `cliver`; replay it minus - // `cliver`. Absent that marker, fall back to a key-name filter over every - // section. + // Locate the CLI-injected section: the one carrying `cliver`, or — when no + // section is marked — the last non-empty one, since `inject_meta` always + // appends after the compile-emitted sections (the linker merges every + // `#[link_section = "contractmetav0"]` static — `contractmeta!` entries plus + // the SDK's `rsver`/`rssdkver` — into a single earlier section). Replay it, + // dropping the keys the rebuild regenerates itself (`REGENERATED_META_KEYS`): + // a well-formed CLI section holds none of them, but this guards a degenerate + // single-section WASM where build fields sit alongside `rsver`/`rssdkver`. let cli_section = sections .iter() - .position(|s| s.iter().any(|(k, _)| k == CLIVER_KEY)); - let meta_entries: Vec<(String, String)> = match cli_section { - Some(i) => sections[i] - .iter() - .filter(|(k, _)| k != CLIVER_KEY) - .cloned() - .collect(), - None => sections - .into_iter() - .flatten() - .filter(|(k, _)| !REGENERATED_META_KEYS.contains(&k.as_str())) - .collect(), - }; + .position(|s| s.iter().any(|(k, _)| k == CLIVER_KEY)) + .or_else(|| sections.iter().rposition(|s| !s.is_empty())) + .expect("a non-empty section exists: the all-empty case is rejected as NoMeta above"); + let meta_entries: Vec<(String, String)> = sections[cli_section] + .iter() + .filter(|(k, _)| !REGENERATED_META_KEYS.contains(&k.as_str())) + .cloned() + .collect(); let mut bldimg: Option = None; let mut source_uri: Option = None; @@ -1148,15 +1150,46 @@ mod tests { } #[test] - fn extract_metadata_fallback_filters_regenerated_keys_without_cliver() { - // No cliver anywhere (ancient CLI or hand-authored per SEP-46): there's - // no marked section to localize, so replay everything except the keys we - // know the rebuild regenerates. + fn extract_metadata_fallback_picks_last_section_without_cliver() { + // Pre-v23.2.0 (or hand-authored per SEP-46): no cliver marker anywhere. + // The build fields were added via plain --meta, so they're in the CLI- + // appended (last) section; the compile-emitted section — contractmeta! + // entries plus rsver/rssdkver — comes first and must be ignored, or its + // key1/key2 would be replayed and duplicated on rebuild. + let wasm = make_wasm_with_sections(&[ + &[ + ("key1", "val1"), + ("key2", "val2"), + ("rsver", "1.97.0"), + ("rssdkver", "22.0.11#abcdef"), + ], + &[ + ("bldimg", &good_bldimg()), + ("source_sha256", &"b".repeat(64)), + ("bldopt", "--locked"), + ], + ]); + let meta = extract_metadata(&wasm).unwrap(); + assert_eq!( + meta.meta_entries, + vec![ + ("bldimg".to_string(), good_bldimg()), + ("source_sha256".to_string(), "b".repeat(64)), + ("bldopt".to_string(), "--locked".to_string()), + ] + ); + } + + #[test] + fn extract_metadata_single_section_fallback_drops_regenerated_keys() { + // Degenerate: only one section, no cliver, build fields embedded next to + // rsver/rssdkver. The last-section fallback picks it, and the guard filter + // still strips rsver/rssdkver so they aren't replayed and duplicated. let wasm = make_wasm_with_meta(&[ - ("rsver", "1.96.0"), - ("rssdkver", "26.1.0#abcdef"), ("bldimg", &good_bldimg()), ("source_sha256", &"b".repeat(64)), + ("rsver", "1.97.0"), + ("rssdkver", "22.0.11#abcdef"), ("home_domain", "fnando.com"), ]); let meta = extract_metadata(&wasm).unwrap(); From 7027bd90f9cfe2766137f5f7eac141335f767074 Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Thu, 16 Jul 2026 11:38:27 -0300 Subject: [PATCH 32/33] Run contract verify through the docker CLI. --- Cargo.lock | 55 +++++++++++++++++++ FULL_HELP_DOCS.md | 2 +- .../src/commands/contract/verify.rs | 11 ++-- 3 files changed, 60 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 48a80191f2..8342c85a94 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2139,6 +2139,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a3d7db9596fecd151c5f638c0ee5d5bd487b6e0ea232e5dc96d5250f6f94b1d" dependencies = [ "crc32fast", + "libz-rs-sys", "miniz_oxide", ] @@ -3431,6 +3432,15 @@ dependencies = [ "redox_syscall", ] +[[package]] +name = "libz-rs-sys" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c10501e7805cee23da17c7790e59df2870c0d4043ec6d03f67d31e2b53e77415" +dependencies = [ + "zlib-rs", +] + [[package]] name = "link-cplusplus" version = "1.0.12" @@ -5303,6 +5313,12 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "similar" version = "2.7.0" @@ -5472,6 +5488,7 @@ dependencies = [ "which", "whoami", "zeroize", + "zip", ] [[package]] @@ -6723,6 +6740,12 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "typed-path" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" + [[package]] name = "typenum" version = "1.18.0" @@ -8053,12 +8076,44 @@ dependencies = [ "syn 2.0.118", ] +[[package]] +name = "zip" +version = "8.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b" +dependencies = [ + "crc32fast", + "flate2", + "indexmap 2.11.0", + "memchr", + "typed-path", + "zopfli", +] + +[[package]] +name = "zlib-rs" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40990edd51aae2c2b6907af74ffb635029d5788228222c4bb811e9351c0caad3" + [[package]] name = "zmij" version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" +[[package]] +name = "zopfli" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] + [[package]] name = "zvariant" version = "4.2.0" diff --git a/FULL_HELP_DOCS.md b/FULL_HELP_DOCS.md index facb71bb91..ae4df36e9c 100644 --- a/FULL_HELP_DOCS.md +++ b/FULL_HELP_DOCS.md @@ -1168,7 +1168,7 @@ Verify that a contract's WASM reproduces from the build metadata it records, per - `--wasm ` — Local WASM file to verify, instead of fetching from the network - `--wasm-hash ` — WASM hash (hex) to fetch the WASM from the network - `--source-uri ` — Local source code file or http(s) URL to use as the source when the WASM's recorded SEP-58 metadata has only `source_sha256` (no `source_uri`). Accepts http(s) URLs or local file paths -- `--trust` — Bypass interactive confirmation when the WASM's bldimg is not in the default trust list, or when the source is a tarball (tarballs are never default-trusted) +- `--trust` — Bypass interactive confirmation when the WASM's bldimg is not in the default trust list, or when the source is provided as an archive (source archives are never default-trusted) - `-d`, `--docker-host ` — Override the default docker host used by the rebuild - `--keep` — Keep the materialized source and rebuild output instead of deleting them on exit, and print the path. Useful for debugging a byte mismatch (e.g. diffing the rebuilt WASM's metadata against the original) diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index df531c6d6e..9dab25128a 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -157,9 +157,6 @@ pub enum Error { #[error(transparent)] Verifiable(#[from] verifiable::Error), - #[error(transparent)] - Bollard(#[from] bollard::errors::Error), - #[error(transparent)] DockerConnection(#[from] container::shared::Error), @@ -365,12 +362,12 @@ impl Cmd { global_args: &global::Args, print: &Print, ) -> Result<(), Error> { - // Rebuild in the recorded bldimg. - let docker_args = container::shared::Args { + // Rebuild in the recorded bldimg. Every docker interaction shells out to + // the `docker` CLI through this `Args` (honoring `--docker-host`). + let docker = container::shared::Args { docker_host: self.docker_host.clone(), }; - let docker = docker_args.connect_to_docker(print).await?; - verifiable::pull_image(&docker, &meta.bldimg, print).await?; + docker.pull_image(&meta.bldimg, print).await?; // `--locked` was only added to `contract build` in cli 25.2.0. The // recorded bldimg may be older (and still valid), so probe it before From 3f9425880c0bbad6c454c75431cd55357b783dec Mon Sep 17 00:00:00 2001 From: Nando Vieira Date: Thu, 16 Jul 2026 21:42:41 -0300 Subject: [PATCH 33/33] Support other container engines in contract verify. --- FULL_HELP_DOCS.md | 78 ++++++++++++++++++- .../src/commands/contract/verify.rs | 28 ++++--- 2 files changed, 90 insertions(+), 16 deletions(-) diff --git a/FULL_HELP_DOCS.md b/FULL_HELP_DOCS.md index ae4df36e9c..916529a10b 100644 --- a/FULL_HELP_DOCS.md +++ b/FULL_HELP_DOCS.md @@ -369,6 +369,18 @@ To view the commands that will be executed, without executing them, use the --pr **Usage:** `stellar contract build [OPTIONS]` +###### **Container Options:** + +- `-d`, `--docker-host ` — Optional argument to override the default docker host. This is useful when you are using a non-standard docker host path for your Docker-compatible container runtime, e.g. Docker Desktop defaults to $HOME/.docker/run/docker.sock instead of /var/run/docker.sock +- `--engine ` — Container engine to use [default: docker] + + Possible values: + - `docker`: Docker, or any Docker-compatible CLI + - `apple-container`: Apple's `container` CLI (macOS 26+, Apple silicon) + +- `--cpus ` — Limit the number of CPUs available to the container, e.g. `2`. A whole number: Apple's `container` engine does not accept fractional CPUs +- `--memory ` — Limit the memory available to the container, e.g. `2g` or `512m` + ###### **Features:** - `--features ` — Build with the list of features activated, space or comma separated @@ -408,13 +420,12 @@ To view the commands that will be executed, without executing them, use the --pr - `--print-commands-only` — Print commands to build without executing them -###### **Verifiable:** +###### **Verifiable Options:** - `--verifiable` — Build inside a trusted Docker container and record SEP-58 metadata (`bldimg`, `source_uri`, `source_sha256`, `bldopt`) so the resulting WASM can be reproduced and verified by third parties. Implies `--locked`. Requires a clean git working tree - `--image ` — Override the auto-selected container image used by `--verifiable`. Must be digest-pinned, e.g. `docker.io/stellar/stellar-cli@sha256:...`. Tag-only refs are rejected because SEP-58 requires content addressing - `--source-sha256 ` — SEP-58 source identification: SHA-256 of the source archive (recorded as the `source_sha256` meta entry). Optional with `--verifiable`: the archive is always generated and its SHA-256 computed for you. When supplied it's treated as a pin — the build fails if it doesn't match the generated archive -- `--source-uri ` — SEP-58 source identification: URI where the source can be obtained, e.g. `https://example.com/src.tar.gz` (recorded as the `source_uri` meta entry). Optional with `--verifiable`; the recorded `source_sha256` is computed from the generated archive, unless `--source-sha256` is explicitly set -- `-d`, `--docker-host ` — Override the default docker host used by `--verifiable` +- `--source-uri ` — entry). Optional with `--verifiable`; the recorded `source_sha256` is computed from the generated archive, unless `--source-sha256` is explicitly set ## `stellar contract extend` @@ -1158,6 +1169,18 @@ Verify that a contract's WASM reproduces from the build metadata it records, per **Usage:** `stellar contract verify [OPTIONS]` +###### **Container Options:** + +- `-d`, `--docker-host ` — Optional argument to override the default docker host. This is useful when you are using a non-standard docker host path for your Docker-compatible container runtime, e.g. Docker Desktop defaults to $HOME/.docker/run/docker.sock instead of /var/run/docker.sock +- `--engine ` — Container engine to use [default: docker] + + Possible values: + - `docker`: Docker, or any Docker-compatible CLI + - `apple-container`: Apple's `container` CLI (macOS 26+, Apple silicon) + +- `--cpus ` — Limit the number of CPUs available to the container, e.g. `2`. A whole number: Apple's `container` engine does not accept fractional CPUs +- `--memory ` — Limit the memory available to the container, e.g. `2g` or `512m` + ###### **Global Options:** - `--config-dir ` — Location of config directory. By default, it uses `$XDG_CONFIG_HOME/stellar` if set, falling back to `~/.config/stellar` otherwise. Contains configuration files, aliases, and other persistent settings @@ -1169,7 +1192,6 @@ Verify that a contract's WASM reproduces from the build metadata it records, per - `--wasm-hash ` — WASM hash (hex) to fetch the WASM from the network - `--source-uri ` — Local source code file or http(s) URL to use as the source when the WASM's recorded SEP-58 metadata has only `source_sha256` (no `source_uri`). Accepts http(s) URLs or local file paths - `--trust` — Bypass interactive confirmation when the WASM's bldimg is not in the default trust list, or when the source is provided as an archive (source archives are never default-trusted) -- `-d`, `--docker-host ` — Override the default docker host used by the rebuild - `--keep` — Keep the materialized source and rebuild output instead of deleting them on exit, and print the path. Useful for debugging a byte mismatch (e.g. diffing the rebuilt WASM's metadata against the original) ###### **RPC Options:** @@ -1712,6 +1734,8 @@ Start local networks in containers - `logs` — Get logs from a running network container - `start` — Start a container running a Stellar node, RPC, API, and friendbot (faucet) - `stop` — Stop a network container started with `stellar container start` +- `use` — Set the default container engine used by `stellar container` commands +- `unset` — Unset the default container engine defined previously with `container use ` ## `stellar container logs` @@ -1728,6 +1752,11 @@ Get logs from a running network container ###### **Options:** - `-d`, `--docker-host ` — Optional argument to override the default docker host. This is useful when you are using a non-standard docker host path for your Docker-compatible container runtime, e.g. Docker Desktop defaults to $HOME/.docker/run/docker.sock instead of /var/run/docker.sock +- `--engine ` — Container engine to use [default: docker] + + Possible values: + - `docker`: Docker, or any Docker-compatible CLI + - `apple-container`: Apple's `container` CLI (macOS 26+, Apple silicon) ## `stellar container start` @@ -1750,6 +1779,14 @@ By default, when starting a testnet container, without any optional arguments, i ###### **Options:** - `-d`, `--docker-host ` — Optional argument to override the default docker host. This is useful when you are using a non-standard docker host path for your Docker-compatible container runtime, e.g. Docker Desktop defaults to $HOME/.docker/run/docker.sock instead of /var/run/docker.sock +- `--engine ` — Container engine to use [default: docker] + + Possible values: + - `docker`: Docker, or any Docker-compatible CLI + - `apple-container`: Apple's `container` CLI (macOS 26+, Apple silicon) + +- `--cpus ` — Limit the number of CPUs available to the container, e.g. `2`. A whole number: Apple's `container` engine does not accept fractional CPUs +- `--memory ` — Limit the memory available to the container, e.g. `2g` or `512m` - `--name ` — Optional argument to specify the container name - `-l`, `--limits ` — Optional argument to specify the limits for the local network only - `-p`, `--ports-mapping ` — Argument to specify the `HOST_PORT:CONTAINER_PORT` mapping @@ -1774,6 +1811,39 @@ Stop a network container started with `stellar container start` ###### **Options:** - `-d`, `--docker-host ` — Optional argument to override the default docker host. This is useful when you are using a non-standard docker host path for your Docker-compatible container runtime, e.g. Docker Desktop defaults to $HOME/.docker/run/docker.sock instead of /var/run/docker.sock +- `--engine ` — Container engine to use [default: docker] + + Possible values: + - `docker`: Docker, or any Docker-compatible CLI + - `apple-container`: Apple's `container` CLI (macOS 26+, Apple silicon) + +## `stellar container use` + +Set the default container engine used by `stellar container` commands + +**Usage:** `stellar container use [OPTIONS] ` + +###### **Arguments:** + +- `` — Container engine to use by default + + Possible values: + - `docker`: Docker, or any Docker-compatible CLI + - `apple-container`: Apple's `container` CLI (macOS 26+, Apple silicon) + +###### **Global Options:** + +- `--config-dir ` — Location of config directory. By default, it uses `$XDG_CONFIG_HOME/stellar` if set, falling back to `~/.config/stellar` otherwise. Contains configuration files, aliases, and other persistent settings + +## `stellar container unset` + +Unset the default container engine defined previously with `container use ` + +**Usage:** `stellar container unset [OPTIONS]` + +###### **Global Options:** + +- `--config-dir ` — Location of config directory. By default, it uses `$XDG_CONFIG_HOME/stellar` if set, falling back to `~/.config/stellar` otherwise. Contains configuration files, aliases, and other persistent settings ## `stellar config` diff --git a/cmd/soroban-cli/src/commands/contract/verify.rs b/cmd/soroban-cli/src/commands/contract/verify.rs index 9dab25128a..7baf74bee0 100644 --- a/cmd/soroban-cli/src/commands/contract/verify.rs +++ b/cmd/soroban-cli/src/commands/contract/verify.rs @@ -11,12 +11,12 @@ use walkdir::WalkDir; use crate::{ commands::{ - container, + container::shared::{self, Args as ContainerArgs, RunArgs as ContainerRunArgs}, contract::build::{ source_archive, verifiable::{self, bldimg_regex, source_sha256_regex, source_uri_regex}, }, - global, + global, HEADING_CONTAINER, }, config::{self, locator, network}, print::Print, @@ -54,10 +54,6 @@ pub struct Cmd { #[arg(long)] pub trust: bool, - /// Override the default docker host used by the rebuild. - #[arg(short = 'd', long, env = "DOCKER_HOST")] - pub docker_host: Option, - /// Keep the materialized source and rebuild output instead of deleting them /// on exit, and print the path. Useful for debugging a byte mismatch (e.g. /// diffing the rebuilt WASM's metadata against the original). @@ -69,6 +65,12 @@ pub struct Cmd { #[command(flatten)] pub network: network::Args, + + #[command(flatten, next_help_heading = HEADING_CONTAINER)] + pub container_args: ContainerArgs, + + #[command(flatten, next_help_heading = HEADING_CONTAINER)] + pub run_args: ContainerRunArgs, } #[derive(thiserror::Error, Debug)] @@ -158,7 +160,7 @@ pub enum Error { Verifiable(#[from] verifiable::Error), #[error(transparent)] - DockerConnection(#[from] container::shared::Error), + DockerConnection(#[from] shared::Error), #[error("could not find a rebuilt WASM under {target}")] NoRebuiltWasm { target: PathBuf }, @@ -362,11 +364,12 @@ impl Cmd { global_args: &global::Args, print: &Print, ) -> Result<(), Error> { - // Rebuild in the recorded bldimg. Every docker interaction shells out to - // the `docker` CLI through this `Args` (honoring `--docker-host`). - let docker = container::shared::Args { - docker_host: self.docker_host.clone(), - }; + // Rebuild in the recorded bldimg. Every interaction shells out through + // these `container_args`, which select the engine binary (`--engine`/ + // `STELLAR_CONTAINER_ENGINE`, default docker) and honor `--docker-host` + // where the engine supports it. + let docker = self.container_args.clone(); + docker.warn_if_host_ignored(print); docker.pull_image(&meta.bldimg, print).await?; // `--locked` was only added to `contract build` in cli 25.2.0. The @@ -400,6 +403,7 @@ impl Cmd { &[container_cmd], &env, &docker, + &self.run_args, print, global_args.verbose || global_args.very_verbose, )