: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(devbox): verify devbox commit signing at setup (#90203)
Raúl Negrón-Otero31f1463a9a2b
diff --git a/tools/hogli-commands/hogli_commands/devbox/cli.py b/tools/hogli-commands/hogli_commands/devbox/cli.pyindex 8b205c424d9b..05e14a7324ce 100644--- a/tools/hogli-commands/hogli_commands/devbox/cli.py+++ b/tools/hogli-commands/hogli_commands/devbox/cli.py@@ -10,6 +10,7 @@ import sysimport errnoimport shutilimport socket+import tempfileimport functoolsimport subprocessimport urllib.parse@@ -36,6 +37,7 @@ from .coder import (REGIONS,_diagnose_unreachable_coder,_fail,+ _ssh_host_alias,_start_app_param,clone_workspace,coder_authenticated,@@ -492,16 +494,51 @@ 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 _ssh_config_without_coder_block() -> str | None:+ """Return ``~/.ssh/config`` with coder's managed block cut out, or ``None`` when there is nothing to cut.++ The deployment hostname matches the ``Host coder.*`` block that+ ``coder config-ssh`` writes, so resolving ``IdentityAgent`` against it+ reads back whatever the previous run wrote. An engineer who started+ without one therefore never acquires one, however many times they+ re-run setup.+ """+ try:+ content = (Path.home() / ".ssh" / "config").read_text()+ except OSError:+ return None+ lines = content.splitlines(keepends=True)+ start = next((i for i, line in enumerate(lines) if "START-CODER" in line), None)+ end = next((i for i, line in enumerate(lines) if "END-CODER" in line), None)+ if start is None or end is None or end < start:+ return None+ return "".join(lines[:start] + lines[end + 1 :])++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.+ ``Host *`` / ``Host *.posthog.dev`` / specific blocks all flow through,+ reading their config with coder's block removed so a value coder wrote+ on an earlier run cannot outrank the one they have set today.++ Falls back to the plain lookup, which sees coder's block, so a machine+ whose only ``IdentityAgent`` is the one coder wrote keeps it."""coder_host = urllib.parse.urlparse(get_coder_url()).hostnameif not coder_host:return None- return _resolve_local_identity_agent(coder_host)+ stripped = _ssh_config_without_coder_block()+ if stripped is None:+ return _resolve_local_identity_agent(coder_host)+ with tempfile.NamedTemporaryFile("w", suffix="-ssh-config", delete=False) as probe:+ probe.write(stripped)+ try:+ own = _resolve_local_identity_agent(coder_host, config_path=probe.name)+ finally:+ os.unlink(probe.name)+ return own or _resolve_local_identity_agent(coder_host)def _resolve_local_signing_key() -> str | None:@@ -532,23 +569,99 @@ def _resolve_local_signing_key() -> str | None:return None-def _resolve_local_identity_agent(host: str) -> str | None:+def _read_identity_agent(host: str, *, config_path: str | None = None) -> str | None:+ """Return the raw ``identityagent`` value ``ssh -G <host>`` resolves, or ``None`` when ssh fails.++ The raw value carries three meanings the normalized form collapses:+ a socket path, ``none`` (use no agent at all), and the placeholder+ ``SSH_AUTH_SOCK`` (fall back to the env var).+ """+ args = ["ssh", "-G", host] if config_path is None else ["ssh", "-F", config_path, "-G", host]+ result = subprocess.run(args, capture_output=True, text=True)+ if result.returncode != 0:+ return None+ for line in result.stdout.splitlines():+ if line.startswith("identityagent "):+ return line[len("identityagent ") :].strip()+ return None+++def _resolve_local_identity_agent(host: str, *, config_path: str | None = None) -> 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 specificagent" so callers can decide their own fallback."""- result = subprocess.run(["ssh", "-G", host], capture_output=True, text=True)+ value = _read_identity_agent(host, config_path=config_path)+ if value and value.lower() not in ("none", "ssh_auth_sock"):+ return value+ return None+++@dataclass(frozen=True)+class SigningAgentStatus:+ """Whether the agent ssh forwards into devboxes can sign commits, and why not when it can't."""++ ok: bool+ detail: str+++def _key_fingerprint(public_key: str) -> str | None:+ """Return the ``SHA256:...`` fingerprint of an SSH public key, or ``None`` when it will not parse."""+ result = subprocess.run(["ssh-keygen", "-lf", "-"], input=public_key, 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+ fields = result.stdout.split()+ return next((field for field in fields if field.startswith("SHA256:")), None)+++def _forwarded_agent_socket() -> str | None:+ """Return the agent socket ssh forwards to devboxes, or ``None`` when it forwards nothing.++ Mirrors what ``ssh`` itself does: ``IdentityAgent`` wins over the+ environment, ``none`` means no agent at all, and everything else falls+ back to ``$SSH_AUTH_SOCK``.+ """+ value = _read_identity_agent(_ssh_host_alias("probe"))+ if value and value.lower() != "ssh_auth_sock":+ return None if value.lower() == "none" else value+ return os.environ.get("SSH_AUTH_SOCK") or None+++def _diagnose_signing_agent() -> SigningAgentStatus:+ """Report whether the agent reaching Coder hosts holds the commit-signing key.++ Devbox signing is ``ssh-keygen -Y sign`` against a forwarded agent.+ Forwarding a socket that holds nothing -- or forwarding none at all --+ is not an ssh error, so the only symptom is a commit that fails to sign+ inside the workspace, hours later and far from the cause.+ """+ public_key = _resolve_local_signing_key()+ if not public_key:+ return SigningAgentStatus(False, "`git config --global user.signingkey` is empty")++ fingerprint = _key_fingerprint(public_key)+ if not fingerprint:+ return SigningAgentStatus(False, "`git config --global user.signingkey` is not a readable public key")++ socket_path = _forwarded_agent_socket()+ if not socket_path:+ return SigningAgentStatus(+ False, "ssh forwards no agent to Coder hosts (IdentityAgent none, or $SSH_AUTH_SOCK unset)"+ )++ listed = subprocess.run(+ ["ssh-add", "-l"],+ env={**os.environ, "SSH_AUTH_SOCK": socket_path},+ capture_output=True,+ text=True,+ )+ if listed.returncode != 0:+ return SigningAgentStatus(False, f"no agent responding at {socket_path}")+ if fingerprint not in listed.stdout:+ return SigningAgentStatus(False, f"agent at {socket_path} does not hold {fingerprint}")+ return SigningAgentStatus(True, f"{fingerprint} via {socket_path}")def maybe_configure_git_signing(@@ -598,12 +711,12 @@ def maybe_configure_git_signing(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}")+ signing_agent = _diagnose_signing_agent()+ if signing_agent.ok:+ click.echo(f" Agent forwarded to Coder hosts holds the key: {signing_agent.detail}")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.style(f" Commits will not sign inside devboxes: {signing_agent.detail}", fg="yellow"))+ click.echo(f" 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")@@ -772,6 +885,9 @@ def devbox_doctor() -> None:# `coder config-ssh` has run -- the prerequisite for devbox:ssh/exec._doctor_check("SSH access configured (devbox:ssh/exec)", coder_ssh_alias_configured("probe"))+ signing_agent = _diagnose_signing_agent()+ _doctor_check(f"Commit signing agent: {signing_agent.detail}", signing_agent.ok)+if not authenticated:_doctor_footer()returndiff --git a/tools/hogli-commands/hogli_commands/tests/test_devbox.py b/tools/hogli-commands/hogli_commands/tests/test_devbox.pyindex af006086f5a4..8e892a627a65 100644--- a/tools/hogli-commands/hogli_commands/tests/test_devbox.py+++ b/tools/hogli-commands/hogli_commands/tests/test_devbox.py@@ -3295,6 +3295,124 @@ class TestResolveLocalIdentityAgent:assert devbox_cli._resolve_local_identity_agent("coder.dev") is None+class TestResolveIdentityAgentForCoder:+ """Test that the Coder-host IdentityAgent lookup ignores coder's own managed block."""++ CODER_BLOCK = (+ "# ------------START-CODER-----------\n"+ "Host coder.*\n"+ '\tIdentityAgent "/tmp/written-by-coder.sock"\n'+ "# ------------END-CODER------------\n"+ )++ def _patch_ssh_g(self, monkeypatch: pytest.MonkeyPatch, home: Path) -> list[list[str]]:+ """Resolve identityagent from whichever config `ssh -G` was pointed at."""+ calls: list[list[str]] = []++ def fake_run(args: list[str], **kwargs: object) -> subprocess.CompletedProcess:+ calls.append(args)+ config = Path(args[2]).read_text() if args[1] == "-F" else (home / ".ssh" / "config").read_text()+ for line in config.splitlines():+ if "IdentityAgent" in line:+ return subprocess.CompletedProcess(args, 0, f"identityagent {line.split()[1].strip(chr(34))}\n", "")+ return subprocess.CompletedProcess(args, 0, "identityagent SSH_AUTH_SOCK\n", "")++ monkeypatch.setattr(devbox_cli.subprocess, "run", fake_run)+ monkeypatch.setattr(devbox_cli.Path, "home", lambda: home)+ return calls++ def test_prefers_the_engineers_own_socket_over_the_one_coder_wrote(+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+ ) -> None:+ (tmp_path / ".ssh").mkdir()+ (tmp_path / ".ssh" / "config").write_text(self.CODER_BLOCK + 'Host *\n\tIdentityAgent "/tmp/mine.sock"\n')+ self._patch_ssh_g(monkeypatch, tmp_path)++ assert devbox_cli._resolve_local_identity_agent_for_coder() == "/tmp/mine.sock"++ def test_keeps_the_socket_coder_wrote_when_the_engineer_has_none(+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path+ ) -> None:+ (tmp_path / ".ssh").mkdir()+ (tmp_path / ".ssh" / "config").write_text(self.CODER_BLOCK)+ self._patch_ssh_g(monkeypatch, tmp_path)++ assert devbox_cli._resolve_local_identity_agent_for_coder() == "/tmp/written-by-coder.sock"+++class TestDiagnoseSigningAgent:+ """Test the pre-flight check that devbox commits will actually sign."""++ PUBLIC_KEY = "ssh-ed25519 AAAAC3 user@host"+ FINGERPRINT = "SHA256:abc123"++ def _patch(+ self,+ monkeypatch: pytest.MonkeyPatch,+ *,+ identity_agent: str | None,+ env_sock: str | None,+ agent_keys: str | None,+ ) -> None:+ monkeypatch.setattr(devbox_cli, "_resolve_local_signing_key", lambda: self.PUBLIC_KEY)+ if env_sock is None:+ monkeypatch.delenv("SSH_AUTH_SOCK", raising=False)+ else:+ monkeypatch.setenv("SSH_AUTH_SOCK", env_sock)++ def fake_run(args: list[str], **kwargs: object) -> subprocess.CompletedProcess:+ if args[0] == "ssh-keygen":+ return subprocess.CompletedProcess(args, 0, f"256 {self.FINGERPRINT} host (ED25519)\n", "")+ if args[0] == "ssh":+ value = identity_agent or "SSH_AUTH_SOCK"+ return subprocess.CompletedProcess(args, 0, f"identityagent {value}\n", "")+ if agent_keys is None:+ return subprocess.CompletedProcess(args, 1, "", "Could not open a connection")+ return subprocess.CompletedProcess(args, 0, agent_keys, "")++ monkeypatch.setattr(devbox_cli.subprocess, "run", fake_run)++ def test_ok_when_the_forwarded_agent_holds_the_signing_key(self, monkeypatch: pytest.MonkeyPatch) -> None:+ self._patch(+ monkeypatch,+ identity_agent=None,+ env_sock="/tmp/agent.sock",+ agent_keys=f"256 {self.FINGERPRINT} host (ED25519)\n",+ )++ assert devbox_cli._diagnose_signing_agent().ok++ @pytest.mark.parametrize(+ "identity_agent,env_sock,agent_keys,expected_detail",+ [+ pytest.param("none", "/tmp/agent.sock", "", "forwards no agent", id="identity-agent-none-wins"),+ pytest.param(None, None, "", "forwards no agent", id="no-agent-anywhere"),+ pytest.param(None, "/tmp/agent.sock", None, "no agent responding", id="dead-socket"),+ pytest.param(+ None,+ "/tmp/agent.sock",+ "256 SHA256:other host (ED25519)\n",+ "does not hold",+ id="agent-holds-a-different-key",+ ),+ ],+ )+ def test_reports_why_signing_will_fail(+ self,+ monkeypatch: pytest.MonkeyPatch,+ identity_agent: str | None,+ env_sock: str | None,+ agent_keys: str | None,+ expected_detail: str,+ ) -> None:+ self._patch(monkeypatch, identity_agent=identity_agent, env_sock=env_sock, agent_keys=agent_keys)++ status = devbox_cli._diagnose_signing_agent()++ assert not status.ok+ assert expected_detail in status.detail++class TestConfigSshArgs:"""Test the `coder config-ssh` argument builder.@@ -3399,6 +3517,11 @@ class TestSetupGitSigning: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)+ monkeypatch.setattr(+ devbox_cli,+ "_diagnose_signing_agent",+ lambda: devbox_cli.SigningAgentStatus(bool(agent), agent or "no agent"),+ )def test_skips_when_secret_already_set(self, monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(devbox_cli, "user_secret_exists", lambda name: True)