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(devex): add hogli git:signing-key for secure enclave signing (#124813)

Julian Bez280562c7cc0e
diff --git a/docs/published/handbook/engineering/developing-locally.md b/docs/published/handbook/engineering/developing-locally.md
index 5c84d753a1aa..4cc8bba5b435 100644
--- a/docs/published/handbook/engineering/developing-locally.md
+++ b/docs/published/handbook/engineering/developing-locally.md
@@ -65,8 +65,17 @@ This is the recommended option for most developers.
### Prerequisites
**GitHub access.**
-Before your first push, set up an [SSH key and commit signing](https://posthog.com/handbook/engineering/security#github) using Secretive or 1Password.
+Before your first push, set up an [SSH key and commit signing](https://posthog.com/handbook/engineering/security#github).
Signing is required: an org-wide ruleset rejects unsigned commits in every PostHog repository, so an unsigned push fails with `GH013: Commits must have verified signatures`.
+The signing key must live in your Mac's Secure Enclave.
+A signing key in 1Password doesn't meet this, because 1Password syncs it off the Mac.
+On macOS 26 or later, `hogli git:signing-key` creates a Secure Enclave signing key. Secretive works too.
+It's an SSH key used only for signing, so no GPG key is involved, and SSH logins and pushes keep using your current agent.
+The key can't be copied off the Mac, so each Mac needs its own key.
+It signs without a prompt, also while the screen is locked, so agents can commit while you're away.
+If you commit from a devbox, keep your previous signing key on GitHub.
+A devbox signs through your forwarded SSH agent, which can't hold a Secure Enclave key, so it keeps signing with the previous key.
+Otherwise, once no repository signs with your previous key, remove it from your GitHub settings, so it can't sign verified commits anymore. Commits you already pushed stay verified.
PR evidence uploads (`hogli pr:upload-image` and `hogli pr:upload-video`) prefer your stored GitHub CLI login over `GITHUB_TOKEN` from `.env.local`. Set `GH_TOKEN` to override the account; `GITHUB_TOKEN` remains the fallback when no CLI login exists.
diff --git a/hogli.yaml b/hogli.yaml
index 0df4afda78a6..e81e97c00236 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -1149,6 +1149,9 @@ devex:
devex:feedback:
click: hogli_commands.feedback:devex_feedback
description: Send feedback about the dev experience to the devex team (humans and agents)
+ git:signing-key:
+ click: hogli_commands.git_signing:signing_key
+ description: Set up commit signing with a Secure Enclave key (macOS 26 or later) and register it on GitHub
agent:usage:
click: hogli_commands.agent_usage:cmd_agent_usage
description: Show agent LLM token spend per pull request, from engineering analytics
diff --git a/tools/hogli-commands/hogli_commands/devbox/cli.py b/tools/hogli-commands/hogli_commands/devbox/cli.py
index 8aac6514f8f0..46932613045e 100644
--- a/tools/hogli-commands/hogli_commands/devbox/cli.py
+++ b/tools/hogli-commands/hogli_commands/devbox/cli.py
@@ -24,6 +24,7 @@ import click
from hogli import telemetry
from hogli.manifest import get_manifest
+from ..git_signing import DEVBOX_FEEDBACK_HINT, DEVBOX_SIGNING_NOTE, signs_with_secure_enclave_key
from . import mutagen
from .coder import (
CLAUDE_CODE_OAUTH_ENV,
@@ -575,7 +576,7 @@ def _resolve_local_signing_key() -> str | None:
Git accepts three formats: a literal ``ssh-... / ecdsa-... / sk-...``
string, the same with a ``key::`` prefix (used by tools like Secretive),
- or a path to a public-key file. All are normalized here. Returns ``None``
+ or a path to a key file. All are normalized here. Returns ``None``
when the value is unset or the referenced file can't be read.
"""
result = subprocess.run(
@@ -592,10 +593,17 @@ def _resolve_local_signing_key() -> str | None:
value = value.removeprefix("key::")
if value.startswith(("ssh-", "ecdsa-", "sk-")):
return value
- try:
- return Path(os.path.expanduser(value)).read_text().strip() or None
- except OSError:
- return None
+ key_path = Path(os.path.expanduser(value))
+ # git also accepts a private key path. The returned value goes into a Coder secret, so
+ # only public key content is returned, and a private key path falls back to its .pub file.
+ for candidate in (key_path, key_path.with_name(f"{key_path.name}.pub")):
+ try:
+ content = candidate.read_text().strip()
+ except OSError:
+ continue
+ if content.startswith(("ssh-", "ecdsa-", "sk-")):
+ return content
+ return None
def _read_identity_agent(host: str, *, config_path: str | None = None) -> str | None:
@@ -720,6 +728,20 @@ def maybe_configure_git_signing(
if configure_git_signing is None and already_set:
return
+ # Pushing this public key would make the devbox ask the forwarded agent for a key it can't hold.
+ if signs_with_secure_enclave_key():
+ click.echo()
+ click.echo(click.style("Git commit signing (Secure Enclave keys not supported yet)", bold=True))
+ if already_set:
+ lines = DEVBOX_SIGNING_NOTE
+ else:
+ lines = (
+ "Devbox commits won't be signed, because the forwarded SSH agent can't hold a Secure Enclave key.",
+ )
+ for line in (*lines, DEVBOX_FEEDBACK_HINT):
+ click.echo(f" {line}")
+ return
+
public_key = _resolve_local_signing_key()
if not public_key:
click.echo()
diff --git a/tools/hogli-commands/hogli_commands/git_signing.py b/tools/hogli-commands/hogli_commands/git_signing.py
new file mode 100644
index 000000000000..e9127c79d16a
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/git_signing.py
@@ -0,0 +1,402 @@
+"""hogli git:signing-key: create a Secure Enclave key and point git commit signing at it.
+
+macOS 26 ships `ssh-keychain.dylib`, a security key provider for OpenSSH that keeps the
+private key inside the Secure Enclave. The key cannot be exported or synced to another device.
+The key signs without a Touch ID prompt, also while the screen is locked, so agents can
+still sign commits when the engineer is away from the laptop.
+"""
+
+from __future__ import annotations
+
+import os
+import shlex
+import shutil
+import platform
+import tempfile
+import subprocess
+from pathlib import Path
+from typing import Final
+
+import click
+
+PROVIDER: Final = Path("/usr/lib/ssh-keychain.dylib")
+# Homebrew OpenSSH can come first on PATH and may not load Apple's provider.
+SSH_KEYGEN: Final = Path("/usr/bin/ssh-keygen")
+KEY_LABEL: Final = "git-signing"
+SSH_DIR: Final = Path.home() / ".ssh"
+KEY_PATH: Final = SSH_DIR / "id_ecdsa_sk_git_signing"
+SIGN_PROGRAM_PATH: Final = SSH_DIR / "ssh-keygen-secure-enclave"
+
+# git calls ssh-keygen without a provider flag, and SSH_SK_PROVIDER is missing in IDEs,
+# launchd jobs and agent shells. The wrapper sets the provider for every git process.
+SIGN_PROGRAM: Final = f"""#!/bin/sh
+SSH_SK_PROVIDER={PROVIDER} exec {SSH_KEYGEN} "$@"
+"""
+
+DEVBOX_SIGNING_NOTE: Final = (
+ "Your devbox keeps signing with your previous key, because it signs through your forwarded SSH agent "
+ "and the agent can't hold a Secure Enclave key.",
+ "Keep your previous signing key on GitHub while you commit from a devbox, so devbox commits still verify.",
+)
+DEVBOX_FEEDBACK_HINT: Final = (
+ 'To ask for Secure Enclave signing on devboxes: hogli devex:feedback -c idea "Secure Enclave signing on devboxes"'
+)
+
+GIT_VALUES: Final = {
+ "gpg.format": "ssh",
+ "user.signingkey": str(KEY_PATH),
+ "gpg.ssh.program": str(SIGN_PROGRAM_PATH),
+ "commit.gpgsign": "true",
+}
+
+
+def public_key_identity(public_key_line: str) -> str:
+ """Return the key type and key blob, without the comment that ssh-keygen -K writes."""
+ return " ".join(public_key_line.split()[:2])
+
+
+def pick_new_key(before: set[str], after: dict[str, Path]) -> Path:
+ """Return the key handle that is in `after` but not in `before`.
+
+ The provider exports every Secure Enclave key on the Mac, so other keys can be present.
+ """
+ new_handles = [handle for identity, handle in after.items() if identity not in before]
+ if len(new_handles) != 1:
+ raise click.ClickException(
+ f"Expected one new Secure Enclave key, found {len(new_handles)}. "
+ f"Check `sc_auth list-ctk-identities` for the `{KEY_LABEL}` key."
+ )
+ return new_handles[0]
+
+
+def add_allowed_signer(path: Path, email: str, public_key_line: str) -> bool:
+ """Append the key to an allowed signers file, unless the file already lists it."""
+ identity = public_key_identity(public_key_line)
+ existing = path.read_text() if path.exists() else ""
+ if identity in existing:
+ return False
+ separator = "\n" if existing and not existing.endswith("\n") else ""
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(f'{existing}{separator}{email} namespaces="git" {identity}\n')
+ return True
+
+
+def signs_with_secure_enclave_key() -> bool:
+ """Return whether the global git config signs through the wrapper this command installs."""
+ result = subprocess.run(["git", "config", "--global", "--get", "gpg.ssh.program"], capture_output=True, text=True)
+ return result.stdout.strip() == str(SIGN_PROGRAM_PATH)
+
+
+def forwards_agent_to_devboxes(ssh_config: Path) -> bool:
+ """Return whether the Coder block that `coder config-ssh` writes forwards an SSH agent."""
+ try:
+ content = ssh_config.read_text()
+ except OSError:
+ return False
+ coder_block = content.partition("START-CODER")[2].partition("END-CODER")[0]
+ return "ForwardAgent yes" in coder_block
+
+
+def git_config_command(repo: Path | None) -> list[str]:
+ """Return the git config command for one target, where `None` is the global config."""
+ if repo is None:
+ return ["git", "config", "--global"]
+ return ["git", "-C", str(repo), "config", "--local"]
+
+
+def effective_config_command(repo: Path | None) -> list[str]:
+ """Return the git config command that reads the merged config a target sees."""
+ if repo is None:
+ return ["git", "config"]
+ return ["git", "-C", str(repo), "config"]
+
+
+def repo_root(path: Path) -> Path:
+ result = subprocess.run(
+ ["git", "-C", str(path.expanduser()), "rev-parse", "--show-toplevel"], capture_output=True, text=True
+ )
+ if result.returncode != 0:
+ raise click.ClickException(f"{path} is not a git repository.")
+ return Path(result.stdout.strip())
+
+
+class SecureEnclaveSigningSetup:
+ def __init__(self, use_global: bool, repos: tuple[Path, ...]) -> None:
+ self.use_global = use_global
+ self.repos = repos
+ self.targets: list[Path | None] = []
+ self.previous_settings: dict[Path | None, dict[str, str | None]] = {}
+ self.uses_devbox = forwards_agent_to_devboxes(SSH_DIR / "config")
+
+ def _check_platform(self) -> None:
+ if platform.system() != "Darwin" or not PROVIDER.exists() or shutil.which("sc_auth") is None:
+ raise click.ClickException(f"This needs macOS 26 or later, which ships {PROVIDER} and sc_auth.")
+
+ def _choose_targets(self) -> list[Path | None]:
+ if self.use_global and self.repos:
+ raise click.ClickException("Pass either --global or --repo, not both.")
+ if self.use_global:
+ return [None]
+ if self.repos:
+ return [repo_root(repo) for repo in self.repos]
+ choice = click.prompt(
+ "Where should git sign with this key? "
+ "repo: this repository and its worktrees. global: every repository. list: repositories you name",
+ type=click.Choice(["repo", "global", "list"]),
+ default="repo",
+ )
+ if choice == "global":
+ return [None]
+ if choice == "repo":
+ return [repo_root(Path.cwd())]
+ paths = click.prompt("Repository paths, separated by commas")
+ return [repo_root(Path(path.strip())) for path in paths.split(",") if path.strip()]
+
+ def _git_config_get(self, command: list[str], setting: str) -> str | None:
+ result = subprocess.run([*command, "--get", setting], capture_output=True, text=True)
+ return result.stdout.strip() or None
+
+ def _confirm(self) -> None:
+ if KEY_PATH.exists():
+ click.echo(f"Using the existing Secure Enclave key at {KEY_PATH}.")
+ else:
+ click.echo(f"This creates a new signing key labeled `{KEY_LABEL}` inside the Mac's Secure Enclave.")
+ click.echo("The private key never leaves the Secure Enclave and can't be exported.")
+ click.echo("Any process running as you can sign with it, also while the screen is locked.")
+ click.echo(f"It writes a key handle to {KEY_PATH}. The handle only works with this Mac's Secure Enclave.")
+ click.echo("\nThese stop using your current signing key. Current values in effect:")
+ for target in self.targets:
+ click.echo(f" {'Global git config (every repository)' if target is None else target}")
+ self.previous_settings[target] = {}
+ for setting in GIT_VALUES:
+ self.previous_settings[target][setting] = self._git_config_get(git_config_command(target), setting)
+ effective = self._git_config_get(effective_config_command(target), setting)
+ click.echo(f" {setting} = {effective or '(unset)'}")
+ click.echo("SSH logins and pushes keep using your current SSH agent.")
+ if self.uses_devbox:
+ for line in (*DEVBOX_SIGNING_NOTE, DEVBOX_FEEDBACK_HINT):
+ click.echo(line)
+ click.confirm("Continue?", abort=True)
+
+ def _export_keys(self, directory: Path) -> dict[str, Path]:
+ """Write a key handle for each Secure Enclave key into `directory`, keyed by public key identity.
+
+ A key handle only references the key in the Secure Enclave. It is not the private key.
+ """
+ result = subprocess.run(
+ [str(SSH_KEYGEN), "-K", "-N", "", "-w", str(PROVIDER)],
+ cwd=directory,
+ capture_output=True,
+ text=True,
+ )
+ # Before the first key exists, the provider has nothing to export and ssh-keygen fails.
+ if result.returncode != 0:
+ return {}
+ return {
+ public_key_identity(public_path.read_text()): public_path.with_suffix("")
+ for public_path in directory.glob("*.pub")
+ }
+
+ def _create_key(self) -> None:
+ subprocess.run(
+ ["sc_auth", "create-ctk-identity", "-l", KEY_LABEL, "-k", "p-256-ne", "-t", "none"],
+ check=True,
+ )
+
+ def _install_key(self, handle: Path) -> None:
+ SSH_DIR.mkdir(mode=0o700, exist_ok=True)
+ shutil.copyfile(handle, KEY_PATH)
+ KEY_PATH.chmod(0o600)
+ shutil.copyfile(handle.with_name(f"{handle.name}.pub"), f"{KEY_PATH}.pub")
+
+ def _create_and_install_key(self) -> None:
+ with tempfile.TemporaryDirectory() as before_dir, tempfile.TemporaryDirectory() as after_dir:
+ before = set(self._export_keys(Path(before_dir)))
+ self._create_key()
+ self._install_key(pick_new_key(before, self._export_keys(Path(after_dir))))
+
+ def _install_sign_program(self) -> None:
+ SIGN_PROGRAM_PATH.write_text(SIGN_PROGRAM)
+ SIGN_PROGRAM_PATH.chmod(0o755)
+
+ def _test_sign(self) -> None:
+ with tempfile.TemporaryDirectory() as directory:
+ payload = Path(directory) / "payload"
+ payload.write_text("hogli git:signing-key test\n")
+ result = subprocess.run(
+ [str(SIGN_PROGRAM_PATH), "-Y", "sign", "-n", "git", "-f", str(KEY_PATH), str(payload)],
+ capture_output=True,
+ text=True,
+ )
+ if result.returncode != 0:
+ raise click.ClickException(f"The test signature failed:\n{result.stderr.strip()}")
+ click.echo("A test signature with the key worked.")
+
+ def _gh_env(self) -> dict[str, str]:
+ # hogli loads .env.local, which can hold an application GITHUB_TOKEN. The key must go
+ # to the engineer's own account, so gh uses its stored login instead.
+ return {key: value for key, value in os.environ.items() if key not in ("GH_TOKEN", "GITHUB_TOKEN")}
+
+ def _gh(self, *args: str) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(["gh", *args], capture_output=True, text=True, env=self._gh_env())
+
+ def _is_on_github(self, login: str) -> bool:
+ # The list of a user's signing keys is public, so this needs no extra gh scope.
+ result = self._gh("api", f"users/{login}/ssh_signing_keys", "--jq", ".[].key")
+ public_key = public_key_identity(Path(f"{KEY_PATH}.pub").read_text())
+ return public_key in {public_key_identity(line) for line in result.stdout.splitlines()}
+
+ def _add_to_github(self) -> bool:
+ title = f"Secure Enclave ({platform.node().split('.')[0]})"
+ result = self._gh("ssh-key", "add", f"{KEY_PATH}.pub", "--type", "signing", "--title", title)
+ return result.returncode == 0
+
+ def _print_manual_github_steps(self) -> None:
+ subprocess.run(["pbcopy"], input=Path(f"{KEY_PATH}.pub").read_text(), text=True)
+ subprocess.run(["open", "https://github.com/settings/ssh/new"])
+ click.echo("Add the key to GitHub in the browser page that just opened. The public key is on your clipboard.")
+ click.echo("Set the key type to Signing Key, paste the key and save.")
+ click.echo("Git config stays as it is until GitHub has the key, because pushes of unverified commits fail.")
+
+ def _wait_for_manual_github_step(self, login: str | None) -> None:
+ self._print_manual_github_steps()
+ while True:
+ click.confirm("Did you save the key on GitHub?", default=True, abort=True)
+ # Without a gh login there is no way to check, so the answer is trusted.
+ if login is None or self._is_on_github(login):
+ return
+ click.echo(f"GitHub doesn't list this signing key for {login} yet. Check that the key type is Signing Key.")
+
+ def _register_on_github(self) -> None:
+ if shutil.which("gh") is None:
+ self._wait_for_manual_github_step(None)
+ return
+ login = self._gh("api", "user", "--jq", ".login").stdout.strip()
+ if not login:
+ self._wait_for_manual_github_step(None)
+ return
+ if self._is_on_github(login):
+ click.echo(f"GitHub already has this signing key for {login}.")
+ return
+ if self._add_to_github():
+ click.echo(f"Added the signing key to GitHub for {login}.")
+ return
+ # No `gh auth refresh --scopes admin:ssh_signing_key` here: the scope would stay on the stored
+ # gh token, and any process that reads the token could then add signing keys to the account.
+ self._wait_for_manual_github_step(login)
+
+ def _restore_commands(self) -> list[list[str]]:
+ commands = []
+ for target, settings in self.previous_settings.items():
+ for setting, value in settings.items():
+ if value is None:
+ commands.append([*git_config_command(target), "--unset", setting])
+ else:
+ commands.append([*git_config_command(target), setting, value])
+ return commands
+
+ def _configure_git(self) -> None:
+ try:
+ for target in self.targets:
+ for setting, value in GIT_VALUES.items():
+ subprocess.run([*git_config_command(target), setting, value], check=True)
+ except subprocess.CalledProcessError as error:
+ for command in self._restore_commands():
+ subprocess.run(command, capture_output=True)
+ raise click.ClickException(f"Writing git config failed, so the previous settings were restored: {error}")
+
+ def _update_allowed_signers(self) -> None:
+ # Without the key in this file, `git log --show-signature` reports "No principal matched".
+ public_key_line = Path(f"{KEY_PATH}.pub").read_text()
+ for target in self.targets:
+ command = effective_config_command(target)
+ signers_file = self._git_config_get([*command, "--type=path"], "gpg.ssh.allowedSignersFile")
+ email = self._git_config_get(command, "user.email")
+ if signers_file is None or email is None:
+ continue
+ # git runs ssh-keygen inside the repository, so a relative path resolves there.
+ signers_path = Path(signers_file)
+ if target is not None and not signers_path.is_absolute():
+ signers_path = target / signers_path
+ if add_allowed_signer(signers_path, email, public_key_line):
+ click.echo(f"Added the key to your allowed signers file {signers_file}.")
+
+ def _warn_about_overrides(self) -> None:
+ if None not in self.targets:
+ return
+ if subprocess.run(["git", "rev-parse", "--git-dir"], capture_output=True).returncode != 0:
+ return
+ for setting, value in GIT_VALUES.items():
+ result = subprocess.run(
+ ["git", "config", "--show-origin", "--get", setting], capture_output=True, text=True
+ )
+ origin, _, effective = result.stdout.strip().partition("\t")
+ if effective != value:
+ click.echo(f"Warning: in this repository, {origin} sets {setting} = {effective}, not {value}.")
+
+ def _print_undo_steps(self) -> None:
+ click.echo("\nTo go back to your previous signing setup:")
+ for command in self._restore_commands():
+ click.echo(f" {shlex.join(command)}")
+ click.echo("To delete the Secure Enclave key as well:")
+ click.echo(f" sc_auth list-ctk-identities # find the hash of the `{KEY_LABEL}` key")
+ click.echo(f" sc_auth delete-ctk-identity -h <hash> && rm {KEY_PATH} {KEY_PATH}.pub")
+ if self.uses_devbox:
+ click.echo(DEVBOX_SIGNING_NOTE[1])
+ return
+ if None not in self.targets:
+ click.echo("Keep your previous signing key on GitHub while other repositories still sign with it.")
+ return
+ click.echo(
+ "Remove your previous signing key at https://github.com/settings/keys, so it can't sign verified "
+ "commits anymore. Commits you already pushed stay verified."
+ )
+
+ def run(self) -> None:
+ self._check_platform()
+ self.targets = self._choose_targets()
+ self._confirm()
+ if not KEY_PATH.exists():
+ self._create_and_install_key()
+ self._install_sign_program()
+ # Test first, so a broken key leaves git config untouched.
+ self._test_sign()
+ # GitHub before git config, so no unverified commits are made if registration stops halfway.
+ self._register_on_github()
+ self._configure_git()
+ self._update_allowed_signers()
+ self._warn_about_overrides()
+ self._print_undo_steps()
+
+
[email protected](name="git:signing-key")
+ "--global",
+ "use_global",
+ is_flag=True,
+ help="Write the git settings to your global config, so every repository signs with this key.",
+)
+ "--repo",
+ "repos",
+ multiple=True,
+ type=click.Path(exists=True, file_okay=False, path_type=Path),
+ help="A repository that signs with this key. Repeat for more. Without --repo or --global, the command asks.",
+)
+def signing_key(use_global: bool, repos: tuple[Path, ...]) -> None:
+ """Set up commit signing with a Secure Enclave key (macOS 26 or later) and register it on GitHub.
+
+ Creates a new SSH key inside the Secure Enclave, so the private key never leaves this Mac.
+ It signs without a prompt, also while the screen is locked. No GPG key is involved.
+ git uses it instead of your current signing key, for example one in 1Password or Secretive.
+ Choose where git signs with it: this repository and its worktrees, a list of repositories,
+ or every repository. SSH logins and pushes stay as they are. Devbox signing with this key
+ isn't supported yet. Run it again to reuse the key, for example to add another repository.
+ Each Mac needs its own key.
+
+ \b
+ hogli git:signing-key
+ hogli git:signing-key --repo . --repo ~/code/other-repo
+ hogli git:signing-key --global
+ """
+ SecureEnclaveSigningSetup(use_global, repos).run()
diff --git a/tools/hogli-commands/hogli_commands/tests/test_devbox.py b/tools/hogli-commands/hogli_commands/tests/test_devbox.py
index 3f291bb93139..b9399ce2f258 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_devbox.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_devbox.py
@@ -3471,13 +3471,17 @@ class TestResolveLocalSigningKey:
)
assert devbox_cli._resolve_local_signing_key() == "ecdsa-sha2-nistp256 AAAA GitHub-Commit-Signing@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")
+ @pytest.mark.parametrize("configured_name", ["id_ed25519.pub", "id_ed25519", "signing-key"])
+ def test_reads_public_file_when_value_is_path(
+ self, configured_name: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ (tmp_path / "id_ed25519").write_text("-----BEGIN OPENSSH PRIVATE KEY-----\n")
+ (tmp_path / "id_ed25519.pub").write_text("ssh-ed25519 AAAAFROMFILE user@host\n")
+ (tmp_path / "signing-key").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), ""),
+ lambda *a, **kw: subprocess.CompletedProcess(a[0], 0, str(tmp_path / configured_name), ""),
)
assert devbox_cli._resolve_local_signing_key() == "ssh-ed25519 AAAAFROMFILE user@host"
@@ -3752,7 +3756,10 @@ class TestSetupGitSigning:
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:
+ def _patch_local_config(
+ self, monkeypatch: pytest.MonkeyPatch, *, key: str | None, agent: str | None, secure_enclave: bool = False
+ ) -> None:
+ monkeypatch.setattr(devbox_cli, "signs_with_secure_enclave_key", lambda: secure_enclave)
monkeypatch.setattr(devbox_cli, "_resolve_local_signing_key", lambda: key)
monkeypatch.setattr(devbox_cli, "_resolve_local_identity_agent_for_coder", lambda: agent)
monkeypatch.setattr(
@@ -3802,9 +3809,16 @@ class TestSetupGitSigning:
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:
+ @pytest.mark.parametrize(
+ "key, secure_enclave",
+ [(None, False), ("[email protected] AAAANEW ssh:", True)],
+ ids=["unset", "secure_enclave"],
+ )
+ def test_skips_when_the_local_key_cannot_sign_on_a_devbox(
+ self, monkeypatch: pytest.MonkeyPatch, key: str | None, secure_enclave: bool
+ ) -> None:
monkeypatch.setattr(devbox_cli, "user_secret_exists", lambda name: False)
- self._patch_local_config(monkeypatch, key=None, agent=None)
+ self._patch_local_config(monkeypatch, key=key, agent=self.AGENT_SOCKET, secure_enclave=secure_enclave)
upserts: list[tuple[str, str, str | None]] = []
monkeypatch.setattr(
devbox_cli,
diff --git a/tools/hogli-commands/hogli_commands/tests/test_git_signing.py b/tools/hogli-commands/hogli_commands/tests/test_git_signing.py
new file mode 100644
index 000000000000..e79bdc6db908
--- /dev/null
+++ b/tools/hogli-commands/hogli_commands/tests/test_git_signing.py
@@ -0,0 +1,148 @@
+from __future__ import annotations
+
+import subprocess
+from pathlib import Path
+
+import pytest
+from unittest import mock
+
+import click
+from hogli_commands.git_signing import (
+ SecureEnclaveSigningSetup,
+ add_allowed_signer,
+ forwards_agent_to_devboxes,
+ pick_new_key,
+ public_key_identity,
+)
+
+
+class TestPickNewKey:
+ EXISTING = "[email protected] AAAAEXISTING"
+ NEW = "[email protected] AAAANEW"
+
+ def test_ignores_secure_enclave_keys_that_existed_before(self) -> None:
+ before = {public_key_identity(f"{self.EXISTING} ssh:")}
+ after = {self.EXISTING: Path("id_ecdsa_sk_rk"), self.NEW: Path("id_ecdsa_sk_rk_1")}
+
+ assert pick_new_key(before, after) == Path("id_ecdsa_sk_rk_1")
+
+ @pytest.mark.parametrize(
+ "after",
+ [
+ {EXISTING: Path("id_ecdsa_sk_rk")},
+ {EXISTING: Path("id_ecdsa_sk_rk"), NEW: Path("a"), f"{NEW}2": Path("b")},
+ ],
+ )
+ def test_refuses_when_the_new_key_is_ambiguous(self, after: dict[str, Path]) -> None:
+ with pytest.raises(click.ClickException):
+ pick_new_key({self.EXISTING}, after)
+
+
+class TestAddAllowedSigner:
+ KEY = "[email protected] AAAANEW"
+
+ @pytest.mark.parametrize(
+ "existing",
+ [
+ None,
+ '[email protected] namespaces="git" ssh-ed25519 AAAAOLD\n',
+ '[email protected] namespaces="git" ssh-ed25519 AAAAOLD',
+ ],
+ )
+ def test_appends_the_key_once(self, tmp_path: Path, existing: str | None) -> None:
+ signers = tmp_path / "allowed_signers"
+ if existing is not None:
+ signers.write_text(existing)
+
+ assert add_allowed_signer(signers, "[email protected]", f"{self.KEY} ssh:\n")
+ assert not add_allowed_signer(signers, "[email protected]", f"{self.KEY} ssh:\n")
+
+ lines = signers.read_text().splitlines()
+ assert lines[-1] == f'[email protected] namespaces="git" {self.KEY}'
+ assert len(lines) == (1 if existing is None else 2)
+
+
+class TestGitHubBeforeGitConfig:
+ @pytest.mark.parametrize(
+ "listed_after_confirm, configured",
+ [(True, True), (False, False)],
+ )
+ def test_git_config_waits_for_the_key_on_github(
+ self, monkeypatch: pytest.MonkeyPatch, listed_after_confirm: bool, configured: bool
+ ) -> None:
+ setup = SecureEnclaveSigningSetup(use_global=True, repos=())
+ local_steps = (
+ "_check_platform",
+ "_confirm",
+ "_install_sign_program",
+ "_test_sign",
+ "_print_manual_github_steps",
+ "_update_allowed_signers",
+ "_warn_about_overrides",
+ "_print_undo_steps",
+ )
+ for step in local_steps:
+ monkeypatch.setattr(setup, step, mock.Mock())
+ monkeypatch.setattr("hogli_commands.git_signing.KEY_PATH", mock.Mock(exists=lambda: True))
+ monkeypatch.setattr("hogli_commands.git_signing.shutil.which", lambda _: "/usr/bin/gh")
+ monkeypatch.setattr(setup, "_gh", lambda *args: subprocess.CompletedProcess(args, 0, stdout="dev\n"))
+ monkeypatch.setattr(setup, "_add_to_github", lambda: False)
+ on_github = iter([False, listed_after_confirm])
+ monkeypatch.setattr(setup, "_is_on_github", lambda login: next(on_github))
+ answers = iter([True, False])
+
+ def confirm(*args: object, **kwargs: object) -> bool:
+ if not next(answers):
+ raise click.Abort()
+ return True
+
+ monkeypatch.setattr("hogli_commands.git_signing.click.confirm", confirm)
+ configure_git = mock.Mock()
+ monkeypatch.setattr(setup, "_configure_git", configure_git)
+
+ if configured:
+ setup.run()
+ else:
+ with pytest.raises(click.Abort):
+ setup.run()
+
+ assert configure_git.called == configured
+
+
+class TestForwardsAgentToDevboxes:
+ @pytest.mark.parametrize(
+ "ssh_config, expected",
+ [
+ ("# --- START-CODER ---\nHost coder.*\n\tForwardAgent yes\n# --- END-CODER ---\n", True),
+ ("# --- START-CODER ---\nHost coder.*\n\tUser coder\n# --- END-CODER ---\n", False),
+ ("Host *\n\tForwardAgent yes\n", False),
+ (None, False),
+ ],
+ ids=["coder_block_forwards", "coder_block_without_forwarding", "forwarding_outside_coder_block", "no_config"],
+ )
+ def test_detects_agent_forwarding_in_the_coder_block(
+ self, tmp_path: Path, ssh_config: str | None, expected: bool
+ ) -> None:
+ config_path = tmp_path / "config"
+ if ssh_config is not None:
+ config_path.write_text(ssh_config)
+
+ assert forwards_agent_to_devboxes(config_path) == expected
+
+
+class TestPreviousKeyAdvice:
+ @pytest.mark.parametrize(
+ "uses_devbox, targets, tells_to_remove",
+ [(True, [None], False), (False, [Path("/repo")], False), (False, [None], True)],
+ ids=["devbox", "repo_only", "global"],
+ )
+ def test_previous_key_is_removed_only_when_nothing_signs_with_it(
+ self, capsys: pytest.CaptureFixture[str], uses_devbox: bool, targets: list[Path | None], tells_to_remove: bool
+ ) -> None:
+ setup = SecureEnclaveSigningSetup(use_global=True, repos=())
+ setup.uses_devbox = uses_devbox
+ setup.targets = targets
+
+ setup._print_undo_steps()
+
+ assert ("Remove your previous signing key" in capsys.readouterr().out) == tells_to_remove