fix(push): redact URL credentials and close the review findings of PR 18
quality clean.default-value: trusted_repo passes --object-format only when the checkout sets extensions.objectFormat; _old_tip refuses an unsigned HEAD only when HEAD is in the pushed range, without a .get fallback. CodeRabbit: _config_all reads git config -z --get-all and splits on NUL, so one pushurl value with a newline stays one value and url_allowed rejects it; file_url uses Path.as_uri; redact_urls replaces URL userinfo with *** in the GitRunError text of _tgit_run and in every push.py refusal, failure, preview and status line while the argv given to git is unchanged; fetch_heads splits ls-remote records at the TAB; _track sets and reads the upstream of the validated branch. Tests: the mirror fixture drops GIT_DIR, GIT_WORK_TREE and GIT_INDEX_FILE, the planted-after-check test asserts the second check ran, and test_push_trusted_review.py covers each fix. | 🌿 Branch | 📊 Diff stat | 🎯 Fix | 💥 Break | 💸 Tokens | ⏱️ Velocity | 🛡️ Security | 🏆 Score | Gate | | --- | --- | --- | --- | --- | --- | --- | --- | --- | | fix/push-trusted-gitdir | 5 files +173/-22 | 90 % | 5 % | – | – | 100 % | 86 | ✅ 90/5, tokens and velocity <= 100, security 100 % | Evidence: tests/unit + tests/integration with PYTHONPATH=src 860 passed; the 33 fake-SSH push fixture tests fail identically on the previous HEAD in the agent sandbox and pass in PR CI, so PR CI is the proof for the push paths; 2 known gpg-in-sandbox failures in test_publish_integration. quality check --staged 0 findings, ruff clean, MEDUSA 100 %, critical 0. Hub review f31edb8114253cb6. Refs https://github.com/kevinveenbirkenbach/package-manager/pull/18 Created-with: https://s.veen.world/skills Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6c7ca613fc
commit
db7532f9b4
5 files changed
+170
-19
No files matched your search
@@ -8,6 +8,7 @@ import tempfile
|
|||||||
from collections.abc import Iterator
|
from collections.abc import Iterator
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
from urllib.parse import urlsplit
|
from urllib.parse import urlsplit
|
||||||
|
|
||||||
from pkgmgr.core.git import GitRunError, run
|
from pkgmgr.core.git import GitRunError, run
|
||||||
@@ -17,6 +18,7 @@ PUSH_SCHEMES = ("https", "ssh")
|
|||||||
_SCP_URL = re.compile(
|
_SCP_URL = re.compile(
|
||||||
r"[A-Za-z0-9_][A-Za-z0-9._-]*@(?:[A-Za-z0-9][A-Za-z0-9.-]*|\[[0-9A-Fa-f:.]+\]):\S+"
|
r"[A-Za-z0-9_][A-Za-z0-9._-]*@(?:[A-Za-z0-9][A-Za-z0-9.-]*|\[[0-9A-Fa-f:.]+\]):\S+"
|
||||||
)
|
)
|
||||||
|
_URL_USERINFO = re.compile(r"(?<=://)[^/?#\s]*@")
|
||||||
TRUSTED_FLAGS = (
|
TRUSTED_FLAGS = (
|
||||||
*SCAN_FLAGS,
|
*SCAN_FLAGS,
|
||||||
"-c",
|
"-c",
|
||||||
@@ -78,12 +80,25 @@ def try_git(repo_dir: str, *args: str) -> str | None:
|
|||||||
|
|
||||||
|
|
||||||
def _config_all(repo_dir: str, key: str) -> list[str]:
|
def _config_all(repo_dir: str, key: str) -> list[str]:
|
||||||
values = try_git(repo_dir, "config", "--get-all", key)
|
values = try_git(repo_dir, "config", "-z", "--get-all", key)
|
||||||
return values.splitlines() if values else []
|
return values.split("\0")[:-1] if values else []
|
||||||
|
|
||||||
|
|
||||||
def file_url(path: str) -> str:
|
def file_url(path: str) -> str:
|
||||||
return "file://" + os.path.abspath(path)
|
return Path(os.path.abspath(path)).as_uri()
|
||||||
|
|
||||||
|
|
||||||
|
def redact_urls(text: str) -> str:
|
||||||
|
"""
|
||||||
|
Args:
|
||||||
|
text: a diagnostic that may name remote URLs.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The text with the userinfo of every scheme URL, which may carry a
|
||||||
|
password or token, replaced by `***`.
|
||||||
|
|
||||||
|
"""
|
||||||
|
return _URL_USERINFO.sub("***@", text)
|
||||||
|
|
||||||
|
|
||||||
def trusted_env(extra: dict[str, str]) -> dict[str, str]:
|
def trusted_env(extra: dict[str, str]) -> dict[str, str]:
|
||||||
@@ -134,10 +149,12 @@ def _tgit_run(tdir: str, args: tuple[str, ...], local: bool) -> bytes:
|
|||||||
)
|
)
|
||||||
if result.returncode != 0:
|
if result.returncode != 0:
|
||||||
raise GitRunError(
|
raise GitRunError(
|
||||||
|
redact_urls(
|
||||||
f"Git command failed in {tdir!r}: {' '.join(cmd)}\n"
|
f"Git command failed in {tdir!r}: {' '.join(cmd)}\n"
|
||||||
f"Exit code: {result.returncode}\n"
|
f"Exit code: {result.returncode}\n"
|
||||||
f"STDERR:\n{os.fsdecode(result.stderr)}"
|
f"STDERR:\n{os.fsdecode(result.stderr)}"
|
||||||
)
|
)
|
||||||
|
)
|
||||||
return result.stdout
|
return result.stdout
|
||||||
|
|
||||||
|
|
||||||
@@ -171,7 +188,7 @@ def trusted_repo(repo_dir: str) -> Iterator[str]:
|
|||||||
"--quiet",
|
"--quiet",
|
||||||
"--bare",
|
"--bare",
|
||||||
"--template=",
|
"--template=",
|
||||||
f"--object-format={object_format or 'sha1'}",
|
*((f"--object-format={object_format}",) if object_format else ()),
|
||||||
)
|
)
|
||||||
yield tdir
|
yield tdir
|
||||||
finally:
|
finally:
|
||||||
@@ -246,8 +263,9 @@ def open_target(repo_dir: str, tdir: str) -> Target:
|
|||||||
for url in (urls[0], *push_urls):
|
for url in (urls[0], *push_urls):
|
||||||
if not url_allowed(url):
|
if not url_allowed(url):
|
||||||
raise PushRefusedError(
|
raise PushRefusedError(
|
||||||
f"{repo_dir}: remote {remote} URL {url!r} is not https, ssh or "
|
f"{repo_dir}: remote {remote} URL {redact_urls(repr(url))} is not "
|
||||||
"user@host:path; local paths and other transports are not pushed to"
|
"https, ssh or user@host:path; local paths and other transports are "
|
||||||
|
"not pushed to"
|
||||||
)
|
)
|
||||||
return Target(repo_dir, tdir, branch, head, remote, urls[0], push_urls)
|
return Target(repo_dir, tdir, branch, head, remote, urls[0], push_urls)
|
||||||
|
|
||||||
@@ -272,7 +290,7 @@ def fetch_heads(
|
|||||||
) -> dict[str, str]:
|
) -> dict[str, str]:
|
||||||
wanted = [f"refs/heads/{name}" for name in dict.fromkeys(names)]
|
wanted = [f"refs/heads/{name}" for name in dict.fromkeys(names)]
|
||||||
listed = tgit(target.tdir, "ls-remote", "--", url, *wanted).splitlines()
|
listed = tgit(target.tdir, "ls-remote", "--", url, *wanted).splitlines()
|
||||||
present = {ln.split()[1] for ln in listed if len(ln.split()) == 2} & set(wanted)
|
present = {ln.partition("\t")[2] for ln in listed} & set(wanted)
|
||||||
if not present:
|
if not present:
|
||||||
return {}
|
return {}
|
||||||
tgit(
|
tgit(
|
||||||
|
|||||||
@@ -22,6 +22,7 @@ from pkgmgr.actions.repository._trusted import (
|
|||||||
fetch_heads,
|
fetch_heads,
|
||||||
file_url,
|
file_url,
|
||||||
open_target,
|
open_target,
|
||||||
|
redact_urls,
|
||||||
tgit,
|
tgit,
|
||||||
tgit_bytes,
|
tgit_bytes,
|
||||||
trusted_env,
|
trusted_env,
|
||||||
@@ -230,7 +231,8 @@ def _refuse_lost(target: Target, url: str, sha: str, keep: tuple[str, ...]) -> N
|
|||||||
lost = plus if lost is None else lost & plus
|
lost = plus if lost is None else lost & plus
|
||||||
if lost:
|
if lost:
|
||||||
raise PushRefusedError(
|
raise PushRefusedError(
|
||||||
f"{url}: {len(lost)} commit(s) exist only there, not overwritten: "
|
f"{redact_urls(url)}: {len(lost)} commit(s) exist only there, "
|
||||||
|
"not overwritten: "
|
||||||
f"{' '.join(s[:10] for s in sorted(lost))}; "
|
f"{' '.join(s[:10] for s in sorted(lost))}; "
|
||||||
"pass --rewrite for a deliberate history rewrite"
|
"pass --rewrite for a deliberate history rewrite"
|
||||||
)
|
)
|
||||||
@@ -273,7 +275,9 @@ def push_branch(
|
|||||||
if not _push_url(target, plan, index, url):
|
if not _push_url(target, plan, index, url):
|
||||||
failed.append(url)
|
failed.append(url)
|
||||||
if failed:
|
if failed:
|
||||||
raise PushRefusedError(f"{repo_dir}: push failed for {', '.join(failed)}")
|
raise PushRefusedError(
|
||||||
|
f"{repo_dir}: push failed for {redact_urls(', '.join(failed))}"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def _old_tip(target: Target, sign: bool, preview: bool) -> str | None:
|
def _old_tip(target: Target, sign: bool, preview: bool) -> str | None:
|
||||||
@@ -293,7 +297,7 @@ def _old_tip(target: Target, sign: bool, preview: bool) -> str | None:
|
|||||||
).get(target.branch)
|
).get(target.branch)
|
||||||
old_tip, candidates = bases(target)
|
old_tip, candidates = bases(target)
|
||||||
_base, signatures = unpushed_signatures(target, candidates)
|
_base, signatures = unpushed_signatures(target, candidates)
|
||||||
if not preview and signatures.get(target.head, "G") != "G":
|
if not preview and target.head in signatures and signatures[target.head] != "G":
|
||||||
raise PushRefusedError(
|
raise PushRefusedError(
|
||||||
f"{target.repo_dir}: HEAD {target.head[:10]} is unsigned; "
|
f"{target.repo_dir}: HEAD {target.head[:10]} is unsigned; "
|
||||||
"run `pkgmgr push` to sign it"
|
"run `pkgmgr push` to sign it"
|
||||||
@@ -351,16 +355,16 @@ def _push_url(target: Target, plan: _Push, index: int, url: str) -> bool:
|
|||||||
if plan.preview:
|
if plan.preview:
|
||||||
print(
|
print(
|
||||||
f"[PREVIEW] Would run in a temporary copy of {target.repo_dir!r}: "
|
f"[PREVIEW] Would run in a temporary copy of {target.repo_dir!r}: "
|
||||||
f"git {' '.join(cmd)}"
|
f"git {redact_urls(' '.join(cmd))}"
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
tgit(target.tdir, *cmd)
|
tgit(target.tdir, *cmd)
|
||||||
except (GitRunError, PushRefusedError) as exc:
|
except (GitRunError, PushRefusedError) as exc:
|
||||||
if canonical:
|
if canonical:
|
||||||
raise
|
raise
|
||||||
print(f"[push] FAILED {url}\n{exc}")
|
print(f"[push] FAILED {redact_urls(url)}\n{exc}")
|
||||||
return False
|
return False
|
||||||
print(f"[push] {url} <- {target.branch} {target.head[:10]}")
|
print(f"[push] {redact_urls(url)} <- {target.branch} {target.head[:10]}")
|
||||||
if canonical and not plan.preview:
|
if canonical and not plan.preview:
|
||||||
_track(target)
|
_track(target)
|
||||||
return True
|
return True
|
||||||
@@ -369,9 +373,14 @@ def _push_url(target: Target, plan: _Push, index: int, url: str) -> bool:
|
|||||||
def _track(target: Target) -> None:
|
def _track(target: Target) -> None:
|
||||||
tracking = f"refs/remotes/{target.remote}/{target.branch}"
|
tracking = f"refs/remotes/{target.remote}/{target.branch}"
|
||||||
run(["update-ref", tracking, target.head], cwd=target.repo_dir, scan=True)
|
run(["update-ref", tracking, target.head], cwd=target.repo_dir, scan=True)
|
||||||
if not try_git(target.repo_dir, "rev-parse", "--abbrev-ref", "@{u}"):
|
upstream = f"{target.branch}@{{upstream}}"
|
||||||
|
if not try_git(target.repo_dir, "rev-parse", "--abbrev-ref", upstream):
|
||||||
run(
|
run(
|
||||||
["branch", f"--set-upstream-to={target.remote}/{target.branch}"],
|
[
|
||||||
|
"branch",
|
||||||
|
f"--set-upstream-to={target.remote}/{target.branch}",
|
||||||
|
target.branch,
|
||||||
|
],
|
||||||
cwd=target.repo_dir,
|
cwd=target.repo_dir,
|
||||||
scan=True,
|
scan=True,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -56,12 +56,16 @@ class SignedRemotesCase(unittest.TestCase):
|
|||||||
self.gitconfig = root / ".gitconfig"
|
self.gitconfig = root / ".gitconfig"
|
||||||
self._write_gitconfig(root)
|
self._write_gitconfig(root)
|
||||||
self.env = {
|
self.env = {
|
||||||
**os.environ,
|
**{
|
||||||
|
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_GLOBAL": str(self.gitconfig),
|
||||||
"GIT_CONFIG_NOSYSTEM": "1",
|
"GIT_CONFIG_NOSYSTEM": "1",
|
||||||
}
|
}
|
||||||
for patcher in (
|
for patcher in (
|
||||||
patch.dict(os.environ, self.env),
|
patch.dict(os.environ, self.env, clear=True),
|
||||||
patch("pkgmgr.core.git.run._passwd_home", return_value=self.root),
|
patch("pkgmgr.core.git.run._passwd_home", return_value=self.root),
|
||||||
):
|
):
|
||||||
patcher.start()
|
patcher.start()
|
||||||
|
|||||||
@@ -95,7 +95,7 @@ class TestPushTrustedGitdir(SignedRemotesCase):
|
|||||||
if e["sid"] in pushes and _repo_param(e, prefixes)
|
if e["sid"] in pushes and _repo_param(e, prefixes)
|
||||||
]
|
]
|
||||||
|
|
||||||
def _push_with_config_planted_after_check(self, check: int) -> None:
|
def _push_with_config_planted_after_check(self, check: int) -> int:
|
||||||
self._commit("feature")
|
self._commit("feature")
|
||||||
real = push_module.local_config
|
real = push_module.local_config
|
||||||
calls: list[str] = []
|
calls: list[str] = []
|
||||||
@@ -110,6 +110,7 @@ class TestPushTrustedGitdir(SignedRemotesCase):
|
|||||||
|
|
||||||
with patch.object(push_module, "local_config", check_then_plant):
|
with patch.object(push_module, "local_config", check_then_plant):
|
||||||
self._push()
|
self._push()
|
||||||
|
return len(calls)
|
||||||
|
|
||||||
def test_vector1_repository_hooks_never_run(self) -> None:
|
def test_vector1_repository_hooks_never_run(self) -> None:
|
||||||
hooks = (
|
hooks = (
|
||||||
@@ -315,8 +316,9 @@ class TestPushTrustedGitdir(SignedRemotesCase):
|
|||||||
self.assertEqual(self._tip(self.mirror), self.init)
|
self.assertEqual(self._tip(self.mirror), self.init)
|
||||||
|
|
||||||
def test_vector10_config_planted_after_the_push_check_never_runs(self) -> None:
|
def test_vector10_config_planted_after_the_push_check_never_runs(self) -> None:
|
||||||
self._push_with_config_planted_after_check(2)
|
checks = self._push_with_config_planted_after_check(2)
|
||||||
|
|
||||||
|
self.assertGreaterEqual(checks, 2, "the config was never planted")
|
||||||
self._assert_nothing_ran()
|
self._assert_nothing_ran()
|
||||||
self._assert_landed()
|
self._assert_landed()
|
||||||
|
|
||||||
|
|||||||
@@ -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()
|
||||||
Reference in new issue
Block a user