From 1cd27d81c06c45eacbe122209333d014f8e6efab Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 5 Nov 2026 13:25:38 -0500 Subject: [PATCH 1/8] fix(browser): make Linux setup opt-in (#90) Add elastos setup --browser for signed host helpers, confirmed administrator setup and verified image preparation. Default Linux install/setup leave Browser preparation to that choice; Marketplace and Browser explain the command. Preserve Apple Silicon setup and move retired pool cleanup to explicit opt-in. Deepen notes: gate every preparation entry path; start at 577bb01d7 install.sh:1117, setup/browser_config.rs:359 and api/gateway_browser_engine.rs:32; use fake Linux/process fixtures and existing signed admission; pinned installer/UI regressions fail before and current installer/behavior checks pass. Opus development/adversarial PASS covers tree d02f1da389ebd16270472ac439d1a985201ddab8. Checks: installer 97 (4 optional publisher-fixture skips), product-data tests 105, behavior 2181, source gate, both fmt checks and server all-target Clippy PASS. Focused Browser Rust tests pending a serial retry after the disk guard stopped parallel compilation before tests ran. No push. --- capsules/browser/browser/browser-status.js | 3 + .../browser/browser/browser-status.test.mjs | 14 + docs/BROWSER_VM_TARGET.md | 25 +- docs/INSTALL.md | 40 ++- elastos/CHANGELOG.md | 1 + .../elastos-server/src/api/gateway_browser.rs | 18 ++ .../api/gateway_capsule_catalog/read_model.rs | 38 ++- elastos/crates/elastos-server/src/main.rs | 28 ++ elastos/crates/elastos-server/src/setup.rs | 7 + .../src/setup/browser_config.rs | 100 +++++- .../elastos-server/src/setup/browser_linux.rs | 306 ++++++++++++++++++ scripts/install-bootstrap-test.py | 206 +++--------- scripts/install.sh | 89 +---- 13 files changed, 593 insertions(+), 282 deletions(-) create mode 100644 elastos/crates/elastos-server/src/setup/browser_linux.rs diff --git a/capsules/browser/browser/browser-status.js b/capsules/browser/browser/browser-status.js index 599393c62..7e705b545 100644 --- a/capsules/browser/browser/browser-status.js +++ b/capsules/browser/browser/browser-status.js @@ -71,6 +71,9 @@ export function friendlyOpenError(error) { : "This browser cannot show the Browser session. Use a supported browser or enable WebRTC."; } if (outcome?.state === "terminal_pre_effect_failure" && error?.payload?.stage === "engine_readiness") { + if (error?.payload?.code === "browser_host_setup_required") { + return sanitizedErrorText({ message: error.payload.message || text }); + } switch (error?.payload?.reason) { case "artifact_invalid": return "Browser Engine files need repair. Prepare this Engine or choose another approved Engine."; diff --git a/capsules/browser/browser/browser-status.test.mjs b/capsules/browser/browser/browser-status.test.mjs index 75f12c1ae..f7c0dc101 100644 --- a/capsules/browser/browser/browser-status.test.mjs +++ b/capsules/browser/browser/browser-status.test.mjs @@ -260,6 +260,20 @@ test("readiness failures explain the repair while cleanup retains priority", () } }); +test("Linux host setup guidance names the opt-in command", () => { + const error = openError("terminal_pre_effect_failure"); + Object.assign(error.payload, { + stage: "engine_readiness", + code: "browser_host_setup_required", + message: "Browser is available on this computer. To turn it on, run: elastos setup --browser", + }); + assert.equal(friendlyOpenError(error), error.payload.message); + error.payload.message = "Browser needs KVM on this computer. After KVM is available, run: elastos setup --browser"; + assert.equal(friendlyOpenError(error), error.payload.message); + error.payload.outcome.state = "cleanup_pending"; + assert.doesNotMatch(friendlyOpenError(error), /elastos setup --browser/); +}); + test("one-page capacity refusal says only one Browser window can be open", () => { for (const state of ["terminal_pre_effect_failure", "terminal_post_effect_cleanup"]) { const error = openError(state); diff --git a/docs/BROWSER_VM_TARGET.md b/docs/BROWSER_VM_TARGET.md index 78be3a9e8..1f00ea97e 100644 --- a/docs/BROWSER_VM_TARGET.md +++ b/docs/BROWSER_VM_TARGET.md @@ -481,22 +481,32 @@ guest and viewer allocations meet; loopback, private ranges and every other peer are denied, and TCP relays are off. coturn checks peer IPs only, so the relay output rule above confines relayed UDP to the TURN ports; host services on the slot IP stay unreachable. `check` refuses a receipt without that rule. -`elastos setup` writes the Home's TURN credential to the +`elastos setup --browser` writes the Linux Home's TURN credential to the owner-only `$DATA_DIR/runtime-turn/turn-credentials.env` and keeps an existing one. -For removal, use the same root shell and helper: +The Linux installer leaves Browser host access and its image to the Home owner. +On a supported Linux ARM64 host with KVM, run `elastos setup --browser` from a +terminal. This command admits the signed helpers, runs the one-time administrator +setup above, checks host access, then downloads and verifies the image with +progress. The administrator helper shows its changes and asks for confirmation. +Ordinary `elastos setup` leaves the Linux Browser image untouched. Close Home +and start it again after enabling Browser. Browser open explains this command +on an unprepared host; after setup it prepares a missing image on demand. +Apple Silicon setup keeps its existing Browser preparation behavior. + +For removal, close Browser and run this as the Home user before uninstalling: ```sh -python3 /usr/local/lib/elastos/browser-vm-linux-network.py remove --user +sudo /usr/bin/python3 -I /usr/local/lib/elastos/browser-vm-linux-network.py remove --user "$(id -un)" ``` After confirmation, removal deletes this account's TAPs, filter hooks/chains, boot service, udev rule, locks and receipts. It restores the prior named KVM ACL, or removes the grant created by setup. The shared root helper is removed when the last account's setup is removed. Other host firewall rules stay with -their owner. `install.sh` integration is a separate change; the installer can -call the exact setup command above as its approved root step. +their owner. Runtime and the installer leave these administrator operations +to the explicit Browser setup and removal commands. ### Linux operator proof @@ -560,8 +570,9 @@ generator/stager for: - verified links to an existing rootfs, kernel, initrd and matching build manifest Linux uses the native supervisor and a disposable qcow2 overlay for each -launch. The installer removes the retired `browser-vm/rootfs-pool` image copies -as their ordinary owner and reports the removed path. +launch. Linux Browser preparation belongs to `elastos setup --browser`. +That command removes retired `browser-vm/rootfs-pool` image copies as their +ordinary owner before preparing Browser. For already-provisioned targets, `scripts/browser-vm-target-refresh.sh` is the host-helper maintenance path. Guest drift requires a rebuilt image set. Runtime diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 5a7a7632f..ebbf044ef 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -87,7 +87,9 @@ stop after bootstrap. The current default Home exposes Assistant, Chat (Community), System, People, Wallet, Documents, Library, Marketplace, and Inbox. On Apple Silicon -Macs it also exposes Browser; Linux Homes do not show Browser in 2.0.0. People is installed as a +Macs it also exposes Browser. On supported Linux ARM64 computers with KVM, +Browser is optional; see [Jetson](#jetson) for `elastos setup --browser`. +People is installed as a separate app capsule; Home presents it but does not own its state or authority. Native Windows is not an accepted install target today. The current product @@ -173,20 +175,24 @@ The installer detects Linux `aarch64`: curl -fsSL https://elastos.elacitylabs.com/install.sh | bash ``` -Home and chat use the ordinary user account. Browser runs on Apple Silicon Macs -and uses the local Engine's virtual machine. When the signed release supplies -Browser support, setup obtains its matching helpers and verified image before -Home starts. The image streams to disk with progress; a transfer stops after 30 -seconds without data. Runtime keeps the committed Browser profile separate from -the image during reopen and updates. - -On other computers, including Linux ARM64 (Jetson) and Linux x86-64, Browser is -hidden until the next release; setup prints "Browser is not available on this -computer yet." Setup also clears the Browser Engine selection and removes the -Browser host helpers and image an earlier release installed (Browser profiles -stay). The installer runs its Linux host step only after setup and only if the -helper is still present, so it asks for no administrator step. If an earlier -release set up Browser host access on Linux, it can be removed with: +Home and chat use the ordinary user account. Browser uses the local Engine's +virtual machine on Apple Silicon Macs and supported Linux ARM64 hosts with KVM. +On Linux, Marketplace lists Browser with its setup command. To turn it on, run +`elastos setup --browser` in a terminal as the user who installed Home. The +command installs the signed Browser helpers, shows the host access changes and +asks for administrator approval. It then downloads and verifies the image with +progress. Close Home and start it again with `elastos home --browser`. + +The Linux installer and ordinary `elastos setup` leave this download to your +choice. Opening Browser on an unprepared Linux host explains the command. +After setup, a later open prepares a missing image on demand. Apple Silicon +setup continues to prepare its helpers and image before Home starts. The image +streams to disk with progress; a transfer stops after 30 seconds without data. +Runtime keeps the committed Browser profile separate from the image during +reopen and updates. Linux x86-64 keeps Browser hidden and retires helpers and +images from unsupported releases while preserving Browser profiles. + +To remove Browser host access, close Browser and run this before uninstalling: ```sh sudo /usr/bin/python3 -I /usr/local/lib/elastos/browser-vm-linux-network.py remove --user "$(id -un)" @@ -502,8 +508,8 @@ directory stays, including Browser profiles, so installing again continues with the same identity. Pass the same `--install-dir` you installed with. An install or update that is running or was interrupted stops the removal; finish it first. -On Linux, the uninstall leaves any Browser host access an earlier release set -up in place. Remove it with: +On Linux, the administrator helper owns Browser host access. If you enabled it, +close Browser and remove that access before uninstalling: ```sh sudo /usr/bin/python3 -I /usr/local/lib/elastos/browser-vm-linux-network.py remove --user "$(id -un)" diff --git a/elastos/CHANGELOG.md b/elastos/CHANGELOG.md index 7b8b72168..bacb49cf3 100644 --- a/elastos/CHANGELOG.md +++ b/elastos/CHANGELOG.md @@ -8,6 +8,7 @@ release's Added, Changed, Fixed, Removed and Security bullets before you update; ### Fixed +- On Linux, Browser is turned on when you choose it, not during install. - Open apps, including Chat, stay connected while Home runs, and reconnect by themselves after a network drop or a restart. - Closing Browser no longer fails after a minute when another program happens to use a port Browser's media relay may need. diff --git a/elastos/crates/elastos-server/src/api/gateway_browser.rs b/elastos/crates/elastos-server/src/api/gateway_browser.rs index 67f5a1e5a..0f35260e3 100644 --- a/elastos/crates/elastos-server/src/api/gateway_browser.rs +++ b/elastos/crates/elastos-server/src/api/gateway_browser.rs @@ -595,6 +595,24 @@ async fn execute_browser_open( err.to_string(), )); } + if adapter_id + .as_deref() + .is_none_or(|id| id == "browser-vm-product") + { + if let Some(message) = crate::setup::linux_host_setup_message( + &state.data_dir, + &crate::setup::detect_platform(), + ) { + return Err(BrowserOpenFailure::json( + StatusCode::CONFLICT, + serde_json::json!({ + "code": "browser_host_setup_required", + "stage": "engine_readiness", + "message": message, + }), + )); + } + } let registry = match state.provider_registry.as_ref().cloned() { Some(registry) => registry, None => { diff --git a/elastos/crates/elastos-server/src/api/gateway_capsule_catalog/read_model.rs b/elastos/crates/elastos-server/src/api/gateway_capsule_catalog/read_model.rs index 523879834..a29ee6fc7 100644 --- a/elastos/crates/elastos-server/src/api/gateway_capsule_catalog/read_model.rs +++ b/elastos/crates/elastos-server/src/api/gateway_capsule_catalog/read_model.rs @@ -40,20 +40,24 @@ pub(in crate::api::gateway) fn capsule_catalog_summary_for( protected_content || manifest.name != crate::protected_content_runtime::ELACITY_PLAYER_CAPSULE_ID }) - // Browser is absent, not merely unlaunchable, where it is unavailable. - .filter(|manifest| { - manifest.name != "browser" || crate::setup::home_browser_available(data_dir, platform) - }) + // Supported Linux owners can find Browser before granting host access. + .filter(|manifest| manifest.name != "browser" || crate::setup::browser_available(platform)) // Hidden Services and an unconfigured WalletConnect are absent here as // in the launcher and Wallet. .filter(|manifest| capsule_is_offered(data_dir, &manifest.name)) .map(|manifest| { - catalog_capsule_summary( + let mut summary = catalog_capsule_summary( manifest, &launch_targets, &components, &accepted_content_by_viewer, - ) + ); + if summary.name == "browser" { + if let Some(message) = crate::setup::linux_host_setup_message(data_dir, platform) { + summary.description = message.to_string(); + } + } + summary }) .collect::>(); // The browser terminal only starts in developer mode, so the Terminal @@ -739,6 +743,28 @@ fn load_capsule_components(data_dir: &std::path::Path) -> BTreeMap, @@ -1586,6 +1590,7 @@ async fn run() -> anyhow::Result<()> { } Commands::Setup { + browser, profile, with, without, @@ -1594,6 +1599,10 @@ async fn run() -> anyhow::Result<()> { media_tools_dir, isolated, } => { + if browser { + setup::enable_browser().await?; + return Ok(()); + } if isolated { setup::choose_isolated_collaboration()?; } @@ -2599,6 +2608,25 @@ mod tests { assert!(super::Cli::try_parse_from(approved_rotation).is_ok()); } + #[test] + fn linux_browser_opt_in_is_an_explicit_setup_command() { + let cli = super::Cli::try_parse_from(["elastos", "setup", "--browser"]).unwrap(); + assert!(matches!( + cli.command, + Some(super::Commands::Setup { browser: true, .. }) + )); + for option in [ + "--list", + "--isolated", + "--prerequisites-only", + "--profile=home", + "--with=browser", + "--without=browser", + ] { + assert!(super::Cli::try_parse_from(["elastos", "setup", "--browser", option]).is_err()); + } + } + #[test] fn home_browser_cli_preserves_terminal_default_and_probe_options() { assert!(super::Cli::try_parse_from(["elastos"]) diff --git a/elastos/crates/elastos-server/src/setup.rs b/elastos/crates/elastos-server/src/setup.rs index 0c106aeb8..f7724f04c 100644 --- a/elastos/crates/elastos-server/src/setup.rs +++ b/elastos/crates/elastos-server/src/setup.rs @@ -15,7 +15,9 @@ use std::path::{Path, PathBuf}; use std::process::Command; mod browser_config; +pub(crate) use browser_config::linux_host_setup_message; pub use browser_config::{browser_available, home_browser_available}; +mod browser_linux; mod browser_vm_image; pub(crate) use browser_vm_image::start_background_verification as start_browser_image_verification; pub(crate) use browser_vm_image::verified_seed_identity as verified_browser_vm_seed_identity; @@ -261,6 +263,11 @@ pub fn validate_provider_runtime<'a>( // ── Entry point ───────────────────────────────────────────────────── +/// Explicit Linux Browser opt-in; normal setup keeps the image on demand. +pub async fn enable_browser() -> anyhow::Result<()> { + browser_linux::enable(&data_dir()?, &detect_platform()).await +} + pub async fn run( profile: Option, with: Vec, diff --git a/elastos/crates/elastos-server/src/setup/browser_config.rs b/elastos/crates/elastos-server/src/setup/browser_config.rs index 926f504b7..ff8ef0b07 100644 --- a/elastos/crates/elastos-server/src/setup/browser_config.rs +++ b/elastos/crates/elastos-server/src/setup/browser_config.rs @@ -22,6 +22,11 @@ pub(super) async fn ensure_host_components( context: super::FirstPartyCarrierContext, ) -> anyhow::Result<()> { ensure_viewer_ingress(data)?; + if matches!(context, super::FirstPartyCarrierContext::Runtime) + && linux_host_setup_message(data, platform).is_some() + { + return Ok(()); // The Browser viewer explains the explicit owner action. + } if !local_vm_selected(data, platform)? { return configure(data, platform, false); } @@ -227,6 +232,36 @@ fn native_host_available(data: &Path) -> anyhow::Result<()> { probe_native_host(&program, data, std::time::Duration::from_secs(2)) } +pub(crate) fn linux_host_setup_message(data: &Path, platform: &str) -> Option<&'static str> { + linux_host_setup_message_with_kvm( + data, + platform, + super::browser_linux::kvm_present(Path::new("/dev/kvm")), + ) +} + +fn linux_host_setup_message_with_kvm( + data: &Path, + platform: &str, + kvm_present: bool, +) -> Option<&'static str> { + if platform != "linux-arm64" || !local_vm_selected(data, platform).unwrap_or(false) { + return None; + } + if !kvm_present { + return Some(super::browser_linux::KVM_MESSAGE); + } + require_linux_host(data) + .is_err() + .then_some(super::browser_linux::SETUP_MESSAGE) +} + +pub(super) fn require_linux_host(data: &Path) -> anyhow::Result<()> { + #[cfg(target_os = "linux")] + require_kvm(Path::new("/dev/kvm"))?; + native_host_available(data) +} + fn probe_native_host( program: &Path, data: &Path, @@ -328,8 +363,15 @@ fn host_program(data: &Path, name: &str) -> Option { fn require_kvm(path: &Path) -> anyhow::Result<()> { use std::os::fd::AsRawFd; use std::os::unix::fs::FileTypeExt; - let file = fs::OpenOptions::new().read(true).write(true).open(path) - .map_err(|error| anyhow::anyhow!("Browser virtualization is unavailable to this Home user: {error}. Complete the installer host-access step, or choose another approved Engine"))?; + let file = fs::OpenOptions::new() + .read(true) + .write(true) + .open(path) + .map_err(|error| { + anyhow::anyhow!( + "Browser virtualization needs host access: {error}. Run elastos setup --browser" + ) + })?; anyhow::ensure!( file.metadata()?.file_type().is_char_device(), "Browser virtualization requires a KVM character device" @@ -360,6 +402,9 @@ pub(super) async fn prepare_home( if !browser_available(platform) { return retire_host(data, manifest); } + if platform.starts_with("linux-") { + return Ok(()); // Only `elastos setup --browser` prepares this host. + } if browser_selected && manifest.profiles.contains_key("browser-host") { println!("Preparing Browser Engine helpers..."); ensure_host_components( @@ -411,7 +456,7 @@ pub(super) fn pending_download_bytes( platform: &str, browser_selected: bool, ) -> u64 { - if !browser_available(platform) || !browser_selected { + if platform.starts_with("linux-") || !browser_available(platform) || !browser_selected { return 0; } let Ok(Some(rows)) = host_rows(manifest, platform) else { @@ -1069,6 +1114,53 @@ mod tests { assert!(!temp.path().join("bin").exists()); } + #[tokio::test] + async fn linux_setup_leaves_browser_helpers_and_image_for_explicit_setup() { + let manifest: super::super::ComponentsManifest = + serde_json::from_str(include_str!("../../../../../components.json")).unwrap(); + let temp = tempfile::tempdir().unwrap(); + let data = temp.path(); + fs::create_dir_all(data.join("capsules/browser")).unwrap(); + prepare_home(data, &manifest, "linux-arm64", true).await; + for path in ["scripts", "bin", "browser-vm", "config"] { + assert!(!data.join(path).exists(), "Linux setup prepared {path}"); + } + assert_eq!( + pending_download_bytes(data, &manifest, "linux-arm64", true), + 0 + ); + } + + #[tokio::test] + async fn linux_browser_open_explains_setup_before_admitting_helpers() { + let temp = tempfile::tempdir().unwrap(); + let data = temp.path(); + assert_eq!( + linux_host_setup_message_with_kvm(data, "linux-arm64", true), + Some("Browser is available on this computer. To turn it on, run: elastos setup --browser") + ); + assert_eq!( + linux_host_setup_message_with_kvm(data, "linux-arm64", false), + Some(super::super::browser_linux::KVM_MESSAGE) + ); + assert_eq!(linux_host_setup_message(data, "darwin-arm64"), None); + let manifest: super::super::ComponentsManifest = + serde_json::from_str(include_str!("../../../../../components.json")).unwrap(); + ensure_host_components( + data, + &manifest, + "linux-arm64", + super::super::FirstPartyCarrierContext::Runtime, + ) + .await + .unwrap(); + assert!(!data.join("bin").exists()); + assert!(!data.join("browser-vm").exists()); + fs::write(data.join("config/browser-engine-adapter.json"), + br#"{"adapters":[{"kind":"chromium_microvm","supervisor":{"program":"/remote/bin/browser-vm-remote-vz-launcher"}}]}"#).unwrap(); + assert_eq!(linux_host_setup_message(data, "linux-arm64"), None); + } + #[tokio::test] async fn linux_setup_installs_no_browser_host_helpers_or_image() { let manifest: super::super::ComponentsManifest = @@ -1084,7 +1176,7 @@ mod tests { fs::create_dir_all(data.join("capsules/browser")).unwrap(); prepare_home(data, &manifest, platform, true).await; assert!(!local_vm_selected(data, platform).unwrap()); - // install.sh asks for sudo only when this helper exists. + // An unsupported host keeps its existing retirement behavior. assert!(!data.join("scripts/browser-vm-linux-network.py").exists()); assert!(!data.join("scripts").exists()); assert!(!data.join("bin").exists()); diff --git a/elastos/crates/elastos-server/src/setup/browser_linux.rs b/elastos/crates/elastos-server/src/setup/browser_linux.rs new file mode 100644 index 000000000..2f487ae67 --- /dev/null +++ b/elastos/crates/elastos-server/src/setup/browser_linux.rs @@ -0,0 +1,306 @@ +//! The Linux owner explicitly grants Browser host access before image acquisition. +use std::path::Path; +use std::process::{Command, Stdio}; + +pub(super) const ENABLE_COMMAND: &str = "elastos setup --browser"; +pub(crate) const SETUP_MESSAGE: &str = + "Browser is available on this computer. To turn it on, run: elastos setup --browser"; +pub(crate) const KVM_MESSAGE: &str = + "Browser needs KVM on this computer. After KVM is available, run: elastos setup --browser"; +const ROOT_HELPER: &str = "/usr/local/lib/elastos/browser-vm-linux-network.py"; + +/// Keep ordinary Home setup and Browser open free of administrator operations. +pub(super) async fn enable(data: &Path, platform: &str) -> anyhow::Result<()> { + validate_host(platform, kvm_present(Path::new("/dev/kvm")))?; + let _writer = crate::install_transaction::acquire_installed_writer(data)?; + let _fresh = if _writer.is_none() { + Some(crate::install_transaction::InstallationGuard::acquire( + &std::fs::canonicalize(data)?, + )?) + } else { + None + }; + let manifest = super::load_manifest_from_path(&data.join("components.json"))?; + anyhow::ensure!( + super::browser_config::local_vm_selected(data, platform)?, + "Browser uses the selected remote Engine. Select the local Engine before running {ENABLE_COMMAND}" + ); + retire_rootfs_pool(data)?; + println!("Preparing Browser Engine helpers..."); + super::browser_config::ensure_host_components( + data, + &manifest, + platform, + super::FirstPartyCarrierContext::Setup, + ) + .await?; + let helper = data.join("scripts/browser-vm-linux-network.py"); + super::verify_installed_component_binary(data, "browser-vm-linux-network", &helper)?; + let user = Command::new("id").arg("-un").output()?; + anyhow::ensure!(user.status.success(), "Could not identify the Home user"); + let user = String::from_utf8(user.stdout)?; + enable_with( + || { + setup_host_with(data, user.trim(), |program, args, quiet| { + let mut command = Command::new(program); + command.args(args); + if quiet { + command + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + } + Ok(command.status()?.success()) + }) + }, + || async { + super::browser_config::require_linux_host(data)?; + println!("Preparing Browser Engine image..."); + super::ensure_browser_vm_image_in_context(data, super::FirstPartyCarrierContext::Setup) + .await + }, + ) + .await?; + println!("Browser is ready. Close Home, then start it with elastos home --browser."); + println!("To remove Browser host access after closing Browser:"); + println!( + " sudo /usr/bin/python3 -I {ROOT_HELPER} remove --user {}", + user.trim() + ); + Ok(()) +} + +fn retire_rootfs_pool(data: &Path) -> anyhow::Result<()> { + retire_rootfs_pool_for_owner(data, unsafe { libc::geteuid() }) +} + +fn retire_rootfs_pool_for_owner(data: &Path, owner: u32) -> anyhow::Result<()> { + use std::os::unix::fs::MetadataExt; + let relative = Path::new("browser-vm/rootfs-pool"); + let mut expected = None; + for name in [Path::new(""), Path::new("browser-vm"), relative] { + let path = data.join(name); + let metadata = match path.symlink_metadata() { + Ok(metadata) => metadata, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error.into()), + }; + anyhow::ensure!( + metadata.uid() == owner, + "Browser pool cleanup requires the Home user's files" + ); + if name != relative { + anyhow::ensure!( + metadata.is_dir() && !metadata.is_symlink(), + "Browser pool cleanup requires plain parent directories" + ); + } else { + if !metadata.is_dir() && !metadata.is_symlink() { + return Ok(()); + } + expected = Some(elastos_common::owned_removal::FileIdentity::of(&metadata)); + } + } + if elastos_common::owned_removal::remove_owned(data, relative, expected)? { + println!( + "Removed retired Browser rootfs pool: {}", + data.join("browser-vm/rootfs-pool").display() + ); + } + Ok(()) +} + +pub(super) fn kvm_present(path: &Path) -> bool { + use std::os::unix::fs::FileTypeExt; + std::fs::metadata(path).is_ok_and(|metadata| metadata.file_type().is_char_device()) +} + +fn validate_host(platform: &str, kvm_present: bool) -> anyhow::Result<()> { + anyhow::ensure!( + platform == "linux-arm64", + "{ENABLE_COMMAND} requires a supported Linux ARM64 Browser host" + ); + anyhow::ensure!(kvm_present, "{KVM_MESSAGE}"); + Ok(()) +} + +async fn enable_with(setup_host: F, prepare_image: P) -> anyhow::Result<()> +where + F: FnOnce() -> anyhow::Result<()>, + P: FnOnce() -> Fut, + Fut: std::future::Future>, +{ + setup_host()?; + prepare_image().await +} + +fn setup_host_with( + data: &Path, + user: &str, + mut run: impl FnMut(&str, &[&std::ffi::OsStr], bool) -> anyhow::Result, +) -> anyhow::Result<()> { + use std::ffi::OsStr; + let helper = data.join("scripts/browser-vm-linux-network.py"); + let check = [ + OsStr::new("-I"), + helper.as_os_str(), + OsStr::new("check"), + OsStr::new("--data-dir"), + data.as_os_str(), + ]; + if run("/usr/bin/python3", &check, true)? { + return Ok(()); + } + println!("Browser needs one-time administrator setup for KVM and its private network devices."); + println!( + "The setup shows its changes and asks for confirmation. Runtime then runs as your user." + ); + let install = [ + OsStr::new("install"), + OsStr::new("-D"), + OsStr::new("-o"), + OsStr::new("root"), + OsStr::new("-g"), + OsStr::new("root"), + OsStr::new("-m"), + OsStr::new("755"), + helper.as_os_str(), + OsStr::new(ROOT_HELPER), + ]; + anyhow::ensure!( + run("sudo", &install, false)?, + "Browser helper installation stopped. Retry with {ENABLE_COMMAND}" + ); + let setup = [ + OsStr::new("/usr/bin/python3"), + OsStr::new("-I"), + OsStr::new(ROOT_HELPER), + OsStr::new("setup"), + OsStr::new("--user"), + OsStr::new(user), + OsStr::new("--data-dir"), + data.as_os_str(), + ]; + anyhow::ensure!( + run("sudo", &setup, false)?, + "Browser administrator setup stopped. Retry with {ENABLE_COMMAND}" + ); + // The helper returns success when confirmation is declined. Prove access + // before downloading an image, including that declined case. + anyhow::ensure!( + run("/usr/bin/python3", &check, true)?, + "Browser host access still needs setup. Run {ENABLE_COMMAND} and confirm its changes" + ); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::RefCell; + + #[test] + fn linux_browser_opt_in_retires_only_owned_pool_without_following_links() { + use std::os::unix::fs::symlink; + let temp = tempfile::tempdir().unwrap(); + let data = temp.path().join("data"); + let outside = temp.path().join("outside"); + let pool = data.join("browser-vm/rootfs-pool"); + std::fs::create_dir_all(&pool).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + std::fs::write(pool.join("old.raw"), b"retired").unwrap(); + std::fs::write(data.join("browser-vm/rootfs.ext4"), b"image").unwrap(); + std::fs::write(outside.join("keep"), b"profile").unwrap(); + assert!( + retire_rootfs_pool_for_owner(&data, unsafe { libc::geteuid() }.wrapping_add(1)) + .is_err() + ); + assert!(pool.join("old.raw").is_file()); + retire_rootfs_pool(&data).unwrap(); + assert!(!pool.exists()); + assert_eq!( + std::fs::read(data.join("browser-vm/rootfs.ext4")).unwrap(), + b"image" + ); + symlink(&outside, &pool).unwrap(); + retire_rootfs_pool(&data).unwrap(); + assert!(pool.symlink_metadata().is_err()); + // A linked parent is refused; its target and the owner's profile stay. + let linked = temp.path().join("linked"); + std::fs::create_dir(&linked).unwrap(); + symlink(&outside, linked.join("browser-vm")).unwrap(); + assert!(retire_rootfs_pool(&linked).is_err()); + assert_eq!(std::fs::read(outside.join("keep")).unwrap(), b"profile"); + } + + #[test] + fn linux_browser_opt_in_requires_kvm_before_preparing_any_files() { + assert!(validate_host("linux-arm64", true).is_ok()); + assert_eq!( + validate_host("linux-arm64", false).unwrap_err().to_string(), + KVM_MESSAGE + ); + for platform in ["linux-amd64", "darwin-arm64", "darwin-amd64"] { + assert!(validate_host(platform, true).is_err()); + } + let temp = tempfile::NamedTempFile::new().unwrap(); + assert!(!kvm_present(temp.path())); + assert!(kvm_present(Path::new("/dev/null"))); + } + + #[tokio::test] + async fn linux_browser_opt_in_refuses_other_platforms_before_writing() { + let temp = tempfile::tempdir().unwrap(); + let data = temp.path().join("unprepared"); + assert!(enable(&data, "darwin-arm64").await.is_err()); + assert!(!data.exists()); + } + + #[tokio::test] + async fn explicit_browser_setup_runs_root_helper_before_image_and_checks_decline() { + for (statuses, prepares) in [ + (vec![true], true), + (vec![false, true, true, true], true), + (vec![false, false], false), + (vec![false, true, false], false), + (vec![false, true, true, false], false), + ] { + let calls = RefCell::new(Vec::new()); + let mut results = statuses.into_iter(); + let result = enable_with( + || { + setup_host_with( + Path::new("/fixture/home with spaces"), + "home-user", + |program, args, quiet| { + calls + .borrow_mut() + .push(format!("{program} {:?} quiet={quiet}", args)); + Ok(results.next().unwrap()) + }, + ) + }, + || async { + calls.borrow_mut().push("image".into()); + Ok(()) + }, + ) + .await; + assert_eq!(result.is_ok(), prepares); + let calls = calls.into_inner(); + assert_eq!(calls.last().unwrap() == "image", prepares); + if calls.len() == 5 { + assert!(calls[1].starts_with("sudo [\"install\", \"-D\"")); + assert!(calls[1] + .contains("/fixture/home with spaces/scripts/browser-vm-linux-network.py")); + assert!(calls[2].starts_with(&format!( + "sudo [\"/usr/bin/python3\", \"-I\", \"{ROOT_HELPER}\", \"setup\"" + ))); + assert!(calls[2].contains( + "\"--user\", \"home-user\", \"--data-dir\", \"/fixture/home with spaces\"" + )); + assert!(calls[3].starts_with("/usr/bin/python3")); + } + } + } +} diff --git a/scripts/install-bootstrap-test.py b/scripts/install-bootstrap-test.py index 6b2bc437e..7dbd4c723 100644 --- a/scripts/install-bootstrap-test.py +++ b/scripts/install-bootstrap-test.py @@ -1761,186 +1761,52 @@ def test_home_guard_compares_identity_not_path_text(self): class DataPathTests(unittest.TestCase): - def test_browser_setup_removes_only_retired_rootfs_pool(self): + def test_linux_summary_explains_missing_kvm(self): with tempfile.TemporaryDirectory() as scratch: root = Path(scratch) - pool = root / 'browser-vm/rootfs-pool' - pool.mkdir(parents=True) - (pool / 'copy.raw').write_text('retired system copy') - image = root / 'browser-vm/rootfs.raw' - image.write_text('system image') - result = shell('DATA_DIR="$1"; retire_browser_rootfs_pool', root) + helpers = HELPERS.replace('/dev/kvm', str(root / 'missing-kvm')) + result = shell(helpers + '\nuname() { case "$1" in -s) echo Linux;; -m) echo aarch64;; esac; }\nshow_ready "$1/elastos"', root) self.assertEqual(result.returncode, 0, result.stderr) - self.assertFalse(pool.exists()) - self.assertEqual(image.read_text(), 'system image') - self.assertIn(f'Removed retired Browser rootfs pool: {pool}', result.stdout) - again = shell('DATA_DIR="$1"; retire_browser_rootfs_pool', root) - self.assertEqual(again.returncode, 0, again.stderr) - self.assertNotIn('Removed', again.stdout) - - def test_browser_pool_cleanup_preserves_link_targets(self): - with tempfile.TemporaryDirectory() as scratch: - root = Path(scratch) - data, outside = root / 'data', root / 'outside' - (data / 'browser-vm').mkdir(parents=True) - outside.mkdir() - (outside / 'keep').write_text('keep') - pool = data / 'browser-vm/rootfs-pool' - pool.symlink_to(outside) - result = shell('DATA_DIR="$1"; retire_browser_rootfs_pool', data) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertFalse(pool.is_symlink()) - self.assertEqual((outside / 'keep').read_text(), 'keep') - (data / 'browser-vm').rmdir() - (data / 'browser-vm').symlink_to(outside) - (outside / 'rootfs-pool').mkdir() - result = shell('DATA_DIR="$1"; retire_browser_rootfs_pool', data) - self.assertNotEqual(result.returncode, 0) - self.assertTrue((outside / 'rootfs-pool').is_dir()) - - def test_browser_pool_cleanup_requires_pool_and_parent_ownership(self): - cleanup = SOURCE.split("<<'PY_RETIRED_BROWSER_POOL'\n", 1)[1].split("\nPY_RETIRED_BROWSER_POOL", 1)[0] - real_lstat = os.lstat - for uid in (0, 1001): - for foreign in ('browser-vm', 'browser-vm/rootfs-pool'): - with self.subTest(uid=uid, foreign=foreign), tempfile.TemporaryDirectory() as scratch: - root = Path(scratch) - pool = root / 'browser-vm/rootfs-pool' - pool.mkdir(parents=True) - image = pool / 'copy.raw' - image.write_text('keep foreign-owned pool') - def metadata(path, *args, **kwargs): - fields = list(real_lstat(path, *args, **kwargs)) - fields[4] = uid + 1 if Path(path) == root / foreign else uid - return os.stat_result(fields) - with mock.patch.object(os, 'lstat', side_effect=metadata), \ - mock.patch.object(os, 'geteuid', return_value=uid), \ - mock.patch.object(sys, 'argv', ['cleanup', str(root)]): - with self.assertRaisesRegex(SystemExit, 'belongs to another user'): - exec(compile(cleanup, str(INSTALLER) + ':pool-cleanup', 'exec'), {}) - self.assertEqual(image.read_text(), 'keep foreign-owned pool') - - def test_browser_host_step_is_installer_only_and_handles_decline_or_unavailable_host(self): - function = SOURCE.split("prepare_browser_linux_host() {", 1)[1].split("\nfinish_install()", 1)[0] - function = "prepare_browser_linux_host() {" + function + self.assertIn('Browser needs KVM', result.stdout) + self.assertIn('setup --browser', result.stdout) + self.assertNotIn('Browser is available', result.stdout) + + def test_linux_install_leaves_browser_setup_to_the_owner(self): with tempfile.TemporaryDirectory() as scratch: root = Path(scratch) (root / 'scripts').mkdir() - (root / 'scripts/browser-vm-linux-network.py').write_text('inert signed-helper fixture') - device, terminal = root / 'kvm', root / 'terminal' - function = function.replace('/dev/kvm', str(device)).replace('/dev/tty', str(terminal)) - function = function.replace('/usr/bin/python3 -I "', 'fixture_python -I "') - script = function + ''' -DATA_DIR="$1" SYSTEM="$2" READY="$3" ROOT_RESULT="$4" -uname() { printf '%s\\n' "$SYSTEM"; } -fixture_python() { - [[ "$READY" != yes ]] || return 0 - printf 'Browser network is unavailable (fixture).\\nAs root, run:\\n/usr/bin/python3 -I /usr/local/lib/elastos/browser-vm-linux-network.py setup --user %s --transport userspace-vsock --data-dir %s\\n' "$(id -un)" "$DATA_DIR" - return 1 -} -sudo() { printf 'ROOT_STEP:%s\\n' "$*"; [[ "$ROOT_RESULT" != 0 ]] || READY=yes; return "$ROOT_RESULT"; } -prepare_browser_linux_host -''' - for case, system, ready, device_present, terminal_present, root_result in [ - ('mac', 'Darwin', 'no', True, True, 0), - ('unavailable', 'Linux', 'no', False, True, 0), - ('ready', 'Linux', 'yes', True, True, 0), - ('headless', 'Linux', 'no', True, False, 0), - ('setup', 'Linux', 'no', True, True, 0), - ('declined', 'Linux', 'no', True, True, 1), - ]: - for path, present in [(device, device_present), (terminal, terminal_present)]: - path.unlink(missing_ok=True) - if present: - path.touch() - result = shell(script, root, system, ready, root_result) - with self.subTest(case=case): - self.assertEqual(result.returncode, root_result if case == 'declined' else 0, result.stderr) - self.assertEqual('ROOT_STEP:' in result.stdout, case in ('setup', 'declined')) - helper = root / 'scripts/browser-vm-linux-network.py' - root_helper = '/usr/local/lib/elastos/browser-vm-linux-network.py' - user = getpass.getuser() - install = f'install -D -o root -g root -m 755 {helper} {root_helper}' - run = f'fixture_python -I {root_helper} setup --user {user} --data-dir {root}' - if case == 'setup': - # sudo runs only the root-owned copy, never the user-writable helper. - self.assertEqual( - [line for line in result.stdout.splitlines() if line.startswith('ROOT_STEP:')], - [f'ROOT_STEP:{install}', f'ROOT_STEP:{run}'], - ) - self.assertIn(f'/usr/bin/python3 -I {root_helper} remove --user ', result.stdout) - if case == 'headless': - self.assertIn('Run from a terminal', result.stdout) - self.assertIn(f' sudo {install}\n', result.stdout) - command = f' sudo /usr/bin/python3 -I {root_helper} setup --user {user} --transport userspace-vsock --data-dir {root}\n' - self.assertIn(command, result.stdout) - self.assertLess(result.stdout.index('Browser network is unavailable'), result.stdout.index(command)) - if case == 'unavailable': - self.assertIn('virtualization is unavailable', result.stdout) - - def test_browser_setup_resumes_after_installer_host_access_and_home_survives_browser_failure(self): - with tempfile.TemporaryDirectory() as scratch: - root = Path(scratch) + (root / 'scripts/browser-vm-linux-network.py').write_text('fixture') + (root / 'kvm').symlink_to('/dev/null') + (root / 'terminal').touch() runtime = root / 'elastos' - runtime.write_text("#!/bin/bash\n" + - 'printf "SETUP:%s\\n" "$*" >> "$CALLS"\n' + - '[[ -f "$HOST_READY" ]] || exit 0\n' + - 'exit "${BROWSER_SETUP_RESULT:-0}"\n') + runtime.write_text('#!/bin/bash\n' + 'printf "RUNTIME:%s\\n" "$*" >> "$CALLS"\n' + 'if [[ -f "$HOST_READY" || "$*" == *--browser* ]]; then ' + 'printf "IMAGE_DOWNLOAD\\n" >> "$CALLS"; fi\n') runtime.chmod(0o755) - script = HELPERS + """ -INSTALL_DIR="$1" INSTALL_ONLY=false DATA_DIR="$1/data" ISOLATED="$3" -export CALLS="$1/calls" HOST_READY="$1/host-ready" BROWSER_SETUP_RESULT="$2" -prepare_browser_linux_host() { touch "$HOST_READY"; BROWSER_LINUX_HOST_READY=true; printf 'HOST_READY\\n' >> "$CALLS"; } -show_ready() { printf 'HOME_READY\\n' >> "$CALLS"; } -finish_install -""" - for isolated in ['false', 'true']: - for browser_result in [0, 7]: - calls, ready = root / 'calls', root / 'host-ready' - calls.unlink(missing_ok=True); ready.unlink(missing_ok=True) - result = shell(script, root, browser_result, isolated) - setup = 'SETUP:setup --isolated' if isolated == 'true' else 'SETUP:setup' - with self.subTest(isolated=isolated, browser_result=browser_result): - self.assertEqual(result.returncode, 0, result.stderr) - self.assertEqual(calls.read_text().splitlines(), [setup, 'HOST_READY', setup, 'HOME_READY']) - - def test_rerun_with_retained_linux_helper_never_asks_for_sudo_after_setup_retires_it(self): - # An earlier release left the helper and its check now fails. Setup runs - # first and, where Browser is unavailable, removes the helper, so the - # host step that follows finds nothing to set up. - function = SOURCE.split("prepare_browser_linux_host() {", 1)[1].split("\nfinish_install()", 1)[0] - with tempfile.TemporaryDirectory() as scratch: - root = Path(scratch) - (root / 'data/scripts').mkdir(parents=True) - helper = root / 'data/scripts/browser-vm-linux-network.py' - device, terminal = root / 'kvm', root / 'terminal' - device.touch(); terminal.touch() - runtime = root / 'elastos' - runtime.write_text("#!/bin/bash\n" + - 'printf "SETUP:%s\\n" "$*" >> "$CALLS"\n' + - '[[ "$1" != setup || "$RETIRES" != yes ]] || rm -f "$HELPER"\n') - runtime.chmod(0o755) - function = "prepare_browser_linux_host() {" + function - function = function.replace('/dev/kvm', str(device)).replace('/dev/tty', str(terminal)) - function = function.replace('/usr/bin/python3', 'fixture_python') - script = function + """ -INSTALL_DIR="$1" INSTALL_ONLY=false DATA_DIR="$1/data" -export CALLS="$1/calls" HELPER="$1/data/scripts/browser-vm-linux-network.py" RETIRES="$2" -uname() { printf 'Linux\\n'; } -fixture_python() { return 1; } -sudo() { printf 'ROOT_STEP:%s\\n' "$*" >> "$CALLS"; return 1; } -show_ready() { printf 'HOME_READY\\n' >> "$CALLS"; } + helpers = HELPERS.replace('/dev/kvm', str(root / 'kvm')) + helpers = helpers.replace('/dev/tty', str(root / 'terminal')) + helpers = helpers.replace('/usr/bin/python3 -I ', 'fixture_python -I ') + script = helpers + r''' +INSTALL_DIR="$1" DATA_DIR="$1" INSTALL_ONLY=false ISOLATED="$2" SYSTEM="$3" +export CALLS="$1/calls" HOST_READY="$1/host-ready" +uname() { case "$1" in -s) echo "$SYSTEM";; -m) echo aarch64;; esac; } +fixture_python() { [[ -f "$HOST_READY" ]]; } +sudo() { printf 'SUDO:%s\n' "$*" >> "$CALLS"; touch "$HOST_READY"; } +retire_browser_rootfs_pool() { :; } finish_install &1)"; then - info "Browser KVM and network access are ready." - elif ( : /dev/null && command -v sudo >/dev/null 2>&1; then - info "Browser needs one-time administrator setup for KVM access and its private network devices." - info "The setup shows its changes and asks for confirmation. Runtime then runs as your user." - sudo install -D -o root -g root -m 755 "$helper" "$root_helper" /dev/null 2>&1 || return $? - else - info "Browser needs one-time administrator setup. Run from a terminal:" - printf ' sudo install -D -o root -g root -m 755 %q %q\n' "$helper" "$root_helper" - while IFS= read -r line; do - case "$line" in - '/usr/bin/python3 -I '*) printf ' sudo %s\n' "$line" ;; - *) printf '%s\n' "$line" ;; - esac - done <<<"$check_result" - return 0 - fi - BROWSER_LINUX_HOST_READY=true - info "To remove Browser host access after closing Browser:" - printf ' sudo /usr/bin/python3 -I %q remove --user %q\n' "$root_helper" "$user" -} - finish_install() { local runtime_bin="${INSTALL_DIR}/elastos" if [[ "$INSTALL_ONLY" == true || "$INSTALL_ONLY" == 1 ]]; then @@ -1171,12 +1106,6 @@ finish_install() { warn "Then run: $(runtime_command "$runtime_bin") ${setup_args[*]}" return "$status" fi - if ! prepare_browser_linux_host; then - warn "Browser host preparation is incomplete. Home is ready. Run the installer from a terminal to complete Browser host access, then run elastos setup." - elif [[ "${BROWSER_LINUX_HOST_READY:-false}" == true ]]; then - # Resume image preparation with the same Community choice. - "$runtime_bin" "${setup_args[@]}" /dev/null && [[ -t 1 ]]; then show_remote_open_hint @@ -1310,6 +1239,10 @@ uninstall_installation() { return 0 fi command -v python3 &>/dev/null || die "Required tool not found: python3" + if [[ "$(uname -s)" == Linux ]]; then + info "If you turned Browser on, close Browser and remove its host access before uninstalling:" + printf ' sudo /usr/bin/python3 -I /usr/local/lib/elastos/browser-vm-linux-network.py remove --user %q\n' "$(id -un)" + fi uninstall_files check "$install_dir" "$data_dir" "$remove_data" \ || die "Nothing was stopped or removed" info "Stopping this installation's verified Runtime processes..." From 8e1a3600052fc512786d364c5ff7a4f3725c25ad Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 5 Nov 2026 13:56:55 -0500 Subject: [PATCH 2/8] test(browser): repair opt-in fixtures (#90) Register Browser in the fixture's active component manifest and resolve the macOS temporary base before testing strict no-link pool removal. The first Browser library run passed 414 tests, failed these two new fixtures and ignored two; the current all-target gate will verify both repairs. Runtime behavior is unchanged. --- .../src/api/gateway_capsule_catalog/read_model.rs | 2 ++ elastos/crates/elastos-server/src/setup/browser_linux.rs | 7 ++++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_capsule_catalog/read_model.rs b/elastos/crates/elastos-server/src/api/gateway_capsule_catalog/read_model.rs index a29ee6fc7..0d672f1b3 100644 --- a/elastos/crates/elastos-server/src/api/gateway_capsule_catalog/read_model.rs +++ b/elastos/crates/elastos-server/src/api/gateway_capsule_catalog/read_model.rs @@ -753,6 +753,8 @@ mod tests { include_str!("../../../../../../capsules/browser/capsule.json"), ) .unwrap(); + std::fs::write(root.path().join("components.json"), + r#"{"profiles":{},"external":{"browser":{"install_path":"capsules/browser","platforms":{}}}}"#).unwrap(); let catalog = super::capsule_catalog_summary_for(root.path(), "linux-arm64"); let browser = catalog .capsules diff --git a/elastos/crates/elastos-server/src/setup/browser_linux.rs b/elastos/crates/elastos-server/src/setup/browser_linux.rs index 2f487ae67..48738e343 100644 --- a/elastos/crates/elastos-server/src/setup/browser_linux.rs +++ b/elastos/crates/elastos-server/src/setup/browser_linux.rs @@ -203,8 +203,9 @@ mod tests { fn linux_browser_opt_in_retires_only_owned_pool_without_following_links() { use std::os::unix::fs::symlink; let temp = tempfile::tempdir().unwrap(); - let data = temp.path().join("data"); - let outside = temp.path().join("outside"); + let base = temp.path().canonicalize().unwrap(); + let data = base.join("data"); + let outside = base.join("outside"); let pool = data.join("browser-vm/rootfs-pool"); std::fs::create_dir_all(&pool).unwrap(); std::fs::create_dir_all(&outside).unwrap(); @@ -226,7 +227,7 @@ mod tests { retire_rootfs_pool(&data).unwrap(); assert!(pool.symlink_metadata().is_err()); // A linked parent is refused; its target and the owner's profile stay. - let linked = temp.path().join("linked"); + let linked = base.join("linked"); std::fs::create_dir(&linked).unwrap(); symlink(&outside, linked.join("browser-vm")).unwrap(); assert!(retire_rootfs_pool(&linked).is_err()); From 405f050330089121a053e612f069ce194feb3c6b Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 5 Nov 2026 16:58:43 -0500 Subject: [PATCH 3/8] fix(browser): preserve Linux opt-in through updates Use the Home owner's stored Browser selection to refresh changed Linux helpers on setup and open. Offer Browser on supported Linux Homes with setup and restart guidance. Keep the installer hint for fresh Homes with accessible or ACL-repairable KVM, and verify the exact managed network script through its manifest checksum. Verification: - cargo fmt --all -- --check; chain-provider fmt check - cargo clippy -p elastos-server --all-targets -- -D warnings - cargo test -p elastos-server --all-targets browser (438 passed, 2 ignored) - Home summary and installed verifier tests (5 passed) - Browser Node tests (85 passed) - scripts/test-source-gate.sh; scripts/test-behaviour.sh (2181 passed) - python3 scripts/install-bootstrap-test.py (95 passed, 4 skipped) - git diff --check --- .../browser/browser/browser-status.test.mjs | 2 +- docs/INSTALL.md | 11 +- .../src/api/browser_capsules.rs | 6 +- .../elastos-server/src/api/gateway_browser.rs | 64 +++++-- .../src/api/gateway_tests/home_system.rs | 4 +- .../crates/elastos-server/src/server_infra.rs | 6 +- elastos/crates/elastos-server/src/setup.rs | 9 +- .../src/setup/browser_config.rs | 164 +++++++++++++++++- .../elastos-server/src/setup/browser_linux.rs | 6 +- scripts/install-bootstrap-test.py | 37 +++- scripts/install.sh | 23 ++- 11 files changed, 282 insertions(+), 50 deletions(-) diff --git a/capsules/browser/browser/browser-status.test.mjs b/capsules/browser/browser/browser-status.test.mjs index f7c0dc101..d90e50df5 100644 --- a/capsules/browser/browser/browser-status.test.mjs +++ b/capsules/browser/browser/browser-status.test.mjs @@ -265,7 +265,7 @@ test("Linux host setup guidance names the opt-in command", () => { Object.assign(error.payload, { stage: "engine_readiness", code: "browser_host_setup_required", - message: "Browser is available on this computer. To turn it on, run: elastos setup --browser", + message: "Browser is available on this computer. To turn it on, run: elastos setup --browser. Then close Home and start it again with elastos home --browser.", }); assert.equal(friendlyOpenError(error), error.payload.message); error.payload.message = "Browser needs KVM on this computer. After KVM is available, run: elastos setup --browser"; diff --git a/docs/INSTALL.md b/docs/INSTALL.md index ebbf044ef..48d370b3e 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -183,10 +183,13 @@ command installs the signed Browser helpers, shows the host access changes and asks for administrator approval. It then downloads and verifies the image with progress. Close Home and start it again with `elastos home --browser`. -The Linux installer and ordinary `elastos setup` leave this download to your -choice. Opening Browser on an unprepared Linux host explains the command. -After setup, a later open prepares a missing image on demand. Apple Silicon -setup continues to prepare its helpers and image before Home starts. The image +The Linux installer and ordinary `elastos setup` leave Browser preparation to +your choice until you enable it. Home lists Browser on supported Linux ARM64 +computers; opening it before setup explains the command and restart. After you +enable Browser, ordinary setup refreshes its signed helpers and image during +updates. A later open repairs missing or changed helpers and prepares a missing +image on demand. Apple Silicon setup continues to prepare its helpers and image +before Home starts. The image streams to disk with progress; a transfer stops after 30 seconds without data. Runtime keeps the committed Browser profile separate from the image during reopen and updates. Linux x86-64 keeps Browser hidden and retires helpers and diff --git a/elastos/crates/elastos-server/src/api/browser_capsules.rs b/elastos/crates/elastos-server/src/api/browser_capsules.rs index ccb3e730a..84b26159a 100644 --- a/elastos/crates/elastos-server/src/api/browser_capsules.rs +++ b/elastos/crates/elastos-server/src/api/browser_capsules.rs @@ -430,7 +430,7 @@ fn list_launchable_browser_capsules_for( if !capsule_is_offered(data_dir, &manifest.name) { continue; } - if manifest.name == "browser" && !crate::setup::home_browser_available(data_dir, platform) { + if manifest.name == "browser" && !crate::setup::browser_available(platform) { continue; } let Ok(capsule) = resolve_browser_capsule(data_dir, &manifest.name) else { @@ -1494,12 +1494,12 @@ mod tests { } #[test] - fn browser_is_launchable_only_on_hosts_with_a_local_engine() { + fn browser_is_launchable_on_supported_hosts_before_setup() { let data_dir = tempfile::tempdir().unwrap(); write_test_browser_capsule(data_dir.path(), "browser", "Browser", "app"); for (platform, listed) in [ ("linux-amd64", false), - ("linux-arm64", false), + ("linux-arm64", true), ("darwin-arm64", true), ] { let names: Vec<_> = list_launchable_browser_capsules_for(data_dir.path(), platform) diff --git a/elastos/crates/elastos-server/src/api/gateway_browser.rs b/elastos/crates/elastos-server/src/api/gateway_browser.rs index 0f35260e3..1f86ad7d0 100644 --- a/elastos/crates/elastos-server/src/api/gateway_browser.rs +++ b/elastos/crates/elastos-server/src/api/gateway_browser.rs @@ -561,6 +561,26 @@ fn browser_open_status_value(open_id: &str, snapshot: BrowserOpenJobSnapshot) -> } } +fn browser_host_setup_failure( + data: &std::path::Path, + platform: &str, + adapter_id: Option<&str>, +) -> Option { + if adapter_id.is_some_and(|id| id != "browser-vm-product") { + return None; + } + crate::setup::linux_host_setup_message(data, platform).map(|message| { + BrowserOpenFailure::json( + StatusCode::CONFLICT, + serde_json::json!({ + "code": "browser_host_setup_required", + "stage": "engine_readiness", + "message": message, + }), + ) + }) +} + async fn execute_browser_open( state: &GatewayState, context: HomeLaunchTokenContext, @@ -595,23 +615,12 @@ async fn execute_browser_open( err.to_string(), )); } - if adapter_id - .as_deref() - .is_none_or(|id| id == "browser-vm-product") - { - if let Some(message) = crate::setup::linux_host_setup_message( - &state.data_dir, - &crate::setup::detect_platform(), - ) { - return Err(BrowserOpenFailure::json( - StatusCode::CONFLICT, - serde_json::json!({ - "code": "browser_host_setup_required", - "stage": "engine_readiness", - "message": message, - }), - )); - } + if let Some(failure) = browser_host_setup_failure( + &state.data_dir, + &crate::setup::detect_platform(), + adapter_id.as_deref(), + ) { + return Err(failure); } let registry = match state.provider_registry.as_ref().cloned() { Some(registry) => registry, @@ -4645,6 +4654,27 @@ fn browser_display_error_response(error: BrowserDisplayError) -> Response { mod browser_open_outcome_tests { use super::*; + #[test] + fn unprepared_linux_browser_open_explains_setup_and_restart_before_acquiring_effects() { + let data = tempfile::tempdir().unwrap(); + for adapter in [None, Some("browser-vm-product")] { + let failure = browser_host_setup_failure(data.path(), "linux-arm64", adapter).unwrap(); + assert_eq!(failure.status, StatusCode::CONFLICT); + let body = failure.status_value(); + assert_eq!(body["code"], "browser_host_setup_required"); + assert_eq!(body["stage"], "engine_readiness"); + let message = body["message"].as_str().unwrap(); + assert!(message.contains("elastos setup --browser")); + assert!(message.contains("close Home and start it again with elastos home --browser")); + assert_eq!(body["outcome"]["effects"]["vm_acquired"], false); + } + assert!( + browser_host_setup_failure(data.path(), "linux-arm64", Some("remote-engine")).is_none() + ); + assert!(browser_host_setup_failure(data.path(), "darwin-arm64", None).is_none()); + assert!(std::fs::read_dir(data.path()).unwrap().next().is_none()); + } + #[test] fn failed_open_serializes_cleanup_pending_separately_from_pre_effect_failure() { let pending = BrowserOpenFailure::text( diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/home_system.rs b/elastos/crates/elastos-server/src/api/gateway_tests/home_system.rs index 0ea134f04..9742cd1e3 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/home_system.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/home_system.rs @@ -1688,7 +1688,7 @@ async fn test_home_summary_reports_identity_and_launch_targets() { assert_eq!(wallet["attach_kind"], "iframe"); assert_eq!(wallet["target_kind"], "app"); let browser = targets.iter().find(|target| target["target"] == "browser"); - if crate::setup::home_browser_available(dir.path(), &crate::setup::detect_platform()) { + if crate::setup::browser_available(&crate::setup::detect_platform()) { let browser = browser.expect("browser target"); assert_eq!(browser["role"], "app"); assert_eq!(browser["title"], "Browser"); @@ -1699,7 +1699,7 @@ async fn test_home_summary_reports_identity_and_launch_targets() { } else { assert!( browser.is_none(), - "Browser is hidden on hosts without a local Engine" + "Browser is hidden on unsupported platforms" ); } assert!(targets diff --git a/elastos/crates/elastos-server/src/server_infra.rs b/elastos/crates/elastos-server/src/server_infra.rs index 5389040e3..3ff428ecb 100644 --- a/elastos/crates/elastos-server/src/server_infra.rs +++ b/elastos/crates/elastos-server/src/server_infra.rs @@ -1226,10 +1226,8 @@ async fn setup_server_infrastructure_impl( // Retained Browser helpers from an earlier release stay stopped where // Browser is unavailable. - let browser_available = elastos_server::setup::home_browser_available( - &data_dir, - &elastos_server::setup::detect_platform(), - ); + let browser_available = + elastos_server::setup::browser_available(&elastos_server::setup::detect_platform()); if let Some(local_exit_config) = browser_available .then(|| browser_local_exit_config_from_env(&data_dir)) .flatten() diff --git a/elastos/crates/elastos-server/src/setup.rs b/elastos/crates/elastos-server/src/setup.rs index f7724f04c..a09be98d1 100644 --- a/elastos/crates/elastos-server/src/setup.rs +++ b/elastos/crates/elastos-server/src/setup.rs @@ -1097,7 +1097,7 @@ fn installed_component_entry( }) } -/// Verify an installed binary whose bytes carry the signed checksum. A binary +/// Verify an installed program whose bytes carry the signed checksum. A program /// extracted from a signed archive is refused: its checksum names the archive. pub fn verify_installed_component_binary( data_dir: &Path, @@ -1235,6 +1235,13 @@ fn write_archive_executable_receipt( } fn installed_component_root_for_path(data_dir: &Path, name: &str, path: &Path) -> Option { + // Browser host setup executes this exact release-owned script through Python. + if name == "browser-vm-linux-network" + && path == data_dir.join("scripts/browser-vm-linux-network.py") + { + return Some(data_dir.to_path_buf()); + } + let installed_bin = data_dir.join("bin").join(name); if path == installed_bin { return Some(data_dir.to_path_buf()); diff --git a/elastos/crates/elastos-server/src/setup/browser_config.rs b/elastos/crates/elastos-server/src/setup/browser_config.rs index ff8ef0b07..4fcd5cb44 100644 --- a/elastos/crates/elastos-server/src/setup/browser_config.rs +++ b/elastos/crates/elastos-server/src/setup/browser_config.rs @@ -23,7 +23,8 @@ pub(super) async fn ensure_host_components( ) -> anyhow::Result<()> { ensure_viewer_ingress(data)?; if matches!(context, super::FirstPartyCarrierContext::Runtime) - && linux_host_setup_message(data, platform).is_some() + && platform == "linux-arm64" + && !local_vm_configured(data, platform)? { return Ok(()); // The Browser viewer explains the explicit owner action. } @@ -402,8 +403,8 @@ pub(super) async fn prepare_home( if !browser_available(platform) { return retire_host(data, manifest); } - if platform.starts_with("linux-") { - return Ok(()); // Only `elastos setup --browser` prepares this host. + if platform.starts_with("linux-") && !local_vm_configured(data, platform)? { + return Ok(()); // The owner enables Browser with `elastos setup --browser`. } if browser_selected && manifest.profiles.contains_key("browser-host") { println!("Preparing Browser Engine helpers..."); @@ -456,7 +457,10 @@ pub(super) fn pending_download_bytes( platform: &str, browser_selected: bool, ) -> u64 { - if platform.starts_with("linux-") || !browser_available(platform) || !browser_selected { + if !browser_available(platform) + || !browser_selected + || (platform.starts_with("linux-") && !local_vm_configured(data, platform).unwrap_or(false)) + { return 0; } let Ok(Some(rows)) = host_rows(manifest, platform) else { @@ -1114,6 +1118,156 @@ mod tests { assert!(!temp.path().join("bin").exists()); } + #[tokio::test] + async fn enabled_linux_home_refreshes_changed_helpers_on_setup() { + check_enabled_linux_helper_refresh(super::super::FirstPartyCarrierContext::Setup).await; + } + + #[tokio::test] + async fn enabled_linux_home_refreshes_changed_helpers_on_open() { + check_enabled_linux_helper_refresh(super::super::FirstPartyCarrierContext::Runtime).await; + } + + async fn check_enabled_linux_helper_refresh(context: super::super::FirstPartyCarrierContext) { + use std::os::unix::fs::PermissionsExt; + let temp = tempfile::tempdir().unwrap(); + let data = temp.path().canonicalize().unwrap(); + fs::create_dir_all(data.join("config")).unwrap(); + fs::write( + data.join("config/browser-engine-adapter.json"), + serde_json::to_vec( + &serde_json::json!({"adapters":[{"kind":"chromium_microvm","supervisor":{ + "program":data.join("bin/browser-vz-engine-supervisor") + }}]}), + ) + .unwrap(), + ) + .unwrap(); + let mut manifest: super::super::ComponentsManifest = serde_json::from_value( + serde_json::json!({"schema":"elastos.components/v1", "capsules":{}, + "profiles":{"browser-host":{"components":[ + "browser-vz-engine-supervisor", "browser-vm-linux-network" + ]}}, "external":{}}), + ) + .unwrap(); + let mut artifacts = std::collections::HashMap::new(); + let helpers = [ + ( + "browser-vz-engine-supervisor", + "bin/browser-vz-engine-supervisor", + ), + ( + "browser-vm-linux-network", + "scripts/browser-vm-linux-network.py", + ), + ]; + for (name, relative) in helpers { + let bytes = format!("{name} current release").into_bytes(); + let digest = sha2::Sha256::digest(&bytes); + let cid = cid::Cid::new_v1( + 0x55, + cid::multihash::Multihash::<64>::wrap(0x12, &digest).unwrap(), + ) + .to_string(); + manifest.external.insert( + name.into(), + serde_json::from_value(serde_json::json!({ + "install_path":relative, "platforms":{"*":{ + "release_path":name, "checksum":format!("sha256:{digest:x}"), + "size":bytes.len(), "cid":cid + }} + })) + .unwrap(), + ); + // Same-size stale bytes exercise checksum validation. + let old_bytes = vec![b'x'; bytes.len()]; + artifacts.insert(cid, bytes); + let path = data.join(relative); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(&path, old_bytes).unwrap(); + fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap(); + } + fs::write( + data.join("components.json"), + serde_json::to_vec(&manifest).unwrap(), + ) + .unwrap(); + for (name, relative) in helpers { + let info = &manifest.external[name].platforms["*"]; + assert!(super::super::verify_checksum( + name, + &fs::read(data.join(relative)).unwrap(), + info + ) + .unwrap_err() + .to_string() + .contains("Checksum mismatch")); + } + let source = serde_json::from_value(serde_json::json!({ + "name":"fixture", "publisher_dids":[elastos_identity::derive_did(&[217;32]).1], + "connect_ticket":"", "publisher_node_id":"" + })) + .unwrap(); + let (_, server, serving) = + crate::setup::tests::carrier_cid_source(&data, &source, artifacts).await; + let pending = pending_download_bytes(&data, &manifest, "linux-arm64", true); + if matches!(context, super::super::FirstPartyCarrierContext::Setup) { + prepare_home(&data, &manifest, "linux-arm64", true).await; + } else { + ensure_host_components(&data, &manifest, "linux-arm64", context) + .await + .unwrap(); + } + for (name, relative) in helpers { + assert_eq!( + fs::read(data.join(relative)).unwrap(), + format!("{name} current release").as_bytes(), + "{name}" + ); + super::super::verify_installed_component_binary(&data, name, &data.join(relative)) + .unwrap(); + } + assert!(pending > 0); + assert_eq!( + pending_download_bytes(&data, &manifest, "linux-arm64", true), + 0 + ); + server.close().await; + assert_eq!(serving.await.unwrap().len(), 2); + } + + #[test] + fn installed_browser_network_helper_requires_its_exact_path_and_manifest_checksum() { + let temp = tempfile::tempdir().unwrap(); + let data = temp.path(); + let name = "browser-vm-linux-network"; + let helper = data.join("scripts/browser-vm-linux-network.py"); + let bytes = b"signed network fixture"; + fs::create_dir_all(helper.parent().unwrap()).unwrap(); + fs::write(&helper, bytes).unwrap(); + let manifest: super::super::ComponentsManifest = serde_json::from_value(serde_json::json!({ + "schema":"elastos.components/v1", "profiles":{}, "capsules":{}, + "external":{name:{"install_path":"scripts/browser-vm-linux-network.py", + "platforms":{"*":{"checksum":format!("sha256:{:x}", sha2::Sha256::digest(bytes))}}}} + })).unwrap(); + fs::write( + data.join("components.json"), + serde_json::to_vec(&manifest).unwrap(), + ) + .unwrap(); + super::super::verify_installed_component_binary(data, name, &helper).unwrap(); + let other = data.join("scripts/other.py"); + fs::write(&other, bytes).unwrap(); + assert!(super::super::verify_installed_component_binary(data, name, &other).is_err()); + fs::write(&helper, b"changed network bytes").unwrap(); + assert!( + super::super::verify_installed_component_binary(data, name, &helper) + .unwrap_err() + .to_string() + .contains("failed checksum verification") + ); + } + #[tokio::test] async fn linux_setup_leaves_browser_helpers_and_image_for_explicit_setup() { let manifest: super::super::ComponentsManifest = @@ -1137,7 +1291,7 @@ mod tests { let data = temp.path(); assert_eq!( linux_host_setup_message_with_kvm(data, "linux-arm64", true), - Some("Browser is available on this computer. To turn it on, run: elastos setup --browser") + Some(super::super::browser_linux::SETUP_MESSAGE) ); assert_eq!( linux_host_setup_message_with_kvm(data, "linux-arm64", false), diff --git a/elastos/crates/elastos-server/src/setup/browser_linux.rs b/elastos/crates/elastos-server/src/setup/browser_linux.rs index 48738e343..3783fe598 100644 --- a/elastos/crates/elastos-server/src/setup/browser_linux.rs +++ b/elastos/crates/elastos-server/src/setup/browser_linux.rs @@ -4,9 +4,9 @@ use std::process::{Command, Stdio}; pub(super) const ENABLE_COMMAND: &str = "elastos setup --browser"; pub(crate) const SETUP_MESSAGE: &str = - "Browser is available on this computer. To turn it on, run: elastos setup --browser"; + "Browser is available on this computer. To turn it on, run: elastos setup --browser. Then close Home and start it again with elastos home --browser."; pub(crate) const KVM_MESSAGE: &str = - "Browser needs KVM on this computer. After KVM is available, run: elastos setup --browser"; + "Browser needs KVM on this computer. After KVM is available, run: elastos setup --browser. Then close Home and start it again with elastos home --browser."; const ROOT_HELPER: &str = "/usr/local/lib/elastos/browser-vm-linux-network.py"; /// Keep ordinary Home setup and Browser open free of administrator operations. @@ -61,12 +61,12 @@ pub(super) async fn enable(data: &Path, platform: &str) -> anyhow::Result<()> { }, ) .await?; - println!("Browser is ready. Close Home, then start it with elastos home --browser."); println!("To remove Browser host access after closing Browser:"); println!( " sudo /usr/bin/python3 -I {ROOT_HELPER} remove --user {}", user.trim() ); + println!("Browser is ready. Close Home, then start it again with elastos home --browser."); Ok(()) } diff --git a/scripts/install-bootstrap-test.py b/scripts/install-bootstrap-test.py index 7dbd4c723..3ae97d337 100644 --- a/scripts/install-bootstrap-test.py +++ b/scripts/install-bootstrap-test.py @@ -1761,15 +1761,44 @@ def test_home_guard_compares_identity_not_path_text(self): class DataPathTests(unittest.TestCase): - def test_linux_summary_explains_missing_kvm(self): + def test_linux_summary_omits_browser_hint_without_kvm(self): with tempfile.TemporaryDirectory() as scratch: root = Path(scratch) helpers = HELPERS.replace('/dev/kvm', str(root / 'missing-kvm')) result = shell(helpers + '\nuname() { case "$1" in -s) echo Linux;; -m) echo aarch64;; esac; }\nshow_ready "$1/elastos"', root) self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn('Browser needs KVM', result.stdout) - self.assertIn('setup --browser', result.stdout) - self.assertNotIn('Browser is available', result.stdout) + self.assertNotIn('setup --browser', result.stdout) + + def test_linux_summary_distinguishes_acl_setup_from_host_open_failure(self): + with tempfile.TemporaryDirectory() as scratch: + root = Path(scratch) + device = root / 'kvm' + device.symlink_to('/dev/null') + # Drive the real helper with an injected device-open error. EACCES + # is repairable by setup's per-user ACL; EPERM/ENODEV are host gaps. + (root / 'sitecustomize.py').write_text( + 'import errno, os\n' + 'original_open = os.open\n' + 'def fixture_open(path, *args, **kwargs):\n' + ' if path == os.environ.get("KVM_DEVICE"):\n' + ' raise OSError(int(os.environ["KVM_ERRNO"]), "fixture")\n' + ' return original_open(path, *args, **kwargs)\n' + 'os.open = fixture_open\n') + helpers = HELPERS.replace('/dev/kvm', str(device)) + for error, hinted in [(13, True), (1, False), (6, False), (19, False)]: + script = helpers + '\nexport PYTHONPATH="$1" KVM_DEVICE="$1/kvm" KVM_ERRNO="$2"\nuname() { case "$1" in -s) echo Linux;; -m) echo aarch64;; esac; }\nshow_ready "$1/elastos"' + result = shell(script, root, error) + with self.subTest(errno=error): + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual('setup --browser' in result.stdout, hinted) + + def test_linux_update_omits_browser_hint(self): + with tempfile.TemporaryDirectory() as scratch: + root = Path(scratch) + helpers = HELPERS.replace('/dev/kvm', '/dev/null') + result = shell(helpers + '\nPREVIOUS_VERSION=0.8.0\nuname() { case "$1" in -s) echo Linux;; -m) echo aarch64;; esac; }\nshow_ready "$1/elastos"', root) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertNotIn('setup --browser', result.stdout) def test_linux_install_leaves_browser_setup_to_the_owner(self): with tempfile.TemporaryDirectory() as scratch: diff --git a/scripts/install.sh b/scripts/install.sh index bd37d2988..3f68ee2c2 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -1048,6 +1048,21 @@ show_login_profile_lines() { done } +# Browser's one-time setup grants a per-user device ACL. Other open failures +# (for example a host/container restriction) need host support, not that ACL. +browser_kvm_access_available() { + [[ -c /dev/kvm ]] || return 1 + python3 - <<'PY_BROWSER_KVM' +import errno, os +try: + device = os.open('/dev/kvm', os.O_RDWR | os.O_CLOEXEC) +except OSError as error: + raise SystemExit(0 if error.errno == errno.EACCES else 1) +else: + os.close(device) +PY_BROWSER_KVM +} + show_ready() { local runtime_bin="$1" command elapsed command="$(runtime_command "$runtime_bin")" @@ -1056,12 +1071,8 @@ show_ready() { echo -e " ${GREEN}${BOLD}ElastOS ${RELEASE_VERSION:-} is ready${NC} ${DIM}(took ${elapsed})${NC}" printf ' %b%-12s%b %s\n' "$DIM" "Open Home" "$NC" "${command} home --browser" printf ' %b%-12s%b %s\n' "$DIM" "Update" "$NC" "${command} update" - if [[ "$(uname -s)" == Linux && "$(uname -m)" =~ ^(aarch64|arm64)$ ]]; then - if [[ -c /dev/kvm ]]; then - printf ' Browser is available on this computer. To turn it on, run: %s setup --browser\n' "$command" - else - printf ' Browser needs KVM on this computer. After KVM is available, run: %s setup --browser\n' "$command" - fi + if [[ -z "${PREVIOUS_VERSION:-}" && "$(uname -s)" == Linux && "$(uname -m)" =~ ^(aarch64|arm64)$ ]] && browser_kvm_access_available; then + printf ' Browser is available on this computer. To turn it on, run: %s setup --browser\n' "$command" fi if [[ "$command" != elastos ]]; then local label="Add to PATH" From ac38aa17e300f07b138fa8f7fdc756294317205b Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 5 Nov 2026 18:35:10 -0500 Subject: [PATCH 4/8] fix(browser): address opt-in review notes --- .../browser/browser/browser-status.test.mjs | 2 +- elastos/crates/elastos-server/src/setup.rs | 2 +- .../src/setup/browser_config.rs | 100 ------------------ scripts/install-bootstrap-test.py | 10 +- scripts/install.sh | 2 +- 5 files changed, 9 insertions(+), 107 deletions(-) diff --git a/capsules/browser/browser/browser-status.test.mjs b/capsules/browser/browser/browser-status.test.mjs index d90e50df5..6bb8d1eda 100644 --- a/capsules/browser/browser/browser-status.test.mjs +++ b/capsules/browser/browser/browser-status.test.mjs @@ -268,7 +268,7 @@ test("Linux host setup guidance names the opt-in command", () => { message: "Browser is available on this computer. To turn it on, run: elastos setup --browser. Then close Home and start it again with elastos home --browser.", }); assert.equal(friendlyOpenError(error), error.payload.message); - error.payload.message = "Browser needs KVM on this computer. After KVM is available, run: elastos setup --browser"; + error.payload.message = "Browser needs KVM on this computer. After KVM is available, run: elastos setup --browser. Then close Home and start it again with elastos home --browser."; assert.equal(friendlyOpenError(error), error.payload.message); error.payload.outcome.state = "cleanup_pending"; assert.doesNotMatch(friendlyOpenError(error), /elastos setup --browser/); diff --git a/elastos/crates/elastos-server/src/setup.rs b/elastos/crates/elastos-server/src/setup.rs index a09be98d1..400f73aa9 100644 --- a/elastos/crates/elastos-server/src/setup.rs +++ b/elastos/crates/elastos-server/src/setup.rs @@ -15,8 +15,8 @@ use std::path::{Path, PathBuf}; use std::process::Command; mod browser_config; +pub use browser_config::browser_available; pub(crate) use browser_config::linux_host_setup_message; -pub use browser_config::{browser_available, home_browser_available}; mod browser_linux; mod browser_vm_image; pub(crate) use browser_vm_image::start_background_verification as start_browser_image_verification; diff --git a/elastos/crates/elastos-server/src/setup/browser_config.rs b/elastos/crates/elastos-server/src/setup/browser_config.rs index 4fcd5cb44..5d64c7f90 100644 --- a/elastos/crates/elastos-server/src/setup/browser_config.rs +++ b/elastos/crates/elastos-server/src/setup/browser_config.rs @@ -188,45 +188,6 @@ pub fn browser_available(platform: &str) -> bool { matches!(platform, "darwin-arm64" | "linux-arm64") } -pub fn home_browser_available(data: &Path, platform: &str) -> bool { - home_browser_available_with_probe( - data, - platform, - std::env::var("ELASTOS_BROWSER_ENGINE_ADAPTER_CONFIG") - .ok() - .as_deref(), - || native_host_available(data).is_ok(), - ) -} - -fn home_browser_available_with_probe( - data: &Path, - platform: &str, - inline: Option<&str>, - native_available: impl FnOnce() -> bool, -) -> bool { - // Apple Silicon retains its existing local and approved remote Engines. - if platform == "darwin-arm64" { - return true; - } - if platform != "linux-arm64" { - return false; - } - let Ok(Some(config)) = read_engine_selection(data, inline) else { - return false; - }; - let native = data.join("bin/browser-vz-engine-supervisor"); - config["adapters"].as_array().is_some_and(|adapters| { - adapters.iter().any(|adapter| { - let supervisor = &adapter["supervisor"]; - let launcher = supervisor["env"]["ELASTOS_BROWSER_VM_CONTROL_LAUNCHER"] - .as_str() - .or_else(|| supervisor["program"].as_str()); - adapter["kind"] == "chromium_microvm" && launcher == native.to_str() - }) - }) && native_available() -} - fn native_host_available(data: &Path) -> anyhow::Result<()> { let program = data.join("bin/browser-vz-engine-supervisor"); super::verify_installed_component_binary(data, "browser-vz-engine-supervisor", &program)?; @@ -730,67 +691,6 @@ mod tests { use serde_json::Value; use sha2::Digest; - #[test] - fn arm_browser_requires_its_selected_managed_native_host() { - let data = Path::new("/fixture/elastos"); - let selected = |program: &str| { - serde_json::json!({"adapters":[{ - "kind":"chromium_microvm", "supervisor":{"env":{ - "ELASTOS_BROWSER_VM_CONTROL_LAUNCHER": program - }} - }]}) - .to_string() - }; - let native = selected("/fixture/elastos/bin/browser-vz-engine-supervisor"); - assert!(home_browser_available_with_probe( - data, - "linux-arm64", - Some(&native), - || true - )); - assert!(!home_browser_available_with_probe( - data, - "linux-arm64", - Some(&native), - || false - )); - for platform in ["linux-amd64", "darwin-amd64", "linux-riscv64"] { - assert!(!home_browser_available_with_probe( - data, - platform, - Some(&native), - || true - )); - } - for program in [ - "/other/browser-vz-engine-supervisor", - "/fixture/elastos/bin/browser-vm-local-crosvm-launcher", - "/fixture/elastos/bin/browser-vm-remote-vz-launcher", - ] { - assert!(!home_browser_available_with_probe( - data, - "linux-arm64", - Some(&selected(program)), - || true - )); - } - for raw in ["invalid", r#"{"adapters":[]}"#] { - assert!(!home_browser_available_with_probe( - data, - "linux-arm64", - Some(raw), - || true - )); - } - let remote = selected("/fixture/elastos/bin/browser-vm-remote-vz-launcher"); - assert!(home_browser_available_with_probe( - data, - "darwin-arm64", - Some(&remote), - || false - )); - } - #[test] fn native_host_probe_requires_its_contract_and_has_a_deadline() { use std::os::unix::fs::PermissionsExt; diff --git a/scripts/install-bootstrap-test.py b/scripts/install-bootstrap-test.py index 4459b02fa..26b685872 100644 --- a/scripts/install-bootstrap-test.py +++ b/scripts/install-bootstrap-test.py @@ -2054,13 +2054,15 @@ def test_linux_summary_distinguishes_acl_setup_from_host_open_failure(self): self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual('setup --browser' in result.stdout, hinted) - def test_linux_update_omits_browser_hint(self): + def test_linux_existing_install_omits_browser_hint(self): with tempfile.TemporaryDirectory() as scratch: root = Path(scratch) helpers = HELPERS.replace('/dev/kvm', '/dev/null') - result = shell(helpers + '\nPREVIOUS_VERSION=0.8.0\nuname() { case "$1" in -s) echo Linux;; -m) echo aarch64;; esac; }\nshow_ready "$1/elastos"', root) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertNotIn('setup --browser', result.stdout) + for previous_version in ['0.8.0', '']: + with self.subTest(previous_version=previous_version): + result = shell(helpers + '\nEXISTING_INSTALL=true\nPREVIOUS_VERSION="$2"\nuname() { case "$1" in -s) echo Linux;; -m) echo aarch64;; esac; }\nshow_ready "$1/elastos"', root, previous_version) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertNotIn('setup --browser', result.stdout) def test_linux_install_leaves_browser_setup_to_the_owner(self): with tempfile.TemporaryDirectory() as scratch: diff --git a/scripts/install.sh b/scripts/install.sh index c7c63ecb2..1a1d983f1 100755 --- a/scripts/install.sh +++ b/scripts/install.sh @@ -1209,7 +1209,7 @@ show_ready() { echo -e " ${GREEN}${BOLD}ElastOS ${RELEASE_VERSION:-} is ready${NC} ${DIM}(took ${elapsed})${NC}" printf ' %b%-12s%b %s\n' "$DIM" "Open Home" "$NC" "${command} home --browser" printf ' %b%-12s%b %s\n' "$DIM" "Update" "$NC" "${command} update" - if [[ -z "${PREVIOUS_VERSION:-}" && "$(uname -s)" == Linux && "$(uname -m)" =~ ^(aarch64|arm64)$ ]] && browser_kvm_access_available; then + if [[ "${EXISTING_INSTALL:-false}" == false && "$(uname -s)" == Linux && "$(uname -m)" =~ ^(aarch64|arm64)$ ]] && browser_kvm_access_available; then printf ' Browser is available on this computer. To turn it on, run: %s setup --browser\n' "$command" fi if [[ "$command" != elastos ]]; then From 10dec7c60936c837dd480231fd091930a63d1b28 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Thu, 5 Nov 2026 19:30:11 -0500 Subject: [PATCH 5/8] test(browser): match ARM64 opt-in catalog visibility --- .../src/api/gateway_capsule_catalog.rs | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_capsule_catalog.rs b/elastos/crates/elastos-server/src/api/gateway_capsule_catalog.rs index 39dc97328..6fdccf1aa 100644 --- a/elastos/crates/elastos-server/src/api/gateway_capsule_catalog.rs +++ b/elastos/crates/elastos-server/src/api/gateway_capsule_catalog.rs @@ -1428,13 +1428,16 @@ mod tests { "expected the first-party development capsule set to be visible" ); - for platform in ["linux-arm64", "linux-amd64"] { - // Where Browser is unavailable it is absent, not merely unlaunchable. - assert!( - !read_model::capsule_catalog_summary_for(data_dir.path(), platform) + for (platform, browser_listed) in [("linux-arm64", true), ("linux-amd64", false)] { + // Linux ARM64 lists Browser so opening it shows the setup command. + // Linux AMD64 has no supported Browser Engine and keeps it absent. + assert_eq!( + read_model::capsule_catalog_summary_for(data_dir.path(), platform) .capsules .iter() - .any(|capsule| capsule.name == "browser") + .any(|capsule| capsule.name == "browser"), + browser_listed, + "Browser catalog visibility on {platform}" ); } let catalog = read_model::capsule_catalog_summary_for(data_dir.path(), "darwin-arm64"); From e7d1ded6dd8cc257038b07ce3fac03b1cfb26189 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 6 Nov 2026 02:47:11 -0500 Subject: [PATCH 6/8] fix(browser): bind root helper setup to admitted bytes Keep the signed release digest with the captured helper bytes. Install and reverify an owned copy in one sudo step, then execute the verified snapshot with the helper confirmation on the tty. Verified: 6 Linux setup unit tests, 7 root bootstrap tests, all-target Clippy, formatting and the source gate. The full server rerun uses the CI process-provider fixtures. --- .../elastos-server/src/setup/browser_linux.rs | 232 +++++++++++++----- .../src/setup/browser_linux_root.py | 98 ++++++++ scripts/browser-root-helper.test.py | 127 ++++++++++ scripts/test-source-gate.sh | 1 + 4 files changed, 394 insertions(+), 64 deletions(-) create mode 100644 elastos/crates/elastos-server/src/setup/browser_linux_root.py create mode 100644 scripts/browser-root-helper.test.py diff --git a/elastos/crates/elastos-server/src/setup/browser_linux.rs b/elastos/crates/elastos-server/src/setup/browser_linux.rs index 3783fe598..706796d6f 100644 --- a/elastos/crates/elastos-server/src/setup/browser_linux.rs +++ b/elastos/crates/elastos-server/src/setup/browser_linux.rs @@ -1,4 +1,5 @@ //! The Linux owner explicitly grants Browser host access before image acquisition. +use std::io::{Read as _, Write as _}; use std::path::Path; use std::process::{Command, Stdio}; @@ -7,6 +8,8 @@ pub(crate) const SETUP_MESSAGE: &str = "Browser is available on this computer. To turn it on, run: elastos setup --browser. Then close Home and start it again with elastos home --browser."; pub(crate) const KVM_MESSAGE: &str = "Browser needs KVM on this computer. After KVM is available, run: elastos setup --browser. Then close Home and start it again with elastos home --browser."; +const ROOT_BOOTSTRAP: &str = include_str!("browser_linux_root.py"); +const MAX_HELPER_BYTES: u64 = 1024 * 1024; const ROOT_HELPER: &str = "/usr/local/lib/elastos/browser-vm-linux-network.py"; /// Keep ordinary Home setup and Browser open free of administrator operations. @@ -34,25 +37,12 @@ pub(super) async fn enable(data: &Path, platform: &str) -> anyhow::Result<()> { super::FirstPartyCarrierContext::Setup, ) .await?; - let helper = data.join("scripts/browser-vm-linux-network.py"); - super::verify_installed_component_binary(data, "browser-vm-linux-network", &helper)?; - let user = Command::new("id").arg("-un").output()?; + let (checksum, payload) = read_admitted_helper(data, platform)?; + let user = Command::new("/usr/bin/id").arg("-un").output()?; anyhow::ensure!(user.status.success(), "Could not identify the Home user"); let user = String::from_utf8(user.stdout)?; enable_with( - || { - setup_host_with(data, user.trim(), |program, args, quiet| { - let mut command = Command::new(program); - command.args(args); - if quiet { - command - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()); - } - Ok(command.status()?.success()) - }) - }, + || setup_host_with(data, user.trim(), &checksum, &payload, run_host_command), || async { super::browser_config::require_linux_host(data)?; println!("Preparing Browser Engine image..."); @@ -134,10 +124,81 @@ where prepare_image().await } +/// The expected digest belongs to the admitted release, independently of the +/// user-owned helper. Capture bounded bytes once, before sudo can prompt. +fn read_admitted_helper(data: &Path, platform: &str) -> anyhow::Result<(String, Vec)> { + let admitted = super::admit_installed_components(data, super::FirstPartyCarrierContext::Setup)? + .ok_or_else(|| { + anyhow::anyhow!("Browser administrator setup requires an installed signed release") + })?; + let name = "browser-vm-linux-network"; + let component = + admitted.manifest.external.get(name).ok_or_else(|| { + anyhow::anyhow!("Signed release is missing the Browser network helper") + })?; + let info = super::resolve_platform_info(component, platform).ok_or_else(|| { + anyhow::anyhow!("Signed release has no Browser network helper for {platform}") + })?; + anyhow::ensure!( + info.extract_path.is_none(), + "Browser network helper requires a signed plain file" + ); + let row = admitted.admission.row(name, info)?; + let checksum = row + .info() + .checksum + .as_deref() + .and_then(|checksum| checksum.strip_prefix("sha256:")) + .ok_or_else(|| anyhow::anyhow!("Browser network helper requires an admitted SHA-256"))?; + let mut payload = Vec::new(); + std::fs::File::open(data.join("scripts/browser-vm-linux-network.py"))? + .take(MAX_HELPER_BYTES + 1) + .read_to_end(&mut payload)?; + anyhow::ensure!( + payload.len() as u64 <= MAX_HELPER_BYTES, + "Browser network helper exceeds its size limit" + ); + super::verify_checksum(name, &payload, row.info())?; + Ok((checksum.to_owned(), payload)) +} + +fn run_host_command( + program: &str, + args: &[&std::ffi::OsStr], + payload: Option<&[u8]>, + quiet: bool, +) -> anyhow::Result { + let mut command = Command::new(program); + command.args(args); + if quiet { + command + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + } + if let Some(payload) = payload { + // sudo keeps its default controlling-tty password prompt. Its stdin + // carries only the captured data to the fixed, embedded bootstrap. + let mut child = command.stdin(Stdio::piped()).spawn()?; + let written = child + .stdin + .take() + .expect("piped helper input") + .write_all(payload); + let status = child.wait()?; + written?; + Ok(status.success()) + } else { + Ok(command.status()?.success()) + } +} + fn setup_host_with( data: &Path, user: &str, - mut run: impl FnMut(&str, &[&std::ffi::OsStr], bool) -> anyhow::Result, + checksum: &str, + payload: &[u8], + mut run: impl FnMut(&str, &[&std::ffi::OsStr], Option<&[u8]>, bool) -> anyhow::Result, ) -> anyhow::Result<()> { use std::ffi::OsStr; let helper = data.join("scripts/browser-vm-linux-network.py"); @@ -148,47 +209,33 @@ fn setup_host_with( OsStr::new("--data-dir"), data.as_os_str(), ]; - if run("/usr/bin/python3", &check, true)? { - return Ok(()); + let needs_setup = !run("/usr/bin/python3", &check, None, true)?; + if needs_setup { + println!( + "Browser needs one-time administrator setup for KVM and its private network devices." + ); + println!("The setup shows its changes and asks for confirmation. Runtime then runs as your user."); } - println!("Browser needs one-time administrator setup for KVM and its private network devices."); - println!( - "The setup shows its changes and asks for confirmation. Runtime then runs as your user." - ); + // Always replace/verify the root copy, including an already prepared host: + // the printed removal command and boot service use only this owned file. let install = [ - OsStr::new("install"), - OsStr::new("-D"), - OsStr::new("-o"), - OsStr::new("root"), - OsStr::new("-g"), - OsStr::new("root"), - OsStr::new("-m"), - OsStr::new("755"), - helper.as_os_str(), - OsStr::new(ROOT_HELPER), - ]; - anyhow::ensure!( - run("sudo", &install, false)?, - "Browser helper installation stopped. Retry with {ENABLE_COMMAND}" - ); - let setup = [ OsStr::new("/usr/bin/python3"), OsStr::new("-I"), - OsStr::new(ROOT_HELPER), - OsStr::new("setup"), - OsStr::new("--user"), + OsStr::new("-c"), + OsStr::new(ROOT_BOOTSTRAP), + OsStr::new(checksum), OsStr::new(user), - OsStr::new("--data-dir"), data.as_os_str(), + OsStr::new(if needs_setup { "setup" } else { "install" }), ]; anyhow::ensure!( - run("sudo", &setup, false)?, + run("/usr/bin/sudo", &install, Some(payload), false)?, "Browser administrator setup stopped. Retry with {ENABLE_COMMAND}" ); // The helper returns success when confirmation is declined. Prove access // before downloading an image, including that declined case. anyhow::ensure!( - run("/usr/bin/python3", &check, true)?, + run("/usr/bin/python3", &check, None, true)?, "Browser host access still needs setup. Run {ENABLE_COMMAND} and confirm its changes" ); Ok(()) @@ -257,14 +304,68 @@ mod tests { assert!(!data.exists()); } + #[test] + fn privileged_handoff_refuses_user_path_replacement() { + use sha2::Digest as _; + let temp = tempfile::tempdir().unwrap(); + let data = temp.path(); + let helper = data.join("scripts/browser-vm-linux-network.py"); + std::fs::create_dir_all(helper.parent().unwrap()).unwrap(); + std::fs::write(&helper, b"admitted").unwrap(); + let payload = std::fs::read(&helper).unwrap(); + let expected = format!("{:x}", sha2::Sha256::digest(&payload)); + let mut checks = 0; + let mut privileged = Vec::new(); + setup_host_with( + data, + "home-user", + &expected, + &payload, + |program, args, stdin, quiet| { + if program != "/usr/bin/sudo" { + checks += 1; + assert!(stdin.is_none() && quiet); + return Ok(checks > 1); + } + // The same account swaps the user path during the sudo password wait. + std::fs::write(&helper, b"changed!").unwrap(); + assert!(!quiet); + assert_eq!(args[0], "/usr/bin/python3"); + assert_eq!(args[3], ROOT_BOOTSTRAP); + assert!(!args.contains(&helper.as_os_str())); + let received = stdin.unwrap(); + let digest = format!("{:x}", sha2::Sha256::digest(received)); + if Some(digest.as_str()) != args[4].to_str() { + return Ok(false); + } + privileged.extend_from_slice(received); + Ok(true) + }, + ) + .unwrap(); + assert_eq!(std::fs::read(helper).unwrap(), b"changed!"); + assert_eq!(privileged, b"admitted"); + assert_eq!(checks, 2); + } + + #[test] + fn privileged_handoff_requires_signed_release_instead_of_local_digest() { + let temp = tempfile::tempdir().unwrap(); + std::fs::write(temp.path().join("components.json"), b"{}").unwrap(); + assert!(read_admitted_helper(temp.path(), "linux-arm64") + .unwrap_err() + .to_string() + .contains("requires an installed signed release")); + } + #[tokio::test] async fn explicit_browser_setup_runs_root_helper_before_image_and_checks_decline() { for (statuses, prepares) in [ - (vec![true], true), - (vec![false, true, true, true], true), + (vec![true, true, true], true), + (vec![false, true, true], true), (vec![false, false], false), + (vec![true, false], false), (vec![false, true, false], false), - (vec![false, true, true, false], false), ] { let calls = RefCell::new(Vec::new()); let mut results = statuses.into_iter(); @@ -273,10 +374,23 @@ mod tests { setup_host_with( Path::new("/fixture/home with spaces"), "home-user", - |program, args, quiet| { - calls - .borrow_mut() - .push(format!("{program} {:?} quiet={quiet}", args)); + &"a".repeat(64), + b"admitted", + |program, args, stdin, quiet| { + if program == "/usr/bin/sudo" { + assert_eq!(args[0], "/usr/bin/python3"); + assert_eq!(args[1], "-I"); + assert_eq!(args[2], "-c"); + assert_eq!(args[3], ROOT_BOOTSTRAP); + assert!(ROOT_BOOTSTRAP.contains(ROOT_HELPER)); + assert_eq!(args[4], "a".repeat(64).as_str()); + assert_eq!(args[5], "home-user"); + assert_eq!(args[6], "/fixture/home with spaces"); + assert!(args[7] == "setup" || args[7] == "install"); + assert_eq!(stdin, Some(b"admitted".as_slice())); + assert!(!quiet); + } + calls.borrow_mut().push(program.to_owned()); Ok(results.next().unwrap()) }, ) @@ -290,18 +404,8 @@ mod tests { assert_eq!(result.is_ok(), prepares); let calls = calls.into_inner(); assert_eq!(calls.last().unwrap() == "image", prepares); - if calls.len() == 5 { - assert!(calls[1].starts_with("sudo [\"install\", \"-D\"")); - assert!(calls[1] - .contains("/fixture/home with spaces/scripts/browser-vm-linux-network.py")); - assert!(calls[2].starts_with(&format!( - "sudo [\"/usr/bin/python3\", \"-I\", \"{ROOT_HELPER}\", \"setup\"" - ))); - assert!(calls[2].contains( - "\"--user\", \"home-user\", \"--data-dir\", \"/fixture/home with spaces\"" - )); - assert!(calls[3].starts_with("/usr/bin/python3")); - } + assert_eq!(calls[0], "/usr/bin/python3"); + assert_eq!(calls[1], "/usr/bin/sudo"); } } } diff --git a/elastos/crates/elastos-server/src/setup/browser_linux_root.py b/elastos/crates/elastos-server/src/setup/browser_linux_root.py new file mode 100644 index 000000000..783295275 --- /dev/null +++ b/elastos/crates/elastos-server/src/setup/browser_linux_root.py @@ -0,0 +1,98 @@ +"""Fixed Runtime bootstrap: stdin carries data, never privileged Python code.""" +import hashlib +import os +import re +import stat +import sys +import uuid + +ROOT_HELPER = '/usr/local/lib/elastos/browser-vm-linux-network.py' +MAX_HELPER_BYTES = 1024 * 1024 + + +def trusted_directory(path, owner): + """Walk from / through owned, non-writable directories without following links.""" + directory = os.open('/', os.O_RDONLY | os.O_DIRECTORY) + try: + metadata = os.fstat(directory) + if metadata.st_uid != owner or metadata.st_mode & 0o022: + raise RuntimeError('Browser helper requires root-owned directories') + for part in path.strip('/').split('/'): + try: + os.mkdir(part, mode=0o755, dir_fd=directory) + except FileExistsError: + pass + child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, + dir_fd=directory) + os.close(directory) + directory = child + metadata = os.fstat(directory) + if metadata.st_uid != owner or metadata.st_mode & 0o022: + raise RuntimeError('Browser helper requires root-owned directories') + return directory + except BaseException: + os.close(directory) + raise + + +def verified_copy(directory, name, expected, payload, owner): + """Replace stale copies atomically; return bytes read back from the owned inode.""" + if not re.fullmatch(r'[0-9a-f]{64}', expected): + raise RuntimeError('Browser helper requires its admitted SHA-256') + if len(payload) > MAX_HELPER_BYTES or hashlib.sha256(payload).hexdigest() != expected: + raise RuntimeError('Browser helper differs from its admitted SHA-256') + metadata = os.fstat(directory) + if metadata.st_uid != owner or metadata.st_mode & 0o022: + raise RuntimeError('Browser helper requires a root-owned directory') + temporary = '.browser-helper-' + uuid.uuid4().hex + fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, + 0o600, dir_fd=directory) + try: + with os.fdopen(fd, 'wb') as output: + output.write(payload) + output.flush() + os.fchmod(output.fileno(), 0o644) + os.fsync(output.fileno()) + os.rename(temporary, name, src_dir_fd=directory, dst_dir_fd=directory) + finally: + try: + os.unlink(temporary, dir_fd=directory) + except FileNotFoundError: + pass + fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory) + with os.fdopen(fd, 'rb') as installed: + metadata = os.fstat(installed.fileno()) + if (not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != owner + or metadata.st_mode & 0o022): + raise RuntimeError('Browser helper requires a root-owned regular file') + verified = installed.read(MAX_HELPER_BYTES + 1) + if hashlib.sha256(verified).hexdigest() != expected: + raise RuntimeError('Root Browser helper differs from its admitted SHA-256') + return verified + + +def main(): + if os.geteuid() != 0: + raise RuntimeError('Browser host setup requires root') + expected, user, data, action = sys.argv[1:] + if action not in ('install', 'setup'): + raise RuntimeError('Invalid Browser host action') + payload = sys.stdin.buffer.read(MAX_HELPER_BYTES + 1) + directory = trusted_directory(os.path.dirname(ROOT_HELPER), 0) + try: + verified = verified_copy(directory, os.path.basename(ROOT_HELPER), expected, payload, 0) + finally: + os.close(directory) + if action == 'install': + return + # sudo reads its password from the controlling tty. The helper keeps its own + # confirmation on that tty after the payload pipe reaches EOF. + sys.stdin = open('/dev/tty', encoding='utf-8') + sys.argv = [ROOT_HELPER, 'setup', '--user', user, '--data-dir', data] + # Compile the bytes read from the verified root inode, without reopening a path. + exec(compile(verified, ROOT_HELPER, 'exec'), + {'__name__': '__main__', '__file__': ROOT_HELPER}) + + +if __name__ == '__main__': + main() diff --git a/scripts/browser-root-helper.test.py b/scripts/browser-root-helper.test.py new file mode 100644 index 000000000..def376efb --- /dev/null +++ b/scripts/browser-root-helper.test.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +"""Exercise Runtime's actual privileged bootstrap without granting root.""" +import hashlib +import importlib.util +import io +import os +from pathlib import Path +import tempfile +import unittest +from unittest.mock import patch +import sys + +SOURCE = (Path(__file__).resolve().parents[1] / 'elastos/crates/elastos-server/src/setup' + / 'browser_linux_root.py') +SPEC = importlib.util.spec_from_file_location('browser_linux_root', SOURCE) +ROOT = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(ROOT) + + +class RootHelperTests(unittest.TestCase): + def test_setup_keeps_the_helper_confirmation_on_the_tty(self): + with tempfile.TemporaryDirectory() as temporary: + directory = os.open(temporary, os.O_RDONLY | os.O_DIRECTORY) + self.addCleanup(os.close, directory) + payload = b"assert input('Continue? [y/N] ') == 'y'\n" + expected = hashlib.sha256(payload).hexdigest() + verified_copy = ROOT.verified_copy + # Model root's ownership with the fixture account; the real copy, + # read-back digest and execution path all run unchanged. + def copy_as_fixture(fd, name, digest, contents, owner): + self.assertEqual(owner, 0) + self.assertEqual(digest, expected) + return verified_copy(fd, name, digest, contents, os.getuid()) + with (patch.object(ROOT.os, 'geteuid', return_value=0), + patch.object(ROOT, 'trusted_directory', return_value=os.dup(directory)), + patch.object(ROOT, 'verified_copy', side_effect=copy_as_fixture), + patch.object(sys, 'argv', ['bootstrap', expected, 'fixture', temporary, 'setup']), + patch.object(sys, 'stdin', io.TextIOWrapper(io.BytesIO(payload))), + patch('builtins.open', return_value=io.StringIO('y\n')) as tty, + patch.object(sys, 'stdout', io.StringIO()) as output): + ROOT.main() + tty.assert_called_once_with('/dev/tty', encoding='utf-8') + self.assertIn('Continue? [y/N]', output.getvalue()) + + def test_copy_accepts_only_admitted_bytes_and_replaces_stale_root_copy(self): + for existing in (None, b'stale root helper'): + with self.subTest(existing=existing), tempfile.TemporaryDirectory() as temporary: + path = Path(temporary) / 'helper.py' + if existing is not None: + path.write_bytes(existing) + directory = os.open(temporary, os.O_RDONLY | os.O_DIRECTORY) + self.addCleanup(os.close, directory) + payload = b'print("admitted")\n' + expected = hashlib.sha256(payload).hexdigest() + verified = ROOT.verified_copy(directory, path.name, expected, payload, os.getuid()) + self.assertEqual(verified, payload) + self.assertEqual(path.read_bytes(), payload) + self.assertEqual(path.stat().st_mode & 0o777, 0o644) + + def test_changed_payload_is_refused_before_replacing_or_executing_root_copy(self): + with tempfile.TemporaryDirectory() as temporary: + path = Path(temporary) / 'helper.py' + path.write_bytes(b'previous admitted root helper') + directory = os.open(temporary, os.O_RDONLY | os.O_DIRECTORY) + self.addCleanup(os.close, directory) + expected = hashlib.sha256(b'admitted').hexdigest() + with self.assertRaisesRegex(RuntimeError, 'admitted SHA-256'): + ROOT.verified_copy(directory, path.name, expected, b'changed!', os.getuid()) + self.assertEqual(path.read_bytes(), b'previous admitted root helper') + + def test_existing_symlink_is_replaced_without_reading_or_writing_its_target(self): + with tempfile.TemporaryDirectory() as temporary: + target = Path(temporary) / 'outside' + target.write_bytes(b'keep') + path = Path(temporary) / 'helper.py' + path.symlink_to(target) + directory = os.open(temporary, os.O_RDONLY | os.O_DIRECTORY) + self.addCleanup(os.close, directory) + payload = b'admitted' + ROOT.verified_copy(directory, path.name, hashlib.sha256(payload).hexdigest(), + payload, os.getuid()) + self.assertFalse(path.is_symlink()) + self.assertEqual(path.read_bytes(), payload) + self.assertEqual(target.read_bytes(), b'keep') + + def test_writable_or_foreign_directory_is_refused(self): + with tempfile.TemporaryDirectory() as temporary: + directory = os.open(temporary, os.O_RDONLY | os.O_DIRECTORY) + self.addCleanup(os.close, directory) + payload = b'admitted' + expected = hashlib.sha256(payload).hexdigest() + with self.assertRaisesRegex(RuntimeError, 'root-owned directory'): + ROOT.verified_copy(directory, 'helper.py', expected, payload, os.getuid() + 1) + os.chmod(temporary, 0o777) + with self.assertRaisesRegex(RuntimeError, 'root-owned directory'): + ROOT.verified_copy(directory, 'helper.py', expected, payload, os.getuid()) + + def test_root_copy_is_reverified_before_any_helper_execution(self): + with tempfile.TemporaryDirectory() as temporary: + directory = os.open(temporary, os.O_RDONLY | os.O_DIRECTORY) + self.addCleanup(os.close, directory) + payload = b'admitted' + expected = hashlib.sha256(payload).hexdigest() + rename = os.rename + def corrupt_after_write(*args, **kwargs): + rename(*args, **kwargs) + (Path(temporary) / 'helper.py').write_bytes(b'changed!') + with patch.object(ROOT.os, 'rename', side_effect=corrupt_after_write): + with self.assertRaisesRegex(RuntimeError, 'Root Browser helper differs'): + ROOT.verified_copy(directory, 'helper.py', expected, payload, os.getuid()) + + def test_directory_walk_refuses_symlink(self): + with tempfile.TemporaryDirectory() as temporary: + link = Path(temporary) / 'link' + link.symlink_to(temporary) + # Start from this process's trusted fixture directory, so the test + # works on macOS (/var is a symlink) and Linux alike. + real_open = os.open + def fixture_open(path, *args, **kwargs): + return real_open(temporary if path == '/' else path, *args, **kwargs) + with patch.object(ROOT.os, 'open', side_effect=fixture_open): + with self.assertRaises(OSError): + ROOT.trusted_directory('/link', os.getuid()) + + +if __name__ == '__main__': + unittest.main() diff --git a/scripts/test-source-gate.sh b/scripts/test-source-gate.sh index d92921fa0..88f5ab445 100755 --- a/scripts/test-source-gate.sh +++ b/scripts/test-source-gate.sh @@ -38,6 +38,7 @@ release() { python3 scripts/release-platform-input-test.py python3 scripts/prepare-release-platform-test.py python3 scripts/browser-vm-linux-network.test.py + python3 scripts/browser-root-helper.test.py python3 scripts/owned-removal-test.py python3 scripts/setup-source-home-native-browser-test.py bash scripts/setup-source-home-browser-artifacts-smoke.sh From 8f40786795470c1405c62144e587089144bd3625 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 6 Nov 2026 02:47:11 -0500 Subject: [PATCH 7/8] fix(browser): repair enabled helpers before Open readiness Normalize the adapter choice before preparation. An existing local Engine selection admits helper repair before the host probe; a fresh Home keeps the setup refusal before downloads. Verified: 4 actual Open consumer regressions, all-target Clippy, formatting, 1286 Browser Node tests and the source gate. --- .../elastos-server/src/api/gateway_browser.rs | 33 +++-- .../src/api/gateway_browser_route_tests.rs | 131 ++++++++++++++++++ elastos/crates/elastos-server/src/setup.rs | 1 + .../src/setup/browser_config.rs | 24 ++++ 4 files changed, 177 insertions(+), 12 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_browser.rs b/elastos/crates/elastos-server/src/api/gateway_browser.rs index 1f86ad7d0..eb684bd1b 100644 --- a/elastos/crates/elastos-server/src/api/gateway_browser.rs +++ b/elastos/crates/elastos-server/src/api/gateway_browser.rs @@ -87,7 +87,7 @@ pub(super) struct BrowserProviderResourceCall { } #[derive(Debug)] -struct BrowserOpenFailure { +pub(in crate::api::gateway) struct BrowserOpenFailure { status: StatusCode, body: BrowserOpenFailureBody, outcome: serde_json::Value, @@ -194,7 +194,7 @@ impl BrowserOpenFailure { (status, Json(self.status_value())).into_response() } - fn status_value(&self) -> serde_json::Value { + pub(in crate::api::gateway) fn status_value(&self) -> serde_json::Value { let mut value = match &self.body { BrowserOpenFailureBody::Text(message) => serde_json::json!({ "schema": "elastos.browser.open-error/v1", @@ -459,6 +459,7 @@ pub(super) async fn browser_app_open( input, home_token, request_origin, + &crate::setup::detect_platform(), ) .await { @@ -485,6 +486,7 @@ pub(super) async fn browser_app_open( input, home_token, request_origin, + &crate::setup::detect_platform(), ) .await { @@ -581,13 +583,14 @@ fn browser_host_setup_failure( }) } -async fn execute_browser_open( +pub(in crate::api::gateway) async fn execute_browser_open( state: &GatewayState, context: HomeLaunchTokenContext, authority: RuntimeWalletAuthority, input: BrowserOpenRequest, home_token: Option, request_origin: Option, + platform: &str, ) -> Result { let BrowserOpenRequest { url: requested_url, @@ -615,11 +618,21 @@ async fn execute_browser_open( err.to_string(), )); } - if let Some(failure) = browser_host_setup_failure( - &state.data_dir, - &crate::setup::detect_platform(), - adapter_id.as_deref(), - ) { + let requested_adapter_id = match browser_engine_adapter_id(adapter_id) { + Ok(value) => value, + Err(message) => return Err(BrowserOpenFailure::text(StatusCode::BAD_REQUEST, message)), + }; + if requested_adapter_id + .as_deref() + .is_none_or(|id| id == "browser-vm-product") + { + crate::setup::repair_browser_host_components_for_open(&state.data_dir, platform) + .await + .map_err(|error| BrowserOpenFailure::provider("browser-engine", error))?; + } + if let Some(failure) = + browser_host_setup_failure(&state.data_dir, platform, requested_adapter_id.as_deref()) + { return Err(failure); } let registry = match state.provider_registry.as_ref().cloned() { @@ -641,10 +654,6 @@ async fn execute_browser_open( Ok(value) => value, Err(message) => return Err(BrowserOpenFailure::text(StatusCode::BAD_REQUEST, message)), }; - let requested_adapter_id = match browser_engine_adapter_id(adapter_id) { - Ok(value) => value, - Err(message) => return Err(BrowserOpenFailure::text(StatusCode::BAD_REQUEST, message)), - }; let browser_instance = match browser_instance_id(browser_instance) { Ok(value) => value, Err(message) => return Err(BrowserOpenFailure::text(StatusCode::BAD_REQUEST, message)), diff --git a/elastos/crates/elastos-server/src/api/gateway_browser_route_tests.rs b/elastos/crates/elastos-server/src/api/gateway_browser_route_tests.rs index e40e8719b..f37412e02 100644 --- a/elastos/crates/elastos-server/src/api/gateway_browser_route_tests.rs +++ b/elastos/crates/elastos-server/src/api/gateway_browser_route_tests.rs @@ -9748,3 +9748,134 @@ async fn test_browser_operator_inspection_fill_bootstrap_and_detach_scope() { ); } } + +#[tokio::test] +async fn browser_open_repairs_missing_helpers_after_viewer_load() { + browser_open_repairs_helpers_after_viewer_load(false, true, None).await; +} + +#[tokio::test] +async fn browser_open_repairs_stale_helpers_after_viewer_load() { + browser_open_repairs_helpers_after_viewer_load(true, true, Some("browser-vm-product")).await; +} + +#[tokio::test] +async fn browser_open_fresh_linux_home_refuses_before_helper_acquisition() { + browser_open_repairs_helpers_after_viewer_load(false, false, None).await; +} + +#[tokio::test] +async fn browser_open_fresh_linux_home_refuses_before_helper_acquisition_with_padded_adapter() { + browser_open_repairs_helpers_after_viewer_load(false, false, Some(" browser-vm-product ")) + .await; +} + +async fn browser_open_repairs_helpers_after_viewer_load( + stale: bool, + enabled: bool, + adapter_id: Option<&str>, +) { + use sha2::Digest as _; + use std::os::unix::fs::PermissionsExt; + let temp = tempfile::tempdir().unwrap(); + let data = temp.path().canonicalize().unwrap(); + std::fs::create_dir_all(data.join("config")).unwrap(); + std::fs::write( + data.join("config/browser-engine-adapter.json"), + serde_json::to_vec( + &json!({"adapters":[{"kind":"chromium_microvm","supervisor":{ + "program":data.join("bin/browser-vz-engine-supervisor") + }}]}), + ) + .unwrap(), + ) + .unwrap(); + let helpers = [ + ("browser-vz-engine-supervisor", "bin/browser-vz-engine-supervisor", + b"#!/bin/sh\nprintf '%s' '{\"schema\":\"elastos.browser.vm-host-capabilities/v1\",\"available\":false}'\n".as_slice()), + ("browser-vm-linux-network", "scripts/browser-vm-linux-network.py", b"# admitted network helper\n".as_slice()), + ]; + let mut manifest = json!({"schema":"elastos.components/v1", "capsules":{}, + "profiles":{"browser-host":{"components":["browser-vz-engine-supervisor","browser-vm-linux-network"]}}, + "external":{}}); + let mut artifacts = HashMap::new(); + for (name, relative, bytes) in helpers { + let digest = Sha256::digest(bytes); + let cid = cid::Cid::new_v1( + 0x55, + cid::multihash::Multihash::<64>::wrap(0x12, &digest).unwrap(), + ) + .to_string(); + manifest["external"][name] = json!({"install_path":relative,"platforms":{"*":{ + "release_path":name,"checksum":format!("sha256:{digest:x}"),"size":bytes.len(),"cid":cid + }}}); + artifacts.insert(cid, bytes.to_vec()); + let path = data.join(relative); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(&path, bytes).unwrap(); + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + std::fs::write( + data.join("components.json"), + serde_json::to_vec(&manifest).unwrap(), + ) + .unwrap(); + let source = serde_json::from_value(json!({"name":"fixture", + "publisher_dids":[elastos_identity::derive_did(&[217;32]).1], + "connect_ticket":"", "publisher_node_id":""})) + .unwrap(); + let (_, server, serving) = + crate::setup::tests::carrier_cid_source(&data, &source, artifacts).await; + let owner = passkey_authority_with_name(&data, Some("helper-repair")); + // The viewer already holds its launch token. Open must repair independently + // of the capsule's earlier Home launch preparation. + let token = app_token_for_authority(&data, BROWSER_CAPSULE_ID, &owner); + let authority = runtime_wallet_authority_for_app_token(&data, BROWSER_CAPSULE_ID, &token); + let state = browser_engine_attached_test_state(&data).await; + for (_, relative, bytes) in helpers { + if stale { + std::fs::write(data.join(relative), vec![b'x'; bytes.len()]).unwrap(); + } else { + std::fs::remove_file(data.join(relative)).unwrap(); + } + } + if !enabled { + std::fs::remove_file(data.join("config/browser-engine-adapter.json")).unwrap(); + } + let input = serde_json::from_value( + json!({"url":"https://example.com/", "adapter_id":adapter_id, + "display_mode":"webrtc_remote_display", "guarantee_level":"operator_rbi"}), + ) + .unwrap(); + let result = super::super::gateway_browser::execute_browser_open( + &state, + authority.home_launch_context(), + authority, + input, + Some(token), + Some("null".into()), + "linux-arm64", + ) + .await; + // This fixture deliberately has no host capability. Repair must finish + // before that refusal, while image acquisition and VM effects stay gated. + let failure = result.unwrap_err(); + assert_eq!( + failure.status_value()["code"], + "browser_host_setup_required" + ); + for (_, relative, bytes) in helpers { + if enabled { + assert_eq!( + std::fs::read(data.join(relative)).ok().as_deref(), + Some(bytes), + "Open must repair {relative}" + ); + } else { + assert!(!data.join(relative).exists()); + } + } + assert!(!data.join("browser-vm").exists()); + server.close().await; + assert_eq!(serving.await.unwrap().len(), if enabled { 2 } else { 0 }); +} diff --git a/elastos/crates/elastos-server/src/setup.rs b/elastos/crates/elastos-server/src/setup.rs index 400f73aa9..57c051387 100644 --- a/elastos/crates/elastos-server/src/setup.rs +++ b/elastos/crates/elastos-server/src/setup.rs @@ -17,6 +17,7 @@ use std::process::Command; mod browser_config; pub use browser_config::browser_available; pub(crate) use browser_config::linux_host_setup_message; +pub(crate) use browser_config::repair_browser_host_components_for_open; mod browser_linux; mod browser_vm_image; pub(crate) use browser_vm_image::start_background_verification as start_browser_image_verification; diff --git a/elastos/crates/elastos-server/src/setup/browser_config.rs b/elastos/crates/elastos-server/src/setup/browser_config.rs index 5d64c7f90..3f66b14a7 100644 --- a/elastos/crates/elastos-server/src/setup/browser_config.rs +++ b/elastos/crates/elastos-server/src/setup/browser_config.rs @@ -13,6 +13,30 @@ const CONFIG_FILES: [&str; 4] = [ ]; const RETIRED_SELECTION: &[u8] = b"{\"adapters\": []}\n"; +/// A loaded viewer can Open again after a helper was removed or updated. +/// An existing local selection grants repair; a fresh Home keeps its opt-in gate. +pub(crate) async fn repair_browser_host_components_for_open( + data: &Path, + platform: &str, +) -> anyhow::Result<()> { + if !local_vm_configured(data, platform)? { + return Ok(()); + } + let bytes = match fs::read(data.join("components.json")) { + Ok(bytes) => bytes, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error.into()), + }; + let manifest = serde_json::from_slice(&bytes)?; + ensure_host_components( + data, + &manifest, + platform, + super::FirstPartyCarrierContext::Runtime, + ) + .await +} + /// Opening Browser admits its host support files from the installed signed release. /// The base Home profile stays small; each helper keeps the normal checksum gate. pub(super) async fn ensure_host_components( From b6093f8c2092aa7a82384c2c6486ba2856f3883c Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Fri, 6 Nov 2026 03:58:58 -0500 Subject: [PATCH 8/8] test(browser): cover helper replacement before privileged handoff --- .../elastos-server/src/setup/browser_linux.rs | 6 ++-- scripts/browser-root-helper.test.py | 33 +++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/elastos/crates/elastos-server/src/setup/browser_linux.rs b/elastos/crates/elastos-server/src/setup/browser_linux.rs index 706796d6f..617e48e85 100644 --- a/elastos/crates/elastos-server/src/setup/browser_linux.rs +++ b/elastos/crates/elastos-server/src/setup/browser_linux.rs @@ -325,10 +325,12 @@ mod tests { if program != "/usr/bin/sudo" { checks += 1; assert!(stdin.is_none() && quiet); + if checks == 1 { + // Replace the user path after capture, before the root handoff. + std::fs::write(&helper, b"changed!").unwrap(); + } return Ok(checks > 1); } - // The same account swaps the user path during the sudo password wait. - std::fs::write(&helper, b"changed!").unwrap(); assert!(!quiet); assert_eq!(args[0], "/usr/bin/python3"); assert_eq!(args[3], ROOT_BOOTSTRAP); diff --git a/scripts/browser-root-helper.test.py b/scripts/browser-root-helper.test.py index def376efb..3ee943557 100644 --- a/scripts/browser-root-helper.test.py +++ b/scripts/browser-root-helper.test.py @@ -18,6 +18,39 @@ class RootHelperTests(unittest.TestCase): + def test_main_refuses_changed_stdin_before_tty_exec_or_root_write(self): + admitted = b'print("admitted")\n' + expected = hashlib.sha256(admitted).hexdigest() + verified_copy = ROOT.verified_copy + for label, payload in ( + ('appended', admitted + b'print("extra")\n'), + ('prepended', b'print("extra")\n' + admitted), + ('different', b'print("changed!")\n')): + with self.subTest(payload=label), tempfile.TemporaryDirectory() as temporary: + directory = os.open(temporary, os.O_RDONLY | os.O_DIRECTORY) + try: + # Exercise the real copy with fixture ownership instead of root. + def copy_as_fixture(fd, name, digest, contents, owner): + self.assertEqual(owner, 0) + self.assertEqual(digest, expected) + return verified_copy(fd, name, digest, contents, os.getuid()) + with (patch.object(ROOT.os, 'geteuid', return_value=0), + patch.object(ROOT, 'trusted_directory', return_value=os.dup(directory)), + patch.object(ROOT, 'verified_copy', side_effect=copy_as_fixture), + patch.object(sys, 'argv', + ['bootstrap', expected, 'fixture', temporary, 'setup']), + patch.object(sys, 'stdin', io.TextIOWrapper(io.BytesIO(payload))), + patch('builtins.open') as tty, + patch('builtins.exec') as execute): + with self.assertRaisesRegex( + RuntimeError, '^Browser helper differs from its admitted SHA-256$'): + ROOT.main() + tty.assert_not_called() + execute.assert_not_called() + self.assertEqual(list(Path(temporary).iterdir()), []) + finally: + os.close(directory) + def test_setup_keeps_the_helper_confirmation_on_the_tty(self): with tempfile.TemporaryDirectory() as temporary: directory = os.open(temporary, os.O_RDONLY | os.O_DIRECTORY)