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

@@ -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)