Merge pull request #18 from kevinveenbirkenbach/fix/push-trusted-gitdir

fix(push): sign and push from a private bare repository
This commit is contained in:
Kevin Veen-Birkenbach authored and GitHub committed 2026-12-01 10:21:53 +01:00
commit 42d3d9aa6d
5 files changed
+1266 -236

No files matched your search

+93 -35
View File
@@ -22,50 +22,94 @@ from pkgmgr.cli.context import CLIContext
from pkgmgr.cli.parser import create_parser
from pkgmgr.cli.proxy import maybe_handle_proxy
_REAL_RUN = subprocess.run
GIT = shutil.which("git")
SSH_KEYGEN = shutil.which("ssh-keygen")
def git(cwd: str, *args: str) -> str:
return subprocess.run(
["git", *args], cwd=cwd, check=True, capture_output=True, text=True
return _REAL_RUN(
[GIT, *args], cwd=cwd, check=True, capture_output=True, text=True
).stdout.strip()
@unittest.skipUnless(shutil.which("ssh-keygen"), "ssh-keygen signs the commits")
class TestPushMirrorLeases(unittest.TestCase):
def keygen(path: Path) -> None:
_REAL_RUN(
[SSH_KEYGEN, "-q", "-t", "ed25519", "-N", "", "-f", str(path)],
check=True,
)
def ssh_url(path: str) -> str:
return f"t@localhost:{path}"
@unittest.skipUnless(GIT and SSH_KEYGEN, "git and ssh-keygen sign the commits")
class SignedRemotesCase(unittest.TestCase):
def setUp(self) -> None:
self._tmp = tempfile.TemporaryDirectory()
self.addCleanup(self._tmp.cleanup)
root = Path(os.path.realpath(self._tmp.name))
self.root = str(root)
key = root / "key"
subprocess.run(
["ssh-keygen", "-q", "-t", "ed25519", "-N", "", "-f", str(key)],
check=True,
)
self.key = root / "key"
keygen(self.key)
(root / "allowed").write_text(f"t@example.org {(root / 'key.pub').read_text()}")
(root / "gitconfig").write_text(
self.gitconfig = root / ".gitconfig"
self._write_gitconfig(root)
self.env = {
**{
key: value
for key, value in os.environ.items()
if key not in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE")
},
"GIT_CONFIG_GLOBAL": str(self.gitconfig),
"GIT_CONFIG_NOSYSTEM": "1",
}
for patcher in (
patch.dict(os.environ, self.env, clear=True),
patch("pkgmgr.core.git.run._passwd_home", return_value=self.root),
):
patcher.start()
self.addCleanup(patcher.stop)
self._init_remotes(root)
def _write_gitconfig(self, root: Path) -> None:
fakessh = root / "fakessh"
fakessh.write_text(
"#!/bin/sh\n"
"shift $(($# - 1))\n"
f'exec env -i PATH="$PATH" HOME={root} sh -c "$1"\n'
)
fakessh.chmod(0o755)
self.gitconfig.write_text(
"[user]\n\tname = t\n\temail = t@example.org\n"
f"\tsigningkey = {key}\n"
f"\tsigningkey = {self.key}\n"
"[gpg]\n\tformat = ssh\n"
f'[gpg "ssh"]\n\tallowedSignersFile = {root / "allowed"}\n'
"[commit]\n\tgpgsign = false\n"
"[init]\n\tdefaultBranch = main\n"
f"[core]\n\tsshCommand = {fakessh}\n"
"[ssh]\n\tvariant = simple\n"
)
env = patch.dict(
os.environ,
{"GIT_CONFIG_GLOBAL": str(root / "gitconfig"), "GIT_CONFIG_NOSYSTEM": "1"},
)
env.start()
self.addCleanup(env.stop)
def _init_remotes(self, root: Path) -> None:
self.canonical = str(root / "canonical.git")
self.mirror = str(root / "mirror.git")
self.repo = str(root / "repo")
git(self.root, "init", "-q", "--bare", self.canonical)
git(self.root, "init", "-q", "--bare", self.mirror)
git(self.root, "init", "-q", self.repo)
git(self.repo, "remote", "add", "origin", self.canonical)
git(self.repo, "remote", "set-url", "--add", "--push", "origin", self.canonical)
git(self.repo, "remote", "set-url", "--add", "--push", "origin", self.mirror)
git(self.repo, "remote", "add", "origin", ssh_url(self.canonical))
for bare in (self.canonical, self.mirror):
git(
self.repo,
"remote",
"set-url",
"--add",
"--push",
"origin",
ssh_url(bare),
)
self.init = self._commit("init")
git(self.repo, "push", "-q", self.canonical, "main")
git(self.repo, "push", "-q", self.mirror, "main")
@@ -79,6 +123,17 @@ class TestPushMirrorLeases(unittest.TestCase):
git(cwd, "commit", "-q", *flags, "-m", name)
return git(cwd, "rev-parse", "HEAD")
def _tip(self, bare: str, ref: str = "refs/heads/main") -> str:
return _REAL_RUN(
[GIT, "rev-parse", "--verify", "--quiet", ref],
cwd=bare,
check=False,
capture_output=True,
text=True,
).stdout.strip()
class TestPushMirrorLeases(SignedRemotesCase):
def _push(self, rewrite: bool = False) -> str:
with redirect_stdout(io.StringIO()) as out:
sign_unpushed(self.repo)
@@ -103,15 +158,6 @@ class TestPushMirrorLeases(unittest.TestCase):
self.assertEqual(cm.exception.code, 0)
def _tip(self, bare: str, ref: str = "refs/heads/main") -> str:
return subprocess.run(
["git", "rev-parse", "--verify", "--quiet", ref],
cwd=bare,
check=False,
capture_output=True,
text=True,
).stdout.strip()
def _assert_shipped_signed(self) -> None:
head = git(self.repo, "rev-parse", "HEAD")
self.assertEqual(self._tip(self.canonical), head)
@@ -227,7 +273,7 @@ class TestPushMirrorLeases(unittest.TestCase):
git(self.repo, "fetch", "-q", "origin")
self._commit("new")
upstream = subprocess.run(
["git", "rev-parse", "--abbrev-ref", "@{u}"],
[GIT, "rev-parse", "--abbrev-ref", "@{u}"],
cwd=self.repo,
check=False,
capture_output=True,
@@ -303,12 +349,24 @@ class TestPushMirrorLeases(unittest.TestCase):
head = git(self.repo, "rev-parse", "HEAD")
git(self.repo, "config", "diff.ignoreSubmodules", "all")
git(self.repo, "update-index", "--add", "--cacheinfo", f"160000,{head},sub")
tree = git(self.repo, "rev-parse", "HEAD^{tree}")
with self.assertRaises(PushRefusedError) as cm:
self._push()
self._push()
self.assertIn("staged changes", str(cm.exception))
self.assertEqual(git(self.repo, "rev-parse", "HEAD"), head)
self._assert_shipped_signed()
self.assertNotEqual(git(self.repo, "rev-parse", "HEAD"), head)
self.assertEqual(git(self.repo, "rev-parse", "HEAD^{tree}"), tree)
self.assertEqual(
git(
self.repo,
"diff",
"--cached",
"--name-only",
"--ignore-submodules=none",
"HEAD",
),
"sub",
)
def test_unstaged_edit_stays_out_of_the_signed_head(self) -> None:
self._commit("feature")
@@ -363,7 +421,7 @@ class TestPushMirrorLeases(unittest.TestCase):
self.assertFalse(marker.exists())
def test_remote_named_like_an_option_is_pushed(self) -> None:
git(self.repo, "config", "remote.-r.url", self.canonical)
git(self.repo, "config", "remote.-r.url", ssh_url(self.canonical))
git(self.repo, "config", "remote.-r.fetch", "+refs/heads/*:refs/remotes/-r/*")
git(self.repo, "config", "branch.main.pushRemote", "-r")
git(self.repo, "fetch", "-q", "--", "-r")
@@ -0,0 +1,364 @@
from __future__ import annotations
import io
import json
import os
import shutil
from contextlib import redirect_stdout
from pathlib import Path
from unittest.mock import patch
from pkgmgr.actions.repository import push as push_module
from pkgmgr.actions.repository.push import (
PushRefusedError,
push_branch,
sign_unpushed,
)
from tests.integration.test_push_mirror_leases import (
_REAL_RUN,
GIT,
SignedRemotesCase,
git,
keygen,
)
def _push_sids(events: list[dict]) -> set[str]:
return {
e["sid"] for e in events if e["event"] == "cmd_name" and e.get("name") == "push"
}
def _repo_param(event: dict, prefixes: tuple[str, ...]) -> bool:
return (
event["event"] == "def_param"
and event.get("scope") in ("local", "worktree")
and event["param"].startswith(prefixes)
)
class TestPushTrustedGitdir(SignedRemotesCase):
def setUp(self) -> None:
super().setUp()
self.marker = Path(self.root, "marker")
self.trace = Path(self.root, "trace.json")
def _push(self) -> str:
with redirect_stdout(io.StringIO()) as out:
sign_unpushed(self.repo)
push_branch(self.repo, [], sign=True)
return out.getvalue()
def _plant(self) -> str:
return f"touch {self.marker}"
def _hook(self, directory: Path, *names: str) -> None:
directory.mkdir(parents=True, exist_ok=True)
for name in names:
hook = directory / name
hook.write_text(f"#!/bin/sh\n{self._plant()}\n")
hook.chmod(0o755)
def _canonical_signature(self) -> str:
return _REAL_RUN(
[GIT, "log", "-1", "--format=%G?", "refs/heads/main"],
cwd=self.canonical,
env={**self.env, "GIT_NO_REPLACE_OBJECTS": "1"},
check=True,
capture_output=True,
text=True,
).stdout.strip()
def _assert_landed(self) -> None:
head = git(self.repo, "rev-parse", "HEAD")
self.assertEqual(self._tip(self.canonical), head)
self.assertEqual(self._tip(self.mirror), head)
self.assertEqual(self._canonical_signature(), "G")
def _assert_nothing_ran(self) -> None:
self.assertFalse(self.marker.exists(), "a planted program ran")
def _trace_repo_config(self, prefixes: tuple[str, ...]) -> None:
with self.gitconfig.open("a") as fh:
fh.write(
f"[trace2]\n\teventTarget = {self.trace}\n"
f"\tconfigParams = {','.join(p + '*' for p in prefixes)}\n"
)
def _repo_config_seen_by_push(self, prefixes: tuple[str, ...]) -> list[str]:
events = [json.loads(line) for line in self.trace.read_text().splitlines()]
pushes = _push_sids(events)
self.assertTrue(pushes, "no push was traced")
return [
f"{e['param']}={e['value']}"
for e in events
if e["sid"] in pushes and _repo_param(e, prefixes)
]
def _push_with_config_planted_after_check(self, check: int) -> int:
self._commit("feature")
real = push_module.local_config
calls: list[str] = []
def check_then_plant(path: str, pattern: str) -> list[str]:
found = real(path, pattern)
calls.append(path)
if len(calls) == check:
git(self.repo, "config", "core.sshCommand", f"{self._plant()}; false #")
git(self.repo, "config", "core.fsmonitor", self._plant())
return found
with patch.object(push_module, "local_config", check_then_plant):
self._push()
return len(calls)
def test_vector1_repository_hooks_never_run(self) -> None:
hooks = (
"pre-push",
"reference-transaction",
"post-commit",
"post-rewrite",
"post-index-change",
)
for name, hook_dir in (
("hooks", Path(self.repo, ".git", "hooks")),
("hooks-path", Path(self.root, "planted-hooks")),
):
with self.subTest(hook_dir=str(hook_dir)):
self._commit(name)
self._hook(hook_dir, *hooks)
if name == "hooks-path":
git(self.repo, "config", "core.hooksPath", str(hook_dir))
self._push()
self._assert_nothing_ran()
self._assert_landed()
shutil.rmtree(hook_dir)
def test_vector2_filter_driver_never_runs(self) -> None:
Path(self.repo, ".gitattributes").write_text("*.txt filter=probe\n")
git(self.repo, "config", "filter.probe.clean", f"{self._plant()}; cat")
git(self.repo, "config", "filter.probe.smudge", "cat")
git(self.repo, "add", ".gitattributes")
self._commit("feature")
stamp = Path(self.repo, "feature.txt").stat().st_mtime + 10
os.utime(Path(self.repo, "feature.txt"), (stamp, stamp))
self.marker.unlink()
self._push()
self._assert_nothing_ran()
self._assert_landed()
def test_vector3_core_worktree_elsewhere_is_never_read(self) -> None:
self._commit("feature")
elsewhere = Path(self.root, "elsewhere")
elsewhere.mkdir()
(elsewhere / ".gitattributes").write_text("* filter=probe\n")
(elsewhere / "feature.txt").write_text("feature")
git(self.repo, "config", "filter.probe.clean", f"{self._plant()}; cat")
git(self.repo, "config", "core.worktree", str(elsewhere))
self._push()
self._assert_nothing_ran()
self._assert_landed()
def test_vector4_repository_credential_config_never_reaches_the_push(
self,
) -> None:
self._trace_repo_config(("credential.",))
for key, value in (
("credential.protectProtocol", "false"),
("credential.username", "planted"),
("credential.useHttpPath", "true"),
("credential.https://example.org.username", "planted"),
):
git(self.repo, "config", key, value)
self._commit("feature")
self._push()
self.assertEqual(self._repo_config_seen_by_push(("credential.",)), [])
self._assert_landed()
def test_vector5_bundle_uri_is_never_fetched(self) -> None:
other = os.path.join(self.root, "other")
git(self.root, "init", "-q", other)
self._commit("planted", other)
bundle = os.path.join(self.root, "planted.bundle")
git(other, "bundle", "create", bundle, "main")
git(self.repo, "config", "fetch.bundleURI", bundle)
git(self.repo, "config", "transfer.bundleURI", "true")
self._commit("feature")
self._push()
self.assertEqual(git(self.repo, "for-each-ref", "refs/bundles/"), "")
self._assert_landed()
def test_vector6_repository_http_config_never_reaches_the_push(self) -> None:
self._trace_repo_config(("http.",))
for key, value in (
("http.curloptResolve", "localhost:443:127.0.0.2"),
("http.delegation", "always"),
("http.proxySSLCert", f"{self.root}/planted.pem"),
("http.proxySSLKey", f"{self.root}/planted.key"),
("http.proxySSLCAInfo", f"{self.root}/planted.ca"),
):
git(self.repo, "config", key, value)
self._commit("feature")
self._push()
self.assertEqual(self._repo_config_seen_by_push(("http.",)), [])
self._assert_landed()
def test_vector7_merge_driver_never_runs(self) -> None:
Path(self.repo, ".gitattributes").write_text("* merge=probe\n")
git(self.repo, "add", ".gitattributes")
git(self.repo, "config", "merge.probe.driver", f"{self._plant()}; false")
git(self.repo, "config", "merge.probe.name", "probe")
self._commit("feature")
self._push()
self._assert_nothing_ran()
self._assert_landed()
def test_vector8_submodule_configs_are_never_read(self) -> None:
upstream = os.path.join(self.root, "sub-upstream")
git(self.root, "init", "-q", upstream)
self._commit("sub", upstream)
git(
self.repo,
"-c",
"protocol.file.allow=always",
"submodule",
"add",
"-q",
upstream,
"sub",
)
git(self.repo, "commit", "-q", "-m", "add sub")
modules = Path(self.repo, ".git", "modules", "sub")
self._hook(
modules / "hooks",
"pre-push",
"reference-transaction",
"post-commit",
"post-checkout",
"pre-commit",
)
git(str(modules), "config", "filter.probe.clean", f"{self._plant()}; cat")
git(str(modules), "config", "core.fsmonitor", self._plant())
Path(self.repo, "sub", ".gitattributes").write_text("* filter=probe\n")
stamp = Path(self.repo, "sub", "sub.txt").stat().st_mtime + 10
os.utime(Path(self.repo, "sub", "sub.txt"), (stamp, stamp))
for key, value in (
("submodule.recurse", "true"),
("push.recurseSubmodules", "on-demand"),
("fetch.recurseSubmodules", "yes"),
("diff.ignoreSubmodules", "none"),
("status.submoduleSummary", "true"),
("diff.submodule", "diff"),
):
git(self.repo, "config", key, value)
self._commit("feature")
self._push()
self._assert_nothing_ran()
self._assert_landed()
def test_vector9_replace_ref_never_fakes_a_good_signature(self) -> None:
unsigned = self._commit("feature")
tree = git(self.repo, "rev-parse", "HEAD^{tree}")
forged = git(
self.repo, "commit-tree", tree, "-p", self.init, "-S", "-m", "forged"
)
git(self.repo, "replace", unsigned, forged)
self.assertEqual(git(self.repo, "log", "-1", "--format=%G?", unsigned), "G")
self._push()
self.assertNotEqual(self._tip(self.canonical), unsigned)
self._assert_landed()
def test_vector9_repository_allowed_signers_never_fake_a_good_signature(
self,
) -> None:
planted_key = Path(self.root, "planted-key")
keygen(planted_key)
allowed = Path(self.root, "planted-allowed")
allowed.write_text(f"t@example.org {Path(f'{planted_key}.pub').read_text()}")
git(self.repo, "config", "gpg.ssh.allowedSignersFile", str(allowed))
git(self.repo, "config", "user.signingKey", str(planted_key))
Path(self.repo, "feature.txt").write_text("feature")
git(self.repo, "add", "feature.txt")
git(self.repo, "commit", "-q", "-S", "-m", "feature")
planted = git(self.repo, "rev-parse", "HEAD")
self.assertEqual(git(self.repo, "log", "-1", "--format=%G?"), "G")
self._push()
self.assertNotEqual(self._tip(self.canonical), planted)
self._assert_landed()
def test_vector10_config_planted_after_the_sign_check_is_refused(self) -> None:
with self.assertRaises(PushRefusedError) as cm:
self._push_with_config_planted_after_check(1)
self.assertIn("core.sshcommand", str(cm.exception))
self._assert_nothing_ran()
self.assertEqual(self._tip(self.canonical), self.init)
self.assertEqual(self._tip(self.mirror), self.init)
def test_vector10_config_planted_after_the_push_check_never_runs(self) -> None:
checks = self._push_with_config_planted_after_check(2)
self.assertGreaterEqual(checks, 2, "the config was never planted")
self._assert_nothing_ran()
self._assert_landed()
def test_vector10_branch_moved_while_signing_is_kept(self) -> None:
self._commit("feature")
moved: list[str] = []
def race(cmd, *args, **kwargs):
if not moved and ("commit-tree" in cmd or "--amend" in cmd):
moved.append(self._commit("racing"))
return _REAL_RUN(cmd, *args, **kwargs)
with (
patch("subprocess.run", side_effect=race),
self.assertRaises(PushRefusedError),
):
self._push()
self.assertEqual(git(self.repo, "rev-parse", "HEAD"), moved[0])
self.assertEqual(self._tip(self.canonical), self.init)
self.assertEqual(self._tip(self.mirror), self.init)
def test_local_and_foreign_push_urls_are_refused(self) -> None:
self._commit("feature")
for url in (
self.mirror,
f"file://{self.mirror}",
f"ext::sh -c touch% {self.marker}",
"t@-oProxyCommand=x:path",
"ssh://-oProxyCommand=x/path",
"http://localhost/x.git",
):
with self.subTest(url=url):
git(self.repo, "config", "--unset-all", "remote.origin.pushurl")
git(self.repo, "config", "--add", "remote.origin.pushurl", url)
with (
self.assertRaises(PushRefusedError),
redirect_stdout(io.StringIO()),
):
push_branch(self.repo, [], sign=False)
self.assertEqual(self._tip(self.mirror), self.init)
@@ -0,0 +1,118 @@
from __future__ import annotations
import io
import os
import shutil
import subprocess
import tempfile
import unittest
from contextlib import redirect_stdout
from unittest.mock import MagicMock, patch
from pkgmgr.actions.repository import _trusted
from pkgmgr.actions.repository import push as push_module
from pkgmgr.core.git import GitRunError
GIT = shutil.which("git")
CREDENTIAL = "pw-value"
OID = "a" * 40
def _target(branch: str) -> _trusted.Target:
return _trusted.Target(
repo_dir="/nonexistent/repo",
tdir="/nonexistent/tdir",
branch=branch,
head=OID,
remote="origin",
fetch_url="t@localhost:canonical.git",
push_urls=("t@localhost:canonical.git",),
)
class TestTrustedReviewFixes(unittest.TestCase):
@unittest.skipUnless(GIT, "git reads the config")
def test_config_value_with_a_newline_stays_one_value(self) -> None:
value = "https://a.example/x\nhttps://b.example/y"
env = {
key: val
for key, val in os.environ.items()
if key not in ("GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE")
}
with tempfile.TemporaryDirectory() as repo:
subprocess.run([GIT, "init", "-q", repo], check=True, env=env)
subprocess.run(
[GIT, "config", "--add", "remote.origin.pushurl", value],
cwd=repo,
check=True,
env=env,
)
values = _trusted._config_all(repo, "remote.origin.pushurl")
self.assertEqual(values, [value])
def test_file_url_percent_encodes_the_path(self) -> None:
self.assertEqual(
_trusted.file_url("/srv/repo%20name"), "file:///srv/repo%2520name"
)
def test_failed_trusted_call_redacts_url_userinfo(self) -> None:
failed = subprocess.CompletedProcess([], 128, b"", b"fatal: refused")
url = f"https://user:{CREDENTIAL}@example.org/x.git"
with (
patch.object(_trusted.subprocess, "run", return_value=failed),
self.assertRaises(GitRunError) as cm,
):
_trusted.tgit("/nonexistent/tdir", "ls-remote", "--", url)
self.assertNotIn(CREDENTIAL, str(cm.exception))
self.assertIn("https://***@example.org/x.git", str(cm.exception))
def test_failed_mirror_line_redacts_url_userinfo(self) -> None:
plan = push_module._Push((), (), False, False, None)
url = f"https://user:{CREDENTIAL}@example.org/mirror.git"
refused = _trusted.PushRefusedError("lease failed")
with (
patch.object(push_module, "_lease", side_effect=refused),
redirect_stdout(io.StringIO()) as out,
):
pushed = push_module._push_url(_target("main"), plan, 1, url)
self.assertFalse(pushed)
self.assertNotIn(CREDENTIAL, out.getvalue())
def test_ls_remote_line_without_a_tab_lists_no_ref(self) -> None:
with patch.object(
_trusted, "tgit", return_value=f"{OID} refs/heads/main"
) as fake:
tips = _trusted.fetch_heads(
_target("main"), "t@localhost:x.git", ["main"], "refs/x"
)
self.assertEqual(tips, {})
fake.assert_called_once()
def test_track_uses_the_validated_branch(self) -> None:
run = MagicMock(return_value="")
target = _target("feature")
with (
patch.object(push_module, "run", run),
patch.object(push_module, "try_git", return_value=None) as probe,
):
push_module._track(target)
probe.assert_called_once_with(
target.repo_dir, "rev-parse", "--abbrev-ref", "feature@{upstream}"
)
self.assertEqual(
run.call_args_list[-1].args[0],
["branch", "--set-upstream-to=origin/feature", "feature"],
)
if __name__ == "__main__":
unittest.main()