diff --git a/Cargo.lock b/Cargo.lock index b447e46..c83b99f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1240,7 +1240,7 @@ checksum = "db13adb97ab515a3691f56e4dbab09283d0b86cb45abd991d8634a9d6f501760" [[package]] name = "lexmount-browser" -version = "1.3.0" +version = "1.4.0" dependencies = [ "base64 0.22.1", "clap", diff --git a/Cargo.toml b/Cargo.toml index d748389..bc7e7b1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "lexmount-browser" -version = "1.3.0" +version = "1.4.0" edition = "2024" license = "MIT" description = "Native Rust SDK and CLI for Lexmount cloud browsers" diff --git a/README.md b/README.md index b6dc22e..386b5fa 100644 --- a/README.md +++ b/README.md @@ -150,8 +150,8 @@ automatic action retries. These changes require a new CLI release; published Explicit page selection is introduced in version 1.2.0. Check that the installed binary's `browser-cli action --help` lists `--target-id`; the published 1.1.15 binary does not have it. The package version and both bootstrap scripts target -1.3.0 together. Merging or building this source does not publish release assets: -bootstrap can install 1.3.0 only after its binaries and checksums are published +1.4.0 together. Merging or building this source does not publish release assets: +bootstrap can install 1.4.0 only after its binaries and checksums are published to COS. Until then, use a source build for local verification. Every `action` command accepts an optional `--target-id`. Obtain the page's CDP @@ -263,7 +263,7 @@ overwrite an existing release with changed binaries. `skills/lexmount-browser/scripts/bootstrap.ps1` and `bootstrap.sh`. 2. Run `.github/scripts/test-release-version.ps1` with Windows PowerShell 5.1 or PowerShell 7, then `.github/scripts/verify-release-version.ps1 -ReleaseTag - v1.3.0` (substitute the intended version). Complete CI and merge the PR. + v1.4.0` (substitute the intended version). Complete CI and merge the PR. 3. Create the matching tag **on that merged commit**. Typing a new tag or release title in GitHub does not update any source version. The release workflow rejects inconsistent versions before building, signing or uploading. @@ -306,3 +306,20 @@ variables. Linux x86_64 uses the static musl release and the same `scripts/bootstrap.sh` and `scripts/doctor.sh` as macOS. Linux ARM64 is not currently a published target. `browser-cli auth login --no-open` prints the authorization URL on stderr and waits for the callback; stdout remains the final JSON result. The default login attempts to open a browser, but keeps waiting if the desktop opener is missing. On a headless/SSH host, forward the printed callback port from your desktop using `ssh -L PORT:127.0.0.1:PORT HOST`, then open the printed URL on your desktop. Keep the login process running until it completes. Do not post authorization URLs or credentials in chat. + +### Device login for SSH / headless Linux + +`browser-cli auth login --device` prints a console address and short code. Open it +on a phone or another computer, sign in, enter the code and approve the request. +The terminal polls over HTTPS and saves credentials automatically (0600 on Unix). +No inbound port or SSH forwarding is required. The console must have device-login +support deployed before using this mode. + +`auth login` automatically selects device mode over SSH or on Linux without +DISPLAY/WAYLAND_DISPLAY. Use `--browser` to force local loopback login; `--no-open` +retains manual loopback behavior. CI should supply credentials instead of starting +interactive login; explicit `--device` is available when a human is present. +`--project-id` verifies the approved account's project before saving credentials. +An expired, denied or consumed request requires a new login; API keys are never +printed. Ctrl+C stops polling. The console authorization request expires in ten +minutes even if the terminal is closed. diff --git a/skills/lexmount-browser/references/authentication.md b/skills/lexmount-browser/references/authentication.md index 797d7eb..37da266 100644 --- a/skills/lexmount-browser/references/authentication.md +++ b/skills/lexmount-browser/references/authentication.md @@ -28,3 +28,15 @@ Use `browser-cli auth logout` to remove only the local credential file. Environm Linux x86_64 uses the static musl release and the same `scripts/bootstrap.sh` and `scripts/doctor.sh` as macOS. Linux ARM64 is not currently a published target. `browser-cli auth login --no-open` prints the authorization URL on stderr and waits for the callback; stdout remains the final JSON result. The default login attempts to open a browser, but keeps waiting if the desktop opener is missing. On a headless/SSH host, forward the printed callback port from your desktop using `ssh -L PORT:127.0.0.1:PORT HOST`, then open the printed URL on your desktop. Keep the login process running until it completes. Do not post authorization URLs or credentials in chat. + +## Device authorization + +Use `browser-cli auth login --device` on a machine without a desktop browser. +Ask the human to open the displayed console URL on another device and enter the +short code. The CLI waits for explicit approval, then stores the credential. Never +ask them to send their password or API key in chat. This requires the console's +`/api/connect/device/authorize` and `/api/connect/device/token` endpoints. + +SSH and headless Linux choose this automatically; `--browser` forces loopback +login, while `--no-open` preserves manual loopback login. CI should use preconfigured +credentials. Denial or expiry stops login; do not silently retry a denied request. diff --git a/skills/lexmount-browser/scripts/bootstrap.ps1 b/skills/lexmount-browser/scripts/bootstrap.ps1 index a3385e9..5a42335 100644 --- a/skills/lexmount-browser/scripts/bootstrap.ps1 +++ b/skills/lexmount-browser/scripts/bootstrap.ps1 @@ -12,7 +12,7 @@ function Invoke-Tls12Download { } } -$version = if ($env:LEXMOUNT_BROWSER_CLI_VERSION) { $env:LEXMOUNT_BROWSER_CLI_VERSION } else { "1.3.0" } +$version = if ($env:LEXMOUNT_BROWSER_CLI_VERSION) { $env:LEXMOUNT_BROWSER_CLI_VERSION } else { "1.4.0" } $downloadBaseUrl = if ($env:LEXMOUNT_BROWSER_CLI_DOWNLOAD_BASE_URL) { $env:LEXMOUNT_BROWSER_CLI_DOWNLOAD_BASE_URL.TrimEnd('/') } else { "https://cli-bin-1377899528.cos.ap-nanjing.myqcloud.com/releases/browser-cli" } $architecture = if ($env:PROCESSOR_ARCHITEW6432) { $env:PROCESSOR_ARCHITEW6432 } else { $env:PROCESSOR_ARCHITECTURE } if ($architecture -ne "AMD64") { throw "Only Windows x64 is supported" } diff --git a/skills/lexmount-browser/scripts/bootstrap.sh b/skills/lexmount-browser/scripts/bootstrap.sh index ec5e8f4..195e25d 100755 --- a/skills/lexmount-browser/scripts/bootstrap.sh +++ b/skills/lexmount-browser/scripts/bootstrap.sh @@ -1,7 +1,7 @@ #!/bin/sh set -eu -version="${LEXMOUNT_BROWSER_CLI_VERSION:-1.3.0}" +version="${LEXMOUNT_BROWSER_CLI_VERSION:-1.4.0}" download_base_url="${LEXMOUNT_BROWSER_CLI_DOWNLOAD_BASE_URL:-https://cli-bin-1377899528.cos.ap-nanjing.myqcloud.com/releases/browser-cli}" repo="${download_base_url%/}/v${version}" case "$(uname -s)-$(uname -m)" in diff --git a/src/auth.rs b/src/auth.rs index 86d7c07..7f23478 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -118,15 +118,37 @@ pub fn status(path: Option<&Path>) -> Result { pub fn save_credentials(credentials: &Credentials, path: Option<&Path>) -> Result { let path = credentials_path(path)?; - if let Some(parent) = path.parent() { - fs::create_dir_all(parent)?; + let parent = path + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or(Path::new(".")); + fs::create_dir_all(parent)?; + // Never truncate through a symlink or expose a newly written key under the + // process umask before chmod. Rename a private file in the same directory. + if fs::symlink_metadata(&path).is_ok_and(|m| m.file_type().is_symlink()) { + return Err(Error::Config( + "Refusing to save credentials through a symlink".into(), + )); } - fs::write(&path, serde_json::to_vec_pretty(credentials)?)?; + let temporary = parent.join(format!(".browser-cli-{}.tmp", random_urlsafe(16))); + let mut options = fs::OpenOptions::new(); + options.write(true).create_new(true); #[cfg(unix)] { - use std::os::unix::fs::PermissionsExt; - fs::set_permissions(&path, fs::Permissions::from_mode(0o600))?; + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let result = (|| -> std::io::Result<()> { + let mut file = options.open(&temporary)?; + file.write_all(&serde_json::to_vec_pretty(credentials)?)?; + file.sync_all()?; + drop(file); + fs::rename(&temporary, &path) + })(); + if result.is_err() { + let _ = fs::remove_file(&temporary); } + result?; Ok(path) } @@ -355,6 +377,9 @@ fn extract_api_key(payload: &Value) -> Option { .or_else(|| payload.get("api_key")) .and_then(Value::as_str); if let (Some(project_id), Some(api_key)) = (project_id, api_key) { + if project_id.trim().is_empty() || api_key.trim().is_empty() { + continue; + } let scopes = value .get("scopes") .or_else(|| value.get("scope")) @@ -405,8 +430,179 @@ fn is_internal_api_base_url(value: &str) -> bool { host.contains(".svc.") || host.ends_with(".svc") || host.ends_with(".cluster.local") } +/// Device authorization needs only outbound HTTPS; no loopback listener or opener. +pub fn device_login( + project_id: Option<&str>, + client_name: &str, + connect_base_url: &str, + timeout: Duration, + path: Option<&Path>, +) -> Result { + let base = Url::parse(connect_base_url).map_err(|e| Error::Config(e.to_string()))?; + let loopback = matches!(base.host_str(), Some("127.0.0.1" | "localhost" | "[::1]")); + if base.scheme() != "https" && !(base.scheme() == "http" && loopback) { + return Err(Error::Config("device login requires HTTPS".into())); + } + let started = Instant::now(); + let client = reqwest::blocking::Client::builder() + .redirect(reqwest::redirect::Policy::none()) + .timeout(Duration::from_secs(15)) + .build()?; + let response = client + .post(base.join("/api/connect/device/authorize").unwrap()) + .json(&json!({"client_name":client_name})) + .send()?; + if !response.status().is_success() { + return Err(Error::Authentication(format!( + "Device login could not start (HTTP {}). The console must support device authorization.", + response.status() + ))); + } + let payload: Value = response.json()?; + let secret = payload["device_code"] + .as_str() + .filter(|s| !s.is_empty()) + .ok_or_else(|| Error::Authentication("Missing device code".into()))?; + let code = payload["user_code"] + .as_str() + .ok_or_else(|| Error::Authentication("Missing user code".into()))?; + let verify = base + .join( + payload["verification_uri"] + .as_str() + .unwrap_or("/connect/device"), + ) + .map_err(|e| Error::Config(e.to_string()))?; + if verify.origin() != base.origin() { + return Err(Error::Authentication( + "Verification page must use the selected console origin".into(), + )); + } + let lifetime = timeout.min(Duration::from_secs( + payload["expires_in"].as_u64().unwrap_or(600), + )); + let mut interval = payload["interval"].as_u64().unwrap_or(5).max(1); + eprintln!( + "Open on your phone or another computer: {verify}\nEnter code: {code}\nWaiting for approval ({} seconds). Ctrl+C to cancel.", + lifetime.as_secs() + ); + loop { + let remaining = lifetime.saturating_sub(started.elapsed()); + if remaining.is_zero() { + return Err(Error::Timeout( + "Device authorization expired; run auth login again".into(), + )); + } + thread::sleep(Duration::from_secs(interval).min(remaining)); + let remaining = lifetime.saturating_sub(started.elapsed()); + if remaining.is_zero() { + continue; + } + let response = match client + .post(base.join("/api/connect/device/token").unwrap()) + .timeout(remaining.min(Duration::from_secs(15))) + .json(&json!({"device_code":secret})) + .send() + { + Ok(response) => response, + Err(error) if error.is_timeout() || error.is_connect() => { + interval = interval.saturating_mul(2).min(30); + continue; + } + Err(error) => return Err(error.into()), + }; + let status = response.status(); + if status.is_server_error() { + interval = interval.saturating_mul(2).min(30); + continue; + } + let payload: Value = response.json()?; + if !status.is_success() { + match payload["error"].as_str() { + Some("authorization_pending") => continue, + Some("slow_down") => { + interval = interval.saturating_add(5); + continue; + } + Some("access_denied") => { + return Err(Error::Authentication("Device authorization denied".into())); + } + Some("expired_token") => { + return Err(Error::Authentication( + "Device authorization expired; run auth login again".into(), + )); + } + _ => { + return Err(Error::Authentication( + "Device authorization failed; run auth login again".into(), + )); + } + } + } + let mut credential = extract_api_key(&payload) + .ok_or_else(|| Error::Authentication("Invalid device credential response".into()))?; + if project_id.is_some_and(|id| id != credential.project_id) { + return Err(Error::Authentication( + "Authorized project does not match --project-id; credentials were not saved".into(), + )); + } + if is_internal_api_base_url(&credential.api_base_url) + || Url::parse(&credential.api_base_url).map_or(true, |u| { + u.scheme() != "https" + || u.host_str().is_none() + || !u.username().is_empty() + || u.password().is_some() + }) + { + return Err(Error::Authentication("Invalid device API base URL".into())); + } + credential.connect_base_url = Some(connect_base_url.trim_end_matches('/').to_owned()); + let saved = save_credentials(&credential, path)?; + return Ok( + json!({"authenticated":true,"credentials_saved":true,"credentials_file":saved, + "project_id":credential.project_id,"api_base_url":credential.api_base_url,"api_key_redacted":true}), + ); + } +} + +pub fn prefers_device_login() -> bool { + std::env::var_os("SSH_CONNECTION").is_some() + || std::env::var_os("SSH_TTY").is_some() + || (cfg!(target_os = "linux") + && std::env::var_os("DISPLAY").is_none() + && std::env::var_os("WAYLAND_DISPLAY").is_none()) +} + #[cfg(test)] mod tests { + #[test] + #[cfg(unix)] + fn credential_save_rejects_symlink_and_replaces_file_privately() { + use std::os::unix::{fs::PermissionsExt, fs::symlink}; + let dir = tempfile::tempdir().unwrap(); + let target = dir.path().join("target"); + std::fs::write(&target, "original").unwrap(); + let link = dir.path().join("credentials"); + symlink(&target, &link).unwrap(); + let credentials = + super::extract_api_key(&serde_json::json!({"project_id":"p","api_key":"secret"})) + .unwrap(); + assert!(super::save_credentials(&credentials, Some(&link)).is_err()); + assert_eq!(std::fs::read_to_string(&target).unwrap(), "original"); + super::save_credentials(&credentials, Some(&target)).unwrap(); + assert_eq!( + std::fs::metadata(&target).unwrap().permissions().mode() & 0o777, + 0o600 + ); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 2); + } + #[test] + fn empty_credentials_are_rejected() { + assert!( + super::extract_api_key(&serde_json::json!({"project_id":"", "api_key":""})).is_none() + ); + } + use super::*; #[test] diff --git a/src/main.rs b/src/main.rs index c501857..c5c26b1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -82,10 +82,16 @@ enum AuthCommand { client_name: String, #[arg(long, default_value = auth::DEFAULT_CONNECT_BASE_URL)] connect_base_url: String, - #[arg(long, default_value_t = 300)] + #[arg(long, default_value_t = 600)] timeout_seconds: u64, #[arg(long)] no_open: bool, + /// Authorize on another device, without a local browser. + #[arg(long, conflicts_with_all = ["no_open", "browser"])] + device: bool, + /// Force local browser / loopback login even over SSH. + #[arg(long)] + browser: bool, #[arg(long)] credentials_file: Option, }, @@ -424,15 +430,32 @@ fn run_auth(command: AuthCommand) -> Result { connect_base_url, timeout_seconds, no_open, + device, + browser, credentials_file, - } => auth::login_with_client_name( - project_id.as_deref(), - &client_name, - &connect_base_url, - Duration::from_secs(timeout_seconds), - !no_open, - credentials_file.as_deref(), - ), + } => { + if device || (!no_open && !browser && auth::prefers_device_login()) { + if !device && std::env::var_os("CI").is_some() { + return Err(Error::Authentication("Configure credentials for CI, or explicitly request interactive --device login".into())); + } + auth::device_login( + project_id.as_deref(), + &client_name, + &connect_base_url, + Duration::from_secs(timeout_seconds), + credentials_file.as_deref(), + ) + } else { + auth::login_with_client_name( + project_id.as_deref(), + &client_name, + &connect_base_url, + Duration::from_secs(timeout_seconds), + !no_open, + credentials_file.as_deref(), + ) + } + } AuthCommand::Logout { credentials_file } => { Ok(json!({"removed":auth::logout(credentials_file.as_deref())?})) } diff --git a/tests/device_login.rs b/tests/device_login.rs new file mode 100644 index 0000000..c4922f7 --- /dev/null +++ b/tests/device_login.rs @@ -0,0 +1,106 @@ +#[allow(dead_code)] +mod support; +use httpmock::prelude::*; +use serde_json::json; + +fn fixture(error: Option<&str>, auto: bool, mismatch: bool) { + fixture_url(error, auto, mismatch, "https://api.example.test"); +} +fn fixture_url(error: Option<&str>, auto: bool, mismatch: bool, api_url: &str) { + let server = MockServer::start(); + let create = server.mock(|when, then| { + when.method(POST).path("/api/connect/device/authorize"); + then.status(200).json_body(json!({"device_code":"private-device-secret", "user_code":"ABCD-EFGH", "verification_uri":"/connect/device", "expires_in":3,"interval":1})); + }); + let poll = server.mock(|when, then| { + when.method(POST).path("/api/connect/device/token").json_body(json!({"device_code":"private-device-secret"})); + if let Some(error) = error { + then.status(400).json_body(json!({"error":error})); + } else { + then.status(200).json_body(json!({"project_id":"fixture", "api_key":"fixture-api-secret", "api_base_url":api_url})); + } + }); + let dir = tempfile::tempdir().unwrap(); + let credential = dir.path().join("device.json"); + let mut command = support::command( + &server.base_url(), + dir.path(), + &[ + "auth", + "login", + "--connect-base-url", + &server.base_url(), + "--credentials-file", + credential.to_str().unwrap(), + ], + ); + command.env_remove("CI"); + if auto { + command.env("SSH_CONNECTION", "fixture"); + } else { + command.arg("--device"); + } + if mismatch { + command.args(["--project-id", "another-project"]); + } + let output = command.output().unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + assert!(stderr.contains("ABCD-EFGH")); + for secret in ["private-device-secret", "fixture-api-secret"] { + assert!(!stdout.contains(secret)); + assert!(!stderr.contains(secret)); + } + assert_eq!( + output.status.success(), + error.is_none() && !mismatch && api_url.starts_with("https://"), + "{stdout} {stderr}" + ); + assert_eq!( + credential.exists(), + error.is_none() && !mismatch && api_url.starts_with("https://") + ); + #[cfg(unix)] + if credential.exists() { + use std::os::unix::fs::PermissionsExt; + assert_eq!( + std::fs::metadata(credential).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } + create.assert(); + assert!(poll.hits() >= 1); +} +#[test] +fn device_success_saves_private_credentials() { + fixture(None, false, false); +} +#[test] +fn ssh_selects_device_flow() { + fixture(None, true, false); +} +#[test] +fn denial_does_not_save_credentials() { + fixture(Some("access_denied"), false, false); +} +#[test] +fn expiry_does_not_save_credentials() { + fixture(Some("expired_token"), false, false); +} +#[test] +fn pending_stops_at_deadline() { + fixture(Some("authorization_pending"), false, false); +} +#[test] +fn slow_down_stops_at_deadline() { + fixture(Some("slow_down"), false, false); +} +#[test] +fn project_mismatch_does_not_save_credentials() { + fixture(None, false, true); +} + +#[test] +fn plaintext_api_origin_is_rejected() { + fixture_url(None, false, false, "http://api.example.test"); +} diff --git a/tests/linux_bootstrap.py b/tests/linux_bootstrap.py index d5cc1ef..9206149 100755 --- a/tests/linux_bootstrap.py +++ b/tests/linux_bootstrap.py @@ -8,7 +8,7 @@ (fake/'curl').write_text('''#!/bin/sh while [ "$#" -gt 0 ]; do case "$1" in https:*) url="$1";; -o) shift; output="$1";; esac; shift; done case "$url" in - *SHA256SUMS) printf '%s %s\\n' "$(openssl dgst -sha256 "$FIXTURE" | awk '{print $NF}')" 'browser-cli-v1.3.0-x86_64-unknown-linux-musl' > "$output";; + *SHA256SUMS) printf '%s %s\\n' "$(openssl dgst -sha256 "$FIXTURE" | awk '{print $NF}')" 'browser-cli-v1.4.0-x86_64-unknown-linux-musl' > "$output";; *x86_64-unknown-linux-musl) cp "$FIXTURE" "$output";; *) exit 9;; esac diff --git a/tests/login_linux.rs b/tests/login_linux.rs index 173a4a3..1c31335 100644 --- a/tests/login_linux.rs +++ b/tests/login_linux.rs @@ -32,7 +32,8 @@ fn login_fixture(no_open: bool) { if no_open { cmd.arg("--no-open"); } else { - cmd.env("PATH", dir.path()) + cmd.arg("--browser") + .env("PATH", dir.path()) .env_remove("DISPLAY") .env_remove("WAYLAND_DISPLAY") .env_remove("BROWSER");