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): CUA_ENV=staging targets the Cua staging deployment (CUA-1395) (#5013)

Francesco Bonacci72f329d85246
diff --git a/apps/cua-spaces-desktop/src/model/daemon.ts b/apps/cua-spaces-desktop/src/model/daemon.ts
index 63883c5c72..89eb648485 100644
--- a/apps/cua-spaces-desktop/src/model/daemon.ts
+++ b/apps/cua-spaces-desktop/src/model/daemon.ts
@@ -26,10 +26,11 @@ export const KEYCHAIN_NONINTERACTIVE_ENV = "CUA_KEYCHAIN_NONINTERACTIVE";
/** `CUA_DAEMON_KEEP` (cua-daemon's `identity::KEEP_ENV`): other apps' daemon executables this app replaced once. */
export const DAEMON_KEEP_ENV = "CUA_DAEMON_KEEP";
-/** The cua home the daemon uses (`CUA_HOME`, else `~/.cua`). */
+/** The cua home the daemon uses (`CUA_HOME`, else `~/.cua`, or `~/.cua/envs/staging` for `CUA_ENV=staging`, as cua-home resolves it). */
export function cuaHome(env: NodeJS.ProcessEnv = process.env): string {
if (env.CUA_HOME) return env.CUA_HOME;
- return path.join(env.HOME || env.USERPROFILE || os.homedir(), ".cua");
+ const base = path.join(env.HOME || env.USERPROFILE || os.homedir(), ".cua");
+ return (env.CUA_ENV ?? "").trim().toLowerCase() === "staging" ? path.join(base, "envs", "staging") : base;
}
/** The daemon still starting (`daemon.starting`) and the one running (`daemon.json`), as their files name them. */
diff --git a/apps/cua-spaces-desktop/test/daemon-startup.test.ts b/apps/cua-spaces-desktop/test/daemon-startup.test.ts
index b3bab21d61..ad58118bce 100644
--- a/apps/cua-spaces-desktop/test/daemon-startup.test.ts
+++ b/apps/cua-spaces-desktop/test/daemon-startup.test.ts
@@ -41,6 +41,8 @@ describe("the daemon's files", () => {
it("finds the cua home in CUA_HOME, else ~/.cua", () => {
expect(cuaHome({ CUA_HOME: "/x/.cua" })).toBe("/x/.cua");
expect(cuaHome({ HOME: "/home/ada" })).toBe(path.join("/home/ada", ".cua"));
+ expect(cuaHome({ HOME: "/home/ada", CUA_ENV: "staging" })).toBe(path.join("/home/ada", ".cua", "envs", "staging"));
+ expect(cuaHome({ HOME: "/home/ada", CUA_ENV: "staging", CUA_HOME: "/x" })).toBe("/x");
});
it("backs off from 2 s to a minute", () => {
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift
index a8f64f6484..33e34fe593 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift
@@ -17,6 +17,9 @@ if CommandLine.arguments.dropFirst().first == "--check-launch-only" {
exit(0)
}
+// `CUA_ENV=staging`: this process and the daemon use the staging home.
+TargetEnvironment.pin()
+
// Teleport, the Cua Volume, persistent agents and the Keyvault for every
// runtime the SDK builds in this process (the Cua Spaces extensions).
cuaSpacesRegister()
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/TargetEnvironment.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/TargetEnvironment.swift
new file mode 100644
index 0000000000..90020f686e
--- /dev/null
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/TargetEnvironment.swift
@@ -0,0 +1,40 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import Foundation
+
+/// Which Cua deployment the app talks to: `CUA_ENV` (`prod`, the default, or
+/// `staging`). The SDK resolves every endpoint from it. The app only settles
+/// it before anything starts:
+///
+/// - `CUA_ENV` unset: the bundle's `CuaEnv` Info.plist value, which a beta
+/// channel build sets to `staging` (`scripts/build-release.sh` with
+/// `CUA_CHANNEL=beta`); release builds have none (production);
+/// - `CUA_HOME` unset under staging: `~/.cua/envs/staging`, so the daemon it
+/// supervises and every file it reads use the same home as the SDK.
+public enum TargetEnvironment {
+ /// The variables to set for `env` and the bundle's `CuaEnv` value.
+ public static func pinned(env: [String: String], bundleEnv: String?, home: String) -> [String: String] {
+ var out: [String: String] = [:]
+ var name = env["CUA_ENV"]
+ if name == nil, let bundleEnv, !bundleEnv.isEmpty {
+ name = bundleEnv
+ out["CUA_ENV"] = bundleEnv
+ }
+ let normalized = (name ?? "").trimmingCharacters(in: .whitespaces).lowercased()
+ if normalized == "staging", (env["CUA_HOME"] ?? "").isEmpty {
+ out["CUA_HOME"] = URL(fileURLWithPath: home, isDirectory: true)
+ .appendingPathComponent(".cua/envs/staging", isDirectory: true).path
+ }
+ return out
+ }
+
+ /// Applies [`pinned`] to this process. Call first in `main`.
+ public static func pin(bundle: Bundle = .main) {
+ let env = ProcessInfo.processInfo.environment
+ let bundleEnv = bundle.object(forInfoDictionaryKey: "CuaEnv") as? String
+ for (key, value) in pinned(env: env, bundleEnv: bundleEnv, home: env["HOME"] ?? NSHomeDirectory()) {
+ setenv(key, value, 1)
+ }
+ }
+}
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/TargetEnvironmentTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/TargetEnvironmentTests.swift
new file mode 100644
index 0000000000..046df594fb
--- /dev/null
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/TargetEnvironmentTests.swift
@@ -0,0 +1,28 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+@testable import CuaSpacesMacKit
+import Foundation
+import Testing
+
+/// `CUA_ENV`: production changes nothing; staging gets its own home; a beta
+/// build's bundle default applies only when `CUA_ENV` is unset.
+@Suite("Target environment")
+struct TargetEnvironmentTests {
+ @Test func productionChangesNothing() {
+ #expect(TargetEnvironment.pinned(env: [:], bundleEnv: nil, home: "/Users/ada").isEmpty)
+ #expect(TargetEnvironment.pinned(env: ["CUA_ENV": "prod"], bundleEnv: "staging", home: "/Users/ada").isEmpty)
+ }
+
+ @Test func stagingUsesItsOwnHome() {
+ #expect(TargetEnvironment.pinned(env: ["CUA_ENV": "Staging"], bundleEnv: nil, home: "/Users/ada")
+ == ["CUA_HOME": "/Users/ada/.cua/envs/staging"])
+ #expect(TargetEnvironment.pinned(env: ["CUA_ENV": "staging", "CUA_HOME": "/tmp/h"], bundleEnv: nil, home: "/Users/ada")
+ .isEmpty)
+ }
+
+ @Test func betaBundleDefaultsToStaging() {
+ #expect(TargetEnvironment.pinned(env: [:], bundleEnv: "staging", home: "/Users/ada")
+ == ["CUA_ENV": "staging", "CUA_HOME": "/Users/ada/.cua/envs/staging"])
+ }
+}
diff --git a/apps/cua-spaces-macos/scripts/build-release.sh b/apps/cua-spaces-macos/scripts/build-release.sh
index 0107b6d48e..6cf8ed7a8b 100755
--- a/apps/cua-spaces-macos/scripts/build-release.sh
+++ b/apps/cua-spaces-macos/scripts/build-release.sh
@@ -19,7 +19,14 @@
#
# scripts/build-release.sh --version 0.2.0[-suffix] [--build-number N]
# [--arch universal|arm64|x86_64] [--sign IDENTITY] [--out DIR]
-# [--feed-url URL] [--skip-cargo]
+# [--feed-url URL] [--channel stable|beta] [--skip-cargo]
+#
+# --channel beta builds the beta channel: it talks to Cua staging by default
+# (Info.plist CuaEnv=staging, and the bundled cua is compiled with
+# CUA_DEFAULT_ENV=staging), with a staging session and home
+# (~/.cua/envs/staging). CUA_ENV=prod at launch still selects production.
+# stable (the default) is production. With --skip-cargo, build the reused
+# binaries with CUA_DEFAULT_ENV=staging yourself.
#
# --feed-url sets the updater's appcast (SUFeedURL; default Support/Info.plist's,
# trycua/cua's rolling cua-spaces-latest release). The release workflow passes
@@ -52,6 +59,7 @@ identity="-"
out="$here/.build/release-app"
skip_cargo=0
feed_url=""
+channel=stable
while [ $# -gt 0 ]; do
case "$1" in
--version) version="$2"; shift ;;
@@ -61,7 +69,8 @@ while [ $# -gt 0 ]; do
--out) out="$2"; shift ;;
--skip-cargo) skip_cargo=1 ;;
--feed-url) feed_url="$2"; shift ;;
- -h | --help) sed -n '5,37p' "$0"; exit 0 ;;
+ --channel) channel="$2"; shift ;;
+ -h | --help) sed -n '5,45p' "$0"; exit 0 ;;
*) echo "unknown option: $1" >&2; exit 2 ;;
esac
shift
@@ -86,13 +95,18 @@ case "$arch" in
arm64 | x86_64) archs="$arch" ;;
*) echo "--arch must be universal, arm64 or x86_64" >&2; exit 2 ;;
esac
+case "$channel" in
+ stable) default_env="" ;;
+ beta) default_env=staging ;;
+ *) echo "--channel must be stable or beta" >&2; exit 2 ;;
+esac
triple() { [ "$1" = arm64 ] && echo aarch64-apple-darwin || echo x86_64-apple-darwin; }
target="${CARGO_TARGET_DIR:-$cua/target}"
case "$target" in /*) ;; *) target="$cua/$target" ;; esac
if [ "$skip_cargo" = 0 ]; then
for a in $archs; do
- (cd "$cua" && cargo build --locked --release -p cua-spaces-ffi -p cua-spaces-cli --target "$(triple "$a")")
+ (cd "$cua" && CUA_DEFAULT_ENV="$default_env" cargo build --locked --release -p cua-spaces-ffi -p cua-spaces-cli --target "$(triple "$a")")
done
fi
@@ -122,6 +136,10 @@ plist="$app/Contents/Info.plist"
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $bundle_version" "$plist"
/usr/libexec/PlistBuddy -c "Delete :CuaVersion" "$plist" 2>/dev/null || true
/usr/libexec/PlistBuddy -c "Add :CuaVersion string $version" "$plist"
+/usr/libexec/PlistBuddy -c "Delete :CuaEnv" "$plist" 2>/dev/null || true
+if [ -n "$default_env" ]; then
+ /usr/libexec/PlistBuddy -c "Add :CuaEnv string $default_env" "$plist"
+fi
if [ -n "$feed_url" ]; then
case "$feed_url" in https://*) ;; *) echo "--feed-url must be https" >&2; exit 2 ;; esac
/usr/libexec/PlistBuddy -c "Set :SUFeedURL $feed_url" "$plist"
diff --git a/apps/cua-spaces/core-wasm/Cargo.lock b/apps/cua-spaces/core-wasm/Cargo.lock
index 62d0b9a697..78a43b64bf 100644
--- a/apps/cua-spaces/core-wasm/Cargo.lock
+++ b/apps/cua-spaces/core-wasm/Cargo.lock
@@ -14,10 +14,19 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+[[package]]
+name = "cua-home"
+version = "0.1.0"
+dependencies = [
+ "libc",
+ "windows-sys",
+]
+
[[package]]
name = "cua-spaces-app-core"
version = "0.1.0"
dependencies = [
+ "cua-home",
"serde",
"serde_json",
]
@@ -73,6 +82,12 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "libc"
+version = "0.2.190"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
+
[[package]]
name = "memchr"
version = "2.8.3"
@@ -237,6 +252,21 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
[[package]]
name = "zmij"
version = "1.0.23"
diff --git a/apps/cua-spaces/src-tauri/Cargo.lock b/apps/cua-spaces/src-tauri/Cargo.lock
index 955c0b65cb..62d833e847 100644
--- a/apps/cua-spaces/src-tauri/Cargo.lock
+++ b/apps/cua-spaces/src-tauri/Cargo.lock
@@ -1653,6 +1653,7 @@ name = "cua-spaces-app-core"
version = "0.1.0"
dependencies = [
"async-trait",
+ "cua-home",
"cua-keyvault",
"cua-telemetry",
"serde",
diff --git a/docs/content/docs/cua-cli/guides/authentication.mdx b/docs/content/docs/cua-cli/guides/authentication.mdx
index 72bb01f214..24e97fef79 100644
--- a/docs/content/docs/cua-cli/guides/authentication.mdx
+++ b/docs/content/docs/cua-cli/guides/authentication.mdx
@@ -81,5 +81,49 @@ steps:
run `cua auth logout` when done, or use an API key or workload token.
</Callout>
+## Targeting staging
+
+`CUA_ENV=staging` points the CLI, the SDK, `cua daemon` and the Cua Spaces app
+at the Cua staging deployment. Unset, or `prod`, is production. Any other value
+makes `cua` exit with code `2` rather than fall back to production.
+
+```bash test="cli-shape" id="cua-env-staging"
+export CUA_ENV=staging
+cua auth login --remote # device code against the staging realm
+cua auth status # starts with "Environment: staging (...)"
+```
+
+| Setting | Override (wins over `CUA_ENV`) | `prod` (default) | `staging` |
+|---------|--------------------------------|------------------|-----------|
+| Sign-in issuer | `CUA_OIDC_ISSUER` | `https://auth.cua.ai/realms/cyclops-cs` | `https://auth.cua.ai/realms/cua-staging` |
+| OAuth client | `CUA_OIDC_CLIENT_ID` | `cua-cli` | `cua-cli` |
+| Relay | `CUA_RELAY_URL` (or `--relay`) | `https://relay.cua.ai` | `https://relay.staging.cua.ai` |
+| Spaces API | `CUA_SPACES_API_URL` | `https://api.spaces.cua.ai` | `https://api.staging.cua.ai` |
+| Spaces site (add-machine links `<site>/add/<code>`) | `CUA_SPACES_SITE_URL` | `https://spaces.cua.ai` | `https://spaces.staging.cua.ai` |
+| cua home | `CUA_HOME` | `~/.cua` | `~/.cua/envs/staging` |
+| Keychain / Credential Manager service | none | `run.cua.ai` | `staging.run.cua.ai` |
+
+Each environment has its own session, host enrollment, Spaces registry and
+daemon, so signing in to staging never replaces or sends your production
+session, and the other way round. Fleet has no staging deployment: under
+`CUA_ENV=staging` the CLI does not send the staging session to
+`https://run.cua.ai`, so cloud sandboxes need `CUA_FLEET_BASE_URL` set to a
+non-production Fleet, or an API key.
+
+Usage telemetry follows the environment too: staging events go to the staging
+PostHog project, never to production's. `CUA_POSTHOG_KEY` overrides the
+project key; `CUA_TELEMETRY_ENDPOINT` overrides the ingest URL.
+
+Beta channel builds talk to staging by default. A `cua` compiled with
+`CUA_DEFAULT_ENV=staging` treats an unset `CUA_ENV` as `staging`, and the macOS
+app built with `scripts/build-release.sh --channel beta` carries `CuaEnv=staging`
+in its `Info.plist` and compiles its bundled `cua` the same way. `CUA_ENV=prod`
+still selects production in a beta build.
+
+For the macOS app, launch it with the variable set:
+`open -n --env CUA_ENV=staging -a "Cua Spaces"`. Quit the production app
+first. The host service (`cua host setup`) has one name on each machine, so pair
+a staging host on a separate machine or VM.
+
Other variables (`CUA_FLEET_BASE_URL`, `CUA_OIDC_ISSUER`, `CUA_AUTH_FLOW`,
`CUA_NO_BROWSER`, ...) are listed in the [CLI reference](/cua-cli/reference/cli).
diff --git a/docs/content/docs/cua-cli/reference/cli/devices.mdx b/docs/content/docs/cua-cli/reference/cli/devices.mdx
index c2aa90fcec..c4ce71376c 100644
--- a/docs/content/docs/cua-cli/reference/cli/devices.mdx
+++ b/docs/content/docs/cua-cli/reference/cli/devices.mdx
@@ -49,7 +49,7 @@ cua devices status [OPTIONS]
| Flag | Type | Default | Description |
| --- | --- | --- | --- |
-| <span id="cua-devices-status--relay"></span>`--relay` | string | | Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai). |
+| <span id="cua-devices-status--relay"></span>`--relay` | string | | Relay URL (default $CUA_RELAY_URL, else the CUA_ENV relay, https://relay.cua.ai in production). |
**Examples**
diff --git a/docs/content/docs/cua-cli/reference/cli/host.mdx b/docs/content/docs/cua-cli/reference/cli/host.mdx
index 6674d241f8..1daef3428f 100644
--- a/docs/content/docs/cua-cli/reference/cli/host.mdx
+++ b/docs/content/docs/cua-cli/reference/cli/host.mdx
@@ -42,7 +42,7 @@ cua host setup [OPTIONS]
| Flag | Type | Default | Description |
| --- | --- | --- | --- |
-| <span id="cua-host-setup--relay"></span>`--relay` | string | | Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai). |
+| <span id="cua-host-setup--relay"></span>`--relay` | string | | Relay URL (default $CUA_RELAY_URL, else the CUA_ENV relay, https://relay.cua.ai in production). |
| <span id="cua-host-setup--pair"></span>`--pair` | string | | Join with a one-time pairing code (or add-machine link) made in the Cua Spaces app or with `cua host pair`, instead of signing in here. The machine joins the account (or team) that made it. |
| <span id="cua-host-setup--direct"></span>`--direct` | string | | Serve directly on ip:port with a local env token (LAN / port-forwarded) instead of joining a relay. |
| <span id="cua-host-setup--name"></span>`--name` | string | | Display name (default: the host name). |
@@ -92,7 +92,7 @@ cua host pair [OPTIONS]
| <span id="cua-host-pair--name"></span>`--name` | string | | Name the machine gets (default: its own host name). |
| <span id="cua-host-pair--expires"></span>`--expires` | integer | `30` | Minutes until the code expires (1 to 1440). |
| <span id="cua-host-pair--revoke"></span>`--revoke` | string | | Revoke an unused code by id (`pc_…`). |
-| <span id="cua-host-pair--relay"></span>`--relay` | string | | Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai). |
+| <span id="cua-host-pair--relay"></span>`--relay` | string | | Relay URL (default $CUA_RELAY_URL, else the CUA_ENV relay, https://relay.cua.ai in production). |
| <span id="cua-host-pair--list"></span>`--list` | boolean | `false` | List your codes (used, unused, revoked, expired) instead. |
**Examples**
diff --git a/docs/content/docs/cua-cli/reference/cli/spaces.mdx b/docs/content/docs/cua-cli/reference/cli/spaces.mdx
index c89ee12ac4..ac5d326859 100644
--- a/docs/content/docs/cua-cli/reference/cli/spaces.mdx
+++ b/docs/content/docs/cua-cli/reference/cli/spaces.mdx
@@ -49,7 +49,7 @@ Alias: `cua spaces list`.
| Flag | Type | Default | Description |
| --- | --- | --- | --- |
-| <span id="cua-spaces-ls--relay"></span>`--relay` | string | | Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai). |
+| <span id="cua-spaces-ls--relay"></span>`--relay` | string | | Relay URL (default $CUA_RELAY_URL, else the CUA_ENV relay, https://relay.cua.ai in production). |
**Examples**
diff --git a/docs/content/docs/cua-cli/reference/cli/usage.mdx b/docs/content/docs/cua-cli/reference/cli/usage.mdx
index b990c85e75..b87a53c995 100644
--- a/docs/content/docs/cua-cli/reference/cli/usage.mdx
+++ b/docs/content/docs/cua-cli/reference/cli/usage.mdx
@@ -22,7 +22,7 @@ cua usage [OPTIONS]
| Flag | Type | Default | Description |
| --- | --- | --- | --- |
-| <span id="cua-usage--relay"></span>`--relay` | string | | Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai). |
+| <span id="cua-usage--relay"></span>`--relay` | string | | Relay URL (default $CUA_RELAY_URL, else the CUA_ENV relay, https://relay.cua.ai in production). |
**Examples**
diff --git a/docs/content/docs/cua-sdk/reference/rust/cua-fleet.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-fleet.mdx
index 81ac39e489..e244bff0df 100644
--- a/docs/content/docs/cua-sdk/reference/rust/cua-fleet.mdx
+++ b/docs/content/docs/cua-sdk/reference/rust/cua-fleet.mdx
@@ -297,6 +297,7 @@ pub struct FleetConfig {
impl FleetConfig {
fn from_env() -> Self;
fn from_lookup(get: impl Fn(&str) -> Option<String>) -> Self;
+ fn accepts_session(&self) -> bool;
fn has_auth(&self) -> bool;
}
```
diff --git a/libs/cua/Cargo.lock b/libs/cua/Cargo.lock
index ce76536361..24de7d6368 100644
--- a/libs/cua/Cargo.lock
+++ b/libs/cua/Cargo.lock
@@ -2838,6 +2838,7 @@ name = "cua-spaces-app-core"
version = "0.1.0"
dependencies = [
"async-trait",
+ "cua-home",
"cua-keyvault",
"cua-telemetry",
"serde",
diff --git a/libs/cua/crates/cua-auth/src/lib.rs b/libs/cua/crates/cua-auth/src/lib.rs
index bb968361f7..93f454f7b0 100644
--- a/libs/cua/crates/cua-auth/src/lib.rs
+++ b/libs/cua/crates/cua-auth/src/lib.rs
@@ -7,7 +7,8 @@
//! for the client and falls back to the device flow when it does not, so
//! it works before and after that client change lands.
//! - **Store**: the OS credential vault on Windows and on macOS for builds
-//! signed by Cua (service `run.cua.ai`, account `cua-cli`), a 0600
+//! signed by Cua (service `run.cua.ai`, `staging.run.cua.ai` for
+//! `CUA_ENV=staging`; account `cua-cli`), a 0600
//! `~/.cua/credentials.json` elsewhere (Linux, and unsigned or ad-hoc
//! macOS builds, which macOS treats as a new app on every rebuild so
//! "Always Allow" never sticks) or with `CUA_CREDENTIAL_STORE=file`.
@@ -22,7 +23,9 @@
//! a sign-out or a token another process rotated is seen at once instead
//! of being refreshed twice.
//!
-//! Configuration: `CUA_OIDC_ISSUER`, `CUA_OIDC_CLIENT_ID`; test hooks
+//! Configuration: `CUA_ENV` (`prod` or `staging`: the default issuer, the
+//! vault service and the cua home, so each environment keeps its own
+//! session), `CUA_OIDC_ISSUER` (wins over `CUA_ENV`), `CUA_OIDC_CLIENT_ID`; test hooks
//! `CUA_OIDC_POLL_UNIT_MS`, `CUA_OIDC_REDIRECT_PORT`,
//! `CUA_OIDC_LOGIN_TIMEOUT_SECS`.
@@ -33,7 +36,7 @@ use std::{
time::Duration,
};
-/// Default OIDC issuer (`CUA_OIDC_ISSUER`).
+/// The production OIDC issuer (`CUA_OIDC_ISSUER` and `CUA_ENV` change it).
pub const DEFAULT_OIDC_ISSUER: &str = "https://auth.cua.ai/realms/cyclops-cs";
/// Public OAuth client of the cua CLI and apps (`CUA_OIDC_CLIENT_ID`).
pub const DEFAULT_CLIENT_ID: &str = "cua-cli";
@@ -41,8 +44,12 @@ const DEFAULT_SCOPE: &str = "openid profile offline_access";
const DEVICE_GRANT: &str = "urn:ietf:params:oauth:grant-type:device_code";
/// Refresh this long before expiry.
const REFRESH_SKEW_SECS: i64 = 60;
+/// The OS vault service of the session: `run.cua.ai` in production,
+/// another one per `CUA_ENV`, so environments never share a session.
#[cfg(any(target_os = "macos", target_os = "windows"))]
-const KEYRING_SERVICE: &str = "run.cua.ai";
+fn keyring_service() -> &'static str {
+ cua_home::env::CuaEnv::current().keyring_service()
+}
#[cfg(any(target_os = "macos", target_os = "windows"))]
const KEYRING_ACCOUNT: &str = "cua-cli";
/// The Spaces app's former session file under `~/.cua`.
@@ -404,7 +411,8 @@ impl Store {
Store::TestKeychain(d) => format!("test keychain {}", d.display()),
#[cfg(any(target_os = "macos", target_os = "windows"))]
Store::Keyring => format!(
- "OS credential vault (service {KEYRING_SERVICE}, account {KEYRING_ACCOUNT})"
+ "OS credential vault (service {}, account {KEYRING_ACCOUNT})",
+ keyring_service()
),
}
}
@@ -451,7 +459,7 @@ impl Store {
};
let items = macos_keychain::check_items(
macos_keychain::Keychain::Default,
- KEYRING_SERVICE,
+ keyring_service(),
&wanted,
prompt,
signed_by_cua(),
@@ -476,7 +484,7 @@ impl Store {
#[cfg(target_os = "macos")]
for item in &self.check_keychain(false).items {
if matches!(item.state, KeychainState::NeedsAccess)
- && let Ok(entry) = keyring::Entry::new(KEYRING_SERVICE, &item.account)
+ && let Ok(entry) = keyring::Entry::new(keyring_service(), &item.account)
{
let _ = vault_delete(&entry);
}
@@ -592,7 +600,7 @@ impl Store {
#[cfg(target_os = "macos")]
if macos_keychain::recover_staged(
macos_keychain::Keychain::Default,
- KEYRING_SERVICE,
+ keyring_service(),
KEYRING_ACCOUNT,
) {
return self.load_stored();
@@ -940,7 +948,7 @@ fn adopt_read(account: &str, text: &str) {
if signed_by_cua() {
let _ = macos_keychain::adopt(
macos_keychain::Keychain::Default,
- KEYRING_SERVICE,
+ keyring_service(),
account,
text.as_bytes(),
true,
@@ -1103,14 +1111,14 @@ fn auth_failed(e: &keyring::Error) -> bool {
}
}
-/// Writes the OS vault item `account` (service [`KEYRING_SERVICE`]). On
+/// Writes the OS vault item `account` (service [`keyring_service`]). On
/// macOS the item trusts every Cua executable of this machine, so the app,
/// the daemon and the CLI share it without a keychain prompt (see
/// `macos_keychain`).
#[cfg(target_os = "macos")]
fn vault_set(account: &str, text: &str) -> Result<()> {
let _quiet = quiet();
- macos_keychain::set_generic_password(KEYRING_SERVICE, account, text.as_bytes()).map_err(|e| {
+ macos_keychain::set_generic_password(keyring_service(), account, text.as_bytes()).map_err(|e| {
if e.0 == macos_keychain::ERR_SEC_INTERACTION_NOT_ALLOWED && keychain_noninteractive() {
Error::Store(KEYCHAIN_NEEDS_ACCESS.into())
} else if e.0 == macos_keychain::ERR_SEC_INTERACTION_NOT_ALLOWED {
@@ -1123,7 +1131,7 @@ fn vault_set(account: &str, text: &str) -> Result<()> {
#[cfg(target_os = "windows")]
fn vault_set(account: &str, text: &str) -> Result<()> {
- keyring::Entry::new(KEYRING_SERVICE, account)
+ keyring::Entry::new(keyring_service(), account)
.map_err(store_err)?
.set_password(text)
.map_err(store_err)
@@ -1143,7 +1151,7 @@ fn interaction_not_allowed(e: &keyring::Error) -> bool {
#[cfg(any(target_os = "macos", target_os = "windows"))]
fn keyring_entry() -> Result<keyring::Entry> {
- keyring::Entry::new(KEYRING_SERVICE, KEYRING_ACCOUNT).map_err(store_err)
+ keyring::Entry::new(keyring_service(), KEYRING_ACCOUNT).map_err(store_err)
}
/// Whether a file store at `path` reads missing secrets from the OS
@@ -1179,7 +1187,7 @@ fn decode_secret(name: &str, text: &str) -> Result<Vec<u8>> {
#[cfg(any(target_os = "macos", target_os = "windows"))]
fn secret_entry(name: &str) -> Result<keyring::Entry> {
- keyring::Entry::new(KEYRING_SERVICE, &format!("{KEYRING_ACCOUNT}.{name}")).map_err(store_err)
+ keyring::Entry::new(keyring_service(), &format!("{KEYRING_ACCOUNT}.{name}")).map_err(store_err)
}
/// Writes a file readable only by the owner (0600 on Unix), atomically.
@@ -1240,7 +1248,8 @@ impl Oidc {
}
}
- /// From `CUA_OIDC_ISSUER` / `CUA_OIDC_CLIENT_ID` or the defaults.
+ /// From `CUA_OIDC_ISSUER` (else the `CUA_ENV` issuer) and
+ /// `CUA_OIDC_CLIENT_ID` (else `cua-cli`).
pub fn from_env() -> Self {
let get = |k: &str, d: &str| {
std::env::var(k)
@@ -1249,7 +1258,7 @@ impl Oidc {
.unwrap_or_else(|| d.to_string())
};
Self::new(
- get("CUA_OIDC_ISSUER", DEFAULT_OIDC_ISSUER),
+ cua_home::env::oidc_issuer(),
get("CUA_OIDC_CLIENT_ID", DEFAULT_CLIENT_ID),
)
}
diff --git a/libs/cua/crates/cua-cli/src/auth.rs b/libs/cua/crates/cua-cli/src/auth.rs
index 91880aa212..5fa1521410 100644
--- a/libs/cua/crates/cua-cli/src/auth.rs
+++ b/libs/cua/crates/cua-cli/src/auth.rs
@@ -78,7 +78,7 @@ pub fn fleet_maybe_configured() -> bool {
let cfg = cua_fleet::FleetConfig::from_env();
cfg.fleet_token.is_some()
|| (cfg.client_id.is_some() && cfg.client_secret.is_some())
- || cua_auth::may_have_session()
+ || (cfg.accepts_session() && cua_auth::may_have_session())
}
/// The Fleet configuration from the environment, falling back to the
@@ -92,6 +92,9 @@ pub async fn fleet_config() -> Result<Option<(cua_fleet::FleetConfig, FleetAuth)
let id = id.clone();
return Ok(Some((cfg, FleetAuth::ClientCredentials(id))));
}
+ if !cfg.accepts_session() {
+ return Ok(None);
+ }
match session_token(&Store::from_env()).await? {
Some(t) => {
cfg.fleet_token = Some(t);
@@ -236,10 +239,14 @@ pub async fn status(json: bool, out: &mut dyn Write) -> Result<i32, CuaError> {
let s = session();
let store = s.store().clone();
let c = store.load().map_err(auth_err)?;
+ let endpoints = cua_home::env::Endpoints::current();
if json {
util::json_line(
out,
&serde_json::json!({
+ "env": endpoints.env.name(),
+ "issuer": s.oidc().issuer,
+ "relay": endpoints.relay_url,
"logged_in": c.is_some(),
"expires_at": c.as_ref().map(|c| c.expires_at.clone()),
"identity": c.as_ref().map(|c| c.identity()),
@@ -248,6 +255,18 @@ pub async fn status(json: bool, out: &mut dyn Write) -> Result<i32, CuaError> {
);
return Ok(if c.is_some() { 0 } else { 1 });
}
+ if !endpoints.env.is_prod() {
+ line(
+ out,
+ format!(
+ "Environment: {} (issuer {}, relay {}, home {}).",
+ endpoints.env.name(),
+ s.oidc().issuer,
+ endpoints.relay_url,
+ util::cua_home().display()
+ ),
+ );
+ }
let Some(c) = c else {
line(out, "Not logged in. Run 'cua auth login'.");
return Ok(1);
diff --git a/libs/cua/crates/cua-cli/src/devices_cmd.rs b/libs/cua/crates/cua-cli/src/devices_cmd.rs
index e4be25a234..03ed7d8110 100644
--- a/libs/cua/crates/cua-cli/src/devices_cmd.rs
+++ b/libs/cua/crates/cua-cli/src/devices_cmd.rs
@@ -20,7 +20,7 @@ pub enum DevicesCmd {
#[command(after_help = "Examples:
cua devices status")]
Status {
- /// Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai).
+ /// Relay URL (default $CUA_RELAY_URL, else the CUA_ENV relay, https://relay.cua.ai in production).
#[arg(long)]
relay: Option<String>,
},
diff --git a/libs/cua/crates/cua-cli/src/host.rs b/libs/cua/crates/cua-cli/src/host.rs
index 7fdba49866..e46ccb696c 100644
--- a/libs/cua/crates/cua-cli/src/host.rs
+++ b/libs/cua/crates/cua-cli/src/host.rs
@@ -34,7 +34,7 @@ pub enum HostCmd {
# (Add a machine) or `cua host pair`: no sign-in needed here
cua host setup --pair K7QM-4XPB-2RHD")]
Setup {
- /// Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai).
+ /// Relay URL (default $CUA_RELAY_URL, else the CUA_ENV relay, https://relay.cua.ai in production).
#[arg(long, conflicts_with = "direct")]
relay: Option<String>,
/// Join with a one-time pairing code (or add-machine link) made in
@@ -117,7 +117,7 @@ pub enum HostCmd {
/// Revoke an unused code by id (`pc_…`).
#[arg(long, value_name = "ID", conflicts_with_all = ["team", "name"])]
revoke: Option<String>,
- /// Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai).
+ /// Relay URL (default $CUA_RELAY_URL, else the CUA_ENV relay, https://relay.cua.ai in production).
#[arg(long)]
relay: Option<String>,
},
@@ -215,7 +215,7 @@ pub enum SpacesCmd {
cua spaces ls --json"
)]
Ls {
- /// Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai).
+ /// Relay URL (default $CUA_RELAY_URL, else the CUA_ENV relay, https://relay.cua.ai in production).
#[arg(long)]
relay: Option<String>,
},
diff --git a/libs/cua/crates/cua-cli/src/lib.rs b/libs/cua/crates/cua-cli/src/lib.rs
index c1b2c147d1..c946454d2b 100644
--- a/libs/cua/crates/cua-cli/src/lib.rs
+++ b/libs/cua/crates/cua-cli/src/lib.rs
@@ -251,7 +251,7 @@ enum Command {
cua usage
cua usage --json")]
Usage {
- /// Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai).
+ /// Relay URL (default $CUA_RELAY_URL, else the CUA_ENV relay, https://relay.cua.ai in production).
#[arg(long)]
relay: Option<String>,
},
@@ -2498,6 +2498,16 @@ pub fn main() {
#[cfg(windows)]
keep_stdio_out_of_children();
promote_spacesd_env_vars();
+ // `CUA_ENV` picks every endpoint and the cua home: a typo must not fall
+ // back to production silently.
+ if let Err(e) = cua_home::env::CuaEnv::try_current() {
+ eprintln!("error: {e}");
+ std::process::exit(2);
+ }
+ // SAFETY: still first in `main`, before any other thread exists. Pins
+ // `CUA_HOME` for a non-production `CUA_ENV` so every component and
+ // child process (the daemon) uses that environment's home.
+ unsafe { cua_home::env::pin_home() };
let matches = Cli::command().get_matches();
let command = command_path(&matches);
let cli = Cli::from_arg_matches(&matches).unwrap_or_else(|e| e.exit());
diff --git a/libs/cua/crates/cua-daemon/src/session.rs b/libs/cua/crates/cua-daemon/src/session.rs
index c02db261a2..ee1635da28 100644
--- a/libs/cua/crates/cua-daemon/src/session.rs
+++ b/libs/cua/crates/cua-daemon/src/session.rs
@@ -26,9 +26,11 @@ impl AccessTokenProvider for SessionTokens {
/// A Fleet client on the stored session when `config` carries no
/// credentials of its own and a session exists; `None` otherwise (the
-/// Fleet provider then stays unconfigured, as before).
+/// Fleet provider then stays unconfigured, as before), and `None` when
+/// the session belongs to another `CUA_ENV` than this Fleet
+/// ([`FleetConfig::accepts_session`]).
pub fn session_fleet_client(config: &FleetConfig) -> Option<FleetClient> {
- if config.has_auth() {
+ if config.has_auth() || !config.accepts_session() {
return None;
}
let session = cua_auth::Session::from_env();
diff --git a/libs/cua/crates/cua-fleet/src/config.rs b/libs/cua/crates/cua-fleet/src/config.rs
index bb85b75d56..4a57b52654 100644
--- a/libs/cua/crates/cua-fleet/src/config.rs
+++ b/libs/cua/crates/cua-fleet/src/config.rs
@@ -93,6 +93,18 @@ impl FleetConfig {
}
}
+ /// Whether the signed-in user's session (`cua auth login`) may be sent
+ /// to this Fleet: always in production; under another `CUA_ENV` only to
+ /// a Fleet that `CUA_FLEET_BASE_URL` names, so the production Fleet never
+ /// receives a staging token.
+ pub fn accepts_session(&self) -> bool {
+ Self::accepts_session_in(cua_home::env::CuaEnv::current(), &self.base_url)
+ }
+
+ fn accepts_session_in(env: cua_home::env::CuaEnv, base_url: &str) -> bool {
+ env.is_prod() || base_url.trim_end_matches('/') != DEFAULT_FLEET_BASE_URL
+ }
+
/// True when a static token or both client credentials are present.
pub fn has_auth(&self) -> bool {
self.fleet_token.is_some() || (self.client_id.is_some() && self.client_secret.is_some())
@@ -131,4 +143,25 @@ mod tests {
assert_eq!(c.fleet_token, None);
assert!(!format!("{c:?}").contains("secret\""));
}
+
+ #[test]
+ fn staging_sessions_never_reach_the_production_fleet() {
+ use cua_home::env::CuaEnv;
+ assert!(FleetConfig::accepts_session_in(
+ CuaEnv::Prod,
+ DEFAULT_FLEET_BASE_URL
+ ));
+ assert!(!FleetConfig::accepts_session_in(
+ CuaEnv::Staging,
+ DEFAULT_FLEET_BASE_URL
+ ));
+ assert!(!FleetConfig::accepts_session_in(
+ CuaEnv::Staging,
+ "https://run.cua.ai/"
+ ));
+ assert!(FleetConfig::accepts_session_in(
+ CuaEnv::Staging,
+ "https://fleet.staging.example"
+ ));
+ }
}
diff --git a/libs/cua/crates/cua-home/src/env.rs b/libs/cua/crates/cua-home/src/env.rs
new file mode 100644
index 0000000000..fe9951c268
--- /dev/null
+++ b/libs/cua/crates/cua-home/src/env.rs
@@ -0,0 +1,294 @@
+//! Which Cua deployment a client talks to: `CUA_ENV` (`prod`, the default,
+//! or `staging`).
+//!
+//! The environment picks the default of every Cua endpoint a client uses,
+//! and the cua home, so a staging session, host enrollment and Spaces
+//! registry never mix with production ones:
+//!
+//! | Setting | Override | prod | staging |
+//! |---------------|-----------------------|------------------------------------------|---------------------------------------------|
+//! | OIDC issuer | `CUA_OIDC_ISSUER` | `https://auth.cua.ai/realms/cyclops-cs` | `https://auth.cua.ai/realms/cua-staging` |
+//! | Relay | `CUA_RELAY_URL` | `https://relay.cua.ai` | `https://relay.staging.cua.ai` |
+//! | Spaces API | `CUA_SPACES_API_URL` | `https://api.spaces.cua.ai` | `https://api.staging.cua.ai` |
+//! | Spaces site | `CUA_SPACES_SITE_URL` | `https://spaces.cua.ai` | `https://spaces.staging.cua.ai` |
+//! | cua home | `CUA_HOME` | `~/.cua` | `~/.cua/envs/staging` |
+//!
+//! A per-setting override always wins over `CUA_ENV`. With `CUA_ENV` unset,
+//! the build's default applies: production, or staging for a beta channel
+//! build (compiled with `CUA_DEFAULT_ENV=staging`).
+
+use std::path::PathBuf;
+
+/// The environment variable that selects the deployment.
+pub const CUA_ENV_VAR: &str = "CUA_ENV";
+
+/// A Cua deployment.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
+pub enum CuaEnv {
+ /// Production (the default).
+ #[default]
+ Prod,
+ /// The staging deployment.
+ Staging,
+}
+
+impl CuaEnv {
+ /// Parses a `CUA_ENV` value: empty, `prod` or `production` is
+ /// [`CuaEnv::Prod`], `staging` is [`CuaEnv::Staging`] (any case).
+ pub fn parse(value: &str) -> Option<Self> {
+ match value.trim().to_ascii_lowercase().as_str() {
+ "" | "prod" | "production" => Some(Self::Prod),
+ "staging" => Some(Self::Staging),
+ _ => None,
+ }
+ }
+
+ /// `CUA_ENV`, or an error naming the accepted values.
+ pub fn try_current() -> Result<Self, String> {
+ Self::try_from_value(std::env::var(CUA_ENV_VAR).ok().as_deref())
+ }
+
+ /// The default when `CUA_ENV` is unset: the build's `CUA_DEFAULT_ENV`
+ /// (beta channel builds are compiled with `staging`), else production.
+ pub fn build_default() -> Self {
+ option_env!("CUA_DEFAULT_ENV")
+ .and_then(Self::parse)
+ .unwrap_or_default()
+ }
+
+ /// [`CuaEnv::try_current`] for a given value (`None`: unset, the
+ /// [`CuaEnv::build_default`]).
+ pub fn try_from_value(value: Option<&str>) -> Result<Self, String> {
+ match value {
+ None => Ok(Self::build_default()),
+ Some(v) => Self::parse(v).ok_or_else(|| {
+ format!("{CUA_ENV_VAR}={v:?} is not a Cua environment (prod or staging)")
+ }),
+ }
+ }
+
+ /// `CUA_ENV`; an unknown value is production (the `cua` CLI refuses
+ /// one at startup instead, see [`CuaEnv::try_current`]).
+ pub fn current() -> Self {
+ Self::try_current().unwrap_or_default()
+ }
+
+ /// `prod` or `staging`.
+ pub fn name(self) -> &'static str {
+ match self {
+ Self::Prod => "prod",
+ Self::Staging => "staging",
+ }
+ }
+
+ /// Whether this is production.
+ pub fn is_prod(self) -> bool {
+ self == Self::Prod
+ }
+
+ /// The default OIDC issuer.
+ pub fn oidc_issuer(self) -> &'static str {
+ match self {
+ Self::Prod => "https://auth.cua.ai/realms/cyclops-cs",
+ Self::Staging => "https://auth.cua.ai/realms/cua-staging",
+ }
+ }
+
+ /// The default relay.
+ pub fn relay_url(self) -> &'static str {
+ match self {
+ Self::Prod => "https://relay.cua.ai",
+ Self::Staging => "https://relay.staging.cua.ai",
+ }
+ }
+
+ /// The default Spaces control plane (entitlements) API.
+ pub fn spaces_api_url(self) -> &'static str {
+ match self {
+ Self::Prod => "https://api.spaces.cua.ai",
+ Self::Staging => "https://api.staging.cua.ai",
+ }
+ }
+
+ /// The default Spaces site (pairing links are `<site>/add/<code>`).
+ pub fn spaces_site_url(self) -> &'static str {
+ match self {
+ Self::Prod => "https://spaces.cua.ai",
+ Self::Staging => "https://spaces.staging.cua.ai",
+ }
+ }
+
+ /// The OS credential vault service the session is stored under
+ /// (production keeps `run.cua.ai`).
+ pub fn keyring_service(self) -> &'static str {
+ match self {
+ Self::Prod => "run.cua.ai",
+ Self::Staging => "staging.run.cua.ai",
+ }
+ }
+
+ /// The cua home below the default `~/.cua` (`None`: `~/.cua` itself).
+ pub fn home_subdir(self) -> Option<&'static str> {
+ match self {
+ Self::Prod => None,
+ Self::Staging => Some("envs/staging"),
+ }
+ }
+}
+
+/// Every endpoint a client uses, resolved for one environment and its
+/// per-setting overrides.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Endpoints {
+ /// The deployment (`CUA_ENV`).
+ pub env: CuaEnv,
+ /// `CUA_OIDC_ISSUER`, else the environment's issuer.
+ pub oidc_issuer: String,
+ /// `CUA_RELAY_URL`, else the environment's relay.
+ pub relay_url: String,
+ /// `CUA_SPACES_API_URL`, else the environment's Spaces API.
+ pub spaces_api_url: String,
+ /// `CUA_SPACES_SITE_URL`, else the environment's Spaces site.
+ pub spaces_site_url: String,
+}
+
+impl Endpoints {
+ /// From the process environment (an unknown `CUA_ENV` is production).
+ pub fn current() -> Self {
+ Self::from_lookup(|k| std::env::var(k).ok())
+ }
+
+ /// From `get` (a variable lookup; for tests).
+ pub fn from_lookup(get: impl Fn(&str) -> Option<String>) -> Self {
+ let env = CuaEnv::try_from_value(get(CUA_ENV_VAR).as_deref()).unwrap_or_default();
+ let setting = |var: &str, default: &str| {
+ get(var)
+ .map(|v| v.trim().trim_end_matches('/').to_string())
+ .filter(|v| !v.is_empty())
+ .unwrap_or_else(|| default.to_string())
+ };
+ Self {
+ env,
+ oidc_issuer: setting("CUA_OIDC_ISSUER", env.oidc_issuer()),
+ relay_url: setting("CUA_RELAY_URL", env.relay_url()),
+ spaces_api_url: setting("CUA_SPACES_API_URL", env.spaces_api_url()),
+ spaces_site_url: setting("CUA_SPACES_SITE_URL", env.spaces_site_url()),
+ }
+ }
+}
+
+/// `CUA_OIDC_ISSUER`, else the environment's issuer.
+pub fn oidc_issuer() -> String {
+ Endpoints::current().oidc_issuer
+}
+
+/// `CUA_RELAY_URL`, else the environment's relay.
+pub fn relay_url() -> String {
+ Endpoints::current().relay_url
+}
+
+/// `CUA_SPACES_API_URL`, else the environment's Spaces API.
+pub fn spaces_api_url() -> String {
+ Endpoints::current().spaces_api_url
+}
+
+/// `CUA_SPACES_SITE_URL`, else the environment's Spaces site.
+pub fn spaces_site_url() -> String {
+ Endpoints::current().spaces_site_url
+}
+
+/// The cua home a non-production environment uses when `CUA_HOME` is not
+/// set: `None` for production or when `CUA_HOME` is set.
+pub fn env_home() -> Option<PathBuf> {
+ if std::env::var_os("CUA_HOME").is_some_and(|v| !v.is_empty()) {
+ return None;
+ }
+ CuaEnv::current().home_subdir()?;
+ Some(crate::cua_home())
+}
+
+/// Sets `CUA_HOME` to the environment's home when `CUA_ENV` selects a
+/// non-production deployment and `CUA_HOME` is unset, so every component
+/// (and every child process) that reads `CUA_HOME` directly agrees with
+/// [`crate::cua_home`]. Returns the home it set.
+///
+/// # Safety
+///
+/// Changes the process environment: call it first in `main`, before any
+/// other thread exists.
+pub unsafe fn pin_home() -> Option<PathBuf> {
+ let home = env_home()?;
+ // SAFETY: the caller guarantees no other thread exists.
+ unsafe { std::env::set_var("CUA_HOME", &home) };
+ Some(home)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::collections::HashMap;
+
+ fn endpoints(vars: &[(&str, &str)]) -> Endpoints {
+ let m: HashMap<String, String> = vars
+ .iter()
+ .map(|(k, v)| (k.to_string(), v.to_string()))
+ .collect();
+ Endpoints::from_lookup(|k| m.get(k).cloned())
+ }
+
+ #[test]
+ fn parses_environment_names() {
+ assert_eq!(CuaEnv::parse(""), Some(CuaEnv::Prod));
+ assert_eq!(CuaEnv::parse("prod"), Some(CuaEnv::Prod));
+ assert_eq!(CuaEnv::parse(" Production "), Some(CuaEnv::Prod));
+ assert_eq!(CuaEnv::parse("STAGING"), Some(CuaEnv::Staging));
+ assert_eq!(CuaEnv::parse("stage"), None);
+ assert_eq!(CuaEnv::try_from_value(None), Ok(CuaEnv::Prod));
+ let err = CuaEnv::try_from_value(Some("dev")).unwrap_err();
+ assert!(err.contains("CUA_ENV") && err.contains("staging"), "{err}");
+ }
+
+ #[test]
+ fn unset_is_production_with_todays_endpoints() {
+ let e = endpoints(&[]);
+ assert_eq!(e.env, CuaEnv::Prod);
+ assert_eq!(e.oidc_issuer, "https://auth.cua.ai/realms/cyclops-cs");
+ assert_eq!(e.relay_url, "https://relay.cua.ai");
+ assert_eq!(e.spaces_api_url, "https://api.spaces.cua.ai");
+ assert_eq!(e.spaces_site_url, "https://spaces.cua.ai");
+ assert_eq!(CuaEnv::Prod.keyring_service(), "run.cua.ai");
+ assert_eq!(CuaEnv::Prod.home_subdir(), None);
+ // An unknown value never selects staging.
+ assert_eq!(endpoints(&[("CUA_ENV", "stagign")]), e);
+ }
+
+ #[test]
+ fn staging_flips_every_endpoint() {
+ let e = endpoints(&[("CUA_ENV", "staging")]);
+ assert_eq!(e.env, CuaEnv::Staging);
+ assert_eq!(e.oidc_issuer, "https://auth.cua.ai/realms/cua-staging");
+ assert_eq!(e.relay_url, "https://relay.staging.cua.ai");
+ assert_eq!(e.spaces_api_url, "https://api.staging.cua.ai");
+ assert_eq!(e.spaces_site_url, "https://spaces.staging.cua.ai");
+ assert_eq!(CuaEnv::Staging.keyring_service(), "staging.run.cua.ai");
+ assert_eq!(CuaEnv::Staging.home_subdir(), Some("envs/staging"));
+ }
+
+ #[test]
+ fn per_setting_overrides_win_over_the_environment() {
+ let e = endpoints(&[
+ ("CUA_ENV", "staging"),
+ ("CUA_OIDC_ISSUER", "http://127.0.0.1:8080/realms/dev/"),
+ ("CUA_RELAY_URL", " http://127.0.0.1:9000 "),
+ ("CUA_SPACES_API_URL", ""),
+ ]);
+ assert_eq!(e.oidc_issuer, "http://127.0.0.1:8080/realms/dev");
+ assert_eq!(e.relay_url, "http://127.0.0.1:9000");
+ // Empty means unset.
+ assert_eq!(e.spaces_api_url, "https://api.staging.cua.ai");
+ assert_eq!(e.spaces_site_url, "https://spaces.staging.cua.ai");
+ let p = endpoints(&[("CUA_RELAY_URL", "https://relay.example")]);
+ assert_eq!(p.relay_url, "https://relay.example");
+ assert_eq!(p.oidc_issuer, "https://auth.cua.ai/realms/cyclops-cs");
+ }
+}
diff --git a/libs/cua/crates/cua-home/src/lib.rs b/libs/cua/crates/cua-home/src/lib.rs
index 1184b5ee35..88c07bc62c 100644
--- a/libs/cua/crates/cua-home/src/lib.rs
+++ b/libs/cua/crates/cua-home/src/lib.rs
@@ -2,7 +2,8 @@
//!
//! [`cua_home`] is `$CUA_HOME`, else `$HOME/.cua` (`%USERPROFILE%\.cua` on
//! Windows): the directory that holds the Spaces registry, sandbox state,
-//! env tokens and credentials.
+//! env tokens and credentials. A non-production `CUA_ENV` (see [`env`])
+//! moves the default below it (`~/.cua/envs/staging`).
//!
//! [`guard_write`] refuses a write under the user's *real* `~/.cua` (the
//! passwd home, or on Windows the account's profile directory; never
@@ -24,6 +25,8 @@
use std::io;
use std::path::{Path, PathBuf};
+pub mod env;
+
/// Environment variable that marks a test process.
pub const CUA_TEST_ENV: &str = "CUA_TEST";
@@ -74,7 +77,8 @@ pub fn bundled_cua_of(exe: &Path) -> Option<PathBuf> {
file(dir.join("resources/native").join(CUA_FILE))
}
-/// The cua home: `$CUA_HOME`, else `~/.cua`.
+/// The cua home: `$CUA_HOME`, else `~/.cua` (production) or
+/// `~/.cua/envs/<env>` (another `CUA_ENV`).
pub fn cua_home() -> PathBuf {
if let Some(h) = std::env::var_os("CUA_HOME").filter(|v| !v.is_empty()) {
return PathBuf::from(h);
@@ -84,7 +88,11 @@ pub fn cua_home() -> PathBuf {
.or_else(|| std::env::var_os("USERPROFILE"))
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("."));
- home.join(".cua")
+ let base = home.join(".cua");
+ match env::CuaEnv::current().home_subdir() {
+ Some(sub) => base.join(sub),
+ None => base,
+ }
}
/// The user's real `~/.cua`, from the account database rather than `$HOME`
diff --git a/libs/cua/crates/cua-host/src/pairing.rs b/libs/cua/crates/cua-host/src/pairing.rs
index 722f745dc4..a819fbb336 100644
--- a/libs/cua/crates/cua-host/src/pairing.rs
+++ b/libs/cua/crates/cua-host/src/pairing.rs
@@ -23,9 +23,16 @@ use serde::{Deserialize, Serialize};
pub const PAIRING_TOKEN_PREFIX: &str = "cpc_";
/// Characters of a code.
pub const PAIRING_CODE_LEN: usize = 12;
-/// Where an add-machine link opens.
+/// Where an add-machine link opens in production.
pub const ADD_MACHINE_BASE_URL: &str = "https://spaces.cua.ai/add";
+/// Where an add-machine link opens: `<Spaces site>/add`, the site of
+/// `CUA_SPACES_SITE_URL` or `CUA_ENV` ([`ADD_MACHINE_BASE_URL`] in
+/// production).
+pub fn add_machine_base_url() -> String {
+ format!("{}/add", cua_home::env::spaces_site_url())
+}
+
const ALPHABET: &str = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
/// A code in canonical form (12 upper-case Crockford base32 characters)
@@ -72,17 +79,19 @@ pub fn display_pairing_code(code: &str) -> String {
}
}
-/// The add-machine link for `code`: `https://spaces.cua.ai/add/<code>`,
-/// plus `?relay=<url>` when the machine must join another relay than
-/// [`DEFAULT_RELAY_URL`].
+/// The add-machine link for `code`: `<add_machine_base_url>/<code>`
+/// (`https://spaces.cua.ai/add/<code>` in production), plus `?relay=<url>`
+/// when the machine must join another relay than the production
+/// [`DEFAULT_RELAY_URL`] (a staging relay is always named, since the
+/// machine being added has no `CUA_ENV`).
pub fn add_machine_url(code: &str, relay: &str) -> String {
let code = display_pairing_code(code);
let relay = relay.trim().trim_end_matches('/');
+ let base = add_machine_base_url();
if relay.is_empty() || relay == DEFAULT_RELAY_URL {
- format!("{ADD_MACHINE_BASE_URL}/{code}")
+ format!("{base}/{code}")
} else {
- let mut url = url::Url::parse(&format!("{ADD_MACHINE_BASE_URL}/{code}"))
- .expect("static add-machine URL");
+ let mut url = url::Url::parse(&format!("{base}/{code}")).expect("static add-machine URL");
url.query_pairs_mut().append_pair("relay", relay);
url.to_string()
}
diff --git a/libs/cua/crates/cua-host/src/relay.rs b/libs/cua/crates/cua-host/src/relay.rs
index 001ceda6b9..2117a7fea6 100644
--- a/libs/cua/crates/cua-host/src/relay.rs
+++ b/libs/cua/crates/cua-host/src/relay.rs
@@ -29,16 +29,13 @@ use crate::{Error, Result};
use serde::{Deserialize, Serialize};
use std::time::Duration;
-/// The relay the app and CLI use unless configured otherwise.
+/// The production relay (`CUA_RELAY_URL` and `CUA_ENV` change it).
pub const DEFAULT_RELAY_URL: &str = "https://relay.cua.ai";
-/// `CUA_RELAY_URL` when set and non-empty, else [`DEFAULT_RELAY_URL`].
+/// `CUA_RELAY_URL` when set and non-empty, else the relay of `CUA_ENV`
+/// ([`DEFAULT_RELAY_URL`] in production).
pub fn relay_url_from_env() -> String {
- std::env::var("CUA_RELAY_URL")
- .ok()
- .map(|v| v.trim().to_string())
- .filter(|v| !v.is_empty())
- .unwrap_or_else(|| DEFAULT_RELAY_URL.to_string())
+ cua_home::env::relay_url()
}
/// Supplies a fresh cua.ai account access token (refreshing as needed).
diff --git a/libs/cua/crates/cua-spaces-app-core/Cargo.toml b/libs/cua/crates/cua-spaces-app-core/Cargo.toml
index 3f9180dfd4..1844a00a04 100644
--- a/libs/cua/crates/cua-spaces-app-core/Cargo.toml
+++ b/libs/cua/crates/cua-spaces-app-core/Cargo.toml
@@ -23,6 +23,7 @@ installer = ["dep:tokio", "tokio/process", "tokio/time", "tokio/fs"]
telemetry = ["dep:cua-telemetry"]
[dependencies]
+cua-home.workspace = true
serde.workspace = true
serde_json.workspace = true
cua-keyvault = { workspace = true, optional = true }
diff --git a/libs/cua/crates/cua-spaces-app-core/src/host.rs b/libs/cua/crates/cua-spaces-app-core/src/host.rs
index 2feb808315..bd70a56265 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/host.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/host.rs
@@ -312,8 +312,17 @@ pub fn validate_setup(mut request: HostSetupRequest) -> Result<HostSetupRequest,
}
}
-/// The relay host setup joins unless the form names another.
+/// The production relay. Host setup joins [`default_relay_url`] unless the
+/// form names another.
pub const DEFAULT_RELAY_URL: &str = "https://relay.cua.ai";
+
+/// The relay host setup joins unless the form names another:
+/// `CUA_RELAY_URL`, else the relay of `CUA_ENV` ([`DEFAULT_RELAY_URL`] in
+/// production).
+pub fn default_relay_url() -> String {
+ cua_home::env::relay_url()
+}
+
/// The direct mode's default listen address.
pub const DEFAULT_LISTEN: &str = "0.0.0.0:3211";
@@ -1467,7 +1476,7 @@ impl Default for HostFormState {
advanced: false,
direct: false,
listen: DEFAULT_LISTEN.into(),
- relay_url: DEFAULT_RELAY_URL.into(),
+ relay_url: default_relay_url(),
busy: false,
error: None,
spare: false,
@@ -1730,7 +1739,7 @@ pub fn form_view(s: &HostFormState, identity: Option<&str>) -> HostFormView {
fields.push(text(
"relay",
"Relay",
- DEFAULT_RELAY_URL,
+ &default_relay_url(),
&s.relay_url,
bad,
true,
diff --git a/libs/cua/crates/cua-telemetry/src/client.rs b/libs/cua/crates/cua-telemetry/src/client.rs
index 3a0b8ee553..5e1187c665 100644
--- a/libs/cua/crates/cua-telemetry/src/client.rs
+++ b/libs/cua/crates/cua-telemetry/src/client.rs
@@ -761,9 +761,12 @@ impl Telemetry {
batch.clear();
}
}
+ // No project for this `CUA_ENV`: `is_enabled` is already false, so
+ // the batch is empty; never fall back to production's key.
+ let api_key = config::posthog_key(&*self.inner.env).unwrap_or_default();
for chunk in batch.chunks(BATCH_SIZE) {
let body = serde_json::json!({
- "api_key": sink::POSTHOG_API_KEY,
+ "api_key": api_key,
"batch": chunk,
});
match self.inner.sink.send(&body) {
diff --git a/libs/cua/crates/cua-telemetry/src/config.rs b/libs/cua/crates/cua-telemetry/src/config.rs
index f5f724c615..3b0d5ced6e 100644
--- a/libs/cua/crates/cua-telemetry/src/config.rs
+++ b/libs/cua/crates/cua-telemetry/src/config.rs
@@ -31,6 +31,8 @@ pub const ENV_SYNTHETIC: &str = "CUA_TELEMETRY_SYNTHETIC";
pub const ENV_DEBUG: &str = "CUA_TELEMETRY_DEBUG";
/// Override the ingest endpoint (self-hosting, tests).
pub const ENV_ENDPOINT: &str = "CUA_TELEMETRY_ENDPOINT";
+/// Override the PostHog project key (wins over the `CUA_ENV` default).
+pub const ENV_POSTHOG_KEY: &str = "CUA_POSTHOG_KEY";
/// Refuse every non-loopback send (set for all test runs).
pub const ENV_FORBID_NETWORK: &str = "CUA_TELEMETRY_FORBID_NETWORK";
/// Set (to the run id) in the environment of every Cua agent run, by the
@@ -78,11 +80,14 @@ pub enum Source {
Ci,
/// The built-in default.
Default,
+ /// The `CUA_ENV` deployment has no PostHog project (and no
+ /// `CUA_POSTHOG_KEY`): nothing is sent, never to production's.
+ NoProject(&'static str),
}
impl Source {
/// Short name (`do_not_track`, `env`, `legacy_env`, `config`, `ci`,
- /// `default`).
+ /// `default`, `no_project`).
pub fn kind(&self) -> &'static str {
match self {
Source::DoNotTrack => "do_not_track",
@@ -91,6 +96,7 @@ impl Source {
Source::Config(_) => "config",
Source::Ci => "ci",
Source::Default => "default",
+ Source::NoProject(_) => "no_project",
}
}
}
@@ -104,6 +110,10 @@ impl std::fmt::Display for Source {
Source::Config(p) => write!(f, "config {}", p.display()),
Source::Ci => f.write_str("CI environment (set CUA_TELEMETRY=1 to send)"),
Source::Default => f.write_str("default"),
+ Source::NoProject(env) => write!(
+ f,
+ "CUA_ENV={env} has no PostHog project (set {ENV_POSTHOG_KEY} to send)"
+ ),
}
}
}
@@ -203,6 +213,34 @@ pub fn write_config_value(home: &Path, enabled: bool) -> std::io::Result<PathBuf
Ok(path)
}
+/// The Cua deployment (`prod` or `staging`), resolved as `cua_home::env`
+/// does: `CUA_ENV`, else the build's `CUA_DEFAULT_ENV`; anything else is
+/// `prod`. Kept here (not a cua-home dependency) so cua-driver, which links
+/// this crate, keeps building with its older toolchain.
+fn deployment(env: Env<'_>) -> &'static str {
+ let value = env("CUA_ENV").or_else(|| option_env!("CUA_DEFAULT_ENV").map(str::to_string));
+ match value.map(|v| v.trim().to_ascii_lowercase()).as_deref() {
+ Some("staging") => "staging",
+ _ => "prod",
+ }
+}
+
+/// The PostHog project key events go to: `CUA_POSTHOG_KEY`, else the
+/// project of the `CUA_ENV` deployment. `None` when that deployment has no
+/// project yet (staging never falls back to production's).
+pub fn posthog_key(env: Env<'_>) -> Option<String> {
+ if let Some(k) = env(ENV_POSTHOG_KEY).map(|k| k.trim().to_string())
+ && !k.is_empty()
+ {
+ return Some(k);
+ }
+ let key = match deployment(env) {
+ "staging" => crate::sink::STAGING_POSTHOG_API_KEY,
+ _ => crate::sink::POSTHOG_API_KEY,
+ };
+ (!key.is_empty()).then(|| key.to_string())
+}
+
/// The effective decision for `env` and the config under `home`.
pub fn decide(env: Env<'_>, home: Option<&Path>) -> Decision {
let ci = is_ci(env);
@@ -211,6 +249,9 @@ pub fn decide(env: Env<'_>, home: Option<&Path>) -> Decision {
source,
is_ci: ci,
};
+ if posthog_key(env).is_none() {
+ return d(false, Source::NoProject(deployment(env)));
+ }
if env(ENV_DO_NOT_TRACK).is_some_and(|v| {
let v = v.trim();
!v.is_empty() && v != "0" && !v.eq_ignore_ascii_case("false")
@@ -245,3 +286,46 @@ pub fn network_forbidden(env: Env<'_>) -> bool {
.and_then(parse_bool)
.unwrap_or(false)
}
+
+#[cfg(test)]
+mod env_project_tests {
+ use super::*;
+
+ fn lookup(vars: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<String> {
+ move |k| {
+ vars.iter()
+ .find(|(n, _)| *n == k)
+ .map(|(_, v)| v.to_string())
+ }
+ }
+
+ #[test]
+ fn production_keeps_its_project() {
+ let env = lookup(&[]);
+ assert_eq!(
+ posthog_key(&env).as_deref(),
+ Some(crate::sink::POSTHOG_API_KEY)
+ );
+ assert_eq!(decide(&env, None).source.kind(), "default");
+ }
+
+ #[test]
+ fn staging_never_sends_to_the_production_project() {
+ let env = lookup(&[("CUA_ENV", "staging"), ("CUA_TELEMETRY", "1")]);
+ let key = posthog_key(&env);
+ assert_ne!(key.as_deref(), Some(crate::sink::POSTHOG_API_KEY));
+ if crate::sink::STAGING_POSTHOG_API_KEY.is_empty() {
+ assert_eq!(key, None);
+ let d = decide(&env, None);
+ assert!(!d.enabled);
+ assert_eq!(d.source, Source::NoProject("staging"));
+ }
+ }
+
+ #[test]
+ fn an_explicit_key_wins() {
+ let env = lookup(&[("CUA_ENV", "staging"), ("CUA_POSTHOG_KEY", " phc_test ")]);
+ assert_eq!(posthog_key(&env).as_deref(), Some("phc_test"));
+ assert_eq!(decide(&env, None).source.kind(), "default");
+ }
+}
diff --git a/libs/cua/crates/cua-telemetry/src/sink.rs b/libs/cua/crates/cua-telemetry/src/sink.rs
index 6a4281970b..ce564283e8 100644
--- a/libs/cua/crates/cua-telemetry/src/sink.rs
+++ b/libs/cua/crates/cua-telemetry/src/sink.rs
@@ -11,6 +11,11 @@ pub const DEFAULT_ENDPOINT: &str = "https://eu.i.posthog.com/batch/";
/// The project's public, write-only ingest key. It is already public in
/// every Cua client; it cannot read data.
pub const POSTHOG_API_KEY: &str = "phc_eSkLnbLxsnYFaXksif1ksbrNzYlJShr35miFLDppF14";
+/// The staging PostHog project's public, write-only ingest key (EU project
+/// "Cua Spaces (staging)"), for `CUA_ENV=staging`: never production's. If
+/// it is ever emptied, staging sends nothing unless `CUA_POSTHOG_KEY` names
+/// a key.
+pub const STAGING_POSTHOG_API_KEY: &str = "phc_xDNLpzypNLVGmzQeBZEgZDZK7Ea6yYAmAnGZ6hMtHNKG";
/// Per-request budget. Telemetry never waits longer.
pub const SEND_TIMEOUT: Duration = Duration::from_secs(3);
diff --git a/scripts/docs-generators/cli-specs/cua.json b/scripts/docs-generators/cli-specs/cua.json
index 74f2cb9f85..f1def3834b 100644
--- a/scripts/docs-generators/cli-specs/cua.json
+++ b/scripts/docs-generators/cli-specs/cua.json
@@ -9341,7 +9341,7 @@
"aliases": [],
"default_value": null,
"env": null,
- "help": "Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai)",
+ "help": "Relay URL (default $CUA_RELAY_URL, else the CUA_ENV relay, https://relay.cua.ai in production)",
"hidden": false,
"is_optional": true,
"multiple_values": false,
@@ -9579,7 +9579,7 @@
"aliases": [],
"default_value": null,
"env": null,
- "help": "Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai)",
+ "help": "Relay URL (default $CUA_RELAY_URL, else the CUA_ENV relay, https://relay.cua.ai in production)",
"hidden": false,
"is_optional": true,
"multiple_values": false,
@@ -9907,7 +9907,7 @@
"aliases": [],
"default_value": null,
"env": null,
- "help": "Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai)",
+ "help": "Relay URL (default $CUA_RELAY_URL, else the CUA_ENV relay, https://relay.cua.ai in production)",
"hidden": false,
"is_optional": true,
"multiple_values": false,
@@ -10923,7 +10923,7 @@
"aliases": [],
"default_value": null,
"env": null,
- "help": "Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai)",
+ "help": "Relay URL (default $CUA_RELAY_URL, else the CUA_ENV relay, https://relay.cua.ai in production)",
"hidden": false,
"is_optional": true,
"multiple_values": false,
@@ -11851,7 +11851,7 @@
"aliases": [],
"default_value": null,
"env": null,
- "help": "Relay URL (default $CUA_RELAY_URL, else https://relay.cua.ai)",
+ "help": "Relay URL (default $CUA_RELAY_URL, else the CUA_ENV relay, https://relay.cua.ai in production)",
"hidden": false,
"is_optional": true,
"multiple_values": false,