use std::path::Path;
use sha2::{Digest, Sha256};
use crate::config::ShunConfig;
use crate::payload::ArchivePayload;
pub const EVERGREEN_PREFIX: &str = "webview2";
const EVERGREEN_INSTALLER_STEM: &str = "microsoftedgewebview2runtimeinstaller";
pub fn evergreen_carried(payload: &ArchivePayload) -> bool {
evergreen_entry(payload).is_some()
}
fn evergreen_entry(payload: &ArchivePayload) -> Option<std::path::PathBuf> {
payload
.entries()
.iter()
.map(|entry| &entry.path)
.find(|path| {
path.starts_with(Path::new(EVERGREEN_PREFIX))
&& path.file_name().is_some_and(|name| {
name.to_string_lossy()
.to_lowercase()
.starts_with(EVERGREEN_INSTALLER_STEM)
})
&& path
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("exe"))
})
.cloned()
}
pub fn evergreen_cache(product: &str) -> Option<std::path::PathBuf> {
std::env::var_os("LOCALAPPDATA")
.map(std::path::PathBuf::from)
.map(|local| local.join("shun").join(product).join("webview2"))
}
pub fn stage_evergreen(payload: &ArchivePayload, cache: &Path) -> Option<std::path::PathBuf> {
stage_evergreen_with_progress(payload, cache, &mut |_| {})
}
pub fn stage_evergreen_with_progress(
payload: &ArchivePayload,
cache: &Path,
on_percent: &mut dyn FnMut(u8),
) -> Option<std::path::PathBuf> {
let entry = evergreen_entry(payload)?;
let mut sink = |event: crate::flow::FlowEvent| {
if let crate::flow::FlowEvent::Progress {
percent: Some(percent),
..
} = event
{
on_percent(percent);
}
};
if payload
.extract_prefix(cache, Path::new(EVERGREEN_PREFIX), &mut sink)
.is_err()
{
return None;
}
let staged = cache.join(&entry);
staged.is_file().then_some(staged)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EvergreenSource {
Carried(std::path::PathBuf),
Download(String),
None,
}
pub fn evergreen_source(config: &ShunConfig, payload: &ArchivePayload) -> EvergreenSource {
if let Some(entry) = evergreen_entry(payload) {
return EvergreenSource::Carried(entry);
}
if config.webview2_silent_install() {
if let Some(url) = config.webview2_download_url() {
return EvergreenSource::Download(url.to_string());
}
}
EvergreenSource::None
}
const EVERGREEN_PERMALINK_SHA256: &[(&str, &str)] = &[
(
"https://go.microsoft.com/fwlink/?linkid=2124703",
"cf2f2445fef0c5c14e372045f84998771eeb8bb01d59be4afd00692fa160082e",
),
(
"https://go.microsoft.com/fwlink/?linkid=2124701",
"d3cbe8fedb104282d745fff106993efead51ae94f5595a4e75804446a974f9c3",
),
];
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EvergreenDigestError {
Unpinned {
url: String,
},
EmptyPin,
MalformedPin {
pinned: String,
},
Mismatch {
expected: String,
actual: String,
},
Unreadable {
path: String,
detail: String,
},
}
impl std::fmt::Display for EvergreenDigestError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Unpinned { url } => write!(
f,
"no sha256 pin covers the Evergreen download URL {url} — declare \
`download-sha256` in the manifest (an unverified download never runs)"
),
Self::EmptyPin => write!(
f,
"the Evergreen download pin is blank — nothing is trusted, nothing runs"
),
Self::MalformedPin { pinned } => write!(
f,
"the Evergreen download pin {pinned:?} is not a 64-character hex sha256"
),
Self::Mismatch { expected, actual } => write!(
f,
"the downloaded Evergreen installer does not match its pin — \
expected sha256 {expected}, got {actual}"
),
Self::Unreadable { path, detail } => write!(
f,
"could not read the staged Evergreen installer {path} for hashing: {detail}"
),
}
}
}
impl std::error::Error for EvergreenDigestError {}
fn normalize_permalink(url: &str) -> String {
let lowered = url.trim().to_lowercase();
let (base, query) = match lowered.split_once('?') {
Some((base, query)) => (base, Some(query)),
None => (lowered.as_str(), None),
};
let base = base.trim_end_matches('/');
let base = base.strip_suffix("/p").unwrap_or(base);
match query {
Some(query) => format!("{base}?{}", query.trim_end_matches('/')),
None => base.to_string(),
}
}
fn permalink_sha256(url: &str) -> Option<&'static str> {
let wanted = normalize_permalink(url);
EVERGREEN_PERMALINK_SHA256
.iter()
.find(|(permalink, _)| normalize_permalink(permalink) == wanted)
.map(|(_, digest)| *digest)
}
pub fn pinned_download_sha256<'a>(config: &'a ShunConfig, url: &str) -> Option<&'a str> {
config
.webview2_download_sha256()
.or_else(|| permalink_sha256(url))
}
fn normalize_pin(pinned: &str) -> Result<String, EvergreenDigestError> {
let trimmed = pinned.trim();
if trimmed.is_empty() {
return Err(EvergreenDigestError::EmptyPin);
}
let lowered = trimmed.to_lowercase();
let hex = lowered.strip_prefix("sha256:").unwrap_or(&lowered).trim();
if hex.len() != 64 || !hex.bytes().all(|byte| byte.is_ascii_hexdigit()) {
return Err(EvergreenDigestError::MalformedPin {
pinned: trimmed.to_string(),
});
}
Ok(hex.to_string())
}
fn hex_digest(digest: impl AsRef<[u8]>) -> String {
let bytes = digest.as_ref();
let mut hex = String::with_capacity(bytes.len() * 2);
for byte in bytes {
hex.push_str(&format!("{byte:02x}"));
}
hex
}
pub fn verify_download(bytes: &[u8], expected_hex: &str) -> Result<(), EvergreenDigestError> {
let expected = normalize_pin(expected_hex)?;
let actual = hex_digest(Sha256::digest(bytes));
if actual != expected {
return Err(EvergreenDigestError::Mismatch { expected, actual });
}
Ok(())
}
pub fn verify_download_file(path: &Path, expected_hex: &str) -> Result<(), EvergreenDigestError> {
let expected = normalize_pin(expected_hex)?;
let unreadable = |detail: String| EvergreenDigestError::Unreadable {
path: path.display().to_string(),
detail,
};
let mut file = std::fs::File::open(path).map_err(|err| unreadable(err.to_string()))?;
let mut hasher = Sha256::new();
let mut buffer = vec![0u8; 64 * 1024];
loop {
let read = std::io::Read::read(&mut file, &mut buffer)
.map_err(|err| unreadable(err.to_string()))?;
if read == 0 {
break;
}
hasher.update(&buffer[..read]);
}
let actual = hex_digest(hasher.finalize());
if actual != expected {
return Err(EvergreenDigestError::Mismatch { expected, actual });
}
Ok(())
}
pub fn check_evergreen_pin(config: &ShunConfig, url: &str) -> Result<String, EvergreenDigestError> {
let pinned =
pinned_download_sha256(config, url).ok_or_else(|| EvergreenDigestError::Unpinned {
url: url.to_string(),
})?;
normalize_pin(pinned)
}
pub fn verify_evergreen_download(
config: &ShunConfig,
url: &str,
path: &Path,
) -> Result<(), EvergreenDigestError> {
let pinned = check_evergreen_pin(config, url)?;
verify_download_file(path, &pinned)
}
#[cfg(windows)]
pub fn run_evergreen(installer: &Path, silent: bool) -> std::io::Result<std::process::ExitStatus> {
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
let mut command = std::process::Command::new(installer);
if silent {
command.args(["/silent", "/install"]);
} else {
command.arg("/install");
}
command.creation_flags(CREATE_NO_WINDOW).status()
}
#[cfg(windows)]
pub fn run_evergreen_elevated(
installer: &Path,
silent: bool,
) -> std::io::Result<std::process::ExitStatus> {
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
let args: Vec<&str> = if silent {
vec!["/silent", "/install"]
} else {
vec!["/install"]
};
let exe = installer.display().to_string().replace('\'', "''");
let script = format!(
"$p = Start-Process -FilePath '{exe}' -ArgumentList '{}' -Verb RunAs -PassThru -Wait; exit $p.ExitCode",
args.join("','")
);
std::process::Command::new("powershell")
.args(["-NoProfile", "-Command", &script])
.creation_flags(CREATE_NO_WINDOW)
.status()
}
#[cfg(not(windows))]
pub fn run_evergreen(
_installer: &Path,
_silent: bool,
) -> std::io::Result<std::process::ExitStatus> {
Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"the Evergreen installer only exists on Windows",
))
}
#[cfg(not(windows))]
pub fn run_evergreen_elevated(
_installer: &Path,
_silent: bool,
) -> std::io::Result<std::process::ExitStatus> {
Err(std::io::Error::new(
std::io::ErrorKind::Unsupported,
"the Evergreen installer only exists on Windows",
))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::payload::pack_directory;
fn packed(dir: &Path) -> ArchivePayload {
ArchivePayload::from_bytes(&pack_directory(dir).expect("packs")).expect("decodes")
}
#[test]
fn evergreen_is_found_under_the_payload_prefix() {
let dir = std::env::temp_dir().join(format!("shun-wv2-found-{}", std::process::id()));
let inner = dir.join(EVERGREEN_PREFIX);
std::fs::create_dir_all(&inner).unwrap();
std::fs::write(
inner.join("MicrosoftEdgeWebView2RuntimeInstallerX64.exe"),
b"MZ",
)
.unwrap();
let payload = packed(&dir);
let _ = std::fs::remove_dir_all(&dir);
assert!(evergreen_carried(&payload));
assert_eq!(
evergreen_entry(&payload),
Some(Path::new("webview2/MicrosoftEdgeWebView2RuntimeInstallerX64.exe").to_path_buf())
);
}
#[test]
fn evergreen_match_is_case_insensitive_but_name_gated() {
let dir = std::env::temp_dir().join(format!("shun-wv2-case-{}", std::process::id()));
let inner = dir.join(EVERGREEN_PREFIX);
std::fs::create_dir_all(&inner).unwrap();
std::fs::write(
inner.join("MICROSOFTEDGEWEBVIEW2RUNTIMEINSTALLERARM64.EXE"),
b"MZ",
)
.unwrap();
std::fs::write(inner.join("license.txt"), b"eula").unwrap();
let payload = packed(&dir);
let _ = std::fs::remove_dir_all(&dir);
assert!(evergreen_carried(&payload));
assert_eq!(
evergreen_entry(&payload)
.unwrap()
.to_string_lossy()
.to_lowercase(),
"webview2/microsoftedgewebview2runtimeinstallerarm64.exe"
);
}
#[test]
fn evergreen_outside_the_prefix_is_ignored() {
let dir = std::env::temp_dir().join(format!("shun-wv2-outside-{}", std::process::id()));
std::fs::create_dir_all(dir.join("tools")).unwrap();
std::fs::write(
dir.join("tools/MicrosoftEdgeWebView2RuntimeInstallerX64.exe"),
b"MZ",
)
.unwrap();
let payload = packed(&dir);
let _ = std::fs::remove_dir_all(&dir);
assert!(!evergreen_carried(&payload));
}
#[test]
fn evergreen_staging_extracts_the_installer() {
let dir = std::env::temp_dir().join(format!("shun-wv2-stage-{}", std::process::id()));
let inner = dir.join(EVERGREEN_PREFIX);
std::fs::create_dir_all(&inner).unwrap();
std::fs::write(
inner.join("MicrosoftEdgeWebView2RuntimeInstallerX64.exe"),
b"MZ-payload",
)
.unwrap();
let payload = packed(&dir);
let _ = std::fs::remove_dir_all(&dir);
let cache = std::env::temp_dir().join(format!("shun-wv2-cache-{}", std::process::id()));
let staged = stage_evergreen(&payload, &cache);
assert_eq!(
staged.as_deref(),
Some(
cache
.join(EVERGREEN_PREFIX)
.join("MicrosoftEdgeWebView2RuntimeInstallerX64.exe")
.as_path()
)
);
assert_eq!(
std::fs::read(staged.unwrap()).unwrap(),
b"MZ-payload".to_vec()
);
let _ = std::fs::remove_dir_all(&cache);
}
#[test]
fn staging_without_a_carried_installer_is_none() {
let dir = std::env::temp_dir().join(format!("shun-wv2-bare-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("app.exe"), b"MZ").unwrap();
let payload = packed(&dir);
let _ = std::fs::remove_dir_all(&dir);
let cache =
std::env::temp_dir().join(format!("shun-wv2-bare-cache-{}", std::process::id()));
assert_eq!(stage_evergreen(&payload, &cache), None);
assert!(!cache.join(EVERGREEN_PREFIX).exists());
}
fn evergreen_config(download_url: Option<&str>, silent_install: bool) -> ShunConfig {
evergreen_config_pinned(download_url, silent_install, None)
}
fn evergreen_config_pinned(
download_url: Option<&str>,
silent_install: bool,
download_sha256: Option<&str>,
) -> ShunConfig {
ShunConfig {
script: None,
variants: None,
product: crate::config::ProductIdentity {
name: "ShunDemo".into(),
version: "0.1.0".into(),
publisher: None,
logo: None,
},
payload: None,
webview2: Some(crate::config::Webview2Strategy::EvergreenInstaller {
silent_install: Some(silent_install),
warn_missing: None,
download_url: download_url.map(str::to_string),
download_sha256: download_sha256.map(str::to_string),
}),
targets: Vec::new(),
shell: None,
source: None,
update: None,
attachments: Vec::new(),
license_sysl: None,
license: None,
license_locales: Default::default(),
licenses: Vec::new(),
custom_steps: Vec::new(),
steps: None,
signing: None,
msix: None,
}
}
#[test]
fn carried_runtime_wins_over_the_download_url() {
let dir = std::env::temp_dir().join(format!("shun-wv2-src-carried-{}", std::process::id()));
let inner = dir.join(EVERGREEN_PREFIX);
std::fs::create_dir_all(&inner).unwrap();
std::fs::write(
inner.join("MicrosoftEdgeWebView2RuntimeInstallerX64.exe"),
b"MZ",
)
.unwrap();
let payload = packed(&dir);
let _ = std::fs::remove_dir_all(&dir);
let config = evergreen_config(
Some("https://go.microsoft.com/fwlink/?linkid=2124701"),
true,
);
assert_eq!(
evergreen_source(&config, &payload),
EvergreenSource::Carried(
Path::new("webview2/MicrosoftEdgeWebView2RuntimeInstallerX64.exe").to_path_buf()
)
);
}
#[test]
fn download_source_needs_url_and_the_silent_knob() {
let dir = std::env::temp_dir().join(format!("shun-wv2-src-dl-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("app.exe"), b"MZ").unwrap();
let payload = packed(&dir);
let _ = std::fs::remove_dir_all(&dir);
let url = "https://go.microsoft.com/fwlink/?linkid=2124701";
let config = evergreen_config(Some(url), true);
assert_eq!(
evergreen_source(&config, &payload),
EvergreenSource::Download(url.to_string())
);
let declined = evergreen_config(Some(url), false);
assert_eq!(evergreen_source(&declined, &payload), EvergreenSource::None);
let offline = evergreen_config(None, true);
assert_eq!(evergreen_source(&offline, &payload), EvergreenSource::None);
}
const TEST_BYTES_SHA256: &str =
"303cf195bd4bdded50e46dba9b36aa780e4e05c2e77a5c4e026a7421f1a9c2bd";
#[test]
fn a_download_must_match_its_pinned_sha256() {
let bytes = b"evergreen-installer-bytes";
assert_eq!(verify_download(bytes, TEST_BYTES_SHA256), Ok(()));
assert_eq!(
verify_download(bytes, &TEST_BYTES_SHA256.to_uppercase()),
Ok(())
);
assert_eq!(
verify_download(bytes, &format!("sha256:{TEST_BYTES_SHA256}")),
Ok(())
);
assert_eq!(
verify_download(
bytes,
&format!(" sha256:{} ", TEST_BYTES_SHA256.to_uppercase())
),
Ok(())
);
let other = "5cea7ca2004304231309e1e0b9d7722e42904d2e7feaf6488cf43c171ee77722";
assert_eq!(
verify_download(bytes, other),
Err(EvergreenDigestError::Mismatch {
expected: other.to_string(),
actual: TEST_BYTES_SHA256.to_string(),
})
);
let mut tampered = bytes.to_vec();
tampered.push(b'!');
assert!(matches!(
verify_download(&tampered, TEST_BYTES_SHA256),
Err(EvergreenDigestError::Mismatch { .. })
));
}
#[test]
fn an_empty_or_malformed_pin_refuses_instead_of_passing() {
let bytes = b"evergreen-installer-bytes";
assert_eq!(
verify_download(bytes, ""),
Err(EvergreenDigestError::EmptyPin)
);
assert_eq!(
verify_download(bytes, " "),
Err(EvergreenDigestError::EmptyPin)
);
for pin in [
"abc",
"zz".repeat(32).as_str(),
"0".repeat(63).as_str(),
&"0".repeat(65),
] {
let err = verify_download(bytes, pin).expect_err("must refuse");
assert!(
matches!(err, EvergreenDigestError::MalformedPin { .. }),
"unexpected error for {pin:?}: {err:?}"
);
}
let blank =
evergreen_config_pinned(Some("https://example.invalid/wv2.exe"), true, Some(" "));
assert_eq!(blank.webview2_download_sha256(), None);
assert_eq!(
pinned_download_sha256(&blank, "https://example.invalid/wv2.exe"),
None
);
}
#[test]
fn permalink_pins_cover_the_documented_fwlinks() {
let bootstrapper = "cf2f2445fef0c5c14e372045f84998771eeb8bb01d59be4afd00692fa160082e";
let standalone = "d3cbe8fedb104282d745fff106993efead51ae94f5595a4e75804446a974f9c3";
let config = evergreen_config(
Some("https://go.microsoft.com/fwlink/?linkid=2124703"),
true,
);
for url in [
"https://go.microsoft.com/fwlink/?linkid=2124703",
"https://go.microsoft.com/fwlink/p/?LinkId=2124703",
"HTTPS://go.microsoft.com/fwlink/?linkid=2124703/",
" https://go.microsoft.com/fwlink/?LinkId=2124703 ",
] {
assert_eq!(
pinned_download_sha256(&config, url),
Some(bootstrapper),
"{url}"
);
}
assert_eq!(
pinned_download_sha256(&config, "https://go.microsoft.com/fwlink/?linkid=2124701"),
Some(standalone)
);
for url in [
"https://example.invalid/MicrosoftEdgeWebview2Setup.exe",
"https://msedge.sf.dl.delivery.mp.microsoft.com/filestreamingservice/files/068be74d-a831-494f-8f57-c173756d5a33/MicrosoftEdgeWebview2Setup.exe",
] {
assert_eq!(pinned_download_sha256(&config, url), None, "{url}");
}
let override_config = evergreen_config_pinned(
Some("https://go.microsoft.com/fwlink/?linkid=2124703"),
true,
Some(TEST_BYTES_SHA256),
);
assert_eq!(
pinned_download_sha256(
&override_config,
"https://go.microsoft.com/fwlink/?linkid=2124703"
),
Some(TEST_BYTES_SHA256)
);
}
#[test]
fn the_staged_file_gate_matches_the_in_memory_one() {
let dir = std::env::temp_dir().join(format!("shun-wv2-digest-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let staged = dir.join("MicrosoftEdgeWebview2Setup.exe");
std::fs::write(&staged, b"evergreen-installer-bytes").unwrap();
assert_eq!(verify_download_file(&staged, TEST_BYTES_SHA256), Ok(()));
let other = "5cea7ca2004304231309e1e0b9d7722e42904d2e7feaf6488cf43c171ee77722";
assert_eq!(
verify_download_file(&staged, other),
Err(EvergreenDigestError::Mismatch {
expected: other.to_string(),
actual: TEST_BYTES_SHA256.to_string(),
})
);
assert_eq!(
verify_download_file(&staged, ""),
Err(EvergreenDigestError::EmptyPin)
);
assert!(matches!(
verify_download_file(&dir.join("absent.exe"), TEST_BYTES_SHA256),
Err(EvergreenDigestError::Unreadable { .. })
));
let pinned = evergreen_config_pinned(
Some("https://example.invalid/wv2.exe"),
true,
Some(TEST_BYTES_SHA256),
);
assert_eq!(
verify_evergreen_download(&pinned, "https://example.invalid/wv2.exe", &staged),
Ok(())
);
let malformed = evergreen_config_pinned(
Some("https://example.invalid/wv2.exe"),
true,
Some("not-a-digest"),
);
assert_eq!(
check_evergreen_pin(&malformed, "https://example.invalid/wv2.exe"),
Err(EvergreenDigestError::MalformedPin {
pinned: "not-a-digest".to_string(),
})
);
let unpinned = evergreen_config(Some("https://example.invalid/wv2.exe"), true);
assert_eq!(
check_evergreen_pin(&unpinned, "https://example.invalid/wv2.exe"),
Err(EvergreenDigestError::Unpinned {
url: "https://example.invalid/wv2.exe".to_string(),
})
);
assert_eq!(
verify_evergreen_download(&unpinned, "https://example.invalid/wv2.exe", &staged),
Err(EvergreenDigestError::Unpinned {
url: "https://example.invalid/wv2.exe".to_string(),
})
);
let _ = std::fs::remove_dir_all(&dir);
}
}