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): enable signed commits inside Coder devboxes (#57316)

Raúl Negrón-Otero350d7bd4d174
diff --git a/tools/hogli-commands/hogli_commands/devbox/cli.py b/tools/hogli-commands/hogli_commands/devbox/cli.py
index eba216bfe30d..2bf0988009ed 100644
--- a/tools/hogli-commands/hogli_commands/devbox/cli.py
+++ b/tools/hogli-commands/hogli_commands/devbox/cli.py
@@ -11,6 +11,7 @@ import shutil
import socket
import functools
import subprocess
+import urllib.parse
from collections.abc import Callable
from pathlib import Path
from typing import Any
@@ -23,6 +24,7 @@ from .coder import (
DOTFILES_URI_PARAMETER,
GIT_EMAIL_PARAMETER,
GIT_NAME_PARAMETER,
+ GIT_SIGNING_KEY_SECRET,
_fail,
create_task,
create_workspace,
@@ -34,6 +36,7 @@ from .coder import (
ensure_tailscale_connected,
ensure_tailscale_routes_accepted,
extract_workspace_label,
+ get_coder_url,
get_coder_user_info,
get_default_git_identity,
get_shared_users,
@@ -61,10 +64,13 @@ from .coder import (
unshare_workspace,
update_workspace,
update_workspace_parameters,
+ upsert_user_secret,
+ user_secret_exists,
)
from .config import load_config, save_dotfiles_uri, save_git_identity
_CLAUDE_TOKEN_SERVICE = "posthog-claude-oauth-token"
+_POSTHOG_COMMIT_SIGNING_HANDBOOK_URL = "https://posthog.com/handbook/engineering/security#commit-signing"
WORKSPACE_STATUS_COLORS = {
"running": "green",
@@ -332,6 +338,123 @@ def maybe_configure_git_identity(configure_git_identity: bool | None) -> None:
click.echo(f"Saved Git identity for new workspaces: {git_name} <{git_email}>")
+def _resolve_local_identity_agent_for_coder() -> str | None:
+ """Return the IdentityAgent ssh would use to connect to Coder workspaces, or ``None``.
+
+ Resolves against the deployment hostname so the engineer's existing
+ ``Host *`` / ``Host *.posthog.dev`` / specific blocks all flow through.
+ """
+ coder_host = urllib.parse.urlparse(get_coder_url()).hostname
+ if not coder_host:
+ return None
+ return _resolve_local_identity_agent(coder_host)
+
+
+def _resolve_local_signing_key() -> str | None:
+ """Return the engineer's ``git config user.signingkey``, normalized to a literal SSH public key string.
+
+ Git accepts two formats: a literal ``ssh-... / ecdsa-... / sk-...`` string
+ or a path to a public-key file. Both are normalized here. Returns ``None``
+ when the value is unset or the referenced file can't be read.
+ """
+ result = subprocess.run(
+ ["git", "config", "--global", "--get", "user.signingkey"],
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode != 0:
+ return None
+ value = result.stdout.strip()
+ if not value:
+ return None
+ if value.startswith(("ssh-", "ecdsa-", "sk-")):
+ return value
+ try:
+ return Path(os.path.expanduser(value)).read_text().strip() or None
+ except OSError:
+ return None
+
+
+def _resolve_local_identity_agent(host: str) -> str | None:
+ """Return the SSH agent socket ``ssh -G <host>`` would use to authenticate, or ``None`` when no specific agent is configured.
+
+ Treats ``none`` (signaling "no agent") and the literal placeholder
+ ``SSH_AUTH_SOCK`` (signaling "fall back to the env var") as "no specific
+ agent" so callers can decide their own fallback.
+ """
+ result = subprocess.run(["ssh", "-G", host], capture_output=True, text=True)
+ if result.returncode != 0:
+ return None
+ for line in result.stdout.splitlines():
+ if line.startswith("identityagent "):
+ value = line[len("identityagent ") :].strip()
+ if value and value.lower() not in ("none", "ssh_auth_sock"):
+ return value
+ return None
+ return None
+
+
+def maybe_configure_git_signing(configure_git_signing: bool | None) -> None:
+ """Propagate the engineer's existing local commit-signing config into devboxes.
+
+ Reads ``git config user.signingkey`` (the public key the engineer already
+ signs locally with) and ``ssh -G <coder-host>``'s ``identityagent`` (the
+ SSH agent ssh would use for the connection, which is the agent that gets
+ forwarded). Pushes the public key to a Coder user secret and pins the
+ agent socket as the local IdentityAgent for Coder hosts. No menus, no
+ probing -- whatever the engineer has set up locally per the handbook is
+ what propagates.
+ """
+ already_set = user_secret_exists(GIT_SIGNING_KEY_SECRET)
+
+ if configure_git_signing is False:
+ if already_set:
+ click.echo("Using saved Git signing key.")
+ click.echo("Run `hogli devbox:setup --configure-git-signing` to change.")
+ else:
+ click.echo("Skipping Git commit signing setup.")
+ return
+
+ if configure_git_signing is None and already_set:
+ click.echo("Git signing: configured (commits inside devbox will be signed).")
+ click.echo("Run `hogli devbox:setup --configure-git-signing` to change.")
+ return
+
+ public_key = _resolve_local_signing_key()
+ if not public_key:
+ click.echo()
+ click.echo(click.style("Git commit signing (skipped)", bold=True))
+ click.echo(" `git config --global user.signingkey` is empty.")
+ click.echo(f" Set up commit signing per the handbook: {_POSTHOG_COMMIT_SIGNING_HANDBOOK_URL}")
+ click.echo(" Then re-run `hogli devbox:setup --configure-git-signing`.")
+ return
+
+ if public_key.startswith("ssh-rsa "):
+ click.echo()
+ click.echo(click.style("RSA signing keys are not allowed.", fg="red"))
+ 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)
+
+ click.echo()
+ click.echo(click.style("Git commit signing", bold=True))
+ click.echo(f" Pushed signing key from `git config user.signingkey`: {public_key}")
+ agent_socket = _resolve_local_identity_agent_for_coder()
+ if agent_socket:
+ click.echo(f" IdentityAgent for Coder hosts (from your ssh config): {agent_socket}")
+ else:
+ click.echo(" No IdentityAgent detected for Coder hosts -- SSH agent forwarding will use")
+ click.echo(f" whatever `$SSH_AUTH_SOCK` points to. Configure per: {_POSTHOG_COMMIT_SIGNING_HANDBOOK_URL}")
+ click.echo()
+ click.echo(click.style("If you haven't already:", bold=True))
+ click.echo(" 1. Open https://github.com/settings/ssh/new")
+ click.echo(" 2. Set 'Key type' to 'Signing Key' (auth keys do not sign).")
+ click.echo(" 3. Paste the key above.")
+ click.echo()
+ click.echo("Restart any running devbox (`hogli devbox:restart`) to pick up the new gitconfig.")
+
+
def maybe_configure_dotfiles(configure_dotfiles: bool | None) -> None:
"""Optionally persist a dotfiles repo URL for new workspaces."""
config = load_config()
@@ -425,6 +548,11 @@ def maybe_configure_claude_token(configure_claude: bool | None) -> None:
default=None,
help="Prompt for Git name/email defaults for new Coder workspaces",
)
+ "--configure-git-signing/--skip-configure-git-signing",
+ default=None,
+ help="Propagate your local git signing key into Coder devboxes (reads git config user.signingkey)",
+)
@click.option(
"--configure-dotfiles/--skip-configure-dotfiles",
default=None,
@@ -440,6 +568,7 @@ def maybe_configure_claude_token(configure_claude: bool | None) -> None:
def devbox_setup(
configure_ssh: bool | None,
configure_git_identity: bool | None,
+ configure_git_signing: bool | None,
configure_dotfiles: bool | None,
configure_claude_setup: bool | None,
verbose: bool,
@@ -450,8 +579,13 @@ def devbox_setup(
ensure_coder_reachable()
ensure_coder_installed(verbose=verbose)
ensure_coder_authenticated()
- maybe_configure_ssh(configure_ssh=configure_ssh, verbose=verbose)
+ maybe_configure_ssh(
+ configure_ssh=configure_ssh,
+ identity_agent_socket=_resolve_local_identity_agent_for_coder(),
+ verbose=verbose,
+ )
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)
print_setup_summary()
diff --git a/tools/hogli-commands/hogli_commands/devbox/coder.py b/tools/hogli-commands/hogli_commands/devbox/coder.py
index bf648f6027a6..06bdd890b18f 100644
--- a/tools/hogli-commands/hogli_commands/devbox/coder.py
+++ b/tools/hogli-commands/hogli_commands/devbox/coder.py
@@ -36,6 +36,13 @@ DOTFILES_URI_PARAMETER = "dotfiles_uri"
DOTFILES_BRANCH_PARAMETER = "dotfiles_branch"
JETBRAINS_IDES_PARAMETER = "jetbrains_ides"
+# Per-user Coder secret holding the SSH public key used to sign commits inside
+# workspaces. Injected as the GIT_SIGNING_KEY env var on every workspace start
+# (including coder task runs); the workspace template reads it to populate
+# user.signingkey. The matching private key never leaves 1Password.
+GIT_SIGNING_KEY_SECRET = "GIT_SIGNING_KEY"
+
+
# Default values for all optional template parameters. Passing these explicitly
# prevents the Coder CLI from prompting interactively for missing values.
# Update this dict when new optional parameters are added to the template.
@@ -322,18 +329,32 @@ def ensure_coder_reachable() -> None:
)
-def _config_ssh_args() -> list[str]:
- """Build the base args for ``coder config-ssh``, pinning the managed binary path."""
+def _config_ssh_args(*, identity_agent_socket: str | None = None) -> list[str]:
+ """Build the base args for ``coder config-ssh``, pinning the managed binary path.
+
+ Appends SSH options that wire up commit signing via SSH agent forwarding:
+ ``ForwardAgent yes`` so the laptop's SSH agent reaches the remote, and (on
+ macOS) ``IdentityAgent <socket>`` pointed at whichever signing-key agent
+ the engineer picked in ``--configure-git-signing`` (Secretive or 1Password).
+ ``IdentityAgent`` is omitted when no socket has been chosen yet, leaving
+ SSH to fall back to the user's default ``$SSH_AUTH_SOCK``.
+ """
args = ["coder", "config-ssh"]
managed = _MANAGED_CODER_DIR / "coder"
if managed.is_file():
args += ["--coder-binary-path", str(managed)]
+ args += ["--ssh-option", "ForwardAgent yes"]
+ if identity_agent_socket:
+ args += ["--ssh-option", f"IdentityAgent {identity_agent_socket}"]
return args
-def _ssh_config_needs_update() -> bool:
+def _ssh_config_needs_update(*, identity_agent_socket: str | None = None) -> bool:
"""Check whether ``coder config-ssh`` would make changes."""
- result = _run([*_config_ssh_args(), "--dry-run", "--yes"], capture_output=True)
+ result = _run(
+ [*_config_ssh_args(identity_agent_socket=identity_agent_socket), "--dry-run", "--yes"],
+ capture_output=True,
+ )
if result.returncode != 0:
return True
combined = result.stdout + result.stderr
@@ -488,9 +509,11 @@ def ensure_runtime_ready() -> None:
_warn_version_mismatch()
-def maybe_configure_ssh(*, configure_ssh: bool | None, verbose: bool = False) -> None:
+def maybe_configure_ssh(
+ *, configure_ssh: bool | None, identity_agent_socket: str | None = None, verbose: bool = False
+) -> None:
"""Install Coder SSH config, skipping only when explicitly opted out."""
- if not _ssh_config_needs_update():
+ if not _ssh_config_needs_update(identity_agent_socket=identity_agent_socket):
click.echo("Coder SSH config is up to date.")
return
@@ -500,7 +523,10 @@ def maybe_configure_ssh(*, configure_ssh: bool | None, verbose: bool = False) ->
return
click.echo("Adding Coder workspace entries to ~/.ssh/config...")
- result = _run([*_config_ssh_args(), "--yes"], capture_output=not verbose)
+ result = _run(
+ [*_config_ssh_args(identity_agent_socket=identity_agent_socket), "--yes"],
+ capture_output=not verbose,
+ )
if result.returncode != 0:
if not verbose:
click.echo(result.stdout or "")
@@ -522,6 +548,7 @@ def print_setup_summary() -> None:
click.echo()
click.echo("To reconfigure later:")
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")
@@ -759,6 +786,50 @@ 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:
+ """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).
+ """
+ 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
+
+ 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)
+
+
+def user_secret_exists(name: str) -> bool:
+ """Return whether the current user has a secret with the given name set."""
+ result = _run(["coder", "secret", "list", "--output", "json"], capture_output=True)
+ if result.returncode != 0:
+ return False
+ try:
+ secrets = json.loads(result.stdout)
+ except json.JSONDecodeError:
+ return False
+ if not isinstance(secrets, list):
+ return False
+ return any(isinstance(s, dict) and s.get("name") == name for s in secrets)
+
+
def ssh_replace(name: str) -> None:
"""SSH into a workspace and replace the current process."""
_run_or_exit(["coder", "ssh", name])
diff --git a/tools/hogli-commands/hogli_commands/devbox/config.py b/tools/hogli-commands/hogli_commands/devbox/config.py
index e4cd20d4341f..b53a60669a03 100644
--- a/tools/hogli-commands/hogli_commands/devbox/config.py
+++ b/tools/hogli-commands/hogli_commands/devbox/config.py
@@ -13,6 +13,9 @@ class DevboxConfig(TypedDict, total=False):
dotfiles_uri: str
+_PERSISTED_FIELDS = ("git_name", "git_email", "dotfiles_uri")
+
+
def get_config_path() -> Path:
"""Return the config path for persisted hogli devbox preferences."""
return Path.home() / ".config" / "posthog" / "hogli_devbox.json"
@@ -29,7 +32,7 @@ def load_config() -> DevboxConfig:
return DevboxConfig()
config = DevboxConfig()
- for key in ("git_name", "git_email", "dotfiles_uri"):
+ for key in _PERSISTED_FIELDS:
value = data.get(key)
if isinstance(value, str):
stripped_value = value.strip()
@@ -41,7 +44,7 @@ def load_config() -> DevboxConfig:
def save_config(config: DevboxConfig) -> None:
"""Persist hogli devbox preferences to disk."""
normalized = DevboxConfig()
- for key in ("git_name", "git_email", "dotfiles_uri"):
+ for key in _PERSISTED_FIELDS:
value = config.get(key)
if isinstance(value, str):
stripped_value = value.strip()
diff --git a/tools/hogli-commands/hogli_commands/tests/test_devbox.py b/tools/hogli-commands/hogli_commands/tests/test_devbox.py
index fc7dd16b504d..0ae93441340b 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_devbox.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_devbox.py
@@ -63,6 +63,70 @@ class TestDevboxConfig:
}
+class TestUserSecrets:
+ """Test the per-user Coder secret helpers used for Git signing."""
+
+ def test_upsert_creates_when_secret_does_not_exist(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ 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", "v1", env_var="API_KEY")
+
+ assert calls == [(["coder", "secret", "create", "API_KEY", "--env", "API_KEY"], "v1")]
+
+ def test_upsert_falls_back_to_update_when_create_fails(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ calls: list[list[str]] = []
+
+ def fake_run(args: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
+ calls.append(args)
+ returncode = 1 if "create" in args else 0
+ return subprocess.CompletedProcess(args, returncode, "", "")
+
+ 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")
+
+ assert calls == [
+ ["coder", "secret", "create", "API_KEY", "--env", "API_KEY"],
+ ["coder", "secret", "update", "API_KEY", "--env", "API_KEY"],
+ ]
+
+ 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")
+
+ monkeypatch.setattr(coder.subprocess, "run", fake_run)
+ 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")
+ assert excinfo.value.code == 2
+
+ def test_user_secret_exists_matches_by_name(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ coder,
+ "_run",
+ lambda args, **kw: subprocess.CompletedProcess(args, 0, '[{"name":"API_KEY"},{"name":"OTHER"}]', ""),
+ )
+ assert coder.user_secret_exists("API_KEY") is True
+ assert coder.user_secret_exists("MISSING") is False
+
+ def test_user_secret_exists_returns_false_on_cli_error(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(coder, "_run", lambda args, **kw: subprocess.CompletedProcess(args, 1, "", "auth required"))
+ assert coder.user_secret_exists("API_KEY") is False
+
+ def test_user_secret_exists_returns_false_on_invalid_json(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(coder, "_run", lambda args, **kw: subprocess.CompletedProcess(args, 0, "not json", ""))
+ assert coder.user_secret_exists("API_KEY") is False
+
+
class TestResolveTailscale:
"""Test Tailscale CLI resolution with macOS app bundle fallback."""
@@ -552,6 +616,11 @@ class TestDevboxCommands:
"maybe_configure_git_identity",
lambda configure_git_identity: calls.append(f"git:{configure_git_identity}"),
)
+ monkeypatch.setattr(
+ devbox_cli,
+ "maybe_configure_git_signing",
+ lambda configure_git_signing: calls.append(f"signing:{configure_git_signing}"),
+ )
monkeypatch.setattr(
devbox_cli,
"maybe_configure_dotfiles",
@@ -570,6 +639,7 @@ class TestDevboxCommands:
"devbox:setup",
"--skip-configure-ssh",
"--skip-configure-git-identity",
+ "--skip-configure-git-signing",
"--skip-configure-dotfiles",
"--skip-configure-claude",
],
@@ -584,11 +654,41 @@ class TestDevboxCommands:
"login",
"ssh:False",
"git:False",
+ "signing:False",
"dotfiles:False",
"claude:False",
"summary",
]
+ def test_devbox_setup_threads_resolved_identity_agent_into_ssh_config(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ captured: dict[str, object] = {}
+
+ monkeypatch.setattr(devbox_cli, "ensure_tailscale_connected", lambda setup_hint="": None)
+ monkeypatch.setattr(devbox_cli, "ensure_tailscale_routes_accepted", lambda: None)
+ monkeypatch.setattr(devbox_cli, "ensure_coder_reachable", lambda: None)
+ monkeypatch.setattr(devbox_cli, "ensure_coder_installed", lambda **kw: None)
+ monkeypatch.setattr(devbox_cli, "ensure_coder_authenticated", lambda: None)
+ monkeypatch.setattr(devbox_cli, "_resolve_local_identity_agent_for_coder", lambda: "/tmp/resolved.sock")
+ 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, "print_setup_summary", lambda: None)
+ monkeypatch.setattr(
+ devbox_cli,
+ "maybe_configure_ssh",
+ lambda *, configure_ssh, identity_agent_socket=None, **_: captured.update(
+ {"identity_agent_socket": identity_agent_socket}
+ ),
+ )
+
+ result = runner.invoke(cli, ["devbox:setup", "--skip-configure-git-identity"])
+
+ assert result.exit_code == 0
+ assert captured == {"identity_agent_socket": "/tmp/resolved.sock"}
+
def test_devbox_setup_uses_coder_profile_as_prompt_defaults(
self,
monkeypatch: pytest.MonkeyPatch,
@@ -599,7 +699,9 @@ class TestDevboxCommands:
monkeypatch.setattr(devbox_cli, "ensure_coder_reachable", lambda: None)
monkeypatch.setattr(devbox_cli, "ensure_coder_installed", lambda **kw: None)
monkeypatch.setattr(devbox_cli, "ensure_coder_authenticated", lambda: None)
+ monkeypatch.setattr(devbox_cli, "_resolve_local_identity_agent_for_coder", lambda: None)
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, "print_setup_summary", lambda: None)
@@ -631,7 +733,9 @@ class TestDevboxCommands:
monkeypatch.setattr(devbox_cli, "ensure_coder_reachable", lambda: None)
monkeypatch.setattr(devbox_cli, "ensure_coder_installed", lambda **kw: None)
monkeypatch.setattr(devbox_cli, "ensure_coder_authenticated", lambda: None)
+ monkeypatch.setattr(devbox_cli, "_resolve_local_identity_agent_for_coder", lambda: None)
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, "print_setup_summary", lambda: None)
@@ -1470,3 +1574,161 @@ class TestSetupClaudeToken:
devbox_cli.maybe_configure_claude_token(True)
assert saved == ["fresh-token"]
+
+
+class TestResolveLocalSigningKey:
+ """Test reading user.signingkey from the engineer's local git config."""
+
+ def test_returns_literal_ssh_string(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ devbox_cli.subprocess,
+ "run",
+ lambda *a, **kw: subprocess.CompletedProcess(a[0], 0, "ssh-ed25519 AAAA user@host\n", ""),
+ )
+ assert devbox_cli._resolve_local_signing_key() == "ssh-ed25519 AAAA user@host"
+
+ def test_reads_file_when_value_is_path(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ key_file = tmp_path / "id_ed25519.pub"
+ key_file.write_text("ssh-ed25519 AAAAFROMFILE user@host\n")
+ monkeypatch.setattr(
+ devbox_cli.subprocess,
+ "run",
+ lambda *a, **kw: subprocess.CompletedProcess(a[0], 0, str(key_file), ""),
+ )
+ assert devbox_cli._resolve_local_signing_key() == "ssh-ed25519 AAAAFROMFILE user@host"
+
+ def test_returns_none_when_unset(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli.subprocess, "run", lambda *a, **kw: subprocess.CompletedProcess(a[0], 1, "", ""))
+ assert devbox_cli._resolve_local_signing_key() is None
+
+ def test_returns_none_when_path_missing(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ missing = str(tmp_path / "absent.pub")
+ monkeypatch.setattr(
+ devbox_cli.subprocess,
+ "run",
+ lambda *a, **kw: subprocess.CompletedProcess(a[0], 0, missing, ""),
+ )
+ assert devbox_cli._resolve_local_signing_key() is None
+
+
+class TestResolveLocalIdentityAgent:
+ """Test reading IdentityAgent from `ssh -G <host>`."""
+
+ def test_returns_socket_path_when_set(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ devbox_cli.subprocess,
+ "run",
+ lambda *a, **kw: subprocess.CompletedProcess(
+ a[0], 0, "host coder.dev\nidentityagent /tmp/agent.sock\nidentityfile ~/.ssh/id_ed25519\n", ""
+ ),
+ )
+ assert devbox_cli._resolve_local_identity_agent("coder.dev") == "/tmp/agent.sock"
+
+ def test_returns_none_for_placeholder_value(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ devbox_cli.subprocess,
+ "run",
+ lambda *a, **kw: subprocess.CompletedProcess(a[0], 0, "identityagent SSH_AUTH_SOCK\n", ""),
+ )
+ assert devbox_cli._resolve_local_identity_agent("coder.dev") is None
+
+ def test_returns_none_for_none_value(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ devbox_cli.subprocess,
+ "run",
+ lambda *a, **kw: subprocess.CompletedProcess(a[0], 0, "identityagent none\n", ""),
+ )
+ assert devbox_cli._resolve_local_identity_agent("coder.dev") is None
+
+ def test_returns_none_when_ssh_g_fails(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ devbox_cli.subprocess,
+ "run",
+ lambda *a, **kw: subprocess.CompletedProcess(a[0], 255, "", "Bad host"),
+ )
+ assert devbox_cli._resolve_local_identity_agent("coder.dev") is None
+
+
+class TestSetupGitSigning:
+ """Test the Git commit signing step in devbox:setup.
+
+ Identity-agent threading into ssh config is not the wizard's job -- the
+ top-level ``devbox_setup`` resolves and applies it via ``ssh -G`` on every
+ run. The wizard only writes the user secret.
+ """
+
+ PUBLIC_KEY = "ssh-ed25519 AAAAC3 user@host"
+ AGENT_SOCKET = "/tmp/test-agent.sock"
+
+ def _patch_local_config(self, monkeypatch: pytest.MonkeyPatch, *, key: str | None, agent: str | None) -> None:
+ monkeypatch.setattr(devbox_cli, "_resolve_local_signing_key", lambda: key)
+ monkeypatch.setattr(devbox_cli, "_resolve_local_identity_agent_for_coder", lambda: agent)
+
+ def test_skips_when_secret_already_set(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli, "user_secret_exists", lambda name: True)
+ upserts: list[tuple[str, str, str | None]] = []
+ monkeypatch.setattr(
+ devbox_cli,
+ "upsert_user_secret",
+ lambda name, value, env_var=None: upserts.append((name, value, env_var)),
+ )
+
+ devbox_cli.maybe_configure_git_signing(None)
+
+ assert upserts == []
+
+ def test_pushes_local_signing_key_to_user_secret(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli, "user_secret_exists", lambda name: False)
+ self._patch_local_config(monkeypatch, key=self.PUBLIC_KEY, agent=self.AGENT_SOCKET)
+ upserts: list[tuple[str, str, str | None]] = []
+ monkeypatch.setattr(
+ devbox_cli,
+ "upsert_user_secret",
+ lambda name, value, env_var=None: upserts.append((name, value, env_var)),
+ )
+
+ devbox_cli.maybe_configure_git_signing(None)
+
+ assert upserts == [(coder.GIT_SIGNING_KEY_SECRET, self.PUBLIC_KEY, coder.GIT_SIGNING_KEY_SECRET)]
+
+ def test_explicit_reconfigure_overrides_existing_secret(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli, "user_secret_exists", lambda name: True)
+ self._patch_local_config(monkeypatch, key=self.PUBLIC_KEY, agent=self.AGENT_SOCKET)
+ upserts: list[tuple[str, str, str | None]] = []
+ monkeypatch.setattr(
+ devbox_cli,
+ "upsert_user_secret",
+ lambda name, value, env_var=None: upserts.append((name, value, env_var)),
+ )
+
+ devbox_cli.maybe_configure_git_signing(True)
+
+ assert upserts == [(coder.GIT_SIGNING_KEY_SECRET, self.PUBLIC_KEY, coder.GIT_SIGNING_KEY_SECRET)]
+
+ def test_skips_when_signing_key_unset_locally(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli, "user_secret_exists", lambda name: False)
+ self._patch_local_config(monkeypatch, key=None, agent=None)
+ upserts: list[tuple[str, str, str | None]] = []
+ monkeypatch.setattr(
+ devbox_cli,
+ "upsert_user_secret",
+ lambda name, value, env_var=None: upserts.append((name, value, env_var)),
+ )
+
+ devbox_cli.maybe_configure_git_signing(None)
+
+ assert upserts == []
+
+ def test_rejects_rsa_keys_per_handbook(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(devbox_cli, "user_secret_exists", lambda name: False)
+ self._patch_local_config(monkeypatch, key="ssh-rsa AAAAB3 old@host", agent=self.AGENT_SOCKET)
+ upserts: list[tuple[str, str, str | None]] = []
+ monkeypatch.setattr(
+ devbox_cli,
+ "upsert_user_secret",
+ lambda name, value, env_var=None: upserts.append((name, value, env_var)),
+ )
+
+ devbox_cli.maybe_configure_git_signing(None)
+
+ assert upserts == []