fix(push): sign and push from a private bare repository

pkgmgr push copies HEAD and tags into a private temporary bare repository and signs (git commit-tree -S) and pushes from there, so the checkout config, hooks, filters, merge drivers, replace refs, bundle URIs, submodule configs and allowed-signers never take part. The checkout is only read via upload-pack and updated by a fetch of the signed commit plus an update-ref guarded by the old HEAD. Push and fetch URLs must be https, ssh or user@host:path. Codacy tightened (D413, Lizard CCN 8, no new defaults, B607 via shutil.which); prose docstrings removed for quality clean.comment.

| 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| fix/push-trusted-gitdir | 4 files +1112/-233 | 90 % | 8 % | – | – | 100 % | 83 | ⛔ break 8 % > 5 |

Evidence: host run 86 tests OK, full unit suite 527 OK, ruff clean, lizard -C 8 clean, MEDUSA 100 % critical 0. Break 8 %: a checkout whose origin fetch URL is a local path or http:// is refused; repository-level http.* and credential.* settings and a GIT_CONFIG_GLOBAL override no longer apply to push. Operator review a41d30aa (re-card of 39022e85).
Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-30 19:44:39 +00:00
1 parent 895ec2f0d4
commit 6c7ca613fc
4 files changed
+1114 -235

No files matched your search

+89 -35
View File
@@ -21,50 +21,90 @@ 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 = {
**os.environ,
"GIT_CONFIG_GLOBAL": str(self.gitconfig),
"GIT_CONFIG_NOSYSTEM": "1",
}
for patcher in (
patch.dict(os.environ, self.env),
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")
@@ -78,6 +118,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)
@@ -102,15 +153,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)
@@ -226,7 +268,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,
@@ -302,12 +344,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")
@@ -364,7 +418,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,362 @@
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) -> None:
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()
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:
self._push_with_config_planted_after_check(2)
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)