From 402d87397813fa6e320e18316e3f41fedb9308ba Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 16 Oct 2026 04:10:46 +0000 Subject: [PATCH 01/18] docs: define the launcher contract for gateway supervision Record the install, start, /healthz, Home URL, data directory, lock, stop, and update interface a desktop launcher can rely on, and lock the /healthz body in the existing gateway test. Co-authored-by: Sash --- docs/LAUNCHER_CONTRACT.md | 196 ++++++++++++++++++ docs/README.md | 2 + .../src/api/gateway_tests/site_publication.rs | 6 + .../elastos-server/src/gateway_entry.rs | 2 + 4 files changed, 206 insertions(+) create mode 100644 docs/LAUNCHER_CONTRACT.md diff --git a/docs/LAUNCHER_CONTRACT.md b/docs/LAUNCHER_CONTRACT.md new file mode 100644 index 000000000..84d952366 --- /dev/null +++ b/docs/LAUNCHER_CONTRACT.md @@ -0,0 +1,196 @@ +# Launcher contract + +This is the stable interface a desktop launcher uses to install, start, watch, +stop, and update the ElastOS Runtime. The launcher owns the supervisor. The +Runtime owns the process, the data directory, the host lock, and the signed +update. + +The checked behavior for readiness is `test_healthz_200` in +`elastos/crates/elastos-server/src/api/gateway_tests/site_publication.rs`. +The supervised start entry is `run_gateway` in +`elastos/crates/elastos-server/src/gateway_entry.rs`. + +## Install + +The launcher runs the publisher installer and stops before setup: + +```bash +curl -fsSL https://elastos.elacitylabs.com/install.sh | bash -s -- --install-only +``` + +`ELASTOS_INSTALL_ONLY=1` selects the same stop. The git copy of +`scripts/install.sh` still contains placeholder trust anchors. The launcher +runs the script the publisher URL serves, which carries the stamped anchors. + +That command installs the Runtime binary and the trusted source, then returns. +It leaves Home setup and the browser to the launcher. + +The launcher then runs: + +```bash +elastos setup +``` + +Setup installs the Home profile. `elastos setup --isolated`, chosen before the +first start, keeps this Home out of the shared Community room. + +The signed release head names the channel. Allowed names are `stable`, +`canary`, and `jetson-test`. The stable channel is the publication from +`main`. The installer records that channel in the trusted source. Later +updates follow the saved source. The launcher does not pass a channel flag. + +The installer accepts Linux x86_64, Linux aarch64, and macOS Apple silicon +(`aarch64-darwin`). On any other operating system or architecture it exits 1. +Intel Mac (`x86_64` / darwin-x64) is outside this install set. See +[Mac notes](MAC.md) for the source-home path on Apple silicon. + +## Start + +The launcher starts Home with: + +```bash +elastos gateway --addr 127.0.0.1:8090 +``` + +`--addr` (`-a`) is `host:port`. The default is `127.0.0.1:8090`. The launcher +owns the address it passes and uses that same address for every probe and for +the Home URL. + +`elastos gateway` leaves the system browser closed. `elastos home --browser` +is a different command: it binds `localhost:8090` and opens the URL with +`open` on macOS, or `wslview` and then `xdg-open` on Linux. The launcher uses +`gateway`. + +`elastos serve` is the operator runtime. Its readiness route is +`GET /api/health`. The launcher does not start `serve` against the same data +directory, and it does not use `/api/health` as the Home probe. + +`--public` starts a tunnel and is outside this contract. + +On startup the gateway prints: + +```text +[gateway] ElastOS starting on +``` + +That line is progress. Readiness is the HTTP probe below. + +## Readiness and Home URL + +When the gateway is listening: + +```text +GET http://127.0.0.1:8090/healthz +``` + +returns HTTP 200 and the body bytes `OK` (three bytes, no trailing newline). +`test_healthz_200` locks that response. + +The launcher opens: + +```text +http://127.0.0.1:8090/home/ +``` + +`/home/` is `HOME_ROUTE`. `/home` and `/apps/home/` redirect to it. The page +is the Home capsule installed by `elastos setup`. The launcher opens this URL +in its own browser after `/healthz` returns `OK`. + +A source-home staging script may bind another port. The launcher uses the +address it passed to `--addr`. + +## Data directory and binary + +| Item | Path | +| --- | --- | +| Binary | `~/.local/bin/elastos`, or the directory passed as `--install-dir` | +| Linux data directory | `$XDG_DATA_HOME/elastos`, or `~/.local/share/elastos` | +| macOS data directory | `~/Library/Application Support/elastos` | +| Trusted source | `{data}/sources.json` | +| Installed components | `{data}/components.json` | +| Host lock | `{data}/host-process.lock` | + +The Runtime resolves the data directory with the platform data directory +(`dirs::data_dir()`), then `elastos`. The installer uses the same split: +`~/Library/Application Support/elastos` on macOS, and +`$XDG_DATA_HOME/elastos` or `~/.local/share/elastos` on Linux. + +The launcher keeps one data directory for the Home it supervises. It leaves +any other product directory in place. + +Coordinate files under the data directory (`runtime-coords.json`, +`gateway-runtime-coords.json`, `home-runtime-coords.json`) hold a local +`attach_secret`. The launcher log is the gateway process stdout and stderr. +The launcher leaves those coordinate files out of the log. + +`elastos version` prints `ElastOS Runtime v`. + +## Single instance + +The gateway takes an exclusive lock on `{data}/host-process.lock` and writes +the pid, the role `gateway`, and the bind address. A second live host for the +same data directory exits 1. Its error contains: + +```text +another ElastOS host already owns +``` + +The launcher shows that error. It leaves the process that holds the lock +running. + +## Stop + +The launcher sends `SIGTERM` to the gateway process. + +`elastos gateway` puts itself in its own process group. On `SIGTERM` or +`SIGINT` the Runtime prints `Shutting down...`, signals that group with +`SIGTERM`, waits 15 seconds, then signals the group with `SIGKILL`. + +The launcher waits until `GET /healthz` fails. A stop that begins with +`SIGKILL` to the parent skips the handler, so child processes can remain. +Exit status after a requested stop is the signal status. The launcher treats +a dead `/healthz` as stopped. + +While the gateway is running, a replaced installed binary makes that process +exit 75. The launcher starts `elastos gateway --addr 127.0.0.1:8090` again +so the new binary takes the lock. + +## Update and rollback + +```bash +elastos update --check +elastos update --yes +elastos update --rollback-to --yes +``` + +There is no `elastos upgrade` command. `--check` and a completed install both +exit 0. When the saved release is current, stdout contains +`Installed release is up to date.` When a newer signed release exists, +stdout contains `Run `elastos update` to install.` The launcher reads that +text. The exit code stays 0 in both cases. + +`--yes` skips the confirmation prompt. The launcher passes `--yes` on every +install and rollback. A declined prompt also exits 0 and prints +`Update cancelled.` + +`--rollback-to` selects that signed head and admits an older release. The +launcher saves the current head CID from `elastos source show` (`Head CID:`) +before an update, and passes that CID to `--rollback-to`. A plain update of +an older release exits 1 and tells the operator to use the rollback command. + +`--force` repairs an invalid installed version. It is a separate flag from +rollback. + +Update and rollback use the trusted source over Carrier. They replace the +installed binary and `components.json` after signature and hash checks. + +## Exit codes + +| Code | Meaning | +| --- | --- | +| 0 | The command finished. This includes `update --check` with or without a newer release, a declined update prompt, and `install.sh --help`. | +| 1 | The command failed. This includes the installer `die` path (unknown option, unsupported platform, failed check), a held host lock, a missing trusted source, a failed signature check, and an older release without `--rollback-to`. | +| 2 | The `elastos` command line is invalid. Clap reports a usage error with exit 2. | +| 75 | The running gateway exited because the installed binary was replaced. The launcher starts the gateway again. | + +`install.sh` reports a failed check with exit 1. 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/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..e3affe5b7 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,6 +221,8 @@ async fn test_root_serves_mywebsite_when_staged() { assert_eq!(&body[..], b"home site"); } +/// Launcher readiness. `docs/LAUNCHER_CONTRACT.md` defines this response: +/// HTTP 200 and the body bytes `OK`. #[tokio::test] async fn test_healthz_200() { let dir = tempfile::tempdir().unwrap(); @@ -238,6 +240,10 @@ 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"); } #[tokio::test] 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, From 53da7e2bbf3a325f77126ff53a71aed93f4062a1 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 16 Oct 2026 05:31:02 +0000 Subject: [PATCH 02/18] fix: an unreadable executable path exits 1, not 75 Exit 75 stays the launcher restart for a replaced binary, a moved path, or a file that changed and then could not be verified. A process that cannot read its own executable path exits 1, and the contract says the launcher leaves that process stopped. Co-authored-by: Sash --- docs/LAUNCHER_CONTRACT.md | 11 +- .../crates/elastos-server/src/host_lock.rs | 121 ++++++++++++++---- 2 files changed, 103 insertions(+), 29 deletions(-) diff --git a/docs/LAUNCHER_CONTRACT.md b/docs/LAUNCHER_CONTRACT.md index 84d952366..113a12f99 100644 --- a/docs/LAUNCHER_CONTRACT.md +++ b/docs/LAUNCHER_CONTRACT.md @@ -152,8 +152,11 @@ Exit status after a requested stop is the signal status. The launcher treats a dead `/healthz` as stopped. While the gateway is running, a replaced installed binary makes that process -exit 75. The launcher starts `elastos gateway --addr 127.0.0.1:8090` again -so the new binary takes the lock. +exit 75. The same exit covers a moved executable path and a file that changed +and then could not be verified. The launcher starts +`elastos gateway --addr 127.0.0.1:8090` again so the new binary takes the lock. +A process that cannot read its own executable path exits 1. The launcher +leaves that process stopped. ## Update and rollback @@ -189,8 +192,8 @@ installed binary and `components.json` after signature and hash checks. | Code | Meaning | | --- | --- | | 0 | The command finished. This includes `update --check` with or without a newer release, a declined update prompt, and `install.sh --help`. | -| 1 | The command failed. This includes the installer `die` path (unknown option, unsupported platform, failed check), a held host lock, a missing trusted source, a failed signature check, and an older release without `--rollback-to`. | +| 1 | The command failed. This includes the installer `die` path (unknown option, unsupported platform, failed check), a held host lock, a missing trusted source, a failed signature check, an older release without `--rollback-to`, and a running gateway whose executable path cannot be read. | | 2 | The `elastos` command line is invalid. Clap reports a usage error with exit 2. | -| 75 | The running gateway exited because the installed binary was replaced. The launcher starts the gateway again. | +| 75 | The running gateway exited because the installed binary was replaced, its path moved, or the file on disk could not be verified after a change. The launcher starts the gateway again. | `install.sh` reports a failed check with exit 1. diff --git a/elastos/crates/elastos-server/src/host_lock.rs b/elastos/crates/elastos-server/src/host_lock.rs index e2988fb7f..f58989fdc 100644 --- a/elastos/crates/elastos-server/src/host_lock.rs +++ b/elastos/crates/elastos-server/src/host_lock.rs @@ -224,6 +224,20 @@ struct BinarySnapshot { sha256: String, } +/// The installed binary was replaced, its path moved, or the file on disk +/// could not be verified after a change. `docs/LAUNCHER_CONTRACT.md` tells +/// the launcher to start the gateway again. +const EXIT_INSTALLED_BINARY_REPLACED: i32 = 75; +/// The process cannot read its own executable path. That is a failure. +/// The launcher leaves this process stopped. +const EXIT_EXECUTABLE_PATH_UNREADABLE: i32 = 1; + +#[derive(Debug, Clone, PartialEq, Eq)] +struct Supersession { + reason: String, + exit_code: i32, +} + pub fn spawn_installed_binary_supersession_watch(data_dir: &Path, role: &str) { let Some(mut watch) = BinarySupersessionWatch::from_data_dir(data_dir) else { return; @@ -234,9 +248,9 @@ pub fn spawn_installed_binary_supersession_watch(data_dir: &Path, role: &str) { interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); loop { interval.tick().await; - if let Some(reason) = watch.superseded_reason() { - eprintln!("[{}] {}", role, reason); - std::process::exit(75); + if let Some(event) = watch.superseded_reason() { + eprintln!("[{}] {}", role, event.reason); + std::process::exit(event.exit_code); } } }); @@ -258,32 +272,45 @@ impl BinarySupersessionWatch { }) } - fn superseded_reason(&mut self) -> Option { + fn superseded_reason(&mut self) -> Option { self.superseded_reason_with(&RealBinarySnapshotReader) } - fn superseded_reason_with(&mut self, reader: &impl BinarySnapshotReader) -> Option { + fn replaced(&self, reason: String) -> Option { + Some(Supersession { + reason, + exit_code: EXIT_INSTALLED_BINARY_REPLACED, + }) + } + + fn superseded_reason_with( + &mut self, + reader: &impl BinarySnapshotReader, + ) -> Option { let current_exe_raw = match reader.current_exe_path_raw() { Ok(path) => path, Err(err) => { - return Some(format!( - "host executable path could not be read for {}: {err:#}. Exiting stale host.", - self.current_exe_path.display() - )); + return Some(Supersession { + reason: format!( + "host executable path could not be read for {}: {err:#}. Exiting stale host.", + self.current_exe_path.display() + ), + exit_code: EXIT_EXECUTABLE_PATH_UNREADABLE, + }); } }; let raw_text = current_exe_raw.to_string_lossy(); let current_exe = normalize_deleted_exe_path(¤t_exe_raw); if raw_text.ends_with(" (deleted)") { - return Some(format!( + return self.replaced(format!( "host executable {} was replaced on disk. Exiting stale host.", self.current_exe_path.display() )); } if current_exe != self.current_exe_path { - return Some(format!( + return self.replaced(format!( "host executable moved from {} to {}. Exiting stale host.", self.current_exe_path.display(), current_exe.display() @@ -293,7 +320,7 @@ impl BinarySupersessionWatch { let current_stamp = match reader.metadata_stamp(&self.current_exe_path) { Ok(stamp) => stamp, Err(err) => { - return Some(format!( + return self.replaced(format!( "host executable {} could not be verified on disk: {err:#}. Exiting stale host.", self.current_exe_path.display() )); @@ -307,14 +334,14 @@ impl BinarySupersessionWatch { let current_snapshot = match reader.digest_snapshot(&self.current_exe_path) { Ok(snapshot) => snapshot, Err(err) => { - return Some(format!( + return self.replaced(format!( "host executable {} changed on disk and could not be re-verified: {err:#}. Exiting stale host.", self.current_exe_path.display() )); } }; if current_snapshot.sha256 != self.current_binary_sha256 { - return Some(format!( + return self.replaced(format!( "host binary {} changed on disk. Exiting stale host so the newer binary can take over.", self.current_exe_path.display() )); @@ -485,6 +512,7 @@ mod tests { struct TestBinarySnapshotReaderState { current_exe_raw: RefCell, digest_reads: Cell, + fail_path: Cell, } impl TestBinarySnapshotReader { @@ -493,6 +521,7 @@ mod tests { state: Rc::new(TestBinarySnapshotReaderState { current_exe_raw: RefCell::new(path), digest_reads: Cell::new(0), + fail_path: Cell::new(false), }), } } @@ -501,6 +530,10 @@ mod tests { *self.state.current_exe_raw.borrow_mut() = path; } + fn fail_current_exe(&self) { + self.state.fail_path.set(true); + } + fn digest_reads(&self) -> usize { self.state.digest_reads.get() } @@ -508,6 +541,9 @@ mod tests { impl BinarySnapshotReader for TestBinarySnapshotReader { fn current_exe_path_raw(&self) -> anyhow::Result { + if self.state.fail_path.get() { + anyhow::bail!("fixture path unreadable"); + } Ok(self.state.current_exe_raw.borrow().clone()) } @@ -669,8 +705,9 @@ mod tests { let initial_reads = reader.digest_reads(); write_file(&exe, b"changed content with a different length"); - let reason = watch.superseded_reason_with(&reader).expect("superseded"); - assert!(reason.contains("changed on disk"), "{reason}"); + let event = watch.superseded_reason_with(&reader).expect("superseded"); + assert!(event.reason.contains("changed on disk"), "{}", event.reason); + assert_eq!(event.exit_code, EXIT_INSTALLED_BINARY_REPLACED); assert_eq!(reader.digest_reads(), initial_reads + 1); } @@ -686,8 +723,9 @@ mod tests { write_file(&replacement, b"modified"); fs::rename(&replacement, &exe).expect("replace file"); - let reason = watch.superseded_reason_with(&reader).expect("superseded"); - assert!(reason.contains("changed on disk"), "{reason}"); + let event = watch.superseded_reason_with(&reader).expect("superseded"); + assert!(event.reason.contains("changed on disk"), "{}", event.reason); + assert_eq!(event.exit_code, EXIT_INSTALLED_BINARY_REPLACED); assert_eq!(reader.digest_reads(), initial_reads + 1); } @@ -701,9 +739,14 @@ mod tests { let moved = temp.path().join("elastos-new"); reader.set_current_exe_raw(moved.clone()); - let reason = watch.superseded_reason_with(&reader).expect("superseded"); - assert!(reason.contains("moved"), "{reason}"); - assert!(reason.contains(&moved.display().to_string()), "{reason}"); + let event = watch.superseded_reason_with(&reader).expect("superseded"); + assert!(event.reason.contains("moved"), "{}", event.reason); + assert!( + event.reason.contains(&moved.display().to_string()), + "{}", + event.reason + ); + assert_eq!(event.exit_code, EXIT_INSTALLED_BINARY_REPLACED); } #[test] @@ -715,8 +758,13 @@ mod tests { let (mut watch, reader) = test_watch(&exe); fs::remove_file(&exe).expect("remove file"); - let reason = watch.superseded_reason_with(&reader).expect("superseded"); - assert!(reason.contains("could not be verified on disk"), "{reason}"); + let event = watch.superseded_reason_with(&reader).expect("superseded"); + assert!( + event.reason.contains("could not be verified on disk"), + "{}", + event.reason + ); + assert_eq!(event.exit_code, EXIT_INSTALLED_BINARY_REPLACED); } #[test] @@ -728,7 +776,30 @@ mod tests { let (mut watch, reader) = test_watch(&exe); reader.set_current_exe_raw(PathBuf::from(format!("{} (deleted)", exe.display()))); - let reason = watch.superseded_reason_with(&reader).expect("superseded"); - assert!(reason.contains("replaced on disk"), "{reason}"); + let event = watch.superseded_reason_with(&reader).expect("superseded"); + assert!( + event.reason.contains("replaced on disk"), + "{}", + event.reason + ); + assert_eq!(event.exit_code, EXIT_INSTALLED_BINARY_REPLACED); + } + + #[test] + fn supersession_watch_unreadable_path_is_a_failure() { + let temp = tempfile::tempdir().expect("tempdir"); + let exe = temp.path().join("elastos"); + write_file(&exe, b"original"); + + let (mut watch, reader) = test_watch(&exe); + reader.fail_current_exe(); + + let event = watch.superseded_reason_with(&reader).expect("unreadable"); + assert!( + event.reason.contains("could not be read"), + "{}", + event.reason + ); + assert_eq!(event.exit_code, EXIT_EXECUTABLE_PATH_UNREADABLE); } } From 2f9334ef91812e1cb2249408f3bdaecd1de6dec7 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 16 Oct 2026 05:31:10 +0000 Subject: [PATCH 03/18] docs: name Intel Mac once and keep the signer closed The release id is x86_64-darwin and the package key is darwin-amd64. The launcher calls that host darwin-x64. The signer still refuses x86_64-darwin, and this tree has no Intel download. Co-authored-by: Sash --- docs/LAUNCHER_CONTRACT.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/docs/LAUNCHER_CONTRACT.md b/docs/LAUNCHER_CONTRACT.md index 113a12f99..9226d8932 100644 --- a/docs/LAUNCHER_CONTRACT.md +++ b/docs/LAUNCHER_CONTRACT.md @@ -41,8 +41,14 @@ updates follow the saved source. The launcher does not pass a channel flag. The installer accepts Linux x86_64, Linux aarch64, and macOS Apple silicon (`aarch64-darwin`). On any other operating system or architecture it exits 1. -Intel Mac (`x86_64` / darwin-x64) is outside this install set. See -[Mac notes](MAC.md) for the source-home path on Apple silicon. +Intel Mac is outside this install set. That host has one name pair. The +release platform id is `x86_64-darwin`. The package key is `darwin-amd64`. +`scripts/release-platforms.json` maps `darwin-amd64` to `x86_64-darwin`. The +launcher calls the same host `darwin-x64`. The signer admits `x86_64-linux`, +`aarch64-linux`, and `aarch64-darwin`. It refuses `x86_64-darwin` in +`scripts/release-signer.py` until one signed Intel artifact exists. This tree +has no Intel download. See [Mac notes](MAC.md) for the source-home path on +Apple silicon. ## Start From 7239d8b1474dfa6c369766b3516f80abca26d0cc Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 16 Oct 2026 07:22:42 +0000 Subject: [PATCH 04/18] fix: exit 75 restarts only for a replaced binary or a changed hash A moved path, an unreadable path, and a failed re-hash exit 1. The launcher leaves that process stopped. The contract uses the same rule. Co-authored-by: Sash --- docs/LAUNCHER_CONTRACT.md | 14 +-- .../crates/elastos-server/src/host_lock.rs | 87 +++++++++++++------ 2 files changed, 67 insertions(+), 34 deletions(-) diff --git a/docs/LAUNCHER_CONTRACT.md b/docs/LAUNCHER_CONTRACT.md index 9226d8932..f6971aeec 100644 --- a/docs/LAUNCHER_CONTRACT.md +++ b/docs/LAUNCHER_CONTRACT.md @@ -157,12 +157,12 @@ The launcher waits until `GET /healthz` fails. A stop that begins with Exit status after a requested stop is the signal status. The launcher treats a dead `/healthz` as stopped. -While the gateway is running, a replaced installed binary makes that process -exit 75. The same exit covers a moved executable path and a file that changed -and then could not be verified. The launcher starts +While the gateway is running, a replaced installed binary or a changed binary +hash makes that process exit 75. The launcher starts `elastos gateway --addr 127.0.0.1:8090` again so the new binary takes the lock. -A process that cannot read its own executable path exits 1. The launcher -leaves that process stopped. +A moved executable path, a path that cannot be read, and a file that changed +and then could not be re-verified exit 1. The launcher leaves that process +stopped. ## Update and rollback @@ -198,8 +198,8 @@ installed binary and `components.json` after signature and hash checks. | Code | Meaning | | --- | --- | | 0 | The command finished. This includes `update --check` with or without a newer release, a declined update prompt, and `install.sh --help`. | -| 1 | The command failed. This includes the installer `die` path (unknown option, unsupported platform, failed check), a held host lock, a missing trusted source, a failed signature check, an older release without `--rollback-to`, and a running gateway whose executable path cannot be read. | +| 1 | The command failed. This includes the installer `die` path (unknown option, unsupported platform, failed check), a held host lock, a missing trusted source, a failed signature check, an older release without `--rollback-to`, and a running gateway whose executable path cannot be read, whose path moved, or whose file could not be re-verified. | | 2 | The `elastos` command line is invalid. Clap reports a usage error with exit 2. | -| 75 | The running gateway exited because the installed binary was replaced, its path moved, or the file on disk could not be verified after a change. The launcher starts the gateway again. | +| 75 | The running gateway exited because the installed binary was replaced or its hash changed. The launcher starts the gateway again. | `install.sh` reports a failed check with exit 1. diff --git a/elastos/crates/elastos-server/src/host_lock.rs b/elastos/crates/elastos-server/src/host_lock.rs index f58989fdc..7627db8a4 100644 --- a/elastos/crates/elastos-server/src/host_lock.rs +++ b/elastos/crates/elastos-server/src/host_lock.rs @@ -224,13 +224,12 @@ struct BinarySnapshot { sha256: String, } -/// The installed binary was replaced, its path moved, or the file on disk -/// could not be verified after a change. `docs/LAUNCHER_CONTRACT.md` tells -/// the launcher to start the gateway again. -const EXIT_INSTALLED_BINARY_REPLACED: i32 = 75; -/// The process cannot read its own executable path. That is a failure. -/// The launcher leaves this process stopped. -const EXIT_EXECUTABLE_PATH_UNREADABLE: i32 = 1; +/// The installed binary was replaced, or its hash changed. +/// `docs/LAUNCHER_CONTRACT.md` tells the launcher to start the gateway again. +const EXIT_LAUNCHER_RESTART: i32 = 75; +/// The launcher leaves this process stopped. A move, an unreadable path, +/// and a failed re-hash are this exit. +const EXIT_LAUNCHER_STAYS_STOPPED: i32 = 1; #[derive(Debug, Clone, PartialEq, Eq)] struct Supersession { @@ -276,10 +275,17 @@ impl BinarySupersessionWatch { self.superseded_reason_with(&RealBinarySnapshotReader) } - fn replaced(&self, reason: String) -> Option { + fn restart(&self, reason: String) -> Option { Some(Supersession { reason, - exit_code: EXIT_INSTALLED_BINARY_REPLACED, + exit_code: EXIT_LAUNCHER_RESTART, + }) + } + + fn stayed_stopped(&self, reason: String) -> Option { + Some(Supersession { + reason, + exit_code: EXIT_LAUNCHER_STAYS_STOPPED, }) } @@ -290,27 +296,24 @@ impl BinarySupersessionWatch { let current_exe_raw = match reader.current_exe_path_raw() { Ok(path) => path, Err(err) => { - return Some(Supersession { - reason: format!( - "host executable path could not be read for {}: {err:#}. Exiting stale host.", - self.current_exe_path.display() - ), - exit_code: EXIT_EXECUTABLE_PATH_UNREADABLE, - }); + return self.stayed_stopped(format!( + "host executable path could not be read for {}: {err:#}. Exiting stale host.", + self.current_exe_path.display() + )); } }; let raw_text = current_exe_raw.to_string_lossy(); let current_exe = normalize_deleted_exe_path(¤t_exe_raw); if raw_text.ends_with(" (deleted)") { - return self.replaced(format!( + return self.restart(format!( "host executable {} was replaced on disk. Exiting stale host.", self.current_exe_path.display() )); } if current_exe != self.current_exe_path { - return self.replaced(format!( + return self.stayed_stopped(format!( "host executable moved from {} to {}. Exiting stale host.", self.current_exe_path.display(), current_exe.display() @@ -320,7 +323,7 @@ impl BinarySupersessionWatch { let current_stamp = match reader.metadata_stamp(&self.current_exe_path) { Ok(stamp) => stamp, Err(err) => { - return self.replaced(format!( + return self.stayed_stopped(format!( "host executable {} could not be verified on disk: {err:#}. Exiting stale host.", self.current_exe_path.display() )); @@ -334,14 +337,14 @@ impl BinarySupersessionWatch { let current_snapshot = match reader.digest_snapshot(&self.current_exe_path) { Ok(snapshot) => snapshot, Err(err) => { - return self.replaced(format!( + return self.stayed_stopped(format!( "host executable {} changed on disk and could not be re-verified: {err:#}. Exiting stale host.", self.current_exe_path.display() )); } }; if current_snapshot.sha256 != self.current_binary_sha256 { - return self.replaced(format!( + return self.restart(format!( "host binary {} changed on disk. Exiting stale host so the newer binary can take over.", self.current_exe_path.display() )); @@ -513,6 +516,7 @@ mod tests { current_exe_raw: RefCell, digest_reads: Cell, fail_path: Cell, + fail_digest: Cell, } impl TestBinarySnapshotReader { @@ -522,6 +526,7 @@ mod tests { current_exe_raw: RefCell::new(path), digest_reads: Cell::new(0), fail_path: Cell::new(false), + fail_digest: Cell::new(false), }), } } @@ -534,6 +539,10 @@ mod tests { self.state.fail_path.set(true); } + fn fail_digest(&self) { + self.state.fail_digest.set(true); + } + fn digest_reads(&self) -> usize { self.state.digest_reads.get() } @@ -552,6 +561,9 @@ mod tests { } fn digest_snapshot(&self, path: &Path) -> anyhow::Result { + if self.state.fail_digest.get() { + anyhow::bail!("fixture re-hash failed"); + } self.state .digest_reads .set(self.state.digest_reads.get().saturating_add(1)); @@ -707,7 +719,7 @@ mod tests { let event = watch.superseded_reason_with(&reader).expect("superseded"); assert!(event.reason.contains("changed on disk"), "{}", event.reason); - assert_eq!(event.exit_code, EXIT_INSTALLED_BINARY_REPLACED); + assert_eq!(event.exit_code, EXIT_LAUNCHER_RESTART); assert_eq!(reader.digest_reads(), initial_reads + 1); } @@ -725,7 +737,7 @@ mod tests { let event = watch.superseded_reason_with(&reader).expect("superseded"); assert!(event.reason.contains("changed on disk"), "{}", event.reason); - assert_eq!(event.exit_code, EXIT_INSTALLED_BINARY_REPLACED); + assert_eq!(event.exit_code, EXIT_LAUNCHER_RESTART); assert_eq!(reader.digest_reads(), initial_reads + 1); } @@ -746,7 +758,7 @@ mod tests { "{}", event.reason ); - assert_eq!(event.exit_code, EXIT_INSTALLED_BINARY_REPLACED); + assert_eq!(event.exit_code, EXIT_LAUNCHER_STAYS_STOPPED); } #[test] @@ -764,7 +776,7 @@ mod tests { "{}", event.reason ); - assert_eq!(event.exit_code, EXIT_INSTALLED_BINARY_REPLACED); + assert_eq!(event.exit_code, EXIT_LAUNCHER_STAYS_STOPPED); } #[test] @@ -782,7 +794,7 @@ mod tests { "{}", event.reason ); - assert_eq!(event.exit_code, EXIT_INSTALLED_BINARY_REPLACED); + assert_eq!(event.exit_code, EXIT_LAUNCHER_RESTART); } #[test] @@ -800,6 +812,27 @@ mod tests { "{}", event.reason ); - assert_eq!(event.exit_code, EXIT_EXECUTABLE_PATH_UNREADABLE); + assert_eq!(event.exit_code, EXIT_LAUNCHER_STAYS_STOPPED); + } + + #[test] + fn supersession_watch_failed_rehash_stays_stopped() { + let temp = tempfile::tempdir().expect("tempdir"); + let exe = temp.path().join("elastos"); + write_file(&exe, b"original"); + + let (mut watch, reader) = test_watch(&exe); + write_file(&exe, b"changed bytes"); + reader.fail_digest(); + + let event = watch + .superseded_reason_with(&reader) + .expect("re-hash failed"); + assert!( + event.reason.contains("could not be re-verified"), + "{}", + event.reason + ); + assert_eq!(event.exit_code, EXIT_LAUNCHER_STAYS_STOPPED); } } From 9db30cc7057a262724bce9edb876286b5ba32754 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 16 Oct 2026 11:36:38 +0000 Subject: [PATCH 05/18] fix: bind gateway readiness and passkeys to the localhost origin Restore the binary watch to the develop exit-75 behavior. This pull request no longer changes which supersession paths restart. /healthz returns the two bytes OK only when this process owns host-process.lock. Passkey registration and sign-in use http://localhost:8090 and refuse an IP-literal origin. The launcher contract states those facts and stops using English stdout as a supervisor interface. Co-authored-by: Sash --- docs/LAUNCHER_CONTRACT.md | 207 ++++-------------- .../elastos-server/src/api/gateway_server.rs | 1 + .../elastos-server/src/api/gateway_site.rs | 24 +- .../src/api/gateway_tests/content_sandbox.rs | 1 + .../src/api/gateway_tests/frontdoor.rs | 1 + .../src/api/gateway_tests/mod.rs | 8 + .../src/api/gateway_tests/site_publication.rs | 46 +++- elastos/crates/elastos-server/src/auth.rs | 109 ++++++++- .../crates/elastos-server/src/host_lock.rs | 165 ++++---------- 9 files changed, 264 insertions(+), 298 deletions(-) diff --git a/docs/LAUNCHER_CONTRACT.md b/docs/LAUNCHER_CONTRACT.md index f6971aeec..b079a7c1c 100644 --- a/docs/LAUNCHER_CONTRACT.md +++ b/docs/LAUNCHER_CONTRACT.md @@ -1,205 +1,78 @@ -# Launcher contract +# Launcher Contract -This is the stable interface a desktop launcher uses to install, start, watch, -stop, and update the ElastOS Runtime. The launcher owns the supervisor. The -Runtime owns the process, the data directory, the host lock, and the signed -update. - -The checked behavior for readiness is `test_healthz_200` in -`elastos/crates/elastos-server/src/api/gateway_tests/site_publication.rs`. -The supervised start entry is `run_gateway` in -`elastos/crates/elastos-server/src/gateway_entry.rs`. - -## Install - -The launcher runs the publisher installer and stops before setup: - -```bash -curl -fsSL https://elastos.elacitylabs.com/install.sh | bash -s -- --install-only -``` - -`ELASTOS_INSTALL_ONLY=1` selects the same stop. The git copy of -`scripts/install.sh` still contains placeholder trust anchors. The launcher -runs the script the publisher URL serves, which carries the stamped anchors. - -That command installs the Runtime binary and the trusted source, then returns. -It leaves Home setup and the browser to the launcher. - -The launcher then runs: - -```bash -elastos setup -``` - -Setup installs the Home profile. `elastos setup --isolated`, chosen before the -first start, keeps this Home out of the shared Community room. - -The signed release head names the channel. Allowed names are `stable`, -`canary`, and `jetson-test`. The stable channel is the publication from -`main`. The installer records that channel in the trusted source. Later -updates follow the saved source. The launcher does not pass a channel flag. - -The installer accepts Linux x86_64, Linux aarch64, and macOS Apple silicon -(`aarch64-darwin`). On any other operating system or architecture it exits 1. -Intel Mac is outside this install set. That host has one name pair. The -release platform id is `x86_64-darwin`. The package key is `darwin-amd64`. -`scripts/release-platforms.json` maps `darwin-amd64` to `x86_64-darwin`. The -launcher calls the same host `darwin-x64`. The signer admits `x86_64-linux`, -`aarch64-linux`, and `aarch64-darwin`. It refuses `x86_64-darwin` in -`scripts/release-signer.py` until one signed Intel artifact exists. This tree -has no Intel download. See [Mac notes](MAC.md) for the source-home path on -Apple silicon. +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 -The launcher starts Home with: - ```bash -elastos gateway --addr 127.0.0.1:8090 +elastos gateway --addr localhost:8090 ``` -`--addr` (`-a`) is `host:port`. The default is `127.0.0.1:8090`. The launcher -owns the address it passes and uses that same address for every probe and for -the Home URL. - -`elastos gateway` leaves the system browser closed. `elastos home --browser` -is a different command: it binds `localhost:8090` and opens the URL with -`open` on macOS, or `wslview` and then `xdg-open` on Linux. The launcher uses -`gateway`. - -`elastos serve` is the operator runtime. Its readiness route is -`GET /api/health`. The launcher does not start `serve` against the same data -directory, and it does not use `/api/health` as the Home probe. - -`--public` starts a tunnel and is outside this contract. +`--addr` is `host:port`. `elastos home` binds `localhost:8090` and opens the +Home URL below. The gateway command leaves the system browser closed. -On startup the gateway prints: - -```text -[gateway] ElastOS starting on -``` - -That line is progress. Readiness is the HTTP probe below. +`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 the gateway is listening: +When this gateway process is the recorded owner of `{data}/host-process.lock`, +with role `gateway` or `gateway-public` and `pid` equal to its process id: ```text -GET http://127.0.0.1:8090/healthz +GET http://localhost:8090/healthz ``` -returns HTTP 200 and the body bytes `OK` (three bytes, no trailing newline). -`test_healthz_200` locks that response. +returns HTTP 200 and the two bytes `OK`. A different pid, a missing lock, or a +lock that is not JSON returns HTTP 503. The probe does not treat another +process on the port as this Home. -The launcher opens: +The Home origin is: ```text -http://127.0.0.1:8090/home/ +http://localhost:8090/home/ ``` -`/home/` is `HOME_ROUTE`. `/home` and `/apps/home/` redirect to it. The page -is the Home capsule installed by `elastos setup`. The launcher opens this URL -in its own browser after `/healthz` returns `OK`. - -A source-home staging script may bind another port. The launcher uses the -address it passed to `--addr`. +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. -## Data directory and binary +## Data directory and lock | Item | Path | | --- | --- | -| Binary | `~/.local/bin/elastos`, or the directory passed as `--install-dir` | | Linux data directory | `$XDG_DATA_HOME/elastos`, or `~/.local/share/elastos` | | macOS data directory | `~/Library/Application Support/elastos` | -| Trusted source | `{data}/sources.json` | -| Installed components | `{data}/components.json` | | Host lock | `{data}/host-process.lock` | -The Runtime resolves the data directory with the platform data directory -(`dirs::data_dir()`), then `elastos`. The installer uses the same split: -`~/Library/Application Support/elastos` on macOS, and -`$XDG_DATA_HOME/elastos` or `~/.local/share/elastos` on Linux. - -The launcher keeps one data directory for the Home it supervises. It leaves -any other product directory in place. - -Coordinate files under the data directory (`runtime-coords.json`, -`gateway-runtime-coords.json`, `home-runtime-coords.json`) hold a local -`attach_secret`. The launcher log is the gateway process stdout and stderr. -The launcher leaves those coordinate files out of the log. - -`elastos version` prints `ElastOS Runtime v`. - -## Single instance - -The gateway takes an exclusive lock on `{data}/host-process.lock` and writes -the pid, the role `gateway`, and the bind address. A second live host for the -same data directory exits 1. Its error contains: - -```text -another ElastOS host already owns -``` - -The launcher shows that error. It leaves the process that holds the lock -running. +The lock record stores `pid`, `role`, and `addr`. A second live host for the +same data directory exits 1. Its error contains `another ElastOS host already owns`. ## Stop -The launcher sends `SIGTERM` to the gateway process. - -`elastos gateway` puts itself in its own process group. On `SIGTERM` or -`SIGINT` the Runtime prints `Shutting down...`, signals that group with -`SIGTERM`, waits 15 seconds, then signals the group with `SIGKILL`. - -The launcher waits until `GET /healthz` fails. A stop that begins with -`SIGKILL` to the parent skips the handler, so child processes can remain. -Exit status after a requested stop is the signal status. The launcher treats -a dead `/healthz` as stopped. +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, a replaced installed binary or a changed binary -hash makes that process exit 75. The launcher starts -`elastos gateway --addr 127.0.0.1:8090` again so the new binary takes the lock. -A moved executable path, a path that cannot be read, and a file that changed -and then could not be re-verified exit 1. The launcher leaves that process -stopped. - -## Update and rollback - -```bash -elastos update --check -elastos update --yes -elastos update --rollback-to --yes -``` - -There is no `elastos upgrade` command. `--check` and a completed install both -exit 0. When the saved release is current, stdout contains -`Installed release is up to date.` When a newer signed release exists, -stdout contains `Run `elastos update` to install.` The launcher reads that -text. The exit code stays 0 in both cases. - -`--yes` skips the confirmation prompt. The launcher passes `--yes` on every -install and rollback. A declined prompt also exits 0 and prints -`Update cancelled.` - -`--rollback-to` selects that signed head and admits an older release. The -launcher saves the current head CID from `elastos source show` (`Head CID:`) -before an update, and passes that CID to `--rollback-to`. A plain update of -an older release exits 1 and tells the operator to use the rollback command. - -`--force` repairs an invalid installed version. It is a separate flag from -rollback. - -Update and rollback use the trusted source over Carrier. They replace the -installed binary and `components.json` after signature and hash checks. +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. This includes `update --check` with or without a newer release, a declined update prompt, and `install.sh --help`. | -| 1 | The command failed. This includes the installer `die` path (unknown option, unsupported platform, failed check), a held host lock, a missing trusted source, a failed signature check, an older release without `--rollback-to`, and a running gateway whose executable path cannot be read, whose path moved, or whose file could not be re-verified. | -| 2 | The `elastos` command line is invalid. Clap reports a usage error with exit 2. | -| 75 | The running gateway exited because the installed binary was replaced or its hash changed. The launcher starts the gateway again. | +| 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. -`install.sh` reports a failed check with exit 1. +Intel Mac's release id is `x86_64-darwin`. This contract does not publish a +download for that id. diff --git a/elastos/crates/elastos-server/src/api/gateway_server.rs b/elastos/crates/elastos-server/src/api/gateway_server.rs index 27b8e787f..ddb3bf897 100644 --- a/elastos/crates/elastos-server/src/api/gateway_server.rs +++ b/elastos/crates/elastos-server/src/api/gateway_server.rs @@ -93,6 +93,7 @@ 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 _health_lock = crate::host_lock::publish_gateway_lock_if_unowned(&data_dir, addr)?; let listener = TcpListener::bind(addr).await?; let local_control_registry = provider_registry.clone(); let gateway_api_url = if addr.parse::()?.port_u16() == Some(0) { diff --git a/elastos/crates/elastos-server/src/api/gateway_site.rs b/elastos/crates/elastos-server/src/api/gateway_site.rs index a8257780b..d48f4db33 100644 --- a/elastos/crates/elastos-server/src/api/gateway_site.rs +++ b/elastos/crates/elastos-server/src/api/gateway_site.rs @@ -429,8 +429,28 @@ pub(super) fn request_host(headers: &HeaderMap) -> anyhow::Result Ok(Some(validated_gateway_host(headers)?)) } -pub(super) async fn healthz() -> &'static str { - "OK" +/// Readiness for the process that holds `host-process.lock`. +/// The body is the two bytes `OK` only when this process is the recorded gateway. +pub(super) async fn healthz(State(state): State) -> Response { + if gateway_health_lock_matches(&state.data_dir) { + (StatusCode::OK, "OK").into_response() + } else { + StatusCode::SERVICE_UNAVAILABLE.into_response() + } +} + +fn gateway_health_lock_matches(data_dir: &std::path::Path) -> bool { + let Ok(bytes) = std::fs::read(data_dir.join("host-process.lock")) else { + return false; + }; + let Ok(meta) = serde_json::from_slice::(&bytes) else { + return false; + }; + meta.get("pid").and_then(|value| value.as_u64()) == Some(u64::from(std::process::id())) + && matches!( + meta.get("role").and_then(|value| value.as_str()), + Some("gateway" | "gateway-public") + ) } 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..52aea3c8a 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'"); + super::write_gateway_health_lock(dir.path(), std::process::id()); 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..c78ac62ad 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 ); + super::write_gateway_health_lock(dir.path(), std::process::id()); let valid = Request::builder() .uri("/healthz") .header(HOST, "127.0.0.1:61180") 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..bf29f9cd2 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,14 @@ fn test_launch_token_from_route(route: &str) -> String { .expect("launch route home token") } +pub(super) fn write_gateway_health_lock(data_dir: &std::path::Path, pid: u32) { + std::fs::write( + data_dir.join("host-process.lock"), + format!("{{\"pid\":{pid},\"role\":\"gateway\",\"addr\":\"localhost:8090\"}}\n"), + ) + .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 e3affe5b7..f127ac7f3 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,11 +221,11 @@ async fn test_root_serves_mywebsite_when_staged() { assert_eq!(&body[..], b"home site"); } -/// Launcher readiness. `docs/LAUNCHER_CONTRACT.md` defines this response: -/// HTTP 200 and the body bytes `OK`. +/// 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(); + super::write_gateway_health_lock(dir.path(), std::process::id()); let state = test_state(dir.path()); let app = gateway_router(state); @@ -244,6 +244,47 @@ async fn test_healthz_200() { .await .unwrap(); assert_eq!(&body[..], b"OK"); + assert_eq!(body.len(), 2); +} + +#[tokio::test] +async fn test_healthz_refuses_another_pid_and_a_tampered_lock() { + let dir = tempfile::tempdir().unwrap(); + super::write_gateway_health_lock(dir.path(), std::process::id().wrapping_add(1)); + let app = gateway_router(test_state(dir.path())); + let response = app + .oneshot( + Request::builder() + .uri("/healthz") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + + std::fs::write(dir.path().join("host-process.lock"), b"not-json").unwrap(); + let app = gateway_router(test_state(dir.path())); + let response = app + .oneshot( + Request::builder() + .uri("/healthz") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + 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/")); } #[tokio::test] @@ -685,6 +726,7 @@ async fn test_concurrent_release_reads_wait_health_works_and_scan_once() { .is_err() ); assert!(requests.iter().all(|request| !request.is_finished())); + super::write_gateway_health_lock(&fixture.base, std::process::id()); let response = app .clone() .oneshot( diff --git a/elastos/crates/elastos-server/src/auth.rs b/elastos/crates/elastos-server/src/auth.rs index 740ab8e1c..0531000f6 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,25 @@ fn check_owner_claim( Ok(()) } +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 enrollment_denied(); + } + Ok(()) +} + +fn require_passkey_origin(origin: &str, rp_id: &str) -> anyhow::Result<()> { + let url = url::Url::parse(origin).map_err(|_| OwnerEnrollmentDenied)?; + let Some(host) = url.host_str() else { + return enrollment_denied(); + }; + if host.parse::().is_ok() || host != rp_id { + return enrollment_denied(); + } + Ok(()) +} + pub(crate) fn begin_owner_enrollment( data_dir: &Path, identity: &mut elastos_identity::IdentityManager, @@ -1851,6 +1870,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 +2806,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 +3980,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/host_lock.rs b/elastos/crates/elastos-server/src/host_lock.rs index 7627db8a4..40bb32c05 100644 --- a/elastos/crates/elastos-server/src/host_lock.rs +++ b/elastos/crates/elastos-server/src/host_lock.rs @@ -78,6 +78,23 @@ struct HostProcessMeta { generation: String, } +/// The gateway server publishes its pid when this process does not already hold the lock. +/// `gateway` and `gateway-public` already write that record before the server starts. +pub fn publish_gateway_lock_if_unowned( + data_dir: &Path, + addr: &str, +) -> anyhow::Result> { + let path = host_lock_path(data_dir); + if let Some(meta) = read_lock_metadata(&path) { + if meta.pid == std::process::id() + && matches!(meta.role.as_str(), "gateway" | "gateway-public") + { + return Ok(None); + } + } + acquire_host_process_lock(data_dir, "gateway", addr).map(Some) +} + pub fn acquire_host_process_lock( data_dir: &Path, role: &str, @@ -224,19 +241,6 @@ struct BinarySnapshot { sha256: String, } -/// The installed binary was replaced, or its hash changed. -/// `docs/LAUNCHER_CONTRACT.md` tells the launcher to start the gateway again. -const EXIT_LAUNCHER_RESTART: i32 = 75; -/// The launcher leaves this process stopped. A move, an unreadable path, -/// and a failed re-hash are this exit. -const EXIT_LAUNCHER_STAYS_STOPPED: i32 = 1; - -#[derive(Debug, Clone, PartialEq, Eq)] -struct Supersession { - reason: String, - exit_code: i32, -} - pub fn spawn_installed_binary_supersession_watch(data_dir: &Path, role: &str) { let Some(mut watch) = BinarySupersessionWatch::from_data_dir(data_dir) else { return; @@ -247,9 +251,9 @@ pub fn spawn_installed_binary_supersession_watch(data_dir: &Path, role: &str) { interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); loop { interval.tick().await; - if let Some(event) = watch.superseded_reason() { - eprintln!("[{}] {}", role, event.reason); - std::process::exit(event.exit_code); + if let Some(reason) = watch.superseded_reason() { + eprintln!("[{}] {}", role, reason); + std::process::exit(75); } } }); @@ -271,32 +275,15 @@ impl BinarySupersessionWatch { }) } - fn superseded_reason(&mut self) -> Option { + fn superseded_reason(&mut self) -> Option { self.superseded_reason_with(&RealBinarySnapshotReader) } - fn restart(&self, reason: String) -> Option { - Some(Supersession { - reason, - exit_code: EXIT_LAUNCHER_RESTART, - }) - } - - fn stayed_stopped(&self, reason: String) -> Option { - Some(Supersession { - reason, - exit_code: EXIT_LAUNCHER_STAYS_STOPPED, - }) - } - - fn superseded_reason_with( - &mut self, - reader: &impl BinarySnapshotReader, - ) -> Option { + fn superseded_reason_with(&mut self, reader: &impl BinarySnapshotReader) -> Option { let current_exe_raw = match reader.current_exe_path_raw() { Ok(path) => path, Err(err) => { - return self.stayed_stopped(format!( + return Some(format!( "host executable path could not be read for {}: {err:#}. Exiting stale host.", self.current_exe_path.display() )); @@ -306,14 +293,14 @@ impl BinarySupersessionWatch { let current_exe = normalize_deleted_exe_path(¤t_exe_raw); if raw_text.ends_with(" (deleted)") { - return self.restart(format!( + return Some(format!( "host executable {} was replaced on disk. Exiting stale host.", self.current_exe_path.display() )); } if current_exe != self.current_exe_path { - return self.stayed_stopped(format!( + return Some(format!( "host executable moved from {} to {}. Exiting stale host.", self.current_exe_path.display(), current_exe.display() @@ -323,7 +310,7 @@ impl BinarySupersessionWatch { let current_stamp = match reader.metadata_stamp(&self.current_exe_path) { Ok(stamp) => stamp, Err(err) => { - return self.stayed_stopped(format!( + return Some(format!( "host executable {} could not be verified on disk: {err:#}. Exiting stale host.", self.current_exe_path.display() )); @@ -337,14 +324,14 @@ impl BinarySupersessionWatch { let current_snapshot = match reader.digest_snapshot(&self.current_exe_path) { Ok(snapshot) => snapshot, Err(err) => { - return self.stayed_stopped(format!( + return Some(format!( "host executable {} changed on disk and could not be re-verified: {err:#}. Exiting stale host.", self.current_exe_path.display() )); } }; if current_snapshot.sha256 != self.current_binary_sha256 { - return self.restart(format!( + return Some(format!( "host binary {} changed on disk. Exiting stale host so the newer binary can take over.", self.current_exe_path.display() )); @@ -515,8 +502,6 @@ mod tests { struct TestBinarySnapshotReaderState { current_exe_raw: RefCell, digest_reads: Cell, - fail_path: Cell, - fail_digest: Cell, } impl TestBinarySnapshotReader { @@ -525,8 +510,6 @@ mod tests { state: Rc::new(TestBinarySnapshotReaderState { current_exe_raw: RefCell::new(path), digest_reads: Cell::new(0), - fail_path: Cell::new(false), - fail_digest: Cell::new(false), }), } } @@ -535,14 +518,6 @@ mod tests { *self.state.current_exe_raw.borrow_mut() = path; } - fn fail_current_exe(&self) { - self.state.fail_path.set(true); - } - - fn fail_digest(&self) { - self.state.fail_digest.set(true); - } - fn digest_reads(&self) -> usize { self.state.digest_reads.get() } @@ -550,9 +525,6 @@ mod tests { impl BinarySnapshotReader for TestBinarySnapshotReader { fn current_exe_path_raw(&self) -> anyhow::Result { - if self.state.fail_path.get() { - anyhow::bail!("fixture path unreadable"); - } Ok(self.state.current_exe_raw.borrow().clone()) } @@ -561,9 +533,6 @@ mod tests { } fn digest_snapshot(&self, path: &Path) -> anyhow::Result { - if self.state.fail_digest.get() { - anyhow::bail!("fixture re-hash failed"); - } self.state .digest_reads .set(self.state.digest_reads.get().saturating_add(1)); @@ -717,9 +686,8 @@ mod tests { let initial_reads = reader.digest_reads(); write_file(&exe, b"changed content with a different length"); - let event = watch.superseded_reason_with(&reader).expect("superseded"); - assert!(event.reason.contains("changed on disk"), "{}", event.reason); - assert_eq!(event.exit_code, EXIT_LAUNCHER_RESTART); + let reason = watch.superseded_reason_with(&reader).expect("superseded"); + assert!(reason.contains("changed on disk"), "{reason}"); assert_eq!(reader.digest_reads(), initial_reads + 1); } @@ -735,9 +703,8 @@ mod tests { write_file(&replacement, b"modified"); fs::rename(&replacement, &exe).expect("replace file"); - let event = watch.superseded_reason_with(&reader).expect("superseded"); - assert!(event.reason.contains("changed on disk"), "{}", event.reason); - assert_eq!(event.exit_code, EXIT_LAUNCHER_RESTART); + let reason = watch.superseded_reason_with(&reader).expect("superseded"); + assert!(reason.contains("changed on disk"), "{reason}"); assert_eq!(reader.digest_reads(), initial_reads + 1); } @@ -751,14 +718,9 @@ mod tests { let moved = temp.path().join("elastos-new"); reader.set_current_exe_raw(moved.clone()); - let event = watch.superseded_reason_with(&reader).expect("superseded"); - assert!(event.reason.contains("moved"), "{}", event.reason); - assert!( - event.reason.contains(&moved.display().to_string()), - "{}", - event.reason - ); - assert_eq!(event.exit_code, EXIT_LAUNCHER_STAYS_STOPPED); + let reason = watch.superseded_reason_with(&reader).expect("superseded"); + assert!(reason.contains("moved"), "{reason}"); + assert!(reason.contains(&moved.display().to_string()), "{reason}"); } #[test] @@ -770,13 +732,8 @@ mod tests { let (mut watch, reader) = test_watch(&exe); fs::remove_file(&exe).expect("remove file"); - let event = watch.superseded_reason_with(&reader).expect("superseded"); - assert!( - event.reason.contains("could not be verified on disk"), - "{}", - event.reason - ); - assert_eq!(event.exit_code, EXIT_LAUNCHER_STAYS_STOPPED); + let reason = watch.superseded_reason_with(&reader).expect("superseded"); + assert!(reason.contains("could not be verified on disk"), "{reason}"); } #[test] @@ -788,51 +745,7 @@ mod tests { let (mut watch, reader) = test_watch(&exe); reader.set_current_exe_raw(PathBuf::from(format!("{} (deleted)", exe.display()))); - let event = watch.superseded_reason_with(&reader).expect("superseded"); - assert!( - event.reason.contains("replaced on disk"), - "{}", - event.reason - ); - assert_eq!(event.exit_code, EXIT_LAUNCHER_RESTART); - } - - #[test] - fn supersession_watch_unreadable_path_is_a_failure() { - let temp = tempfile::tempdir().expect("tempdir"); - let exe = temp.path().join("elastos"); - write_file(&exe, b"original"); - - let (mut watch, reader) = test_watch(&exe); - reader.fail_current_exe(); - - let event = watch.superseded_reason_with(&reader).expect("unreadable"); - assert!( - event.reason.contains("could not be read"), - "{}", - event.reason - ); - assert_eq!(event.exit_code, EXIT_LAUNCHER_STAYS_STOPPED); - } - - #[test] - fn supersession_watch_failed_rehash_stays_stopped() { - let temp = tempfile::tempdir().expect("tempdir"); - let exe = temp.path().join("elastos"); - write_file(&exe, b"original"); - - let (mut watch, reader) = test_watch(&exe); - write_file(&exe, b"changed bytes"); - reader.fail_digest(); - - let event = watch - .superseded_reason_with(&reader) - .expect("re-hash failed"); - assert!( - event.reason.contains("could not be re-verified"), - "{}", - event.reason - ); - assert_eq!(event.exit_code, EXIT_LAUNCHER_STAYS_STOPPED); + let reason = watch.superseded_reason_with(&reader).expect("superseded"); + assert!(reason.contains("replaced on disk"), "{reason}"); } } From 1e63148f21e1dee29905f5f9b0ca3259472dafe4 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 16 Oct 2026 12:20:30 +0000 Subject: [PATCH 06/18] fix: keep local passkey fixtures on the localhost relying party The configured-host /healthz check writes the gateway lock before it expects HTTP 200. Local guest fixtures use rp id localhost, matching the origin the session grant accepts. Co-authored-by: Sash --- elastos/crates/elastos-server/src/api/auth_gateway.rs | 6 ++++-- .../elastos-server/src/api/gateway_tests/frontdoor.rs | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/auth_gateway.rs b/elastos/crates/elastos-server/src/api/auth_gateway.rs index 62c380ed8..6f6293bb5 100644 --- a/elastos/crates/elastos-server/src/api/auth_gateway.rs +++ b/elastos/crates/elastos-server/src/api/auth_gateway.rs @@ -8784,7 +8784,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(), @@ -8854,7 +8855,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_tests/frontdoor.rs b/elastos/crates/elastos-server/src/api/gateway_tests/frontdoor.rs index c78ac62ad..2e814875a 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/frontdoor.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/frontdoor.rs @@ -155,6 +155,7 @@ async fn frontdoor_public_list_requires_configured_gateway_host() { "gateway_allowed_hosts = [\"home.example.test\"]\n", ) .unwrap(); + super::write_gateway_health_lock(dir.path(), std::process::id()); let app = app(dir.path()); let response = app .clone() From 6c7675220e8ca2f614424ac23909412b57a18688 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 07:15:04 +0000 Subject: [PATCH 07/18] fix: let a gateway inside serve start without taking the host lock again elastos serve holds host-process.lock as serve, and its supervisor can start a gateway in the same process for elastos room open. The readiness change made that gateway take the lock a second time, so it stopped at start with "another ElastOS host already owns" naming its own pid. The gateway now keeps a record that already names this process. Its /healthz returns 503 because the role is serve, not a Home gateway. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W6Qn9RX7LDqrwiAfNC2F2K --- docs/LAUNCHER_CONTRACT.md | 5 +- .../elastos-server/src/api/gateway_server.rs | 52 +++++++++++++++++++ .../crates/elastos-server/src/host_lock.rs | 14 +++-- 3 files changed, 61 insertions(+), 10 deletions(-) diff --git a/docs/LAUNCHER_CONTRACT.md b/docs/LAUNCHER_CONTRACT.md index b079a7c1c..eb591e041 100644 --- a/docs/LAUNCHER_CONTRACT.md +++ b/docs/LAUNCHER_CONTRACT.md @@ -27,8 +27,9 @@ GET http://localhost:8090/healthz ``` returns HTTP 200 and the two bytes `OK`. A different pid, a missing lock, or a -lock that is not JSON returns HTTP 503. The probe does not treat another -process on the port as this Home. +lock that is not JSON returns HTTP 503. A gateway that `elastos serve` starts +keeps the `serve` record, so its `/healthz` returns 503. The probe does not +treat another process on the port as this Home. The Home origin is: diff --git a/elastos/crates/elastos-server/src/api/gateway_server.rs b/elastos/crates/elastos-server/src/api/gateway_server.rs index ddb3bf897..441f8882c 100644 --- a/elastos/crates/elastos-server/src/api/gateway_server.rs +++ b/elastos/crates/elastos-server/src/api/gateway_server.rs @@ -751,6 +751,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(); diff --git a/elastos/crates/elastos-server/src/host_lock.rs b/elastos/crates/elastos-server/src/host_lock.rs index 40bb32c05..5bfd5d053 100644 --- a/elastos/crates/elastos-server/src/host_lock.rs +++ b/elastos/crates/elastos-server/src/host_lock.rs @@ -78,19 +78,17 @@ struct HostProcessMeta { generation: String, } -/// The gateway server publishes its pid when this process does not already hold the lock. -/// `gateway` and `gateway-public` already write that record before the server starts. +/// The gateway server publishes its pid when no host in this process holds the lock. +/// `gateway` and `gateway-public` write that record before the server starts. +/// `serve` also holds it when its supervisor starts a gateway in the same process. +/// That gateway keeps the `serve` record, so its `/healthz` answers 503. pub fn publish_gateway_lock_if_unowned( data_dir: &Path, addr: &str, ) -> anyhow::Result> { let path = host_lock_path(data_dir); - if let Some(meta) = read_lock_metadata(&path) { - if meta.pid == std::process::id() - && matches!(meta.role.as_str(), "gateway" | "gateway-public") - { - return Ok(None); - } + if read_lock_metadata(&path).is_some_and(|meta| meta.pid == std::process::id()) { + return Ok(None); } acquire_host_process_lock(data_dir, "gateway", addr).map(Some) } From a41378d41fa6f617be1aa0a7d5b8c2893cc9860a Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 07:15:04 +0000 Subject: [PATCH 08/18] fix: tell the person which address to open when a passkey origin is refused Every release takes the relying party id from the page host, and browsers refuse an IP address as that id, so a stored passkey names the host where it was made. A test signs a stored localhost owner passkey in at three ports and a public passkey at its https host, and refuses both at foreign, IP-literal and look-alike hosts without a state change. The refusal is HTTP 403 with plain text that names http://localhost:/home/ for a loopback page, instead of "owner enrollment unavailable". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W6Qn9RX7LDqrwiAfNC2F2K --- docs/LAUNCHER_CONTRACT.md | 9 +- .../elastos-server/src/api/auth_gateway.rs | 122 ++++++++++++++++++ .../src/api/handlers/identity.rs | 4 +- elastos/crates/elastos-server/src/auth.rs | 52 +++++++- 4 files changed, 179 insertions(+), 8 deletions(-) diff --git a/docs/LAUNCHER_CONTRACT.md b/docs/LAUNCHER_CONTRACT.md index eb591e041..c4e137692 100644 --- a/docs/LAUNCHER_CONTRACT.md +++ b/docs/LAUNCHER_CONTRACT.md @@ -38,7 +38,14 @@ http://localhost:8090/home/ ``` 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. +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 diff --git a/elastos/crates/elastos-server/src/api/auth_gateway.rs b/elastos/crates/elastos-server/src/api/auth_gateway.rs index 6f6293bb5..30010cc0c 100644 --- a/elastos/crates/elastos-server/src/api/auth_gateway.rs +++ b/elastos/crates/elastos-server/src/api/auth_gateway.rs @@ -4512,6 +4512,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") @@ -8614,6 +8615,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"] { 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 0531000f6..3b79ddc82 100644 --- a/elastos/crates/elastos-server/src/auth.rs +++ b/elastos/crates/elastos-server/src/auth.rs @@ -1831,21 +1831,61 @@ 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 enrollment_denied(); + 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 Some(host) = url.host_str() else { - return enrollment_denied(); - }; - if host.parse::().is_ok() || host != rp_id { - return enrollment_denied(); + 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(()) } From 5e0e9f8e691427511fa6ffca1c91028ab10135f2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 07:15:04 +0000 Subject: [PATCH 09/18] docs: state the readiness and listen-socket gaps in the launcher contract /healthz describes the process that answers on the port, so another gateway for a different data directory also returns OK. The contract now says what a supervisor checks before it trusts OK. It also states that --addr with a host name binds one address, so localhost:8090 listens on one address family. The healthz test adds another role, a missing lock and a string pid, and pins the gap text. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W6Qn9RX7LDqrwiAfNC2F2K --- docs/LAUNCHER_CONTRACT.md | 21 ++++++-- .../src/api/gateway_tests/site_publication.rs | 53 ++++++++++++++----- 2 files changed, 58 insertions(+), 16 deletions(-) diff --git a/docs/LAUNCHER_CONTRACT.md b/docs/LAUNCHER_CONTRACT.md index c4e137692..4539c1b5c 100644 --- a/docs/LAUNCHER_CONTRACT.md +++ b/docs/LAUNCHER_CONTRACT.md @@ -14,6 +14,13 @@ 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 gateway listens on one socket. For a host name, it binds the first address +that the name resolves to and that it can bind. `localhost` can resolve to +`127.0.0.1` or to `::1` first, so `localhost:8090` listens on one address +family only. A client that connects to the other family gets no answer from +this gateway. Listening on every address of `localhost` 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`. @@ -26,10 +33,16 @@ with role `gateway` or `gateway-public` and `pid` equal to its process id: GET http://localhost:8090/healthz ``` -returns HTTP 200 and the two bytes `OK`. A different pid, a missing lock, or a -lock that is not JSON returns HTTP 503. A gateway that `elastos serve` starts -keeps the `serve` record, so its `/healthz` returns 503. The probe does not -treat another process on the port as this Home. +returns HTTP 200 and the two bytes `OK`. A different pid, another role, a +missing lock, or a lock that is not JSON returns HTTP 503. A gateway that +`elastos serve` starts keeps the `serve` record, so its `/healthz` returns 503. + +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`. 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`. A reply that names the lock owner is a gap in this contract. The Home origin is: 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 f127ac7f3..d6379551b 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 @@ -263,18 +263,43 @@ async fn test_healthz_refuses_another_pid_and_a_tampered_lock() { .unwrap(); assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); - std::fs::write(dir.path().join("host-process.lock"), b"not-json").unwrap(); - let app = gateway_router(test_state(dir.path())); - let response = app - .oneshot( - Request::builder() - .uri("/healthz") - .body(Body::empty()) - .unwrap(), - ) - .await - .unwrap(); - assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + let pid = std::process::id(); + for lock in [ + Some(b"not-json".to_vec()), + None, + Some( + format!("{{\"pid\":{pid},\"role\":\"serve\",\"addr\":\"localhost:8090\"}}") + .into_bytes(), + ), + Some( + format!("{{\"pid\":\"{pid}\",\"role\":\"gateway\",\"addr\":\"localhost:8090\"}}") + .into_bytes(), + ), + ] { + let path = dir.path().join("host-process.lock"); + match &lock { + Some(bytes) => std::fs::write(&path, bytes).unwrap(), + None => { + let _ = std::fs::remove_file(&path); + } + } + let app = gateway_router(test_state(dir.path())); + let response = app + .oneshot( + Request::builder() + .uri("/healthz") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!( + response.status(), + StatusCode::SERVICE_UNAVAILABLE, + "{:?}", + lock.map(String::from_utf8) + ); + } let contract = std::fs::read_to_string(concat!( env!("CARGO_MANIFEST_DIR"), "/../../../docs/LAUNCHER_CONTRACT.md" @@ -285,6 +310,10 @@ async fn test_healthz_refuses_another_pid_and_a_tampered_lock() { 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")); } #[tokio::test] From 756dad1c55210bb6f5732276b83d865b167f0818 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 07:22:39 +0000 Subject: [PATCH 10/18] deps: move zip to 9.x for RUSTSEC-2026-0367/0368/0369 cargo-audit fails on every PR: zip 2.4.2 in elastos/Cargo.lock and in capsules/object-provider/Cargo.lock (through its elastos-server path dependency) has three advisories against ZipArchive::extract and the stream extract API. The runtime calls neither; it reads each entry itself. zip 9.0.4 is the patched release. - elastos-server uses zip 9.0.4, still without default features. 9.x has no separate flate2 feature; deflate-flate2 now enables the dependency. - Both lockfiles change only for zip: nix 0.31.3 and typed-path come in, derive_arbitrary goes. `cargo update -p zip` also moved unrelated range dependencies (windows-sys, getrandom); those lines stay as they were, and `cargo metadata --locked` accepts both files. - ZipFile::name now returns a Result. The ZIP readers report an error as "invalid ZIP archive entry". - Whole-archive extract keeps its rule for entry names. zip 9 enclosed_name turns "/a.txt" into "a.txt" and folds "x/../a.txt" into "a.txt", so an entry that extract refuses today would be written. The runtime now checks the name with the rule zip 2.x applied: no NUL byte, no root or drive prefix, no climb above the archive root. test_library_provider_extract_zip_refuses_absolute_dotdot_and_symlink_entries covers absolute, "..", inner "..", backslash and symlink entries. It passes on zip 2.4.2 and with this change, and fails on the Absolute.zip case when extract uses zip 9 enclosed_name. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W6Qn9RX7LDqrwiAfNC2F2K --- capsules/object-provider/Cargo.lock | 50 ++--- elastos/Cargo.lock | 50 ++--- elastos/crates/elastos-server/Cargo.toml | 2 +- .../src/api/gateway_tests/library.rs | 199 +++++++++++++++++- elastos/crates/elastos-server/src/library.rs | 44 +++- 5 files changed, 290 insertions(+), 55 deletions(-) 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/elastos/Cargo.lock b/elastos/Cargo.lock index ac82b721d..dc06da84e 100644 --- a/elastos/Cargo.lock +++ b/elastos/Cargo.lock @@ -167,9 +167,6 @@ name = "arbitrary" version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" -dependencies = [ - "derive_arbitrary", -] [[package]] name = "arc-swap" @@ -1197,7 +1194,7 @@ dependencies = [ "elastos-protected-content-provider-contracts", "elastos-protected-content-rights", "getrandom 0.2.17", - "nix", + "nix 0.29.0", "serde", "serde_json", "sha2 0.10.9", @@ -1281,17 +1278,6 @@ version = "0.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" -[[package]] -name = "derive_arbitrary" -version = "1.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "derive_more" version = "2.1.1" @@ -1598,7 +1584,7 @@ dependencies = [ "elastos-common", "elastos-compute", "libc", - "nix", + "nix 0.29.0", "serde", "serde_json", "tempfile", @@ -1706,7 +1692,7 @@ dependencies = [ "hkdf", "hpke", "k256", - "nix", + "nix 0.29.0", "rand 0.10.2", "rand 0.9.5", "rand_chacha 0.3.1", @@ -1765,7 +1751,7 @@ dependencies = [ "elastos-wallet-contract", "hex", "k256", - "nix", + "nix 0.29.0", "serde", "serde_json", "sha2 0.10.9", @@ -3925,6 +3911,18 @@ dependencies = [ "libc", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nom" version = "7.1.3" @@ -6164,6 +6162,12 @@ dependencies = [ "utf-8", ] +[[package]] +name = "typed-path" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e" + [[package]] name = "typenum" version = "1.20.1" @@ -7703,18 +7707,16 @@ dependencies = [ [[package]] name = "zip" -version = "2.4.2" +version = "9.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50" +checksum = "a954114b47a54df49f83d2722814e86b23d4bb1b54a1b90fb7d92b41619ddc22" dependencies = [ - "arbitrary", "crc32fast", - "crossbeam-utils", - "displaydoc", "flate2", "indexmap", "memchr", - "thiserror 2.0.20", + "nix 0.31.3", + "typed-path", ] [[package]] diff --git a/elastos/crates/elastos-server/Cargo.toml b/elastos/crates/elastos-server/Cargo.toml index 84788f1d5..e54e95885 100644 --- a/elastos/crates/elastos-server/Cargo.toml +++ b/elastos/crates/elastos-server/Cargo.toml @@ -104,7 +104,7 @@ tempfile = "3.10" # Archive extraction (for capsule artifacts) flate2 = "1.0" tar = "0.4" -zip = { version = "2.4.2", default-features = false, features = ["deflate-flate2", "flate2"] } +zip = { version = "9.0.4", default-features = false, features = ["deflate-flate2"] } libc = "0.2" # Built-in Carrier transport (P2P for updates, gossip messaging, DHT discovery). diff --git a/elastos/crates/elastos-server/src/api/gateway_tests/library.rs b/elastos/crates/elastos-server/src/api/gateway_tests/library.rs index d8477c0db..0253c229f 100644 --- a/elastos/crates/elastos-server/src/api/gateway_tests/library.rs +++ b/elastos/crates/elastos-server/src/api/gateway_tests/library.rs @@ -892,7 +892,7 @@ fn zip_text_files(bytes: &[u8]) -> std::collections::BTreeMap { if entry.is_dir() { continue; } - let name = entry.name().to_string(); + let name = entry.name().unwrap().into_owned(); let mut body = String::new(); entry.read_to_string(&mut body).unwrap(); files.insert(name, body); @@ -3870,6 +3870,203 @@ async fn test_library_provider_rejects_unsafe_zip_entries() { .contains("relative and safe")); } +/// Every path under `root` (files, folders and symlinks, not followed). +fn walk_paths(root: &std::path::Path) -> Vec { + let mut out = Vec::new(); + let mut stack = vec![root.to_path_buf()]; + while let Some(dir) = stack.pop() { + for entry in std::fs::read_dir(&dir).unwrap() { + let entry = entry.unwrap(); + let path = entry.path(); + if entry.file_type().unwrap().is_dir() { + stack.push(path.clone()); + } + out.push(path); + } + } + out +} + +#[tokio::test] +async fn test_library_provider_extract_zip_refuses_absolute_dotdot_and_symlink_entries() { + use std::io::Write as _; + + let dir = tempfile::tempdir().unwrap(); + let app = gateway_router(library_test_state(dir.path()).await); + let authority = passkey_authority_with_name(dir.path(), Some("admin")); + let token = app_token_for_authority(dir.path(), LIBRARY_CAPSULE_ID, &authority); + let root = crate::auth::principal_localhost_root(&authority.principal_id); + let documents_uri = format!("{root}/Documents"); + let imports_uri = format!("{documents_uri}/Imports"); + + let (status, _) = post_library( + app.clone(), + &token, + "mkdir", + json!({ "parent_uri": root, "name": "Documents" }), + ) + .await; + assert_eq!(status, StatusCode::OK); + let (status, _) = post_library( + app.clone(), + &token, + "mkdir", + json!({ "parent_uri": documents_uri, "name": "Imports" }), + ) + .await; + assert_eq!(status, StatusCode::OK); + + let options = + zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Stored); + // Each archive holds one hostile entry. The whole-archive extract must + // refuse it and write nothing for it, inside or outside the Library. + // (archive name, entry kind, entry name, symlink target, expected message) + let cases: [(&str, &str, &str, &str, &str); 5] = [ + ( + "Absolute.zip", + "file", + "/absolute-escape.txt", + "", + "relative and safe", + ), + ( + "DotDot.zip", + "file", + "../dotdot-escape.txt", + "", + "relative and safe", + ), + ( + "Inner.zip", + "file", + "Nested/../inner-escape.txt", + "", + "relative and safe", + ), + ( + "Backslash.zip", + "file", + "..\\backslash-escape.txt", + "", + "invalid library object name", + ), + ( + "Symlink.zip", + "symlink", + "symlink-escape.txt", + "/etc/passwd", + "non-file", + ), + ]; + for (archive_name, kind, entry_name, link_target, expected) in cases { + let archive_bytes = { + let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + if kind == "symlink" { + writer + .add_symlink(entry_name, link_target, options) + .unwrap(); + } else { + writer.start_file(entry_name, options).unwrap(); + writer.write_all(b"escape").unwrap(); + } + writer.finish().unwrap().into_inner() + }; + let zip_uri = format!("{documents_uri}/{archive_name}"); + let (write_status, write) = post_library( + app.clone(), + &token, + "write", + json!({ + "uri": zip_uri, + "mime": "application/zip", + "data": base64::engine::general_purpose::STANDARD.encode(archive_bytes), + }), + ) + .await; + assert_eq!(write_status, StatusCode::OK, "{archive_name}"); + assert_eq!(write["status"], "ok", "{archive_name}: {write}"); + + let (extract_status, extracted) = post_library( + app.clone(), + &token, + "extract_archive", + json!({ "uri": zip_uri }), + ) + .await; + assert_eq!(extract_status, StatusCode::OK, "{archive_name}"); + assert_eq!( + extracted["status"], "error", + "{archive_name}: hostile entry {entry_name:?} was not refused: {extracted}" + ); + assert!( + extracted["message"].as_str().unwrap().contains(expected), + "{archive_name}: {extracted}" + ); + + if kind == "symlink" { + // The listing marks it blocked and a selected extract refuses it. + let (list_status, listed) = post_library( + app.clone(), + &token, + "archive_entries", + json!({ "uri": zip_uri }), + ) + .await; + assert_eq!(list_status, StatusCode::OK); + let rows = listed["data"]["entries"].as_array().unwrap(); + assert!( + rows.iter().any(|entry| entry["path"] == entry_name + && entry["kind"] == "blocked" + && entry["safety"]["reason"] + .as_str() + .unwrap() + .contains("non-file")), + "{listed}" + ); + let (select_status, selected) = post_library( + app.clone(), + &token, + "archive_extract_entries", + json!({ + "uri": zip_uri, + "destination_uri": imports_uri, + "entries": [entry_name], + }), + ) + .await; + assert_eq!(select_status, StatusCode::OK); + assert_eq!(selected["status"], "ok", "{selected}"); + assert_eq!( + selected["data"]["receipt"]["progress"]["blocked_entries"], + 1 + ); + assert!(selected["data"]["blocked"][0]["reason"] + .as_str() + .unwrap() + .contains("non-file")); + } + } + + // Nothing from any hostile entry exists anywhere under the data dir, and + // no symlink was created. + for path in walk_paths(dir.path()) { + let name = path.file_name().unwrap().to_string_lossy().to_string(); + assert!( + !name.contains("escape"), + "hostile entry was written: {}", + path.display() + ); + assert!( + !std::fs::symlink_metadata(&path) + .unwrap() + .file_type() + .is_symlink(), + "symlink was created: {}", + path.display() + ); + } +} + #[tokio::test] async fn test_library_gateway_reads_webspace_files_through_runtime_provider() { let dir = tempfile::tempdir().unwrap(); diff --git a/elastos/crates/elastos-server/src/library.rs b/elastos/crates/elastos-server/src/library.rs index 9e537d229..84c791d0a 100644 --- a/elastos/crates/elastos-server/src/library.rs +++ b/elastos/crates/elastos-server/src/library.rs @@ -4239,7 +4239,10 @@ fn preview_zip_archive_entry( let mut file = archive .by_index(index) .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))?; - let raw_name = file.name().to_string(); + let raw_name = file + .name() + .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))? + .into_owned(); let Ok(normalized) = normalized_archive_entry_path(Path::new(&raw_name)) else { continue; }; @@ -4457,7 +4460,10 @@ fn list_zip_archive_entries(bytes: Vec) -> anyhow::Result<(Vec, bool) let file = archive .by_index(index) .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))?; - let raw_name = file.name().to_string(); + let raw_name = file + .name() + .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))? + .into_owned(); let path = Path::new(&raw_name); let normalized = match normalized_archive_entry_path(path) { Ok(path) => path, @@ -4939,7 +4945,10 @@ fn collect_selected_zip_writes( let mut file = archive .by_index(index) .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))?; - let raw_name = file.name().to_string(); + let raw_name = file + .name() + .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))? + .into_owned(); let normalized = match normalized_archive_entry_path(Path::new(&raw_name)) { Ok(path) => path, Err(err) => { @@ -5429,8 +5438,10 @@ fn extract_zip_archive( let mut file = archive .by_index(index) .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))?; - let entry_path = file - .enclosed_name() + let raw_name = file + .name() + .map_err(|err| anyhow!("invalid ZIP archive entry: {err}"))?; + let entry_path = zip_entry_enclosed_path(&raw_name) .ok_or_else(|| anyhow!("library archive entry path must be relative and safe"))?; let entry_uri = archive_entry_uri(&destination.uri, &entry_path)?; if entry_uri == destination.uri { @@ -5461,6 +5472,29 @@ fn extract_zip_archive( Ok(()) } +/// The path a whole-archive ZIP extract writes for an entry name, or `None` +/// when the name holds a NUL byte, is absolute (a root or a drive prefix), or +/// climbs above the archive root. `archive_entry_uri` then refuses any `..` +/// that is left. This keeps the rule in the runtime: zip 9 `enclosed_name` +/// strips a leading `/` or drive prefix and folds `..` instead, which would +/// write entries that this extract refuses. +fn zip_entry_enclosed_path(name: &str) -> Option { + if name.contains('\0') { + return None; + } + let path = PathBuf::from(name); + let mut depth = 0usize; + for component in path.components() { + match component { + Component::Prefix(_) | Component::RootDir => return None, + Component::ParentDir => depth = depth.checked_sub(1)?, + Component::Normal(_) => depth += 1, + Component::CurDir => {} + } + } + Some(path) +} + fn archive_entry_uri(destination_uri: &str, path: &Path) -> anyhow::Result { let mut uri = destination_uri.trim_end_matches('/').to_string(); for component in path.components() { From ce5d187b25e1803cb656954dc549eaa90b63cb24 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 09:17:03 +0000 Subject: [PATCH 11/18] fix: listen on every localhost address and move IP Home pages to localhost Passkeys work only at localhost, and a browser reaches localhost on 127.0.0.1 and on ::1. --addr localhost: now binds each address the computer resolves for localhost plus 127.0.0.1 and ::1, on one port, and serves the same router on each. Another program on any of them, or any other bind error, stops the start with a message that names the address. Only an address family the computer lacks (EADDRNOTAVAIL, EAFNOSUPPORT) is left out, and at least one address must bind. A localhost that points off this computer is refused. An IP-literal --addr binds exactly as before, and the host lock still records --addr as given. When the gateway listens on localhost, a GET or HEAD for /, /home, /home/, /apps/home or /apps/home/ with a loopback IP Host gets 308 to the same path at http://localhost:. Health, API, asset and app routes answer on every address. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W6Qn9RX7LDqrwiAfNC2F2K --- .../elastos-server/src/api/gateway_server.rs | 594 +++++++++++++++++- 1 file changed, 586 insertions(+), 8 deletions(-) diff --git a/elastos/crates/elastos-server/src/api/gateway_server.rs b/elastos/crates/elastos-server/src/api/gateway_server.rs index 441f8882c..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; @@ -94,10 +99,20 @@ async fn start_gateway_server_with_shutdown( ) -> anyhow::Result<()> { crate::auth::verify_auth_audit_chain_ready(&data_dir)?; let _health_lock = crate::host_lock::publish_gateway_lock_if_unowned(&data_dir, addr)?; - let listener = TcpListener::bind(addr).await?; + 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)? }; @@ -117,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 { @@ -149,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); @@ -167,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, @@ -215,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::() @@ -354,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)] @@ -841,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(); + } } From 9c9766b324a1a7da3384cfc3cf5072a4e437ffdc Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 09:17:03 +0000 Subject: [PATCH 12/18] docs: make the launcher contract the one source for the Home address The contract now states the localhost listeners, the redirect from a loopback IP Home page, that localhost is the one Home origin, and that the lock records --addr as given. It drops the single-family gap and names the untested Windows-to-WSL2 localhost forwarding. HOME_LOCAL_SETUP, INSTALL, MAC and WINDOWS cite it; 61180 is labelled the developer lane. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W6Qn9RX7LDqrwiAfNC2F2K --- docs/HOME_LOCAL_SETUP.md | 10 ++++++---- docs/INSTALL.md | 4 +++- docs/LAUNCHER_CONTRACT.md | 36 +++++++++++++++++++++++++++--------- docs/MAC.md | 2 ++ docs/WINDOWS.md | 3 ++- 5 files changed, 40 insertions(+), 15 deletions(-) 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 index 4539c1b5c..b5a71a29b 100644 --- a/docs/LAUNCHER_CONTRACT.md +++ b/docs/LAUNCHER_CONTRACT.md @@ -12,14 +12,22 @@ 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 gateway listens on one socket. For a host name, it binds the first address -that the name resolves to and that it can bind. `localhost` can resolve to -`127.0.0.1` or to `::1` first, so `localhost:8090` listens on one address -family only. A client that connects to the other family gets no answer from -this gateway. Listening on every address of `localhost` is a gap in this -contract. +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`. @@ -50,6 +58,15 @@ The Home origin is: 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 @@ -68,7 +85,8 @@ the same host on any port, and refuses it at every other host. | macOS data directory | `~/Library/Application Support/elastos` | | Host lock | `{data}/host-process.lock` | -The lock record stores `pid`, `role`, and `addr`. A second live host for the +The lock record stores `pid`, `role`, and `addr`. `addr` is the `--addr` +value as given, for example `localhost:8090`. A second live host for the same data directory exits 1. Its error contains `another ElastOS host already owns`. ## Stop 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/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. From f1fcb219cefbd13417acc31589a590c8789130f2 Mon Sep 17 00:00:00 2001 From: Anders Alm Date: Sat, 17 Oct 2026 09:51:55 +0000 Subject: [PATCH 13/18] model-provider: held-lock journal test takes its lock with the bounded retry (#381) Port of develop commit 50515055 (Anders Alm). The test flaked in CI with "WouldBlock" at journal.rs:4223 on PR heads that predate the fix. (cherry picked from commit 505150556cf3ed34357c55fecdb3c3533d8d47c3) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W6Qn9RX7LDqrwiAfNC2F2K --- capsules/model-provider/src/journal.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/capsules/model-provider/src/journal.rs b/capsules/model-provider/src/journal.rs index b711b092d..d3c6878f2 100644 --- a/capsules/model-provider/src/journal.rs +++ b/capsules/model-provider/src/journal.rs @@ -4220,7 +4220,10 @@ mod tests { } let temp_before = file_bytes(&temp); let writer = open_journal_directory(&directory).unwrap(); - writer.try_lock().unwrap(); + // A child forked on another test thread can briefly hold a copy of an + // earlier lock fd on this directory (#381); take the lock with the + // provider's own bounded retry instead of one try. + lock_journal_directory(&writer).unwrap(); assert_eq!( RunJournal::open(root.clone()).err().unwrap().code(), "selection_unavailable" From 3672007089e9d49225fe6dfe22811a9c092558e2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 12:56:21 +0000 Subject: [PATCH 14/18] fix: prove gateway lock ownership from the held flock, not the lock record Any process that runs as the same user can rewrite the JSON record in host-process.lock. /healthz returned OK when that record named this pid with role gateway, and a gateway skipped taking the lock when the record named its pid. A forged or stale record could therefore make a process that holds no lock answer OK, or start a gateway with no host lock. This process now remembers each host lock it holds (role, device and inode of the locked file). /healthz and publish_gateway_lock_if_unowned answer from that state: the path must name the same file now, and a new open of it cannot take the lock. The record is not read. A removed or replaced lock file, a lock another process holds, and a released lock return 503. The launcher contract states what proves ownership. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W6Qn9RX7LDqrwiAfNC2F2K --- docs/LAUNCHER_CONTRACT.md | 26 ++- .../elastos-server/src/api/gateway_site.rs | 22 +-- .../src/api/gateway_tests/content_sandbox.rs | 2 +- .../src/api/gateway_tests/frontdoor.rs | 4 +- .../src/api/gateway_tests/mod.rs | 9 +- .../src/api/gateway_tests/site_publication.rs | 143 ++++++++++---- .../crates/elastos-server/src/host_lock.rs | 174 ++++++++++++++++-- 7 files changed, 295 insertions(+), 85 deletions(-) diff --git a/docs/LAUNCHER_CONTRACT.md b/docs/LAUNCHER_CONTRACT.md index b5a71a29b..61c4800a3 100644 --- a/docs/LAUNCHER_CONTRACT.md +++ b/docs/LAUNCHER_CONTRACT.md @@ -34,23 +34,34 @@ A Home supervisor uses `gateway` and `/healthz`. ## Readiness and Home URL -When this gateway process is the recorded owner of `{data}/host-process.lock`, -with role `gateway` or `gateway-public` and `pid` equal to its process id: +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`. A different pid, another role, a -missing lock, or a lock that is not JSON returns HTTP 503. A gateway that -`elastos serve` starts keeps the `serve` record, so its `/healthz` returns 503. +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 ownership: 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 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`. 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`. A reply that names the lock owner is a gap in this contract. +role `gateway`. That record is a hint, not proof, for the reason above. A reply +that names the lock owner is a gap in this contract. The Home origin is: @@ -86,7 +97,8 @@ the same host on any port, and refuses it at every other host. | 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`. A second live host for the +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`. ## Stop diff --git a/elastos/crates/elastos-server/src/api/gateway_site.rs b/elastos/crates/elastos-server/src/api/gateway_site.rs index d48f4db33..dcfeb0966 100644 --- a/elastos/crates/elastos-server/src/api/gateway_site.rs +++ b/elastos/crates/elastos-server/src/api/gateway_site.rs @@ -429,30 +429,18 @@ pub(super) fn request_host(headers: &HeaderMap) -> anyhow::Result Ok(Some(validated_gateway_host(headers)?)) } -/// Readiness for the process that holds `host-process.lock`. -/// The body is the two bytes `OK` only when this process is the recorded gateway. +/// 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. pub(super) async fn healthz(State(state): State) -> Response { - if gateway_health_lock_matches(&state.data_dir) { + if crate::host_lock::holds_gateway_host_lock(&state.data_dir) { (StatusCode::OK, "OK").into_response() } else { StatusCode::SERVICE_UNAVAILABLE.into_response() } } -fn gateway_health_lock_matches(data_dir: &std::path::Path) -> bool { - let Ok(bytes) = std::fs::read(data_dir.join("host-process.lock")) else { - return false; - }; - let Ok(meta) = serde_json::from_slice::(&bytes) else { - return false; - }; - meta.get("pid").and_then(|value| value.as_u64()) == Some(u64::from(std::process::id())) - && matches!( - meta.get("role").and_then(|value| value.as_str()), - Some("gateway" | "gateway-public") - ) -} - pub(super) async fn serve_release_manifest( State(state): State, Extension(gate): Extension, 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 52aea3c8a..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,7 +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'"); - super::write_gateway_health_lock(dir.path(), std::process::id()); + 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 2e814875a..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,7 +45,7 @@ async fn frontdoor_refuses_foreign_origins_rebinding_and_missing_or_duplicate_ho app.clone().oneshot(duplicate).await.unwrap().status(), StatusCode::FORBIDDEN ); - super::write_gateway_health_lock(dir.path(), std::process::id()); + let _gateway_lock = super::hold_gateway_health_lock(dir.path()); let valid = Request::builder() .uri("/healthz") .header(HOST, "127.0.0.1:61180") @@ -155,7 +155,7 @@ async fn frontdoor_public_list_requires_configured_gateway_host() { "gateway_allowed_hosts = [\"home.example.test\"]\n", ) .unwrap(); - super::write_gateway_health_lock(dir.path(), std::process::id()); + 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/mod.rs b/elastos/crates/elastos-server/src/api/gateway_tests/mod.rs index bf29f9cd2..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,12 +86,9 @@ fn test_launch_token_from_route(route: &str) -> String { .expect("launch route home token") } -pub(super) fn write_gateway_health_lock(data_dir: &std::path::Path, pid: u32) { - std::fs::write( - data_dir.join("host-process.lock"), - format!("{{\"pid\":{pid},\"role\":\"gateway\",\"addr\":\"localhost:8090\"}}\n"), - ) - .unwrap(); +/// 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 { 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 d6379551b..fdcf566a6 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 @@ -225,7 +225,7 @@ async fn test_root_serves_mywebsite_when_staged() { #[tokio::test] async fn test_healthz_200() { let dir = tempfile::tempdir().unwrap(); - super::write_gateway_health_lock(dir.path(), std::process::id()); + let _gateway_lock = super::hold_gateway_health_lock(dir.path()); let state = test_state(dir.path()); let app = gateway_router(state); @@ -247,12 +247,8 @@ async fn test_healthz_200() { assert_eq!(body.len(), 2); } -#[tokio::test] -async fn test_healthz_refuses_another_pid_and_a_tampered_lock() { - let dir = tempfile::tempdir().unwrap(); - super::write_gateway_health_lock(dir.path(), std::process::id().wrapping_add(1)); - let app = gateway_router(test_state(dir.path())); - let response = app +async fn healthz_status(data_dir: &std::path::Path) -> StatusCode { + gateway_router(test_state(data_dir)) .oneshot( Request::builder() .uri("/healthz") @@ -260,46 +256,112 @@ async fn test_healthz_refuses_another_pid_and_a_tampered_lock() { .unwrap(), ) .await - .unwrap(); - assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE); + .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(); - for lock in [ - Some(b"not-json".to_vec()), - None, - Some( - format!("{{\"pid\":{pid},\"role\":\"serve\",\"addr\":\"localhost:8090\"}}") - .into_bytes(), + 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"), ), - Some( - format!("{{\"pid\":\"{pid}\",\"role\":\"gateway\",\"addr\":\"localhost:8090\"}}") - .into_bytes(), + ("another role", record(&pid.to_string(), "serve")), + ( + "a pid that is a string", + record(&format!("\"{pid}\""), "gateway"), ), + ("not JSON", "not-json".to_string()), ] { - let path = dir.path().join("host-process.lock"); - match &lock { - Some(bytes) => std::fs::write(&path, bytes).unwrap(), - None => { - let _ = std::fs::remove_file(&path); - } - } - let app = gateway_router(test_state(dir.path())); - let response = app - .oneshot( - Request::builder() - .uri("/healthz") - .body(Body::empty()) - .unwrap(), - ) - .await - .unwrap(); + std::fs::write(&path, bytes).unwrap(); assert_eq!( - response.status(), + healthz_status(dir.path()).await, StatusCode::SERVICE_UNAVAILABLE, - "{:?}", - lock.map(String::from_utf8) + "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" @@ -314,6 +376,9 @@ async fn test_healthz_refuses_another_pid_and_a_tampered_lock() { 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 ownership:")); + assert!(!contract.contains("recorded owner")); } #[tokio::test] @@ -755,7 +820,7 @@ async fn test_concurrent_release_reads_wait_health_works_and_scan_once() { .is_err() ); assert!(requests.iter().all(|request| !request.is_finished())); - super::write_gateway_health_lock(&fixture.base, std::process::id()); + let _gateway_lock = super::hold_gateway_health_lock(&fixture.base); let response = app .clone() .oneshot( diff --git a/elastos/crates/elastos-server/src/host_lock.rs b/elastos/crates/elastos-server/src/host_lock.rs index 5bfd5d053..47764fb48 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,110 @@ 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 proves ownership. The JSON record +/// in the lock file is not proof: any process of the same user can rewrite it. +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, + file: LockedFileId, + 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<()> { + let Some(file) = locked_file_id(&lock.metadata()?) else { + return Ok(()); + }; + 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); + } +} + +/// The role under which this process holds the host lock of `data_dir`. +/// +/// The proof is the flock itself: this process holds an exclusive lock on an +/// open file, `{data}/host-process.lock` names that same file now, and a new +/// open of it cannot take the lock. The JSON record is not read. +pub fn held_host_role(data_dir: &Path) -> Option { + let probe = fs::File::open(host_lock_path(data_dir)).ok()?; + let file = locked_file_id(&probe.metadata().ok()?)?; + let role = held_host_locks() + .iter() + .find(|held| held.file == file) + .map(|held| held.role.clone())?; + match probe.try_lock() { + Err(fs::TryLockError::WouldBlock) => Some(role), + Ok(()) => { + // The lock was free, so this process does not hold it. + let _ = probe.unlock(); + None + } + Err(fs::TryLockError::Error(_)) => None, + } +} + +/// Whether this process holds the host lock of `data_dir` as a gateway. +pub fn holds_gateway_host_lock(data_dir: &Path) -> bool { + matches!( + held_host_role(data_dir).as_deref(), + Some("gateway" | "gateway-public") + ) +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct HostProcessInfo { pub pid: u32, @@ -78,16 +179,16 @@ struct HostProcessMeta { generation: String, } -/// The gateway server publishes its pid when no host in this process holds the lock. -/// `gateway` and `gateway-public` write that record before the server starts. -/// `serve` also holds it when its supervisor starts a gateway in the same process. -/// That gateway keeps the `serve` record, so its `/healthz` answers 503. +/// 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> { - let path = host_lock_path(data_dir); - if read_lock_metadata(&path).is_some_and(|meta| meta.pid == std::process::id()) { + if held_host_role(data_dir).is_some() { return Ok(None); } acquire_host_process_lock(data_dir, "gateway", addr).map(Some) @@ -127,7 +228,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); @@ -157,6 +258,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) } @@ -563,6 +665,52 @@ 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); + } + #[test] fn model_host_lock_is_data_root_scoped() { let temp = tempfile::tempdir().expect("tempdir"); From 85f3142e747916f4f706963959284b34fb089a29 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 15:30:22 +0000 Subject: [PATCH 15/18] fix: prove host lock ownership in one step against the holder's own lock held_host_role looked up the registry, released its mutex, and then probed the lock with a new open of the file. A release and a retake by another holder could come between the two, and the probe then saw the other holder's lock and answered with this process's role. A registry entry also stood for any lock on the same file, so a guard whose open file was unlocked behind its back still counted when another holder took the lock. Each registry entry now keeps a second descriptor of the open file that holds the flock. The proof keeps the registry mutex from the lookup to the end of the probe, and a guard removes its entry under that mutex before it unlocks. The probe checks that the path names the same file, that a new open cannot take the lock, and that the entry's own open file can take it again (which is a no-op only for the current holder). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W6Qn9RX7LDqrwiAfNC2F2K --- .../crates/elastos-server/src/host_lock.rs | 217 ++++++++++++++++-- 1 file changed, 195 insertions(+), 22 deletions(-) diff --git a/elastos/crates/elastos-server/src/host_lock.rs b/elastos/crates/elastos-server/src/host_lock.rs index 47764fb48..620d1a519 100644 --- a/elastos/crates/elastos-server/src/host_lock.rs +++ b/elastos/crates/elastos-server/src/host_lock.rs @@ -79,13 +79,19 @@ impl Drop for FileLock { /// Host locks that this process holds now. `docs/LAUNCHER_CONTRACT.md` /// ("Readiness and Home URL") states what proves ownership. The JSON record /// in the lock file is not proof: any process of the same user can rewrite it. +/// +/// 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, - file: LockedFileId, + /// The same open file description as the guard's file (a `dup`). + file: fs::File, role: String, } @@ -113,9 +119,10 @@ fn held_host_locks() -> std::sync::MutexGuard<'static, Vec> { } fn remember_held_host_lock(lock: &mut FileLock, role: &str) -> std::io::Result<()> { - let Some(file) = locked_file_id(&lock.metadata()?) else { + 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, @@ -132,35 +139,85 @@ fn forget_held_host_lock(id: Option) { } } -/// The role under which this process holds the host lock of `data_dir`. +/// Whether the open file description of `held` holds the exclusive flock on +/// the file that `lock_path` names now. /// -/// The proof is the flock itself: this process holds an exclusive lock on an -/// open file, `{data}/host-process.lock` names that same file now, and a new -/// open of it cannot take the lock. The JSON record is not read. -pub fn held_host_role(data_dir: &Path) -> Option { - let probe = fs::File::open(host_lock_path(data_dir)).ok()?; - let file = locked_file_id(&probe.metadata().ok()?)?; - let role = held_host_locks() - .iter() - .find(|held| held.file == file) - .map(|held| held.role.clone())?; +/// 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) => Some(role), + Err(fs::TryLockError::WouldBlock) => {} Ok(()) => { - // The lock was free, so this process does not hold it. + // The lock was free, so no description holds it. let _ = probe.unlock(); - None + return false; } - Err(fs::TryLockError::Error(_)) => None, + 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 { - matches!( - held_host_role(data_dir).as_deref(), - Some("gateway" | "gateway-public") - ) + held_host_role(data_dir).is_some_and(|role| is_gateway_role(&role)) } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -711,6 +768,122 @@ mod tests { 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"); + 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())); + 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(); + } + #[test] fn model_host_lock_is_data_root_scoped() { let temp = tempfile::tempdir().expect("tempdir"); From eed83a72ded2264accfa534d54ee3de1b8a8621c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 15:33:30 +0000 Subject: [PATCH 16/18] fix: open the subordinate runtime lane only on the held gateway lock A managed runtime ran as the subordinate of a gateway when the JSON record in host-process.lock named this pid as a gateway, or, for a Home terminal, named its parent pid as a gateway. Any process of the same user can write that record, so a forged or stale record opened the lane while another host held the lock. The lane now uses the same proof as /healthz. In the gateway process, holds_gateway_host_lock checks the flock it holds. A Home terminal gets a descriptor of the gateway's locked open file and the gateway pid when the gateway starts it; it must be that gateway's direct child, and that descriptor must hold the flock now (the path names the same file, a new open cannot take the lock, and the inherited open file can). After the gateway releases the lock, or another holder retakes it, the lane is refused. The record only names the holder in the refusal. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W6Qn9RX7LDqrwiAfNC2F2K --- .../src/api/gateway_home_terminal.rs | 32 +- .../crates/elastos-server/src/host_lock.rs | 119 ++++++++ .../elastos-server/src/runtime_control.rs | 276 ++++++++++++------ 3 files changed, 344 insertions(+), 83 deletions(-) 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/host_lock.rs b/elastos/crates/elastos-server/src/host_lock.rs index 620d1a519..729a06120 100644 --- a/elastos/crates/elastos-server/src/host_lock.rs +++ b/elastos/crates/elastos-server/src/host_lock.rs @@ -220,6 +220,44 @@ 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`. +/// +/// 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, @@ -794,6 +832,7 @@ mod tests { 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") @@ -819,6 +858,7 @@ mod tests { 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); } @@ -884,6 +924,85 @@ mod tests { 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"); diff --git a/elastos/crates/elastos-server/src/runtime_control.rs b/elastos/crates/elastos-server/src/runtime_control.rs index 2d3341314..bf574f289 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,69 @@ 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. +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 +1276,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 +2036,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 +2114,144 @@ mod tests { pin_parent_model_catalog_head(data_dir, &crate::setup::catalog_head_cid(catalog).unwrap()); } - #[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 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(); + } - assert!(gateway_owner_allows_subordinate_managed_runtime(&owner)); + /// 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 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(), - }; - - assert!(!gateway_owner_allows_subordinate_managed_runtime(&owner)); + 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); + + // 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] - 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(), + #[cfg(unix)] + 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)); - } - - struct EnvRestore { - key: &'static str, - value: Option, - } - - 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, - } - } - - fn remove(key: &'static str) -> Self { - let previous = std::env::var_os(key); - std::env::remove_var(key); - Self { - key, - value: previous, - } - } - } + // 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) + )); - 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), - } - } + // 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); } } From 4bb19dcf1f17f79c552f3827dd8c0272178070cd Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 17 Oct 2026 15:49:57 +0000 Subject: [PATCH 17/18] fix: report a host lock holder whose record cannot be read active_host_process reported no active host when the lock was held but its JSON record was empty, being written, or not JSON. The update controller, principal-root upgrade and the managed runtime lane then treated a running host as stopped. The flock now decides whether a host is active; such a holder is reported with role "unknown". Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W6Qn9RX7LDqrwiAfNC2F2K --- .../crates/elastos-server/src/host_lock.rs | 42 +++++++++++++++++-- .../elastos-server/src/runtime_control.rs | 10 +++++ 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/elastos/crates/elastos-server/src/host_lock.rs b/elastos/crates/elastos-server/src/host_lock.rs index 729a06120..ec43b1cf4 100644 --- a/elastos/crates/elastos-server/src/host_lock.rs +++ b/elastos/crates/elastos-server/src/host_lock.rs @@ -379,9 +379,13 @@ pub fn active_host_process(data_dir: &Path) -> anyhow::Result { - Ok(read_lock_metadata(&lock_path).map(Into::into)) - } + // The flock decides that a host is active. The record only describes + // it, 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())), } } @@ -394,6 +398,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 { @@ -1060,6 +1076,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/runtime_control.rs b/elastos/crates/elastos-server/src/runtime_control.rs index bf574f289..dab1c1ea7 100644 --- a/elastos/crates/elastos-server/src/runtime_control.rs +++ b/elastos/crates/elastos-server/src/runtime_control.rs @@ -2169,6 +2169,16 @@ mod tests { 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); + // 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(); From 13cdcad0419669b382c3f6e17cb571a0c098cdab Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 18 Oct 2026 02:33:18 +0000 Subject: [PATCH 18/18] docs: state that the host lock proves possession, not that the holder is the gateway Holding the flock on host-process.lock proves that a process has the lock. It does not prove that the holder is a gateway or ElastOS: any process of the same user can open the file and hold it. The launcher contract now says so for /healthz, for the Home terminal's inherited lock descriptor (ELASTOS_GATEWAY_HOST_LOCK_FD), and for the "another ElastOS host already owns" error, which names the holder from a record that can be false. Code comments in host_lock.rs, gateway_site.rs and runtime_control.rs say the same. Two tests pin the statement with real processes. In one, /bin/sleep opens the lock file and takes the flock: the gateway does not start by either path, this process's /healthz answers 503 and it gives no lock descriptor to a child. In the other, this test process takes the flock with a plain open (not as a host) and gives the descriptor and the gateway variables to a real child process; the child's Home terminal check accepts it while the lock is held, and refuses a descriptor that does not hold the lock and the same descriptor after the release. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01W6Qn9RX7LDqrwiAfNC2F2K --- docs/LAUNCHER_CONTRACT.md | 43 +++++-- .../elastos-server/src/api/gateway_site.rs | 3 +- .../src/api/gateway_tests/site_publication.rs | 91 +++++++++++++- .../crates/elastos-server/src/host_lock.rs | 65 +++++++++- .../elastos-server/src/runtime_control.rs | 115 +++++++++++++++++- 5 files changed, 300 insertions(+), 17 deletions(-) diff --git a/docs/LAUNCHER_CONTRACT.md b/docs/LAUNCHER_CONTRACT.md index 61c4800a3..95b917717 100644 --- a/docs/LAUNCHER_CONTRACT.md +++ b/docs/LAUNCHER_CONTRACT.md @@ -47,21 +47,41 @@ 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 ownership: 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. +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`. The reply does not name the process. +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 reason above. A reply -that names the lock owner is a gap in this contract. +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: @@ -100,6 +120,9 @@ 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 diff --git a/elastos/crates/elastos-server/src/api/gateway_site.rs b/elastos/crates/elastos-server/src/api/gateway_site.rs index dcfeb0966..4fd98fe2d 100644 --- a/elastos/crates/elastos-server/src/api/gateway_site.rs +++ b/elastos/crates/elastos-server/src/api/gateway_site.rs @@ -432,7 +432,8 @@ pub(super) fn request_host(headers: &HeaderMap) -> anyhow::Result /// 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. +/// 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() 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 fdcf566a6..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 @@ -377,10 +377,99 @@ async fn test_healthz_refuses_a_forged_or_foreign_lock_owner() { 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 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] async fn test_invalid_cid_400() { let dir = tempfile::tempdir().unwrap(); diff --git a/elastos/crates/elastos-server/src/host_lock.rs b/elastos/crates/elastos-server/src/host_lock.rs index ec43b1cf4..0fd3a1c36 100644 --- a/elastos/crates/elastos-server/src/host_lock.rs +++ b/elastos/crates/elastos-server/src/host_lock.rs @@ -77,8 +77,10 @@ impl Drop for FileLock { } /// Host locks that this process holds now. `docs/LAUNCHER_CONTRACT.md` -/// ("Readiness and Home URL") states what proves ownership. The JSON record +/// ("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 @@ -236,7 +238,9 @@ pub fn gateway_host_lock_for_child(data_dir: &Path) -> Option { /// `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`. +/// 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 @@ -379,8 +383,10 @@ pub fn active_host_process(data_dir: &Path) -> anyhow::Result Ok(Some( read_lock_metadata(&lock_path) .map(Into::into) @@ -692,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() diff --git a/elastos/crates/elastos-server/src/runtime_control.rs b/elastos/crates/elastos-server/src/runtime_control.rs index dab1c1ea7..a657eff55 100644 --- a/elastos/crates/elastos-server/src/runtime_control.rs +++ b/elastos/crates/elastos-server/src/runtime_control.rs @@ -392,7 +392,9 @@ fn parent_gateway_holds_host_lock(data_dir: &Path) -> bool { /// 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. +/// 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>, @@ -2264,4 +2266,115 @@ mod tests { 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] + #[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" + }; + + // 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()); + + // 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" + ); + + // 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" + ); + + // 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)); + + 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.") + ); + } }