Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(cua-cli): replace legacy auth with run device flow (#2311)

r33drichardsd3ca33ab0a86
diff --git a/libs/python/cua-cli/README.md b/libs/python/cua-cli/README.md
index fbec61f7bd..6417820a31 100644
--- a/libs/python/cua-cli/README.md
+++ b/libs/python/cua-cli/README.md
@@ -12,18 +12,10 @@ pip install cua-cli
```bash
# Authentication
-cua auth login # Authenticate via browser
-cua auth login --api-key # Authenticate with API key
-cua auth list # List authenticated workspaces
-cua auth status # Show auth status and credits
-cua auth logout # Remove active workspace credentials
-cua auth logout --workspace <slug> # Remove specific workspace
-cua auth logout --all # Remove all credentials
-cua auth env # Export API key to .env file
-
-# Workspace Management
-cua ws set <slug> # Switch active workspace
-cua ws set # Interactive workspace picker
+cua auth login # Authenticate with run.cua.ai device authorization
+cua auth login --no-browser # Print the verification URL without opening a browser
+cua auth status # Show local session status
+cua auth logout # Revoke the refresh token and remove local credentials
# Sandbox Management
cua sb list # List all sandboxes
@@ -101,8 +93,12 @@ Individual permissions: `sandbox:list`, `sandbox:create`, `sandbox:delete`, `san
## Environment Variables
-- `CUA_API_KEY`: API key for authentication
-- `CUA_API_BASE`: API base URL (default: `https://api.cua.ai`)
-- `CUA_WEBSITE_URL`: Website URL for OAuth (default: https://cua.ai)
+- Authentication uses OIDC device authorization discovered from `https://auth.cua.ai/realms/cyclops-cs`, while authenticated cloud requests use `https://run.cua.ai`. Tokens are stored in the operating system credential vault; the CLI does not read API keys from environment variables or write them to `.env` files.
- `CUA_MCP_PERMISSIONS`: Default MCP permissions (comma-separated)
- `CUA_SANDBOX`: Default sandbox name for computer commands
+
+## Cloud Authentication
+
+`cua auth login` uses the standard OAuth device authorization flow. It discovers Keycloak endpoints from `https://auth.cua.ai/realms/cyclops-cs`, while the short verification UI is served from `https://run.cua.ai/device`. The CLI prints a verification URL and code, so it also works over SSH or in CI-style terminals; use `--no-browser` to prevent an automatic browser attempt. Complete the verification in any browser, then return to the terminal while the CLI polls for approval.
+
+Access tokens refresh automatically before authenticated `run.cua.ai` requests. `cua auth logout` asks the issuer to revoke the refresh token and always removes the local credential-vault entry, even when the network is unavailable. The CLI never prints access or refresh tokens.
diff --git a/libs/python/cua-cli/cua_cli/api/client.py b/libs/python/cua-cli/cua_cli/api/client.py
index 772e357255..11a8c64f65 100644
--- a/libs/python/cua-cli/cua_cli/api/client.py
+++ b/libs/python/cua-cli/cua_cli/api/client.py
@@ -1,33 +1,24 @@
"""HTTP API client for CUA cloud services."""
import hashlib
-import os
from pathlib import Path
from typing import Any, Optional
from urllib.parse import quote
import aiohttp
-from cua_cli.auth.store import require_api_key
+from cua_cli.auth.oidc import DEFAULT_RUN_API_BASE, get_access_token
from cua_core.http import cua_version_headers
-DEFAULT_API_BASE = "https://api.cua.ai"
-
-
-def get_api_base() -> str:
- """Get the API base URL."""
- return os.environ.get("CUA_API_BASE", DEFAULT_API_BASE).rstrip("/")
-
class CloudAPIClient:
- """HTTP client for CUA cloud API."""
+ """HTTP client for authenticated run.cua.ai API requests."""
- def __init__(self, api_key: Optional[str] = None, api_base: Optional[str] = None):
- self.api_key = api_key or require_api_key()
- self.api_base = api_base or get_api_base()
+ def __init__(self, api_base: str = DEFAULT_RUN_API_BASE):
+ self.api_base = api_base.rstrip("/")
- def _headers(self) -> dict[str, str]:
+ async def _headers(self) -> dict[str, str]:
return {
- "Authorization": f"Bearer {self.api_key}",
+ "Authorization": f"Bearer {await get_access_token()}",
"Accept": "application/json",
**cua_version_headers(),
}
@@ -45,7 +36,7 @@ class CloudAPIClient:
Tuple of (status_code, response_data)
"""
url = f"{self.api_base}{path}"
- headers = self._headers()
+ headers = await self._headers()
if json is not None:
headers["Content-Type"] = "application/json"
diff --git a/libs/python/cua-cli/cua_cli/auth/__init__.py b/libs/python/cua-cli/cua_cli/auth/__init__.py
index 37aecc4370..51f1c18b14 100644
--- a/libs/python/cua-cli/cua_cli/auth/__init__.py
+++ b/libs/python/cua-cli/cua_cli/auth/__init__.py
@@ -1,5 +1,10 @@
-"""Authentication module for CUA CLI."""
+"""Authentication utilities for Cua CLI."""
-from .store import CredentialStore, clear_credentials, get_api_key, save_api_key
+from .store import (
+ OAuthCredentials,
+ clear_credentials,
+ load_credentials,
+ save_credentials,
+)
-__all__ = ["CredentialStore", "get_api_key", "save_api_key", "clear_credentials"]
+__all__ = ["OAuthCredentials", "clear_credentials", "load_credentials", "save_credentials"]
diff --git a/libs/python/cua-cli/cua_cli/auth/browser.py b/libs/python/cua-cli/cua_cli/auth/browser.py
deleted file mode 100644
index f9fcf6f167..0000000000
--- a/libs/python/cua-cli/cua_cli/auth/browser.py
+++ /dev/null
@@ -1,177 +0,0 @@
-"""Browser-based OAuth authentication for Cua CLI."""
-
-import asyncio
-import os
-import platform
-import subprocess
-import urllib.parse
-from dataclasses import dataclass
-from http.server import BaseHTTPRequestHandler, HTTPServer
-from threading import Thread
-from typing import Optional
-
-# Default URLs
-DEFAULT_WEBSITE_URL = "https://cua.ai"
-
-# Timeout for browser authentication (2 minutes)
-AUTH_TIMEOUT_SECONDS = 120
-
-
-@dataclass
-class AuthResult:
- """Result from browser authentication containing token and workspace metadata."""
-
- token: str
- workspace_slug: str
- workspace_name: str
- org_name: str
-
-
-class CallbackHandler(BaseHTTPRequestHandler):
- """HTTP request handler for OAuth callback."""
-
- token: Optional[str] = None
- workspace_slug: Optional[str] = None
- workspace_name: Optional[str] = None
- org_name: Optional[str] = None
- error: Optional[str] = None
-
- def do_GET(self) -> None:
- """Handle GET request from OAuth callback."""
- parsed = urllib.parse.urlparse(self.path)
- params = urllib.parse.parse_qs(parsed.query)
-
- if "token" in params:
- CallbackHandler.token = params["token"][0]
- CallbackHandler.workspace_slug = params.get("workspace_slug", [""])[0]
- CallbackHandler.workspace_name = params.get("workspace_name", [""])[0]
- CallbackHandler.org_name = params.get("org_name", [""])[0]
- self._send_response(
- 200,
- "<html><body><h1>Authentication successful!</h1>"
- "<p>You can close this window and return to the terminal.</p></body></html>",
- )
- elif "error" in params:
- CallbackHandler.error = params.get("error_description", params["error"])[0]
- self._send_response(
- 400,
- f"<html><body><h1>Authentication failed</h1>"
- f"<p>{CallbackHandler.error}</p></body></html>",
- )
- else:
- self._send_response(
- 400,
- "<html><body><h1>Invalid callback</h1>"
- "<p>Missing token parameter.</p></body></html>",
- )
-
- def _send_response(self, status: int, body: str) -> None:
- """Send an HTTP response."""
- self.send_response(status)
- self.send_header("Content-Type", "text/html")
- self.end_headers()
- self.wfile.write(body.encode())
-
- def log_message(self, format: str, *args) -> None:
- """Suppress default logging."""
- pass
-
-
-def open_browser(url: str) -> bool:
- """Open a URL in the default browser.
-
- Args:
- url: The URL to open
-
- Returns:
- True if the browser was opened successfully
- """
- system = platform.system()
-
- try:
- if system == "Darwin":
- subprocess.run(["open", url], check=True)
- elif system == "Windows":
- subprocess.run(["cmd", "/c", "start", url], check=True, shell=True)
- else: # Linux and others
- subprocess.run(["xdg-open", url], check=True)
- return True
- except (subprocess.SubprocessError, FileNotFoundError):
- return False
-
-
-async def authenticate_via_browser(
- website_url: Optional[str] = None,
- workspace_slug: Optional[str] = None,
-) -> AuthResult:
- """Authenticate via browser OAuth flow.
-
- Starts a local HTTP server to receive the callback, opens the browser
- to the authentication page, and waits for the token.
-
- Args:
- website_url: Base URL for the authentication page. Defaults to CUA_WEBSITE_URL
- env var or https://cua.ai
- workspace_slug: Optional workspace slug to pre-select in the browser
-
- Returns:
- AuthResult with token and workspace metadata
-
- Raises:
- TimeoutError: If authentication times out
- RuntimeError: If authentication fails
- """
- website_url = website_url or os.environ.get("CUA_WEBSITE_URL", DEFAULT_WEBSITE_URL)
-
- # Reset handler state
- CallbackHandler.token = None
- CallbackHandler.workspace_slug = None
- CallbackHandler.workspace_name = None
- CallbackHandler.org_name = None
- CallbackHandler.error = None
-
- # Start local server on dynamic port
- server = HTTPServer(("localhost", 0), CallbackHandler)
- port = server.server_address[1]
- callback_url = f"http://localhost:{port}"
-
- # Build auth URL
- encoded_callback = urllib.parse.quote(callback_url, safe="")
- auth_url = f"{website_url}/cli-auth?callback_url={encoded_callback}"
- if workspace_slug:
- auth_url += f"&workspace_slug={urllib.parse.quote(workspace_slug, safe='')}"
-
- # Start server in background thread
- server_thread = Thread(target=server.handle_request, daemon=True)
- server_thread.start()
-
- # Open browser
- print("Opening browser for authentication...")
- if not open_browser(auth_url):
- print("Could not open browser automatically.")
- print(f"Please visit: {auth_url}")
-
- # Wait for callback with timeout
- try:
- for _ in range(AUTH_TIMEOUT_SECONDS):
- if CallbackHandler.token or CallbackHandler.error:
- break
- await asyncio.sleep(1)
- else:
- raise TimeoutError("Authentication timed out. Please try again.")
-
- if CallbackHandler.error:
- raise RuntimeError(f"Authentication failed: {CallbackHandler.error}")
-
- if not CallbackHandler.token:
- raise RuntimeError("Authentication failed: No token received")
-
- return AuthResult(
- token=CallbackHandler.token,
- workspace_slug=CallbackHandler.workspace_slug or "",
- workspace_name=CallbackHandler.workspace_name or "",
- org_name=CallbackHandler.org_name or "",
- )
-
- finally:
- server.server_close()
diff --git a/libs/python/cua-cli/cua_cli/auth/oidc.py b/libs/python/cua-cli/cua_cli/auth/oidc.py
new file mode 100644
index 0000000000..5c94c0533a
--- /dev/null
+++ b/libs/python/cua-cli/cua_cli/auth/oidc.py
@@ -0,0 +1,240 @@
+"""OIDC device authorization and refresh support for run.cua.ai."""
+
+import asyncio
+import time
+from collections.abc import Awaitable, Callable, Mapping
+from dataclasses import dataclass
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import aiohttp
+from cua_cli.auth.store import OAuthCredentials, load_credentials, save_credentials
+
+DEFAULT_RUN_API_BASE = "https://run.cua.ai"
+DEFAULT_OIDC_ISSUER = "https://auth.cua.ai/realms/cyclops-cs"
+DEFAULT_CLIENT_ID = "cua-cli"
+DEFAULT_SCOPE = "openid profile offline_access"
+DEVICE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code"
+
+
+class OidcError(RuntimeError):
+ """Raised for an OIDC protocol or authorization failure."""
+
+
+HttpRequest = Callable[[str, str, Mapping[str, str] | None], Awaitable[tuple[int, dict[str, Any]]]]
+Sleep = Callable[[float], Awaitable[None]]
+
+
+@dataclass(frozen=True)
+class OidcDiscovery:
+ """Relevant endpoints published by OIDC discovery."""
+
+ token_endpoint: str
+ device_authorization_endpoint: str
+ revocation_endpoint: str | None
+
+ @classmethod
+ def from_response(cls, value: Mapping[str, Any]) -> "OidcDiscovery":
+ try:
+ return cls(
+ token_endpoint=str(value["token_endpoint"]),
+ device_authorization_endpoint=str(value["device_authorization_endpoint"]),
+ revocation_endpoint=(
+ str(value["revocation_endpoint"]) if value.get("revocation_endpoint") else None
+ ),
+ )
+ except (KeyError, TypeError) as error:
+ raise OidcError("OIDC issuer returned an incomplete discovery document.") from error
+
+
+@dataclass(frozen=True)
+class DeviceCode:
+ """A device authorization response."""
+
+ device_code: str
+ user_code: str
+ verification_uri: str
+ verification_uri_complete: str | None
+ expires_in: int
+ interval: int
+
+ @classmethod
+ def from_response(cls, value: Mapping[str, Any]) -> "DeviceCode":
+ try:
+ return cls(
+ device_code=str(value["device_code"]),
+ user_code=str(value["user_code"]),
+ verification_uri=str(value["verification_uri"]),
+ verification_uri_complete=(
+ str(value["verification_uri_complete"])
+ if value.get("verification_uri_complete")
+ else None
+ ),
+ expires_in=int(value["expires_in"]),
+ interval=max(1, int(value.get("interval", 5))),
+ )
+ except (KeyError, TypeError, ValueError) as error:
+ raise OidcError(
+ "OIDC issuer returned an invalid device authorization response."
+ ) from error
+
+
+async def _aiohttp_form_request(
+ method: str, url: str, form: Mapping[str, str] | None
+) -> tuple[int, dict[str, Any]]:
+ timeout = aiohttp.ClientTimeout(total=15)
+ headers = {"Accept": "application/json"}
+ async with aiohttp.ClientSession() as session:
+ async with session.request(
+ method, url, data=form, headers=headers, timeout=timeout
+ ) as response:
+ try:
+ payload = await response.json(content_type=None)
+ except (aiohttp.ClientError, ValueError):
+ payload = {"error_description": await response.text()}
+ if not isinstance(payload, dict):
+ payload = {"error_description": "OIDC server returned a non-object response."}
+ return response.status, payload
+
+
+class OidcClient:
+ """Minimal public-client OIDC implementation using standard OAuth grants."""
+
+ def __init__(
+ self,
+ oidc_issuer: str = DEFAULT_OIDC_ISSUER,
+ client_id: str = DEFAULT_CLIENT_ID,
+ scope: str = DEFAULT_SCOPE,
+ request: HttpRequest = _aiohttp_form_request,
+ sleep: Sleep = asyncio.sleep,
+ ) -> None:
+ self.oidc_issuer = oidc_issuer.rstrip("/")
+ self.client_id = client_id
+ self.scope = scope
+ self._request = request
+ self._sleep = sleep
+
+ async def discover(self) -> OidcDiscovery:
+ status, payload = await self._request(
+ "GET", f"{self.oidc_issuer}/.well-known/openid-configuration", None
+ )
+ if status != 200:
+ raise OidcError(f"OIDC discovery failed (HTTP {status}).")
+ return OidcDiscovery.from_response(payload)
+
+ async def request_device_code(self, discovery: OidcDiscovery) -> DeviceCode:
+ status, payload = await self._request(
+ "POST",
+ discovery.device_authorization_endpoint,
+ {"client_id": self.client_id, "scope": self.scope},
+ )
+ if status != 200:
+ raise OidcError(_error_description(payload, "Could not start device authorization."))
+ return DeviceCode.from_response(payload)
+
+ async def poll_for_tokens(
+ self, discovery: OidcDiscovery, device_code: DeviceCode
+ ) -> OAuthCredentials:
+ deadline = time.monotonic() + device_code.expires_in
+ interval = device_code.interval
+ while time.monotonic() < deadline:
+ status, payload = await self._request(
+ "POST",
+ discovery.token_endpoint,
+ {
+ "grant_type": DEVICE_GRANT_TYPE,
+ "device_code": device_code.device_code,
+ "client_id": self.client_id,
+ },
+ )
+ if status == 200:
+ return _credentials_from_token_response(payload)
+
+ error = payload.get("error")
+ if error == "authorization_pending":
+ await self._sleep(interval)
+ continue
+ if error == "slow_down":
+ interval += 5
+ await self._sleep(interval)
+ continue
+ if error in {"access_denied", "expired_token"}:
+ raise OidcError(
+ _error_description(payload, "Device authorization was not completed.")
+ )
+ raise OidcError(_error_description(payload, f"Token request failed (HTTP {status})."))
+ raise OidcError("Device authorization expired before it was completed.")
+
+ async def refresh(
+ self, discovery: OidcDiscovery, credentials: OAuthCredentials
+ ) -> OAuthCredentials:
+ if not credentials.refresh_token:
+ raise OidcError("Your session cannot be refreshed. Run 'cua auth login' again.")
+ status, payload = await self._request(
+ "POST",
+ discovery.token_endpoint,
+ {
+ "grant_type": "refresh_token",
+ "refresh_token": credentials.refresh_token,
+ "client_id": self.client_id,
+ },
+ )
+ if status != 200:
+ raise OidcError(
+ _error_description(payload, "Your session expired. Run 'cua auth login' again.")
+ )
+ refreshed = _credentials_from_token_response(payload)
+ if not refreshed.refresh_token:
+ refreshed = OAuthCredentials(
+ access_token=refreshed.access_token,
+ refresh_token=credentials.refresh_token,
+ expires_at=refreshed.expires_at,
+ token_type=refreshed.token_type,
+ scope=refreshed.scope,
+ )
+ return refreshed
+
+ async def revoke(self, discovery: OidcDiscovery, credentials: OAuthCredentials) -> bool:
+ if not discovery.revocation_endpoint:
+ return False
+ token = credentials.refresh_token or credentials.access_token
+ status, _payload = await self._request(
+ "POST",
+ discovery.revocation_endpoint,
+ {"token": token, "client_id": self.client_id},
+ )
+ return 200 <= status < 300
+
+
+def _credentials_from_token_response(payload: Mapping[str, Any]) -> OAuthCredentials:
+ try:
+ expires_in = int(payload["expires_in"])
+ access_token = str(payload["access_token"])
+ except (KeyError, TypeError, ValueError) as error:
+ raise OidcError("OIDC issuer returned an invalid token response.") from error
+ return OAuthCredentials(
+ access_token=access_token,
+ refresh_token=str(payload["refresh_token"]) if payload.get("refresh_token") else None,
+ expires_at=datetime.now(UTC) + timedelta(seconds=max(0, expires_in)),
+ token_type=str(payload.get("token_type", "Bearer")),
+ scope=str(payload["scope"]) if payload.get("scope") else None,
+ )
+
+
+def _error_description(payload: Mapping[str, Any], fallback: str) -> str:
+ description = payload.get("error_description") or payload.get("error")
+ return str(description) if description else fallback
+
+
+async def get_access_token() -> str:
+ """Return a valid access token, refreshing and persisting it when needed."""
+ credentials = load_credentials()
+ if credentials is None:
+ raise OidcError("Not logged in. Run 'cua auth login' first.")
+ if credentials.expires_at > datetime.now(UTC) + timedelta(seconds=60):
+ return credentials.access_token
+
+ client = OidcClient()
+ refreshed = await client.refresh(await client.discover(), credentials)
+ save_credentials(refreshed)
+ return refreshed.access_token
diff --git a/libs/python/cua-cli/cua_cli/auth/store.py b/libs/python/cua-cli/cua_cli/auth/store.py
index 177a9ecf83..6cbc6b5045 100644
--- a/libs/python/cua-cli/cua_cli/auth/store.py
+++ b/libs/python/cua-cli/cua_cli/auth/store.py
@@ -1,293 +1,98 @@
-"""SQLite-based credential storage for Cua CLI."""
+"""Secure credential storage for Cua CLI."""
-import os
-import sqlite3
-from pathlib import Path
-from typing import Optional
+import json
+from dataclasses import asdict, dataclass
+from datetime import UTC, datetime
+from typing import Any
-# Default storage location
-CUA_DIR = Path.home() / ".cua"
-CREDENTIALS_DB = CUA_DIR / "credentials.db"
+import keyring
+from keyring.errors import KeyringError, PasswordDeleteError
-# Key names
-API_KEY_NAME = "api_key"
+KEYRING_SERVICE = "run.cua.ai"
+KEYRING_ACCOUNT = "cua-cli"
-# Workspace key patterns
-ACTIVE_WORKSPACE_KEY = "active_workspace"
+class CredentialStorageError(RuntimeError):
+ """Raised when the operating system credential vault is unavailable."""
-class CredentialStore:
- """SQLite-based credential store with WAL mode for concurrent access."""
- def __init__(self, db_path: Path | None = None):
- """Initialize the credential store.
+@dataclass(frozen=True)
+class OAuthCredentials:
+ """OIDC tokens issued to the CLI's public client."""
- Args:
- db_path: Path to the SQLite database. Defaults to ~/.cua/credentials.db
- """
- self.db_path = db_path or CREDENTIALS_DB
- self._ensure_db()
+ access_token: str
+ refresh_token: str | None
+ expires_at: datetime
+ token_type: str = "Bearer"
+ scope: str | None = None
- def _ensure_db(self) -> None:
- """Ensure the database and table exist."""
- self.db_path.parent.mkdir(parents=True, exist_ok=True)
-
- conn = sqlite3.connect(self.db_path)
- try:
- # Enable WAL mode for better concurrent access
- conn.execute("PRAGMA journal_mode=WAL")
-
- # Create key-value table
- conn.execute("""
- CREATE TABLE IF NOT EXISTS kv (
- key TEXT PRIMARY KEY,
- value TEXT NOT NULL
- )
- """)
- conn.commit()
- finally:
- conn.close()
-
- def get(self, key: str) -> Optional[str]:
- """Get a value from the store.
-
- Args:
- key: The key to look up
-
- Returns:
- The value, or None if not found
- """
- conn = sqlite3.connect(self.db_path)
- try:
- cursor = conn.execute("SELECT value FROM kv WHERE key = ?", (key,))
- row = cursor.fetchone()
- return row[0] if row else None
- finally:
- conn.close()
-
- def set(self, key: str, value: str) -> None:
- """Set a value in the store.
-
- Args:
- key: The key to set
- value: The value to store
- """
- conn = sqlite3.connect(self.db_path)
+ @classmethod
+ def from_dict(cls, value: dict[str, Any]) -> "OAuthCredentials":
try:
- conn.execute(
- "INSERT OR REPLACE INTO kv (key, value) VALUES (?, ?)",
- (key, value),
+ expires_at = datetime.fromisoformat(value["expires_at"])
+ if expires_at.tzinfo is None:
+ raise ValueError("expires_at must include a timezone")
+ return cls(
+ access_token=str(value["access_token"]),
+ refresh_token=value.get("refresh_token"),
+ expires_at=expires_at.astimezone(UTC),
+ token_type=str(value.get("token_type", "Bearer")),
+ scope=value.get("scope"),
)
- conn.commit()
- finally:
- conn.close()
-
- def delete(self, key: str) -> bool:
- """Delete a value from the store.
-
- Args:
- key: The key to delete
-
- Returns:
- True if the key was deleted, False if it didn't exist
- """
- conn = sqlite3.connect(self.db_path)
- try:
- cursor = conn.execute("DELETE FROM kv WHERE key = ?", (key,))
- conn.commit()
- return cursor.rowcount > 0
- finally:
- conn.close()
-
- def delete_by_prefix(self, prefix: str) -> int:
- """Delete all keys matching a prefix.
-
- Args:
- prefix: The key prefix to match (uses LIKE prefix%)
-
- Returns:
- Number of rows deleted
- """
- conn = sqlite3.connect(self.db_path)
- try:
- cursor = conn.execute("DELETE FROM kv WHERE key LIKE ?", (prefix + "%",))
- conn.commit()
- return cursor.rowcount
- finally:
- conn.close()
-
- def list_by_prefix(self, prefix: str) -> list[tuple[str, str]]:
- """List all key-value pairs matching a prefix.
-
- Args:
- prefix: The key prefix to match (uses LIKE prefix%)
-
- Returns:
- List of (key, value) tuples
- """
- conn = sqlite3.connect(self.db_path)
- try:
- cursor = conn.execute("SELECT key, value FROM kv WHERE key LIKE ?", (prefix + "%",))
- return cursor.fetchall()
- finally:
- conn.close()
-
- def clear(self) -> None:
- """Clear all stored credentials."""
- conn = sqlite3.connect(self.db_path)
- try:
- conn.execute("DELETE FROM kv")
- conn.commit()
- finally:
- conn.close()
-
-
-# Module-level convenience functions
-_store: Optional[CredentialStore] = None
-
-
-def _get_store() -> CredentialStore:
- """Get the global credential store instance."""
- global _store
- if _store is None:
- _store = CredentialStore()
- return _store
-
-
-def save_workspace(slug: str, api_key: str, name: str, org: str) -> None:
- """Save workspace credentials and metadata."""
- store = _get_store()
- store.set(f"workspace:{slug}:api_key", api_key)
- store.set(f"workspace:{slug}:name", name)
- store.set(f"workspace:{slug}:org", org)
-
-
-def get_active_workspace() -> Optional[str]:
- """Get the slug of the currently active workspace."""
- return _get_store().get(ACTIVE_WORKSPACE_KEY)
-
-
-def set_active_workspace(slug: str) -> None:
- """Set the active workspace by slug."""
- _get_store().set(ACTIVE_WORKSPACE_KEY, slug)
-
-
-def list_workspaces() -> list[dict]:
- """List all authenticated workspaces.
-
- Returns:
- List of dicts with keys: slug, name, org, is_active
- """
- store = _get_store()
- active = store.get(ACTIVE_WORKSPACE_KEY)
- rows = store.list_by_prefix("workspace:")
-
- # Group by slug — extract from keys like workspace:<slug>:api_key
- slugs: dict[str, dict] = {}
- for key, value in rows:
- parts = key.split(":")
- if len(parts) != 3:
- continue
- slug = parts[1]
- field = parts[2]
- if slug not in slugs:
- slugs[slug] = {"slug": slug, "name": "", "org": "", "is_active": False}
- if field == "name":
- slugs[slug]["name"] = value
- elif field == "org":
- slugs[slug]["org"] = value
-
- # Only include workspaces that have an api_key stored
- result = []
- for key, _value in rows:
- parts = key.split(":")
- if len(parts) == 3 and parts[2] == "api_key" and parts[1] in slugs:
- ws = slugs[parts[1]]
- ws["is_active"] = ws["slug"] == active
- result.append(ws)
-
- result.sort(key=lambda ws: ws["slug"])
- return result
-
-
-def get_workspace_api_key(slug: str) -> Optional[str]:
- """Get the API key for a specific workspace."""
- return _get_store().get(f"workspace:{slug}:api_key")
-
-
-def delete_workspace(slug: str) -> None:
- """Delete all stored data for a workspace."""
- store = _get_store()
- store.delete(f"workspace:{slug}:api_key")
- store.delete(f"workspace:{slug}:name")
- store.delete(f"workspace:{slug}:org")
-
-
-def clear_all_workspaces() -> None:
- """Delete all workspace keys and the active workspace marker."""
- store = _get_store()
- store.delete_by_prefix("workspace:")
- store.delete(ACTIVE_WORKSPACE_KEY)
-
-
-def get_api_key() -> Optional[str]:
- """Get the stored API key.
-
- Priority:
- 1. CUA_API_KEY environment variable
- 2. Active workspace's API key
- 3. Legacy 'api_key' key (backward compat)
-
- Returns:
- The API key, or None if not found
- """
- # Environment variable takes precedence
- env_key = os.environ.get("CUA_API_KEY")
- if env_key:
- return env_key
-
- # Active workspace
- store = _get_store()
- active_slug = store.get(ACTIVE_WORKSPACE_KEY)
- if active_slug:
- ws_key = store.get(f"workspace:{active_slug}:api_key")
- if ws_key:
- return ws_key
-
- # Legacy fallback
- return store.get(API_KEY_NAME)
-
-
-def save_api_key(api_key: str) -> None:
- """Save an API key to the credential store (legacy path)."""
- _get_store().set(API_KEY_NAME, api_key)
-
-
-def clear_credentials() -> None:
- """Clear all stored credentials including workspaces and legacy key."""
- store = _get_store()
- clear_all_workspaces()
- store.delete(API_KEY_NAME)
-
-
-def clear_legacy_credentials() -> None:
- """Clear only the legacy API key (not workspace data)."""
- _get_store().delete(API_KEY_NAME)
-
-
-def require_api_key() -> str:
- """Get the API key, raising an error if not found.
-
- Returns:
- The API key
-
- Raises:
- RuntimeError: If no API key is configured
- """
- api_key = get_api_key()
- if not api_key:
- raise RuntimeError(
- "No API key configured. Run 'cua auth login' to authenticate, "
- "or set the CUA_API_KEY environment variable."
- )
- return api_key
+ except (KeyError, TypeError, ValueError) as error:
+ raise CredentialStorageError(
+ "Stored Cua credentials are invalid; log in again."
+ ) from error
+
+ def to_dict(self) -> dict[str, Any]:
+ value = asdict(self)
+ value["expires_at"] = self.expires_at.astimezone(UTC).isoformat()
+ return value
+
+
+def _read() -> str | None:
+ try:
+ return keyring.get_password(KEYRING_SERVICE, KEYRING_ACCOUNT)
+ except KeyringError as error:
+ raise CredentialStorageError(
+ "No secure credential store is available. Configure an OS keyring before logging in."
+ ) from error
+
+
+def load_credentials() -> OAuthCredentials | None:
+ """Load OIDC credentials from the operating system credential vault."""
+ raw = _read()
+ if raw is None:
+ return None
+ try:
+ value = json.loads(raw)
+ except json.JSONDecodeError as error:
+ raise CredentialStorageError("Stored Cua credentials are invalid; log in again.") from error
+ if not isinstance(value, dict):
+ raise CredentialStorageError("Stored Cua credentials are invalid; log in again.")
+ return OAuthCredentials.from_dict(value)
+
+
+def save_credentials(credentials: OAuthCredentials) -> None:
+ """Store OIDC credentials in the operating system credential vault."""
+ try:
+ keyring.set_password(KEYRING_SERVICE, KEYRING_ACCOUNT, json.dumps(credentials.to_dict()))
+ except KeyringError as error:
+ raise CredentialStorageError(
+ "No secure credential store is available. Configure an OS keyring before logging in."
+ ) from error
+
+
+def clear_credentials() -> bool:
+ """Remove locally stored OIDC credentials, returning whether any existed."""
+ if _read() is None:
+ return False
+ try:
+ keyring.delete_password(KEYRING_SERVICE, KEYRING_ACCOUNT)
+ except PasswordDeleteError:
+ return False
+ except KeyringError as error:
+ raise CredentialStorageError(
+ "Could not remove credentials from the operating system credential store."
+ ) from error
+ return True
diff --git a/libs/python/cua-cli/cua_cli/commands/auth.py b/libs/python/cua-cli/cua_cli/commands/auth.py
index 4589ca7892..c7ad9b9809 100644
--- a/libs/python/cua-cli/cua_cli/commands/auth.py
+++ b/libs/python/cua-cli/cua_cli/commands/auth.py
@@ -1,392 +1,142 @@
"""Authentication commands for Cua CLI."""
import argparse
-import os
-from pathlib import Path
+import sys
+import webbrowser
+from datetime import UTC, datetime
-import aiohttp
-from cua_cli.auth.browser import authenticate_via_browser
+from cua_cli.auth.oidc import OidcClient, OidcError
from cua_cli.auth.store import (
- ACTIVE_WORKSPACE_KEY,
- _get_store,
+ CredentialStorageError,
clear_credentials,
- clear_legacy_credentials,
- delete_workspace,
- get_active_workspace,
- get_api_key,
- list_workspaces,
- save_api_key,
- save_workspace,
- set_active_workspace,
+ load_credentials,
+ save_credentials,
)
from cua_cli.utils.async_utils import run_async
from cua_cli.utils.output import print_error, print_info, print_success
-from cua_core.http import cua_version_headers
-
-DEFAULT_API_BASE = "https://api.cua.ai"
-
-
-def _get_api_base() -> str:
- return os.environ.get("CUA_API_BASE", DEFAULT_API_BASE).rstrip("/")
def register_parser(subparsers: argparse._SubParsersAction) -> None:
- """Register the auth command and subcommands.
-
- Args:
- subparsers: The subparsers object from the main parser
- """
+ """Register authentication commands."""
auth_parser = subparsers.add_parser(
"auth",
help="Authentication commands",
- description="Manage authentication for Cua cloud services",
+ description="Manage run.cua.ai authentication",
)
+ auth_subparsers = auth_parser.add_subparsers(dest="auth_command", help="Authentication command")
- auth_subparsers = auth_parser.add_subparsers(
- dest="auth_command",
- help="Authentication command",
- )
-
- # login command
login_parser = auth_subparsers.add_parser(
- "login",
- help="Authenticate with Cua cloud",
- description="Authenticate via browser or API key",
+ "login", help="Log in with device authorization", description="Authenticate with run.cua.ai"
)
login_parser.add_argument(
- "--api-key",
- type=str,
- help="API key for direct authentication (skips browser flow)",
- )
-
- # list command
- auth_subparsers.add_parser(
- "list",
- help="List authenticated workspaces",
- description="Show all authenticated workspaces",
- )
-
- # logout command
- logout_parser = auth_subparsers.add_parser(
- "logout",
- help="Clear stored credentials",
- description="Remove stored authentication credentials",
- )
- logout_parser.add_argument(
- "--workspace",
- type=str,
- help="Remove credentials for a specific workspace slug",
- )
- logout_parser.add_argument(
- "--all",
+ "--no-browser",
action="store_true",
- help="Remove all workspace credentials",
- )
-
- # status command
- auth_subparsers.add_parser(
- "status",
- help="Show authentication status and account info",
- description="Display current user, credits, and API key info",
- )
-
- # env command
- env_parser = auth_subparsers.add_parser(
- "env",
- help="Export API key to .env file",
- description="Write CUA_API_KEY to .env file in current directory",
- )
- env_parser.add_argument(
- "--file",
- type=str,
- default=".env",
- help="Path to .env file (default: .env)",
+ help="Do not try to open the verification URL automatically",
)
+ auth_subparsers.add_parser("logout", help="Revoke and remove local credentials")
+ auth_subparsers.add_parser("status", help="Show local authentication status")
def execute(args: argparse.Namespace) -> int:
- """Execute auth command based on subcommand.
-
- Args:
- args: Parsed command-line arguments
-
- Returns:
- Exit code (0 for success, non-zero for failure)
- """
- cmd = getattr(args, "auth_command", None)
-
- if cmd == "login":
+ """Execute an authentication subcommand."""
+ command = getattr(args, "auth_command", None)
+ if command == "login":
return cmd_login(args)
- elif cmd == "logout":
+ if command == "logout":
return cmd_logout(args)
- elif cmd == "status":
+ if command == "status":
return cmd_status(args)
- elif cmd == "list":
- return cmd_list(args)
- elif cmd == "env":
- return cmd_env(args)
- else:
- print_error("Usage: cua auth <command>")
- print_info("Commands: login, logout, status, list, env")
- return 1
-
-
-def _fetch_me(api_key: str) -> tuple[int, dict]:
- """Call /v1/me to get workspace metadata for an API key."""
-
- async def _do():
- url = f"{_get_api_base()}/v1/me"
- headers = {
- "Authorization": f"Bearer {api_key}",
- "Accept": "application/json",
- **cua_version_headers(),
- }
- async with aiohttp.ClientSession() as session:
- timeout = aiohttp.ClientTimeout(total=10)
- async with session.get(url, headers=headers, timeout=timeout) as resp:
- try:
- data = await resp.json(content_type=None)
- except Exception:
- text = await resp.text()
- return resp.status, {"error": text}
- return resp.status, data
-
- return run_async(_do())
+ print_error("Usage: cua auth <login|logout|status>")
+ return 1
def cmd_login(args: argparse.Namespace) -> int:
- """Handle the login command."""
- if args.api_key:
- # Direct API key authentication — discover workspace via /v1/me
- api_key = args.api_key
- print_info("Authenticating with provided API key...")
- try:
- status_code, data = _fetch_me(api_key)
- except Exception as e:
- print_error(f"Failed to reach API: {e}")
- return 1
-
- if status_code != 200:
- print_error(f"API key validation failed (HTTP {status_code})")
- return 1
+ """Start OAuth device authorization and store the resulting tokens."""
+ client = OidcClient()
+ try:
+ discovery = run_async(client.discover())
+ device_code = run_async(client.request_device_code(discovery))
+ except (OidcError, OSError) as error:
+ print_error(f"Could not start device authorization: {error}")
+ return 1
- ws = data.get("workspace", {})
- org = data.get("organization", {})
- slug = ws.get("slug")
- if slug:
- name = ws.get("name", slug)
- org_name = org.get("name", "")
- save_workspace(slug, api_key, name, org_name)
- set_active_workspace(slug)
- print_success(f"Authenticated and switched to workspace: {name} ({slug})")
- else:
- # Legacy fallback — no workspace metadata from API
- save_api_key(api_key)
- _get_store().delete(ACTIVE_WORKSPACE_KEY)
- print_success("Successfully authenticated!")
- else:
- # Browser-based authentication
+ verification_url = device_code.verification_uri_complete or device_code.verification_uri
+ print_info(f"Open this URL in any browser: {verification_url}")
+ print_info(f"Enter this code if prompted: {device_code.user_code}")
+ if not args.no_browser and sys.stdin.isatty() and sys.stdout.isatty():
try:
- result = run_async(authenticate_via_browser())
- except TimeoutError as e:
- print_error(str(e))
- return 1
- except RuntimeError as e:
- print_error(str(e))
- return 1
+ if webbrowser.open(verification_url):
+ print_info("Opened the verification URL in your browser.")
+ except webbrowser.Error:
+ print_info("Could not open a browser. Use the URL shown above.")
+ elif not args.no_browser:
+ print_info("No interactive terminal detected; use the URL shown above in a browser.")
- if result.workspace_slug:
- save_workspace(
- result.workspace_slug,
- result.token,
- result.workspace_name,
- result.org_name,
- )
- set_active_workspace(result.workspace_slug)
- print_success(
- f"Authenticated and switched to workspace: "
- f"{result.workspace_name} ({result.workspace_slug})"
- )
- else:
- # Fallback if website didn't send workspace metadata
- save_api_key(result.token)
- _get_store().delete(ACTIVE_WORKSPACE_KEY)
- print_success("Successfully authenticated!")
+ try:
+ credentials = run_async(client.poll_for_tokens(discovery, device_code))
+ save_credentials(credentials)
+ except (CredentialStorageError, OidcError, OSError) as error:
+ print_error(f"Login failed: {error}")
+ return 1
+ print_success("Logged in to run.cua.ai.")
return 0
-def cmd_logout(args: argparse.Namespace) -> int:
- """Handle the logout command."""
- if getattr(args, "all", False):
- clear_credentials()
- print_success("All credentials cleared.")
+def cmd_logout(_args: argparse.Namespace) -> int:
+ """Revoke the refresh token when possible, then remove local credentials."""
+ try:
+ credentials = load_credentials()
+ except CredentialStorageError as error:
+ print_error(str(error))
+ return 1
+ if credentials is None:
+ print_info("Not logged in.")
return 0
- ws_slug = getattr(args, "workspace", None)
- if ws_slug:
- delete_workspace(ws_slug)
- active = get_active_workspace()
- if active == ws_slug:
- # Active workspace was removed — pick another or clear
- remaining = list_workspaces()
- if remaining:
- set_active_workspace(remaining[0]["slug"])
- print_info(
- f"Switched to workspace: {remaining[0]['name']} ({remaining[0]['slug']})"
- )
- else:
- _get_store().delete(ACTIVE_WORKSPACE_KEY)
- print_success(f"Removed credentials for workspace: {ws_slug}")
- return 0
+ try:
+ client = OidcClient()
- # No flags — remove only the active workspace
- active = get_active_workspace()
- if active:
- delete_workspace(active)
- remaining = list_workspaces()
- if remaining:
- set_active_workspace(remaining[0]["slug"])
- print_success(f"Logged out of workspace: {active}")
+ async def revoke_remote() -> bool:
+ return await client.revoke(await client.discover(), credentials)
+
+ revoked = run_async(revoke_remote())
+ if not revoked:
print_info(
- f"Switched to workspace: {remaining[0]['name']} ({remaining[0]['slug']}). "
- f"Use 'cua workspace set <slug>' to switch workspaces."
+ "Remote token revocation was unavailable; removing local credentials anyway."
)
- else:
- _get_store().delete(ACTIVE_WORKSPACE_KEY)
- print_success(f"Logged out of workspace: {active}")
- else:
- clear_legacy_credentials()
- print_success("Credentials cleared.")
- return 0
-
-
-def cmd_list(args: argparse.Namespace) -> int:
- """Handle the list command — show all authenticated workspaces."""
- workspaces = list_workspaces()
- if not workspaces:
- print_info("No authenticated workspaces. Run 'cua auth login' to add one.")
- return 0
-
- # Group by org
- by_org: dict[str, list[dict]] = {}
- for ws in workspaces:
- org = ws["org"] or "Unknown"
- by_org.setdefault(org, []).append(ws)
-
- from rich.console import Console
-
- c = Console()
- for org, org_workspaces in by_org.items():
- c.print(f"[bold]{org}[/bold]")
- for ws in org_workspaces:
- name = ws["name"] or ws["slug"]
- slug = ws["slug"]
- if ws["is_active"]:
- c.print(f" [green]* {name} ({slug})[/green]")
- else:
- c.print(f" {name} ({slug})")
- return 0
-
-
-def cmd_status(args: argparse.Namespace) -> int:
- """Handle the status command — show auth status and account info."""
- api_key = get_api_key()
- if not api_key:
- print_error("Not logged in. Run 'cua auth login' first.")
- return 1
+ except (OidcError, OSError):
+ print_info(
+ "Could not reach run.cua.ai to revoke the token; removing local credentials anyway."
+ )
try:
- status_code, data = _fetch_me(api_key)
- except Exception as e:
- print_error(f"Failed to reach API: {e}")
- return 1
-
- if status_code == 401:
- # Don't mutate cached workspaces if the token came from the environment
- if os.environ.get("CUA_API_KEY"):
- print_error("Session expired. The CUA_API_KEY environment variable is invalid.")
- return 1
-
- active = get_active_workspace()
- if active:
- delete_workspace(active)
- print_info(f"Removed expired credentials for workspace: {active}")
- remaining = list_workspaces()
- if remaining:
- set_active_workspace(remaining[0]["slug"])
- print_info(
- f"Switched to workspace: {remaining[0]['name']} ({remaining[0]['slug']})"
- )
- else:
- _get_store().delete(ACTIVE_WORKSPACE_KEY)
- else:
- clear_legacy_credentials()
- print_info("Removed expired credentials.")
- print_error("Session expired. Run 'cua auth login' to re-authenticate.")
- return 1
-
- if status_code != 200:
- print_error(f"Failed to fetch account info (HTTP {status_code})")
+ clear_credentials()
+ except CredentialStorageError as error:
+ print_error(str(error))
return 1
-
- ws = data.get("workspace", {})
- org = data.get("organization", {})
- credits = data.get("credits", {})
-
- active_slug = get_active_workspace()
- active_label = f" [active: {active_slug}]" if active_slug else ""
- print_success(f"Logged in to cua.ai{active_label}")
- print_info(f" Workspace: {ws.get('name', 'unknown')} ({ws.get('slug', 'unknown')})")
- print_info(f" Organization: {org.get('name', 'unknown')} ({org.get('plan_type', 'unknown')})")
- print_info(f" Credits: {credits.get('balance', 0):.2f} remaining")
-
+ print_success("Logged out.")
return 0
-def cmd_env(args: argparse.Namespace) -> int:
- """Handle the env command - export API key to .env file.
-
- Args:
- args: Parsed command-line arguments
-
- Returns:
- Exit code
- """
- api_key = get_api_key()
- if not api_key:
- print_error("Not authenticated. Run 'cua auth login' first.")
+def cmd_status(_args: argparse.Namespace) -> int:
+ """Show local session availability without exposing token material."""
+ try:
+ credentials = load_credentials()
+ except CredentialStorageError as error:
+ print_error(str(error))
+ return 1
+ if credentials is None:
+ print_info("Not logged in. Run 'cua auth login'.")
return 1
- env_file = Path(args.file)
- env_line = f"CUA_API_KEY={api_key}"
-
- if env_file.exists():
- # Read existing content
- content = env_file.read_text()
- lines = content.splitlines()
-
- # Check if CUA_API_KEY already exists
- updated = False
- for i, line in enumerate(lines):
- if line.startswith("CUA_API_KEY="):
- lines[i] = env_line
- updated = True
- break
-
- if updated:
- env_file.write_text("\n".join(lines) + "\n")
- print_success(f"Updated CUA_API_KEY in {env_file}")
- else:
- # Append to file
- with env_file.open("a") as f:
- if content and not content.endswith("\n"):
- f.write("\n")
- f.write(env_line + "\n")
- print_success(f"Added CUA_API_KEY to {env_file}")
+ now = datetime.now(UTC)
+ if credentials.expires_at <= now:
+ print_info(
+ "Logged in; access token expired and will refresh on the next run.cua.ai request."
+ )
else:
- # Create new file
- env_file.write_text(env_line + "\n")
- print_success(f"Created {env_file} with CUA_API_KEY")
-
+ print_success(
+ f"Logged in to run.cua.ai. Access token expires {credentials.expires_at.isoformat()}."
+ )
return 0
diff --git a/libs/python/cua-cli/cua_cli/commands/do.py b/libs/python/cua-cli/cua_cli/commands/do.py
index 02cc186989..05f4a590d0 100644
--- a/libs/python/cua-cli/cua_cli/commands/do.py
+++ b/libs/python/cua-cli/cua_cli/commands/do.py
@@ -103,10 +103,10 @@ async def _get_api_url(provider_type: str, name: str) -> str:
return f"http://{state['host']}:{state['api_port']}"
if provider_type in ("cloud", "cloudv2"):
- from cua_cli.auth.store import get_api_key
+ from cua_cli.auth.oidc import get_access_token
from cua_sandbox.transport.cloud import CloudTransport, cloud_get_vm
- api_key = get_api_key()
+ api_key = await get_access_token()
if not api_key:
raise ValueError("Not authenticated. Run 'cua auth login' first")
vm = await cloud_get_vm(name, api_key=api_key)
@@ -331,11 +331,10 @@ async def _send(provider_type: str, name: str, command: str, params: dict) -> di
headers = {"Content-Type": "application/json", **cua_version_headers()}
if provider_type in ("cloud", "cloudv2"):
- from cua_cli.auth.store import get_api_key
+ from cua_cli.auth.oidc import get_access_token
- api_key = get_api_key()
- if api_key:
- headers["X-API-Key"] = api_key
+ access_token = await get_access_token()
+ headers["Authorization"] = f"Bearer {access_token}"
if name:
headers["X-Container-Name"] = name
@@ -626,7 +625,7 @@ def _cmd_ls(args: argparse.Namespace) -> int:
explicit_provider = getattr(args, "provider", None)
async def _list_all() -> int:
- from cua_cli.auth.store import get_api_key
+ from cua_cli.auth.oidc import get_access_token
from cua_sandbox import Sandbox
print(" host [local]")
@@ -639,7 +638,7 @@ def _cmd_ls(args: argparse.Namespace) -> int:
pass
try:
- api_key = get_api_key()
+ api_key = await get_access_token()
if api_key:
cloud_sandboxes = await Sandbox.list(local=False, api_key=api_key)
for s in cloud_sandboxes:
@@ -650,7 +649,7 @@ def _cmd_ls(args: argparse.Namespace) -> int:
return 0
async def _list_one(ptype: str) -> int:
- from cua_cli.auth.store import get_api_key
+ from cua_cli.auth.oidc import get_access_token
from cua_sandbox import Sandbox
if ptype == "host":
@@ -659,7 +658,7 @@ def _cmd_ls(args: argparse.Namespace) -> int:
local = ptype in ("local", "lume", "lumier", "docker", "winsandbox")
try:
- api_key = None if local else get_api_key()
+ api_key = None if local else await get_access_token()
sandboxes = await Sandbox.list(local=local, api_key=api_key)
if not sandboxes:
print(f"No sandboxes found for provider '{ptype}'")
@@ -1265,12 +1264,10 @@ async def _shell_remote_pty(
headers: dict = {}
ws_params: dict = {}
if provider in ("cloud", "cloudv2"):
- from cua_cli.auth.store import get_api_key
+ from cua_cli.auth.oidc import get_access_token
- api_key = get_api_key()
- if api_key:
- headers["X-API-Key"] = api_key
- ws_params["api_key"] = api_key
+ access_token = await get_access_token()
+ headers["Authorization"] = f"Bearer {access_token}"
if name:
headers["X-Container-Name"] = name
ws_params["container_name"] = name
diff --git a/libs/python/cua-cli/cua_cli/commands/mcp.py b/libs/python/cua-cli/cua_cli/commands/mcp.py
index b36421420f..404b0c63d7 100644
--- a/libs/python/cua-cli/cua_cli/commands/mcp.py
+++ b/libs/python/cua-cli/cua_cli/commands/mcp.py
@@ -205,10 +205,10 @@ async def _register_sandbox_tools(server: "FastMCP", permissions: set[Permission
@server.tool()
async def sandbox_list(ctx: Context) -> str:
"""List all cloud sandboxes."""
- from cua_cli.auth.store import get_api_key
+ from cua_cli.auth.oidc import get_access_token
from cua_sandbox import Sandbox
- sandboxes = await Sandbox.list(api_key=get_api_key())
+ sandboxes = await Sandbox.list(api_key=await get_access_token())
return json.dumps(
[
{
@@ -238,7 +238,7 @@ async def _register_sandbox_tools(server: "FastMCP", permissions: set[Permission
size: VM size (small, medium, large, xlarge)
region: Region (north-america, europe, asia)
"""
- from cua_cli.auth.store import get_api_key
+ from cua_cli.auth.oidc import get_access_token
from cua_sandbox import Image, Sandbox
if os_type == "macos":
@@ -247,7 +247,7 @@ async def _register_sandbox_tools(server: "FastMCP", permissions: set[Permission
image = Image.windows("11")
else:
image = Image.linux("ubuntu", "24.04")
- sb = await Sandbox.create(image, api_key=get_api_key(), region=region)
+ sb = await Sandbox.create(image, api_key=await get_access_token(), region=region)
name = sb.name
await sb.disconnect()
return json.dumps(
@@ -269,11 +269,11 @@ async def _register_sandbox_tools(server: "FastMCP", permissions: set[Permission
Args:
name: Sandbox name
"""
- from cua_cli.auth.store import get_api_key
+ from cua_cli.auth.oidc import get_access_token
from cua_sandbox import Sandbox
try:
- info = await Sandbox.get_info(name, api_key=get_api_key())
+ info = await Sandbox.get_info(name, api_key=await get_access_token())
return json.dumps(
{
"name": info.name,
@@ -295,10 +295,10 @@ async def _register_sandbox_tools(server: "FastMCP", permissions: set[Permission
Args:
name: Sandbox name
"""
- from cua_cli.auth.store import get_api_key
+ from cua_cli.auth.oidc import get_access_token
from cua_sandbox import Sandbox
- await Sandbox.resume(name, api_key=get_api_key())
+ await Sandbox.resume(name, api_key=await get_access_token())
return json.dumps({"success": True, "message": f"Started sandbox: {name}"})
if Permission.SANDBOX_STOP in permissions:
@@ -310,10 +310,10 @@ async def _register_sandbox_tools(server: "FastMCP", permissions: set[Permission
Args:
name: Sandbox name
"""
- from cua_cli.auth.store import get_api_key
+ from cua_cli.auth.oidc import get_access_token
from cua_sandbox import Sandbox
- await Sandbox.suspend(name, api_key=get_api_key())
+ await Sandbox.suspend(name, api_key=await get_access_token())
return json.dumps({"success": True, "message": f"Stopped sandbox: {name}"})
if Permission.SANDBOX_RESTART in permissions:
@@ -325,10 +325,10 @@ async def _register_sandbox_tools(server: "FastMCP", permissions: set[Permission
Args:
name: Sandbox name
"""
- from cua_cli.auth.store import get_api_key
+ from cua_cli.auth.oidc import get_access_token
from cua_sandbox import Sandbox
- await Sandbox.restart(name, api_key=get_api_key())
+ await Sandbox.restart(name, api_key=await get_access_token())
return json.dumps({"success": True, "message": f"Restarted sandbox: {name}"})
if Permission.SANDBOX_SUSPEND in permissions:
@@ -340,10 +340,10 @@ async def _register_sandbox_tools(server: "FastMCP", permissions: set[Permission
Args:
name: Sandbox name
"""
- from cua_cli.auth.store import get_api_key
+ from cua_cli.auth.oidc import get_access_token
from cua_sandbox import Sandbox
- await Sandbox.suspend(name, api_key=get_api_key())
+ await Sandbox.suspend(name, api_key=await get_access_token())
return json.dumps({"success": True, "message": f"Suspended sandbox: {name}"})
if Permission.SANDBOX_DELETE in permissions:
@@ -355,10 +355,10 @@ async def _register_sandbox_tools(server: "FastMCP", permissions: set[Permission
Args:
name: Sandbox name
"""
- from cua_cli.auth.store import get_api_key
+ from cua_cli.auth.oidc import get_access_token
from cua_sandbox import Sandbox
- await Sandbox.delete(name, api_key=get_api_key())
+ await Sandbox.delete(name, api_key=await get_access_token())
return json.dumps({"success": True, "message": f"Deleted sandbox: {name}"})
if Permission.SANDBOX_VNC in permissions:
@@ -370,11 +370,11 @@ async def _register_sandbox_tools(server: "FastMCP", permissions: set[Permission
Args:
name: Sandbox name
"""
- from cua_cli.auth.store import get_api_key
+ from cua_cli.auth.oidc import get_access_token
from cua_sandbox import Sandbox
try:
- sb = await Sandbox.connect(name, api_key=get_api_key())
+ sb = await Sandbox.connect(name, api_key=await get_access_token())
vnc_url = await sb.get_display_url(share=True)
await sb.disconnect()
return json.dumps({"vnc_url": vnc_url})
@@ -389,7 +389,7 @@ async def _register_computer_tools(
) -> None:
"""Register computer control tools that proxy to computer-server."""
import aiohttp
- from cua_cli.auth.store import get_api_key
+ from cua_cli.auth.oidc import get_access_token
from mcp.server.fastmcp import Context
from mcp.server.fastmcp.utilities.types import Image
@@ -398,7 +398,7 @@ async def _register_computer_tools(
name = sandbox_name or default_sandbox
if not name:
raise ValueError("No sandbox specified. Use --sandbox or set CUA_SANDBOX env var")
- api_key = get_api_key()
+ api_key = await get_access_token()
if not api_key:
raise ValueError("Not authenticated. Run 'cua auth login' first")
from cua_sandbox.transport.cloud import CloudTransport, cloud_get_vm
@@ -411,13 +411,13 @@ async def _register_computer_tools(
async def _send_command(sandbox_name: str, command: str, params: dict) -> dict:
"""Send a command to the computer-server."""
server_url = await _get_server_url(sandbox_name)
- api_key = get_api_key()
+ access_token = await get_access_token()
from cua_core.http import cua_version_headers
headers = {
"Content-Type": "application/json",
- "X-API-Key": api_key,
+ "Authorization": f"Bearer {access_token}",
"X-Container-Name": sandbox_name or default_sandbox,
**cua_version_headers(),
}
diff --git a/libs/python/cua-cli/cua_cli/commands/sandbox.py b/libs/python/cua-cli/cua_cli/commands/sandbox.py
index 8188490f8e..fbdfead330 100644
--- a/libs/python/cua-cli/cua_cli/commands/sandbox.py
+++ b/libs/python/cua-cli/cua_cli/commands/sandbox.py
@@ -10,7 +10,7 @@ import webbrowser
from typing import Any, Optional
import aiohttp
-from cua_cli.auth.store import get_api_key, require_api_key
+from cua_cli.auth.oidc import get_access_token
from cua_cli.utils.async_utils import run_async
from cua_cli.utils.output import (
print_error,
@@ -146,7 +146,7 @@ async def _get_sandbox_api_url(name: str, local: bool) -> tuple[str, Optional[st
url = f"http://{state['host']}:{state['api_port']}"
return url, None
- api_key = require_api_key()
+ api_key = await get_access_token()
from cua_sandbox.transport.cloud import CloudTransport, cloud_get_vm
vm = await cloud_get_vm(name, api_key=api_key)
@@ -442,7 +442,7 @@ def cmd_launch(args: argparse.Namespace) -> int:
create_kwargs["memory_mb"] = memory_mb
if disk_gb is not None:
create_kwargs["disk_gb"] = disk_gb
- api_key = require_api_key()
+ api_key = await get_access_token()
create_kwargs["api_key"] = api_key
sb = await Sandbox.create(image, **create_kwargs)
@@ -491,7 +491,7 @@ def cmd_ls(args: argparse.Namespace) -> int:
if show_all or not local:
try:
- api_key = get_api_key()
+ api_key = await get_access_token()
cloud_list = await Sandbox.list(local=False, api_key=api_key)
for s in cloud_list:
results.append(
@@ -531,7 +531,7 @@ def cmd_info(args: argparse.Namespace) -> int:
try:
kwargs: dict[str, Any] = {}
if not local:
- kwargs["api_key"] = require_api_key()
+ kwargs["api_key"] = await get_access_token()
info = await Sandbox.get_info(args.name, local=local, **kwargs)
except Exception as e:
print_error(str(e))
@@ -575,7 +575,7 @@ def cmd_suspend(args: argparse.Namespace) -> int:
try:
kwargs: dict[str, Any] = {}
if not local:
- kwargs["api_key"] = require_api_key()
+ kwargs["api_key"] = await get_access_token()
await Sandbox.suspend(args.name, local=local, **kwargs)
except Exception as e:
print_error(f"Failed to suspend sandbox: {e}")
@@ -596,7 +596,7 @@ def cmd_resume(args: argparse.Namespace) -> int:
try:
kwargs: dict[str, Any] = {}
if not local:
- kwargs["api_key"] = require_api_key()
+ kwargs["api_key"] = await get_access_token()
await Sandbox.resume(args.name, local=local, **kwargs)
except Exception as e:
print_error(f"Failed to resume sandbox: {e}")
@@ -617,7 +617,7 @@ def cmd_restart(args: argparse.Namespace) -> int:
try:
kwargs: dict[str, Any] = {}
if not local:
- kwargs["api_key"] = require_api_key()
+ kwargs["api_key"] = await get_access_token()
await Sandbox.restart(args.name, local=local, **kwargs)
except Exception as e:
print_error(f"Failed to restart sandbox: {e}")
@@ -654,7 +654,7 @@ def cmd_delete(args: argparse.Namespace) -> int:
try:
kwargs: dict[str, Any] = {}
if not local:
- kwargs["api_key"] = require_api_key()
+ kwargs["api_key"] = await get_access_token()
await Sandbox.delete(args.name, local=local, **kwargs)
except Exception as e:
print_error(f"Failed to delete sandbox: {e}")
@@ -675,7 +675,7 @@ def cmd_vnc(args: argparse.Namespace) -> int:
try:
kwargs: dict[str, Any] = {}
if not local:
- kwargs["api_key"] = require_api_key()
+ kwargs["api_key"] = await get_access_token()
sb = await Sandbox.connect(args.name, local=local, **kwargs)
vnc_url = await sb.get_display_url(share=True)
await sb.disconnect()
@@ -725,8 +725,7 @@ async def _shell_interactive(
"container_name": name,
}
if api_key:
- headers["X-API-Key"] = api_key
- ws_params["api_key"] = api_key
+ headers["Authorization"] = f"Bearer {api_key}"
try:
async with aiohttp.ClientSession() as http:
@@ -870,7 +869,7 @@ async def _exec_noninteractive(
"Content-Type": "application/json",
}
if api_key:
- headers["X-API-Key"] = api_key
+ headers["Authorization"] = f"Bearer {api_key}"
async with aiohttp.ClientSession() as http:
async with http.post(
diff --git a/libs/python/cua-cli/cua_cli/commands/skills.py b/libs/python/cua-cli/cua_cli/commands/skills.py
index f7dbc424fe..c4eebf17b1 100644
--- a/libs/python/cua-cli/cua_cli/commands/skills.py
+++ b/libs/python/cua-cli/cua_cli/commands/skills.py
@@ -479,11 +479,11 @@ async def _record_skill_async(args: argparse.Namespace) -> int:
# Build VNC URL with recording parameters
if args.sandbox:
# Get sandbox VNC URL
- from cua_cli.auth.store import require_api_key
+ from cua_cli.auth.oidc import get_access_token
from cua_sandbox.transport.cloud import cloud_get_vm
try:
- vm = await cloud_get_vm(args.sandbox, api_key=require_api_key())
+ vm = await cloud_get_vm(args.sandbox, api_key=await get_access_token())
except Exception:
vm = None
if not vm or vm.get("status") == "not_found":
diff --git a/libs/python/cua-cli/cua_cli/commands/workspace.py b/libs/python/cua-cli/cua_cli/commands/workspace.py
deleted file mode 100644
index 82d66b4840..0000000000
--- a/libs/python/cua-cli/cua_cli/commands/workspace.py
+++ /dev/null
@@ -1,205 +0,0 @@
-"""Workspace commands for Cua CLI."""
-
-import argparse
-import asyncio
-import os
-
-import aiohttp
-from cua_cli.auth.browser import authenticate_via_browser
-from cua_cli.auth.store import (
- _get_store,
- delete_workspace,
- get_workspace_api_key,
- list_workspaces,
- save_workspace,
- set_active_workspace,
-)
-from cua_cli.utils.async_utils import run_async
-from cua_cli.utils.output import print_error, print_info, print_success
-from cua_core.http import cua_version_headers
-
-DEFAULT_API_BASE = "https://api.cua.ai"
-
-
-def _get_api_base() -> str:
- return os.environ.get("CUA_API_BASE", DEFAULT_API_BASE).rstrip("/")
-
-
-def register_parser(subparsers: argparse._SubParsersAction) -> None:
- """Register the workspace command and subcommands."""
- ws_parser = subparsers.add_parser(
- "workspace",
- help="Workspace commands",
- description="Manage workspaces",
- aliases=["ws"],
- )
-
- ws_subparsers = ws_parser.add_subparsers(
- dest="workspace_command",
- help="Workspace command",
- )
-
- set_parser = ws_subparsers.add_parser(
- "set",
- help="Switch active workspace",
- description="Switch to a different workspace",
- )
- set_parser.add_argument(
- "slug",
- nargs="?",
- help="Workspace slug to switch to",
- )
-
-
-def execute(args: argparse.Namespace) -> int:
- """Execute workspace command based on subcommand."""
- cmd = getattr(args, "workspace_command", None)
-
- if cmd == "set":
- return cmd_set(args)
- else:
- print_error("Usage: cua workspace <command>")
- print_info("Commands: set")
- return 1
-
-
-def _validate_workspace_key(api_key: str) -> tuple[bool | None, dict]:
- """Validate an API key by calling /v1/me.
-
- Returns:
- (True, data) — valid key (HTTP 200)
- (False, data) — explicitly invalid/expired (HTTP 401)
- (None, {}) — transport error or unexpected HTTP status
- """
-
- async def _do():
- url = f"{_get_api_base()}/v1/me"
- headers = {
- "Authorization": f"Bearer {api_key}",
- "Accept": "application/json",
- **cua_version_headers(),
- }
- async with aiohttp.ClientSession() as session:
- timeout = aiohttp.ClientTimeout(total=10)
- async with session.get(url, headers=headers, timeout=timeout) as resp:
- try:
- data = await resp.json(content_type=None)
- except Exception:
- return resp.status, {}
- return resp.status, data
-
- try:
- status_code, data = run_async(_do())
- if status_code == 200:
- return True, data
- elif status_code == 401:
- return False, data
- else:
- return None, {}
- except (aiohttp.ClientError, asyncio.TimeoutError, OSError):
- return None, {}
- except Exception:
- return None, {}
-
-
-def cmd_set(args: argparse.Namespace) -> int:
- """Handle the workspace set command."""
- slug = getattr(args, "slug", None)
-
- if slug:
- # Check if we have a stored key for this workspace
- stored_key = get_workspace_api_key(slug)
- if stored_key:
- # Validate the stored key
- valid, _data = _validate_workspace_key(stored_key)
- if valid is True:
- set_active_workspace(slug)
- ws_name = _get_store().get(f"workspace:{slug}:name") or slug
- print_success(f"Switched to workspace: {ws_name} ({slug})")
- return 0
- elif valid is None:
- # Transport error — don't delete cached credentials
- print_error(
- f"Could not verify credentials for '{slug}' (API unreachable). Try again later."
- )
- return 1
- else:
- # Explicitly expired (401) — remove and fall through to browser auth
- print_info(f"Credentials for '{slug}' are expired. Re-authenticating...")
- delete_workspace(slug)
-
- # Not authenticated or stale — trigger browser auth with hint
- try:
- result = run_async(authenticate_via_browser(workspace_slug=slug))
- except (TimeoutError, RuntimeError) as e:
- print_error(str(e))
- return 1
-
- if result.workspace_slug:
- if result.workspace_slug != slug:
- print_error(
- f"Authenticated workspace '{result.workspace_slug}' does not match "
- f"requested workspace '{slug}'."
- )
- return 1
- save_workspace(
- result.workspace_slug,
- result.token,
- result.workspace_name,
- result.org_name,
- )
- set_active_workspace(result.workspace_slug)
- print_success(
- f"Authenticated and switched to workspace: "
- f"{result.workspace_name} ({result.workspace_slug})"
- )
- else:
- print_error("Authentication did not return workspace metadata.")
- return 1
- return 0
-
- # No slug — interactive selection from authenticated workspaces
- workspaces = list_workspaces()
- if not workspaces:
- print_info("No authenticated workspaces. Run 'cua auth login' to add one.")
- return 0
-
- print_info("Select a workspace:")
- for i, ws in enumerate(workspaces, 1):
- marker = " (active)" if ws["is_active"] else ""
- name_part = f" - {ws['name']}" if ws["name"] else ""
- print(f" {i}. {ws['slug']}{name_part}{marker}")
-
- try:
- choice = input("\nEnter number: ").strip()
- idx = int(choice) - 1
- if idx < 0 or idx >= len(workspaces):
- print_error("Invalid selection.")
- return 1
- except (ValueError, EOFError, KeyboardInterrupt):
- print_error("Invalid selection.")
- return 1
-
- selected = workspaces[idx]
-
- # Validate the selected workspace's session before switching
- stored_key = get_workspace_api_key(selected["slug"])
- if stored_key:
- valid, _data = _validate_workspace_key(stored_key)
- if valid is None:
- print_error(
- f"Could not verify credentials for '{selected['slug']}' (API unreachable). "
- f"Try again later."
- )
- return 1
- elif valid is False:
- delete_workspace(selected["slug"])
- print_error(
- f"Credentials for '{selected['slug']}' are expired. "
- f"Run 'cua auth login' to re-authenticate."
- )
- return 1
-
- set_active_workspace(selected["slug"])
- print_success(f"Switched to workspace: {selected['name']} ({selected['slug']})")
- return 0
diff --git a/libs/python/cua-cli/cua_cli/main.py b/libs/python/cua-cli/cua_cli/main.py
index 03938b277b..553ae68b52 100644
--- a/libs/python/cua-cli/cua_cli/main.py
+++ b/libs/python/cua-cli/cua_cli/main.py
@@ -2,12 +2,13 @@
import argparse
import logging
+import os
import sys
import time
from cua_cli import __version__
+from cua_cli.auth.oidc import DEFAULT_RUN_API_BASE
from cua_cli.commands import auth, do, image, mcp, platform, sandbox, skills, trajectory
-from cua_cli.commands import workspace as workspace_cmd
from cua_cli.utils.output import print_error
try:
@@ -52,7 +53,6 @@ def create_parser() -> argparse.ArgumentParser:
do.register_parser(subparsers)
do.register_host_consent_parser(subparsers)
trajectory.register_parser(subparsers)
- workspace_cmd.register_parser(subparsers)
return parser
@@ -65,6 +65,9 @@ def main() -> int:
for name in ("computer", "cua_core", "cua_core.telemetry", "httpx", "httpcore", "cua_sandbox"):
logging.getLogger(name).setLevel(logging.WARNING)
+ # The CLI only sends cloud requests to the run API, never a legacy endpoint.
+ os.environ["CUA_BASE_URL"] = DEFAULT_RUN_API_BASE
+
parser = create_parser()
args = parser.parse_args()
@@ -95,8 +98,6 @@ def main() -> int:
exit_code = do.execute_host_consent(args)
elif args.command in ("trajectory", "traj"):
exit_code = trajectory.execute(args)
- elif args.command in ("workspace", "ws"):
- exit_code = workspace_cmd.execute(args)
else:
print_error(f"Unknown command: {args.command}")
exit_code = 1
diff --git a/libs/python/cua-cli/pyproject.toml b/libs/python/cua-cli/pyproject.toml
index 15e1c8fa2d..51199bcb56 100644
--- a/libs/python/cua-cli/pyproject.toml
+++ b/libs/python/cua-cli/pyproject.toml
@@ -34,6 +34,8 @@ dependencies = [
"cua-auto[all]>=0.1.0",
# HTTP client
"aiohttp>=3.9.0",
+ # OS-backed credential storage for OAuth tokens
+ "keyring>=25.0",
# CLI output
"rich>=13.0.0",
# Image processing for skills
diff --git a/libs/python/cua-cli/tests/api/test_client.py b/libs/python/cua-cli/tests/api/test_client.py
new file mode 100644
index 0000000000..dc81f5adc7
--- /dev/null
+++ b/libs/python/cua-cli/tests/api/test_client.py
@@ -0,0 +1,18 @@
+"""Tests for authenticated run API requests."""
+
+import pytest
+from cua_cli.api.client import CloudAPIClient
+
+
+async def test_cloud_client_uses_refreshable_bearer_token(monkeypatch) -> None:
+ async def access_token() -> str:
+ return "refreshed-access-token"
+
+ monkeypatch.setattr("cua_cli.api.client.get_access_token", access_token)
+ client = CloudAPIClient()
+
+ headers = await client._headers()
+
+ assert client.api_base == "https://run.cua.ai"
+ assert headers["Authorization"] == "Bearer refreshed-access-token"
diff --git a/libs/python/cua-cli/tests/auth/test_oidc.py b/libs/python/cua-cli/tests/auth/test_oidc.py
new file mode 100644
index 0000000000..dfc22d46dc
--- /dev/null
+++ b/libs/python/cua-cli/tests/auth/test_oidc.py
@@ -0,0 +1,144 @@
+"""Tests for the Keycloak OIDC device flow used by run.cua.ai."""
+
+from collections.abc import Mapping
+from datetime import UTC, datetime
+
+import pytest
+from cua_cli.auth.oidc import DEVICE_GRANT_TYPE, OidcClient
+from cua_cli.auth.store import OAuthCredentials
+
+
+class ScriptedRequester:
+ def __init__(self, responses: list[tuple[int, dict]]) -> None:
+ self.responses = responses
+ self.calls: list[tuple[str, str, Mapping[str, str] | None]] = []
+
+ async def __call__(
+ self, method: str, url: str, form: Mapping[str, str] | None
+ ) -> tuple[int, dict]:
+ self.calls.append((method, url, form))
+ return self.responses.pop(0)
+
+
+async def test_device_flow_discovers_requests_and_polls() -> None:
+ requester = ScriptedRequester(
+ [
+ (
+ 200,
+ {
+ "token_endpoint": "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token",
+ "device_authorization_endpoint": "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/device/code",
+ "revocation_endpoint": "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/revoke",
+ },
+ ),
+ (
+ 200,
+ {
+ "device_code": "device-code",
+ "user_code": "ABCD-EFGH",
+ "verification_uri": "https://run.cua.ai/device",
+ "verification_uri_complete": "https://run.cua.ai/device?user_code=ABCD-EFGH",
+ "expires_in": 600,
+ "interval": 2,
+ },
+ ),
+ (400, {"error": "authorization_pending"}),
+ (
+ 200,
+ {
+ "access_token": "access-token",
+ "refresh_token": "refresh-token",
+ "token_type": "Bearer",
+ "expires_in": 3600,
+ },
+ ),
+ ]
+ )
+ delays: list[float] = []
+
+ async def sleep(delay: float) -> None:
+ delays.append(delay)
+
+ client = OidcClient(request=requester, sleep=sleep)
+ discovery = await client.discover()
+ device_code = await client.request_device_code(discovery)
+ credentials = await client.poll_for_tokens(discovery, device_code)
+
+ assert credentials.access_token == "access-token"
+ assert credentials.refresh_token == "refresh-token"
+ assert delays == [2]
+ assert requester.calls[0] == (
+ "GET",
+ "https://auth.cua.ai/realms/cyclops-cs/.well-known/openid-configuration",
+ None,
+ )
+ assert requester.calls[1][2] == {
+ "client_id": "cua-cli",
+ "scope": "openid profile offline_access",
+ }
+ assert requester.calls[2][2] == {
+ "grant_type": DEVICE_GRANT_TYPE,
+ "device_code": "device-code",
+ "client_id": "cua-cli",
+ }
+
+
+async def test_refresh_preserves_existing_refresh_token_when_not_rotated() -> None:
+ requester = ScriptedRequester(
+ [
+ (
+ 200,
+ {
+ "access_token": "new-access-token",
+ "expires_in": 3600,
+ },
+ ),
+ ]
+ )
+ credentials = OAuthCredentials(
+ access_token="old-access-token",
+ refresh_token="existing-refresh-token",
+ expires_at=datetime.now(UTC),
+ )
+ discovery = type(
+ "Discovery",
+ (),
+ {"token_endpoint": "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"},
+ )()
+
+ refreshed = await OidcClient(request=requester).refresh(discovery, credentials)
+
+ assert refreshed.access_token == "new-access-token"
+ assert refreshed.refresh_token == "existing-refresh-token"
+ assert requester.calls[0][2] == {
+ "grant_type": "refresh_token",
+ "refresh_token": "existing-refresh-token",
+ "client_id": "cua-cli",
+ }
+
+
+async def test_poll_slow_down_increases_interval() -> None:
+ requester = ScriptedRequester(
+ [
+ (400, {"error": "slow_down"}),
+ (200, {"access_token": "access-token", "expires_in": 3600}),
+ ]
+ )
+ delays: list[float] = []
+
+ async def sleep(delay: float) -> None:
+ delays.append(delay)
+
+ discovery = type(
+ "Discovery",
+ (),
+ {"token_endpoint": "https://auth.cua.ai/realms/cyclops-cs/protocol/openid-connect/token"},
+ )()
+ device_code = type("Device", (), {"device_code": "device", "expires_in": 600, "interval": 3})()
+
+ await OidcClient(request=requester, sleep=sleep).poll_for_tokens(discovery, device_code)
+
+ assert delays == [8]
diff --git a/libs/python/cua-cli/tests/auth/test_store.py b/libs/python/cua-cli/tests/auth/test_store.py
index f0d8484bfa..b540c3a82c 100644
--- a/libs/python/cua-cli/tests/auth/test_store.py
+++ b/libs/python/cua-cli/tests/auth/test_store.py
@@ -1,230 +1,57 @@
-"""Tests for auth.store module."""
+"""Tests for OS-backed OAuth credential storage."""
-import sqlite3
-import threading
+import json
+from datetime import UTC, datetime
from unittest.mock import patch
import pytest
from cua_cli.auth.store import (
- CredentialStore,
+ CredentialStorageError,
+ OAuthCredentials,
clear_credentials,
- get_api_key,
- require_api_key,
- save_api_key,
+ load_credentials,
+ save_credentials,
)
+from keyring.errors import NoKeyringError
-class TestCredentialStore:
- """Tests for CredentialStore class."""
+def credentials() -> OAuthCredentials:
+ return OAuthCredentials(
+ access_token="access-token",
+ refresh_token="refresh-token",
+ expires_at=datetime(2030, 1, 1, tzinfo=UTC),
+ scope="openid profile offline_access",
+ )
- def test_init_creates_database(self, tmp_path):
- """Test that initializing creates the database file."""
- db_path = tmp_path / "test.db"
- CredentialStore(db_path)
- assert db_path.exists()
+def test_save_credentials_uses_keyring() -> None:
+ with patch("cua_cli.auth.store.keyring.set_password") as set_password:
+ save_credentials(credentials())
- def test_init_creates_parent_directory(self, tmp_path):
- """Test that initializing creates parent directories."""
- db_path = tmp_path / "nested" / "dir" / "test.db"
- CredentialStore(db_path)
+ service, account, raw = set_password.call_args.args
+ assert (service, account) == ("run.cua.ai", "cua-cli")
+ assert json.loads(raw)["access_token"] == "access-token"
- assert db_path.parent.exists()
- assert db_path.exists()
- def test_set_and_get(self, tmp_path):
- """Test setting and getting a value."""
- store = CredentialStore(tmp_path / "test.db")
+def test_load_credentials_deserializes_keyring_value() -> None:
+ raw = json.dumps(credentials().to_dict())
+ with patch("cua_cli.auth.store.keyring.get_password", return_value=raw):
+ loaded = load_credentials()
- store.set("test_key", "test_value")
- result = store.get("test_key")
+ assert loaded == credentials()
- assert result == "test_value"
- def test_get_nonexistent_key(self, tmp_path):
- """Test getting a nonexistent key returns None."""
- store = CredentialStore(tmp_path / "test.db")
+def test_clear_credentials_deletes_keyring_value() -> None:
+ with (
+ patch("cua_cli.auth.store.keyring.get_password", return_value="stored"),
+ patch("cua_cli.auth.store.keyring.delete_password") as delete_password,
+ ):
+ assert clear_credentials() is True
- result = store.get("nonexistent")
+ delete_password.assert_called_once_with("run.cua.ai", "cua-cli")
- assert result is None
- def test_set_overwrites_existing(self, tmp_path):
- """Test that setting an existing key overwrites the value."""
- store = CredentialStore(tmp_path / "test.db")
-
- store.set("key", "value1")
- store.set("key", "value2")
- result = store.get("key")
-
- assert result == "value2"
-
- def test_delete_existing_key(self, tmp_path):
- """Test deleting an existing key returns True."""
- store = CredentialStore(tmp_path / "test.db")
-
- store.set("key", "value")
- result = store.delete("key")
-
- assert result is True
- assert store.get("key") is None
-
- def test_delete_nonexistent_key(self, tmp_path):
- """Test deleting a nonexistent key returns False."""
- store = CredentialStore(tmp_path / "test.db")
-
- result = store.delete("nonexistent")
-
- assert result is False
-
- def test_clear_removes_all(self, tmp_path):
- """Test that clear removes all values."""
- store = CredentialStore(tmp_path / "test.db")
-
- store.set("key1", "value1")
- store.set("key2", "value2")
- store.clear()
-
- assert store.get("key1") is None
- assert store.get("key2") is None
-
- def test_wal_mode_enabled(self, tmp_path):
- """Test that WAL mode is enabled for concurrent access."""
- db_path = tmp_path / "test.db"
- CredentialStore(db_path)
-
- conn = sqlite3.connect(db_path)
- try:
- cursor = conn.execute("PRAGMA journal_mode")
- mode = cursor.fetchone()[0]
- assert mode.lower() == "wal"
- finally:
- conn.close()
-
- def test_concurrent_access(self, tmp_path):
- """Test that concurrent access works with WAL mode."""
- db_path = tmp_path / "test.db"
- store = CredentialStore(db_path)
- results = []
- errors = []
-
- def writer():
- try:
- for i in range(10):
- store.set(f"key_{i}", f"value_{i}")
- except Exception as e:
- errors.append(e)
-
- def reader():
- try:
- for i in range(10):
- result = store.get(f"key_{i}")
- if result is not None:
- results.append(result)
- except Exception as e:
- errors.append(e)
-
- threads = [
- threading.Thread(target=writer),
- threading.Thread(target=reader),
- threading.Thread(target=reader),
- ]
-
- for t in threads:
- t.start()
- for t in threads:
- t.join()
-
- assert len(errors) == 0
-
-
-class TestGetApiKey:
- """Tests for get_api_key function."""
-
- def test_returns_env_var_first(self, monkeypatch, tmp_path):
- """Test that environment variable takes precedence."""
- # Set up a store with a different value
- with patch("cua_cli.auth.store.CREDENTIALS_DB", tmp_path / "test.db"):
- with patch("cua_cli.auth.store._store", None):
- monkeypatch.setenv("CUA_API_KEY", "env-key")
- save_api_key("stored-key")
-
- result = get_api_key()
-
- assert result == "env-key"
-
- def test_falls_back_to_stored(self, monkeypatch, tmp_path):
- """Test that stored key is used when env var not set."""
- with patch("cua_cli.auth.store.CREDENTIALS_DB", tmp_path / "test.db"):
- with patch("cua_cli.auth.store._store", None):
- monkeypatch.delenv("CUA_API_KEY", raising=False)
- save_api_key("stored-key")
-
- result = get_api_key()
-
- assert result == "stored-key"
-
- def test_returns_none_when_not_found(self, monkeypatch, tmp_path):
- """Test that None is returned when no key is found."""
- with patch("cua_cli.auth.store.CREDENTIALS_DB", tmp_path / "test.db"):
- with patch("cua_cli.auth.store._store", None):
- monkeypatch.delenv("CUA_API_KEY", raising=False)
-
- result = get_api_key()
-
- assert result is None
-
-
-class TestSaveApiKey:
- """Tests for save_api_key function."""
-
- def test_saves_api_key(self, tmp_path, monkeypatch):
- """Test that API key is saved correctly."""
- with patch("cua_cli.auth.store.CREDENTIALS_DB", tmp_path / "test.db"):
- with patch("cua_cli.auth.store._store", None):
- monkeypatch.delenv("CUA_API_KEY", raising=False)
-
- save_api_key("my-api-key")
- result = get_api_key()
-
- assert result == "my-api-key"
-
-
-class TestClearCredentials:
- """Tests for clear_credentials function."""
-
- def test_clears_all_credentials(self, tmp_path, monkeypatch):
- """Test that all credentials are cleared."""
- with patch("cua_cli.auth.store.CREDENTIALS_DB", tmp_path / "test.db"):
- with patch("cua_cli.auth.store._store", None):
- monkeypatch.delenv("CUA_API_KEY", raising=False)
-
- save_api_key("my-api-key")
- clear_credentials()
- result = get_api_key()
-
- assert result is None
-
-
-class TestRequireApiKey:
- """Tests for require_api_key function."""
-
- def test_returns_key_when_available(self, monkeypatch):
- """Test that key is returned when available."""
- monkeypatch.setenv("CUA_API_KEY", "my-api-key")
-
- result = require_api_key()
-
- assert result == "my-api-key"
-
- def test_raises_when_not_available(self, monkeypatch, tmp_path):
- """Test that RuntimeError is raised when no key available."""
- with patch("cua_cli.auth.store.CREDENTIALS_DB", tmp_path / "test.db"):
- with patch("cua_cli.auth.store._store", None):
- monkeypatch.delenv("CUA_API_KEY", raising=False)
-
- with pytest.raises(RuntimeError) as exc_info:
- require_api_key()
-
- assert "No API key configured" in str(exc_info.value)
- assert "cua auth login" in str(exc_info.value)
+def test_store_errors_explain_secure_storage_requirement() -> None:
+ with patch("cua_cli.auth.store.keyring.get_password", side_effect=NoKeyringError):
+ with pytest.raises(CredentialStorageError, match="secure credential store"):
+ load_credentials()
diff --git a/libs/python/cua-cli/tests/commands/test_auth.py b/libs/python/cua-cli/tests/commands/test_auth.py
index 457997a6ee..2615813ded 100644
--- a/libs/python/cua-cli/tests/commands/test_auth.py
+++ b/libs/python/cua-cli/tests/commands/test_auth.py
@@ -1,200 +1,84 @@
-"""Tests for auth command module."""
+"""Tests for authentication commands."""
import argparse
+import asyncio
+from datetime import UTC, datetime, timedelta
from unittest.mock import patch
+from cua_cli.auth.store import OAuthCredentials
from cua_cli.commands import auth
-class TestRegisterParser:
- """Tests for register_parser function."""
+class FakeOidcClient:
+ async def discover(self):
+ return object()
- def test_registers_auth_command(self):
- """Test that auth command is registered."""
- parser = argparse.ArgumentParser()
- subparsers = parser.add_subparsers()
+ async def request_device_code(self, _discovery):
+ return type(
+ "DeviceCode",
+ (),
+ {
+ "verification_uri": "https://run.cua.ai/device",
+ "verification_uri_complete": "https://run.cua.ai/device?user_code=ABCD-EFGH",
+ "user_code": "ABCD-EFGH",
+ },
+ )()
- auth.register_parser(subparsers)
+ async def poll_for_tokens(self, _discovery, _device_code):
+ return OAuthCredentials(
+ access_token="access-token",
+ refresh_token="refresh-token",
+ expires_at=datetime.now(UTC) + timedelta(hours=1),
+ )
- args = parser.parse_args(["auth", "login"])
- assert args.auth_command == "login"
+ async def revoke(self, _discovery, _credentials):
+ return True
- def test_login_has_api_key_flag(self):
- """Test that login has --api-key flag."""
- parser = argparse.ArgumentParser()
- subparsers = parser.add_subparsers()
- auth.register_parser(subparsers)
- args = parser.parse_args(["auth", "login", "--api-key", "my-key"])
- assert args.api_key == "my-key"
+def run(coroutine):
+ return asyncio.run(coroutine)
- def test_logout_command(self):
- """Test that logout command is registered."""
- parser = argparse.ArgumentParser()
- subparsers = parser.add_subparsers()
- auth.register_parser(subparsers)
- args = parser.parse_args(["auth", "logout"])
- assert args.auth_command == "logout"
+def test_login_uses_device_flow_without_opening_browser(monkeypatch) -> None:
+ saved: list[OAuthCredentials] = []
+ monkeypatch.setattr(auth, "OidcClient", FakeOidcClient)
+ monkeypatch.setattr(auth, "run_async", run)
+ monkeypatch.setattr(auth, "save_credentials", saved.append)
- def test_env_command(self):
- """Test that env command is registered."""
- parser = argparse.ArgumentParser()
- subparsers = parser.add_subparsers()
- auth.register_parser(subparsers)
+ with patch.object(auth.webbrowser, "open") as browser_open:
+ result = auth.cmd_login(argparse.Namespace(no_browser=True))
- args = parser.parse_args(["auth", "env"])
- assert args.auth_command == "env"
+ assert result == 0
+ assert saved[0].access_token == "access-token"
+ browser_open.assert_not_called()
-class TestExecute:
- """Tests for execute function."""
+def test_logout_clears_local_credentials_when_remote_revocation_fails(monkeypatch) -> None:
+ credentials = OAuthCredentials(
+ access_token="access-token",
+ refresh_token="refresh-token",
+ expires_at=datetime.now(UTC) + timedelta(hours=1),
+ )
+ monkeypatch.setattr(auth, "load_credentials", lambda: credentials)
+ monkeypatch.setattr(auth, "OidcClient", FakeOidcClient)
+ monkeypatch.setattr(auth, "run_async", run)
- def test_dispatch_to_login(self, args_namespace):
- """Test dispatch to login command."""
- args = args_namespace(command="auth", auth_command="login", api_key=False)
+ with patch.object(auth, "clear_credentials") as clear:
+ result = auth.cmd_logout(argparse.Namespace())
- with patch.object(auth, "cmd_login", return_value=0) as mock_cmd:
- result = auth.execute(args)
+ assert result == 0
+ clear.assert_called_once()
- mock_cmd.assert_called_once_with(args)
- assert result == 0
- def test_dispatch_to_logout(self, args_namespace):
- """Test dispatch to logout command."""
- args = args_namespace(command="auth", auth_command="logout")
+def test_status_does_not_expose_token(capsys, monkeypatch) -> None:
+ credentials = OAuthCredentials(
+ access_token="secret-access-token",
+ refresh_token="secret-refresh-token",
+ expires_at=datetime.now(UTC) + timedelta(hours=1),
+ )
+ monkeypatch.setattr(auth, "load_credentials", lambda: credentials)
- with patch.object(auth, "cmd_logout", return_value=0) as mock_cmd:
- auth.execute(args)
-
- mock_cmd.assert_called_once_with(args)
-
- def test_dispatch_to_env(self, args_namespace):
- """Test dispatch to env command."""
- args = args_namespace(command="auth", auth_command="env")
-
- with patch.object(auth, "cmd_env", return_value=0) as mock_cmd:
- auth.execute(args)
-
- mock_cmd.assert_called_once_with(args)
-
- def test_unknown_command_returns_error(self, args_namespace):
- """Test that unknown command returns error."""
- args = args_namespace(command="auth", auth_command=None)
-
- with patch.object(auth, "print_error"):
- result = auth.execute(args)
-
- assert result == 1
-
-
-class TestCmdLogin:
- """Tests for cmd_login function."""
-
- def test_login_with_api_key_direct(self, args_namespace):
- """Test login with --api-key flag and value."""
- args = args_namespace(api_key="test-api-key")
-
- with patch.object(auth, "get_api_key", return_value=None):
- with patch.object(auth, "save_api_key") as mock_save:
- with patch.object(auth, "print_info"):
- with patch.object(auth, "print_success"):
- result = auth.cmd_login(args)
-
- mock_save.assert_called_once_with("test-api-key")
- assert result == 0
-
- def test_login_already_authenticated(self, args_namespace):
- """Test login when already authenticated."""
- args = args_namespace(api_key=None)
-
- with patch.object(auth, "get_api_key", return_value="existing-key"):
- with patch.object(auth, "print_info") as mock_info:
- result = auth.cmd_login(args)
-
- assert result == 0
- mock_info.assert_called()
-
- def test_login_browser_flow(self, args_namespace):
- """Test login with browser OAuth flow."""
- args = args_namespace(api_key=None)
-
- with patch.object(auth, "get_api_key", return_value=None):
- with patch.object(auth, "run_async") as mock_run:
- mock_run.return_value = "browser-api-key"
- with patch.object(auth, "save_api_key") as mock_save:
- with patch.object(auth, "print_success"):
- result = auth.cmd_login(args)
-
- mock_save.assert_called_once_with("browser-api-key")
- assert result == 0
-
- def test_login_browser_flow_timeout(self, args_namespace):
- """Test login when browser flow times out."""
- args = args_namespace(api_key=None)
-
- with patch.object(auth, "get_api_key", return_value=None):
- with patch.object(auth, "run_async") as mock_run:
- mock_run.side_effect = TimeoutError("Authentication timed out")
- with patch.object(auth, "print_error"):
- result = auth.cmd_login(args)
-
- assert result == 1
-
-
-class TestCmdLogout:
- """Tests for cmd_logout function."""
-
- def test_logout_clears_credentials(self, args_namespace):
- """Test that logout clears credentials."""
- args = args_namespace()
-
- with patch.object(auth, "clear_credentials") as mock_clear:
- with patch.object(auth, "print_success"):
- result = auth.cmd_logout(args)
-
- mock_clear.assert_called_once()
- assert result == 0
-
-
-class TestCmdEnv:
- """Tests for cmd_env function."""
-
- def test_env_writes_to_dotenv(self, args_namespace, tmp_path, monkeypatch):
- """Test that env command writes to .env file."""
- args = args_namespace(file=str(tmp_path / ".env"))
-
- with patch.object(auth, "get_api_key", return_value="test-api-key"):
- with patch.object(auth, "print_success"):
- result = auth.cmd_env(args)
-
- assert result == 0
- env_file = tmp_path / ".env"
- assert env_file.exists()
- content = env_file.read_text()
- assert "CUA_API_KEY=test-api-key" in content
-
- def test_env_no_credentials_fails(self, args_namespace, tmp_path):
- """Test that env command fails when not logged in."""
- args = args_namespace(file=str(tmp_path / ".env"))
-
- with patch.object(auth, "get_api_key", return_value=None):
- with patch.object(auth, "print_error"):
- result = auth.cmd_env(args)
-
- assert result == 1
-
- def test_env_appends_to_existing_dotenv(self, args_namespace, tmp_path):
- """Test that env command appends to existing .env file."""
- env_file = tmp_path / ".env"
- env_file.write_text("EXISTING_VAR=value\n")
- args = args_namespace(file=str(env_file))
-
- with patch.object(auth, "get_api_key", return_value="test-api-key"):
- with patch.object(auth, "print_success"):
- result = auth.cmd_env(args)
-
- assert result == 0
- content = env_file.read_text()
- assert "EXISTING_VAR=value" in content
- assert "CUA_API_KEY=test-api-key" in content
+ assert auth.cmd_status(argparse.Namespace()) == 0
+ output = capsys.readouterr().out
+ assert "secret-access-token" not in output
+ assert "secret-refresh-token" not in output
diff --git a/libs/python/cua-cli/tests/conftest.py b/libs/python/cua-cli/tests/conftest.py
index f269da5b45..fdb9786abe 100644
--- a/libs/python/cua-cli/tests/conftest.py
+++ b/libs/python/cua-cli/tests/conftest.py
@@ -30,33 +30,17 @@ def disable_telemetry(monkeypatch):
monkeypatch.setenv("CUA_TELEMETRY_ENABLED", "false")
-def temp_credentials_db(tmp_path, monkeypatch):
- """Provide a temporary credentials database."""
- cua_dir = tmp_path / ".cua"
- cua_dir.mkdir(parents=True)
- db_path = cua_dir / "credentials.db"
-
- # Patch the CREDENTIALS_DB path in the store module
- monkeypatch.setattr("cua_cli.auth.store.CREDENTIALS_DB", db_path)
-
- yield db_path
-
- if db_path.exists():
- db_path.unlink()
-
-
@pytest.fixture
def mock_api_key(monkeypatch):
- """Set a mock API key in environment."""
- monkeypatch.setenv("CUA_API_KEY", "test-api-key-12345")
- return "test-api-key-12345"
+ """Provide a refreshable bearer token without invoking OIDC."""
+ async def token() -> str:
+ return "test-access-token"
-def clear_api_key_env(monkeypatch):
- """Ensure no API key is in environment."""
- monkeypatch.delenv("CUA_API_KEY", raising=False)
+ monkeypatch.setattr("cua_cli.auth.oidc.get_access_token", token)
+ monkeypatch.setattr("cua_cli.api.client.get_access_token", token)
+ monkeypatch.setattr("cua_cli.commands.sandbox.get_access_token", token)
+ return "test-access-token"
@pytest.fixture
diff --git a/libs/python/cua-cli/uv.lock b/libs/python/cua-cli/uv.lock
index 6eb9ef8cc1..697af01b5f 100644
--- a/libs/python/cua-cli/uv.lock
+++ b/libs/python/cua-cli/uv.lock
@@ -420,6 +420,7 @@ dependencies = [
{ name = "cua-auto", extra = ["all"] },
{ name = "cua-computer" },
{ name = "cua-core" },
+ { name = "keyring" },
{ name = "pillow" },
{ name = "rich" },
{ name = "websockets" },
@@ -452,6 +453,7 @@ requires-dist = [
{ name = "cua-computer", specifier = ">=0.5.0" },
{ name = "cua-core", specifier = ">=0.3.0,<0.4.0" },
{ name = "fastmcp", marker = "extra == 'mcp'", specifier = ">=2.0" },
+ { name = "keyring", specifier = ">=25.0" },
{ name = "litellm", marker = "extra == 'skills'", specifier = "==1.86.2" },
{ name = "pillow", specifier = ">=10.0.0" },
{ name = "pytest", marker = "extra == 'dev'", specifier = ">=8.0.0" },
@@ -560,7 +562,7 @@ name = "ewmhlib"
version = "0.2"
source = { registry = "https://pypi.org/simple" }
dependencies = [
- { name = "python-xlib", marker = "sys_platform == 'linux'" },
+ { name = "python-xlib" },
{ name = "typing-extensions" },
]
wheels = [