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(cli): add GitHub WIF token command (#2999)

r33drichards9aa41c12bd48
diff --git a/.github/workflows/ci-py-cli-wif-token.yml b/.github/workflows/ci-py-cli-wif-token.yml
new file mode 100644
index 0000000000..7ddd553da9
--- /dev/null
+++ b/.github/workflows/ci-py-cli-wif-token.yml
@@ -0,0 +1,46 @@
+name: "CI: cua-cli GitHub WIF token"
+
+on:
+ push:
+ branches: [main]
+ paths:
+ - "libs/python/cua-cli/**"
+ - ".github/workflows/ci-py-cli-wif-token.yml"
+
+permissions:
+ contents: read
+ id-token: write
+
+jobs:
+ smoke:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
+ - uses: astral-sh/setup-uv@d0cc045d04ccac9d8b7881df0226f9e82c39688e
+ - name: Install cua-cli from the locked dependency set
+ working-directory: libs/python/cua-cli
+ run: uv sync --frozen
+ - name: Validate GitHub WIF token claims
+ working-directory: libs/python/cua-cli
+ shell: bash
+ run: |
+ set -euo pipefail
+ FLEETS_TOKEN="$(uv run cua wif-token github)"
+ export FLEETS_TOKEN
+ uv run python - <<'PY'
+ import base64
+ import json
+ import os
+
+ parts = os.environ["FLEETS_TOKEN"].split(".")
+ if len(parts) != 3:
+ raise SystemExit("GitHub returned a non-JWT token")
+ payload = parts[1] + "=" * (-len(parts[1]) % 4)
+ claims = json.loads(base64.urlsafe_b64decode(payload))
+ if claims.get("iss") != "https://token.actions.githubusercontent.com":
+ raise SystemExit("unexpected issuer")
+ aud = claims.get("aud")
+ if aud != "fleets" and not (isinstance(aud, list) and "fleets" in aud):
+ raise SystemExit("unexpected audience")
+ PY
+ unset FLEETS_TOKEN
diff --git a/libs/python/cua-cli/README.md b/libs/python/cua-cli/README.md
index 6417820a31..21f7032091 100644
--- a/libs/python/cua-cli/README.md
+++ b/libs/python/cua-cli/README.md
@@ -102,3 +102,19 @@ Individual permissions: `sandbox:list`, `sandbox:create`, `sandbox:delete`, `san
`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.
+
+## GitHub Actions workload identity
+
+Use `cua wif-token github` from a GitHub Actions job to obtain a GitHub OIDC token for Fleets. The command runs only in GitHub Actions, requests the `fleets` audience, and prints only the raw token. It does not use the interactive `cua auth login` session.
+
+```yaml
+permissions:
+ id-token: write
+ contents: read
+
+steps:
+ - name: Get GitHub WIF token for Fleets
+ run: |
+ FLEETS_TOKEN="$(cua wif-token github)"
+ test -n "$FLEETS_TOKEN"
+```
diff --git a/libs/python/cua-cli/cua_cli/auth/github_wif.py b/libs/python/cua-cli/cua_cli/auth/github_wif.py
new file mode 100644
index 0000000000..593eaaa9ee
--- /dev/null
+++ b/libs/python/cua-cli/cua_cli/auth/github_wif.py
@@ -0,0 +1,81 @@
+"""GitHub Actions workload identity token retrieval."""
+
+import os
+from collections.abc import Awaitable, Callable, Mapping
+from typing import Any
+from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
+
+import aiohttp
+
+DEFAULT_GITHUB_WIF_AUDIENCE = "fleets"
+
+
+class GitHubWifError(RuntimeError):
+ """Raised when GitHub Actions cannot issue a workload identity token."""
+
+
+HttpRequest = Callable[[str, dict[str, str]], Awaitable[tuple[int, Mapping[str, Any]]]]
+
+
+async def _aiohttp_json_get(url: str, headers: dict[str, str]) -> tuple[int, Mapping[str, Any]]:
+ timeout = aiohttp.ClientTimeout(total=15)
+ try:
+ async with aiohttp.ClientSession(timeout=timeout) as session:
+ async with session.get(url, headers=headers) as response:
+ try:
+ payload = await response.json(content_type=None)
+ except (aiohttp.ClientError, ValueError) as error:
+ raise GitHubWifError("GitHub OIDC endpoint returned invalid JSON.") from error
+ except GitHubWifError:
+ raise
+ except (aiohttp.ClientError, TimeoutError) as error:
+ raise GitHubWifError("GitHub OIDC request failed.") from error
+ if not isinstance(payload, Mapping):
+ raise GitHubWifError("GitHub OIDC endpoint returned an invalid response.")
+ return response.status, payload
+
+
+def _with_audience(request_url: str, audience: str) -> str:
+ parts = urlsplit(request_url)
+ query = [
+ (key, value)
+ for key, value in parse_qsl(parts.query, keep_blank_values=True)
+ if key != "audience"
+ ]
+ query.append(("audience", audience))
+ return urlunsplit((parts.scheme, parts.netloc, parts.path, urlencode(query), parts.fragment))
+
+
+async def request_github_wif_token(
+ *,
+ audience: str = DEFAULT_GITHUB_WIF_AUDIENCE,
+ environ: Mapping[str, str] | None = None,
+ request: HttpRequest = _aiohttp_json_get,
+) -> str:
+ environment = os.environ if environ is None else environ
+ request_url = environment.get("ACTIONS_ID_TOKEN_REQUEST_URL", "")
+ request_token = environment.get("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "")
+ if not request_url:
+ raise GitHubWifError(
+ "ACTIONS_ID_TOKEN_REQUEST_URL is missing; run in GitHub Actions with "
+ "permissions: id-token: write."
+ )
+ if not request_token:
+ raise GitHubWifError(
+ "ACTIONS_ID_TOKEN_REQUEST_TOKEN is missing; run in GitHub Actions with "
+ "permissions: id-token: write."
+ )
+
+ status, payload = await request(
+ _with_audience(request_url, audience),
+ {
+ "Accept": "application/json",
+ "Authorization": f"bearer {request_token}",
+ },
+ )
+ if status != 200:
+ raise GitHubWifError(f"GitHub OIDC request failed with HTTP {status}.")
+ value = payload.get("value")
+ if not isinstance(value, str) or not value:
+ raise GitHubWifError("GitHub OIDC response did not contain a non-empty token.")
+ return value
diff --git a/libs/python/cua-cli/cua_cli/commands/__init__.py b/libs/python/cua-cli/cua_cli/commands/__init__.py
index f1080b896f..c82af03165 100644
--- a/libs/python/cua-cli/cua_cli/commands/__init__.py
+++ b/libs/python/cua-cli/cua_cli/commands/__init__.py
@@ -1,5 +1,5 @@
"""CLI commands for CUA."""
-from . import auth, image, mcp, sandbox, skills, trajectory
+from . import auth, image, mcp, sandbox, skills, trajectory, wif_token
-__all__ = ["auth", "sandbox", "image", "skills", "mcp", "trajectory"]
+__all__ = ["auth", "sandbox", "image", "skills", "mcp", "trajectory", "wif_token"]
diff --git a/libs/python/cua-cli/cua_cli/commands/wif_token.py b/libs/python/cua-cli/cua_cli/commands/wif_token.py
new file mode 100644
index 0000000000..900840f81a
--- /dev/null
+++ b/libs/python/cua-cli/cua_cli/commands/wif_token.py
@@ -0,0 +1,39 @@
+"""Workload identity federation token commands."""
+
+import argparse
+import sys
+
+from cua_cli.auth.github_wif import GitHubWifError, request_github_wif_token
+from cua_cli.utils.async_utils import run_async
+from cua_cli.utils.output import print_error
+
+
+def register_parser(subparsers: argparse._SubParsersAction) -> None:
+ parser = subparsers.add_parser(
+ "wif-token",
+ help="Request a workload identity federation token",
+ description="Request a provider-issued workload identity token",
+ )
+ providers = parser.add_subparsers(dest="wif_token_provider", help="Workload identity provider")
+ providers.add_parser(
+ "github",
+ help="Request a GitHub Actions OIDC token for Fleets",
+ description="Print a GitHub Actions OIDC token for Fleets",
+ )
+
+
+def execute(args: argparse.Namespace) -> int:
+ if getattr(args, "wif_token_provider", None) == "github":
+ return cmd_github(args)
+ print_error("Usage: cua wif-token github")
+ return 1
+
+
+def cmd_github(_args: argparse.Namespace) -> int:
+ try:
+ token = run_async(request_github_wif_token())
+ except (GitHubWifError, OSError) as error:
+ print_error(str(error))
+ return 1
+ sys.stdout.write(f"{token}\n")
+ return 0
diff --git a/libs/python/cua-cli/cua_cli/main.py b/libs/python/cua-cli/cua_cli/main.py
index 553ae68b52..3daf4c8804 100644
--- a/libs/python/cua-cli/cua_cli/main.py
+++ b/libs/python/cua-cli/cua_cli/main.py
@@ -8,7 +8,17 @@ 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 (
+ auth,
+ do,
+ image,
+ mcp,
+ platform,
+ sandbox,
+ skills,
+ trajectory,
+ wif_token,
+)
from cua_cli.utils.output import print_error
try:
@@ -53,6 +63,7 @@ def create_parser() -> argparse.ArgumentParser:
do.register_parser(subparsers)
do.register_host_consent_parser(subparsers)
trajectory.register_parser(subparsers)
+ wif_token.register_parser(subparsers)
return parser
@@ -98,6 +109,8 @@ def main() -> int:
exit_code = do.execute_host_consent(args)
elif args.command in ("trajectory", "traj"):
exit_code = trajectory.execute(args)
+ elif args.command == "wif-token":
+ exit_code = wif_token.execute(args)
else:
print_error(f"Unknown command: {args.command}")
exit_code = 1
@@ -111,7 +124,7 @@ def main() -> int:
exit_code = 1
return exit_code
finally:
- if _TELEMETRY_AVAILABLE and is_telemetry_enabled():
+ if args.command != "wif-token" and _TELEMETRY_AVAILABLE and is_telemetry_enabled():
record_event(
"cli_command",
{
diff --git a/libs/python/cua-cli/tests/auth/test_github_wif.py b/libs/python/cua-cli/tests/auth/test_github_wif.py
new file mode 100644
index 0000000000..debfc0ed2e
--- /dev/null
+++ b/libs/python/cua-cli/tests/auth/test_github_wif.py
@@ -0,0 +1,187 @@
+import asyncio
+from urllib.parse import parse_qs, urlparse
+
+import aiohttp
+import pytest
+from cua_cli.auth import github_wif
+from cua_cli.auth.github_wif import (
+ GitHubWifError,
+ _aiohttp_json_get,
+ request_github_wif_token,
+)
+
+
+def run(coroutine):
+ return asyncio.run(coroutine)
+
+
+def github_environment() -> dict[str, str]:
+ return {
+ "ACTIONS_ID_TOKEN_REQUEST_URL": (
+ "https://actions.example.test/oidc?api-version=2.0&audience=old"
+ ),
+ "ACTIONS_ID_TOKEN_REQUEST_TOKEN": "request-secret",
+ }
+
+
+def test_requests_fleets_audience_and_returns_value() -> None:
+ captured: dict[str, object] = {}
+
+ async def request(url: str, headers: dict[str, str]):
+ captured["url"] = url
+ captured["headers"] = headers
+ return 200, {"value": "signed-jwt"}
+
+ token = run(request_github_wif_token(environ=github_environment(), request=request))
+
+ query = parse_qs(urlparse(str(captured["url"])).query)
+ assert query == {"api-version": ["2.0"], "audience": ["fleets"]}
+ assert captured["headers"] == {
+ "Accept": "application/json",
+ "Authorization": "bearer request-secret",
+ }
+ assert token == "signed-jwt"
+
+
+ ("missing", "message"),
+ [
+ ("ACTIONS_ID_TOKEN_REQUEST_URL", "ACTIONS_ID_TOKEN_REQUEST_URL"),
+ ("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "ACTIONS_ID_TOKEN_REQUEST_TOKEN"),
+ ],
+)
+def test_requires_github_actions_oidc_environment(missing: str, message: str) -> None:
+ environment = github_environment()
+ del environment[missing]
+
+ with pytest.raises(GitHubWifError, match=message):
+ run(request_github_wif_token(environ=environment))
+
+
+def test_rejects_non_success_without_exposing_secrets() -> None:
+ async def request(_url: str, _headers: dict[str, str]):
+ return 403, {"message": "denied", "value": "response-secret"}
+
+ with pytest.raises(GitHubWifError) as error:
+ run(request_github_wif_token(environ=github_environment(), request=request))
+
+ message = str(error.value)
+ assert "HTTP 403" in message
+ assert "request-secret" not in message
+ assert "response-secret" not in message
+
+
[email protected]("payload", [{}, {"value": ""}, {"value": 123}])
+def test_requires_non_empty_string_value(payload: dict[str, object]) -> None:
+ async def request(_url: str, _headers: dict[str, str]):
+ return 200, payload
+
+ with pytest.raises(GitHubWifError, match="non-empty token"):
+ run(request_github_wif_token(environ=github_environment(), request=request))
+
+
+class FakeAiohttpResponse:
+ def __init__(self, *, payload: object = None, json_error: Exception | None = None) -> None:
+ self.status = 200
+ self.payload = payload
+ self.json_error = json_error
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args) -> None:
+ return None
+
+ async def json(self, *, content_type: object = None) -> object:
+ if self.json_error is not None:
+ raise self.json_error
+ return self.payload
+
+
+class FakeAiohttpSession:
+ def __init__(self, response: FakeAiohttpResponse | None, get_error: Exception | None) -> None:
+ self.response = response
+ self.get_error = get_error
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_args) -> None:
+ return None
+
+ def get(self, _url: str, *, headers: dict[str, str]) -> FakeAiohttpResponse:
+ if self.get_error is not None:
+ raise self.get_error
+ assert self.response is not None
+ return self.response
+
+
+def mock_aiohttp_session(
+ monkeypatch,
+ *,
+ payload: object = None,
+ json_error: Exception | None = None,
+ get_error: Exception | None = None,
+) -> None:
+ response = (
+ None
+ if get_error is not None
+ else FakeAiohttpResponse(payload=payload, json_error=json_error)
+ )
+ monkeypatch.setattr(
+ github_wif.aiohttp,
+ "ClientSession",
+ lambda **_kwargs: FakeAiohttpSession(response, get_error),
+ )
+
+
+def assert_sanitized_error(error: GitHubWifError, message: str) -> None:
+ rendered = str(error)
+ assert rendered == message
+ assert "request-secret" not in rendered
+ assert "response-secret" not in rendered
+
+
+def test_aiohttp_json_get_rejects_invalid_json_without_leaking_response_body(monkeypatch) -> None:
+ mock_aiohttp_session(monkeypatch, json_error=ValueError("response-secret"))
+
+ with pytest.raises(GitHubWifError) as error:
+ run(
+ _aiohttp_json_get(
+ "https://actions.example.test/oidc?token=request-secret",
+ {"Authorization": "bearer request-secret"},
+ )
+ )
+
+ assert_sanitized_error(error.value, "GitHub OIDC endpoint returned invalid JSON.")
+
+
+def test_aiohttp_json_get_rejects_non_object_json_without_leaking_response_body(
+ monkeypatch,
+) -> None:
+ mock_aiohttp_session(monkeypatch, payload=["response-secret"])
+
+ with pytest.raises(GitHubWifError) as error:
+ run(
+ _aiohttp_json_get(
+ "https://actions.example.test/oidc?token=request-secret",
+ {"Authorization": "bearer request-secret"},
+ )
+ )
+
+ assert_sanitized_error(error.value, "GitHub OIDC endpoint returned an invalid response.")
+
+
[email protected]("request_error", [TimeoutError(), aiohttp.ClientConnectionError()])
+def test_aiohttp_json_get_sanitizes_timeout_and_client_errors(monkeypatch, request_error) -> None:
+ mock_aiohttp_session(monkeypatch, get_error=request_error)
+
+ with pytest.raises(GitHubWifError) as error:
+ run(
+ _aiohttp_json_get(
+ "https://actions.example.test/oidc?token=request-secret",
+ {"Authorization": "bearer request-secret"},
+ )
+ )
+
+ assert_sanitized_error(error.value, "GitHub OIDC request failed.")
diff --git a/libs/python/cua-cli/tests/commands/test_wif_token.py b/libs/python/cua-cli/tests/commands/test_wif_token.py
new file mode 100644
index 0000000000..b01ab46e94
--- /dev/null
+++ b/libs/python/cua-cli/tests/commands/test_wif_token.py
@@ -0,0 +1,47 @@
+import argparse
+import asyncio
+from pathlib import Path
+
+from cua_cli.auth.github_wif import GitHubWifError
+from cua_cli.commands import wif_token
+
+README = Path(__file__).parents[2] / "README.md"
+
+
+def run(coroutine):
+ return asyncio.run(coroutine)
+
+
+def test_github_prints_only_raw_token(capsys, monkeypatch) -> None:
+ async def token() -> str:
+ return "header.payload.signature"
+
+ monkeypatch.setattr(wif_token, "request_github_wif_token", token)
+ monkeypatch.setattr(wif_token, "run_async", run)
+
+ assert wif_token.cmd_github(argparse.Namespace()) == 0
+ captured = capsys.readouterr()
+ assert captured.out == "header.payload.signature\n"
+ assert captured.err == ""
+
+
+def test_github_error_has_empty_stdout(capsys, monkeypatch) -> None:
+ async def token() -> str:
+ raise GitHubWifError("GitHub Actions OIDC environment is unavailable.")
+
+ monkeypatch.setattr(wif_token, "request_github_wif_token", token)
+ monkeypatch.setattr(wif_token, "run_async", run)
+
+ assert wif_token.cmd_github(argparse.Namespace()) == 1
+ captured = capsys.readouterr()
+ assert captured.out == ""
+ assert "GitHub Actions OIDC environment is unavailable" in captured.err
+
+
+def test_readme_documents_github_wif_token() -> None:
+ readme = README.read_text()
+
+ assert "cua wif-token github" in readme
+ assert "id-token: write" in readme
+ assert "FLEETS_TOKEN" in readme
+ assert "ACTIONS_ID_TOKEN_REQUEST_URL" not in readme
diff --git a/libs/python/cua-cli/tests/test_main.py b/libs/python/cua-cli/tests/test_main.py
index ee6592f401..79239ea7fc 100644
--- a/libs/python/cua-cli/tests/test_main.py
+++ b/libs/python/cua-cli/tests/test_main.py
@@ -74,6 +74,12 @@ class TestCreateParser:
args = parser.parse_args(["serve-mcp"])
assert args.command == "serve-mcp"
+ def test_has_wif_token_github_command(self):
+ parser = create_parser()
+ args = parser.parse_args(["wif-token", "github"])
+ assert args.command == "wif-token"
+ assert args.wif_token_provider == "github"
+
class TestMain:
"""Tests for main function."""
@@ -141,6 +147,13 @@ class TestMain:
mock_execute.assert_called_once()
assert result == 0
+ def test_dispatch_to_wif_token(self):
+ with patch.object(sys, "argv", ["cua", "wif-token", "github"]):
+ with patch("cua_cli.commands.wif_token.execute", return_value=0) as execute:
+ result = main()
+ execute.assert_called_once()
+ assert result == 0
+
def test_keyboard_interrupt_returns_130(self):
"""Test that KeyboardInterrupt returns exit code 130."""
with patch.object(sys, "argv", ["cua", "sandbox", "list"]):