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/HOME_LOCAL_SETUP.md b/docs/HOME_LOCAL_SETUP.md index 32f8daf2a..240fe8464 100644 --- a/docs/HOME_LOCAL_SETUP.md +++ b/docs/HOME_LOCAL_SETUP.md @@ -42,10 +42,12 @@ export HOME_URL="http://localhost:61180/apps/home/" `HOME_URL` is the browser URL you open. -You may choose a different loopback port if it is free. The Mac source-home -examples in this repository use `localhost:61180`. The agent smoke script -defaults to `localhost:8090`; that is only a script default, not product -authority. +These values are for the developer source-home lane. You may choose a +different loopback port if it is free. The Mac source-home examples in this +repository use `localhost:61180`. The installed Home address is +`http://localhost:8090/home/`; the +[launcher contract](LAUNCHER_CONTRACT.md#readiness-and-home-url) owns that +address and the redirect from a loopback IP address to `localhost`. ## Know the two host lanes diff --git a/docs/INSTALL.md b/docs/INSTALL.md index 637fc2705..78dd02afa 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -57,7 +57,9 @@ the bootstrap and connection contract. The installer detects the platform (Linux `x86_64`/`aarch64` or macOS Apple silicon), verifies the signed release, installs Runtime, and fetches the Home profile from the trusted publisher. It -starts Home at `http://localhost:8090/home/` and opens your browser. Keep the +starts Home at `http://localhost:8090/home/` and opens your browser. The +[launcher contract](LAUNCHER_CONTRACT.md#readiness-and-home-url) owns this +address. Keep the terminal open while you use Home; Ctrl+C stops it. With no interactive terminal, setup completes and prints the full command for opening Home later. The installer uses the installed binary's full path, so editing PATH is optional. diff --git a/docs/LAUNCHER_CONTRACT.md b/docs/LAUNCHER_CONTRACT.md new file mode 100644 index 000000000..95b917717 --- /dev/null +++ b/docs/LAUNCHER_CONTRACT.md @@ -0,0 +1,152 @@ +# Launcher Contract + +A supervisor starts Home with the gateway command below. This repository owns the +gateway, the readiness probe, the passkey origin, and the exit codes. A desktop +launcher is a separate program. This document states the behavior the Runtime +implements today. + +## Start + +```bash +elastos gateway --addr localhost:8090 +``` + +`--addr` is `host:port`. `elastos home` binds `localhost:8090` and opens the +Home URL below. The gateway command leaves the system browser closed. The +default `--addr` of the gateway command is `127.0.0.1:8090`, so a launcher +passes `--addr localhost:8090`. + +For the host name `localhost`, the gateway listens on every loopback address +that a client can use for that name on the given port: each address that the +computer resolves for `localhost`, and also `127.0.0.1` and `::1`, which +browsers use for `localhost`. Each of these listeners serves the same Home. +When the computer has no IPv6, the gateway listens without `::1`. The gateway +exits 1 and its error names the address when another program already uses one +of these addresses, when it cannot listen on one of them for another reason, +or when `localhost` resolves to an address that is not loopback. For an IP +address in `--addr`, the gateway listens on that one address. + +On Windows, Home runs in WSL2. This repository does not test how Windows +forwards `localhost` into WSL2; that is a gap in this contract. + +`elastos serve` is the operator runtime. Its readiness route is `GET /api/health`. +A Home supervisor uses `gateway` and `/healthz`. + +## Readiness and Home URL + +When this gateway process holds the host lock `{data}/host-process.lock` +with role `gateway` or `gateway-public`: + +```text +GET http://localhost:8090/healthz +``` + +returns HTTP 200 and the two bytes `OK`. Otherwise it returns HTTP 503: when +no process holds the lock, when another process holds it, when the file at +that path was removed or replaced after the gateway took its lock, and when +the gateway has released it. A gateway that `elastos serve` starts keeps the +`serve` lock, so its `/healthz` returns 503. + +What proves that this gateway holds the lock: the process that owns the +listening socket answers, and it checks its own state. It holds an exclusive +lock (`flock`) on an open file, `{data}/host-process.lock` names that same file +now (the same device and inode), and a new open of that file cannot take the +lock. The JSON record in the file is not proof. Any process that runs as the +same user can rewrite it, so `/healthz` does not read it, and a gateway does +not skip taking the lock because the record names its pid. + +The lock proves possession, not identity. A process that holds the `flock` +has the host lock. That does not prove that the holder is a gateway, or that +it is ElastOS. Any process that runs as the same user can open +`{data}/host-process.lock` and hold the lock. While it holds the lock, a +gateway for that data directory does not start (see "Data directory and +lock"), and a gateway that does not hold the lock itself returns 503 from +`/healthz`. A gateway can prove only that it holds the lock itself, so `OK` is +a statement that the gateway makes about itself. + +The same limit applies to a Home terminal that the gateway starts. The gateway +gives it `ELASTOS_GATEWAY_HOST_PID`, its own pid, and +`ELASTOS_GATEWAY_HOST_LOCK_FD`, a descriptor of the open file that holds the +lock. The terminal checks that its parent has that pid and that the descriptor +holds the lock now. This proves lock possession, not that the parent is the +gateway. A process that runs as the same user and holds the lock can give the +same variables and its descriptor to a child of its own, and that child's +check accepts them. + +The process that answers on the port gives this reply about its own data +directory. If an ElastOS gateway for another data directory already listens on +the port, that gateway also returns `OK`, and so can any other program that +listens on the port. The reply does not name the process. +Before it trusts `OK`, a supervisor confirms that the child it started is still +running and that `{data}/host-process.lock` records the pid of that child with +role `gateway`. That record is a hint, not proof, for the reasons above: a +process that is not that child can hold the lock and write a record that names +the child. A reply that names the lock holder is a gap in this contract. + +The Home origin is: + +```text +http://localhost:8090/home/ +``` + +`localhost` is the one Home origin. Other documents cite this section for the +Home address. When the gateway listens on `localhost`, a `GET` or `HEAD` +request for a Home page (`/`, `/home`, `/home/`, `/apps/home`, or +`/apps/home/`) whose `Host` is a loopback IP address, such as `127.0.0.1` or +`[::1]`, gets HTTP 308. Its `Location` is the same path and query at +`http://localhost:`. `/healthz`, `/api/` routes, Home assets, and app +routes answer on every listening address without a redirect. A gateway with an +IP address in `--addr` serves its Home pages at that address. + +The passkey relying party id is `localhost`. Registration and sign-in use that +origin. An IP-literal origin, including `http://127.0.0.1:8090`, is refused +with HTTP 403. For a loopback address, the reply tells the person to open +`http://localhost:/home/`. + +Each release takes the relying party id from the host of the page, and browsers +refuse an IP address as a relying party id. A passkey from an earlier release +therefore names the host where it was made. Sign-in accepts that passkey at +the same host on any port, and refuses it at every other host. + +## Data directory and lock + +| Item | Path | +| --- | --- | +| Linux data directory | `$XDG_DATA_HOME/elastos`, or `~/.local/share/elastos` | +| macOS data directory | `~/Library/Application Support/elastos` | +| Host lock | `{data}/host-process.lock` | + +The lock record stores `pid`, `role`, and `addr`. `addr` is the `--addr` +value as given, for example `localhost:8090`. The record is for people and +tools to read; the `flock` on the file is the lock. A second live host for the +same data directory exits 1. Its error contains `another ElastOS host already owns`. +The gateway gives this error when any process holds the lock, also a process +that is not ElastOS. The error names the holder from the record, and the +record can be false. + +## Stop + +The gateway handles `SIGTERM` and `SIGINT` by signalling its process group, +waiting, and then signalling that group again. Exit 75 comes from +`std::process::exit` in the binary watch and skips that handler. + +While the gateway is running, the binary watch exits 75 when the installed +binary is replaced, when its path changes, or when the watch cannot read it. +The install transaction replaces that binary by renaming the staged file onto +the installed path. On Linux that running path then ends in ` (deleted)`. + +## Exit codes + +| Code | Meaning | +| --- | --- | +| 0 | The command finished. | +| 1 | The command failed. A second host for the same data directory is one case. | +| 2 | The `elastos` command line is invalid. | +| 75 | The running gateway's binary watch exited. | + +A supervisor uses these exit codes. It does not parse English sentences from +stdout. Exit 0 covers more than one successful update outcome. A later issue +owns a machine-readable update status. + +Intel Mac's release id is `x86_64-darwin`. This contract does not publish a +download for that id. diff --git a/docs/MAC.md b/docs/MAC.md index aa4e005fe..e2ee5830a 100644 --- a/docs/MAC.md +++ b/docs/MAC.md @@ -79,6 +79,8 @@ On first launch, Home shows `Set up Home`. Enter a passkey name, choose passkey becomes the Home admin. Later launches show `Sign in` / `Use passkey`. Use `http://localhost:61180/apps/home/`; do not switch the visible origin to `127.0.0.1`, because passkey RP/origin state is bound to the browser origin. +Port `61180` is the developer source-home lane. The installed Home address is +in the [launcher contract](LAUNCHER_CONTRACT.md#readiness-and-home-url). ## Browser VM Artifacts diff --git a/docs/README.md b/docs/README.md index b75810a9f..d9d3d98ef 100644 --- a/docs/README.md +++ b/docs/README.md @@ -55,6 +55,8 @@ Each top-level ledger has one job: lifecycle, and child intents - [Interactive runtime contract](INTERACTIVE_RUNTIME_CONTRACT.md): interactive sessions and return behavior +- [Launcher contract](LAUNCHER_CONTRACT.md): install, gateway start, `/healthz`, + Home URL, data directory, lock, stop, and update - [Execution](EXECUTION.md): release execution boundaries - [Command runtime matrix](COMMAND_MATRIX.md): Runtime ownership for every command diff --git a/docs/WINDOWS.md b/docs/WINDOWS.md index 18a7dc8a9..3bf5a721d 100644 --- a/docs/WINDOWS.md +++ b/docs/WINDOWS.md @@ -24,7 +24,8 @@ WSL2. - 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/`. + and opens the Home origin in the + [launcher contract](LAUNCHER_CONTRACT.md#readiness-and-home-url). - Keep Runtime state in the Linux filesystem, not in mixed host paths. - Enforce explicit storage budgets and cleanup. - Keep localhost and passkey origin stable. diff --git a/elastos/Cargo.lock b/elastos/Cargo.lock index 324256b60..eda3abe91 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", @@ -3926,6 +3912,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" @@ -6165,6 +6163,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" @@ -7704,18 +7708,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 56bf3b4ac..18fb4371a 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/auth_gateway.rs b/elastos/crates/elastos-server/src/api/auth_gateway.rs index 72ffedd81..864428dc2 100644 --- a/elastos/crates/elastos-server/src/api/auth_gateway.rs +++ b/elastos/crates/elastos-server/src/api/auth_gateway.rs @@ -4609,6 +4609,7 @@ pub(in crate::api) fn auth_error_response(err: anyhow::Error) -> Response { let text = err.to_string(); let status = if err.is::() || err.is::() + || err.is::() || text.contains("missing") || text.contains("invalid") || text.contains("expired") @@ -8711,6 +8712,127 @@ mod tests { .unwrap() } + fn passkey_sign_in_at( + data_dir: &std::path::Path, + credential: &StoredCredential, + origin: &str, + ) -> anyhow::Result { + crate::auth::grant_passkey_session( + data_dir, + crate::auth::PasskeySessionRequest { + credential, + origin, + user_verified: true, + display_name: None, + profile_display_name: None, + reason: "upgrade sign-in fixture", + purpose: crate::auth::PasskeySessionPurpose::SignIn, + }, + ) + } + + /// Every release takes the relying party id from the page host (`derive_rp`), and + /// browsers refuse an IP address as a relying party id. A stored passkey therefore + /// names the host it was made at, and the origin check accepts that host on any port. + #[test] + fn passkey_from_an_earlier_release_signs_in_and_a_foreign_origin_is_refused() { + let root = local_profile_fixture_root(); + let _auth = super::super::gateway::set_test_home_launch_auth_data_dir(root.path()); + // The owner credential is stored as an earlier release stored it at a custom port. + let (owner_credential, owner) = local_profile_owner_grant(root.path()); + for origin in ["http://localhost:8090", "http://localhost:61180"] { + let mut headers = HeaderMap::new(); + headers.insert("origin", HeaderValue::from_str(origin).unwrap()); + assert_eq!( + super::super::handlers::identity::derive_rp(&headers) + .unwrap() + .id, + owner_credential.rp_id + ); + } + for origin in [ + "http://localhost:8090", + "http://localhost:61180", + "http://LOCALHOST:18090", + ] { + let grant = passkey_sign_in_at(root.path(), &owner_credential, origin).unwrap(); + assert_eq!(grant.principal_id, owner.principal_id, "{origin}"); + } + // A public Home credential keeps its own https host. + crate::auth::set_guest_registration_enabled(root.path(), true, crate::auth::now_ts()) + .unwrap(); + let mut public = test_credential_2(); + public.rp_id = "home.example.test".to_string(); + store_test_credential(root.path(), public.clone()); + let guest = crate::auth::grant_passkey_session( + root.path(), + crate::auth::PasskeySessionRequest { + credential: &public, + origin: "https://home.example.test", + user_verified: true, + display_name: None, + profile_display_name: None, + reason: "public registration fixture", + purpose: crate::auth::PasskeySessionPurpose::GuestRegistration, + }, + ) + .unwrap(); + let signed_in = + passkey_sign_in_at(root.path(), &public, "https://home.example.test").unwrap(); + assert_eq!(signed_in.principal_id, guest.principal_id); + + let before = std::fs::read(crate::auth::auth_state_path(root.path()).unwrap()).unwrap(); + for (credential, origin) in [ + (&owner_credential, "https://evil.example"), + (&owner_credential, "http://localhost.evil.example:8090"), + (&owner_credential, "http://evil.localhost:8090"), + (&owner_credential, "http://127.0.0.1:8090"), + (&owner_credential, "http://[::1]:8090"), + (&owner_credential, "not a url"), + (&public, "http://localhost:8090"), + (&public, "https://evil.home.example.test"), + ] { + assert!( + passkey_sign_in_at(root.path(), credential, origin).is_err(), + "{} at {origin}", + credential.rp_id + ); + } + assert_eq!( + std::fs::read(crate::auth::auth_state_path(root.path()).unwrap()).unwrap(), + before + ); + + // The refusal tells the person which address to open, with a 403 reply. + let local = "Passkeys work on this computer only at the localhost address. Open http://localhost:8090/home/ and try again."; + let refused = passkey_sign_in_at(root.path(), &owner_credential, "http://127.0.0.1:8090") + .unwrap_err(); + assert_eq!(refused.to_string(), local); + assert_eq!(auth_error_response(refused).status(), StatusCode::FORBIDDEN); + let foreign = + passkey_sign_in_at(root.path(), &owner_credential, "https://evil.example").unwrap_err(); + assert!(foreign + .to_string() + .starts_with("This passkey works only at the Home address")); + let fresh = local_profile_fixture_root(); + let mut identity = elastos_identity::IdentityManager::new(fresh.path().into()).unwrap(); + let secret = crate::auth::random_secret_hex(); + let enrollment = crate::auth::begin_owner_enrollment( + fresh.path(), + &mut identity, + &crate::auth::OwnerAdmission { + origin: "http://127.0.0.1:8090", + rp_id: "127.0.0.1", + claimant: &secret, + loopback: true, + }, + "launcher-owner", + crate::auth::now_ts(), + ) + .unwrap_err(); + assert_eq!(enrollment.to_string(), local); + } + #[test] fn local_profile_setup_resumes_with_current_grant_after_interruption() { for fault in ["after-terminal", "after-root", "after-profile"] { @@ -8881,7 +9003,8 @@ mod tests { let (_, owner) = local_profile_owner_grant(root.path()); crate::auth::set_guest_registration_enabled(root.path(), true, crate::auth::now_ts()) .unwrap(); - let guest_credential = test_credential_2(); + let mut guest_credential = test_credential_2(); + guest_credential.rp_id = "localhost".to_string(); store_test_credential(root.path(), guest_credential.clone()); let guest = crate::auth::grant_passkey_session( root.path(), @@ -8951,7 +9074,8 @@ mod tests { .unwrap() .is_none() ); - let unrelated_credential = test_credential(); + let mut unrelated_credential = test_credential(); + unrelated_credential.rp_id = "localhost".to_string(); store_test_credential(root.path(), unrelated_credential.clone()); let unrelated = crate::auth::grant_passkey_session( root.path(), diff --git a/elastos/crates/elastos-server/src/api/gateway_home_terminal.rs b/elastos/crates/elastos-server/src/api/gateway_home_terminal.rs index b62ee2459..e855b3710 100644 --- a/elastos/crates/elastos-server/src/api/gateway_home_terminal.rs +++ b/elastos/crates/elastos-server/src/api/gateway_home_terminal.rs @@ -778,14 +778,43 @@ async fn start_home_terminal_session( if let Some(gateway_api_url) = gateway_api_url { command.env(HOME_CLI_GATEWAY_API_URL_ENV, gateway_api_url); } + // The terminal proves that this gateway holds the host lock from this + // descriptor of the locked file, never from the lock file's JSON record + // (`runtime_control::parent_gateway_lock_proven`). + let host_lock = crate::host_lock::gateway_host_lock_for_child(data_dir); + let inherited_lock_fd = host_lock.as_ref().map(|file| file.as_raw_fd()); + match inherited_lock_fd { + Some(fd) => { + command + .env( + crate::runtime_control::GATEWAY_HOST_PID_ENV, + std::process::id().to_string(), + ) + .env( + crate::runtime_control::GATEWAY_HOST_LOCK_FD_ENV, + fd.to_string(), + ); + } + None => { + command + .env_remove(crate::runtime_control::GATEWAY_HOST_PID_ENV) + .env_remove(crate::runtime_control::GATEWAY_HOST_LOCK_FD_ENV); + } + } unsafe { - command.pre_exec(|| { + command.pre_exec(move || { if libc::setsid() == -1 { return Err(io::Error::last_os_error()); } if libc::ioctl(libc::STDIN_FILENO, libc::TIOCSCTTY as _, 0) == -1 { return Err(io::Error::last_os_error()); } + // Only this child keeps the lock descriptor across exec. + if let Some(fd) = inherited_lock_fd { + if libc::fcntl(fd, libc::F_SETFD, 0) == -1 { + return Err(io::Error::last_os_error()); + } + } Ok(()) }); } @@ -798,6 +827,7 @@ async fn start_home_terminal_session( let child = command .spawn() .with_context(|| format!("failed to start terminal process {}", command_spec.label))?; + drop(host_lock); let child_pid = child.id(); let (events, _receiver) = broadcast::channel(256); let session = Arc::new(HomeTerminalSession { diff --git a/elastos/crates/elastos-server/src/api/gateway_server.rs b/elastos/crates/elastos-server/src/api/gateway_server.rs index 27b8e787f..8288de52d 100644 --- a/elastos/crates/elastos-server/src/api/gateway_server.rs +++ b/elastos/crates/elastos-server/src/api/gateway_server.rs @@ -1,8 +1,13 @@ use std::collections::BTreeSet; -use std::net::{IpAddr, SocketAddr}; +use std::future::Future; +use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use std::path::PathBuf; +use std::pin::Pin; use std::sync::{Arc, OnceLock}; +use std::task::Poll; +use axum::extract::State; +use axum::response::{IntoResponse, Redirect, Response}; use elastos_runtime::provider::ProviderRegistry; use tokio::net::TcpListener; @@ -93,10 +98,21 @@ async fn start_gateway_server_with_shutdown( shutdown: impl std::future::Future + Send + 'static, ) -> anyhow::Result<()> { crate::auth::verify_auth_audit_chain_ready(&data_dir)?; - let listener = TcpListener::bind(addr).await?; + let _health_lock = crate::host_lock::publish_gateway_lock_if_unowned(&data_dir, addr)?; + let listeners = bind_gateway_listeners(addr).await?; + let listen_addrs = listeners + .iter() + .map(TcpListener::local_addr) + .collect::>>()?; + let bound_port = listen_addrs[0].port(); + let localhost = localhost_port(addr).is_some(); let local_control_registry = provider_registry.clone(); let gateway_api_url = if addr.parse::()?.port_u16() == Some(0) { - trusted_gateway_api_url(&listener.local_addr()?.to_string())? + if localhost { + trusted_gateway_api_url(&format!("localhost:{bound_port}"))? + } else { + trusted_gateway_api_url(&listen_addrs[0].to_string())? + } } else { trusted_gateway_api_url(addr)? }; @@ -116,6 +132,16 @@ async fn start_gateway_server_with_shutdown( .map_err(anyhow::Error::msg)?; let home_url = format!("{gateway_api_url}/home/"); let app = gateway_router_with_api_url(state, gateway_api_url); + // This gateway owns every localhost address on its port, so a Home page + // opened at a loopback IP moves to the one origin where passkeys work. + let app = if localhost { + app.layer(axum::middleware::from_fn_with_state( + bound_port, + home_page_on_localhost, + )) + } else { + app + }; // Publish one complete coordinate identity after Home setup, before children // capture its owner generation. A later mutation would change their owner hash. let gateway_local_control = match local_control_registry { @@ -148,6 +174,9 @@ async fn start_gateway_server_with_shutdown( let advertised = advertised_gateway_urls(addr); println!("ElastOS Gateway v{}", GATEWAY_VERSION); println!(" Bind: http://{}", addr); + for listen_addr in &listen_addrs { + println!(" Listen: {}", listen_addr); + } if let Some(primary) = advertised.first() { println!(" Open: {}", primary); println!(" Room: {}apps/chat-room/", primary); @@ -166,9 +195,17 @@ async fn start_gateway_server_with_shutdown( on_ready(&home_url); } let connections = axum_server::Handle::new(); - let server = axum_server::Server::::from_listener(listener) - .handle(connections.clone()) - .serve(app.into_make_service_with_connect_info::()); + let make_service = app.into_make_service_with_connect_info::(); + let server = serve_all( + listeners + .into_iter() + .map(|listener| { + axum_server::Server::::from_listener(listener) + .handle(connections.clone()) + .serve(make_service.clone()) + }) + .collect(), + ); tokio::pin!(server); let serve_result = tokio::select! { result = &mut server => result, @@ -214,6 +251,198 @@ async fn start_gateway_server_with_shutdown( Ok(()) } +/// Polls every listener's server with one shared handle. It returns the first +/// error, or `Ok` after every server has stopped. +async fn serve_all(servers: Vec) -> std::io::Result<()> +where + F: Future>, +{ + let mut servers: Vec>>> = servers + .into_iter() + .map(|server| Some(Box::pin(server))) + .collect(); + std::future::poll_fn(|cx| { + let mut running = false; + for slot in &mut servers { + let Some(server) = slot else { continue }; + match server.as_mut().poll(cx) { + Poll::Ready(Ok(())) => *slot = None, + Poll::Ready(Err(error)) => return Poll::Ready(Err(error)), + Poll::Pending => running = true, + } + } + if running { + Poll::Pending + } else { + Poll::Ready(Ok(())) + } + }) + .await +} + +/// The port of `addr` when its host is the name `localhost`. +fn localhost_port(addr: &str) -> Option { + let (host, port) = addr.rsplit_once(':')?; + if host.eq_ignore_ascii_case("localhost") { + port.parse().ok() + } else { + None + } +} + +/// `localhost` is the one Home origin (`docs/LAUNCHER_CONTRACT.md`). For that +/// name the gateway listens on every loopback address a client can reach it at. +/// Any other host binds exactly as given. +async fn bind_gateway_listeners(addr: &str) -> anyhow::Result> { + let Some(port) = localhost_port(addr) else { + return Ok(vec![TcpListener::bind(addr).await?]); + }; + let resolved = tokio::net::lookup_host(("localhost", port)) + .await + .map_err(|error| { + anyhow::Error::new(error).context( + "Home cannot start because this computer cannot find the address of localhost.", + ) + })? + .collect::>(); + bind_localhost_listeners(port, resolved).await +} + +/// The addresses for `localhost`: what this computer resolves, then 127.0.0.1 +/// and ::1, which browsers use for `localhost` whatever the hosts file says. +fn localhost_bind_addresses( + port: u16, + resolved: impl IntoIterator, +) -> anyhow::Result> { + let browser = [ + IpAddr::V4(Ipv4Addr::LOCALHOST), + IpAddr::V6(Ipv6Addr::LOCALHOST), + ]; + let mut addresses = Vec::new(); + for ip in resolved + .into_iter() + .map(|address| address.ip()) + .chain(browser) + { + anyhow::ensure!( + ip.is_loopback(), + "Home cannot start because localhost points to {ip}, which is not this computer. \ + Set localhost to 127.0.0.1 and ::1 in the hosts file, then start Home again." + ); + let address = SocketAddr::new(ip, port); + if !addresses.contains(&address) { + addresses.push(address); + } + } + Ok(addresses) +} + +/// Binds each localhost address on one port, or refuses to start. Only an +/// address family that this computer does not have is left out, because no +/// other program can listen there either. +async fn bind_localhost_listeners( + port: u16, + resolved: Vec, +) -> anyhow::Result> { + let mut port = port; + let mut listeners = Vec::new(); + for address in localhost_bind_addresses(port, resolved)? { + let address = SocketAddr::new(address.ip(), port); + match TcpListener::bind(address).await { + Ok(listener) => { + // Port 0 takes the first free port, and each other address uses it too. + port = listener.local_addr()?.port(); + listeners.push(listener); + } + Err(error) if address_family_unavailable(&error) => { + eprintln!( + "[gateway] {address} does not exist on this computer; Home listens without it" + ); + } + Err(error) => { + let message = if error.kind() == std::io::ErrorKind::AddrInUse { + format!( + "Home cannot start because another program already uses {address}. \ + Stop that program, then start Home again." + ) + } else { + format!( + "Home cannot start because it cannot listen on {address}. \ + Home needs every localhost address on port {port}." + ) + }; + return Err(anyhow::Error::new(error).context(message)); + } + } + } + anyhow::ensure!( + !listeners.is_empty(), + "Home cannot start because this computer has no localhost address to listen on." + ); + Ok(listeners) +} + +/// This computer has no such address family or address, as for ::1 without IPv6. +fn address_family_unavailable(error: &std::io::Error) -> bool { + if error.kind() == std::io::ErrorKind::AddrNotAvailable { + return true; + } + #[cfg(unix)] + { + error.raw_os_error() == Some(libc::EAFNOSUPPORT) + } + #[cfg(windows)] + { + // WSAEAFNOSUPPORT + error.raw_os_error() == Some(10047) + } + #[cfg(not(any(unix, windows)))] + { + false + } +} + +/// The Home page paths. Their API, health, and capsule routes stay on every host. +const HOME_PAGE_PATHS: [&str; 5] = ["/", "/home", "/home/", "/apps/home", "/apps/home/"]; + +/// Sends a Home page request for a loopback IP host to the same path at +/// `localhost` on the port this gateway listens on. +async fn home_page_on_localhost( + State(port): State, + request: axum::extract::Request, + next: axum::middleware::Next, +) -> Response { + let home_page = matches!( + *request.method(), + axum::http::Method::GET | axum::http::Method::HEAD + ) && HOME_PAGE_PATHS.contains(&request.uri().path()) + && request + .headers() + .get(axum::http::header::HOST) + .and_then(|value| value.to_str().ok()) + .is_some_and(is_loopback_ip_host); + if !home_page { + return next.run(request).await; + } + let path_and_query = request + .uri() + .path_and_query() + .map_or("/", |value| value.as_str()); + Redirect::permanent(&format!("http://localhost:{port}{path_and_query}")).into_response() +} + +fn is_loopback_ip_host(host: &str) -> bool { + let Ok(authority) = host.parse::() else { + return false; + }; + let host = authority.host(); + let host = host + .strip_prefix('[') + .and_then(|host| host.strip_suffix(']')) + .unwrap_or(host); + host.parse::().is_ok_and(|ip| ip.is_loopback()) +} + fn trusted_gateway_api_url(addr: &str) -> anyhow::Result { let authority = addr .parse::() @@ -353,9 +582,105 @@ mod trusted_gateway_tests { panic!("failed gateway startup must not open Home"); } + /// A port that is free on 127.0.0.1 and, when this host has it, on ::1. fn unused_localhost_address() -> String { - let listener = std::net::TcpListener::bind("localhost:0").unwrap(); - format!("localhost:{}", listener.local_addr().unwrap().port()) + format!("localhost:{}", unused_loopback_port()) + } + + fn unused_loopback_port() -> u16 { + loop { + let ipv4 = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = ipv4.local_addr().unwrap().port(); + match std::net::TcpListener::bind((Ipv6Addr::LOCALHOST, port)) { + Ok(_) => return port, + Err(error) if address_family_unavailable(&error) => return port, + Err(_) => continue, + } + } + } + + /// `None` with a loud reason when this host has no IPv6 loopback. + fn ipv6_loopback() -> Option<()> { + match std::net::TcpListener::bind((Ipv6Addr::LOCALHOST, 0)) { + Ok(_) => Some(()), + Err(error) if address_family_unavailable(&error) => { + eprintln!( + "SKIPPED IPv6 PART: this host has no IPv6 loopback (::1): {error}. \ + CI hosts have ::1 and run it." + ); + None + } + Err(error) => panic!("::1 probe failed: {error}"), + } + } + + /// One HTTP/1.1 GET with an explicit Host. Returns the status and Location. + async fn raw_get(connect: SocketAddr, host: &str, path: &str) -> (u16, Option) { + let mut stream = tokio::net::TcpStream::connect(connect).await.unwrap(); + stream + .write_all( + format!("GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n") + .as_bytes(), + ) + .await + .unwrap(); + let mut bytes = Vec::new(); + tokio::time::timeout(Duration::from_secs(10), stream.read_to_end(&mut bytes)) + .await + .unwrap() + .unwrap(); + let text = String::from_utf8_lossy(&bytes); + let status = text.split(' ').nth(1).unwrap().parse().unwrap(); + let location = text + .lines() + .take_while(|line| !line.is_empty()) + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("location") + .then(|| value.trim().to_string()) + }); + (status, location) + } + + /// Starts a gateway at `addr` and waits until 127.0.0.1 answers `/healthz`. + fn start_test_gateway( + addr: String, + data: PathBuf, + ) -> ( + oneshot::Sender<()>, + tokio::task::JoinHandle>, + ) { + let (stop_tx, stop_rx) = oneshot::channel::<()>(); + let server = tokio::spawn(async move { + start_gateway_server_with_shutdown( + &addr, + None, + GatewayCollaborationContext::default(), + data.join("cache"), + data, + None, + async { + let _ = stop_rx.await; + }, + ) + .await + }); + (stop_tx, server) + } + + async fn wait_for_health( + server: &tokio::task::JoinHandle>, + connect: SocketAddr, + ) { + let deadline = tokio::time::Instant::now() + Duration::from_secs(20); + while tokio::net::TcpStream::connect(connect).await.is_err() { + assert!(!server.is_finished(), "the test gateway stopped"); + assert!( + tokio::time::Instant::now() < deadline, + "gateway did not listen" + ); + tokio::time::sleep(Duration::from_millis(20)).await; + } } #[cfg(unix)] @@ -750,6 +1075,58 @@ mod trusted_gateway_tests { assert!(!crate::runtime_control::gateway_runtime_coord_path(temp.path()).exists()); } + /// `elastos serve` holds the host lock as `serve` and can start a gateway in the + /// same process. That gateway starts, and its `/healthz` is not Home readiness. + #[tokio::test] + async fn gateway_inside_serve_starts_and_answers_health_unavailable() { + let temp = tempfile::tempdir().unwrap(); + let data = temp.path().to_path_buf(); + let addr = unused_localhost_address(); + let _serve = + crate::host_lock::acquire_host_process_lock(&data, "serve", "127.0.0.1:3000").unwrap(); + let (stop_tx, stop_rx) = oneshot::channel::<()>(); + let task_addr = addr.clone(); + let task_data = data.clone(); + let server = tokio::spawn(async move { + start_gateway_server_with_shutdown( + &task_addr, + None, + GatewayCollaborationContext::default(), + task_data.join("cache"), + task_data, + None, + async { + let _ = stop_rx.await; + }, + ) + .await + }); + let client = reqwest::Client::builder() + .no_proxy() + .timeout(Duration::from_secs(2)) + .build() + .unwrap(); + let deadline = tokio::time::Instant::now() + Duration::from_secs(20); + let status = loop { + if server.is_finished() { + panic!("the gateway inside serve stopped: {:?}", server.await); + } + if let Ok(response) = client.get(format!("http://{addr}/healthz")).send().await { + break response.status(); + } + assert!(tokio::time::Instant::now() < deadline); + tokio::time::sleep(Duration::from_millis(20)).await; + }; + assert_eq!(status, reqwest::StatusCode::SERVICE_UNAVAILABLE); + let _ = stop_tx.send(()); + server.await.unwrap().unwrap(); + let lock: serde_json::Value = + serde_json::from_slice(&std::fs::read(data.join("host-process.lock")).unwrap()) + .unwrap(); + assert_eq!(lock["role"], "serve"); + assert_eq!(lock["pid"], std::process::id()); + } + #[tokio::test] async fn browser_home_ready_is_skipped_when_auth_setup_fails() { let temp = tempfile::tempdir().unwrap(); @@ -788,4 +1165,258 @@ mod trusted_gateway_tests { "http://localhost:8090" ); } + + #[test] + fn localhost_port_matches_only_the_name_localhost() { + assert_eq!(localhost_port("localhost:8090"), Some(8090)); + assert_eq!(localhost_port("LocalHost:0"), Some(0)); + assert_eq!(localhost_port("127.0.0.1:8090"), None); + assert_eq!(localhost_port("[::1]:8090"), None); + assert_eq!(localhost_port("0.0.0.0:8090"), None); + assert_eq!(localhost_port("home.localhost:8090"), None); + assert_eq!(localhost_port("localhost"), None); + } + + #[test] + fn localhost_addresses_add_both_browser_loopbacks_once() { + let v4 = SocketAddr::from((Ipv4Addr::LOCALHOST, 8090)); + let v6 = SocketAddr::from((Ipv6Addr::LOCALHOST, 8090)); + // macOS resolves ::1 first; Linux often resolves only 127.0.0.1. + assert_eq!( + localhost_bind_addresses(8090, [v6, v4, v6]).unwrap(), + vec![v6, v4] + ); + assert_eq!(localhost_bind_addresses(8090, [v4]).unwrap(), vec![v4, v6]); + assert_eq!(localhost_bind_addresses(8090, []).unwrap(), vec![v4, v6]); + } + + #[test] + fn localhost_that_points_off_this_computer_is_refused() { + let error = localhost_bind_addresses(8090, ["10.0.0.7:8090".parse().unwrap()]) + .unwrap_err() + .to_string(); + assert!(error.contains("localhost points to 10.0.0.7"), "{error}"); + } + + #[test] + fn only_a_missing_address_family_may_be_left_out() { + use std::io::{Error, ErrorKind}; + assert!(address_family_unavailable(&Error::from( + ErrorKind::AddrNotAvailable + ))); + #[cfg(unix)] + { + assert!(address_family_unavailable(&Error::from_raw_os_error( + libc::EAFNOSUPPORT + ))); + assert!(address_family_unavailable(&Error::from_raw_os_error( + libc::EADDRNOTAVAIL + ))); + assert!(!address_family_unavailable(&Error::from_raw_os_error( + libc::EADDRINUSE + ))); + assert!(!address_family_unavailable(&Error::from_raw_os_error( + libc::EACCES + ))); + } + assert!(!address_family_unavailable(&Error::from( + ErrorKind::AddrInUse + ))); + assert!(!address_family_unavailable(&Error::from( + ErrorKind::PermissionDenied + ))); + } + + #[tokio::test] + async fn localhost_binds_ipv4_and_ipv6_loopback_on_one_port() { + let v4 = SocketAddr::from((Ipv4Addr::LOCALHOST, 0)); + let v6 = SocketAddr::from((Ipv6Addr::LOCALHOST, 0)); + let listeners = bind_localhost_listeners(0, vec![v4, v6]).await.unwrap(); + let bound = listeners + .iter() + .map(|listener| listener.local_addr().unwrap()) + .collect::>(); + let port = bound[0].port(); + assert_ne!(port, 0); + if ipv6_loopback().is_none() { + // This host can only listen on 127.0.0.1; ::1 is left out, not an error. + assert_eq!(bound, vec![SocketAddr::from((Ipv4Addr::LOCALHOST, port))]); + return; + } + assert_eq!( + bound, + vec![ + SocketAddr::from((Ipv4Addr::LOCALHOST, port)), + SocketAddr::from((Ipv6Addr::LOCALHOST, port)), + ] + ); + for address in bound { + tokio::net::TcpStream::connect(address).await.unwrap(); + } + } + + /// A hostile or stale program that holds one localhost address must not + /// receive the Home origin while the gateway listens on the other one. + #[tokio::test] + async fn localhost_refuses_to_start_when_another_program_holds_ipv4_loopback() { + let temp = tempfile::tempdir().unwrap(); + let port = unused_loopback_port(); + let _hostile = std::net::TcpListener::bind((Ipv4Addr::LOCALHOST, port)).unwrap(); + let error = start_gateway_server_with_ready( + &format!("localhost:{port}"), + None, + GatewayCollaborationContext::default(), + temp.path().join("cache"), + temp.path().to_path_buf(), + Some(unexpected_ready), + ) + .await + .unwrap_err(); + assert_eq!( + error.to_string(), + format!( + "Home cannot start because another program already uses 127.0.0.1:{port}. \ + Stop that program, then start Home again." + ) + ); + assert_eq!( + error.downcast_ref::().unwrap().kind(), + std::io::ErrorKind::AddrInUse + ); + assert!(!crate::runtime_control::gateway_runtime_coord_path(temp.path()).exists()); + } + + #[tokio::test] + async fn localhost_refuses_to_start_when_another_program_holds_ipv6_loopback() { + if ipv6_loopback().is_none() { + return; + } + let temp = tempfile::tempdir().unwrap(); + let port = unused_loopback_port(); + let _hostile = std::net::TcpListener::bind((Ipv6Addr::LOCALHOST, port)).unwrap(); + let error = start_gateway_server_with_ready( + &format!("localhost:{port}"), + None, + GatewayCollaborationContext::default(), + temp.path().join("cache"), + temp.path().to_path_buf(), + Some(unexpected_ready), + ) + .await + .unwrap_err(); + assert_eq!( + error.to_string(), + format!( + "Home cannot start because another program already uses [::1]:{port}. \ + Stop that program, then start Home again." + ) + ); + assert!(!crate::runtime_control::gateway_runtime_coord_path(temp.path()).exists()); + } + + #[tokio::test] + async fn ip_literal_addr_binds_one_listener_as_before() { + let listeners = bind_gateway_listeners("127.0.0.1:0").await.unwrap(); + assert_eq!(listeners.len(), 1); + assert_eq!( + listeners[0].local_addr().unwrap().ip(), + IpAddr::V4(Ipv4Addr::LOCALHOST) + ); + let held = listeners[0].local_addr().unwrap().to_string(); + let error = bind_gateway_listeners(&held).await.unwrap_err(); + // The plain io error, with no localhost message added. + assert_eq!(error.chain().count(), 1); + assert_eq!( + error.downcast_ref::().unwrap().kind(), + std::io::ErrorKind::AddrInUse + ); + } + + #[tokio::test] + async fn loopback_ip_home_pages_move_to_localhost_and_other_routes_stay() { + let temp = tempfile::tempdir().unwrap(); + let port = unused_loopback_port(); + let v4 = SocketAddr::from((Ipv4Addr::LOCALHOST, port)); + let (stop, server) = + start_test_gateway(format!("localhost:{port}"), temp.path().to_path_buf()); + wait_for_health(&server, v4).await; + let ip_host = format!("127.0.0.1:{port}"); + for path in [ + "/", + "/home", + "/home/", + "/apps/home", + "/apps/home/", + "/home/?pair=1", + ] { + assert_eq!( + raw_get(v4, &ip_host, path).await, + (308, Some(format!("http://localhost:{port}{path}"))), + "{path}" + ); + } + assert_eq!( + raw_get(v4, &format!("[::1]:{port}"), "/home/").await, + (308, Some(format!("http://localhost:{port}/home/"))) + ); + // Health, API, and Home assets answer on the IP host itself. A + // launcher probes each address with `Host: localhost:`. + assert_eq!(raw_get(v4, &ip_host, "/healthz").await, (200, None)); + assert_eq!( + raw_get(v4, &format!("localhost:{port}"), "/healthz").await, + (200, None) + ); + for path in ["/api/auth/passkeys", "/home/index.html", "/apps/chat-room/"] { + let (status, location) = raw_get(v4, &ip_host, path).await; + assert_ne!(status, 308, "{path}"); + assert_eq!(location, None, "{path}"); + } + // localhost itself and hosts that are not loopback IPs are served in place. + for host in [ + format!("localhost:{port}"), + format!("example.com:{port}"), + format!("10.0.0.7:{port}"), + ] { + let (status, location) = raw_get(v4, &host, "/home/").await; + assert_ne!(status, 308, "{host}"); + assert_eq!(location, None, "{host}"); + } + if ipv6_loopback().is_some() { + let v6 = SocketAddr::from((Ipv6Addr::LOCALHOST, port)); + assert_eq!( + raw_get(v6, &format!("[::1]:{port}"), "/healthz").await, + (200, None) + ); + assert_eq!( + raw_get(v6, &format!("localhost:{port}"), "/healthz").await, + (200, None) + ); + assert_eq!( + raw_get(v6, &format!("[::1]:{port}"), "/home/").await, + (308, Some(format!("http://localhost:{port}/home/"))) + ); + } + // The lock records the requested address, as the launcher compares it. + let lock: serde_json::Value = + serde_json::from_slice(&std::fs::read(temp.path().join("host-process.lock")).unwrap()) + .unwrap(); + assert_eq!(lock["addr"], format!("localhost:{port}")); + assert_eq!(lock["role"], "gateway"); + let _ = stop.send(()); + server.await.unwrap().unwrap(); + } + + #[tokio::test] + async fn ip_literal_gateway_serves_home_pages_in_place() { + let temp = tempfile::tempdir().unwrap(); + let port = unused_loopback_port(); + let v4 = SocketAddr::from((Ipv4Addr::LOCALHOST, port)); + let (stop, server) = start_test_gateway(v4.to_string(), temp.path().to_path_buf()); + wait_for_health(&server, v4).await; + let (status, location) = raw_get(v4, &v4.to_string(), "/home/").await; + assert_ne!(status, 308); + assert_eq!(location, None); + let _ = stop.send(()); + server.await.unwrap().unwrap(); + } } diff --git a/elastos/crates/elastos-server/src/api/gateway_site.rs b/elastos/crates/elastos-server/src/api/gateway_site.rs index a8257780b..4fd98fe2d 100644 --- a/elastos/crates/elastos-server/src/api/gateway_site.rs +++ b/elastos/crates/elastos-server/src/api/gateway_site.rs @@ -429,8 +429,17 @@ pub(super) fn request_host(headers: &HeaderMap) -> anyhow::Result Ok(Some(validated_gateway_host(headers)?)) } -pub(super) async fn healthz() -> &'static str { - "OK" +/// Launcher readiness, `docs/LAUNCHER_CONTRACT.md` ("Readiness and Home URL"). +/// The process that owns the listening socket answers. The body is the two +/// bytes `OK` only while this process holds the host lock as a gateway; the +/// JSON record in the lock file is not read. Any process of the same user can +/// hold that lock. While another process holds it, this one answers 503. +pub(super) async fn healthz(State(state): State) -> Response { + if crate::host_lock::holds_gateway_host_lock(&state.data_dir) { + (StatusCode::OK, "OK").into_response() + } else { + StatusCode::SERVICE_UNAVAILABLE.into_response() + } } pub(super) async fn serve_release_manifest( diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs b/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs index 3422de43a..cf7aea7ef 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/content_sandbox.rs @@ -287,6 +287,7 @@ async fn content_sandbox_site_files_and_admitted_bundle_preserve_provenance() { assert_eq!(home.status(), StatusCode::OK); assert_eq!(home.headers().get("content-security-policy").unwrap(), "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' blob: data:; connect-src 'self'; frame-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'"); + let _gateway_lock = super::hold_gateway_health_lock(dir.path()); let health = app .oneshot( Request::builder() diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/frontdoor.rs b/elastos/crates/elastos-server/src/api/gateway_tests/frontdoor.rs index 2d7f1c00b..dbccd9a60 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/frontdoor.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/frontdoor.rs @@ -45,6 +45,7 @@ async fn frontdoor_refuses_foreign_origins_rebinding_and_missing_or_duplicate_ho app.clone().oneshot(duplicate).await.unwrap().status(), StatusCode::FORBIDDEN ); + let _gateway_lock = super::hold_gateway_health_lock(dir.path()); let valid = Request::builder() .uri("/healthz") .header(HOST, "127.0.0.1:61180") @@ -154,6 +155,7 @@ async fn frontdoor_public_list_requires_configured_gateway_host() { "gateway_allowed_hosts = [\"home.example.test\"]\n", ) .unwrap(); + let _gateway_lock = super::hold_gateway_health_lock(dir.path()); let app = app(dir.path()); let response = app .clone() 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/api/gateway_tests/mod.rs b/elastos/crates/elastos-server/src/api/gateway_tests/mod.rs index 79383eaf6..8afbffb4a 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/mod.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/mod.rs @@ -86,6 +86,11 @@ fn test_launch_token_from_route(route: &str) -> String { .expect("launch route home token") } +/// Takes the host lock as this test process's gateway, as `elastos gateway` does. +pub(super) fn hold_gateway_health_lock(data_dir: &std::path::Path) -> crate::host_lock::FileLock { + crate::host_lock::acquire_host_process_lock(data_dir, "gateway", "localhost:8090").unwrap() +} + fn test_state(cache_dir: &std::path::Path) -> GatewayState { seed_test_browser_capsules(cache_dir); GatewayState { diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/site_publication.rs b/elastos/crates/elastos-server/src/api/gateway_tests/site_publication.rs index e4f3971f2..ebc300a3a 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/site_publication.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/site_publication.rs @@ -221,9 +221,11 @@ async fn test_root_serves_mywebsite_when_staged() { assert_eq!(&body[..], b"home site"); } +/// Launcher readiness. The body is the two bytes `OK` when this process holds the lock. #[tokio::test] async fn test_healthz_200() { let dir = tempfile::tempdir().unwrap(); + let _gateway_lock = super::hold_gateway_health_lock(dir.path()); let state = test_state(dir.path()); let app = gateway_router(state); @@ -238,6 +240,234 @@ async fn test_healthz_200() { .unwrap(); assert_eq!(resp.status(), StatusCode::OK); + let body = axum::body::to_bytes(resp.into_body(), usize::MAX) + .await + .unwrap(); + assert_eq!(&body[..], b"OK"); + assert_eq!(body.len(), 2); +} + +async fn healthz_status(data_dir: &std::path::Path) -> StatusCode { + gateway_router(test_state(data_dir)) + .oneshot( + Request::builder() + .uri("/healthz") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap() + .status() +} + +/// Another process of the same user can rewrite `host-process.lock`. Health +/// reads ownership from the flock this process holds, never from that record. +#[tokio::test] +async fn test_healthz_refuses_a_forged_or_foreign_lock_owner() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("host-process.lock"); + let pid = std::process::id(); + let record = |pid: &str, role: &str| { + format!("{{\"pid\":{pid},\"role\":\"{role}\",\"addr\":\"localhost:8090\"}}\n") + }; + let forged = record(&pid.to_string(), "gateway"); + + // No process holds the lock. A record that names this gateway is a forgery. + for (case, bytes) in [ + ("this pid as gateway", forged.clone()), + ( + "this pid as gateway-public", + record(&pid.to_string(), "gateway-public"), + ), + ( + "another pid", + record(&pid.wrapping_add(1).to_string(), "gateway"), + ), + ("another role", record(&pid.to_string(), "serve")), + ( + "a pid that is a string", + record(&format!("\"{pid}\""), "gateway"), + ), + ("not JSON", "not-json".to_string()), + ] { + std::fs::write(&path, bytes).unwrap(); + assert_eq!( + healthz_status(dir.path()).await, + StatusCode::SERVICE_UNAVAILABLE, + "unheld lock, {case}" + ); + } + std::fs::remove_file(&path).unwrap(); + assert_eq!( + healthz_status(dir.path()).await, + StatusCode::SERVICE_UNAVAILABLE, + "missing lock" + ); + + // Another lock holder, here a separate open file in place of another + // process, owns the flock while the record names this gateway. + std::fs::write(&path, &forged).unwrap(); + let foreign = + crate::host_lock::FileLock::try_exclusive(std::fs::File::open(&path).unwrap()).unwrap(); + assert_eq!( + healthz_status(dir.path()).await, + StatusCode::SERVICE_UNAVAILABLE, + "foreign holder" + ); + drop(foreign); + + // This process holds the lock as `serve`. A record rewritten to `gateway` is refused. + let serve = + crate::host_lock::acquire_host_process_lock(dir.path(), "serve", "127.0.0.1:3000").unwrap(); + std::fs::write(&path, &forged).unwrap(); + assert_eq!( + healthz_status(dir.path()).await, + StatusCode::SERVICE_UNAVAILABLE, + "serve lock" + ); + drop(serve); + + // This process holds the lock as a gateway. The record does not change the answer. + let gateway = super::hold_gateway_health_lock(dir.path()); + assert_eq!(healthz_status(dir.path()).await, StatusCode::OK); + for bytes in [ + record(&pid.wrapping_add(1).to_string(), "gateway"), + record(&pid.to_string(), "serve"), + "not-json".to_string(), + ] { + std::fs::write(&path, bytes).unwrap(); + assert_eq!(healthz_status(dir.path()).await, StatusCode::OK); + } + + // A replaced lock file is not the file this gateway locked. + std::fs::remove_file(&path).unwrap(); + std::fs::write(&path, &forged).unwrap(); + assert_eq!( + healthz_status(dir.path()).await, + StatusCode::SERVICE_UNAVAILABLE, + "replaced file" + ); + drop(gateway); + + // After the gateway releases its lock, the record it left is not readiness. + let gateway = super::hold_gateway_health_lock(dir.path()); + assert_eq!(healthz_status(dir.path()).await, StatusCode::OK); + drop(gateway); + assert!(std::fs::read_to_string(&path) + .unwrap() + .contains("\"gateway\"")); + assert_eq!( + healthz_status(dir.path()).await, + StatusCode::SERVICE_UNAVAILABLE, + "released lock" + ); + + let contract = std::fs::read_to_string(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../docs/LAUNCHER_CONTRACT.md" + )) + .unwrap(); + assert!(contract.contains("http://localhost:8090/home/")); + assert!(contract.contains("two bytes `OK`")); + assert!(!contract.contains("three bytes")); + assert!(!contract.contains("darwin-x64")); + assert!(!contract.contains("127.0.0.1:8090/home/")); + // The reply describes the answering process, so the contract states that gap. + assert!(!contract.contains("does not treat another")); + assert!(contract.contains("The reply does not name the process.")); + assert!(contract.contains("its `/healthz` returns 503")); + // The contract names the flock, not the record, as the proof of ownership. + assert!(contract.contains("What proves that this gateway holds the lock:")); + assert!(!contract.contains("recorded owner")); +} + +/// The host lock proves possession, not identity (`docs/LAUNCHER_CONTRACT.md`, +/// "Readiness and Home URL"). A separate process of the same user that is not +/// a gateway, and not ElastOS, opens the lock file and holds the flock. The +/// record names that process as a gateway. From outside the holder, the held +/// lock and the record look the same as a gateway's. +/// The gateway refuses to start, and `/healthz` here does not treat that +/// holder as this gateway. +#[tokio::test] +async fn test_the_host_lock_proves_possession_not_that_the_holder_is_the_gateway() { + use crate::host_lock::test_support::{lock_is_free, HeldByAnotherProcess}; + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("host-process.lock"); + std::fs::write(&path, "").unwrap(); + let holder = HeldByAnotherProcess::new(&path); + std::fs::write( + &path, + format!( + "{{\"pid\":{},\"role\":\"gateway\",\"addr\":\"localhost:8090\"}}\n", + holder.pid() + ), + ) + .unwrap(); + + // The lock is held, and the report looks like a gateway with that pid. + // The holder is `/bin/sleep`. + assert!(!lock_is_free(&path), "the other process holds the lock"); + let reported = crate::host_lock::active_host_process(dir.path()) + .unwrap() + .expect("a held lock is reported as held"); + assert_eq!( + (reported.pid, reported.role.as_str()), + (holder.pid(), "gateway") + ); + + // A gateway for this data directory does not start, by either path. + for start in [ + crate::host_lock::acquire_host_process_lock(dir.path(), "gateway", "localhost:8090") + .map(|_| ()), + crate::host_lock::publish_gateway_lock_if_unowned(dir.path(), "localhost:8090").map(|_| ()), + ] { + let err = start.expect_err("a gateway does not start while another process holds the lock"); + let text = err.to_string(); + assert!(text.contains("another ElastOS host already owns"), "{text}"); + assert!(text.contains(&format!("pid {}", holder.pid())), "{text}"); + } + + // This process does not hold the lock, so it does not claim to be the + // gateway: its `/healthz` answers 503, and it gives no descriptor to a child. + assert_eq!(crate::host_lock::held_host_role(dir.path()), None); + assert!(!crate::host_lock::holds_gateway_host_lock(dir.path())); + assert!(crate::host_lock::gateway_host_lock_for_child(dir.path()).is_none()); + assert_eq!( + healthz_status(dir.path()).await, + StatusCode::SERVICE_UNAVAILABLE, + "a lock held by another process" + ); + + // When the other process ends, its lock ends, and the record it left + // proves nothing. Then this process takes the lock and answers `OK`. + holder.stop(); + assert!(lock_is_free(&path)); + assert!(std::fs::read_to_string(&path) + .unwrap() + .contains("\"gateway\"")); + assert!(crate::host_lock::active_host_process(dir.path()) + .unwrap() + .is_none()); + assert_eq!( + healthz_status(dir.path()).await, + StatusCode::SERVICE_UNAVAILABLE, + "the record left by the ended holder" + ); + let gateway = super::hold_gateway_health_lock(dir.path()); + assert_eq!(healthz_status(dir.path()).await, StatusCode::OK); + drop(gateway); + + let contract = std::fs::read_to_string(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../docs/LAUNCHER_CONTRACT.md" + )) + .unwrap(); + let contract = contract.split_whitespace().collect::>().join(" "); + assert!(contract.contains("The lock proves possession, not identity.")); + assert!(contract.contains("That does not prove that the holder is a gateway")); + assert!( + contract.contains("when any process holds the lock, also a process that is not ElastOS") + ); } #[tokio::test] @@ -679,6 +909,7 @@ async fn test_concurrent_release_reads_wait_health_works_and_scan_once() { .is_err() ); assert!(requests.iter().all(|request| !request.is_finished())); + let _gateway_lock = super::hold_gateway_health_lock(&fixture.base); let response = app .clone() .oneshot( diff --git a/elastos/crates/elastos-server/src/api/handlers/identity.rs b/elastos/crates/elastos-server/src/api/handlers/identity.rs index 807aa2400..004c96f85 100644 --- a/elastos/crates/elastos-server/src/api/handlers/identity.rs +++ b/elastos/crates/elastos-server/src/api/handlers/identity.rs @@ -482,7 +482,9 @@ fn issue_passkey_session_grant( } fn owner_error(error: anyhow::Error) -> (StatusCode, Json) { - let status = if error.is::() { + let status = if error.is::() + || error.is::() + { StatusCode::FORBIDDEN } else { StatusCode::INTERNAL_SERVER_ERROR diff --git a/elastos/crates/elastos-server/src/auth.rs b/elastos/crates/elastos-server/src/auth.rs index 9abc2ef10..207b18400 100644 --- a/elastos/crates/elastos-server/src/auth.rs +++ b/elastos/crates/elastos-server/src/auth.rs @@ -1368,7 +1368,7 @@ pub fn arm_owner_recovery( ttl_secs: u64, ) -> anyhow::Result> { let origin_url = url::Url::parse(origin).map_err(|_| OwnerEnrollmentDenied)?; - let loopback = matches!(origin_url.host_str(), Some("localhost" | "127.0.0.1")); + let loopback = origin_url.host_str() == Some("localhost"); if origin.len() > 512 || rp_id.len() > 253 || !(origin_url.scheme() == "https" || origin_url.scheme() == "http" && loopback) @@ -1831,6 +1831,65 @@ fn check_owner_claim( Ok(()) } +/// A passkey ceremony from a page address that cannot use the stored or local passkey. +/// The text is the reply body, so it tells the person which address to open. +#[derive(Debug)] +pub(crate) struct PasskeyOriginRefused { + local_home: Option, +} +impl std::fmt::Display for PasskeyOriginRefused { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match &self.local_home { + Some(home) => write!( + f, + "Passkeys work on this computer only at the localhost address. Open {home} and try again." + ), + None => f.write_str( + "This passkey works only at the Home address where you made it. Open Home at that address and try again.", + ), + } + } +} +impl std::error::Error for PasskeyOriginRefused {} + +/// The Home URL at `localhost` with the same port, for a loopback page address. +fn local_home_for(url: &url::Url) -> Option { + let loopback = match url.host()? { + url::Host::Domain(host) => host.eq_ignore_ascii_case("localhost"), + url::Host::Ipv4(address) => address.is_loopback(), + url::Host::Ipv6(address) => address.is_loopback(), + }; + loopback.then(|| match url.port() { + Some(port) => format!("http://localhost:{port}/home/"), + None => "http://localhost/home/".to_string(), + }) +} + +fn require_localhost_origin(origin: &str, rp_id: &str) -> anyhow::Result<()> { + let url = url::Url::parse(origin).map_err(|_| OwnerEnrollmentDenied)?; + if url.scheme() != "http" || url.host_str() != Some("localhost") || rp_id != "localhost" { + return Err(PasskeyOriginRefused { + local_home: local_home_for(&url), + } + .into()); + } + Ok(()) +} + +/// Browsers bind a passkey to the page host (its relying party id) and refuse an +/// IP address as that id. Sign-in accepts the stored host on any port. +fn require_passkey_origin(origin: &str, rp_id: &str) -> anyhow::Result<()> { + let url = url::Url::parse(origin).map_err(|_| OwnerEnrollmentDenied)?; + let matches = matches!(url.host(), Some(url::Host::Domain(host)) if host == rp_id); + if !matches { + let local_home = (rp_id == "localhost") + .then(|| local_home_for(&url)) + .flatten(); + return Err(PasskeyOriginRefused { local_home }.into()); + } + Ok(()) +} + pub(crate) fn begin_owner_enrollment( data_dir: &Path, identity: &mut elastos_identity::IdentityManager, @@ -1851,6 +1910,9 @@ pub(crate) fn begin_owner_enrollment_with_intent( now: u64, ) -> anyhow::Result)>> { validate_owner_enrollment_intent(intent)?; + if request.loopback { + require_localhost_origin(request.origin, request.rp_id)?; + } mutate_auth_state(data_dir, |state| { identity.reload_credentials()?; if let Some(record) = &state.owner_enrollment { @@ -2784,6 +2846,90 @@ mod owner_recovery_tests { .to_string() } + #[test] + fn local_home_passkey_registers_and_signs_in_at_localhost() { + let origin = "http://localhost:8090"; + let root = tempfile::tempdir().unwrap(); + let mut identity = elastos_identity::IdentityManager::new(root.path().into()).unwrap(); + let secret = random_secret_hex(); + let owner = OwnerAdmission { + origin, + rp_id: "localhost", + claimant: &secret, + loopback: true, + }; + let (_, options) = + begin_owner_enrollment(root.path(), &mut identity, &owner, "owner", now_ts()) + .unwrap() + .unwrap(); + let response = + owner_attestation_for_test(&options.unwrap().public_key.challenge, "localhost", origin); + let grant = complete_owner_enrollment( + root.path(), + &mut identity, + &owner, + "owner", + Some(&response), + None, + now_ts(), + ) + .unwrap() + .unwrap(); + let credential = identity + .credentials() + .into_iter() + .find(|credential| credential.rp_id == "localhost") + .unwrap(); + let signed_in = grant_passkey_session( + root.path(), + PasskeySessionRequest { + credential: &credential, + origin, + user_verified: true, + display_name: None, + profile_display_name: None, + reason: "local home sign-in", + purpose: PasskeySessionPurpose::SignIn, + }, + ) + .unwrap(); + assert_eq!(signed_in.principal_id, grant.principal_id); + assert!(grant_passkey_session( + root.path(), + PasskeySessionRequest { + credential: &credential, + origin: "http://127.0.0.1:8090", + user_verified: true, + display_name: None, + profile_display_name: None, + reason: "ip literal sign-in", + purpose: PasskeySessionPurpose::SignIn, + }, + ) + .is_err()); + + let fresh = tempfile::tempdir().unwrap(); + let mut fresh_identity = + elastos_identity::IdentityManager::new(fresh.path().into()).unwrap(); + let ip_owner = OwnerAdmission { + origin: "http://127.0.0.1:8090", + rp_id: "127.0.0.1", + claimant: &secret, + loopback: true, + }; + assert!(begin_owner_enrollment( + fresh.path(), + &mut fresh_identity, + &ip_owner, + "ip", + now_ts() + ) + .is_err()); + assert!( + arm_owner_recovery(fresh.path(), "http://127.0.0.1:8090", "127.0.0.1", 300).is_err() + ); + } + fn begin( home: &mut Home, code: &str, @@ -3874,6 +4020,7 @@ fn grant_passkey_session_in_state( now: u64, ) -> anyhow::Result { let credential = request.credential; + require_passkey_origin(request.origin, &credential.rp_id)?; let mut binding = ProofBinding::passkey_webauthn(elastos_runtime::auth::PasskeyWebAuthnBinding { credential_id: credential.credential_id.clone(), diff --git a/elastos/crates/elastos-server/src/gateway_entry.rs b/elastos/crates/elastos-server/src/gateway_entry.rs index 1918155cd..fcdde1be3 100644 --- a/elastos/crates/elastos-server/src/gateway_entry.rs +++ b/elastos/crates/elastos-server/src/gateway_entry.rs @@ -1,3 +1,5 @@ +/// Supervised Home entry. `docs/LAUNCHER_CONTRACT.md` is the launcher +/// interface. This entry does not open a browser. pub async fn run_gateway( addr: String, public: bool, diff --git a/elastos/crates/elastos-server/src/host_lock.rs b/elastos/crates/elastos-server/src/host_lock.rs index e2988fb7f..0fd3a1c36 100644 --- a/elastos/crates/elastos-server/src/host_lock.rs +++ b/elastos/crates/elastos-server/src/host_lock.rs @@ -8,13 +8,24 @@ use serde::{Deserialize, Serialize}; /// An exclusive flock held for this guard's scope. #[derive(Debug)] -pub struct FileLock(Option); +pub struct FileLock { + file: Option, + /// Set while this guard is the host lock of a data directory. + held_host: Option, +} impl FileLock { + fn held(file: fs::File) -> Self { + Self { + file: Some(file), + held_host: None, + } + } + /// Waits until this open file holds the exclusive lock. pub(crate) fn exclusive(file: fs::File) -> std::io::Result { file.lock()?; - Ok(Self(Some(file))) + Ok(Self::held(file)) } /// Takes the exclusive lock now or fails with `WouldBlock`. @@ -27,7 +38,7 @@ impl FileLock { let deadline = Instant::now() + wait; loop { match file.try_lock() { - Ok(()) => return Ok(Self(Some(file))), + Ok(()) => return Ok(Self::held(file)), Err(fs::TryLockError::WouldBlock) if Instant::now() < deadline => { let remaining = deadline.saturating_duration_since(Instant::now()); std::thread::sleep(remaining.min(Duration::from_millis(5))); @@ -39,7 +50,8 @@ impl FileLock { /// Unlocks now and reports the result; dropping instead discards it. pub(crate) fn release(mut self) -> std::io::Result<()> { - self.0.take().map_or(Ok(()), |file| file.unlock()) + forget_held_host_lock(self.held_host.take()); + self.file.take().map_or(Ok(()), |file| file.unlock()) } } @@ -47,21 +59,209 @@ impl std::ops::Deref for FileLock { type Target = fs::File; fn deref(&self) -> &fs::File { - self.0.as_ref().expect("only release takes the file") + self.file.as_ref().expect("only release takes the file") } } impl Drop for FileLock { fn drop(&mut self) { + // This process stops claiming the host lock before it unlocks. + forget_held_host_lock(self.held_host.take()); // A command spawned meanwhile by another thread can retain this // description until its CLOEXEC fd closes at exec. The guard's scope // owns the lock, so release it before closing our fd. - if let Some(file) = &self.0 { + if let Some(file) = &self.file { let _ = file.unlock(); } } } +/// Host locks that this process holds now. `docs/LAUNCHER_CONTRACT.md` +/// ("Readiness and Home URL") states what the lock proves. The JSON record +/// in the lock file is not proof: any process of the same user can rewrite it. +/// The flock proves possession, not identity: any process of the same user can +/// hold it. So this process proves only that it holds the lock itself. +/// +/// Each entry keeps a second descriptor of the open file description that +/// holds the flock. A proof keeps this mutex for its whole check, and a guard +/// removes its entry under the mutex before it unlocks. So no release or +/// retake can come between finding an entry and probing its lock. +static HELD_HOST_LOCKS: std::sync::Mutex> = std::sync::Mutex::new(Vec::new()); +static NEXT_HELD_HOST_LOCK: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + +#[derive(Debug)] +struct HeldHostLock { + id: u64, + /// The same open file description as the guard's file (a `dup`). + file: fs::File, + role: String, +} + +/// The file a lock is on. While this process keeps the file open, no other +/// file can have the same device and inode. +type LockedFileId = (u64, u64); + +#[cfg(unix)] +fn locked_file_id(metadata: &fs::Metadata) -> Option { + use std::os::unix::fs::MetadataExt as _; + Some((metadata.dev(), metadata.ino())) +} + +/// Without a device and inode, this process cannot prove the path names the +/// file it locked, so it claims no host lock. +#[cfg(not(unix))] +fn locked_file_id(_metadata: &fs::Metadata) -> Option { + None +} + +fn held_host_locks() -> std::sync::MutexGuard<'static, Vec> { + HELD_HOST_LOCKS + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} + +fn remember_held_host_lock(lock: &mut FileLock, role: &str) -> std::io::Result<()> { + if locked_file_id(&lock.metadata()?).is_none() { + return Ok(()); + } + let file = lock.try_clone()?; + let id = NEXT_HELD_HOST_LOCK.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + held_host_locks().push(HeldHostLock { + id, + file, + role: role.to_string(), + }); + lock.held_host = Some(id); + Ok(()) +} + +fn forget_held_host_lock(id: Option) { + if let Some(id) = id { + held_host_locks().retain(|held| held.id != id); + } +} + +/// Whether the open file description of `held` holds the exclusive flock on +/// the file that `lock_path` names now. +/// +/// 1. `lock_path` names the same file (device and inode) as `held`. +/// 2. A new open of that file cannot take the lock, so some description holds it. +/// 3. `held` can take it. A description that already holds an exclusive flock +/// takes it again with no change, and any other holder blocks this step. +/// +/// If no description holds the lock at step 2, the check stops there and +/// changes nothing. Step 3 changes the lock only when the holder from step 2 +/// released it in the meantime: then `held` takes it. +fn description_holds_lock(lock_path: &Path, held: &fs::File) -> bool { + let Ok(probe) = fs::File::open(lock_path) else { + return false; + }; + let (Ok(probe_metadata), Ok(held_metadata)) = (probe.metadata(), held.metadata()) else { + return false; + }; + match ( + locked_file_id(&probe_metadata), + locked_file_id(&held_metadata), + ) { + (Some(path_file), Some(held_file)) if path_file == held_file => {} + _ => return false, + } + match probe.try_lock() { + Err(fs::TryLockError::WouldBlock) => {} + Ok(()) => { + // The lock was free, so no description holds it. + let _ = probe.unlock(); + return false; + } + Err(fs::TryLockError::Error(_)) => return false, + } + held.try_lock().is_ok() +} + +#[cfg(test)] +thread_local! { + /// Runs inside a proof after it finds a matching entry and before it + /// probes the lock: the point a release or retake must not reach. + static BEFORE_HELD_HOST_LOCK_PROBE: std::cell::RefCell>> = + std::cell::RefCell::new(None); +} + +/// The entry whose description holds the host lock of `data_dir` now. The +/// caller keeps the registry locked while it uses the entry. +fn proven_held_host_lock<'a>( + held: &'a [HeldHostLock], + data_dir: &Path, +) -> Option<&'a HeldHostLock> { + let lock_path = host_lock_path(data_dir); + held.iter().find(|entry| { + #[cfg(test)] + if let Some(hook) = BEFORE_HELD_HOST_LOCK_PROBE.with(|hook| hook.borrow_mut().take()) { + hook(); + } + description_holds_lock(&lock_path, &entry.file) + }) +} + +fn is_gateway_role(role: &str) -> bool { + matches!(role, "gateway" | "gateway-public") +} + +/// The role under which this process holds the host lock of `data_dir`. +/// +/// The proof is the flock itself: an open file description that this process +/// keeps holds the exclusive lock on the file `{data}/host-process.lock` names +/// now. The JSON record is not read. The registry stays locked from the +/// lookup to the end of the probe, so the lookup and the probe are one step. +pub fn held_host_role(data_dir: &Path) -> Option { + let held = held_host_locks(); + proven_held_host_lock(&held, data_dir).map(|entry| entry.role.clone()) +} + +/// Whether this process holds the host lock of `data_dir` as a gateway. +pub fn holds_gateway_host_lock(data_dir: &Path) -> bool { + held_host_role(data_dir).is_some_and(|role| is_gateway_role(&role)) +} + +/// A new descriptor of the gateway host lock this process holds for +/// `data_dir`, for a child process that must prove its parent gateway holds +/// the lock (see [`inherited_gateway_host_lock_is_held`]). `None` when this +/// process does not hold that lock as a gateway now. +pub fn gateway_host_lock_for_child(data_dir: &Path) -> Option { + let held = held_host_locks(); + proven_held_host_lock(&held, data_dir) + .filter(|entry| is_gateway_role(&entry.role)) + .and_then(|entry| entry.file.try_clone().ok()) +} + +/// Whether the inherited descriptor `fd`, which a gateway gave this process +/// with [`gateway_host_lock_for_child`], still holds the host lock of +/// `data_dir`. The check is the same flock proof the gateway uses for +/// `/healthz`, run against the gateway's own open file description. The JSON +/// record is not read. After the gateway releases its lock, or after another +/// process takes the lock, the answer is `false`. A `true` answer proves that +/// `fd` holds the lock, not that the process that gave it is a gateway: any +/// process of the same user that holds the lock can give its descriptor. +/// +/// The check marks `fd` close-on-exec, so commands this process starts later +/// do not receive it. This process never closes `fd`. If the gateway releases +/// its lock in the short time between the two probes, the second probe takes +/// the lock again through the shared open file, and this process keeps the +/// home locked until it exits. That fails closed: no second host can start. +#[cfg(unix)] +pub fn inherited_gateway_host_lock_is_held(data_dir: &Path, fd: std::os::fd::RawFd) -> bool { + use std::os::fd::FromRawFd as _; + if fd <= libc::STDERR_FILENO { + return false; + } + // A descriptor number from the environment may be closed or reused. + if unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) } == -1 { + return false; + } + // Borrow the descriptor: this process did not open it and never closes it. + let inherited = std::mem::ManuallyDrop::new(unsafe { fs::File::from_raw_fd(fd) }); + description_holds_lock(&host_lock_path(data_dir), &inherited) +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct HostProcessInfo { pub pid: u32, @@ -78,6 +278,21 @@ struct HostProcessMeta { generation: String, } +/// The gateway server takes the host lock as `gateway` unless this process +/// already holds it. `gateway` and `gateway-public` take it before the server +/// starts. `serve` also holds it when its supervisor starts a gateway in the +/// same process. That gateway keeps the `serve` lock, so its `/healthz` answers 503. +/// A record that only names this pid is not a lock this process holds. +pub fn publish_gateway_lock_if_unowned( + data_dir: &Path, + addr: &str, +) -> anyhow::Result> { + if held_host_role(data_dir).is_some() { + return Ok(None); + } + acquire_host_process_lock(data_dir, "gateway", addr).map(Some) +} + pub fn acquire_host_process_lock( data_dir: &Path, role: &str, @@ -112,7 +327,7 @@ fn acquire_host_process_lock_inner( .open(&lock_path) .with_context(|| format!("open host lock {}", lock_path.display()))?; - let lock = match FileLock::try_exclusive(file) { + let mut lock = match FileLock::try_exclusive(file) { Ok(lock) => lock, Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => { let holder = read_lock_metadata(&lock_path); @@ -142,6 +357,7 @@ fn acquire_host_process_lock_inner( serde_json::to_writer_pretty(&mut file, &meta)?; writeln!(file)?; file.sync_data()?; + remember_held_host_lock(&mut lock, role)?; Ok(lock) } @@ -167,9 +383,15 @@ pub fn active_host_process(data_dir: &Path) -> anyhow::Result { - Ok(read_lock_metadata(&lock_path).map(Into::into)) - } + // The flock decides that a holder is active. It proves possession, + // not that the holder is ElastOS: any process of the same user can + // hold it. The record only describes the holder and can be false, and + // a holder whose record cannot be read is still a holder. + Err(err) if err.kind() == std::io::ErrorKind::WouldBlock => Ok(Some( + read_lock_metadata(&lock_path) + .map(Into::into) + .unwrap_or_else(HostProcessInfo::unreadable_record), + )), Err(err) => Err(err).with_context(|| format!("inspect host lock {}", lock_path.display())), } } @@ -182,6 +404,18 @@ fn read_lock_metadata(lock_path: &Path) -> Option { serde_json::from_slice(&fs::read(lock_path).ok()?).ok() } +impl HostProcessInfo { + /// A process holds the lock, but its record is missing, being written, or + /// not a record. + fn unreadable_record() -> Self { + Self { + pid: 0, + role: "unknown".to_string(), + addr: "unknown".to_string(), + } + } +} + impl From for HostProcessInfo { fn from(value: HostProcessMeta) -> Self { Self { @@ -464,6 +698,57 @@ pub(crate) mod test_support { } } + /// A separate process of the same user that is not a gateway and not + /// ElastOS (`/bin/sleep`). Before exec it opens `path` itself and takes + /// the exclusive flock on that new open file description, which it keeps + /// across exec. It shares no descriptor with this process. + pub(crate) struct HeldByAnotherProcess(Child); + + impl HeldByAnotherProcess { + pub(crate) fn new(path: &Path) -> Self { + use std::os::unix::ffi::OsStrExt as _; + let path = std::ffi::CString::new(path.as_os_str().as_bytes()).unwrap(); + let mut command = Command::new("/bin/sleep"); + command + .arg("30") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()); + unsafe { + command.pre_exec(move || { + // No O_CLOEXEC: the descriptor and its lock survive exec. + let fd = libc::open(path.as_ptr(), libc::O_RDONLY); + if fd == -1 || libc::flock(fd, libc::LOCK_EX | libc::LOCK_NB) == -1 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + // `spawn` returns after exec, so the child holds the lock now. + Self( + command + .spawn() + .expect("another process takes the host lock"), + ) + } + + pub(crate) fn pid(&self) -> u32 { + self.0.id() + } + + /// Ends the process, which releases its lock. + pub(crate) fn stop(self) { + drop(self); + } + } + + impl Drop for HeldByAnotherProcess { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + /// Whether another open description can take the exclusive lock on `path` now. pub(crate) fn lock_is_free(path: &Path) -> bool { super::FileLock::try_exclusive(std::fs::File::open(path).unwrap()).is_ok() @@ -548,6 +833,249 @@ mod tests { ); } + /// A record naming this pid, written by any process of the same user, is + /// not a lock this process holds. The gateway still takes the real lock. + #[test] + fn gateway_takes_the_lock_when_only_a_forged_record_names_this_process() { + let temp = tempfile::tempdir().expect("tempdir"); + let path = host_lock_path(temp.path()); + fs::write( + &path, + format!( + "{{\"pid\":{},\"role\":\"serve\",\"addr\":\"127.0.0.1:3000\"}}\n", + std::process::id() + ), + ) + .expect("forged record"); + assert_eq!(held_host_role(temp.path()), None); + let gateway = publish_gateway_lock_if_unowned(temp.path(), "localhost:8090") + .expect("gateway start") + .expect("the forged record does not stand in for the lock"); + assert!(!test_support::lock_is_free(&path)); + assert!(holds_gateway_host_lock(temp.path())); + let err = acquire_host_process_lock(temp.path(), "serve", "127.0.0.1:3000") + .expect_err("a second host is refused"); + assert!(err + .to_string() + .contains("another ElastOS host already owns")); + drop(gateway); + assert_eq!(held_host_role(temp.path()), None); + } + + /// A gateway inside `serve` keeps the `serve` lock that this process holds. + #[test] + fn gateway_inside_a_held_serve_lock_keeps_it() { + let temp = tempfile::tempdir().expect("tempdir"); + let serve = + acquire_host_process_lock(temp.path(), "serve", "127.0.0.1:3000").expect("serve lock"); + assert!( + publish_gateway_lock_if_unowned(temp.path(), "localhost:8090") + .expect("gateway inside serve starts") + .is_none() + ); + assert_eq!(held_host_role(temp.path()).as_deref(), Some("serve")); + assert!(!holds_gateway_host_lock(temp.path())); + serve.release().expect("release"); + assert_eq!(held_host_role(temp.path()), None); + } + + /// The proof follows the lock, not the file: a release ends it, and a + /// retake proves only the new holder. + #[test] + fn release_and_retake_prove_only_the_current_holder() { + let temp = tempfile::tempdir().expect("tempdir"); + let path = host_lock_path(temp.path()); + + let gateway = acquire_host_process_lock(temp.path(), "gateway", "localhost:8090") + .expect("gateway lock"); + assert_eq!(held_host_role(temp.path()).as_deref(), Some("gateway")); + gateway.release().expect("release"); + assert_eq!(held_host_role(temp.path()), None, "released"); + + // This process takes the lock again under another role. + let serve = + acquire_host_process_lock(temp.path(), "serve", "127.0.0.1:3000").expect("retake"); + assert_eq!(held_host_role(temp.path()).as_deref(), Some("serve")); + assert!(!holds_gateway_host_lock(temp.path())); + drop(serve); + assert_eq!(held_host_role(temp.path()), None, "dropped"); + + // Another holder (a separate open file, as another process would have) + // takes it. The record still names this process as a gateway. + let foreign = FileLock::try_exclusive(fs::File::open(&path).unwrap()).expect("foreign"); + assert!(fs::read_to_string(&path).unwrap().contains("\"serve\"")); + assert_eq!(held_host_role(temp.path()), None, "foreign holder"); + assert!(gateway_host_lock_for_child(temp.path()).is_none()); + drop(foreign); + + let gateway = acquire_host_process_lock(temp.path(), "gateway", "localhost:8090") + .expect("gateway retakes"); + assert!(holds_gateway_host_lock(temp.path())); + drop(gateway); + assert!(!holds_gateway_host_lock(temp.path())); + } + + /// A guard whose open file was unlocked behind its back (here by a direct + /// unlock; a command that shares the description can do the same) no longer + /// holds the lock. When another holder then takes it, the registry entry + /// for the same file is not proof: the probe runs on the guard's own + /// open file description. + #[test] + fn an_entry_for_the_same_file_is_not_proof_when_another_holder_has_the_lock() { + let temp = tempfile::tempdir().expect("tempdir"); + let path = host_lock_path(temp.path()); + let gateway = acquire_host_process_lock(temp.path(), "gateway", "localhost:8090") + .expect("gateway lock"); + gateway.unlock().expect("unlock behind the guard"); + let foreign = FileLock::try_exclusive(fs::File::open(&path).unwrap()).expect("foreign"); + assert!(!test_support::lock_is_free(&path)); + assert_eq!(held_host_role(temp.path()), None); + assert!(!holds_gateway_host_lock(temp.path())); + assert!(gateway_host_lock_for_child(temp.path()).is_none()); + drop(foreign); + drop(gateway); + } + + /// A release that starts after the proof finds its entry waits for the + /// probe. So a `Some` answer is never about a lock that another holder + /// took in between. + #[test] + fn a_release_and_retake_cannot_come_between_the_lookup_and_the_probe() { + use std::sync::mpsc; + let temp = tempfile::tempdir().expect("tempdir"); + let path = host_lock_path(temp.path()); + let gateway = acquire_host_process_lock(temp.path(), "gateway", "localhost:8090") + .expect("gateway lock"); + + let (retaken_tx, retaken_rx) = mpsc::channel(); + let retaken_rx = Rc::new(retaken_rx); + let (finish_tx, finish_rx) = mpsc::channel::<()>(); + let releaser = Rc::new(RefCell::new(None)); + let retaken_before_probe = Rc::new(Cell::new(false)); + let (hook_releaser, observed, hook_retaken_rx) = ( + releaser.clone(), + retaken_before_probe.clone(), + retaken_rx.clone(), + ); + let foreign_path = path.clone(); + BEFORE_HELD_HOST_LOCK_PROBE.with(|hook| { + *hook.borrow_mut() = Some(Box::new(move || { + *hook_releaser.borrow_mut() = Some(std::thread::spawn(move || { + // Release this process's lock, then another holder takes it. + drop(gateway); + let foreign = + FileLock::try_exclusive(fs::File::open(&foreign_path).unwrap()).unwrap(); + retaken_tx.send(()).unwrap(); + let _ = finish_rx.recv(); + drop(foreign); + })); + observed.set( + hook_retaken_rx + .recv_timeout(Duration::from_millis(300)) + .is_ok(), + ); + }) as Box); + }); + + let answer = held_host_role(temp.path()); + let retaken = retaken_before_probe.get(); + assert!( + !(retaken && answer.is_some()), + "a lock another holder took before the probe was reported as held: {answer:?}" + ); + assert_eq!(answer.as_deref(), Some("gateway")); + assert!(!retaken, "the release waited for the probe"); + + // After the proof, the release and the retake go ahead. + let releaser = releaser.borrow_mut().take().expect("hook ran"); + retaken_rx + .recv_timeout(Duration::from_secs(10)) + .expect("another holder has the lock"); + assert!(!test_support::lock_is_free(&path)); + assert_eq!(held_host_role(temp.path()), None); + finish_tx.send(()).unwrap(); + releaser.join().unwrap(); + } + + /// A Home terminal proves its parent gateway holds the lock from the + /// descriptor the gateway gave it, never from the record. + #[test] + fn inherited_gateway_descriptor_proves_only_a_lock_its_gateway_still_holds() { + use std::os::fd::AsRawFd as _; + let temp = tempfile::tempdir().expect("tempdir"); + let path = host_lock_path(temp.path()); + + // No gateway: a serve lock gives the child nothing. + let serve = + acquire_host_process_lock(temp.path(), "serve", "127.0.0.1:3000").expect("serve"); + assert!(gateway_host_lock_for_child(temp.path()).is_none()); + drop(serve); + + let gateway = acquire_host_process_lock(temp.path(), "gateway", "localhost:8090") + .expect("gateway lock"); + let inherited = gateway_host_lock_for_child(temp.path()).expect("descriptor for child"); + assert!(inherited_gateway_host_lock_is_held( + temp.path(), + inherited.as_raw_fd() + )); + + // A descriptor of the same file that does not hold the lock, with a + // record that names this gateway, is refused. + let plain = fs::File::open(&path).unwrap(); + assert!(fs::read_to_string(&path).unwrap().contains("\"gateway\"")); + assert!(!inherited_gateway_host_lock_is_held( + temp.path(), + plain.as_raw_fd() + )); + // Standard streams and closed or unrelated descriptors are refused. + let other = tempfile::tempfile().unwrap(); + assert!(!inherited_gateway_host_lock_is_held( + temp.path(), + other.as_raw_fd() + )); + assert!(!inherited_gateway_host_lock_is_held(temp.path(), 0)); + assert!(!inherited_gateway_host_lock_is_held(temp.path(), 2)); + assert!(!inherited_gateway_host_lock_is_held(temp.path(), -1)); + + // The gateway releases its lock: the child's descriptor proves nothing. + drop(gateway); + assert!(!inherited_gateway_host_lock_is_held( + temp.path(), + inherited.as_raw_fd() + )); + assert!(test_support::lock_is_free(&path), "the check took no lock"); + + // Another holder retakes it: refused for the old descriptor. + let foreign = FileLock::try_exclusive(fs::File::open(&path).unwrap()).expect("foreign"); + assert!(!inherited_gateway_host_lock_is_held( + temp.path(), + inherited.as_raw_fd() + )); + drop(foreign); + + // The gateway takes the lock again: only a new descriptor proves it. + let gateway = acquire_host_process_lock(temp.path(), "gateway", "localhost:8090") + .expect("gateway retakes"); + assert!(!inherited_gateway_host_lock_is_held( + temp.path(), + inherited.as_raw_fd() + )); + let renewed = gateway_host_lock_for_child(temp.path()).expect("new descriptor"); + assert!(inherited_gateway_host_lock_is_held( + temp.path(), + renewed.as_raw_fd() + )); + + // A replaced lock file is not the file the gateway locked. + fs::remove_file(&path).unwrap(); + fs::write(&path, "{}").unwrap(); + assert!(!inherited_gateway_host_lock_is_held( + temp.path(), + renewed.as_raw_fd() + )); + drop(gateway); + } + #[test] fn model_host_lock_is_data_root_scoped() { let temp = tempfile::tempdir().expect("tempdir"); @@ -605,6 +1133,26 @@ mod tests { assert_eq!(owner.addr, "127.0.0.1:8090"); } + /// Whether a host is active comes from the flock. A holder whose record + /// is empty, not JSON, or rewritten to garbage is still active. + #[test] + fn active_host_process_reports_a_holder_whose_record_cannot_be_read() { + let temp = tempfile::tempdir().expect("tempdir"); + let path = host_lock_path(temp.path()); + let host = + acquire_host_process_lock(temp.path(), "gateway", "localhost:8090").expect("host lock"); + for record in ["", "not-json", "{\"pid\":\"1\"}"] { + fs::write(&path, record).unwrap(); + let owner = active_host_process(temp.path()) + .expect("inspect owner") + .unwrap_or_else(|| panic!("held lock with record {record:?} reported free")); + assert_eq!(owner.role, "unknown"); + } + drop(host); + fs::write(&path, "not-json").unwrap(); + assert!(active_host_process(temp.path()).unwrap().is_none()); + } + #[test] fn normalize_deleted_exe_path_strips_linux_deleted_suffix() { let raw = PathBuf::from("/home/test/.local/bin/elastos (deleted)"); 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() { diff --git a/elastos/crates/elastos-server/src/runtime_control.rs b/elastos/crates/elastos-server/src/runtime_control.rs index 2d3341314..a657eff55 100644 --- a/elastos/crates/elastos-server/src/runtime_control.rs +++ b/elastos/crates/elastos-server/src/runtime_control.rs @@ -40,6 +40,11 @@ pub const RUNTIME_KIND_MANAGED_HOME: &str = "managed-home"; pub const OPERATOR_RUNTIME_REQUIRED_MESSAGE: &str = "This command requires a running runtime.\n\n elastos serve\n\nThen run this command again."; pub const GATEWAY_OWNED_HOME_TERMINAL_ENV: &str = "ELASTOS_GATEWAY_OWNED_HOME_TERMINAL"; +/// The pid of the gateway that started this Home terminal. +pub const GATEWAY_HOST_PID_ENV: &str = "ELASTOS_GATEWAY_HOST_PID"; +/// A descriptor this Home terminal inherits from its gateway: the open file +/// that holds the gateway's host lock. +pub const GATEWAY_HOST_LOCK_FD_ENV: &str = "ELASTOS_GATEWAY_HOST_LOCK_FD"; const MANAGED_RUNTIME_REQUIRED_NATIVE_PROVIDERS: &[&str] = &["localhost-provider", "did-provider"]; const MANAGED_RUNTIME_REQUIRED_COMPONENTS: &[&str] = &["shell"]; @@ -354,17 +359,71 @@ fn managed_runtime_lane_conflict_message( ) } -fn gateway_owner_allows_subordinate_managed_runtime( - owner: &crate::host_lock::HostProcessInfo, +/// Whether a managed runtime that starts here runs under a gateway that holds +/// the host lock of `data_dir`: this process (a gateway serving Home), or the +/// parent gateway of a Home terminal. The proof is the held flock, the same +/// proof as `/healthz` (`docs/LAUNCHER_CONTRACT.md`, "Readiness and Home +/// URL"). The JSON record in the lock file is not proof; it only names the +/// holder in the refusal. +fn subordinate_gateway_host(data_dir: &Path, surface_name: &str) -> anyhow::Result { + if crate::host_lock::holds_gateway_host_lock(data_dir) + || parent_gateway_holds_host_lock(data_dir) + { + return Ok(true); + } + match crate::host_lock::active_host_process(data_dir)? { + Some(owner) => anyhow::bail!(managed_runtime_lane_conflict_message(surface_name, &owner)), + None => Ok(false), + } +} + +/// Whether this process is a Home terminal that its gateway started, and that +/// gateway still holds the host lock of `data_dir`. +fn parent_gateway_holds_host_lock(data_dir: &Path) -> bool { + parent_gateway_lock_proven( + data_dir, + std::env::var_os(GATEWAY_OWNED_HOME_TERMINAL_ENV).as_deref(), + std::env::var_os(GATEWAY_HOST_PID_ENV).as_deref(), + std::env::var_os(GATEWAY_HOST_LOCK_FD_ENV).as_deref(), + parent_process_id(), + ) +} + +/// The gateway starts a Home terminal with the marker, its own pid, and a +/// descriptor of the open file that holds its host lock +/// (`gateway_home_terminal.rs`). This process must be that direct child, and +/// that descriptor must hold the flock now. This proves lock possession, not +/// that the parent is the gateway: a same-user parent that holds the lock can +/// set the same variables. +fn parent_gateway_lock_proven( + data_dir: &Path, + marker: Option<&std::ffi::OsStr>, + gateway_pid: Option<&std::ffi::OsStr>, + lock_fd: Option<&std::ffi::OsStr>, + parent_pid: Option, ) -> bool { - if !matches!(owner.role.as_str(), "gateway" | "gateway-public") { + if marker != Some(std::ffi::OsStr::new("1")) { return false; } - if owner.pid == std::process::id() { - return true; + let number = |value: Option<&std::ffi::OsStr>| value?.to_str()?.parse::().ok(); + let (Some(gateway_pid), Some(lock_fd)) = (number(gateway_pid), number(lock_fd)) else { + return false; + }; + if parent_pid != Some(gateway_pid) { + return false; + } + #[cfg(unix)] + { + let Ok(lock_fd) = std::os::fd::RawFd::try_from(lock_fd) else { + return false; + }; + crate::host_lock::inherited_gateway_host_lock_is_held(data_dir, lock_fd) + } + #[cfg(not(unix))] + { + let _ = (data_dir, lock_fd); + false } - std::env::var_os(GATEWAY_OWNED_HOME_TERMINAL_ENV).as_deref() == Some(std::ffi::OsStr::new("1")) - && parent_process_id() == Some(owner.pid) } fn parent_process_id() -> Option { @@ -1219,11 +1278,7 @@ async fn ensure_managed_runtime( } } - let subordinate_gateway_host = match crate::host_lock::active_host_process(data_dir)? { - Some(owner) if gateway_owner_allows_subordinate_managed_runtime(&owner) => true, - Some(owner) => anyhow::bail!(managed_runtime_lane_conflict_message(surface_name, &owner)), - None => false, - }; + let subordinate_gateway_host = subordinate_gateway_host(data_dir, surface_name)?; let gateway_owner = subordinate_gateway_host .then(|| gateway_children::Owner::read(data_dir)) .transpose()?; @@ -1983,17 +2038,6 @@ mod tests { assert!(message.contains("managed chat lane")); } - #[test] - fn current_gateway_host_allows_subordinate_managed_runtime() { - let owner = crate::host_lock::HostProcessInfo { - pid: std::process::id(), - role: "gateway".to_string(), - addr: "127.0.0.1:8090".to_string(), - }; - - assert!(gateway_owner_allows_subordinate_managed_runtime(&owner)); - } - fn write_managed_runtime_parent_support_artifacts(data_dir: &Path) -> Vec { let platform = match (std::env::consts::OS, std::env::consts::ARCH) { ("linux", "x86_64") => "linux-amd64", @@ -2072,74 +2116,265 @@ mod tests { pin_parent_model_catalog_head(data_dir, &crate::setup::catalog_head_cid(catalog).unwrap()); } + fn forge_host_lock_record(data_dir: &Path, pid: u32, role: &str) { + std::fs::write( + data_dir.join("host-process.lock"), + format!("{{\"pid\":{pid},\"role\":\"{role}\",\"addr\":\"localhost:8090\"}}\n"), + ) + .unwrap(); + } + + /// Another holder, here a separate open file in place of another process. + fn foreign_host_lock(data_dir: &Path) -> crate::host_lock::FileLock { + crate::host_lock::FileLock::try_exclusive( + std::fs::File::open(data_dir.join("host-process.lock")).unwrap(), + ) + .unwrap() + } + + /// The gateway that serves Home in this process proves the lane from the + /// flock it holds, the same proof as `/healthz`. A record naming this pid + /// as a gateway, written by any process of the same user, is refused. #[test] - #[cfg(unix)] - fn gateway_owned_terminal_child_allows_parent_gateway_subordinate_runtime() { - let _guard = EnvRestore::set(GATEWAY_OWNED_HOME_TERMINAL_ENV, "1"); - let owner = crate::host_lock::HostProcessInfo { - pid: parent_process_id().expect("test process should have a parent"), - role: "gateway".to_string(), - addr: "127.0.0.1:8090".to_string(), - }; + fn subordinate_lane_in_this_process_needs_the_held_gateway_lock() { + let temp = tempfile::tempdir().unwrap(); + let data = temp.path(); + let pid = std::process::id(); + + // No holder: the forged record does not make a gateway. + forge_host_lock_record(data, pid, "gateway"); + assert!(!subordinate_gateway_host(data, "home").unwrap()); + + // Another holder has the lock; the record names this gateway. + let foreign = foreign_host_lock(data); + for role in ["gateway", "gateway-public"] { + forge_host_lock_record(data, pid, role); + let err = subordinate_gateway_host(data, "home").unwrap_err(); + assert!( + err.to_string().contains("already owns this identity"), + "forged {role}: {err}" + ); + } + drop(foreign); + + // This process holds the gateway lock: the lane is open, whatever the record says. + let gateway = + crate::host_lock::acquire_host_process_lock(data, "gateway", "localhost:8090").unwrap(); + assert!(subordinate_gateway_host(data, "home").unwrap()); + forge_host_lock_record(data, pid.wrapping_add(1), "serve"); + assert!(subordinate_gateway_host(data, "home").unwrap()); + + // After the release, the record this gateway left is not proof. + drop(gateway); + forge_host_lock_record(data, pid, "gateway"); + let foreign = foreign_host_lock(data); + assert!(subordinate_gateway_host(data, "home").is_err()); + drop(foreign); + + // A holder whose record is not JSON still owns the home. + std::fs::write(data.join("host-process.lock"), "not-json").unwrap(); + let foreign = foreign_host_lock(data); + let err = subordinate_gateway_host(data, "home").unwrap_err(); + assert!( + err.to_string().contains("already owns this identity"), + "{err}" + ); + drop(foreign); - assert!(gateway_owner_allows_subordinate_managed_runtime(&owner)); + // This process holds the lock as `serve`: the lane is refused. + let serve = + crate::host_lock::acquire_host_process_lock(data, "serve", "127.0.0.1:3000").unwrap(); + forge_host_lock_record(data, pid, "gateway"); + let err = subordinate_gateway_host(data, "home").unwrap_err(); + assert!( + err.to_string().contains("already owns this identity"), + "{err}" + ); + drop(serve); } + /// A Home terminal proves its parent gateway holds the lock from the + /// descriptor that gateway gave it. A record naming the parent as a + /// gateway is refused. #[test] #[cfg(unix)] - fn unmarked_terminal_child_does_not_bypass_foreign_gateway_owner() { - let _guard = EnvRestore::remove(GATEWAY_OWNED_HOME_TERMINAL_ENV); - let owner = crate::host_lock::HostProcessInfo { - pid: parent_process_id().expect("test process should have a parent"), - role: "gateway".to_string(), - addr: "127.0.0.1:8090".to_string(), + fn subordinate_lane_for_a_home_terminal_needs_its_gateway_lock_descriptor() { + use std::ffi::OsStr; + let temp = tempfile::tempdir().unwrap(); + let data = temp.path(); + let parent = 4242_u32; + let parent_text = parent.to_string(); + let marker = Some(OsStr::new("1")); + let proven = |fd: &dyn std::os::fd::AsRawFd, + marker: Option<&OsStr>, + pid: &str, + ppid: Option| { + let fd = fd.as_raw_fd().to_string(); + parent_gateway_lock_proven( + data, + marker, + Some(OsStr::new(pid)), + Some(OsStr::new(&fd)), + ppid, + ) }; - assert!(!gateway_owner_allows_subordinate_managed_runtime(&owner)); + // The record names the parent as a gateway; another process holds the + // lock; the descriptor is a plain open of the lock file. + forge_host_lock_record(data, parent, "gateway"); + let foreign = foreign_host_lock(data); + let plain = std::fs::File::open(data.join("host-process.lock")).unwrap(); + assert!(!proven(&plain, marker, &parent_text, Some(parent))); + drop(foreign); + + // The parent gateway holds the lock and gave this descriptor. + let gateway = + crate::host_lock::acquire_host_process_lock(data, "gateway", "localhost:8090").unwrap(); + let inherited = crate::host_lock::gateway_host_lock_for_child(data).unwrap(); + assert!(proven(&inherited, marker, &parent_text, Some(parent))); + // Without the marker, from a process that is not the gateway's child, + // or without a descriptor, the lane stays closed. + assert!(!proven(&inherited, None, &parent_text, Some(parent))); + assert!(!proven( + &inherited, + Some(OsStr::new("0")), + &parent_text, + Some(parent) + )); + assert!(!proven(&inherited, marker, &parent_text, Some(parent + 1))); + assert!(!proven(&inherited, marker, &parent_text, None)); + assert!(!parent_gateway_lock_proven( + data, + marker, + Some(OsStr::new(&parent_text)), + None, + Some(parent) + )); + assert!(!parent_gateway_lock_proven( + data, + marker, + Some(OsStr::new(&parent_text)), + Some(OsStr::new("not-a-number")), + Some(parent) + )); + + // The gateway releases: refused. Another holder retakes: refused. + drop(gateway); + assert!(!proven(&inherited, marker, &parent_text, Some(parent))); + let foreign = foreign_host_lock(data); + forge_host_lock_record(data, parent, "gateway"); + assert!(!proven(&inherited, marker, &parent_text, Some(parent))); + drop(foreign); } + const LANE_PROBE_DATA_ENV: &str = "ELASTOS_TEST_LANE_PROBE_DATA"; + const LANE_PROBE_ANSWER: &str = "HOME_TERMINAL_LANE_PROOF="; + + /// The child half of the test below: a separate process that runs the + /// Home terminal check on what its parent gave it, and prints the answer. #[test] - fn foreign_gateway_host_still_conflicts_with_managed_runtime() { - let owner = crate::host_lock::HostProcessInfo { - pid: std::process::id().saturating_add(1), - role: "gateway-public".to_string(), - addr: "127.0.0.1:8090".to_string(), + #[ignore = "run as a child by the test below"] + #[cfg(unix)] + fn home_terminal_lane_probe_child() { + let data = std::env::var_os(LANE_PROBE_DATA_ENV).expect("data directory"); + let proven = parent_gateway_holds_host_lock(Path::new(&data)); + println!("{LANE_PROBE_ANSWER}{proven}"); + } + + /// The inherited lock descriptor proves possession of the host lock, not + /// that the parent is the gateway (`docs/LAUNCHER_CONTRACT.md`, "Readiness + /// and Home URL"). Here the parent is this test process. It is not a + /// gateway: it takes the flock with a plain open, not as a host, and the + /// record does not name a gateway. It sets the variables a gateway sets and + /// gives the descriptor to a real child process. The child's check accepts + /// it while the parent holds the lock, and refuses a descriptor that does + /// not hold the lock and the same descriptor after the parent releases it. + #[test] + #[cfg(unix)] + fn home_terminal_lane_proves_lock_possession_not_that_the_parent_is_the_gateway() { + use std::os::fd::AsRawFd as _; + use std::os::unix::process::CommandExt as _; + let temp = tempfile::tempdir().unwrap(); + let data = temp.path(); + let path = data.join("host-process.lock"); + std::fs::write(&path, "not a gateway record\n").unwrap(); + let child_answer = |fd: std::os::fd::RawFd| -> bool { + let mut command = std::process::Command::new(std::env::current_exe().unwrap()); + command + .args([ + "--exact", + &format!( + "{}::home_terminal_lane_probe_child", + module_path!().split_once("::").unwrap().1 + ), + "--ignored", + "--nocapture", + "--test-threads=1", + ]) + .env(LANE_PROBE_DATA_ENV, data) + .env(GATEWAY_OWNED_HOME_TERMINAL_ENV, "1") + .env(GATEWAY_HOST_PID_ENV, std::process::id().to_string()) + .env(GATEWAY_HOST_LOCK_FD_ENV, fd.to_string()) + .stdin(std::process::Stdio::null()); + unsafe { + command.pre_exec(move || { + // Keep this one descriptor open across exec, as a gateway does. + if libc::fcntl(fd, libc::F_SETFD, 0) == -1 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + }); + } + let output = command.output().unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!(output.status.success(), "child failed: {stdout}"); + let answer = stdout + .lines() + .find_map(|line| line.split_once(LANE_PROBE_ANSWER)) + .map(|(_, answer)| answer.trim()) + .unwrap_or_else(|| panic!("no answer from the child: {stdout}")); + answer == "true" }; - assert!(!gateway_owner_allows_subordinate_managed_runtime(&owner)); - } + // This process holds the flock, but not as a host, so it is no gateway. + let held = + crate::host_lock::FileLock::try_exclusive(std::fs::File::open(&path).unwrap()).unwrap(); + assert_eq!(crate::host_lock::held_host_role(data), None); + assert!(!crate::host_lock::holds_gateway_host_lock(data)); + assert!(crate::host_lock::gateway_host_lock_for_child(data).is_none()); - struct EnvRestore { - key: &'static str, - value: Option, - } + // The child accepts the descriptor: it proves the lock is held through + // it, and that its parent is the pid it was given. Nothing more. + assert!( + child_answer(held.as_raw_fd()), + "a descriptor that holds the lock, from a parent that is not a gateway" + ); - impl EnvRestore { - fn set(key: &'static str, value: &str) -> Self { - let previous = std::env::var_os(key); - std::env::set_var(key, value); - Self { - key, - value: previous, - } - } + // A descriptor of the same file that does not hold the lock is refused. + let plain = std::fs::File::open(&path).unwrap(); + assert!( + !child_answer(plain.as_raw_fd()), + "a descriptor without the lock" + ); - fn remove(key: &'static str) -> Self { - let previous = std::env::var_os(key); - std::env::remove_var(key); - Self { - key, - value: previous, - } - } - } + // After the parent releases the lock, the same descriptor is refused. + let descriptor = held.try_clone().unwrap(); + held.release().unwrap(); + assert!( + !child_answer(descriptor.as_raw_fd()), + "the descriptor after the release" + ); + assert!(crate::host_lock::test_support::lock_is_free(&path)); - impl Drop for EnvRestore { - fn drop(&mut self) { - match &self.value { - Some(value) => std::env::set_var(self.key, value), - None => std::env::remove_var(self.key), - } - } + let contract = std::fs::read_to_string(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../docs/LAUNCHER_CONTRACT.md" + )) + .unwrap(); + let contract = contract.split_whitespace().collect::>().join(" "); + assert!(contract.contains("`ELASTOS_GATEWAY_HOST_LOCK_FD`")); + assert!( + contract.contains("This proves lock possession, not that the parent is the gateway.") + ); } }