From 0988edb78852f6ee4c18a074bd2a10db29ab025f Mon Sep 17 00:00:00 2001 From: neng Date: Mon, 16 Nov 2026 11:48:25 +0800 Subject: [PATCH] feat: add OPS login to browser-cli --- README.md | 24 +++ src/client.rs | 21 ++- src/lib.rs | 1 + src/main.rs | 160 +++++++++++++++++ src/ops.rs | 471 ++++++++++++++++++++++++++++++++++++++++++++++++++ tests/ops.rs | 194 +++++++++++++++++++++ 6 files changed, 868 insertions(+), 3 deletions(-) create mode 100644 src/ops.rs create mode 100644 tests/ops.rs diff --git a/README.md b/README.md index ed99b9b..7f28f42 100644 --- a/README.md +++ b/README.md @@ -299,3 +299,27 @@ Tencent Cloud COS through the `cos-release` GitHub environment. It requires `TENCENT_CLOUD_SECRET_ID` and `TENCENT_CLOUD_SECRET_KEY` secrets plus `COS_BUCKET`, `COS_REGION`, `COS_PUBLIC_BASE_URL`, and `COS_OBJECT_PREFIX` variables. + +## OPS website login + +Use a project API key and a project with an active OPS credential connection. +Choose the Chrome image configured for the target environment. + +```sh +browser-cli ops connections +browser-cli ops items --connection-id CONNECTION --site-origin https://example.com +browser-cli ops session --custom-image-id IMAGE +browser-cli ops start --session-id SESSION --connection-id CONNECTION --site-origin https://example.com +browser-cli ops wait --task-id TASK +``` + +Add both `--vault-id` and `--item-id` to `ops start` when account selection is +required. To retry an explicit start after an uncertain response, use the same +`--idempotency-key`, session, connection, site, and item. Without a key, each +invocation starts a new login intent. + +If the task state is `awaiting_user`, run `browser-cli ops verify --task-id TASK`, +complete verification in the browser, then run `browser-cli ops resume --task-id TASK` +and wait again. `ops get` reads the current state, and `ops cancel` requests +cancellation. Close the session with `browser-cli session close --session-id SESSION` +when you finish using it. diff --git a/src/client.rs b/src/client.rs index e460187..c2d29ad 100644 --- a/src/client.rs +++ b/src/client.rs @@ -96,17 +96,22 @@ impl ClientBuilder { base_url, region, http, + ops_http: HttpClient::builder() + .timeout(self.timeout) + .redirect(reqwest::redirect::Policy::none()) + .build()?, }) } } #[derive(Debug, Clone)] pub struct Client { - api_key: String, + pub(crate) api_key: String, project_id: String, base_url: String, region: Option, http: HttpClient, + pub(crate) ops_http: HttpClient, } impl Client { @@ -123,7 +128,7 @@ impl Client { &self.base_url } - fn body_with_region(&self, mut body: Value) -> Value { + pub(crate) fn body_with_region(&self, mut body: Value) -> Value { if let (Some(region), Some(object)) = (&self.region, body.as_object_mut()) { object.insert("region_id".into(), Value::String(region.clone())); } @@ -259,6 +264,15 @@ impl Client { if let Some(region) = region { body["region_id"] = region["region_id"].clone(); } + self.create_session_from_body(body, poll_timeout, true) + } + + pub(crate) fn create_session_from_body( + &self, + body: Value, + poll_timeout: Duration, + hydrate: bool, + ) -> Result { let accepted: Value = self.json(Method::POST, "/instance/v2", Some(body))?; let session_id = accepted .get("session_id") @@ -272,7 +286,8 @@ impl Client { loop { let session = self.get_session(session_id)?; match session.status.as_str() { - "active" => return self.hydrate_ws(session), + "active" if hydrate => return self.hydrate_ws(session), + "active" => return Ok(session), "create_failed" => { return Err(Error::Api { status: 500, diff --git a/src/lib.rs b/src/lib.rs index 5123849..52f8c49 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ pub mod cdp; pub mod client; pub mod error; pub mod models; +pub mod ops; pub mod tunnels; pub use client::{Client, ClientBuilder}; diff --git a/src/main.rs b/src/main.rs index c501857..fe00540 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,6 +10,7 @@ use lexmount_browser::{ Client, Error, Result, auth, cdp::{Cdp, WaitTextOptions}, models::CreateSession, + ops::{CreateLogin, LoginItemRef}, }; use serde_json::{Value, json}; @@ -41,6 +42,11 @@ enum Command { #[command(subcommand)] command: SessionCommand, }, + /// Start and manage OPS website login tasks. + Ops { + #[command(subcommand)] + command: OpsCommand, + }, Context { #[command(subcommand)] command: ContextCommand, @@ -130,6 +136,74 @@ enum SessionCommand { }, } +#[derive(Subcommand)] +enum OpsCommand { + /// Create a fresh OPS Chrome session using an explicit image. + Session { + #[arg(long)] + custom_image_id: String, + #[arg(long, default_value_t = 85)] + timeout_seconds: u64, + }, + /// List credential connections for the project. + Connections { + #[command(flatten)] + page: OpsPage, + }, + /// List credential items matching a website origin. + Items { + #[arg(long)] + connection_id: String, + #[arg(long)] + site_origin: String, + #[command(flatten)] + page: OpsPage, + }, + /// Start a login using the only match or an explicitly selected item. + Start { + #[arg(long)] + session_id: String, + #[arg(long)] + connection_id: String, + #[arg(long)] + site_origin: String, + #[arg(long, requires = "item_id")] + vault_id: Option, + #[arg(long, requires = "vault_id")] + item_id: Option, + /// Retry a start request with the same key and explicit item. + #[arg(long, requires_all = ["vault_id", "item_id"])] + idempotency_key: Option, + }, + Get(OpsTask), + /// Wait for completion or a request for manual verification. + Wait { + #[command(flatten)] + task: OpsTask, + #[arg(long, default_value_t = 120)] + timeout_seconds: u64, + }, + /// Open the manual verification page. + Verify(OpsTask), + /// Resume after completing manual verification in the browser. + Resume(OpsTask), + Cancel(OpsTask), +} + +#[derive(Args)] +struct OpsPage { + #[arg(long)] + cursor: Option, + #[arg(long, default_value_t = 50)] + limit: u8, +} + +#[derive(Args)] +struct OpsTask { + #[arg(long)] + task_id: String, +} + #[derive(Subcommand)] enum DownloadsCommand { List { @@ -408,6 +482,7 @@ fn run(cli: Cli) -> Result { } } Command::Session { command } => run_session(Client::from_env()?, command), + Command::Ops { command } => run_ops(Client::from_env()?, command), Command::Context { command } => run_context(Client::from_env()?, command), Command::Action { command, target_id } => { run_action(Client::from_env()?, command, target_id.as_deref()) @@ -549,6 +624,91 @@ fn run_session(client: Client, command: SessionCommand) -> Result { } } +fn run_ops(client: Client, command: OpsCommand) -> Result { + let task = match command { + OpsCommand::Session { + custom_image_id, + timeout_seconds, + } => { + let session = client + .create_ops_session(&custom_image_id, Duration::from_secs(timeout_seconds))?; + return Ok(json!({ + "session_id": session.session_id, + "status": session.status, + "region_id": session.region_id, + "requested_image": custom_image_id, + })); + } + OpsCommand::Connections { page } => { + return Ok(serde_json::to_value(client.list_credential_connections( + page.cursor.as_deref(), + page.limit, + )?)?); + } + OpsCommand::Items { + connection_id, + site_origin, + page, + } => { + return Ok(serde_json::to_value(client.list_login_items( + &connection_id, + &site_origin, + page.cursor.as_deref(), + page.limit, + )?)?); + } + OpsCommand::Start { + session_id, + connection_id, + site_origin, + vault_id, + item_id, + idempotency_key, + } => client.create_login_task(CreateLogin { + session_id: &session_id, + connection_id: &connection_id, + site_origin: &site_origin, + item: vault_id + .zip(item_id) + .map(|(vault_id, item_id)| LoginItemRef { vault_id, item_id }), + idempotency_key: idempotency_key.as_deref(), + })?, + OpsCommand::Get(task) => client.get_login_task(&task.task_id)?, + OpsCommand::Wait { + task, + timeout_seconds, + } => client.wait_for_login_task(&task.task_id, Duration::from_secs(timeout_seconds))?, + OpsCommand::Verify(task) => { + let task = client.get_login_task(&task.task_id)?; + let url = task + .requires_action + .as_ref() + .filter(|action| { + task.state == "awaiting_user" + && !task.cancel_requested + && action.kind == "manual_verification" + }) + .and_then(|action| action.open_url.as_deref()) + .and_then(|url| url::Url::parse(url).ok()) + .filter(|url| { + url.scheme() == "https" + && url.host().is_some() + && url.username().is_empty() + && url.password().is_none() + }) + .ok_or_else(|| { + Error::Config("OPS task has no available manual verification page".into()) + })?; + open::that(url.as_str()) + .map_err(|_| Error::Config("could not open OPS verification page".into()))?; + task + } + OpsCommand::Resume(task) => client.resume_login_task(&task.task_id)?, + OpsCommand::Cancel(task) => client.cancel_login_task(&task.task_id)?, + }; + Ok(serde_json::to_value(task)?) +} + fn run_context(client: Client, command: ContextCommand) -> Result { match command { ContextCommand::Create { diff --git a/src/ops.rs b/src/ops.rs new file mode 100644 index 0000000..8685c52 --- /dev/null +++ b/src/ops.rs @@ -0,0 +1,471 @@ +use std::{ + collections::HashSet, + thread, + time::{Duration, Instant}, +}; + +use reqwest::{Method, Url}; +use serde::{Deserialize, Serialize, de::DeserializeOwned}; +use serde_json::{Value, json}; + +use crate::{Client, Error, Result, Session}; + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct CredentialConnection { + pub id: String, + pub name: Option, + pub label: Option, + pub provider: Option, + pub status: Option, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ConnectionPage { + pub items: Vec, + pub next_cursor: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LoginItemRef { + pub vault_id: String, + pub item_id: String, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LoginItem { + #[serde(flatten)] + pub reference: LoginItemRef, + pub title: Option, + pub username_hint: Option, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LoginItemPage { + pub items: Vec, + pub next_cursor: Option, + pub connection_id: String, + pub enumeration_complete: bool, + pub site_match_complete: bool, + pub requires_explicit_selection: bool, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LoginTaskError { + pub code: Option, + pub phase: Option, + #[serde(default)] + pub retryable: bool, + pub trace_id: Option, +} + +#[derive(Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LoginAction { + #[serde(rename = "type")] + pub kind: String, + pub expires_at: Option, + #[serde(skip_serializing)] + pub open_url: Option, +} + +impl std::fmt::Debug for LoginAction { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("LoginAction") + .field("kind", &self.kind) + .field("expires_at", &self.expires_at) + .finish_non_exhaustive() + } +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LoginTask { + #[serde(alias = "taskId")] + pub id: String, + pub state: String, + pub phase: Option, + pub session_id: Option, + #[serde(default)] + pub cancel_requested: bool, + pub requires_action: Option, + pub error: Option, +} + +pub struct CreateLogin<'a> { + pub session_id: &'a str, + pub connection_id: &'a str, + pub site_origin: &'a str, + pub item: Option, + pub idempotency_key: Option<&'a str>, +} + +fn invalid_response() -> Error { + Error::Config("invalid OPS API response".into()) +} + +fn identifier(value: &str, field: &str) -> Result<()> { + if value.is_empty() + || value.len() > 256 + || matches!(value, "." | "..") + || !value + .bytes() + .all(|c| c.is_ascii_alphanumeric() || b"_.:-".contains(&c)) + { + return Err(Error::Config(format!("invalid {field}"))); + } + Ok(()) +} + +fn https_origin(value: &str) -> Result { + let url = + Url::parse(value).map_err(|_| Error::Config("expected an HTTPS site origin".into()))?; + if url.scheme() != "https" + || url.host().is_none() + || !url.username().is_empty() + || url.password().is_some() + || url.path() != "/" + || url.query().is_some() + || url.fragment().is_some() + || value.contains(['@', '\\']) + || value.trim() != value + { + return Err(Error::Config("expected an HTTPS site origin".into())); + } + Ok(url.origin().ascii_serialization()) +} + +fn page_query(cursor: Option<&str>, limit: u8) -> Result> { + if !(1..=100).contains(&limit) { + return Err(Error::Config( + "OPS page limit must be between 1 and 100".into(), + )); + } + let mut query = vec![("limit", limit.to_string())]; + if let Some(cursor) = cursor { + if cursor.is_empty() || cursor.chars().any(char::is_control) { + return Err(Error::Config("invalid OPS page cursor".into())); + } + query.push(("cursor", cursor.to_owned())); + } + Ok(query) +} + +impl Client { + fn ops_request( + &self, + method: Method, + path: &str, + query: &[(&str, String)], + body: Option, + key: Option<&str>, + timeout: Option, + ) -> Result { + let body_is_read = method == Method::GET; + let mut request = self + .ops_http + .request(method, format!("{}{path}", self.base_url())) + .header("x-api-key", &self.api_key) + .header("x-project-id", self.project_id()) + .header("accept", "application/json") + .query(query); + if let Some(body) = body { + request = request.json(&body); + } + if let Some(key) = key { + request = request.header("Idempotency-Key", key); + } + if let Some(timeout) = timeout { + request = request.timeout(timeout); + } + // Only reads and starts with a stable idempotency key are safe to retry. + let retries = if timeout.is_none() && (key.is_some() || body_is_read) { + 2 + } else { + 0 + }; + let mut retries_left = retries; + let response = loop { + if retries_left == 0 { + break request + .send() + .map_err(|error| Error::Http(error.without_url()))?; + } + match request.try_clone().ok_or_else(invalid_response)?.send() { + Ok(response) + if retries_left > 0 + && matches!(response.status().as_u16(), 429 | 502 | 503 | 504) => + { + let retry_after = response.headers().get("retry-after"); + let delay = retry_after + .map_or(Some(1), |header| header.to_str().ok()?.parse::().ok()); + let Some(delay @ 0..=5) = delay else { + break response; + }; + thread::sleep(Duration::from_secs(delay)); + } + Err(ref error) + if retries_left > 0 && (error.is_connect() || error.is_timeout()) => + { + thread::sleep(Duration::from_secs(1)); + } + Ok(response) => break response, + Err(error) => return Err(Error::Http(error.without_url())), + } + retries_left -= 1; + }; + let status = response.status(); + if !status.is_success() { + // Credential endpoints can return sensitive diagnostics in error bodies. + return Err(Error::Api { + status: status.as_u16(), + message: "OPS request rejected".into(), + body: None, + }); + } + let mut value: Value = response.json().map_err(|_| invalid_response())?; + redact(&mut value, &self.api_key); + if let Some(data) = value.get_mut("data") { + return serde_json::from_value(data.take()).map_err(|_| invalid_response()); + } + serde_json::from_value(value).map_err(|_| invalid_response()) + } + + pub fn create_ops_session(&self, image: &str, timeout: Duration) -> Result { + if image.trim().is_empty() || image.chars().any(char::is_whitespace) { + return Err(Error::Config( + "an explicit Chrome image is required for an OPS session".into(), + )); + } + let body = json!({ + "browser_mode": "normal", "custom_image_id": image, + "enable_lightmount_layout": false, "enable_lightmount_resource": false, + "enable_captcha": false, "downloads": {"enabled": false}, + "recording": {"persistent": false} + }); + self.create_session_from_body(self.body_with_region(body), timeout, false) + } + + pub fn list_credential_connections( + &self, + cursor: Option<&str>, + limit: u8, + ) -> Result { + self.ops_request( + Method::GET, + "/v1/credential-connections", + &page_query(cursor, limit)?, + None, + None, + None, + ) + } + + pub fn list_login_items( + &self, + connection_id: &str, + site_origin: &str, + cursor: Option<&str>, + limit: u8, + ) -> Result { + identifier(connection_id, "connection ID")?; + let mut query = page_query(cursor, limit)?; + query.push(("siteOrigin", https_origin(site_origin)?)); + let page: LoginItemPage = self.ops_request( + Method::GET, + &format!("/v1/credential-connections/{connection_id}/items"), + &query, + None, + None, + None, + )?; + if page.connection_id != connection_id { + return Err(invalid_response()); + } + Ok(page) + } + + pub fn create_login_task(&self, options: CreateLogin<'_>) -> Result { + identifier(options.session_id, "session ID")?; + identifier(options.connection_id, "connection ID")?; + let origin = https_origin(options.site_origin)?; + if let Some(item) = &options.item { + identifier(&item.vault_id, "vault ID")?; + identifier(&item.item_id, "item ID")?; + } + if options.idempotency_key.is_some() && options.item.is_none() { + return Err(Error::Config( + "an explicit OPS item is required when reusing an idempotency key".into(), + )); + } + let generated_key = format!("{:032x}", rand::random::()); + let key = options.idempotency_key.unwrap_or(&generated_key); + if key.trim().is_empty() || key.len() > 256 || !key.bytes().all(|c| (32..127).contains(&c)) + { + return Err(Error::Config("invalid idempotency key".into())); + } + let connection: CredentialConnection = self.ops_request( + Method::GET, + &format!("/v1/credential-connections/{}", options.connection_id), + &[], + None, + None, + None, + )?; + if connection.id != options.connection_id { + return Err(invalid_response()); + } + let name = connection + .name + .filter(|name| !name.trim().is_empty()) + .ok_or_else(invalid_response)?; + let item = self.select_login_item(options.connection_id, &origin, options.item.as_ref())?; + let task: LoginTask = self.ops_request( + Method::POST, + "/v1/login-tasks", + &[], + Some(json!({ + "sessionId": options.session_id, "name": name, "url": origin, + "vaultId": item.vault_id, "itemId": item.item_id, + })), + Some(key), + None, + )?; + if task.session_id.as_deref() != Some(options.session_id) { + return Err(invalid_response()); + } + identifier(&task.id, "returned login task ID")?; + Ok(task) + } + + fn select_login_item( + &self, + connection: &str, + origin: &str, + explicit: Option<&LoginItemRef>, + ) -> Result { + let mut cursor = None; + let mut seen_cursors = HashSet::new(); + let mut items = HashSet::new(); + let mut requires_explicit = false; + for _ in 0..20 { + let page = self.list_login_items(connection, origin, cursor.as_deref(), 50)?; + if !page.enumeration_complete || !page.site_match_complete { + break; + } + requires_explicit |= page.requires_explicit_selection; + for item in page.items { + identifier(&item.reference.vault_id, "returned vault ID")?; + identifier(&item.reference.item_id, "returned item ID")?; + items.insert(item.reference); + } + cursor = page.next_cursor; + match &cursor { + None => { + if let Some(explicit) = explicit { + return items.take(explicit).ok_or_else(|| { + Error::NotFound("selected OPS item does not match the site".into()) + }); + } + if requires_explicit || items.len() > 1 { + return Err(Error::Config( + "select an OPS account with --vault-id and --item-id".into(), + )); + } + return items + .into_iter() + .next() + .ok_or_else(|| Error::NotFound("no OPS item matches the site".into())); + } + Some(value) if !seen_cursors.insert(value.clone()) => break, + Some(_) => {} + } + } + Err(Error::Config("OPS item listing was incomplete".into())) + } + + fn request_login_task( + &self, + task_id: &str, + action: Option<&str>, + timeout: Option, + ) -> Result { + identifier(task_id, "login task ID")?; + let mut path = format!("/v1/login-tasks/{task_id}"); + if let Some(action) = action { + path.push('/'); + path.push_str(action); + } + let task: LoginTask = self.ops_request( + if action.is_some() { + Method::POST + } else { + Method::GET + }, + &path, + &[], + action.map(|_| json!({})), + None, + timeout, + )?; + if task.id != task_id { + return Err(invalid_response()); + } + Ok(task) + } + + pub fn get_login_task(&self, task_id: &str) -> Result { + self.request_login_task(task_id, None, None) + } + + pub fn resume_login_task(&self, task_id: &str) -> Result { + self.request_login_task(task_id, Some("resume"), None) + } + + pub fn cancel_login_task(&self, task_id: &str) -> Result { + self.request_login_task(task_id, Some("cancel"), None) + } + + pub fn wait_for_login_task(&self, task_id: &str, timeout: Duration) -> Result { + identifier(task_id, "login task ID")?; + let started = Instant::now(); + loop { + let remaining = timeout.saturating_sub(started.elapsed()); + if remaining.is_zero() { + return Err(Error::Timeout(format!("waiting for OPS task {task_id}"))); + } + let task = self.request_login_task( + task_id, + None, + Some(remaining.min(Duration::from_secs(10))), + )?; + match task.state.as_str() { + "succeeded" | "failed" | "cancelled" | "expired" => return Ok(task), + "awaiting_user" if !task.cancel_requested => return Ok(task), + "queued" | "running" | "awaiting_user" | "finalizing" => {} + _ => return Err(invalid_response()), + } + thread::sleep(Duration::from_secs(1).min(timeout.saturating_sub(started.elapsed()))); + } + } +} + +fn redact(value: &mut Value, secret: &str) { + if secret.is_empty() { + return; + } + match value { + Value::String(value) if value.contains(secret) => { + *value = value.replace(secret, "[REDACTED]") + } + Value::Array(items) => items.iter_mut().for_each(|item| redact(item, secret)), + Value::Object(fields) => fields.values_mut().for_each(|item| redact(item, secret)), + _ => {} + } +} diff --git a/tests/ops.rs b/tests/ops.rs new file mode 100644 index 0000000..13cb4ee --- /dev/null +++ b/tests/ops.rs @@ -0,0 +1,194 @@ +use std::time::Duration; + +use httpmock::{ + Method::{GET, POST}, + MockServer, +}; +use lexmount_browser::{ + Client, + ops::{CreateLogin, LoginTask}, +}; +use serde_json::json; + +const SITE: &str = "https://example.test"; + +fn client(server: &MockServer) -> Client { + Client::builder() + .api_key("fixture-api-key") + .project_id("project") + .base_url(server.base_url()) + .region("test-region") + .build() + .unwrap() +} + +#[test] +fn ops_session_uses_requested_image_and_isolation_compatible_options() { + let server = MockServer::start(); + let create = server.mock(|when, then| { + when.method(POST).path("/instance/v2").json_body(json!({ + "browser_mode":"normal", "custom_image_id":"registry.example.test/browser:test", + "enable_lightmount_layout":false, "enable_lightmount_resource":false, + "enable_captcha":false, "downloads":{"enabled":false}, + "recording":{"persistent":false}, "region_id":"test-region", + })); + then.status(202) + .json_body(json!({"session_id":"session-1"})); + }); + let poll = server.mock(|when, then| { + when.method(POST).path("/instance/session"); + then.json_body(json!({"session_id":"session-1","status":"active"})); + }); + let session = client(&server) + .create_ops_session("registry.example.test/browser:test", Duration::from_secs(3)) + .unwrap(); + assert_eq!(session.session_id, "session-1"); + create.assert_hits(1); + poll.assert_hits(1); +} + +#[test] +fn ops_selects_unique_item_across_pages_and_sends_deployed_request() { + let server = MockServer::start(); + let connection = server.mock(|when, then| { + when.method(GET) + .path("/v1/credential-connections/conn") + .header("x-api-key", "fixture-api-key") + .header("x-project-id", "project"); + then.json_body(json!({"id":"conn","name":"connection-name"})); + }); + let make_page = |items, next_cursor| { + json!({ + "items":items,"nextCursor":next_cursor,"connectionId":"conn", + "enumerationComplete":true,"siteMatchComplete":true,"requiresExplicitSelection":false, + }) + }; + server.mock(|when, then| { + when.method(GET) + .path("/v1/credential-connections/conn/items") + .query_param("siteOrigin", SITE) + .matches(|request| { + request + .query_params + .as_ref() + .is_none_or(|query| !query.iter().any(|(key, _)| key == "cursor")) + }); + then.json_body(make_page(json!([]), json!("opaque+/="))); + }); + let next = server.mock(|when, then| { + when.method(GET) + .path("/v1/credential-connections/conn/items") + .query_param("siteOrigin", SITE) + .query_param("cursor", "opaque+/="); + then.json_body(make_page( + json!([{"vaultId":"vault","itemId":"item"}]), + json!(null), + )); + }); + let mut create = server.mock(|when, then| { + when.method(POST) + .path("/v1/login-tasks") + .header_exists("Idempotency-Key") + .json_body(json!({ + "sessionId":"session-1", "name":"connection-name", "url":SITE, + "vaultId":"vault","itemId":"item", + })); + then.status(202).json_body( + json!({"data":{"taskId":"task-1","sessionId":"session-1","state":"queued"}}), + ); + }); + let task = client(&server) + .create_login_task(CreateLogin { + session_id: "session-1", + connection_id: "conn", + site_origin: SITE, + item: None, + idempotency_key: None, + }) + .unwrap(); + assert_eq!(task.id, "task-1"); + connection.assert_hits(1); + next.assert_hits(1); + create.assert_hits(1); + create.delete(); + + let unavailable = server.mock(|when, then| { + when.method(POST) + .path("/v1/login-tasks") + .header("Idempotency-Key", "same-intent") + .json_body(json!({ + "sessionId":"session-1", "name":"connection-name", "url":SITE, + "vaultId":"vault", "itemId":"item", + })); + then.status(504) + .header("Retry-After", "0") + .body("fixture-api-key"); + }); + let error = client(&server) + .create_login_task(CreateLogin { + session_id: "session-1", + connection_id: "conn", + site_origin: SITE, + item: Some(lexmount_browser::ops::LoginItemRef { + vault_id: "vault".into(), + item_id: "item".into(), + }), + idempotency_key: Some("same-intent"), + }) + .unwrap_err(); + assert!(error.to_string().contains("504")); + assert!(!format!("{error:?}").contains("fixture-api-key")); + unavailable.assert_hits(3); +} + +#[test] +fn ops_multiple_accounts_require_selection_without_submitting() { + let server = MockServer::start(); + server.mock(|when, then| { + when.method(GET).path("/v1/credential-connections/conn"); + then.json_body(json!({"id":"conn","name":"connection-name"})); + }); + server.mock(|when, then| { + when.method(GET) + .path("/v1/credential-connections/conn/items"); + then.json_body(json!({ + "connectionId":"conn", "enumerationComplete":true, "siteMatchComplete":true, + "requiresExplicitSelection":true, "nextCursor":null, + "items":[{"vaultId":"v","itemId":"i"},{"vaultId":"v","itemId":"j"}], + })); + }); + let create = server.mock(|when, then| { + when.method(POST).path("/v1/login-tasks"); + then.status(500); + }); + let error = client(&server) + .create_login_task(CreateLogin { + session_id: "session-1", + connection_id: "conn", + site_origin: SITE, + item: None, + idempotency_key: None, + }) + .unwrap_err(); + assert!(error.to_string().contains("select an OPS account")); + create.assert_hits(0); +} + +#[test] +fn ops_wait_returns_manual_verification_without_exporting_open_url() { + let server = MockServer::start(); + server.mock(|when, then| { + when.method(GET).path("/v1/login-tasks/task-1"); + then.json_body(json!({ + "id":"task-1","state":"awaiting_user","requiresAction":{ + "type":"manual_verification","openUrl":"https://example.test/secret-url" + }, + })); + }); + let task: LoginTask = client(&server) + .wait_for_login_task("task-1", Duration::from_secs(3)) + .unwrap(); + assert_eq!(task.state, "awaiting_user"); + assert!(!serde_json::to_string(&task).unwrap().contains("secret-url")); + assert!(!format!("{task:?}").contains("secret-url")); +}