diff --git a/capsules/model-provider/src/journal.rs b/capsules/model-provider/src/journal.rs index b711b092d..d3c6878f2 100644 --- a/capsules/model-provider/src/journal.rs +++ b/capsules/model-provider/src/journal.rs @@ -4220,7 +4220,10 @@ mod tests { } let temp_before = file_bytes(&temp); let writer = open_journal_directory(&directory).unwrap(); - writer.try_lock().unwrap(); + // A child forked on another test thread can briefly hold a copy of an + // earlier lock fd on this directory (#381); take the lock with the + // provider's own bounded retry instead of one try. + lock_journal_directory(&writer).unwrap(); assert_eq!( RunJournal::open(root.clone()).err().unwrap().code(), "selection_unavailable" diff --git a/capsules/object-provider/Cargo.lock b/capsules/object-provider/Cargo.lock index d5114091d..914d1dc39 100644 --- a/capsules/object-provider/Cargo.lock +++ b/capsules/object-provider/Cargo.lock @@ -167,9 +167,6 @@ name = "arbitrary" version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" -dependencies = [ - "derive_arbitrary", -] [[package]] name = "arc-swap" @@ -1190,7 +1187,7 @@ dependencies = [ "elastos-protected-content-provider-contracts", "elastos-protected-content-rights", "getrandom 0.2.17", - "nix", + "nix 0.29.0", "serde", "serde_json", "sha2 0.10.9", @@ -1274,17 +1271,6 @@ version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" -[[package]] -name = "derive_arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "derive_more" version = "2.1.1" @@ -1589,7 +1575,7 @@ dependencies = [ "elastos-common", "elastos-compute", "libc", - "nix", + "nix 0.29.0", "serde", "serde_json", "thiserror 1.0.69", @@ -1689,7 +1675,7 @@ dependencies = [ "ghash", "hkdf", "hpke", - "nix", + "nix 0.29.0", "rand 0.10.2", "rand 0.9.5", "rand_chacha 0.3.1", @@ -1734,7 +1720,7 @@ dependencies = [ "elastos-protected-content-provider-contracts", "elastos-wallet-contract", "hex", - "nix", + "nix 0.29.0", "serde", "serde_json", "sha2 0.10.9", @@ -3855,6 +3841,18 @@ dependencies = [ "libc", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nom" version = "7.1.3" @@ -6053,6 +6051,12 @@ dependencies = [ "utf-8", ] +[[package]] +name = "typed-path" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" + [[package]] name = "typenum" version = "1.20.1" @@ -7446,18 +7450,16 @@ dependencies = [ [[package]] name = "zip" -version = "2.4.2" +version = "9.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50" +checksum = "a954114b47a54df49f83d2722814e86b23d4bb1b54a1b90fb7d92b41619ddc22" dependencies = [ - "arbitrary", "crc32fast", - "crossbeam-utils", - "displaydoc", "flate2", "indexmap", "memchr", - "thiserror 2.0.20", + "nix 0.31.3", + "typed-path", ] [[package]] diff --git a/docs/WINDOWS.md b/docs/WINDOWS.md index 18a7dc8a9..6c0cde347 100644 --- a/docs/WINDOWS.md +++ b/docs/WINDOWS.md @@ -19,24 +19,217 @@ Browser contracts. Capsules must not branch on Windows or learn host topology. ## First Windows product: WSL2 -The first honest Windows product should run the Linux Runtime locally inside -WSL2. +The first honest Windows product runs the Linux Runtime locally inside WSL2. +[Issue #265](https://github.com/Elacity/elastos-runtime/issues/265) owns the +proof for that product. Until its acceptance items are proven, this section is +a target, not a result. - Package the Runtime as a signed or importable ElastOS WSL distribution. -- Provide a small Windows launcher that starts, stops, updates, health-checks, - and opens `http://localhost:61180/apps/home/`. -- Keep Runtime state in the Linux filesystem, not in mixed host paths. -- Enforce explicit storage budgets and cleanup. -- Keep localhost and passkey origin stable. -- Report Browser availability honestly. Edge is a shell surface for Home, not - proof of a local isolated Browser capsule. +- A Windows launcher starts, stops, updates, and health-checks the Linux + Runtime, and opens one Home origin. The + [launcher contract](LAUNCHER_CONTRACT.md#readiness-and-home-url) owns that + URL. +- The launcher keeps Runtime state on the distro filesystem. +- The launcher enforces explicit storage budgets and cleanup. +- The launcher keeps the passkey origin stable. +- The launcher reports Browser availability honestly. Edge is a shell surface + for Home. It is not proof of a local isolated Browser capsule. -WSL2 is a host substrate, not a new capsule API and not a substitute for -capsule isolation. Capsules keep the same Runtime, Carrier, provider, -identity, and capability contracts. +WSL2 is a host substrate. It is not a new capsule API and it is not a +substitute for capsule isolation. Capsules keep the same Runtime, Carrier, +provider, identity, and capability contracts. -Do not leak WSL paths, host ports, or shell commands into capsule, provider, or -object contracts. +Capsule, provider, and object contracts stay on the Runtime surface. WSL paths, +host ports, and shell commands stay in the host launcher. + +## Linux build inside WSL2 + +A Windows launcher runs the Linux Runtime inside a WSL2 distro. This section +records what the installer and Runtime do there today. Each statement cites +the code. If a line number moves, use the named function. Rust paths are +relative to `elastos/crates/elastos-server/src/`. + +### Platform + +Inside a distro, `uname -s` is `Linux`. `detect_platform` +(`scripts/install.sh:317-336`) selects `x86_64-linux` or `aarch64-linux`. +`scripts/prepare-release-platform.sh:107-108` builds those releases for +`x86_64-unknown-linux-musl` and `aarch64-unknown-linux-musl`. +`installer_data_dir` (`scripts/install.sh:300-315`) stops on a system name +that is not `Linux` or `Darwin`. A Windows launcher starts the distro and runs +the Linux installer and binary there. + +### Tools in the distro + +The installer needs `curl`, `python3`, and `sha256sum` or `shasum` inside the +distro (`scripts/install.sh:35`). It stops before it downloads anything when +`curl` or `python3` is missing or `python3` does not run, and when neither +SHA-256 tool is present (`scripts/install.sh:1177-1191`). `python3` runs the +release checks: `verify_signature` (`scripts/install.sh:683`) and +`validate_release_identity` (`scripts/install.sh:830`). A WSL2 distro without +`python3` cannot install the Runtime. A launcher checks for these tools, or +installs them, before it runs `install.sh`. + +### Home origin + +The [launcher contract](LAUNCHER_CONTRACT.md#readiness-and-home-url) is the +one source for the Home URL that a launcher opens and for the passkey origin. +This note does not repeat the URL. It records what the Runtime code serves: + +- `elastos home --browser` binds the host name `localhost` at + `BROWSER_HOME_PORT` (`gateway_entry.rs:17-31`, + `update_controller.rs:2288-2289`). +- The gateway keeps the host name that it was given in its URL + (`api/gateway_server.rs:96-101`) and adds `/home/` + (`api/gateway_server.rs:117`). `HOME_ROUTE` is `/home/` + (`api/gateway.rs:440`). +- `/home`, `/apps/home`, and `/apps/home/` redirect permanently to `/home/` + (`api/gateway.rs:1222-1235`, `redirect_home_root` in + `api/browser_capsules.rs:58-64`). +- After an update restart, Runtime prints the Home URL with the host name + `localhost` (`update_controller.rs:1049`). The update controller accepts a + ready Home at `BROWSER_HOME_PORT` and `/home/` on `localhost`, `127.0.0.1`, + or `[::1]` (`approved_home_url`, `update_controller.rs:2291-2299`). +- `elastos gateway` is a hidden operator command. Without `--addr` it binds + `127.0.0.1` at the same port (`main.rs:438-441`). + +`localhost` and `127.0.0.1` are different browser origins. A passkey that is +registered on one origin does not sign in on the other. Browsers refuse +passkeys (WebAuthn) on an IP-address origin such as `http://127.0.0.1:8090`, +so passkeys work only on `localhost`. The Home origin is decided: `localhost` +everywhere. The launcher contract states it, and a WSL2 launcher opens and +probes Home on `localhost`, as on every other computer. + +`docs/INSTALL.md` describes `elastos home --browser`. The source-build guides +`docs/MAC.md` and `docs/HOME_LOCAL_SETUP.md` use a developer gateway on a +different port. That is a developer lane, not the installed product. + +`elastos home --browser` can open a browser itself. `browser_home_ready` +(`gateway_entry.rs:33-40`) prints the URL and calls `open_browser` +(`main.rs:2268-2283`). On Linux, `open_browser` starts `wslview` and, if that +cannot start, `xdg-open`. It does not check that a page opened. It skips the +open after an update restart (`ELASTOS_UPDATE_RESTART=1`). There is no flag +that stops this open. A launcher that runs `elastos home --browser` and also +opens Home can thus get a second tab. This is possible, not certain: it +depends on whether `wslview` or `xdg-open` is in the distro and can reach a +Windows browser. That is a gap. `elastos gateway` (`gateway_entry.rs:1-15`) +opens no browser. + +### Release verification + +The installer trusts one maintainer key. The publish step writes that +`did:key` into `install.sh` as `MAINTAINER_DID` +(`scripts/install.sh:45-48`). `ELASTOS_MAINTAINER_DID` or `--maintainer-did` +replaces it (`scripts/install.sh:45`, `scripts/install.sh:1128`). The +installer stops when the value is empty or is not a `did:key` +(`scripts/install.sh:1167-1172`). The signature check is only as strong as the +`install.sh` copy that carries this key. A Windows launcher must check the +SHA-256 of `install.sh` against its own signed record before it runs it, and +must not set `ELASTOS_MAINTAINER_DID`. + +Before the installer changes any file, it does these checks: + +1. `verify_signature` (`scripts/install.sh:678-825`) checks the Ed25519 + signature over the domain and the canonical payload. It also checks that + the signer is the pinned `MAINTAINER_DID`. The installer runs it on + `release-head.json` (`scripts/install.sh:1286`) and on `release.json` + (`scripts/install.sh:1313`). +2. `validate_release_identity` (`scripts/install.sh:827-863`) checks that the + signed head names the SHA-256 of the exact `release.json` bytes. +3. `sha256_check` (`scripts/install.sh:356-364`) checks the downloaded binary + against the SHA-256 in the signed `release.json` + (`scripts/install.sh:1354`). + +These tests in `scripts/install-bootstrap-test.py` feed a bad input and check +that the installer stops and changes nothing: + +- `test_signature_and_binding_failures_reject_before_artifacts_in_populated_installation` + (line 1235): a release with one changed field, a head bound to another + release, and a foreign trust anchor. The first and last expect + `Signature verification FAILED`. +- `test_corrupt_artifacts_fail_before_changes_then_clean_rerun_installs` + (line 991): a truncated binary and a binary with different bytes. Both + expect `SHA-256 mismatch`. +- `test_altered_message_signature_and_key` (line 215) and + `test_binding_precedes_artifacts` (line 731) cover the Ed25519 check and + the head-to-release binding. + +On an existing installation, the release writer refuses a release that is +older than the installed release, and a release from another channel +(`install_release`, `update.rs:505-513`). The Rust test +`older_installer_after_update_is_refused_without_changes` (`update.rs:5067`) +covers the older release. A new installation has no installed release to +compare. It accepts any release that the pinned key signed. A launcher that +needs a version floor on a new installation must supply it. That is a gap. + +### Data location + +The installer writes `$XDG_DATA_HOME/elastos` or `~/.local/share/elastos` +(`installer_data_dir`, `scripts/install.sh:300-315`). The launcher keeps +`HOME` and that data directory on the distro filesystem. `install.sh` does not +reject a data directory under `/mnt`. That guard is a gap. + +### Update path + +The signed release head names its channel. The installer reads it, accepts +`stable`, `canary`, or `jetson-test` (`scripts/install.sh:84`, +`scripts/install.sh:1290-1293`), and records it as the channel of the trusted +source in `sources.json` (`scripts/install.sh:1406-1425`). The publisher +gateway that the installer reads sets which channel a new installation gets. + +- `elastos update` (`Commands::Update`, `main.rs:550-570`) is the update + command. `show_ready` prints it after installation + (`scripts/install.sh:885-904`). +- `elastos update` refuses a signed release that is older than the installed + release (`update.rs:1233-1237`). The release writer keeps the installed + version as a floor (`update.rs:505-512`; test + `force_keeps_signed_installed_version_as_downgrade_floor`, + `update.rs:4081`). This note does not describe a rollback path. +- `verify_source_channel` (`update.rs:170-183`) accepts only the subscribed + channel. A `canary` subscription also accepts `stable` releases from the + same publisher. +- `elastos source switch-channel ` changes the subscription + (`sources.rs:465-475`, `sources.rs:713-719`). +- A second run of `install.sh` also updates. It uses the same release writer + and the same refusals as above. + +A Windows launcher calls `elastos update`. It does not ship a second updater. +This note does not define the stop signal. Issue #265 owns that path. +`wsl --shutdown` stops the distro without a Runtime stop. + +### Browser on WSL2 + +Runtime offers Browser only on `darwin-arm64` (`browser_available`, +`setup/browser_config.rs:166-168`). On every Linux host, WSL2 included, +Browser fails closed: + +- `elastos setup` removes the Browser host files that a release installs + (`retire_host`, `setup/browser_config.rs:300-355`). The removed files + include `scripts/browser-vm-linux-network.py`. When a Browser capsule + folder exists, setup also writes an empty Engine selection and prints + `Browser is not available on this computer yet.` + (`setup/browser_config.rs:301-306`, `setup/browser_config.rs:352-354`). + Without that folder, setup prints no Browser line. +- The Home catalog leaves Browser out + (`api/gateway_capsule_catalog/read_model.rs:44`, + `api/browser_capsules.rs:431-433`). +- The installer runs `elastos setup` before its Linux host step + (`scripts/install.sh:950-952`). `prepare_browser_linux_host` + (`scripts/install.sh:908-937`) returns when the helper file is absent + (`scripts/install.sh:914`). Thus the installer asks for no `sudo`, and no + systemd unit, udev rule, TAP device, or KVM access rule is written. +- The Rust test `linux_setup_installs_no_browser_host_helpers_or_image` + (`setup/browser_config.rs:808`) checks this for `linux-amd64` and + `linux-arm64`. + +This result does not depend on `/dev/kvm`. This note claims no Windows Browser +Engine. + +If an earlier release ran the root helper on a host, `retire_host` removes +only the files in the data directory. The root-owned copy in +`/usr/local/lib/elastos`, the systemd unit, the udev rule, and the KVM access +rule stay until an administrator runs the helper `remove` action. That is a +gap. ## Later native Windows direction @@ -64,6 +257,6 @@ Before Windows support is called product-ready, prove: - same-device and cross-device Carrier behavior where applicable - bounded disk usage and explicit cleanup - no orphan processes after stop -- stable localhost and passkey origin +- stable Home and passkey origin - honest Browser availability - installed artifact receipt and source receipt diff --git a/elastos/Cargo.lock b/elastos/Cargo.lock index ac82b721d..dc06da84e 100644 --- a/elastos/Cargo.lock +++ b/elastos/Cargo.lock @@ -167,9 +167,6 @@ name = "arbitrary" version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" -dependencies = [ - "derive_arbitrary", -] [[package]] name = "arc-swap" @@ -1197,7 +1194,7 @@ dependencies = [ "elastos-protected-content-provider-contracts", "elastos-protected-content-rights", "getrandom 0.2.17", - "nix", + "nix 0.29.0", "serde", "serde_json", "sha2 0.10.9", @@ -1281,17 +1278,6 @@ version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" -[[package]] -name = "derive_arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "derive_more" version = "2.1.1" @@ -1598,7 +1584,7 @@ dependencies = [ "elastos-common", "elastos-compute", "libc", - "nix", + "nix 0.29.0", "serde", "serde_json", "tempfile", @@ -1706,7 +1692,7 @@ dependencies = [ "hkdf", "hpke", "k256", - "nix", + "nix 0.29.0", "rand 0.10.2", "rand 0.9.5", "rand_chacha 0.3.1", @@ -1765,7 +1751,7 @@ dependencies = [ "elastos-wallet-contract", "hex", "k256", - "nix", + "nix 0.29.0", "serde", "serde_json", "sha2 0.10.9", @@ -3925,6 +3911,18 @@ dependencies = [ "libc", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nom" version = "7.1.3" @@ -6164,6 +6162,12 @@ dependencies = [ "utf-8", ] +[[package]] +name = "typed-path" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" + [[package]] name = "typenum" version = "1.20.1" @@ -7703,18 +7707,16 @@ dependencies = [ [[package]] name = "zip" -version = "2.4.2" +version = "9.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50" +checksum = "a954114b47a54df49f83d2722814e86b23d4bb1b54a1b90fb7d92b41619ddc22" dependencies = [ - "arbitrary", "crc32fast", - "crossbeam-utils", - "displaydoc", "flate2", "indexmap", "memchr", - "thiserror 2.0.20", + "nix 0.31.3", + "typed-path", ] [[package]] diff --git a/elastos/crates/elastos-server/Cargo.toml b/elastos/crates/elastos-server/Cargo.toml index 84788f1d5..e54e95885 100644 --- a/elastos/crates/elastos-server/Cargo.toml +++ b/elastos/crates/elastos-server/Cargo.toml @@ -104,7 +104,7 @@ tempfile = "3.10" # Archive extraction (for capsule artifacts) flate2 = "1.0" tar = "0.4" -zip = { version = "2.4.2", default-features = false, features = ["deflate-flate2", "flate2"] } +zip = { version = "9.0.4", default-features = false, features = ["deflate-flate2"] } libc = "0.2" # Built-in Carrier transport (P2P for updates, gossip messaging, DHT discovery). diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/library.rs b/elastos/crates/elastos-server/src/api/gateway_tests/library.rs index d8477c0db..0253c229f 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/library.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/library.rs @@ -892,7 +892,7 @@ fn zip_text_files(bytes: &[u8]) -> std::collections::BTreeMap { if entry.is_dir() { continue; } - let name = entry.name().to_string(); + let name = entry.name().unwrap().into_owned(); let mut body = String::new(); entry.read_to_string(&mut body).unwrap(); files.insert(name, body); @@ -3870,6 +3870,203 @@ async fn test_library_provider_rejects_unsafe_zip_entries() { .contains("relative and safe")); } +/// Every path under `root` (files, folders and symlinks, not followed). +fn walk_paths(root: &std::path::Path) -> Vec { + let mut out = Vec::new(); + let mut stack = vec![root.to_path_buf()]; + while let Some(dir) = stack.pop() { + for entry in std::fs::read_dir(&dir).unwrap() { + let entry = entry.unwrap(); + let path = entry.path(); + if entry.file_type().unwrap().is_dir() { + stack.push(path.clone()); + } + out.push(path); + } + } + out +} + +#[tokio::test] +async fn test_library_provider_extract_zip_refuses_absolute_dotdot_and_symlink_entries() { + use std::io::Write as _; + + let dir = tempfile::tempdir().unwrap(); + let app = gateway_router(library_test_state(dir.path()).await); + let authority = passkey_authority_with_name(dir.path(), Some("admin")); + let token = app_token_for_authority(dir.path(), LIBRARY_CAPSULE_ID, &authority); + let root = crate::auth::principal_localhost_root(&authority.principal_id); + let documents_uri = format!("{root}/Documents"); + let imports_uri = format!("{documents_uri}/Imports"); + + let (status, _) = post_library( + app.clone(), + &token, + "mkdir", + json!({ "parent_uri": root, "name": "Documents" }), + ) + .await; + assert_eq!(status, StatusCode::OK); + let (status, _) = post_library( + app.clone(), + &token, + "mkdir", + json!({ "parent_uri": documents_uri, "name": "Imports" }), + ) + .await; + assert_eq!(status, StatusCode::OK); + + let options = + zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); + // Each archive holds one hostile entry. The whole-archive extract must + // refuse it and write nothing for it, inside or outside the Library. + // (archive name, entry kind, entry name, symlink target, expected message) + let cases: [(&str, &str, &str, &str, &str); 5] = [ + ( + "Absolute.zip", + "file", + "/absolute-escape.txt", + "", + "relative and safe", + ), + ( + "DotDot.zip", + "file", + "../dotdot-escape.txt", + "", + "relative and safe", + ), + ( + "Inner.zip", + "file", + "Nested/../inner-escape.txt", + "", + "relative and safe", + ), + ( + "Backslash.zip", + "file", + "..\\backslash-escape.txt", + "", + "invalid library object name", + ), + ( + "Symlink.zip", + "symlink", + "symlink-escape.txt", + "/etc/passwd", + "non-file", + ), + ]; + for (archive_name, kind, entry_name, link_target, expected) in cases { + let archive_bytes = { + let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + if kind == "symlink" { + writer + .add_symlink(entry_name, link_target, options) + .unwrap(); + } else { + writer.start_file(entry_name, options).unwrap(); + writer.write_all(b"escape").unwrap(); + } + writer.finish().unwrap().into_inner() + }; + let zip_uri = format!("{documents_uri}/{archive_name}"); + let (write_status, write) = post_library( + app.clone(), + &token, + "write", + json!({ + "uri": zip_uri, + "mime": "application/zip", + "data": base64::engine::general_purpose::STANDARD.encode(archive_bytes), + }), + ) + .await; + assert_eq!(write_status, StatusCode::OK, "{archive_name}"); + assert_eq!(write["status"], "ok", "{archive_name}: {write}"); + + let (extract_status, extracted) = post_library( + app.clone(), + &token, + "extract_archive", + json!({ "uri": zip_uri }), + ) + .await; + assert_eq!(extract_status, StatusCode::OK, "{archive_name}"); + assert_eq!( + extracted["status"], "error", + "{archive_name}: hostile entry {entry_name:?} was not refused: {extracted}" + ); + assert!( + extracted["message"].as_str().unwrap().contains(expected), + "{archive_name}: {extracted}" + ); + + if kind == "symlink" { + // The listing marks it blocked and a selected extract refuses it. + let (list_status, listed) = post_library( + app.clone(), + &token, + "archive_entries", + json!({ "uri": zip_uri }), + ) + .await; + assert_eq!(list_status, StatusCode::OK); + let rows = listed["data"]["entries"].as_array().unwrap(); + assert!( + rows.iter().any(|entry| entry["path"] == entry_name + && entry["kind"] == "blocked" + && entry["safety"]["reason"] + .as_str() + .unwrap() + .contains("non-file")), + "{listed}" + ); + let (select_status, selected) = post_library( + app.clone(), + &token, + "archive_extract_entries", + json!({ + "uri": zip_uri, + "destination_uri": imports_uri, + "entries": [entry_name], + }), + ) + .await; + assert_eq!(select_status, StatusCode::OK); + assert_eq!(selected["status"], "ok", "{selected}"); + assert_eq!( + selected["data"]["receipt"]["progress"]["blocked_entries"], + 1 + ); + assert!(selected["data"]["blocked"][0]["reason"] + .as_str() + .unwrap() + .contains("non-file")); + } + } + + // Nothing from any hostile entry exists anywhere under the data dir, and + // no symlink was created. + for path in walk_paths(dir.path()) { + let name = path.file_name().unwrap().to_string_lossy().to_string(); + assert!( + !name.contains("escape"), + "hostile entry was written: {}", + path.display() + ); + assert!( + !std::fs::symlink_metadata(&path) + .unwrap() + .file_type() + .is_symlink(), + "symlink was created: {}", + path.display() + ); + } +} + #[tokio::test] async fn test_library_gateway_reads_webspace_files_through_runtime_provider() { let dir = tempfile::tempdir().unwrap(); diff --git a/elastos/crates/elastos-server/src/library.rs b/elastos/crates/elastos-server/src/library.rs index 9e537d229..84c791d0a 100644 --- a/elastos/crates/elastos-server/src/library.rs +++ b/elastos/crates/elastos-server/src/library.rs @@ -4239,7 +4239,10 @@ fn preview_zip_archive_entry( let mut file = archive .by_index(index) .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))?; - let raw_name = file.name().to_string(); + let raw_name = file + .name() + .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))? + .into_owned(); let Ok(normalized) = normalized_archive_entry_path(Path::new(&raw_name)) else { continue; }; @@ -4457,7 +4460,10 @@ fn list_zip_archive_entries(bytes: Vec) -> anyhow::Result<(Vec, bool) let file = archive .by_index(index) .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))?; - let raw_name = file.name().to_string(); + let raw_name = file + .name() + .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))? + .into_owned(); let path = Path::new(&raw_name); let normalized = match normalized_archive_entry_path(path) { Ok(path) => path, @@ -4939,7 +4945,10 @@ fn collect_selected_zip_writes( let mut file = archive .by_index(index) .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))?; - let raw_name = file.name().to_string(); + let raw_name = file + .name() + .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))? + .into_owned(); let normalized = match normalized_archive_entry_path(Path::new(&raw_name)) { Ok(path) => path, Err(err) => { @@ -5429,8 +5438,10 @@ fn extract_zip_archive( let mut file = archive .by_index(index) .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))?; - let entry_path = file - .enclosed_name() + let raw_name = file + .name() + .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))?; + let entry_path = zip_entry_enclosed_path(&raw_name) .ok_or_else(|| anyhow!("library archive entry path must be relative and safe"))?; let entry_uri = archive_entry_uri(&destination.uri, &entry_path)?; if entry_uri == destination.uri { @@ -5461,6 +5472,29 @@ fn extract_zip_archive( Ok(()) } +/// The path a whole-archive ZIP extract writes for an entry name, or `None` +/// when the name holds a NUL byte, is absolute (a root or a drive prefix), or +/// climbs above the archive root. `archive_entry_uri` then refuses any `..` +/// that is left. This keeps the rule in the runtime: zip 9 `enclosed_name` +/// strips a leading `/` or drive prefix and folds `..` instead, which would +/// write entries that this extract refuses. +fn zip_entry_enclosed_path(name: &str) -> Option { + if name.contains('\0') { + return None; + } + let path = PathBuf::from(name); + let mut depth = 0usize; + for component in path.components() { + match component { + Component::Prefix(_) | Component::RootDir => return None, + Component::ParentDir => depth = depth.checked_sub(1)?, + Component::Normal(_) => depth += 1, + Component::CurDir => {} + } + } + Some(path) +} + fn archive_entry_uri(destination_uri: &str, path: &Path) -> anyhow::Result { let mut uri = destination_uri.trim_end_matches('/').to_string(); for component in path.components() {