Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(hogli): migrate Claude OAuth to Coder user secrets (#57824)

Raúl Negrón-Otero321f1673f822
diff --git a/hogli.yaml b/hogli.yaml
index 16ff0ee3ebd1..a6331b652c4a 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -174,6 +174,15 @@ devbox:
devbox:task:
click: hogli_commands.devbox.cli:devbox_task
description: Run a background agent task on a fresh devbox
+ devbox:secret:list:
+ click: hogli_commands.devbox.cli:devbox_secret_list
+ description: List your Coder user secrets
+ devbox:secret:set:
+ click: hogli_commands.devbox.cli:devbox_secret_set
+ description: Create or replace a Coder user secret
+ devbox:secret:rm:
+ click: hogli_commands.devbox.cli:devbox_secret_rm
+ description: Delete a Coder user secret
devenv:
dev:setup:
click: hogli_commands.devenv.cli:dev_setup
diff --git a/tools/hogli-commands/hogli_commands/devbox/cli.py b/tools/hogli-commands/hogli_commands/devbox/cli.py
index b55e4aa4746d..b0fb94af8318 100644
--- a/tools/hogli-commands/hogli_commands/devbox/cli.py
+++ b/tools/hogli-commands/hogli_commands/devbox/cli.py
@@ -6,6 +6,7 @@ Provides hogli devbox:* commands for managing Coder-based remote dev environment
from __future__ import annotations
import os
+import sys
import errno
import shutil
import socket
@@ -19,8 +20,8 @@ from typing import Any
import click
from hogli.manifest import get_manifest
-from . import keychain
from .coder import (
+ CLAUDE_CODE_OAUTH_ENV,
DOTFILES_URI_PARAMETER,
GIT_EMAIL_PARAMETER,
GIT_NAME_PARAMETER,
@@ -28,6 +29,7 @@ from .coder import (
_fail,
create_task,
create_workspace,
+ delete_user_secret,
delete_workspace,
ensure_coder_authenticated,
ensure_coder_installed,
@@ -44,8 +46,10 @@ from .coder import (
get_workspace,
get_workspace_name,
get_workspace_status,
+ has_claude_oauth_secret,
list_coder_users,
list_shared_workspaces,
+ list_user_secrets,
list_user_workspaces,
logs_replace,
maybe_configure_ssh,
@@ -57,6 +61,7 @@ from .coder import (
port_forward_replace,
print_setup_summary,
restart_workspace,
+ server_supports_user_secrets,
share_workspace,
ssh_replace,
start_workspace,
@@ -69,7 +74,7 @@ from .coder import (
)
from .config import load_config, save_dotfiles_uri, save_git_identity
-_CLAUDE_TOKEN_SERVICE = "posthog-claude-oauth-token"
+_LEGACY_KEYCHAIN_SERVICE = "posthog-claude-oauth-token"
_POSTHOG_COMMIT_SIGNING_HANDBOOK_URL = "https://posthog.com/handbook/engineering/security#commit-signing"
WORKSPACE_STATUS_COLORS = {
@@ -239,55 +244,66 @@ def _start_existing_workspace(name: str, workspace: dict[str, Any], *, verbose:
_print_connection_info(name)
-def _prompt_for_claude_token(*, skip_pause: bool = False) -> str | None:
- """Prompt for a Claude OAuth token and save it to Keychain."""
- if not skip_pause:
- click.echo("Run `claude setup-token` in another terminal to generate a token.")
- click.pause("Press Enter when you have the token ready...")
- token = click.prompt(
- "Claude OAuth token (Enter to skip)",
- default="",
- hide_input=True,
- show_default=False,
- ).strip()
- if not token:
- return None
-
- if keychain.write(_CLAUDE_TOKEN_SERVICE, token):
- click.echo("Saved to Keychain.")
- else:
- click.echo(click.style("Failed to save to Keychain.", fg="red"))
- return token
-
+def _read_legacy_keychain_token() -> str | None:
+ """Read the legacy macOS Keychain Claude token, if present.
-def _maybe_prompt_for_claude_oauth_token(configure_claude: bool | None) -> str | None:
- """Resolve a Claude OAuth token from env, Keychain, or interactive prompt.
-
- When configure_claude is True (explicit --configure-claude), the user is
- asked for a fresh token even if one exists in Keychain. This lets users
- replace an expired token without a separate ``devbox:auth --set`` call.
+ Used during migration only. Older hogli versions stashed the token under
+ a generic-password entry; the new flow stores it as a Coder user secret,
+ so this read happens once and the entry is then deleted.
"""
- if token := os.environ.get("CLAUDE_OAUTH_TOKEN"):
- return token
+ if sys.platform != "darwin":
+ return None
+ result = subprocess.run(
+ [
+ "security",
+ "find-generic-password",
+ "-a",
+ os.environ.get("USER", "posthog"),
+ "-s",
+ _LEGACY_KEYCHAIN_SERVICE,
+ "-w",
+ ],
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode != 0:
+ return None
+ value = result.stdout.strip()
+ return value or None
- # Explicit --configure-claude: skip cached token, prompt for a fresh one
- if configure_claude is True:
- return _prompt_for_claude_token()
- if token := keychain.read(_CLAUDE_TOKEN_SERVICE):
- click.echo("Using Claude token from Keychain. Pass --configure-claude to replace it.")
- return token
+def _delete_legacy_keychain_token() -> bool:
+ """Best-effort delete of the legacy macOS Keychain Claude token entry."""
+ if sys.platform != "darwin":
+ return False
+ result = subprocess.run(
+ [
+ "security",
+ "delete-generic-password",
+ "-a",
+ os.environ.get("USER", "posthog"),
+ "-s",
+ _LEGACY_KEYCHAIN_SERVICE,
+ ],
+ capture_output=True,
+ )
+ return result.returncode == 0
- if configure_claude is None:
- configure_claude = click.confirm(
- "Configure Claude Code in the workspace?",
- default=True,
- )
- if not configure_claude:
- return None
+def _prompt_for_claude_token() -> str | None:
+ """Prompt for a Claude OAuth token interactively.
- return _prompt_for_claude_token()
+ Returns the trimmed token, or ``None`` if the user accepts the empty default.
+ """
+ click.echo("Run `claude setup-token` in another terminal to generate a token.")
+ click.pause("Press Enter when you have the token ready...")
+ token = click.prompt(
+ "Claude OAuth token (Enter to skip)",
+ default="",
+ hide_input=True,
+ show_default=False,
+ ).strip()
+ return token or None
def maybe_configure_git_identity(configure_git_identity: bool | None) -> None:
@@ -438,7 +454,7 @@ def maybe_configure_git_signing(configure_git_signing: bool | None) -> None:
click.echo(f" Use ECDSA or Ed25519 per the handbook: {_POSTHOG_COMMIT_SIGNING_HANDBOOK_URL}")
return
- upsert_user_secret(GIT_SIGNING_KEY_SECRET, public_key, env_var=GIT_SIGNING_KEY_SECRET)
+ upsert_user_secret(GIT_SIGNING_KEY_SECRET, public_key, env_name=GIT_SIGNING_KEY_SECRET)
click.echo()
click.echo(click.style("Git commit signing", bold=True))
@@ -513,31 +529,71 @@ def devbox_help() -> None:
click.echo("Run `hogli <command> --help` for command-specific options.")
-def maybe_configure_claude_token(configure_claude: bool | None) -> None:
- """Optionally prompt for a Claude OAuth token and store it in Keychain."""
- if keychain.read(_CLAUDE_TOKEN_SERVICE) and configure_claude is not True:
- click.echo("Claude token: configured (stored in Keychain).")
- click.echo("Run `hogli devbox:setup --configure-claude` to replace.")
- return
+def maybe_configure_claude_secret(configure_claude: bool | None) -> None:
+ """Manage the ``CLAUDE_CODE_OAUTH_TOKEN`` Coder user secret for this user.
+
+ Resolution order:
- if not keychain.is_supported():
- click.echo("Claude token: set CLAUDE_OAUTH_TOKEN env var (Keychain not available on this platform).")
+ 1. Server unsupported (< 2.33) -- skip with a one-line note.
+ 2. Secret already exists and the user did not pass --configure-claude -- skip.
+ 3. Legacy macOS Keychain entry exists -- offer to migrate, then delete it.
+ 4. Otherwise -- prompt for a fresh token and create the secret.
+ """
+ if not server_supports_user_secrets():
+ click.echo("Claude token: skipping (Coder server is older than 2.33; user secrets unavailable).")
return
if configure_claude is False:
click.echo("Skipping Claude token setup.")
return
+ secret_exists = has_claude_oauth_secret()
+
+ if secret_exists and configure_claude is not True:
+ click.echo(f"Claude token already set as a Coder user secret ({CLAUDE_CODE_OAUTH_ENV}).")
+ click.echo("Run `hogli devbox:setup --configure-claude` to replace it.")
+ return
+
+ legacy_token = _read_legacy_keychain_token()
+
+ if legacy_token and not secret_exists and configure_claude is not True:
+ click.echo()
+ click.echo(click.style("Claude Code: migrating Keychain token to a Coder user secret", bold=True))
+ click.echo(" hogli now stores the Claude OAuth token as a Coder user secret so that")
+ click.echo(" workspaces -- and devbox:task runs -- pick it up automatically.")
+ if click.confirm("Migrate the existing Keychain entry now?", default=True):
+ upsert_user_secret(
+ CLAUDE_CODE_OAUTH_ENV,
+ legacy_token,
+ env_name=CLAUDE_CODE_OAUTH_ENV,
+ description="Claude Code OAuth token (managed by hogli)",
+ )
+ if _delete_legacy_keychain_token():
+ click.echo("Migrated to Coder user secret. Removed the legacy Keychain entry.")
+ else:
+ click.echo("Migrated to Coder user secret. (Could not remove the legacy Keychain entry.)")
+ return
+
click.echo()
click.echo(click.style("Claude Code (optional)", bold=True))
- click.echo(" Workspaces can run Claude Code if you provide an OAuth token.")
- click.echo(" The token will be stored in your macOS Keychain and reused for future workspaces.")
+ click.echo(" Workspaces and devbox:task runs can use Claude Code if you provide an OAuth token.")
+ click.echo(" The token will be stored as a Coder user secret and injected as")
+ click.echo(f" ${CLAUDE_CODE_OAUTH_ENV} into every workspace you start.")
click.echo(" To generate one, run `claude setup-token` in another terminal.")
- click.echo(" You can also skip this and pass --claude-oauth-token later, or set CLAUDE_OAUTH_TOKEN.")
click.echo()
- if not _prompt_for_claude_token(skip_pause=True):
+ token = _prompt_for_claude_token()
+ if not token:
click.echo("No token provided. Skipping.")
+ return
+
+ upsert_user_secret(
+ CLAUDE_CODE_OAUTH_ENV,
+ token,
+ env_name=CLAUDE_CODE_OAUTH_ENV,
+ description="Claude Code OAuth token (managed by hogli)",
+ )
+ click.echo(f"Saved Claude token as Coder user secret '{CLAUDE_CODE_OAUTH_ENV}'.")
@click.command(name="devbox:setup", help="Install and configure local access to Coder devboxes")
@@ -565,7 +621,7 @@ def maybe_configure_claude_token(configure_claude: bool | None) -> None:
"--configure-claude/--skip-configure-claude",
"configure_claude_setup",
default=None,
- help="Prompt for a Claude OAuth token to store in Keychain",
+ help="Manage the CLAUDE_CODE_OAUTH_TOKEN Coder user secret for this user",
)
@click.option("-v", "--verbose", is_flag=True, help="Show full Coder/Terraform build output")
def devbox_setup(
@@ -590,7 +646,7 @@ def devbox_setup(
maybe_configure_git_identity(configure_git_identity)
maybe_configure_git_signing(configure_git_signing)
maybe_configure_dotfiles(configure_dotfiles)
- maybe_configure_claude_token(configure_claude_setup)
+ maybe_configure_claude_secret(configure_claude_setup)
print_setup_summary()
@@ -736,22 +792,10 @@ def devbox_unshare(workspace: str | None, users: tuple[str, ...]) -> None:
default="100",
help="Disk size in GiB (default: 100)",
)
- "--configure-claude/--skip-configure-claude",
- default=None,
- help="Prompt for a Claude OAuth token when creating a new workspace",
-)
- "--claude-oauth-token",
- envvar="HOGLI_DEVBOX_CLAUDE_OAUTH_TOKEN",
- hidden=True,
-)
@click.option("-v", "--verbose", is_flag=True, help="Show full Coder/Terraform build output")
def devbox_start(
workspace: str | None,
disk: str,
- configure_claude: bool | None,
- claude_oauth_token: str | None,
verbose: bool,
) -> None:
"""Start or create the remote devbox."""
@@ -763,14 +807,12 @@ def devbox_start(
_start_existing_workspace(name, ws, verbose=verbose)
return
- token = claude_oauth_token or _maybe_prompt_for_claude_oauth_token(configure_claude)
config = load_config()
click.echo(f"Creating devbox '{name}' (disk={disk}GiB)...")
create_workspace(
name,
int(disk),
- claude_oauth_token=token,
git_name=config.get("git_name"),
git_email=config.get("git_email"),
dotfiles_uri=config.get("dotfiles_uri"),
@@ -903,9 +945,99 @@ def devbox_task(prompt: str | None, task_name: str | None, quiet: bool) -> None:
'Example: hogli devbox:task "document the ingestion pipeline"'
)
ensure_runtime_ready()
+ if server_supports_user_secrets() and not has_claude_oauth_secret():
+ click.echo(
+ click.style(
+ f"Warning: no '{CLAUDE_CODE_OAUTH_ENV}' Coder user secret set; the task will run without Claude auth.",
+ fg="yellow",
+ ),
+ err=True,
+ )
+ click.echo(
+ " Run `hogli devbox:setup --configure-claude` (or `hogli devbox:secret:set "
+ f"{CLAUDE_CODE_OAUTH_ENV}`) to set it.",
+ err=True,
+ )
create_task(prompt, task_name=task_name, quiet=quiet)
+def _ensure_user_secrets_supported() -> None:
+ """Fail fast when the Coder server does not support user secrets."""
+ if server_supports_user_secrets():
+ return
+ _fail("Coder server does not support user secrets (requires >= 2.33). Update the deployment first.")
+
+
[email protected](name="devbox:secret:list", help="List your Coder user secrets")
+def devbox_secret_list() -> None:
+ """List the user secrets attached to your Coder account."""
+ ensure_runtime_ready()
+ _ensure_user_secrets_supported()
+
+ secrets = list_user_secrets()
+ if secrets is None:
+ _fail("Could not list user secrets. Check `coder secret list` directly for details.")
+ if not secrets:
+ click.echo("No user secrets configured. Run `hogli devbox:secret:set NAME` to add one.")
+ return
+
+ click.echo(f" {'NAME':<32} {'ENV':<32} DESCRIPTION")
+ for secret in secrets:
+ name = str(secret.get("name", ""))
+ env = str(secret.get("env_name") or secret.get("env") or "")
+ description = str(secret.get("description", ""))
+ click.echo(f" {name:<32} {env:<32} {description}")
+
+
[email protected](name="devbox:secret:set", help="Create or replace a Coder user secret")
+ "--file",
+ "file_path",
+ type=click.Path(exists=True, dir_okay=False, readable=True, path_type=Path),
+ default=None,
+ help="Read the secret value from this file instead of prompting for it",
+)
+ "--env",
+ "env_name",
+ default=None,
+ help="Environment variable name to inject in the workspace (defaults to NAME)",
+)
[email protected]("--description", default=None, help="Optional description")
+def devbox_secret_set(name: str, file_path: Path | None, env_name: str | None, description: str | None) -> None:
+ """Set a Coder user secret. Replaces any existing secret with the same name."""
+ ensure_runtime_ready()
+ _ensure_user_secrets_supported()
+
+ target_env = env_name or name
+
+ if file_path is not None:
+ value = file_path.read_text().rstrip("\n")
+ else:
+ value = click.prompt(f"Value for {name}", hide_input=True, confirmation_prompt=True)
+ if not value:
+ _fail("Empty value rejected. Pass --file PATH or enter a non-empty value.")
+
+ upsert_user_secret(name, value, env_name=target_env, description=description)
+ click.echo(f"Set user secret '{name}' (env: {target_env}). Restart workspaces to pick up the change.")
+
+
[email protected](name="devbox:secret:rm", help="Delete a Coder user secret")
+def devbox_secret_rm(name: str) -> None:
+ """Delete a Coder user secret by name."""
+ ensure_runtime_ready()
+ _ensure_user_secrets_supported()
+
+ result = delete_user_secret(name)
+ if result.returncode != 0:
+ if result.stderr:
+ click.echo(result.stderr.strip(), err=True)
+ _fail(f"Failed to delete user secret '{name}'.")
+ click.echo(f"Deleted user secret '{name}'.")
+
+
@click.command(name="devbox:destroy", help="Destroy your devbox and its data")
@workspace_argument
@click.option("-v", "--verbose", is_flag=True, help="Show full Coder/Terraform build output")
diff --git a/tools/hogli-commands/hogli_commands/devbox/coder.py b/tools/hogli-commands/hogli_commands/devbox/coder.py
index 8011d6e01a02..2de2b0453963 100644
--- a/tools/hogli-commands/hogli_commands/devbox/coder.py
+++ b/tools/hogli-commands/hogli_commands/devbox/coder.py
@@ -29,7 +29,6 @@ TEMPLATE_NAME = "posthog-linux"
BREW_PACKAGE = "coder/coder/coder"
RUNTIME_SETUP_HINT = "Run `hogli devbox:setup`."
_MANAGED_CODER_DIR = Path.home() / ".hogli" / "bin"
-CLAUDE_OAUTH_PARAMETER = "claude_oauth_token"
GIT_NAME_PARAMETER = "git_name"
GIT_EMAIL_PARAMETER = "git_email"
DOTFILES_URI_PARAMETER = "dotfiles_uri"
@@ -91,6 +90,38 @@ def _normalize_version(version: str) -> str:
return version.lstrip("v").split("+")[0]
+# Coder server version that introduced user secrets (Early Access).
+USER_SECRETS_MIN_VERSION = (2, 33)
+
+
+def _version_tuple(version: str) -> tuple[int, ...]:
+ """Parse a normalized semver string into an int tuple for ordered comparison.
+
+ Trailing pre-release segments (``-rc1``) are dropped from each component so
+ ``2.33.0-rc1`` compares equal to ``2.33.0`` for the gate we care about.
+ """
+ parts: list[int] = []
+ for segment in version.split("."):
+ digits = segment.split("-", 1)[0]
+ if not digits.isdigit():
+ break
+ parts.append(int(digits))
+ return tuple(parts)
+
+
+def server_supports_user_secrets() -> bool:
+ """Return whether the configured Coder server is >= 2.33.
+
+ Returns ``False`` (graceful) if the server version cannot be determined,
+ so callers can skip secret-related steps without aborting setup.
+ """
+ try:
+ version = get_server_version()
+ except RuntimeError:
+ return False
+ return _version_tuple(version) >= USER_SECRETS_MIN_VERSION
+
+
def get_server_version() -> str:
"""Query the Coder deployment for its running version."""
if version := os.environ.get("HOGLI_DEVBOX_CODER_VERSION"):
@@ -552,7 +583,12 @@ def print_setup_summary() -> None:
click.echo(" hogli devbox:setup --configure-git-identity")
click.echo(" hogli devbox:setup --configure-git-signing")
click.echo(" hogli devbox:setup --configure-dotfiles")
- click.echo(" hogli devbox:setup --configure-claude")
+ click.echo(" hogli devbox:setup --configure-claude (manage CLAUDE_CODE_OAUTH_TOKEN as a Coder user secret)")
+ click.echo()
+ click.echo("To manage other workspace secrets (GH_TOKEN, AWS creds, etc):")
+ click.echo(" hogli devbox:secret:list")
+ click.echo(" hogli devbox:secret:set NAME")
+ click.echo(" hogli devbox:secret:rm NAME")
def _first_non_empty_string(*values: Any) -> str | None:
@@ -704,7 +740,6 @@ def get_workspace_status(workspace: dict[str, Any]) -> str:
def create_workspace(
name: str,
disk_size: int,
- claude_oauth_token: str | None = None,
git_name: str | None = None,
git_email: str | None = None,
dotfiles_uri: str | None = None,
@@ -717,7 +752,6 @@ def create_workspace(
**_TEMPLATE_PARAMETER_DEFAULTS,
"disk_size": str(disk_size),
"repo": repo,
- CLAUDE_OAUTH_PARAMETER: claude_oauth_token or "",
}
if git_name:
parameters[GIT_NAME_PARAMETER] = git_name
@@ -788,34 +822,41 @@ def update_workspace_parameters(name: str, parameters: dict[str, str]) -> None:
raise SystemExit(result.returncode)
-def upsert_user_secret(name: str, value: str, *, env_var: str | None = None) -> None:
+def upsert_user_secret(
+ name: str,
+ value: str,
+ *,
+ env_name: str | None = None,
+ description: str | None = None,
+) -> None:
"""Idempotently set a per-user Coder secret. Requires server >= 2.33.
- Tries ``coder secret create`` first; falls back to ``coder secret update``
- when the secret already exists. The secret value is piped through stdin so
- it never appears in process args or shell history. ``env_var`` is the
- workspace-side environment variable target; passing ``None`` leaves the
- secret with whatever target it already has (only meaningful on update).
+ Pipes ``value`` via stdin so it never appears in argv, process listings,
+ or shell history. Tries ``coder secret create`` first; falls back to
+ ``coder secret update`` when the secret already exists. Raises
+ ``SystemExit`` (with stderr surfaced) on failure, so callers do not have
+ to branch on a return code. ``env_name`` is the workspace-side
+ environment variable the secret will be exported as; ``description`` is
+ informational.
"""
- flags = ["--env", env_var] if env_var else []
- payload = subprocess.run(
- _resolve_coder(["coder", "secret", "create", name, *flags]),
- input=value,
- text=True,
- capture_output=True,
- )
- if payload.returncode == 0:
- return
+ flags: list[str] = []
+ if env_name is not None:
+ flags += ["--env", env_name]
+ if description is not None:
+ flags += ["--description", description]
+
+ for verb in ("create", "update"):
+ payload = subprocess.run(
+ _resolve_coder(["coder", "secret", verb, name, *flags]),
+ input=value,
+ text=True,
+ capture_output=True,
+ )
+ if payload.returncode == 0:
+ return
- payload = subprocess.run(
- _resolve_coder(["coder", "secret", "update", name, *flags]),
- input=value,
- text=True,
- capture_output=True,
- )
- if payload.returncode != 0:
- click.echo(payload.stderr or payload.stdout, err=True)
- raise SystemExit(payload.returncode)
+ click.echo(payload.stderr or payload.stdout, err=True)
+ raise SystemExit(payload.returncode)
def user_secret_exists(name: str) -> bool:
@@ -915,6 +956,48 @@ def open_web_ide(name: str) -> None:
webbrowser.open(f"{get_coder_url()}/@{username}/{name}/apps/code-server")
+# ---------------------------------------------------------------------------
+# Coder user secrets
+# ---------------------------------------------------------------------------
+
+CLAUDE_CODE_OAUTH_ENV = "CLAUDE_CODE_OAUTH_TOKEN"
+
+
+def list_user_secrets() -> list[dict[str, Any]] | None:
+ """Return user secrets via ``coder secret list -o json``.
+
+ Returns ``None`` when the CLI rejects the command (older server / missing
+ feature flag) so callers can distinguish "no secrets" from "unsupported".
+ """
+ result = _run(["coder", "secret", "list", "--output", "json"], capture_output=True)
+ if result.returncode != 0:
+ return None
+ try:
+ secrets = json.loads(result.stdout or "[]")
+ except json.JSONDecodeError:
+ return None
+ return secrets if isinstance(secrets, list) else []
+
+
+def get_user_secret(name: str) -> dict[str, Any] | None:
+ """Return a single secret payload by name, or ``None`` if not present."""
+ secrets = list_user_secrets() or []
+ for secret in secrets:
+ if isinstance(secret, dict) and secret.get("name") == name:
+ return secret
+ return None
+
+
+def has_claude_oauth_secret() -> bool:
+ """Return whether a Coder user secret named ``CLAUDE_CODE_OAUTH_TOKEN`` exists."""
+ return get_user_secret(CLAUDE_CODE_OAUTH_ENV) is not None
+
+
+def delete_user_secret(name: str) -> subprocess.CompletedProcess[str]:
+ """Delete a Coder user secret by name."""
+ return _run(["coder", "secret", "delete", name, "--yes"], capture_output=True)
+
+
# ---------------------------------------------------------------------------
# Shared workspace helpers
# ---------------------------------------------------------------------------
diff --git a/tools/hogli-commands/hogli_commands/devbox/keychain.py b/tools/hogli-commands/hogli_commands/devbox/keychain.py
deleted file mode 100644
index aa35437a3e35..000000000000
--- a/tools/hogli-commands/hogli_commands/devbox/keychain.py
+++ /dev/null
@@ -1,72 +0,0 @@
-"""macOS Keychain helpers for storing secrets.
-
-On non-macOS platforms all functions silently return None/False.
-"""
-
-from __future__ import annotations
-
-import os
-import sys
-import subprocess
-
-
-def _account() -> str:
- return os.environ.get("USER", "posthog")
-
-
-def _is_macos() -> bool:
- return sys.platform == "darwin"
-
-
-def is_supported() -> bool:
- """Return whether Keychain storage is available on this platform."""
- return _is_macos()
-
-
-def read(service: str) -> str | None:
- """Read a secret from macOS Keychain by service name."""
- if not _is_macos():
- return None
-
- result = subprocess.run(
- ["security", "find-generic-password", "-a", _account(), "-s", service, "-w"],
- capture_output=True,
- text=True,
- )
- if result.returncode != 0:
- return None
-
- value = result.stdout.strip()
- return value or None
-
-
-def write(service: str, value: str) -> bool:
- """Store a secret in macOS Keychain under the given service name."""
- if not _is_macos():
- return False
-
- account = _account()
-
- # Delete existing entry (add-generic-password doesn't update in place)
- subprocess.run(
- ["security", "delete-generic-password", "-a", account, "-s", service],
- capture_output=True,
- )
-
- result = subprocess.run(
- ["security", "add-generic-password", "-a", account, "-s", service, "-w", value],
- capture_output=True,
- )
- return result.returncode == 0
-
-
-def delete(service: str) -> bool:
- """Remove a secret from macOS Keychain by service name."""
- if not _is_macos():
- return False
-
- result = subprocess.run(
- ["security", "delete-generic-password", "-a", _account(), "-s", service],
- capture_output=True,
- )
- return result.returncode == 0
diff --git a/tools/hogli-commands/hogli_commands/tests/test_devbox.py b/tools/hogli-commands/hogli_commands/tests/test_devbox.py
index 7678f62c46f9..95a26cde5480 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_devbox.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_devbox.py
@@ -10,14 +10,12 @@ from pathlib import Path
import pytest
from unittest.mock import MagicMock, patch
-import click
from click.testing import CliRunner
from hogli.cli import cli
from hogli_commands.devbox import (
cli as devbox_cli,
coder,
config as devbox_config,
- keychain,
)
runner = CliRunner()
@@ -76,7 +74,7 @@ class TestUserSecrets:
monkeypatch.setattr(coder.subprocess, "run", fake_run)
monkeypatch.setattr(coder, "_resolve_coder", lambda args: args)
- coder.upsert_user_secret("API_KEY", "v1", env_var="API_KEY")
+ coder.upsert_user_secret("API_KEY", "v1", env_name="API_KEY")
assert calls == [(["coder", "secret", "create", "API_KEY", "--env", "API_KEY"], "v1")]
@@ -91,13 +89,35 @@ class TestUserSecrets:
monkeypatch.setattr(coder.subprocess, "run", fake_run)
monkeypatch.setattr(coder, "_resolve_coder", lambda args: args)
- coder.upsert_user_secret("API_KEY", "v2", env_var="API_KEY")
+ coder.upsert_user_secret("API_KEY", "v2", env_name="API_KEY")
assert calls == [
["coder", "secret", "create", "API_KEY", "--env", "API_KEY"],
["coder", "secret", "update", "API_KEY", "--env", "API_KEY"],
]
+ def test_upsert_pipes_value_via_stdin_never_argv(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # Security invariant: the value MUST be piped on stdin, never as a
+ # CLI flag. coder secret create's --value would expose it in argv /
+ # /proc/<pid>/cmdline / ps aux.
+ calls: list[tuple[list[str], str | None]] = []
+
+ def fake_run(args: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
+ calls.append((args, kwargs.get("input"))) # type: ignore[arg-type]
+ return subprocess.CompletedProcess(args, 0, "", "")
+
+ monkeypatch.setattr(coder.subprocess, "run", fake_run)
+ monkeypatch.setattr(coder, "_resolve_coder", lambda args: args)
+
+ coder.upsert_user_secret("API_KEY", "super-secret", env_name="API_KEY", description="api creds")
+
+ argv, stdin = calls[0]
+ assert stdin == "super-secret"
+ assert "--value" not in argv
+ assert "super-secret" not in argv
+ assert argv[: argv.index("--env")] == ["coder", "secret", "create", "API_KEY"]
+ assert "--description" in argv and argv[argv.index("--description") + 1] == "api creds"
+
def test_upsert_exits_when_both_create_and_update_fail(self, monkeypatch: pytest.MonkeyPatch) -> None:
def fake_run(args: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
return subprocess.CompletedProcess(args, 2, "", "boom")
@@ -106,7 +126,7 @@ class TestUserSecrets:
monkeypatch.setattr(coder, "_resolve_coder", lambda args: args)
with pytest.raises(SystemExit) as excinfo:
- coder.upsert_user_secret("API_KEY", "v3", env_var="API_KEY")
+ coder.upsert_user_secret("API_KEY", "v3", env_name="API_KEY")
assert excinfo.value.code == 2
def test_user_secret_exists_matches_by_name(self, monkeypatch: pytest.MonkeyPatch) -> None:
@@ -473,7 +493,6 @@ class TestWorkspaceCreation:
coder.create_workspace(
"devbox-test-user",
50,
- claude_oauth_token="oauth-token",
git_name="PostHog Engineer",
git_email="[email protected]",
verbose=True,
@@ -485,13 +504,29 @@ class TestWorkspaceCreation:
**coder._TEMPLATE_PARAMETER_DEFAULTS,
"disk_size": "50",
"repo": "https://github.com/PostHog/posthog",
- "claude_oauth_token": "oauth-token",
"git_name": "PostHog Engineer",
"git_email": "[email protected]",
},
"verbose": True,
}
+ def test_create_workspace_does_not_pass_claude_parameter(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ captured: dict[str, object] = {}
+
+ def fake_run_with_rich_parameters(
+ args: list[str], parameters: dict[str, str], *, verbose: bool | None = None
+ ) -> subprocess.CompletedProcess[str]:
+ captured["parameters"] = parameters
+ return subprocess.CompletedProcess(args, 0, "", "")
+
+ monkeypatch.setattr(coder, "_run_with_rich_parameters", fake_run_with_rich_parameters)
+
+ coder.create_workspace("devbox-test-user", 100, verbose=True)
+
+ # The template no longer declares ``claude_oauth_token``; passing it would
+ # cause Coder to reject the create call.
+ assert "claude_oauth_token" not in captured["parameters"]
+
def test_create_workspace_passes_dotfiles_uri_as_rich_parameter(self, monkeypatch: pytest.MonkeyPatch) -> None:
captured: dict[str, dict[str, str]] = {}
@@ -628,7 +663,7 @@ class TestDevboxCommands:
)
monkeypatch.setattr(
devbox_cli,
- "maybe_configure_claude_token",
+ "maybe_configure_claude_secret",
lambda configure_claude: calls.append(f"claude:{configure_claude}"),
)
monkeypatch.setattr(devbox_cli, "print_setup_summary", lambda: calls.append("summary"))
@@ -674,7 +709,7 @@ class TestDevboxCommands:
monkeypatch.setattr(devbox_cli, "maybe_configure_git_identity", lambda *a, **kw: None)
monkeypatch.setattr(devbox_cli, "maybe_configure_git_signing", lambda *a, **kw: None)
monkeypatch.setattr(devbox_cli, "maybe_configure_dotfiles", lambda *a, **kw: None)
- monkeypatch.setattr(devbox_cli, "maybe_configure_claude_token", lambda *a, **kw: None)
+ monkeypatch.setattr(devbox_cli, "maybe_configure_claude_secret", lambda *a, **kw: None)
monkeypatch.setattr(devbox_cli, "print_setup_summary", lambda: None)
monkeypatch.setattr(
devbox_cli,
@@ -703,7 +738,7 @@ class TestDevboxCommands:
monkeypatch.setattr(devbox_cli, "maybe_configure_ssh", lambda configure_ssh, **kw: None)
monkeypatch.setattr(devbox_cli, "maybe_configure_git_signing", lambda configure_git_signing: None)
monkeypatch.setattr(devbox_cli, "maybe_configure_dotfiles", lambda configure_dotfiles: None)
- monkeypatch.setattr(devbox_cli, "maybe_configure_claude_token", lambda configure_claude: None)
+ monkeypatch.setattr(devbox_cli, "maybe_configure_claude_secret", lambda configure_claude: None)
monkeypatch.setattr(devbox_cli, "print_setup_summary", lambda: None)
monkeypatch.setattr(devbox_cli, "get_default_git_identity", lambda: ("Coder User", "[email protected]"))
@@ -737,7 +772,7 @@ class TestDevboxCommands:
monkeypatch.setattr(devbox_cli, "maybe_configure_ssh", lambda configure_ssh, **kw: None)
monkeypatch.setattr(devbox_cli, "maybe_configure_git_signing", lambda configure_git_signing: None)
monkeypatch.setattr(devbox_cli, "maybe_configure_dotfiles", lambda configure_dotfiles: None)
- monkeypatch.setattr(devbox_cli, "maybe_configure_claude_token", lambda configure_claude: None)
+ monkeypatch.setattr(devbox_cli, "maybe_configure_claude_secret", lambda configure_claude: None)
monkeypatch.setattr(devbox_cli, "print_setup_summary", lambda: None)
result = runner.invoke(cli, ["devbox:setup", "--skip-configure-ssh"])
@@ -756,25 +791,13 @@ class TestDevboxCommands:
monkeypatch.setattr(devbox_cli, "get_workspace", lambda name, workspaces=None: None)
monkeypatch.setattr(devbox_cli, "extract_workspace_label", lambda name: None)
monkeypatch.setattr(devbox_cli, "load_config", lambda: {})
- monkeypatch.setattr(
- devbox_cli,
- "_maybe_prompt_for_claude_oauth_token",
- lambda configure_claude: "oauth-token",
- )
monkeypatch.setattr(
devbox_cli,
"create_workspace",
- lambda name,
- disk_size,
- claude_oauth_token=None,
- git_name=None,
- git_email=None,
- dotfiles_uri=None,
- verbose=False: captured.update(
+ lambda name, disk_size, git_name=None, git_email=None, dotfiles_uri=None, verbose=False: captured.update(
{
"name": name,
"disk_size": str(disk_size),
- "claude_oauth_token": claude_oauth_token,
"git_name": git_name,
"git_email": git_email,
"dotfiles_uri": dotfiles_uri,
@@ -788,7 +811,6 @@ class TestDevboxCommands:
assert captured == {
"name": "devbox-test-user",
"disk_size": "100",
- "claude_oauth_token": "oauth-token",
"git_name": None,
"git_email": None,
"dotfiles_uri": None,
@@ -814,21 +836,10 @@ class TestDevboxCommands:
"dotfiles_uri": "https://github.com/user/dotfiles",
},
)
- monkeypatch.setattr(
- devbox_cli,
- "_maybe_prompt_for_claude_oauth_token",
- lambda configure_claude: None,
- )
monkeypatch.setattr(
devbox_cli,
"create_workspace",
- lambda name,
- disk_size,
- claude_oauth_token=None,
- git_name=None,
- git_email=None,
- dotfiles_uri=None,
- verbose=False: captured.update(
+ lambda name, disk_size, git_name=None, git_email=None, dotfiles_uri=None, verbose=False: captured.update(
{
"name": name,
"git_name": git_name,
@@ -909,13 +920,6 @@ class TestDevboxCommands:
assert result.exit_code == 0
assert "already up to date" in result.output
- def test_claude_prompt_uses_fallback_env_var(self, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.delenv("HOGLI_DEVBOX_CLAUDE_OAUTH_TOKEN", raising=False)
- monkeypatch.setenv("CLAUDE_OAUTH_TOKEN", "oauth-token")
- monkeypatch.setattr(keychain, "read", lambda service: None)
-
- assert devbox_cli._maybe_prompt_for_claude_oauth_token(None) == "oauth-token"
-
def test_local_port_check_ignores_missing_ipv6_support(self, monkeypatch: pytest.MonkeyPatch) -> None:
ipv4_socket = MagicMock()
ipv4_socket.__enter__.return_value = ipv4_socket
@@ -1280,140 +1284,285 @@ class TestSharingFunctions:
assert result[0]["name"] == "devbox-alice"
-class TestKeychain:
- """Test macOS Keychain helpers."""
+class TestServerSupportsUserSecrets:
+ """Test the >=2.33 gate for Coder user secrets."""
@pytest.mark.parametrize(
- "fn,args,expected",
+ "version, expected",
[
- (keychain.read, ("test-service",), None),
- (keychain.write, ("test-service", "value"), False),
- (keychain.delete, ("test-service",), False),
+ ("2.32.5", False),
+ ("2.33.0", True),
+ ("2.33.1", True),
+ ("3.0.0", True),
+ ("2.33.0-rc1", True),
+ ("1.0.0", False),
],
)
- def test_operations_return_sentinel_on_non_macos(self, monkeypatch: pytest.MonkeyPatch, fn, args, expected) -> None:
- monkeypatch.setattr(keychain, "_is_macos", lambda: False)
- assert fn(*args) == expected
-
- def test_is_supported_reflects_platform(self, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(keychain, "_is_macos", lambda: True)
- assert keychain.is_supported() is True
- monkeypatch.setattr(keychain, "_is_macos", lambda: False)
- assert keychain.is_supported() is False
-
- def test_read_returns_value_on_success(self, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(keychain, "_is_macos", lambda: True)
+ def test_version_gate(self, monkeypatch: pytest.MonkeyPatch, version: str, expected: bool) -> None:
+ monkeypatch.setattr(coder, "get_server_version", lambda: version)
+ assert coder.server_supports_user_secrets() is expected
+
+ def test_returns_false_when_version_undetermined(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ def boom() -> str:
+ raise RuntimeError("offline")
+
+ monkeypatch.setattr(coder, "get_server_version", boom)
+ assert coder.server_supports_user_secrets() is False
+
+
+class TestCoderUserSecrets:
+ """Test the coder.py wrappers around `coder secret list/create/delete`."""
+
+ def test_list_user_secrets_parses_json(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ payload = [{"name": "CLAUDE_CODE_OAUTH_TOKEN", "env_name": "CLAUDE_CODE_OAUTH_TOKEN"}]
monkeypatch.setattr(
- keychain.subprocess,
- "run",
- lambda args, **kwargs: subprocess.CompletedProcess(args, 0, stdout="my-token\n", stderr=""),
+ coder,
+ "_run",
+ lambda args, capture_output=False: subprocess.CompletedProcess(args, 0, json.dumps(payload), ""),
)
- assert keychain.read("test-service") == "my-token"
+ secrets = coder.list_user_secrets()
+ assert secrets is not None
+ assert secrets[0]["name"] == "CLAUDE_CODE_OAUTH_TOKEN"
- def test_read_returns_none_on_failure(self, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(keychain, "_is_macos", lambda: True)
+ def test_list_user_secrets_returns_none_on_cli_failure(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(
- keychain.subprocess,
- "run",
- lambda args, **kwargs: subprocess.CompletedProcess(args, 44, stdout="", stderr=""),
+ coder,
+ "_run",
+ lambda args, capture_output=False: subprocess.CompletedProcess(args, 1, "", "unsupported"),
)
- assert keychain.read("test-service") is None
+ assert coder.list_user_secrets() is None
- def test_write_calls_delete_then_add(self, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(keychain, "_is_macos", lambda: True)
- calls: list[list[str]] = []
+ def test_has_claude_oauth_secret(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(coder, "list_user_secrets", lambda: [{"name": "CLAUDE_CODE_OAUTH_TOKEN"}])
+ assert coder.has_claude_oauth_secret() is True
+ monkeypatch.setattr(coder, "list_user_secrets", lambda: [{"name": "OTHER"}])
+ assert coder.has_claude_oauth_secret() is False
+ monkeypatch.setattr(coder, "list_user_secrets", lambda: None)
+ assert coder.has_claude_oauth_secret() is False
- def fake_run(args: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
- calls.append(args)
+ def test_delete_user_secret_passes_yes(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ captured: list[list[str]] = []
+
+ def fake_run(args: list[str], capture_output: bool = False) -> subprocess.CompletedProcess[str]:
+ captured.append(args)
return subprocess.CompletedProcess(args, 0, "", "")
- monkeypatch.setattr(keychain.subprocess, "run", fake_run)
- assert keychain.write("test-service", "my-value") is True
- assert len(calls) == 2
- assert "delete-generic-password" in calls[0]
- assert "test-service" in calls[0]
- assert "add-generic-password" in calls[1]
- assert "my-value" in calls[1]
+ monkeypatch.setattr(coder, "_run", fake_run)
+ coder.delete_user_secret("CLAUDE_CODE_OAUTH_TOKEN")
+ assert captured == [["coder", "secret", "delete", "CLAUDE_CODE_OAUTH_TOKEN", "--yes"]]
+
+
+class TestSetupClaudeSecret:
+ """Test the Claude user-secret step in devbox:setup."""
- def test_delete_returns_true_on_success(self, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(keychain, "_is_macos", lambda: True)
+ def test_skips_when_server_does_not_support_user_secrets(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli, "server_supports_user_secrets", lambda: False)
+
+ echoed: list[str] = []
+ monkeypatch.setattr(devbox_cli.click, "echo", lambda msg="", **kw: echoed.append(str(msg)))
+
+ devbox_cli.maybe_configure_claude_secret(None)
+ assert any("older than 2.33" in line for line in echoed)
+
+ def test_skips_when_secret_already_exists(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli, "server_supports_user_secrets", lambda: True)
+ monkeypatch.setattr(devbox_cli, "has_claude_oauth_secret", lambda: True)
+
+ echoed: list[str] = []
+ monkeypatch.setattr(devbox_cli.click, "echo", lambda msg="", **kw: echoed.append(str(msg)))
+
+ devbox_cli.maybe_configure_claude_secret(None)
+ assert any("already set as a Coder user secret" in line for line in echoed)
+
+ def test_skip_flag_short_circuits(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli, "server_supports_user_secrets", lambda: True)
+
+ called: list[str] = []
+ monkeypatch.setattr(devbox_cli, "has_claude_oauth_secret", lambda: called.append("listed") or False)
+
+ echoed: list[str] = []
+ monkeypatch.setattr(devbox_cli.click, "echo", lambda msg="", **kw: echoed.append(str(msg)))
+
+ devbox_cli.maybe_configure_claude_secret(False)
+ assert any("Skipping" in line for line in echoed)
+ assert called == []
+
+ def test_migrates_legacy_keychain_token_into_user_secret(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli, "server_supports_user_secrets", lambda: True)
+ monkeypatch.setattr(devbox_cli, "has_claude_oauth_secret", lambda: False)
+ monkeypatch.setattr(devbox_cli, "_read_legacy_keychain_token", lambda: "legacy-token")
+ monkeypatch.setattr(devbox_cli.click, "confirm", lambda *a, **kw: True)
+
+ deleted: list[bool] = []
+ monkeypatch.setattr(devbox_cli, "_delete_legacy_keychain_token", lambda: deleted.append(True) or True)
+
+ upserts: list[tuple[str, str]] = []
monkeypatch.setattr(
- keychain.subprocess,
- "run",
- lambda args, **kwargs: subprocess.CompletedProcess(args, 0, "", ""),
+ devbox_cli,
+ "upsert_user_secret",
+ lambda name, value, **kw: upserts.append((name, value)),
+ )
+
+ echoed: list[str] = []
+ monkeypatch.setattr(devbox_cli.click, "echo", lambda msg="", **kw: echoed.append(str(msg)))
+
+ devbox_cli.maybe_configure_claude_secret(None)
+
+ assert upserts == [("CLAUDE_CODE_OAUTH_TOKEN", "legacy-token")]
+ assert deleted == [True]
+
+ def test_fresh_setup_creates_secret_from_prompt(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli, "server_supports_user_secrets", lambda: True)
+ monkeypatch.setattr(devbox_cli, "has_claude_oauth_secret", lambda: False)
+ monkeypatch.setattr(devbox_cli, "_read_legacy_keychain_token", lambda: None)
+ monkeypatch.setattr(devbox_cli.click, "pause", lambda *a, **kw: None)
+ monkeypatch.setattr(devbox_cli.click, "echo", lambda *a, **kw: None)
+ monkeypatch.setattr(devbox_cli.click, "prompt", lambda *a, **kw: "fresh-token")
+
+ upserts: list[str] = []
+ monkeypatch.setattr(
+ devbox_cli,
+ "upsert_user_secret",
+ lambda name, value, **kw: upserts.append(value),
)
- assert keychain.delete("test-service") is True
- def test_delete_returns_false_when_not_found(self, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(keychain, "_is_macos", lambda: True)
+ devbox_cli.maybe_configure_claude_secret(None)
+ assert upserts == ["fresh-token"]
+
+ def test_empty_prompt_skips_create(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli, "server_supports_user_secrets", lambda: True)
+ monkeypatch.setattr(devbox_cli, "has_claude_oauth_secret", lambda: False)
+ monkeypatch.setattr(devbox_cli, "_read_legacy_keychain_token", lambda: None)
+ monkeypatch.setattr(devbox_cli.click, "pause", lambda *a, **kw: None)
+ monkeypatch.setattr(devbox_cli.click, "echo", lambda *a, **kw: None)
+ monkeypatch.setattr(devbox_cli.click, "prompt", lambda *a, **kw: "")
+
+ called: list[str] = []
monkeypatch.setattr(
- keychain.subprocess,
- "run",
- lambda args, **kwargs: subprocess.CompletedProcess(args, 44, "", ""),
+ devbox_cli,
+ "upsert_user_secret",
+ lambda *a, **kw: called.append("upsert"),
)
- assert keychain.delete("test-service") is False
+ devbox_cli.maybe_configure_claude_secret(None)
+ assert called == []
+
+
+class TestDevboxTaskClaudeWarning:
+ """Test the Claude-secret warning printed by devbox:task."""
+
+ def test_warns_when_secret_missing(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(devbox_cli, "server_supports_user_secrets", lambda: True)
+ monkeypatch.setattr(devbox_cli, "has_claude_oauth_secret", lambda: False)
+ monkeypatch.setattr(devbox_cli, "create_task", lambda *a, **kw: None)
+
+ result = runner.invoke(cli, ["devbox:task", "do something"])
+
+ assert result.exit_code == 0
+ assert "no 'CLAUDE_CODE_OAUTH_TOKEN' Coder user secret set" in result.output
+
+ def test_no_warning_when_secret_present(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(devbox_cli, "server_supports_user_secrets", lambda: True)
+ monkeypatch.setattr(devbox_cli, "has_claude_oauth_secret", lambda: True)
+ monkeypatch.setattr(devbox_cli, "create_task", lambda *a, **kw: None)
+
+ result = runner.invoke(cli, ["devbox:task", "do something"])
+
+ assert result.exit_code == 0
+ assert "no 'CLAUDE_CODE_OAUTH_TOKEN' Coder user secret set" not in result.output
+
+ def test_no_warning_when_server_unsupported(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(devbox_cli, "server_supports_user_secrets", lambda: False)
+ called: list[bool] = []
+ monkeypatch.setattr(devbox_cli, "has_claude_oauth_secret", lambda: called.append(True) or False)
+ monkeypatch.setattr(devbox_cli, "create_task", lambda *a, **kw: None)
+
+ result = runner.invoke(cli, ["devbox:task", "do something"])
+
+ assert result.exit_code == 0
+ assert called == []
+
+
+class TestDevboxSecretCommands:
+ """Test the devbox:secret:list / set / rm wrappers."""
-class TestClaudeTokenResolution:
- """Test the token resolution order in _maybe_prompt_for_claude_oauth_token."""
+ def test_secret_list_renders_rows(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(devbox_cli, "server_supports_user_secrets", lambda: True)
+ monkeypatch.setattr(
+ devbox_cli,
+ "list_user_secrets",
+ lambda: [
+ {"name": "CLAUDE_CODE_OAUTH_TOKEN", "env_name": "CLAUDE_CODE_OAUTH_TOKEN", "description": "claude"},
+ {"name": "GH_TOKEN", "env_name": "GH_TOKEN", "description": "github"},
+ ],
+ )
- def test_env_var_wins_over_keychain(self, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.delenv("HOGLI_DEVBOX_CLAUDE_OAUTH_TOKEN", raising=False)
- monkeypatch.setenv("CLAUDE_OAUTH_TOKEN", "env-token")
- monkeypatch.setattr(keychain, "read", lambda service: "keychain-token")
+ result = runner.invoke(cli, ["devbox:secret:list"])
+ assert result.exit_code == 0
+ assert "CLAUDE_CODE_OAUTH_TOKEN" in result.output
+ assert "GH_TOKEN" in result.output
- assert devbox_cli._maybe_prompt_for_claude_oauth_token(None) == "env-token"
+ def test_secret_list_fails_on_old_server(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(devbox_cli, "server_supports_user_secrets", lambda: False)
- def test_keychain_used_when_no_env_var(self, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.delenv("HOGLI_DEVBOX_CLAUDE_OAUTH_TOKEN", raising=False)
- monkeypatch.delenv("CLAUDE_OAUTH_TOKEN", raising=False)
- monkeypatch.setattr(keychain, "read", lambda service: "keychain-token")
+ result = runner.invoke(cli, ["devbox:secret:list"])
+ assert result.exit_code != 0
+ assert "does not support user secrets" in result.output
- assert devbox_cli._maybe_prompt_for_claude_oauth_token(None) == "keychain-token"
+ def test_secret_set_upserts_from_prompt(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(devbox_cli, "server_supports_user_secrets", lambda: True)
+ captured: dict[str, object] = {}
- def test_interactive_prompt_saves_to_keychain(self, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.delenv("HOGLI_DEVBOX_CLAUDE_OAUTH_TOKEN", raising=False)
- monkeypatch.delenv("CLAUDE_OAUTH_TOKEN", raising=False)
- monkeypatch.setattr(keychain, "read", lambda service: None)
- saved: list[str] = []
+ def fake_upsert(name: str, value: str, *, env_name=None, description=None) -> None:
+ captured["name"] = name
+ captured["value"] = value
+ captured["env_name"] = env_name
- def fake_write(service: str, value: str) -> bool:
- saved.append(value)
- return True
+ monkeypatch.setattr(devbox_cli, "upsert_user_secret", fake_upsert)
- monkeypatch.setattr(keychain, "write", fake_write)
+ result = runner.invoke(cli, ["devbox:secret:set", "GH_TOKEN"], input="ghp-value\nghp-value\n")
- monkeypatch.setattr(click, "confirm", lambda *a, **kw: True)
- monkeypatch.setattr(click, "prompt", lambda *a, **kw: "my-pasted-token")
- token = devbox_cli._maybe_prompt_for_claude_oauth_token(None)
+ assert result.exit_code == 0
+ assert captured == {"name": "GH_TOKEN", "value": "ghp-value", "env_name": "GH_TOKEN"}
- assert token == "my-pasted-token"
- assert saved == ["my-pasted-token"]
+ def test_secret_set_reads_value_from_file(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(devbox_cli, "server_supports_user_secrets", lambda: True)
+ source = tmp_path / "secret.txt"
+ source.write_text("file-value\n") # trailing newline must be stripped
- def test_explicit_configure_claude_skips_keychain(self, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.delenv("HOGLI_DEVBOX_CLAUDE_OAUTH_TOKEN", raising=False)
- monkeypatch.delenv("CLAUDE_OAUTH_TOKEN", raising=False)
- monkeypatch.setattr(keychain, "read", lambda service: "stale-token")
- saved: list[str] = []
+ captured: dict[str, object] = {}
+ monkeypatch.setattr(
+ devbox_cli,
+ "upsert_user_secret",
+ lambda name, value, **kw: captured.update({"name": name, "value": value}),
+ )
- def fake_write(service: str, value: str) -> bool:
- saved.append(value)
- return True
+ result = runner.invoke(cli, ["devbox:secret:set", "GH_TOKEN", "--file", str(source)])
+ assert result.exit_code == 0, result.output
+ assert captured == {"name": "GH_TOKEN", "value": "file-value"}
- monkeypatch.setattr(keychain, "write", fake_write)
+ def test_secret_rm_calls_delete(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli, "ensure_runtime_ready", lambda: None)
+ monkeypatch.setattr(devbox_cli, "server_supports_user_secrets", lambda: True)
- monkeypatch.setattr(click, "prompt", lambda *a, **kw: "fresh-token")
- token = devbox_cli._maybe_prompt_for_claude_oauth_token(True)
+ captured: list[str] = []
- assert token == "fresh-token"
- assert saved == ["fresh-token"]
+ def fake_delete(name: str) -> subprocess.CompletedProcess[str]:
+ captured.append(name)
+ return subprocess.CompletedProcess([], 0, "", "")
- def test_skipping_claude_returns_none(self, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.delenv("HOGLI_DEVBOX_CLAUDE_OAUTH_TOKEN", raising=False)
- monkeypatch.delenv("CLAUDE_OAUTH_TOKEN", raising=False)
- monkeypatch.setattr(keychain, "read", lambda service: None)
+ monkeypatch.setattr(devbox_cli, "delete_user_secret", fake_delete)
- assert devbox_cli._maybe_prompt_for_claude_oauth_token(False) is None
+ result = runner.invoke(cli, ["devbox:secret:rm", "GH_TOKEN"])
+ assert result.exit_code == 0
+ assert captured == ["GH_TOKEN"]
class TestCreateTask:
@@ -1517,65 +1666,6 @@ class TestDevboxTaskCommand:
assert captured == {"prompt": None, "task_name": None, "quiet": False}
-class TestSetupClaudeToken:
- """Test the Claude token step in devbox:setup."""
-
- def test_skips_when_token_already_in_keychain(self, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(keychain, "read", lambda service: "existing-token")
- monkeypatch.setattr(keychain, "is_supported", lambda: True)
-
- from io import StringIO
-
- output = StringIO()
- monkeypatch.setattr("sys.stdout", output)
- devbox_cli.maybe_configure_claude_token(None)
- assert "configured" in output.getvalue()
-
- def test_shows_explanation_before_prompt(self, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(keychain, "read", lambda service: None)
- monkeypatch.setattr(keychain, "is_supported", lambda: True)
-
- from io import StringIO
-
- output = StringIO()
- monkeypatch.setattr(click, "echo", lambda msg="", **kw: output.write(msg + "\n"))
- monkeypatch.setattr(click, "prompt", lambda *a, **kw: "")
- devbox_cli.maybe_configure_claude_token(None)
- text = output.getvalue()
- assert "Claude Code (optional)" in text
- assert "Keychain" in text
- assert "claude setup-token" in text
-
- def test_skips_on_non_macos(self, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(keychain, "read", lambda service: None)
- monkeypatch.setattr(keychain, "is_supported", lambda: False)
-
- from io import StringIO
-
- output = StringIO()
- monkeypatch.setattr(click, "echo", lambda msg="", **kw: output.write(msg + "\n"))
- devbox_cli.maybe_configure_claude_token(None)
- assert "CLAUDE_OAUTH_TOKEN" in output.getvalue()
-
- def test_configure_claude_true_replaces_existing_token(self, monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(keychain, "read", lambda service: "stale-token")
- monkeypatch.setattr(keychain, "is_supported", lambda: True)
- saved: list[str] = []
-
- def fake_write(service: str, value: str) -> bool:
- saved.append(value)
- return True
-
- monkeypatch.setattr(keychain, "write", fake_write)
- monkeypatch.setattr(click, "echo", lambda msg="", **kw: None)
- monkeypatch.setattr(click, "pause", lambda msg="": None)
- monkeypatch.setattr(click, "confirm", lambda *a, **kw: True)
- monkeypatch.setattr(click, "prompt", lambda *a, **kw: "fresh-token")
-
- devbox_cli.maybe_configure_claude_token(True)
- assert saved == ["fresh-token"]
-
-
class TestResolveLocalSigningKey:
"""Test reading user.signingkey from the engineer's local git config."""
@@ -1680,7 +1770,7 @@ class TestSetupGitSigning:
monkeypatch.setattr(
devbox_cli,
"upsert_user_secret",
- lambda name, value, env_var=None: upserts.append((name, value, env_var)),
+ lambda name, value, env_name=None, description=None: upserts.append((name, value, env_name)),
)
devbox_cli.maybe_configure_git_signing(None)
@@ -1694,7 +1784,7 @@ class TestSetupGitSigning:
monkeypatch.setattr(
devbox_cli,
"upsert_user_secret",
- lambda name, value, env_var=None: upserts.append((name, value, env_var)),
+ lambda name, value, env_name=None, description=None: upserts.append((name, value, env_name)),
)
devbox_cli.maybe_configure_git_signing(None)
@@ -1708,7 +1798,7 @@ class TestSetupGitSigning:
monkeypatch.setattr(
devbox_cli,
"upsert_user_secret",
- lambda name, value, env_var=None: upserts.append((name, value, env_var)),
+ lambda name, value, env_name=None, description=None: upserts.append((name, value, env_name)),
)
devbox_cli.maybe_configure_git_signing(True)
@@ -1722,7 +1812,7 @@ class TestSetupGitSigning:
monkeypatch.setattr(
devbox_cli,
"upsert_user_secret",
- lambda name, value, env_var=None: upserts.append((name, value, env_var)),
+ lambda name, value, env_name=None, description=None: upserts.append((name, value, env_name)),
)
devbox_cli.maybe_configure_git_signing(None)
@@ -1736,7 +1826,7 @@ class TestSetupGitSigning:
monkeypatch.setattr(
devbox_cli,
"upsert_user_secret",
- lambda name, value, env_var=None: upserts.append((name, value, env_var)),
+ lambda name, value, env_name=None, description=None: upserts.append((name, value, env_name)),
)
devbox_cli.maybe_configure_git_signing(None)