diff --git a/src/pkgmgr/actions/repository/_trusted.py b/src/pkgmgr/actions/repository/_trusted.py new file mode 100644 index 0000000..90330f0 --- /dev/null +++ b/src/pkgmgr/actions/repository/_trusted.py @@ -0,0 +1,374 @@ +from __future__ import annotations + +import os +import re +import shutil +import subprocess +import tempfile +from collections.abc import Iterator +from contextlib import contextmanager +from dataclasses import dataclass +from urllib.parse import urlsplit + +from pkgmgr.core.git import GitRunError, run +from pkgmgr.core.git.run import DEFAULT_CONFIG, SCAN_FLAGS, _scan_env + +PUSH_SCHEMES = ("https", "ssh") +_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+" +) +TRUSTED_FLAGS = ( + *SCAN_FLAGS, + "-c", + "protocol.allow=never", + *( + arg + for scheme in PUSH_SCHEMES + for arg in ("-c", f"protocol.{scheme}.allow=always") + ), + "-c", + "transfer.bundleURI=false", + "-c", + "submodule.recurse=false", + "-c", + "fetch.recurseSubmodules=false", +) +_FILE_PROTOCOL = ("-c", "protocol.file.allow=always") +CHECKOUT_FETCH_FLAGS = ( + "-c", + "protocol.allow=never", + *_FILE_PROTOCOL, + "-c", + "fetch.bundleURI=", + "-c", + "transfer.bundleURI=false", + "-c", + "core.alternateRefsCommand=true", + "-c", + "submodule.recurse=false", + "-c", + "fetch.recurseSubmodules=false", +) + + +class PushRefusedError(RuntimeError): + pass + + +@dataclass(frozen=True) +class Target: + repo_dir: str + tdir: str + branch: str + head: str + remote: str + fetch_url: str + push_urls: tuple[str, ...] + + @property + def branch_ref(self) -> str: + return f"refs/heads/{self.branch}" + + +def try_git(repo_dir: str, *args: str) -> str | None: + try: + return run(list(args), cwd=repo_dir, scan=True) + except GitRunError: + return None + + +def _config_all(repo_dir: str, key: str) -> list[str]: + values = try_git(repo_dir, "config", "--get-all", key) + return values.splitlines() if values else [] + + +def file_url(path: str) -> str: + return "file://" + os.path.abspath(path) + + +def trusted_env(extra: dict[str, str]) -> dict[str, str]: + """ + Args: + extra: variables set on top, e.g. the author of a re-signed commit. + + Returns: + The environment of every git call in the temporary repository: no + inherited `GIT_*` variable, the system and passwd-home global config, + no replace objects, prompts and askpass helpers left to that config. + + """ + env = _scan_env(False, DEFAULT_CONFIG) + env.pop("GIT_TERMINAL_PROMPT", None) + env.pop("GIT_ASKPASS", None) + return {**env, **extra} + + +def _tgit_run(tdir: str, args: tuple[str, ...], local: bool) -> bytes: + """ + Args: + tdir: the temporary bare repository. + args: the git arguments. + local: also allow the file protocol, for transfers with the checkout. + + Returns: + The raw stdout. + + Raises: + GitRunError: git failed. + + """ + cmd = [ + "git", + f"--git-dir={tdir}", + *TRUSTED_FLAGS, + *(_FILE_PROTOCOL if local else ()), + *args, + ] + result = subprocess.run( + cmd, + cwd=tdir, + env=trusted_env({}), + input=b"", + capture_output=True, + check=False, + ) + if result.returncode != 0: + raise GitRunError( + f"Git command failed in {tdir!r}: {' '.join(cmd)}\n" + f"Exit code: {result.returncode}\n" + f"STDERR:\n{os.fsdecode(result.stderr)}" + ) + return result.stdout + + +def tgit_bytes(tdir: str, *args: str) -> bytes: + return _tgit_run(tdir, args, False) + + +def tgit(tdir: str, *args: str) -> str: + return os.fsdecode(_tgit_run(tdir, args, False)).strip() + + +def tgit_local(tdir: str, *args: str) -> str: + return os.fsdecode(_tgit_run(tdir, args, True)).strip() + + +def _ttry(tdir: str, *args: str) -> str | None: + try: + return tgit(tdir, *args) or None + except GitRunError: + return None + + +@contextmanager +def trusted_repo(repo_dir: str) -> Iterator[str]: + tdir = tempfile.mkdtemp(prefix="pkgmgr-push-") + try: + object_format = try_git(repo_dir, "config", "--get", "extensions.objectFormat") + tgit( + tdir, + "init", + "--quiet", + "--bare", + "--template=", + f"--object-format={object_format or 'sha1'}", + ) + yield tdir + finally: + shutil.rmtree(tdir, ignore_errors=True) + + +def _scheme_url_allowed(url: str) -> bool: + if url.split("://", 1)[0] not in PUSH_SCHEMES: + return False + try: + parts = urlsplit(url) + host = parts.hostname or "" + user = parts.username or "" + except ValueError: + return False + return bool(host) and not host.startswith("-") and not user.startswith("-") + + +def url_allowed(url: str) -> bool: + if any(ch.isspace() or not ch.isprintable() for ch in url): + return False + if "://" not in url: + return _SCP_URL.fullmatch(url) is not None + return _scheme_url_allowed(url) + + +def _listed_head(repo_dir: str, tdir: str) -> tuple[str, str]: + symrefs: dict[str, str] = {} + refs: dict[str, str] = {} + listed = tgit_local(tdir, "ls-remote", "--symref", "--", file_url(repo_dir)) + for line in listed.splitlines(): + value, _, name = line.partition("\t") + if value.startswith("ref: "): + symrefs[name] = value[len("ref: ") :] + else: + refs[name] = value + target = symrefs.get("HEAD", "") + if "HEAD" not in refs or not target.startswith("refs/heads/"): + raise PushRefusedError(f"{repo_dir}: detached HEAD, nothing to push") + return target[len("refs/heads/") :], refs["HEAD"] + + +def _push_remote(repo_dir: str, branch: str) -> str: + return ( + try_git(repo_dir, "config", "--get", f"branch.{branch}.pushRemote") + or try_git(repo_dir, "config", "--get", "remote.pushDefault") + or try_git(repo_dir, "config", "--get", f"branch.{branch}.remote") + or "origin" + ) + + +def open_target(repo_dir: str, tdir: str) -> Target: + """ + Args: + repo_dir: the checkout, read through upload-pack and `git config`. + tdir: the temporary bare repository. + + Returns: + The checkout's current branch, its HEAD and the push remote's URLs. + + Raises: + PushRefusedError: detached HEAD, no URL, or a URL that is not https, + ssh or user@host:path. + + """ + branch, head = _listed_head(repo_dir, tdir) + remote = _push_remote(repo_dir, branch) + urls = _config_all(repo_dir, f"remote.{remote}.url") + if not urls: + raise PushRefusedError(f"{repo_dir}: remote {remote} has no URL") + push_urls = tuple(_config_all(repo_dir, f"remote.{remote}.pushurl") or urls) + for url in (urls[0], *push_urls): + if not url_allowed(url): + raise PushRefusedError( + f"{repo_dir}: remote {remote} URL {url!r} is not 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) + + +def copy_head(target: Target, *, tags: bool) -> None: + tgit_local( + target.tdir, + "fetch", + "--quiet", + "--no-tags", + "--no-write-fetch-head", + "--no-recurse-submodules", + "--", + file_url(target.repo_dir), + target.head, + *(("+refs/tags/*:refs/tags/*",) if tags else ()), + ) + + +def fetch_heads( + target: Target, url: str, names: list[str], prefix: str +) -> dict[str, str]: + wanted = [f"refs/heads/{name}" for name in dict.fromkeys(names)] + listed = tgit(target.tdir, "ls-remote", "--", url, *wanted).splitlines() + present = {ln.split()[1] for ln in listed if len(ln.split()) == 2} & set(wanted) + if not present: + return {} + tgit( + target.tdir, + "fetch", + "--quiet", + "--no-tags", + "--no-write-fetch-head", + "--no-recurse-submodules", + "--", + url, + *(f"+{ref}:{prefix}/{ref}" for ref in sorted(present)), + ) + return { + ref[len("refs/heads/") :]: tgit( + target.tdir, "rev-parse", "--verify", "--quiet", f"{prefix}/{ref}" + ) + for ref in present + } + + +def _upstream_branch(target: Target) -> tuple[str, str] | None: + remote = try_git( + target.repo_dir, "config", "--get", f"branch.{target.branch}.remote" + ) + merge = try_git(target.repo_dir, "config", "--get", f"branch.{target.branch}.merge") + if not remote or remote == "." or not (merge or "").startswith("refs/heads/"): + return None + return remote, merge[len("refs/heads/") :] + + +def _upstream_tip(target: Target) -> tuple[str | None, str | None]: + upstream = _upstream_branch(target) + if upstream is None: + return None, None + remote, name = upstream + if remote == target.remote: + return name, None + urls = _config_all(target.repo_dir, f"remote.{remote}.url") + if not urls or not url_allowed(urls[0]): + return None, None + try: + return None, fetch_heads(target, urls[0], [name], "refs/pkgmgr/upstream").get( + name + ) + except GitRunError: + return None, None + + +def bases(target: Target) -> tuple[str | None, list[str | None]]: + """ + Returns: + The push remote's tip of the branch, and the candidate bases in order: + that tip, the upstream's tip, then the remote's main and master. + + """ + upstream_name, upstream_sha = _upstream_tip(target) + names = [ + target.branch, + *([upstream_name] if upstream_name else []), + "main", + "master", + ] + tips = fetch_heads(target, target.fetch_url, names, "refs/pkgmgr/base") + upstream = tips.get(upstream_name) if upstream_name else upstream_sha + return tips.get(target.branch), [ + tips.get(target.branch), + upstream, + tips.get("main"), + tips.get("master"), + ] + + +def unpushed_signatures( + target: Target, candidates: list[str | None] +) -> tuple[str, dict[str, str]]: + """ + Args: + target: the copied checkout. + candidates: bases as `bases` returns them; the first with a merge base wins. + + Returns: + The merge base, and the `%G?` signature status of every commit after it. + + Raises: + PushRefusedError: no candidate shares history with HEAD. + + """ + for tip in candidates: + base = tip and _ttry(target.tdir, "merge-base", target.head, tip) + if base: + lines = tgit( + target.tdir, "log", "--format=%H %G?", f"{base}..{target.head}" + ).splitlines() + return base, dict(line.split() for line in lines) + raise PushRefusedError( + f"{target.repo_dir}: no {target.remote}/{target.branch}, no upstream and no " + f"{target.remote}/main or {target.remote}/master to sign against" + ) diff --git a/src/pkgmgr/actions/repository/push.py b/src/pkgmgr/actions/repository/push.py index 5ceed26..0f9cc5c 100644 --- a/src/pkgmgr/actions/repository/push.py +++ b/src/pkgmgr/actions/repository/push.py @@ -1,7 +1,10 @@ from __future__ import annotations +import os +import re import subprocess import threading +from dataclasses import dataclass from typing import Any from pkgmgr.actions.repository._parallel import ( @@ -9,25 +12,41 @@ from pkgmgr.actions.repository._parallel import ( resolve_repos, run_on_repos, ) +from pkgmgr.actions.repository._trusted import ( + CHECKOUT_FETCH_FLAGS, + TRUSTED_FLAGS, + PushRefusedError, + Target, + bases, + copy_head, + fetch_heads, + file_url, + open_target, + tgit, + tgit_bytes, + trusted_env, + trusted_repo, + try_git, + unpushed_signatures, +) from pkgmgr.core.git import GitRunError, run from pkgmgr.core.git.queries import UNSAFE_CONFIG, local_config -from pkgmgr.core.git.run import SCAN_FLAGS Repository = dict[str, Any] # Re-signing opens pinentry; parallel pushes must not ask for the passphrase at once. _SIGN_LOCK = threading.Lock() - -class PushRefusedError(RuntimeError): - """Raised when a push would ship unsigned commits or overwrite a mirror.""" +_AUTHOR = re.compile(rb"(.*?) <([^>]*)> (\d+) ([+-]\d{4})") -def _try_git(repo_dir: str, *args: str) -> str | None: - try: - return run(list(args), cwd=repo_dir) - except GitRunError: - return None +@dataclass(frozen=True) +class _Push: + extra_args: tuple[str, ...] + refs: tuple[str, ...] + rewrite: bool + preview: bool + old_tip: str | None def refuse_unsafe_config(repo_dir: str) -> None: @@ -38,9 +57,10 @@ def refuse_unsafe_config(repo_dir: str) -> None: Raises: PushRefusedError: the repository's own config, which an agent may have written, sets a key that makes git run a program or reroute the push. - Filter drivers stay allowed on purpose: git-lfs and git-crypt need - them locally, so a clean filter can still run in the amend's index - refresh, as it did before. + Signing and pushing never read that config, so this is only an early + refusal; filter drivers stay allowed because git-lfs and git-crypt + need them locally. + """ unsafe = local_config(repo_dir, UNSAFE_CONFIG) if unsafe: @@ -50,132 +70,161 @@ def refuse_unsafe_config(repo_dir: str) -> None: ) -def _push_target(repo_dir: str) -> tuple[str, str]: - refuse_unsafe_config(repo_dir) - branch = run(["rev-parse", "--abbrev-ref", "HEAD"], cwd=repo_dir) - if branch == "HEAD": - raise PushRefusedError(f"{repo_dir}: detached HEAD, nothing to push") - remote = ( - _try_git(repo_dir, "config", "--get", f"branch.{branch}.pushRemote") - or _try_git(repo_dir, "config", "--get", "remote.pushDefault") - or _try_git(repo_dir, "config", "--get", f"branch.{branch}.remote") - or "origin" - ) - return branch, remote +def _head_commit(target: Target) -> tuple[list[str], dict[str, str], bytes]: + """ + Args: + target: the copied checkout. + + Returns: + The `git commit-tree` arguments that rebuild HEAD (encoding, tree, + parents), its author as environment variables, and its message. + + Raises: + PushRefusedError: HEAD has no tree or no parseable author. + + """ + fields, message = _commit_fields(target) + author = _AUTHOR.fullmatch((fields.get(b"author") or [b""])[0]) + if not fields.get(b"tree") or author is None: + raise PushRefusedError( + f"{target.repo_dir}: cannot parse HEAD {target.head[:10]}" + ) + name, email, stamp, zone = (os.fsdecode(part) for part in author.groups()) + args = [ + "-c", + "i18n.commitEncoding=" + + os.fsdecode((fields.get(b"encoding") or [b"UTF-8"])[0]), + "commit-tree", + os.fsdecode(fields[b"tree"][0]), + *(arg for p in fields.get(b"parent", []) for arg in ("-p", os.fsdecode(p))), + ] + env = { + "GIT_AUTHOR_NAME": name, + "GIT_AUTHOR_EMAIL": email, + "GIT_AUTHOR_DATE": f"@{stamp} {zone}", + } + return args, env, message -def _unpushed_signatures( - repo_dir: str, remote: str, branch: str -) -> tuple[str, dict[str, str]]: - for ref in ( - f"refs/remotes/{remote}/{branch}", - "@{u}", - f"refs/remotes/{remote}/main", - f"refs/remotes/{remote}/master", - ): - base = _try_git(repo_dir, "merge-base", "HEAD", ref) - if base: - lines = run( - ["log", "--format=%H %G?", f"{base}..HEAD"], cwd=repo_dir - ).splitlines() - return base, dict(line.split() for line in lines) - raise PushRefusedError( - f"{repo_dir}: no {remote}/{branch}, no upstream and no {remote}/main or " - f"{remote}/master to sign against" +def _commit_fields(target: Target) -> tuple[dict[bytes, list[bytes]], bytes]: + header, _, message = tgit_bytes( + target.tdir, "cat-file", "commit", target.head + ).partition(b"\n\n") + fields: dict[bytes, list[bytes]] = {} + for line in header.split(b"\n"): + key, _, value = line.partition(b" ") + fields.setdefault(key, []).append(value) + return fields, message + + +def _sign_head(target: Target) -> str: + args, author, message = _head_commit(target) + cmd = ["git", f"--git-dir={target.tdir}", *TRUSTED_FLAGS, *args, "-S"] + with _SIGN_LOCK: + result = subprocess.run( + cmd, + cwd=target.tdir, + env=trusted_env(author), + input=message, + stdout=subprocess.PIPE, + check=False, + ) + signed = os.fsdecode(result.stdout).strip() + if result.returncode != 0 or not signed: + raise PushRefusedError( + f"{target.repo_dir}: signing HEAD {target.head[:10]} failed" + ) + tgit(target.tdir, "update-ref", "refs/pkgmgr/signed", signed) + return signed + + +def _adopt(target: Target, signed: str) -> None: + """ + Args: + target: the checkout and its temporary repository. + signed: the signed commit; fetched into the checkout, then its branch + moves there. That fetch still reads the checkout's config, so + CHECKOUT_FETCH_FLAGS pins every key that would fetch from elsewhere + or run a program, in case the refuse-list check is stale. + + Raises: + PushRefusedError: the branch moved away from HEAD while it was signed. + + """ + run( + [ + *CHECKOUT_FETCH_FLAGS, + "fetch", + "--quiet", + "--no-tags", + "--no-write-fetch-head", + "--no-recurse-submodules", + "--upload-pack=git-upload-pack", + "--", + file_url(target.tdir), + signed, + ], + cwd=target.repo_dir, + scan=True, ) + try: + run( + [ + "update-ref", + "-m", + "pkgmgr push: sign HEAD", + target.branch_ref, + signed, + target.head, + ], + cwd=target.repo_dir, + scan=True, + ) + except GitRunError as exc: + raise PushRefusedError( + f"{target.repo_dir}: {target.branch} moved away from {target.head[:10]} " + f"while it was signed; left it where it is, signed {signed[:10]} is dropped" + ) from exc def sign_unpushed(repo_dir: str, *, preview: bool = False) -> None: """ Args: repo_dir: checkout whose current branch is signed. - preview: print the fetch and the amend instead of running them. + preview: read and check as usual, but print the signing instead of doing it. + """ - branch, remote = _push_target(repo_dir) - run( - ["fetch", "--quiet", "--no-recurse-submodules", "--", remote], - cwd=repo_dir, - preview=preview, - ) - base, signatures = _unpushed_signatures(repo_dir, remote, branch) - head = run(["rev-parse", "HEAD"], cwd=repo_dir) - older = sum(1 for sha, s in signatures.items() if sha != head and s != "G") - if older: - print( - f"[push] WARN {older} older unsigned commit(s) in {base[:10]}..HEAD~ of " - f"{repo_dir} stay unsigned: signing them would rewrite history" - ) - if signatures.get(head, "G") == "G": - return - if run( - [ - *SCAN_FLAGS, - "diff", - "--cached", - "--name-only", - "--no-ext-diff", - "--ignore-submodules=none", - "HEAD", - ], - cwd=repo_dir, - ): - raise PushRefusedError(f"{repo_dir}: staged changes, cannot sign HEAD") - - cmd = [ - "git", - *SCAN_FLAGS, - "commit", - "--amend", - "--no-edit", - "--no-verify", - "--allow-empty", - "-S", - ] - print(f"[push] Signing HEAD {head[:10]} in {repo_dir}") - if preview: - print(f"[PREVIEW] Would run in {repo_dir!r}: {' '.join(cmd)}") - return - with _SIGN_LOCK: - result = subprocess.run(cmd, cwd=repo_dir, check=False) - if result.returncode != 0: - raise PushRefusedError(f"{repo_dir}: signing HEAD {head[:10]} failed") - - -def _lease( - repo_dir: str, - url: str, - branch_ref: str, - tracking: str | None, - keep: tuple[str, ...], - preview: bool, -) -> str: - if tracking is not None: - sha = _try_git(repo_dir, "rev-parse", "--verify", "--quiet", tracking) or "" - else: - listed = run(["ls-remote", "--", url, branch_ref], cwd=repo_dir).splitlines() - sha = next( - (ln.split()[0] for ln in listed if ln.split()[1:] == [branch_ref]), "" - ) - if sha and not preview: - run( - [ - "fetch", - "--quiet", - "--no-tags", - "--no-recurse-submodules", - "--", - url, - branch_ref, - ], - cwd=repo_dir, + refuse_unsafe_config(repo_dir) + with trusted_repo(repo_dir) as tdir: + target = open_target(repo_dir, tdir) + copy_head(target, tags=False) + _tip, candidates = bases(target) + base, signatures = unpushed_signatures(target, candidates) + head = target.head + older = sum(1 for sha, s in signatures.items() if sha != head and s != "G") + if older: + print( + f"[push] WARN {older} older unsigned commit(s) in {base[:10]}..HEAD~ of " + f"{repo_dir} stay unsigned: signing them would rewrite history" ) - if not sha or preview: - return sha + if signatures.get(head, "G") == "G": + return + print(f"[push] Signing HEAD {head[:10]} in {repo_dir}") + if preview: + print( + f"[PREVIEW] Would re-sign {head[:10]} with git commit-tree -S in a " + f"temporary repository and move {target.branch_ref} of {repo_dir!r} to it" + ) + return + _adopt(target, _sign_head(target)) + + +def _refuse_lost(target: Target, url: str, sha: str, keep: tuple[str, ...]) -> None: lost: set[str] | None = None for tip in keep: plus = { line[2:] - for line in run(["cherry", tip, sha], cwd=repo_dir).splitlines() + for line in tgit(target.tdir, "cherry", tip, sha).splitlines() if line.startswith("+") } lost = plus if lost is None else lost & plus @@ -185,7 +234,6 @@ def _lease( f"{' '.join(s[:10] for s in sorted(lost))}; " "pass --rewrite for a deliberate history rewrite" ) - return sha def push_branch( @@ -198,13 +246,6 @@ def push_branch( preview: bool = False, ) -> None: """ - Push the current branch to every pushurl of its push remote, each with its own lease. - - The fetch URL is leased against the remote-tracking ref, every other - pushurl against its own branch tip; each only after `git cherry` shows it - holds no commit the new tip lacks. A mirror failure is reported after the - others were pushed; a canonical failure stops before any mirror. - Args: repo_dir: checkout whose current branch is pushed. extra_args: flags appended to every `git push`. @@ -213,75 +254,129 @@ def push_branch( rewrite: replace commits of the old canonical tip; the fetch URL skips the cherry check, mirrors only refuse commits the old tip never had. preview: print the pushes instead of running them. + """ - branch, remote = _push_target(repo_dir) - head = run(["rev-parse", "HEAD"], cwd=repo_dir) - if sign: - _base, signatures = _unpushed_signatures(repo_dir, remote, branch) - if not preview and signatures.get(head, "G") != "G": - raise PushRefusedError( - f"{repo_dir}: HEAD {head[:10]} is unsigned; run `pkgmgr push` to sign it" + refuse_unsafe_config(repo_dir) + with trusted_repo(repo_dir) as tdir: + target = open_target(repo_dir, tdir) + copy_head(target, tags=True) + old_tip = _old_tip(target, sign, preview) + plan = _Push(tuple(extra_args), refs, rewrite, preview, old_tip) + if target.fetch_url not in target.push_urls: + print( + f"[push] WARN {target.remote}: fetch URL is no pushurl; every URL is " + "leased as a mirror, tracking ref and upstream stay untouched" ) - - fetch_url = run(["remote", "get-url", "--", remote], cwd=repo_dir) - push_urls = run( - ["remote", "get-url", "--push", "--all", "--", remote], cwd=repo_dir - ).splitlines() - branch_ref = f"refs/heads/{branch}" - tracking = f"refs/remotes/{remote}/{branch}" - old_tip = _try_git(repo_dir, "rev-parse", "--verify", "--quiet", tracking) - if fetch_url not in push_urls: - print( - f"[push] WARN {remote}: fetch URL is no pushurl; every URL is leased " - "as a mirror, tracking ref and upstream stay untouched" - ) - - failed: list[str] = [] - for url in sorted(push_urls, key=lambda u: u != fetch_url): - if url == fetch_url: - keep: tuple[str, ...] = () if rewrite else (head,) - else: - keep = (head, old_tip) if rewrite and old_tip else (head,) - try: - expect = _lease( - repo_dir, - url, - branch_ref, - tracking if url == fetch_url else None, - keep, - preview, - ) - run( - [ - "push", - "--follow-tags", - "--no-recurse-submodules", - f"--force-with-lease={branch_ref}:{expect}", - *extra_args, - "--", - url, - branch_ref, - *refs, - ], - cwd=repo_dir, - preview=preview, - ) - except (GitRunError, PushRefusedError) as exc: - if url == fetch_url: - raise - print(f"[push] FAILED {url}\n{exc}") - failed.append(url) - continue - print(f"[push] {url} <- {branch} {head[:10]}") - if url == fetch_url and not preview: - run(["update-ref", tracking, head], cwd=repo_dir) - if not _try_git(repo_dir, "rev-parse", "--abbrev-ref", "@{u}"): - run(["branch", f"--set-upstream-to={remote}/{branch}"], cwd=repo_dir) - + failed: list[str] = [] + ordered = sorted(target.push_urls, key=lambda u: u != target.fetch_url) + for index, url in enumerate(ordered): + if not _push_url(target, plan, index, url): + failed.append(url) if failed: raise PushRefusedError(f"{repo_dir}: push failed for {', '.join(failed)}") +def _old_tip(target: Target, sign: bool, preview: bool) -> str | None: + """ + Args: + target: the copied checkout. + sign: also refuse an unpushed, unsigned HEAD. + preview: skip that refusal. + + Returns: + The canonical URL's branch tip, or None when it has no such branch. + + """ + if not sign: + return fetch_heads( + target, target.fetch_url, [target.branch], "refs/pkgmgr/base" + ).get(target.branch) + old_tip, candidates = bases(target) + _base, signatures = unpushed_signatures(target, candidates) + if not preview and signatures.get(target.head, "G") != "G": + raise PushRefusedError( + f"{target.repo_dir}: HEAD {target.head[:10]} is unsigned; " + "run `pkgmgr push` to sign it" + ) + return old_tip + + +def _lease(target: Target, plan: _Push, index: int, url: str) -> str: + if url == target.fetch_url: + return plan.old_tip or "" + tips = fetch_heads(target, url, [target.branch], f"refs/pkgmgr/lease/{index}") + return tips.get(target.branch) or "" + + +def _keep(target: Target, plan: _Push, canonical: bool) -> tuple[str, ...]: + if canonical: + return () if plan.rewrite else (target.head,) + if plan.rewrite and plan.old_tip: + return (target.head, plan.old_tip) + return (target.head,) + + +def _push_url(target: Target, plan: _Push, index: int, url: str) -> bool: + """ + Args: + target: the copied checkout. + plan: the push options and the canonical URL's old tip. + index: position of the URL, naming its lease ref. + url: the URL pushed to. + + Returns: + False when a mirror failed; the failure is printed. + + Raises: + GitRunError, PushRefusedError: the canonical URL failed. + + """ + canonical = url == target.fetch_url + try: + expect = _lease(target, plan, index, url) + if expect and not plan.preview: + _refuse_lost(target, url, expect, _keep(target, plan, canonical)) + cmd = [ + "push", + "--follow-tags", + "--no-recurse-submodules", + "--no-verify", + f"--force-with-lease={target.branch_ref}:{expect}", + *plan.extra_args, + "--", + url, + f"{target.head}:{target.branch_ref}", + *plan.refs, + ] + if plan.preview: + print( + f"[PREVIEW] Would run in a temporary copy of {target.repo_dir!r}: " + f"git {' '.join(cmd)}" + ) + else: + tgit(target.tdir, *cmd) + except (GitRunError, PushRefusedError) as exc: + if canonical: + raise + print(f"[push] FAILED {url}\n{exc}") + return False + print(f"[push] {url} <- {target.branch} {target.head[:10]}") + if canonical and not plan.preview: + _track(target) + return True + + +def _track(target: Target) -> None: + tracking = f"refs/remotes/{target.remote}/{target.branch}" + run(["update-ref", tracking, target.head], cwd=target.repo_dir, scan=True) + if not try_git(target.repo_dir, "rev-parse", "--abbrev-ref", "@{u}"): + run( + ["branch", f"--set-upstream-to={target.remote}/{target.branch}"], + cwd=target.repo_dir, + scan=True, + ) + + def _push_one( repo_dir: str, extra_args: list[str], sign: bool, rewrite: bool, preview: bool ) -> tuple[bool, str]: @@ -302,9 +397,6 @@ def push_repo_dirs( jobs: int = 1, rewrite: bool = False, ) -> None: - """ - Sign and push each ``(identifier, repo_dir)``, optionally in parallel. - """ run_on_repos( repos, lambda rd: _push_one(rd, extra_args, sign, rewrite, preview), @@ -323,9 +415,6 @@ def push_in_parallel( jobs: int = 1, rewrite: bool = False, ) -> None: - """ - Sign and push each selected repository, optionally in parallel. - """ push_repo_dirs( resolve_repos(selected_repos, repositories_base_dir, all_repos), extra_args, diff --git a/tests/integration/test_push_mirror_leases.py b/tests/integration/test_push_mirror_leases.py index 6f12e42..6920676 100644 --- a/tests/integration/test_push_mirror_leases.py +++ b/tests/integration/test_push_mirror_leases.py @@ -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") diff --git a/tests/unit/pkgmgr/actions/repository/test_push_trusted_gitdir.py b/tests/unit/pkgmgr/actions/repository/test_push_trusted_gitdir.py new file mode 100644 index 0000000..4a9fe30 --- /dev/null +++ b/tests/unit/pkgmgr/actions/repository/test_push_trusted_gitdir.py @@ -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)