diff --git a/docs/cli-reference.md b/docs/cli-reference.md index 4af3e7f..cc5472e 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -236,8 +236,10 @@ steel browser start ### Parameters -- `--stealth` (boolean, optional): Enable stealth mode (humanize interactions + auto CAPTCHA) -- `-p, --proxy` (string, optional): Use a residential proxy +- `--stealth` (boolean, optional): Enable stealth mode: humanized interactions, plus automatic CAPTCHA solving when your plan includes it +- `-p, --proxy` (string, optional): Route the session through your own proxy (http://user:pass@host:port) +- `--use-proxy` (boolean, optional): Use a Steel-managed residential proxy +- `--project` (string, optional): Project to create the session in, needed with an organization-wide API key. Defaults to STEEL_PROJECT_ID - `--timeout` (string, optional): Session timeout in milliseconds. Defaults to 900000 (15 minutes), which every plan allows (create-time only) - `--inactivity-timeout` (string, optional): Inactivity timeout in milliseconds: release the session when no command, CDP message, or remote input arrives for this long. Defaults to 600000 (10 minutes); pass 0 to disable (create-time only) - `--solve-captcha` (boolean, optional): Enable manual CAPTCHA solving on new sessions (create-time only) @@ -1283,6 +1285,7 @@ steel init ### Parameters - `--agent` (boolean, optional): Run in agent mode: auto-accept interactive prompts and print agent-friendly output. Designed for AI coding agents +- `--from` (string, optional): Coding client for targeted agent setup (opencode, claude-code, codex, pi) - `--skills` (string[], optional): Open the Steel skills installer flow. With no value, lets you choose skills interactively - `--no-skills` (boolean, optional): Skip Steel skill installation diff --git a/docs/references/agent-troubleshooting.md b/docs/references/agent-troubleshooting.md index 1c15aa2..63b88ad 100644 --- a/docs/references/agent-troubleshooting.md +++ b/docs/references/agent-troubleshooting.md @@ -76,8 +76,11 @@ steel browser start --local --session "$SESSION_NAME" ## Common Failures and Actions -- `Missing browser auth...`: - authenticate (`steel login`) or export `STEEL_API_KEY`. +- `auth_required` with `data.login`: you are not signed in. Show the user + `data.login.verificationUrl` and the code `data.login.userCode`. After they + approve, run the same command again. +- `auth_required` without `data.login`: export `STEEL_API_KEY` (CI, or another + API URL). - `Failed to reach Steel session API ...`: check endpoint flags/env and runtime availability. - `Session "" is not running...`: diff --git a/docs/references/steel-browser.md b/docs/references/steel-browser.md index bb50a59..6b08b7b 100644 --- a/docs/references/steel-browser.md +++ b/docs/references/steel-browser.md @@ -37,6 +37,8 @@ Main flags: - `--session ` - `--stealth` - `--proxy ` +- `--use-proxy` +- `--project ` - `--timeout ` - `--inactivity-timeout ` (default 600000; `0` turns it off) - `--solve-captcha` @@ -52,11 +54,20 @@ Flag semantics: - `stealthConfig.humanizeInteractions = true` - `stealthConfig.autoCaptchaSolving = true` - `solveCaptcha = true` + - If the plan refuses CAPTCHA solving (`plan_feature_unavailable` or + `deposit_required`), the session starts again without it and the output + carries a note in `data.notes`. Interactions are still humanized. - `--solve-captcha` enables manual CAPTCHA solving for new sessions: - `solveCaptcha = true` - `stealthConfig.autoCaptchaSolving` is not forced on -- `--proxy ` sets `proxyUrl` on session creation. The Sessions API may return - `proxySource: "external"` rather than echoing the proxy URL in responses. + - If the plan refuses it, the command fails. It is never dropped. +- `--proxy ` sets `proxyUrl` on session creation (your own proxy). It must be + a URL. The Sessions API may return `proxySource: "external"` rather than + echoing the proxy URL in responses. +- `--use-proxy` sets `useProxy = true` (a Steel residential proxy). + `--proxy residential` is read the same way, with a note. +- `--project ` sets `projectId`. An organization-wide API key needs it. + `STEEL_PROJECT_ID` sets it when the flag is absent. - `--namespace ` sets the credential namespace for the session. Credentials stored under this namespace will be available for injection. - `--credentials` enables credential injection for the session. Sends @@ -201,8 +212,11 @@ serve the execution routes or the `find` target form. ## Troubleshooting (Agent-Focused) -- `Missing browser auth. Run steel login or set STEEL_API_KEY.`: - run `steel login` locally, or set `STEEL_API_KEY` in CI/job env. +- `auth_required` with `data.login`: you are not signed in, and a sign-in has + started. Show the user `data.login.verificationUrl` and the code + `data.login.userCode`. After they approve, run the same command again. +- `auth_required` without `data.login` (CI, or another API URL): set + `STEEL_API_KEY` in the job env. - `Failed to reach Steel session API ...` in local mode: verify `steel dev start` is running and endpoint resolution matches expected host/port. diff --git a/src/api/client.rs b/src/api/client.rs index 92df177..959b402 100644 --- a/src/api/client.rs +++ b/src/api/client.rs @@ -10,6 +10,7 @@ use crate::config::settings::ApiMode; pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(120); +pub const USER_AGENT: &str = concat!("steel-cli/", env!("CARGO_PKG_VERSION")); #[derive(Debug, Error)] #[non_exhaustive] @@ -48,6 +49,15 @@ pub enum ApiError { } impl ApiError { + pub fn body_str(&self, key: &str) -> Option<&str> { + match self { + Self::RequestFailed { + body: Some(body), .. + } => body.get(key).and_then(Value::as_str), + _ => None, + } + } + /// Check if this is a 404/410 (not found). Matches TS `isNotFoundApiError()`. pub const fn is_not_found(&self) -> bool { matches!(self, Self::RequestFailed { status, .. } if *status == 404 || *status == 410) @@ -177,7 +187,7 @@ impl SteelClient { pub fn with(base_url: String, mode: ApiMode, auth: Auth) -> Result { let http = Client::builder() - .user_agent("steel-cli") + .user_agent(USER_AGENT) .connect_timeout(CONNECT_TIMEOUT) .timeout(REQUEST_TIMEOUT) .redirect(refuse_redirects()) @@ -502,4 +512,34 @@ mod tests { assert!(matches!(result, Err(ApiError::Unreachable { .. }))); } + + #[tokio::test] + async fn requests_carry_the_cli_version_in_the_user_agent() { + use wiremock::matchers::{header, method, path}; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + assert_eq!( + USER_AGENT, + format!("steel-cli/{}", env!("CARGO_PKG_VERSION")) + ); + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/test")) + .and(header("user-agent", USER_AGENT)) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({}))) + .expect(1) + .mount(&server) + .await; + let auth = Auth { + api_key: None, + access_token: None, + source: crate::config::auth::AuthSource::None, + }; + let client = SteelClient::with(server.uri(), ApiMode::Local, auth).unwrap(); + + client + .request(reqwest::Method::GET, "/test", None) + .await + .unwrap(); + } } diff --git a/src/api/session.rs b/src/api/session.rs index 2128b1f..e9f88bc 100644 --- a/src/api/session.rs +++ b/src/api/session.rs @@ -11,10 +11,13 @@ use crate::config::settings::ApiMode; const CLOUD_CONNECT_URL: &str = "wss://connect.steel.dev"; const CLOUD_VIEWER_URL: &str = "https://app.steel.dev/sessions"; -#[derive(Debug, Default)] +#[derive(Debug, Default, Clone)] pub struct CreateSessionOptions { pub stealth: bool, + pub stealth_without_captcha: bool, pub proxy_url: Option, + pub use_proxy: bool, + pub project_id: Option, pub timeout_ms: Option, pub inactivity_timeout_ms: Option, pub headless: Option, @@ -46,7 +49,9 @@ fn non_empty(value: Option<&str>) -> Option<&str> { impl Session { pub fn parse(value: Value) -> anyhow::Result { - serde_json::from_value(value).context("The Steel API returned an unexpected session.") + serde_json::from_value(value).context(crate::util::error::ApiBadResponse( + "The Steel API returned an unexpected session.", + )) } pub fn is_live(&self) -> bool { @@ -129,7 +134,12 @@ fn build_create_body(options: &CreateSessionOptions) -> Value { } } - if options.stealth { + if options.stealth && options.stealth_without_captcha { + obj.insert( + "stealthConfig".into(), + json!({"humanizeInteractions": true}), + ); + } else if options.stealth { obj.insert( "stealthConfig".into(), json!({"humanizeInteractions": true, "autoCaptchaSolving": true}), @@ -137,6 +147,17 @@ fn build_create_body(options: &CreateSessionOptions) -> Value { obj.insert("solveCaptcha".into(), json!(true)); } + if options.use_proxy { + obj.insert("useProxy".into(), json!(true)); + } + + if let Some(ref project_id) = options.project_id { + let trimmed = project_id.trim(); + if !trimmed.is_empty() { + obj.insert("projectId".into(), json!(trimmed)); + } + } + if options.solve_captcha { obj.insert("solveCaptcha".into(), json!(true)); } @@ -256,7 +277,12 @@ mod tests { #[test] fn parse_needs_an_id() { - assert!(Session::parse(json!({"status": "live"})).is_err()); + let err = Session::parse(json!({"status": "live"})).unwrap_err(); + assert_eq!(crate::util::output::classify(&err).code, "api_bad_response"); + assert_eq!( + err.to_string(), + "The Steel API returned an unexpected session." + ); assert_eq!(session(json!({"id": "s1"})).id, "s1"); } @@ -379,6 +405,29 @@ mod tests { assert!(body["stealthConfig"].is_object()); } + #[test] + fn create_body_stealth_without_captcha_keeps_humanizing_only() { + let body = build_create_body(&CreateSessionOptions { + stealth: true, + stealth_without_captcha: true, + ..Default::default() + }); + assert_eq!( + body, + json!({"stealthConfig": {"humanizeInteractions": true}}) + ); + } + + #[test] + fn create_body_steel_proxy_and_project() { + let body = build_create_body(&CreateSessionOptions { + use_proxy: true, + project_id: Some(" p-1 ".into()), + ..Default::default() + }); + assert_eq!(body, json!({"useProxy": true, "projectId": "p-1"})); + } + #[test] fn create_body_all_fields() { let body = build_create_body(&CreateSessionOptions { diff --git a/src/browser/profile_store.rs b/src/browser/profile_store.rs index 0297f52..9a1fa2c 100644 --- a/src/browser/profile_store.rs +++ b/src/browser/profile_store.rs @@ -1,6 +1,6 @@ use std::path::{Path, PathBuf}; -use anyhow::Result; +use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, Serialize, Deserialize)] @@ -69,7 +69,8 @@ fn read_profile_in(name: &str, dir: &Path) -> Result> { return Ok(None); } let contents = std::fs::read_to_string(&path)?; - let data: ProfileData = serde_json::from_str(&contents)?; + let data: ProfileData = serde_json::from_str(&contents) + .with_context(|| crate::util::error::LocalStateInvalid(path.display().to_string()))?; Ok(Some(data)) } diff --git a/src/browser/state.rs b/src/browser/state.rs index d3391c5..4e063d2 100644 --- a/src/browser/state.rs +++ b/src/browser/state.rs @@ -1,6 +1,6 @@ use std::path::{Path, PathBuf}; -use anyhow::Result; +use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use crate::config::settings::ApiMode; @@ -117,7 +117,9 @@ fn load_in(name: &str, dir: &Path) -> Result> { return Ok(None); } let contents = std::fs::read_to_string(&path)?; - Ok(Some(serde_json::from_str(&contents)?)) + Ok(Some(serde_json::from_str(&contents).with_context( + || crate::util::error::LocalStateInvalid(path.display().to_string()), + )?)) } fn save_in(session: &BrowserSession, dir: &Path) -> Result<()> { @@ -183,6 +185,18 @@ mod tests { assert_eq!(load_in("work", dir.path()).unwrap(), Some(s)); } + #[test] + fn corrupt_session_file_is_local_state_error() { + let dir = tempfile::TempDir::new().unwrap(); + std::fs::write(dir.path().join("broken.json"), "{").unwrap(); + let err = load_in("broken", dir.path()).unwrap_err(); + assert_eq!( + crate::util::output::classify(&err).code, + "local_state_invalid" + ); + assert!(err.to_string().contains("broken.json")); + } + #[test] fn load_missing_is_none() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/commands/browser/action.rs b/src/commands/browser/action.rs index 1a92b9d..8d71693 100644 --- a/src/commands/browser/action.rs +++ b/src/commands/browser/action.rs @@ -1231,17 +1231,28 @@ async fn attach(client: &SteelClient, id: &str) -> Result { impl Browser { pub async fn open(name: Option<&str>, start_default: bool) -> Result { + let target = super::target(name)?; + let signs_in = match &target { + Some(Target::Saved(found)) => found.mode == ApiMode::Cloud, + Some(Target::Id(_)) => true, + None if name.is_none() && start_default => { + eprintln!("warning: session \"default\" is not running; starting a new one"); + true + } + None => return Err(super::not_running(name)), + }; + if signs_in { + crate::commands::login::ensure_signed_in().await?; + } let client = SteelClient::new()?; - let state = match super::target(name)? { + let state = match target { Some(Target::Saved(found)) => *found, Some(Target::Id(id)) => attach(&client, &id).await?, - None if name.is_none() && start_default => { - eprintln!("warning: session \"default\" is not running; starting a new one"); + None => { start::create(&client, DEFAULT_SESSION, &start::default_options()) .await? .0 } - None => return Err(super::not_running(name)), }; let client = client.at(&state.api_url, state.mode); Ok(Self { client, state }) diff --git a/src/commands/browser/mod.rs b/src/commands/browser/mod.rs index fbeda43..e9c9782 100644 --- a/src/commands/browser/mod.rs +++ b/src/commands/browser/mod.rs @@ -77,7 +77,7 @@ pub enum Target { pub fn target(name: Option<&str>) -> anyhow::Result> { let wanted = name.unwrap_or(DEFAULT_SESSION); if let Some(err) = state::validate_session_name(wanted) { - anyhow::bail!("{err}"); + return Err(crate::util::error::invalid_input(err)); } if let Some(found) = state::load(wanted)? { return Ok(Some(Target::Saved(Box::new(found)))); @@ -112,7 +112,7 @@ pub async fn run(args: BrowserArgs) -> anyhow::Result<()> { if let Some(ref name) = session && let Some(err) = state::validate_session_name(name) { - anyhow::bail!("{err}"); + return Err(crate::util::error::invalid_input(err)); } match args.command { Command::Start(start_args) => start::run(start_args, session.as_deref()).await, diff --git a/src/commands/browser/start.rs b/src/commands/browser/start.rs index 860b941..49ea55b 100644 --- a/src/commands/browser/start.rs +++ b/src/commands/browser/start.rs @@ -1,10 +1,11 @@ use clap::Parser; use serde_json::json; -use crate::api::client::SteelClient; +use crate::api::client::{ApiError, SteelClient}; use crate::api::session::CreateSessionOptions; use crate::browser::profile_store; use crate::browser::state::{self, BrowserSession}; +use crate::util::error::invalid_input; use crate::util::{metadata, output}; pub const DEFAULT_TIMEOUT_MS: u64 = 900_000; @@ -12,14 +13,22 @@ pub const DEFAULT_INACTIVITY_TIMEOUT_MS: u64 = 600_000; #[derive(Parser)] pub struct Args { - /// Enable stealth mode (humanize interactions + auto CAPTCHA) + /// Enable stealth mode: humanized interactions, plus automatic CAPTCHA solving when your plan includes it #[arg(long)] pub stealth: bool, - /// Use a residential proxy - #[arg(short = 'p', long)] + /// Route the session through your own proxy (http://user:pass@host:port) + #[arg(short = 'p', long, value_name = "URL", conflicts_with = "use_proxy")] pub proxy: Option, + /// Use a Steel-managed residential proxy + #[arg(long = "use-proxy")] + pub use_proxy: bool, + + /// Project to create the session in, needed with an organization-wide API key. Defaults to STEEL_PROJECT_ID + #[arg(long, value_name = "ID")] + pub project: Option, + /// Session timeout in milliseconds. Defaults to 900000 (15 minutes), which every plan allows (create-time only) #[arg(long, alias = "session-timeout")] pub timeout: Option, @@ -65,10 +74,69 @@ pub fn default_options() -> CreateSessionOptions { CreateSessionOptions { timeout_ms: Some(DEFAULT_TIMEOUT_MS), inactivity_timeout_ms: Some(DEFAULT_INACTIVITY_TIMEOUT_MS), + project_id: project_from_env(), ..Default::default() } } +fn project_from_env() -> Option { + std::env::var("STEEL_PROJECT_ID") + .ok() + .filter(|value| !value.trim().is_empty()) +} + +#[derive(Debug, PartialEq, Eq)] +struct ProxyChoice { + url: Option, + steel: bool, + aliased: bool, +} + +const PROXY_URL_REQUIRED: &str = "--proxy takes a proxy URL such as http://user:pass@host:port. For a Steel residential proxy, use --use-proxy."; + +fn resolve_proxy(proxy: Option, use_proxy: bool) -> anyhow::Result { + let Some(value) = proxy + .map(|value| value.trim().to_string()) + .filter(|value| !value.is_empty()) + else { + return Ok(ProxyChoice { + url: None, + steel: use_proxy, + aliased: false, + }); + }; + if value.eq_ignore_ascii_case("residential") || value.eq_ignore_ascii_case("steel") { + return Ok(ProxyChoice { + url: None, + steel: true, + aliased: true, + }); + } + match url::Url::parse(&value) { + Ok(url) if url.has_host() => Ok(ProxyChoice { + url: Some(value), + steel: use_proxy, + aliased: false, + }), + _ => Err(invalid_input(PROXY_URL_REQUIRED)), + } +} + +fn captcha_refusal(err: &anyhow::Error, options: &CreateSessionOptions) -> Option<&'static str> { + if !options.stealth || options.solve_captcha || options.stealth_without_captcha { + return None; + } + let api = err.downcast_ref::()?; + if api.body_str("param") != Some("solveCaptcha") { + return None; + } + match api.body_str("code")? { + "plan_feature_unavailable" => Some("your plan does not include CAPTCHA solving"), + "deposit_required" => Some("CAPTCHA solving needs a paid balance on your plan"), + _ => None, + } +} + fn now_ms() -> Option { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) @@ -103,32 +171,41 @@ pub async fn create( pub async fn run(args: Args, session: Option<&str>) -> anyhow::Result<()> { let session_name = session.unwrap_or("default").to_string(); if state::looks_like_session_id(&session_name) { - anyhow::bail!( + return Err(invalid_input(format!( "Session names cannot look like session IDs. Use `--session {session_name}` on other commands to drive that session, or pick a name." - ); + ))); } let session_metadata = metadata::collect(args.metadata)?; + let proxy = resolve_proxy(args.proxy, args.use_proxy)?; + let mut notes = Vec::new(); + if proxy.aliased { + notes.push( + "--proxy takes a proxy URL, so a Steel residential proxy (--use-proxy) is used instead." + .to_string(), + ); + } + let project_id = args.project.or_else(project_from_env); let mut resolved_profile_id = None; let mut stored_browser_profile = None; let mut stored_browser = None; if let Some(ref profile_name) = args.profile { if let Some(err) = profile_store::validate_profile_name(profile_name) { - anyhow::bail!("{err}"); + return Err(invalid_input(err)); } if let Some(data) = profile_store::read_profile(profile_name)? { resolved_profile_id = Some(data.profile_id); stored_browser_profile = data.browser_profile; stored_browser = data.browser; } else if !args.update_profile { - anyhow::bail!( + return Err(invalid_input(format!( "Profile \"{profile_name}\" not found. Import one with `steel profile import {profile_name}`, or add --update-profile to create it from this session." - ); + ))); } } let persist_profile = args.profile.is_some() && args.update_profile; - let proxy_enabled = args.proxy.is_some(); + let proxy_enabled = proxy.url.is_some() || proxy.steel; let namespace_set = args.namespace.is_some(); let metadata_set = !session_metadata.is_empty(); let timeout = args.timeout.unwrap_or(DEFAULT_TIMEOUT_MS); @@ -141,6 +218,7 @@ pub async fn run(args: Args, session: Option<&str>) -> anyhow::Result<()> { ); } + crate::commands::login::ensure_signed_in().await?; let client = SteelClient::new()?; let replaced = match state::load(&session_name)? { @@ -164,7 +242,10 @@ pub async fn run(args: Args, session: Option<&str>) -> anyhow::Result<()> { let options = CreateSessionOptions { stealth: args.stealth, - proxy_url: args.proxy, + stealth_without_captcha: false, + proxy_url: proxy.url, + use_proxy: proxy.steel, + project_id: project_id.clone(), timeout_ms: Some(timeout), inactivity_timeout_ms, headless: args.headless, @@ -177,7 +258,24 @@ pub async fn run(args: Args, session: Option<&str>) -> anyhow::Result<()> { metadata: session_metadata, }; - let (created, connect_url) = create(&client, &session_name, &options).await?; + let mut captcha_dropped = false; + let (created, connect_url) = match create(&client, &session_name, &options).await { + Ok(done) => done, + Err(err) => { + let Some(reason) = captcha_refusal(&err, &options) else { + return Err(err); + }; + captcha_dropped = true; + notes.push(format!( + "Started without CAPTCHA solving because {reason}. Interactions are still humanized." + )); + let without_captcha = CreateSessionOptions { + stealth_without_captcha: true, + ..options.clone() + }; + create(&client, &session_name, &without_captcha).await? + } + }; if let Some(ref profile_name) = args.profile && let Some(ref returned_profile_id) = created.profile_id @@ -193,6 +291,9 @@ pub async fn run(args: Args, session: Option<&str>) -> anyhow::Result<()> { let mut properties = serde_json::Map::new(); properties.insert("stealth".into(), json!(args.stealth)); properties.insert("proxy_enabled".into(), json!(proxy_enabled)); + properties.insert("use_proxy".into(), json!(proxy.steel)); + properties.insert("project_set".into(), json!(project_id.is_some())); + properties.insert("stealth_captcha_dropped".into(), json!(captcha_dropped)); properties.insert("has_profile".into(), json!(args.profile.is_some())); properties.insert("persist_profile".into(), json!(persist_profile)); properties.insert("credentials".into(), json!(args.credentials)); @@ -202,7 +303,10 @@ pub async fn run(args: Args, session: Option<&str>) -> anyhow::Result<()> { properties.insert("inactivity_timeout_ms".into(), json!(inactivity_timeout_ms)); crate::telemetry::track_event("browser_session_started", properties); - display_session_info(&created, connect_url.as_deref(), replaced.as_ref()); + for note in ¬es { + eprintln!("note: {note}"); + } + display_session_info(&created, connect_url.as_deref(), replaced.as_ref(), ¬es); Ok(()) } @@ -211,6 +315,7 @@ fn display_session_info( info: &BrowserSession, connect_url: Option<&str>, replaced: Option<&(String, bool)>, + notes: &[String], ) { let remaining = remaining_time_str(info); @@ -236,6 +341,9 @@ fn display_session_info( if let Some(ms) = info.inactivity_timeout_ms { data["inactivityTimeoutMs"] = json!(ms); } + if !notes.is_empty() { + data["notes"] = json!(notes); + } output::success_data(data); } else { println!("id: {}", info.id); diff --git a/src/commands/browser/stop.rs b/src/commands/browser/stop.rs index 748c110..2f52f3e 100644 --- a/src/commands/browser/stop.rs +++ b/src/commands/browser/stop.rs @@ -28,7 +28,9 @@ pub async fn release(client: &SteelClient, session: &BrowserSession) -> anyhow:: pub async fn run(args: Args, session: Option<&str>) -> anyhow::Result<()> { if args.all && session.is_some() { - anyhow::bail!("Cannot combine `--all` with `--session`."); + return Err(crate::util::error::invalid_input( + "Cannot combine `--all` with `--session`.", + )); } let client = SteelClient::new()?; diff --git a/src/commands/login.rs b/src/commands/login.rs index 5bc2f1c..70a404b 100644 --- a/src/commands/login.rs +++ b/src/commands/login.rs @@ -1,3 +1,5 @@ +use crate::api::client::ApiError; +use crate::config::settings::ApiMode; use crate::config::{auth, device}; use crate::util::output; use clap::Parser; @@ -48,3 +50,61 @@ pub async fn authorize(args: Args) -> anyhow::Result { "next_action":if complete {"Run steel doctor --preflight to verify product API access"} else {"Approve the displayed code, then run steel login --resume or repeat steel init"} })) } + +const WAITING_FOR_APPROVAL: &str = "Waiting for approval. This command continues once you approve."; + +fn same_transport(base_url: &str, device_api: &str) -> bool { + base_url.trim_end_matches('/') == device_api.trim_end_matches('/') +} + +pub async fn ensure_signed_in() -> anyhow::Result<()> { + let (mode, base_url, credentials) = crate::util::api::resolve_with_auth(); + if mode != ApiMode::Cloud || credentials.has_credentials() || crate::telemetry::is_ci() { + return Ok(()); + } + let saved = device::saved_settings().ok().flatten(); + let Ok(settings) = device::Settings::resolve(saved.as_ref()) else { + return Ok(()); + }; + if !same_transport(&base_url, &settings.api_base_url) { + return Ok(()); + } + let interactive = + !output::is_json() && std::io::stdin().is_terminal() && std::io::stderr().is_terminal(); + let outcome = if interactive { + device::authorize( + device::Wait::UntilExpiry, + true, + false, + Some(WAITING_FOR_APPROVAL), + ) + .await + } else { + device::authorize(device::Wait::No, false, false, None).await + } + .map_err(|err| { + ApiError::DeviceAuth(err.context("Not signed in to Steel, and sign-in failed")) + })?; + match outcome { + device::Outcome::Authorized => { + let mut properties = serde_json::Map::new(); + properties.insert("trigger".into(), serde_json::json!("command")); + crate::telemetry::track_event("login_completed", properties); + Ok(()) + } + device::Outcome::Pending(handoff) => Err(handoff.into()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn handoff_only_targets_the_transport_the_login_is_for() { + let api = "https://api.steel.dev/v1"; + assert!(same_transport(api, api)); + assert!(same_transport("https://api.steel.dev/v1/", api)); + assert!(!same_transport("https://api.staging.steel.dev/v1", api)); + } +} diff --git a/src/commands/mod.rs b/src/commands/mod.rs index aa4a618..dc824bb 100644 --- a/src/commands/mod.rs +++ b/src/commands/mod.rs @@ -381,7 +381,8 @@ mod tests { event["event"] == "command_failed" && event["properties"]["command_path"] == "browser.stop" && event["properties"]["success"] == false - && event["properties"]["error_class"] == "internal_error" + && event["properties"]["error_class"] == "invalid_input" + && event["properties"]["ci"].is_boolean() })); } diff --git a/src/commands/pdf.rs b/src/commands/pdf.rs index aab2166..63ed51e 100644 --- a/src/commands/pdf.rs +++ b/src/commands/pdf.rs @@ -32,6 +32,7 @@ pub async fn run(args: Args) -> anyhow::Result<()> { use_proxy: args.use_proxy, region: args.region.as_deref(), }; + super::login::ensure_signed_in().await?; let response = SteelClient::new()?.pdf(&target).await?; if output::is_json() { diff --git a/src/commands/scrape.rs b/src/commands/scrape.rs index c1afcdb..75f42fd 100644 --- a/src/commands/scrape.rs +++ b/src/commands/scrape.rs @@ -49,6 +49,7 @@ pub async fn run(args: Args) -> anyhow::Result<()> { use_proxy: args.use_proxy, region: args.region.as_deref(), }; + super::login::ensure_signed_in().await?; let response = SteelClient::new()? .scrape(&target, &formats, args.pdf, args.screenshot) .await?; diff --git a/src/commands/screenshot.rs b/src/commands/screenshot.rs index 77b1807..cf0e65e 100644 --- a/src/commands/screenshot.rs +++ b/src/commands/screenshot.rs @@ -36,6 +36,7 @@ pub async fn run(args: Args) -> anyhow::Result<()> { use_proxy: args.use_proxy, region: args.region.as_deref(), }; + super::login::ensure_signed_in().await?; let response = SteelClient::new()? .screenshot(&target, args.full_page) .await?; diff --git a/src/config/device.rs b/src/config/device.rs index 3f1536b..249d94a 100644 --- a/src/config/device.rs +++ b/src/config/device.rs @@ -235,7 +235,7 @@ fn http() -> Result { Ok(reqwest::Client::builder() .timeout(Duration::from_secs(15)) .redirect(reqwest::redirect::Policy::none()) - .user_agent("steel-cli") + .user_agent(crate::api::client::USER_AGENT) .build()?) } @@ -322,9 +322,41 @@ pub fn saved_access_token() -> Option { } } +pub enum Outcome { + Authorized, + Pending(crate::util::error::LoginRequired), +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum Wait { + No, + Briefly, + UntilExpiry, +} + +const LOGIN_NEXT_STEP: &str = "After approval, run steel login --resume or repeat steel init. Pending login survives interruption."; + /// Returns false while approval is pending. Repeated calls continue the same /// request and polling schedule; --resume never replaces an expired request. pub async fn login(no_wait: bool, no_browser: bool, resume: bool) -> Result { + Ok(matches!( + authorize( + if no_wait { Wait::No } else { Wait::Briefly }, + !no_browser, + resume, + Some(LOGIN_NEXT_STEP) + ) + .await?, + Outcome::Authorized + )) +} + +pub async fn authorize( + wait: Wait, + open_browser: bool, + resume: bool, + next_step: Option<&str>, +) -> Result { let _guard = lock().await?; let existing = read()?; let settings = Settings::resolve(existing.as_ref().map(|s| &s.settings))?; @@ -339,7 +371,7 @@ pub async fn login(no_wait: bool, no_browser: bool, resume: bool) -> Result Result u64::from(!new_request), + Wait::Briefly => 45, + Wait::UntilExpiry => pending.expires_at.saturating_sub(now()).saturating_add(1), + }; + let deadline = tokio::time::Instant::now() + Duration::from_secs(wait_for); loop { let p = state.pending.as_mut().expect("pending request"); if now() >= p.expires_at { @@ -430,7 +466,13 @@ pub async fn login(no_wait: bool, no_browser: bool, resume: bool) -> Result= deadline.saturating_duration_since(tokio::time::Instant::now()) { - return Ok(false); + return Ok(Outcome::Pending(crate::util::error::LoginRequired { + verification_uri: p.verification_uri.clone(), + verification_uri_complete: p.verification_uri_complete.clone(), + user_code: p.user_code.clone(), + expires_at: p.expires_at, + started: new_request, + })); } tokio::time::sleep(delay).await; p.next_poll_at = now().saturating_add(p.interval); @@ -449,7 +491,7 @@ pub async fn login(no_wait: bool, no_browser: bool, resume: bool) -> Result { store_tokens(&mut state, tokens); save(&state)?; - return Ok(true); + return Ok(Outcome::Authorized); } Err(code) if code == "authorization_pending" => {} Err(code) if code == "slow_down" => { diff --git a/src/telemetry.rs b/src/telemetry.rs index 53d2841..9ddb80d 100644 --- a/src/telemetry.rs +++ b/src/telemetry.rs @@ -241,6 +241,7 @@ pub fn track_command_failed(context: &CommandContext, duration: Duration, err: & properties.insert("success".into(), json!(false)); properties.insert("duration_ms".into(), json!(duration.as_millis() as u64)); properties.insert("error_class".into(), json!(error_class(err))); + properties.extend(failure_properties(err)); track("command_failed", properties); } @@ -433,9 +434,36 @@ fn default_properties() -> Map { properties.insert("arch".into(), json!(std::env::consts::ARCH)); properties.insert("json".into(), json!(crate::util::output::is_json())); properties.insert("mode".into(), json!(telemetry_mode())); + properties.insert("ci".into(), json!(is_ci())); properties } +const CI_ENV_VARS: &[&str] = &[ + "CI", + "GITHUB_ACTIONS", + "GITLAB_CI", + "BUILDKITE", + "CIRCLECI", + "JENKINS_URL", + "TF_BUILD", + "TEAMCITY_VERSION", + "BITBUCKET_BUILD_NUMBER", + "CODEBUILD_BUILD_ID", +]; + +pub fn is_ci() -> bool { + running_in_ci(|name| std::env::var(name).ok()) +} + +fn running_in_ci(var: impl Fn(&str) -> Option) -> bool { + CI_ENV_VARS.iter().any(|name| { + var(name).is_some_and(|value| { + let value = value.trim(); + !value.is_empty() && !value.eq_ignore_ascii_case("false") && value != "0" + }) + }) +} + fn telemetry_disabled( env: &TelemetryEnv, config: Option<&crate::config::settings::Config>, @@ -456,30 +484,39 @@ fn error_class(err: &anyhow::Error) -> String { if let Some(silent) = err.downcast_ref::() { return silent.error_code.clone(); } - if let Some(api_err) = err.downcast_ref::() { - let class = match api_err { - crate::api::client::ApiError::MissingAuth => "auth_required", - crate::api::client::ApiError::DeviceAuth(_) => "device_auth_failed", - crate::api::client::ApiError::Unreachable { .. } => "network_unreachable", - crate::api::client::ApiError::Redirected { .. } => "api_redirect_refused", - crate::api::client::ApiError::RequestFailed { status, .. } => match *status { - 401 => "api_unauthorized", - 403 => "api_forbidden", - 404 | 410 => "api_not_found", - 429 => "api_rate_limited", - s if s >= 500 => "api_server_error", - _ => "api_request_failed", - }, - crate::api::client::ApiError::Other(_) => "network_error", - }; - return class.to_string(); - } + crate::util::output::classify(err).telemetry.to_string() +} - if err.chain().any(|source| source.is::()) { - return "io_error".to_string(); - } +fn machine_token(value: Option<&Value>) -> Option<&str> { + value.and_then(Value::as_str).filter(|token| { + !token.is_empty() + && token.len() <= 64 + && token + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.')) + }) +} - "internal_error".to_string() +fn failure_properties(err: &anyhow::Error) -> Map { + let mut properties = Map::new(); + if let Some(crate::api::client::ApiError::RequestFailed { status, body, .. }) = + err.downcast_ref::() + { + properties.insert("http_status".into(), json!(status)); + if let Some(code) = machine_token(body.as_ref().and_then(|body| body.get("code"))) { + properties.insert("api_error_code".into(), json!(code)); + } + if let Some(param) = machine_token(body.as_ref().and_then(|body| body.get("param"))) { + properties.insert("api_error_param".into(), json!(param)); + } + } + if let Some(login) = err.downcast_ref::() { + properties.insert( + "login_handoff".into(), + json!(if login.started { "started" } else { "pending" }), + ); + } + properties } struct TelemetryIdentity { @@ -724,6 +761,98 @@ mod tests { assert_eq!(error_class(&anyhow::anyhow!("boom")), "internal_error"); } + #[test] + fn error_classes_keep_their_names() { + use crate::api::client::ApiError; + let failed = |status| -> anyhow::Error { + ApiError::RequestFailed { + status, + message: std::borrow::Cow::Borrowed("x"), + body: None, + } + .into() + }; + assert_eq!(error_class(&ApiError::MissingAuth.into()), "auth_required"); + assert_eq!(error_class(&failed(401)), "api_unauthorized"); + assert_eq!(error_class(&failed(403)), "api_forbidden"); + assert_eq!(error_class(&failed(410)), "api_not_found"); + assert_eq!(error_class(&failed(429)), "api_rate_limited"); + assert_eq!(error_class(&failed(503)), "api_server_error"); + assert_eq!(error_class(&failed(400)), "api_request_failed"); + assert_eq!( + error_class(&std::io::Error::other("disk").into()), + "io_error" + ); + assert_eq!( + error_class(&crate::util::error::invalid_input("bad name")), + "invalid_input" + ); + } + + #[test] + fn api_failures_report_status_and_machine_codes_only() { + let err: anyhow::Error = crate::api::client::ApiError::RequestFailed { + status: 400, + message: std::borrow::Cow::Borrowed("Requested timeout exceeds the maximum"), + body: Some(json!({ + "error": "Bad Request", + "code": "invalid_request", + "param": "timeout", + "message": "Requested timeout exceeds the maximum for your plan (15 min).", + })), + } + .into(); + let properties = failure_properties(&err); + assert_eq!(properties["http_status"], json!(400)); + assert_eq!(properties["api_error_code"], json!("invalid_request")); + assert_eq!(properties["api_error_param"], json!("timeout")); + assert!( + !properties + .values() + .any(|v| v.to_string().contains("maximum")) + ); + + let free_text: anyhow::Error = crate::api::client::ApiError::RequestFailed { + status: 403, + message: std::borrow::Cow::Borrowed("x"), + body: Some(json!({"code": "user@example.com is blocked"})), + } + .into(); + assert!(!failure_properties(&free_text).contains_key("api_error_code")); + } + + #[test] + fn login_handoff_is_reported() { + let err: anyhow::Error = crate::util::error::LoginRequired { + verification_uri: "https://auth.steel.dev/device".into(), + verification_uri_complete: "https://auth.steel.dev/device?user_code=ABCD2345".into(), + user_code: "ABCD2345".into(), + expires_at: u64::MAX, + started: false, + } + .into(); + assert_eq!(error_class(&err), "auth_required"); + assert_eq!(failure_properties(&err)["login_handoff"], json!("pending")); + } + + #[test] + fn ci_is_detected_from_common_variables() { + let env = |pairs: &'static [(&'static str, &'static str)]| { + move |name: &str| { + pairs + .iter() + .find(|(key, _)| *key == name) + .map(|(_, value)| (*value).to_string()) + } + }; + assert!(running_in_ci(env(&[("CI", "true")]))); + assert!(running_in_ci(env(&[("GITHUB_ACTIONS", "true")]))); + assert!(running_in_ci(env(&[("JENKINS_URL", "https://ci.example")]))); + assert!(!running_in_ci(env(&[("CI", "false")]))); + assert!(!running_in_ci(env(&[("CI", "0")]))); + assert!(!running_in_ci(env(&[]))); + } + #[test] fn batch_payload_includes_events_with_distinct_id_and_timestamp() { let mut properties = Map::new(); diff --git a/src/util/error.rs b/src/util/error.rs new file mode 100644 index 0000000..862a2f6 --- /dev/null +++ b/src/util/error.rs @@ -0,0 +1,121 @@ +use serde_json::{Value, json}; + +#[derive(Debug, thiserror::Error)] +#[error("{0}")] +pub struct InvalidInput(pub String); + +pub fn invalid_input(message: impl std::fmt::Display) -> anyhow::Error { + InvalidInput(message.to_string()).into() +} + +#[derive(Debug, thiserror::Error)] +#[error("{0}")] +pub struct ApiBadResponse(pub &'static str); + +#[derive(Debug, thiserror::Error)] +#[error("Could not read {0}")] +pub struct LocalStateInvalid(pub String); + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LoginRequired { + pub verification_uri: String, + pub verification_uri_complete: String, + pub user_code: String, + pub expires_at: u64, + pub started: bool, +} + +impl LoginRequired { + pub fn expires_in(&self) -> u64 { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_secs(); + self.expires_at.saturating_sub(now) + } + + pub fn to_json(&self) -> Value { + let mut login = json!({ + "status": "pending", + "verificationUrl": self.verification_uri_complete, + "verificationUri": self.verification_uri, + "userCode": self.user_code, + "expiresInSeconds": self.expires_in(), + "nextAction": "Open verificationUrl in a browser and approve the code, then run the same command again.", + }); + if let Ok(at) = + jiff::Timestamp::from_second(i64::try_from(self.expires_at).unwrap_or(i64::MAX)) + { + login["expiresAt"] = json!(at.to_string()); + } + json!({ "login": login }) + } +} + +fn minutes(seconds: u64) -> String { + match seconds.div_ceil(60) { + 0 | 1 => "1 minute".to_string(), + n => format!("{n} minutes"), + } +} + +impl std::fmt::Display for LoginRequired { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "Not signed in to Steel. Open {} in a browser and approve code {} (expires in {}), then run this command again.", + self.verification_uri_complete, + self.user_code, + minutes(self.expires_in()) + ) + } +} + +impl std::error::Error for LoginRequired {} + +#[cfg(test)] +mod tests { + use super::*; + + fn handoff(expires_at: u64) -> LoginRequired { + LoginRequired { + verification_uri: "https://auth.steel.dev/device".into(), + verification_uri_complete: "https://auth.steel.dev/device?user_code=ABCD2345".into(), + user_code: "ABCD2345".into(), + expires_at, + started: true, + } + } + + #[test] + fn login_required_names_the_url_code_and_next_step() { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(); + let message = handoff(now + 600).to_string(); + assert!(message.contains("https://auth.steel.dev/device?user_code=ABCD2345")); + assert!(message.contains("ABCD2345")); + assert!(message.contains("10 minutes")); + assert!(message.contains("run this command again")); + } + + #[test] + fn login_required_json_carries_the_handoff() { + let data = handoff(1_900_000_000).to_json(); + assert_eq!(data["login"]["status"], "pending"); + assert_eq!( + data["login"]["verificationUrl"], + "https://auth.steel.dev/device?user_code=ABCD2345" + ); + assert_eq!(data["login"]["userCode"], "ABCD2345"); + assert_eq!(data["login"]["expiresAt"], "2030-03-17T17:46:40Z"); + } + + #[test] + fn expired_handoff_reports_zero_seconds_left() { + assert_eq!(handoff(1).expires_in(), 0); + assert_eq!(minutes(0), "1 minute"); + assert_eq!(minutes(61), "2 minutes"); + } +} diff --git a/src/util/metadata.rs b/src/util/metadata.rs index 72342c2..6989d89 100644 --- a/src/util/metadata.rs +++ b/src/util/metadata.rs @@ -11,7 +11,9 @@ pub fn collect(pairs: Vec<(String, String)>) -> anyhow::Result) -> anyhow::Result ! { std::process::exit(silent.code); } - let (code, error_code, hint) = classify_error(err); + let class = classify(err); let msg = format!("{err:#}"); + let data = err + .downcast_ref::() + .map(crate::util::error::LoginRequired::to_json); if is_json() { let mut obj = json!({ "success": false, "error": msg, - "error_code": error_code, + "error_code": class.code, }); - if let Some(h) = hint { + if let Some(h) = class.hint { obj["hint"] = json!(h); } + if let Some(data) = data { + obj["data"] = data; + } println!("{obj}"); } else { eprintln!("Error: {msg}"); - if let Some(h) = hint { + if let Some(h) = class.hint { eprintln!("Hint: {h}"); } } - std::process::exit(code); + std::process::exit(class.exit_code); } -fn classify_error(err: &anyhow::Error) -> (i32, &'static str, Option<&'static str>) { - if let Some(api_err) = err.downcast_ref::() { - match api_err { - crate::api::client::ApiError::DeviceAuth(_) => ( +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ErrorClass { + pub exit_code: i32, + pub code: &'static str, + pub telemetry: &'static str, + pub hint: Option<&'static str>, +} + +const fn class( + exit_code: i32, + code: &'static str, + telemetry: &'static str, + hint: Option<&'static str>, +) -> ErrorClass { + ErrorClass { + exit_code, + code, + telemetry, + hint, + } +} + +const NETWORK_HINT: Option<&str> = Some("Check your network connection."); +const LOCAL_STATE_HINT: Option<&str> = Some("Delete the file and retry."); +const PROJECT_HINT: Option<&str> = Some( + "This API key covers the whole organization. Pass --project to steel browser start, or set STEEL_PROJECT_ID.", +); +const LOGIN_HINT: Option<&str> = Some( + "If an agent runs this command, show the URL and code to the user and retry after they approve. STEEL_API_KEY also works.", +); + +fn classify_api(err: &crate::api::client::ApiError) -> ErrorClass { + use crate::api::client::ApiError; + match err { + ApiError::DeviceAuth(_) => class( + exit_code::AUTH, + "device_auth_failed", + "device_auth_failed", + Some("Resume pending login or reauthorize as directed."), + ), + ApiError::MissingAuth => class( + exit_code::AUTH, + "auth_required", + "auth_required", + Some("Run `steel login` or set STEEL_API_KEY."), + ), + ApiError::Unreachable { .. } => class( + exit_code::NETWORK, + "unreachable", + "network_unreachable", + Some("Check your network connection and API URL."), + ), + ApiError::Redirected { .. } => class( + exit_code::NETWORK, + "network_error", + "api_redirect_refused", + NETWORK_HINT, + ), + ApiError::RequestFailed { .. } if err.body_str("code") == Some("project_required") => { + class( + exit_code::API_CLIENT, + "request_failed", + "api_request_failed", + PROJECT_HINT, + ) + } + ApiError::RequestFailed { status, .. } => match *status { + 401 => class( exit_code::AUTH, - "device_auth_failed", - Some("Resume pending login or reauthorize as directed."), + "unauthorized", + "api_unauthorized", + Some("API key may be invalid. Run `steel login`."), ), - crate::api::client::ApiError::MissingAuth => ( - exit_code::AUTH, - "auth_required", - Some("Run `steel login` or set STEEL_API_KEY."), + 403 => class(exit_code::API_CLIENT, "forbidden", "api_forbidden", None), + 404 | 410 => class(exit_code::API_CLIENT, "not_found", "api_not_found", None), + 429 => class( + exit_code::API_CLIENT, + "rate_limited", + "api_rate_limited", + Some("Too many requests. Wait and retry."), ), - crate::api::client::ApiError::Unreachable { .. } => ( - exit_code::NETWORK, - "unreachable", - Some("Check your network connection and API URL."), + s if s >= 500 => class( + exit_code::API_SERVER, + "server_error", + "api_server_error", + Some("Steel API server error. Try again later."), + ), + _ => class( + exit_code::API_CLIENT, + "request_failed", + "api_request_failed", + None, ), - crate::api::client::ApiError::RequestFailed { status, .. } => match *status { - 401 => ( - exit_code::AUTH, - "unauthorized", - Some("API key may be invalid. Run `steel login`."), - ), - 403 => (exit_code::API_CLIENT, "forbidden", None), - 404 => (exit_code::API_CLIENT, "not_found", None), - 429 => ( - exit_code::API_CLIENT, - "rate_limited", - Some("Too many requests. Wait and retry."), - ), - s if s >= 500 => ( - exit_code::API_SERVER, - "server_error", - Some("Steel API server error. Try again later."), - ), - _ => (exit_code::API_CLIENT, "request_failed", None), - }, - _ => ( + }, + ApiError::Other(_) => class( + exit_code::NETWORK, + "network_error", + "network_error", + NETWORK_HINT, + ), + } +} + +pub fn classify(err: &anyhow::Error) -> ErrorClass { + use crate::util::error::{ApiBadResponse, InvalidInput, LocalStateInvalid, LoginRequired}; + if let Some(api_err) = err.downcast_ref::() { + return classify_api(api_err); + } + if err.downcast_ref::().is_some() { + return class( + exit_code::AUTH, + "auth_required", + "auth_required", + LOGIN_HINT, + ); + } + if err.downcast_ref::().is_some() { + return class(exit_code::USAGE, "invalid_input", "invalid_input", None); + } + if err.downcast_ref::().is_some() { + return class( + exit_code::API_SERVER, + "api_bad_response", + "api_bad_response", + None, + ); + } + if err.downcast_ref::().is_some() { + return class( + exit_code::GENERAL, + "local_state_invalid", + "local_state_invalid", + LOCAL_STATE_HINT, + ); + } + if let Some(http) = err + .chain() + .find_map(|source| source.downcast_ref::()) + { + if http.is_decode() { + return class( + exit_code::API_SERVER, + "api_bad_response", + "api_bad_response", + None, + ); + } + if !http.is_builder() && !http.is_status() { + return class( exit_code::NETWORK, "network_error", - Some("Check your network connection."), - ), + "network_error", + NETWORK_HINT, + ); } - } else { - (exit_code::GENERAL, "internal_error", None) } + if err.chain().any(|source| source.is::()) { + return class(exit_code::GENERAL, "io_error", "io_error", None); + } + class(exit_code::GENERAL, "internal_error", "internal_error", None) } #[cfg(test)] mod tests { use super::*; + use anyhow::Context; use serde_json::json; // --- format_success --- @@ -306,12 +427,17 @@ mod tests { assert!(format_success_silent(false).is_none()); } - // --- classify_error --- + // --- classify --- #[test] fn classify_missing_auth() { let err: anyhow::Error = crate::api::client::ApiError::MissingAuth.into(); - let (code, error_code, hint) = classify_error(&err); + let ErrorClass { + exit_code: code, + code: error_code, + hint, + .. + } = classify(&err); assert_eq!(code, exit_code::AUTH); assert_eq!(error_code, "auth_required"); assert!(hint.is_some()); @@ -325,7 +451,11 @@ mod tests { body: None, } .into(); - let (code, error_code, _) = classify_error(&err); + let ErrorClass { + exit_code: code, + code: error_code, + .. + } = classify(&err); assert_eq!(code, exit_code::AUTH); assert_eq!(error_code, "unauthorized"); } @@ -338,7 +468,11 @@ mod tests { body: None, } .into(); - let (code, error_code, _) = classify_error(&err); + let ErrorClass { + exit_code: code, + code: error_code, + .. + } = classify(&err); assert_eq!(code, exit_code::API_CLIENT); assert_eq!(error_code, "not_found"); } @@ -351,7 +485,12 @@ mod tests { body: None, } .into(); - let (code, error_code, hint) = classify_error(&err); + let ErrorClass { + exit_code: code, + code: error_code, + hint, + .. + } = classify(&err); assert_eq!(code, exit_code::API_CLIENT); assert_eq!(error_code, "rate_limited"); assert!(hint.is_some()); @@ -365,7 +504,11 @@ mod tests { body: None, } .into(); - let (code, error_code, _) = classify_error(&err); + let ErrorClass { + exit_code: code, + code: error_code, + .. + } = classify(&err); assert_eq!(code, exit_code::API_SERVER); assert_eq!(error_code, "server_error"); } @@ -378,7 +521,11 @@ mod tests { body: None, } .into(); - let (code, error_code, _) = classify_error(&err); + let ErrorClass { + exit_code: code, + code: error_code, + .. + } = classify(&err); assert_eq!(code, exit_code::API_CLIENT); assert_eq!(error_code, "request_failed"); } @@ -386,8 +533,123 @@ mod tests { #[test] fn classify_generic_error() { let err = anyhow::anyhow!("something unexpected"); - let (code, error_code, _) = classify_error(&err); + let ErrorClass { + exit_code: code, + code: error_code, + .. + } = classify(&err); assert_eq!(code, exit_code::GENERAL); assert_eq!(error_code, "internal_error"); } + + #[test] + fn classify_invalid_input() { + let err = crate::util::error::invalid_input("Session names cannot look like session IDs."); + let ErrorClass { + exit_code: code, + code: error_code, + .. + } = classify(&err); + assert_eq!(code, exit_code::USAGE); + assert_eq!(error_code, "invalid_input"); + } + + #[test] + fn classify_login_required_as_auth_required() { + let err: anyhow::Error = crate::util::error::LoginRequired { + verification_uri: "https://auth.steel.dev/device".into(), + verification_uri_complete: "https://auth.steel.dev/device?user_code=ABCD2345".into(), + user_code: "ABCD2345".into(), + expires_at: u64::MAX, + started: true, + } + .into(); + let class = classify(&err); + assert_eq!(class.exit_code, exit_code::AUTH); + assert_eq!(class.code, "auth_required"); + assert_eq!(class.telemetry, "auth_required"); + assert!(class.hint.is_some()); + } + + #[test] + fn classify_bad_session_response() { + let err = serde_json::from_value::>(json!({})) + .map_err(anyhow::Error::from) + .context(crate::util::error::ApiBadResponse( + "The Steel API returned an unexpected session.", + )) + .unwrap_err(); + let class = classify(&err); + assert_eq!(class.exit_code, exit_code::API_SERVER); + assert_eq!(class.code, "api_bad_response"); + } + + #[test] + fn classify_corrupt_local_state() { + let err = serde_json::from_str::("{") + .map_err(anyhow::Error::from) + .context(crate::util::error::LocalStateInvalid("default.json".into())) + .unwrap_err(); + let class = classify(&err); + assert_eq!(class.code, "local_state_invalid"); + assert_eq!(class.hint, Some("Delete the file and retry.")); + assert!(format!("{err:#}").starts_with("Could not read default.json: ")); + } + + #[tokio::test] + async fn classify_reqwest_errors_by_kind() { + let server = wiremock::MockServer::start().await; + wiremock::Mock::given(wiremock::matchers::any()) + .respond_with(wiremock::ResponseTemplate::new(200).set_body_string("")) + .mount(&server) + .await; + let decode = reqwest::get(server.uri()) + .await + .unwrap() + .json::() + .await + .map_err(anyhow::Error::from) + .context("Auth service returned non-JSON data") + .unwrap_err(); + let class = classify(&decode); + assert_eq!(class.code, "api_bad_response"); + assert_eq!(class.exit_code, exit_code::API_SERVER); + + let unreachable = reqwest::get("http://127.0.0.1:1") + .await + .map_err(anyhow::Error::from) + .unwrap_err(); + assert_eq!(classify(&unreachable).code, "network_error"); + + let missing = wiremock::MockServer::start().await; + let status = reqwest::get(format!("{}/repos/x/y", missing.uri())) + .await + .unwrap() + .error_for_status() + .map_err(anyhow::Error::from) + .unwrap_err(); + assert_ne!(classify(&status).code, "network_error"); + } + + #[test] + fn classify_io_and_client_errors() { + let io: anyhow::Error = std::io::Error::other("disk full").into(); + assert_eq!(classify(&io).code, "io_error"); + let device: anyhow::Error = + crate::api::client::ApiError::DeviceAuth(anyhow::anyhow!("expired")).into(); + assert_eq!(classify(&device).code, "device_auth_failed"); + } + + #[test] + fn classify_gone_as_not_found() { + let err: anyhow::Error = crate::api::client::ApiError::RequestFailed { + status: 410, + message: std::borrow::Cow::Borrowed("Gone"), + body: None, + } + .into(); + let class = classify(&err); + assert_eq!(class.code, "not_found"); + assert_eq!(class.telemetry, "api_not_found"); + } } diff --git a/tests/browser_commands.rs b/tests/browser_commands.rs index 3ea1040..83e0835 100644 --- a/tests/browser_commands.rs +++ b/tests/browser_commands.rs @@ -828,3 +828,174 @@ async fn batch_sends_one_request() { ); assert_eq!(cli.state("s").unwrap()["snapshot"]["compact"], true); } + +async fn session_bodies(server: &MockServer) -> Vec { + server + .received_requests() + .await + .unwrap() + .into_iter() + .filter(|r| r.method.as_str() == "POST" && r.url.path() == "/v1/sessions") + .map(|r| serde_json::from_slice(&r.body).unwrap()) + .collect() +} + +async fn refuse_captcha(server: &MockServer, code: &str) { + Mock::given(method("POST")) + .and(path("/v1/sessions")) + .and(body_partial_json(json!({"solveCaptcha": true}))) + .respond_with(ResponseTemplate::new(400).set_body_json(json!({ + "error": "Bad Request", + "code": code, + "message": "Captcha solving is not available on the hobby plan.", + "param": "solveCaptcha" + }))) + .with_priority(1) + .mount(server) + .await; +} + +async fn accept_sessions(server: &MockServer) { + Mock::given(method("POST")) + .and(path("/v1/sessions")) + .respond_with(ResponseTemplate::new(200).set_body_json(session_json())) + .with_priority(2) + .mount(server) + .await; +} + +#[tokio::test] +async fn stealth_starts_without_captcha_when_the_plan_refuses_it() { + for code in ["plan_feature_unavailable", "deposit_required"] { + let server = MockServer::start().await; + refuse_captcha(&server, code).await; + accept_sessions(&server).await; + let cli = Cli::new(&server); + + let started = cli.run(&["browser", "start", "--stealth"]).await; + assert!(started.status.success(), "{started:?}"); + let out = json_out(&started); + assert_eq!(out["data"]["id"], ID); + assert!( + out["data"]["notes"][0] + .as_str() + .is_some_and(|note| note.contains("without CAPTCHA solving")) + ); + assert!(String::from_utf8_lossy(&started.stderr).contains("without CAPTCHA solving")); + let bodies = session_bodies(&server).await; + assert_eq!(bodies.len(), 2); + assert_eq!(bodies[0]["solveCaptcha"], true); + assert!(bodies[1].get("solveCaptcha").is_none()); + assert_eq!( + bodies[1]["stealthConfig"], + json!({"humanizeInteractions": true}) + ); + } +} + +#[tokio::test] +async fn an_explicit_captcha_request_is_never_dropped() { + let server = MockServer::start().await; + refuse_captcha(&server, "plan_feature_unavailable").await; + accept_sessions(&server).await; + let cli = Cli::new(&server); + + let refused = cli + .run(&["browser", "start", "--stealth", "--solve-captcha"]) + .await; + assert!(!refused.status.success()); + assert_eq!(json_out(&refused)["error_code"], "request_failed"); + assert_eq!(session_bodies(&server).await.len(), 1); + assert!(cli.state("default").is_none()); +} + +#[tokio::test] +async fn proxy_takes_a_url_and_residential_means_a_steel_proxy() { + let server = MockServer::start().await; + accept_sessions(&server).await; + let cli = Cli::new(&server); + + let aliased = cli + .run(&["browser", "start", "--proxy", "residential"]) + .await; + assert!(aliased.status.success(), "{aliased:?}"); + assert!( + json_out(&aliased)["data"]["notes"][0] + .as_str() + .is_some_and(|note| note.contains("--use-proxy")) + ); + + let steel = cli.run(&["browser", "start", "--use-proxy"]).await; + assert!(steel.status.success(), "{steel:?}"); + + let own = cli + .run(&[ + "browser", + "start", + "-p", + "http://user:pass@proxy.example:8080", + ]) + .await; + assert!(own.status.success(), "{own:?}"); + + let bodies = session_bodies(&server).await; + assert_eq!(bodies.len(), 3); + assert_eq!(bodies[0]["useProxy"], true); + assert!(bodies[0].get("proxyUrl").is_none()); + assert_eq!(bodies[1]["useProxy"], true); + assert_eq!(bodies[2]["proxyUrl"], "http://user:pass@proxy.example:8080"); + assert!(bodies[2].get("useProxy").is_none()); + + for value in ["proxy.example:8080", "not a url"] { + let invalid = cli.run(&["browser", "start", "--proxy", value]).await; + assert_eq!(json_out(&invalid)["error_code"], "invalid_input", "{value}"); + } + assert_eq!(session_bodies(&server).await.len(), 3); +} + +#[tokio::test] +async fn project_comes_from_the_flag_or_steel_project_id() { + let server = MockServer::start().await; + accept_sessions(&server).await; + let cli = Cli::new(&server); + + let flagged = cli.run(&["browser", "start", "--project", "p-flag"]).await; + assert!(flagged.status.success(), "{flagged:?}"); + + let from_env = cli + .command(cli.config.path(), &["browser", "start"]) + .env("STEEL_PROJECT_ID", "p-env") + .output() + .await + .unwrap(); + assert!(from_env.status.success(), "{from_env:?}"); + + let bodies = session_bodies(&server).await; + assert_eq!(bodies[0]["projectId"], "p-flag"); + assert_eq!(bodies[1]["projectId"], "p-env"); +} + +#[tokio::test] +async fn an_organization_key_without_a_project_points_at_the_project_option() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/v1/sessions")) + .respond_with(ResponseTemplate::new(400).set_body_json(json!({ + "error": "Bad Request", + "code": "project_required", + "message": "This API key is scoped to the whole organization, so it binds to no project. Pass projectId to say which project this request is for.", + "param": "projectId" + }))) + .mount(&server) + .await; + let cli = Cli::new(&server); + + let refused = cli.run(&["browser", "start"]).await; + let out = json_out(&refused); + assert_eq!(out["error_code"], "request_failed"); + assert!( + out["hint"] + .as_str() + .is_some_and(|hint| hint.contains("--project")) + ); +} diff --git a/tests/cli_blackbox.rs b/tests/cli_blackbox.rs index 2cf5df7..98faf94 100644 --- a/tests/cli_blackbox.rs +++ b/tests/cli_blackbox.rs @@ -23,11 +23,49 @@ fn steel_cmd() -> (Command, tempfile::TempDir) { cmd.env("STEEL_CONFIG_DIR", tmp.path()); cmd.env("STEEL_TELEMETRY_DISABLED", "1"); cmd.env_remove("STEEL_API_KEY"); + cmd.env("STEEL_AUTH_ISSUER", "http://127.0.0.1:1"); + for name in [ + "CI", + "GITHUB_ACTIONS", + "GITLAB_CI", + "BUILDKITE", + "CIRCLECI", + "JENKINS_URL", + "TF_BUILD", + "TEAMCITY_VERSION", + "BITBUCKET_BUILD_NUMBER", + "CODEBUILD_BUILD_ID", + ] { + cmd.env_remove(name); + } // Suppress update checks so they don't interfere with output cmd.arg("--no-update-check"); (cmd, tmp) } +async fn device_issuer() -> MockServer { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/auth/device/code")) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "device_code": "private-device-fixture", + "user_code": "ABCD2345", + "verification_uri": format!("{}/device", server.uri()), + "verification_uri_complete": format!("{}/device?user_code=ABCD2345", server.uri()), + "expires_in": 600, + "interval": 5, + }))) + .mount(&server) + .await; + server +} + +async fn run_signed_out(issuer: &MockServer, args: &[&str]) -> Output { + let (mut cmd, _tmp) = steel_cmd(); + cmd.env("STEEL_AUTH_ISSUER", issuer.uri()).args(args); + tokio::process::Command::from(cmd).output().await.unwrap() +} + /// Convenience: run steel with the given args and return the Output. fn run(args: &[&str]) -> Output { let (mut cmd, _tmp) = steel_cmd(); @@ -473,64 +511,76 @@ fn nonexistent_command_fails() { } #[test] -fn browser_start_without_auth_or_local_fails() { - // With no API key and no --local flag, `browser start` should fail - // with the missing API key error, not a generic timeout. +fn browser_start_without_auth_fails_fast_when_sign_in_is_unreachable() { let start = std::time::Instant::now(); - let output = run(&["browser", "start"]); + let output = run(&["--json", "browser", "start"]); let elapsed = start.elapsed(); + assert_eq!(output.status.code(), Some(3), "{output:?}"); + let parsed: serde_json::Value = serde_json::from_str(stdout(&output).trim()).unwrap(); + assert_eq!(parsed["error_code"], "device_auth_failed"); assert!( - !output.status.success(), - "steel browser start without auth should exit non-zero" - ); - - let err = stderr(&output); - let out = stdout(&output); - let combined = format!("{err}{out}"); - let lower = combined.to_lowercase(); - - // The error should surface the actual failure reason (missing API key). - assert!( - lower.contains("api key") || lower.contains("api_key") || lower.contains("login"), - "output should mention the actual auth error (API key / login), got: {combined}" + parsed["error"] + .as_str() + .unwrap() + .contains("Not signed in to Steel"), + "{parsed}" ); - assert!( elapsed.as_secs() < 15, "should fail quickly, but took {elapsed:?}" ); } -#[test] -fn piped_output_is_text_unless_json_is_passed() { - let text = run(&["scrape", "https://example.com"]); - assert!(!text.status.success()); +#[tokio::test] +async fn piped_output_is_text_unless_json_is_passed() { + let issuer = device_issuer().await; + let text = run_signed_out(&issuer, &["scrape", "https://example.com"]).await; + assert_eq!(text.status.code(), Some(3)); assert!(stdout(&text).is_empty(), "got: {}", stdout(&text)); - assert!(stderr(&text).contains("Error: Missing Steel API key")); + let err = stderr(&text); + assert!( + err.contains(&format!( + "Error: Not signed in to Steel. Open {}/device?user_code=ABCD2345 in a browser and approve code ABCD2345", + issuer.uri() + )), + "{err}" + ); + assert!(err.contains("run this command again"), "{err}"); + assert!(err.contains("Hint: "), "{err}"); - let json = run(&["--json", "scrape", "https://example.com"]); + let json = run_signed_out(&issuer, &["--json", "scrape", "https://example.com"]).await; let parsed: serde_json::Value = serde_json::from_str(stdout(&json).trim()).unwrap(); assert_eq!(parsed["error_code"], "auth_required"); } -#[test] -fn browser_start_without_auth_json_mode_surfaces_error() { - // In --json mode, the actual error should also appear in the output. - let output = run(&["--json", "browser", "start"]); - assert!(!output.status.success()); +#[tokio::test] +async fn browser_start_without_auth_json_mode_hands_off_sign_in() { + let issuer = device_issuer().await; + let output = run_signed_out(&issuer, &["--json", "browser", "start"]).await; + assert_eq!(output.status.code(), Some(3)); let out = stdout(&output); let parsed: serde_json::Value = serde_json::from_str(out.trim()) .unwrap_or_else(|_| panic!("expected valid JSON, got: {out}")); assert_eq!(parsed["success"], false); - - let error_msg = parsed["error"].as_str().unwrap_or(""); - let lower = error_msg.to_lowercase(); + assert_eq!(parsed["error_code"], "auth_required"); + let login = &parsed["data"]["login"]; + assert_eq!(login["status"], "pending"); + assert_eq!( + login["verificationUrl"], + format!("{}/device?user_code=ABCD2345", issuer.uri()) + ); + assert_eq!(login["userCode"], "ABCD2345"); + assert!(login["expiresAt"].is_string(), "{login}"); + assert!(login["expiresInSeconds"].as_u64().unwrap() <= 600); assert!( - lower.contains("api key") || lower.contains("api_key") || lower.contains("login"), - "JSON error should mention the actual auth error, got: {error_msg}" + parsed["error"] + .as_str() + .unwrap() + .contains("run this command again") ); + assert!(!out.contains("private-device-fixture")); } #[test] diff --git a/tests/cli_compat.rs b/tests/cli_compat.rs index 6cddf4e..c2a8bf9 100644 --- a/tests/cli_compat.rs +++ b/tests/cli_compat.rs @@ -293,6 +293,8 @@ fn browser_start_flags() { &[ flag("stealth"), flag_val_short("proxy", 'p'), + flag("use-proxy"), + flag_val("project"), flag_val("timeout"), flag_val("inactivity-timeout"), flag("solve-captcha"), diff --git a/tests/device_auth.rs b/tests/device_auth.rs index ae8553c..a2eca87 100644 --- a/tests/device_auth.rs +++ b/tests/device_auth.rs @@ -17,9 +17,25 @@ fn command(home: &std::path::Path) -> Command { .env_remove("STEEL_AUTH_ISSUER") .env_remove("STEEL_AUTH_AUDIENCE") .args(["--no-update-check", "--json"]); + for name in CI_ENV_VARS { + command.env_remove(name); + } command } +const CI_ENV_VARS: &[&str] = &[ + "CI", + "GITHUB_ACTIONS", + "GITLAB_CI", + "BUILDKITE", + "CIRCLECI", + "JENKINS_URL", + "TF_BUILD", + "TEAMCITY_VERSION", + "BITBUCKET_BUILD_NUMBER", + "CODEBUILD_BUILD_ID", +]; + fn state(home: &std::path::Path, issuer: &str, transport: &str, expires: u64) { let file = home.join("auth.json"); std::fs::write(&file,serde_json::to_vec(&json!({"settings":{"issuer":issuer,"audience":"https://resource.example.test","api_base_url":transport},"installation_id":"synthetic-installation","pending":null,"tokens":{"access_token":"old-access-fixture","refresh_token":"old-refresh-fixture","expires_at":expires}})).unwrap()).unwrap(); @@ -425,3 +441,134 @@ async fn device_code_token_and_revoke_endpoints_never_follow_redirects() { assert!(home.path().join("auth.json").exists()); } } + +fn signed_out(home: &std::path::Path, issuer: &str) -> Command { + let mut command = command(home); + command + .env("STEEL_AUTH_ISSUER", issuer) + .env("HTTPS_PROXY", "http://127.0.0.1:1") + .env("https_proxy", "http://127.0.0.1:1") + .env_remove("NO_PROXY") + .env_remove("no_proxy"); + command +} + +fn json_result(output: &Output) -> Value { + serde_json::from_slice(&output.stdout).unwrap_or_else(|_| panic!("{}", text(output))) +} + +#[tokio::test] +async fn commands_without_credentials_hand_off_sign_in_and_continue_after_approval() { + let home = tempfile::tempdir().unwrap(); + let auth = MockServer::start().await; + device(&auth).await; + + let first = signed_out(home.path(), &auth.uri()) + .args(["browser", "start"]) + .output() + .unwrap(); + assert_eq!(first.status.code(), Some(3), "{}", text(&first)); + let result = json_result(&first); + assert_eq!(result["error_code"], "auth_required"); + assert_eq!( + result["data"]["login"]["verificationUrl"], + format!("{}/device?user_code=ABCD2345", auth.uri()) + ); + let saved: Value = + serde_json::from_slice(&std::fs::read(home.path().join("auth.json")).unwrap()).unwrap(); + assert!(saved["tokens"].is_null()); + assert!(!saved["pending"].is_null()); + + Mock::given(method("POST")) + .and(path("/api/auth/oauth2/token")) + .and(body_string_contains("device_code=private-device-fixture")) + .respond_with( + ResponseTemplate::new(400).set_body_json(json!({"error":"authorization_pending"})), + ) + .up_to_n_times(1) + .expect(1) + .mount(&auth) + .await; + std::thread::sleep(std::time::Duration::from_millis(1100)); + let pending = signed_out(home.path(), &auth.uri()) + .args(["scrape", "https://example.com"]) + .output() + .unwrap(); + assert_eq!(pending.status.code(), Some(3), "{}", text(&pending)); + let result = json_result(&pending); + assert_eq!(result["error_code"], "auth_required"); + assert_eq!(result["data"]["login"]["userCode"], "ABCD2345"); + + Mock::given(method("POST")) + .and(path("/api/auth/oauth2/token")) + .and(body_string_contains("device_code=private-device-fixture")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"access_token":"new-access-fixture","refresh_token":"new-refresh-fixture","expires_in":600,"token_type":"Bearer"}))) + .expect(1) + .mount(&auth) + .await; + std::thread::sleep(std::time::Duration::from_millis(1100)); + let approved = signed_out(home.path(), &auth.uri()) + .args(["browser", "start"]) + .output() + .unwrap(); + let result = json_result(&approved); + assert_eq!(result["error_code"], "unreachable", "{}", text(&approved)); + assert!(!text(&approved).contains("new-access-fixture")); + let saved: Value = + serde_json::from_slice(&std::fs::read(home.path().join("auth.json")).unwrap()).unwrap(); + assert_eq!(saved["tokens"]["access_token"], "new-access-fixture"); + assert!(saved["pending"].is_null()); +} + +#[tokio::test] +async fn api_keys_and_other_transports_never_start_a_device_login() { + let home = tempfile::tempdir().unwrap(); + let auth = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/api/auth/device/code")) + .respond_with(ResponseTemplate::new(500)) + .expect(0) + .mount(&auth) + .await; + + let keyed = signed_out(home.path(), &auth.uri()) + .env("STEEL_API_KEY", "sk-test") + .args(["browser", "start"]) + .output() + .unwrap(); + assert_eq!(json_result(&keyed)["error_code"], "unreachable"); + + let other = signed_out(home.path(), &auth.uri()) + .args(["--api-url", "http://127.0.0.1:1/v1", "browser", "start"]) + .output() + .unwrap(); + assert_eq!(json_result(&other)["error_code"], "unreachable"); + + let other_cloud = signed_out(home.path(), &auth.uri()) + .args([ + "--api-url", + "https://api.staging.steel.dev/v1", + "browser", + "start", + ]) + .output() + .unwrap(); + let other_cloud = json_result(&other_cloud); + assert_eq!(other_cloud["error_code"], "auth_required"); + assert!(other_cloud["data"].is_null()); + + let ci = signed_out(home.path(), &auth.uri()) + .env("CI", "true") + .args(["browser", "start"]) + .output() + .unwrap(); + let ci = json_result(&ci); + assert_eq!(ci["error_code"], "auth_required"); + assert!(ci["data"].is_null()); + assert!( + ci["error"] + .as_str() + .is_some_and(|error| error.contains("STEEL_API_KEY")) + ); + assert!(!home.path().join("auth.json").exists()); +}