Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
9e02f4d
Fetch every named ref by the commit it was admitted at (#5138)
danielmeppiel Nov 23, 2026
217a63e
Add changelog fragment for #5195
danielmeppiel Nov 23, 2026
ebfd245
Record the spec waiver for the fetch-by-commit change
danielmeppiel Nov 23, 2026
9e4e021
Fold review: fall back only on want refusal; name lost commit safely
danielmeppiel Nov 23, 2026
4769eae
Fold review: locale-proof refusal, by-name fetch of a live tip
danielmeppiel Nov 23, 2026
98aa08f
Keep a named-ref cell on the mkdtemp error path
danielmeppiel Nov 23, 2026
d45e352
Verify the by-name fallback after links are materialized
danielmeppiel Nov 23, 2026
6662920
Merge origin/main into fix-5138-fetch-named-ref-by-commit
danielmeppiel Nov 24, 2026
e2d6f04
List the fallback ref through the validated clone environment
danielmeppiel Nov 24, 2026
2754944
Admit a named ref a host cannot clone shallowly by its exact listing
danielmeppiel Nov 24, 2026
8d90a03
Probe a listing's clone config once per origin; pin TLS floor in a cell
danielmeppiel Nov 24, 2026
35c6480
Keep a listing's clone-config probe for the install attempt only
danielmeppiel Nov 24, 2026
2d8db69
Record a listed tip under the environment that listed it
danielmeppiel Nov 24, 2026
e23fbd0
Record a resolved tip under the environment its contact gets
danielmeppiel Nov 24, 2026
b3fdc7c
Check reachability under the environment a clone of the origin gets
danielmeppiel Nov 24, 2026
9e107d9
Probe clone config only when an includeIf can apply; trust tips safely
danielmeppiel Nov 24, 2026
4fe2a6c
Probe a resolved tip's contact without credentials
danielmeppiel Nov 24, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/5195.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- A branch or tag dependency is fetched by the commit it was admitted at, so a ref moved mid-install cannot change what installs. (#5195)
391 changes: 356 additions & 35 deletions src/apm_cli/cache/commit_reachability.py

Large diffs are not rendered by default.

119 changes: 119 additions & 0 deletions src/apm_cli/deps/bare_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,125 @@ def _scrub_bare_remote_url(bare_path: Path, git_exe: str, env: dict[str, str]) -
)


# Protocol v0 servers refuse a want for an unadvertised commit. Under v2 a
# "not our ref" means the commit is gone on stock git, but some hosts answer
# so for any unadvertised commit; neither may clone the history in full.
_WANT_REFUSED = ("does not allow request for unadvertised object",)
_NOT_OUR_REF = "not our ref"
# git translates its own messages; the fetch runs untranslated so they match.
_UNTRANSLATED = {"LC_ALL": "C", "LANGUAGE": "C"}


def _refuses_want_by_commit(exc: subprocess.CalledProcessError) -> bool:
"""Whether git failed because the server refuses to serve a commit by its id."""
return any(marker in _stderr_text(exc) for marker in _WANT_REFUSED)


def _stderr_text(exc: subprocess.CalledProcessError) -> str:
detail = exc.stderr
if isinstance(detail, bytes):
detail = detail.decode("utf-8", "replace")
return (detail or "").lower()


def _fetch_admitted_tip_by_name(
git_exe: str, path: Path, url: str, ref: str, sha: str, fetch_env: dict[str, str]
) -> bool:
"""Fetch *ref* by name when it still points at *sha*; ``False`` if unknown.

Both the listing and the fetch use *fetch_env*, the validated clone env of
*path*, so they reach the destination a clone would (a mirror rewrite).

Raises:
AdmittedCommitGoneError: *ref* no longer points at *sha*.
"""
from ..cache.commit_reachability import admitted_tip_name

name = admitted_tip_name(url, ref, sha, fetch_env)
if name is None:
return False
subprocess.run(
[git_exe, "-C", str(path), "fetch", "-q", "--depth=1", "--no-tags", url, name],
env={**fetch_env, **_UNTRANSLATED},
check=True,
capture_output=True,
timeout=300,
)
return True


def fetch_commit_worktree(
execute_transport_plan: Callable[..., None],
repo_url_base: str,
target: Path,
*,
dep_ref: DependencyReference,
sha: str,
verbose_callback: Callable[[str], None] | None = None,
) -> None:
"""Check out commit *sha* at *target*, fetched by that commit, never by a name (#5138).

Shallow: ``git init``, ``git fetch --depth=1 --no-tags <url> <sha>`` and a
detached checkout. A server that refuses a want by commit falls back to a
full clone and a checkout of *sha*. A server that answers "not our ref"
gets the ref fetched by name, only while it still points at *sha*; the
checkout is still of *sha*. Runs over the clone transport plan. The
caller verifies the checkout against *sha* once links are materialized.
"""
from ..utils.git_env import (
checkout_git_worktree,
clone_git_worktree,
get_git_executable,
git_clone_env,
git_no_templates_args,
git_subprocess_env,
)

git_exe = get_git_executable()

def _action(url: str, env: dict[str, str], path: Path) -> None:
env = git_subprocess_env(env)
if path.exists():
_rmtree(path)
# The env a clone would get, with remote-activated config applied.
fetch_env = git_clone_env(url, env, path)
try:
subprocess.run(
[git_exe, "init", "-q", *git_no_templates_args(), str(path)],
env=fetch_env,
check=True,
capture_output=True,
)
subprocess.run(
[git_exe, "-C", str(path), "fetch", "-q", "--depth=1", "--no-tags", url, sha],
env={**fetch_env, **_UNTRANSLATED},
check=True,
capture_output=True,
timeout=300,
)
except subprocess.CalledProcessError as exc:
# Only a server that refuses a want by commit gets the full clone; a
# missing commit or an auth failure fails here, at depth-1 cost.
ref = getattr(dep_ref, "reference", None)
if ref and _NOT_OUR_REF in _stderr_text(exc):
if not _fetch_admitted_tip_by_name(git_exe, path, url, ref, sha, fetch_env):
raise
checkout_git_worktree(path, sha, env=env)
return
if not _refuses_want_by_commit(exc):
raise
if verbose_callback:
verbose_callback(
f"Fetch by commit refused; cloning in full to check out {sha[:12]}"
)
if path.exists():
_rmtree(path)
clone_git_worktree(url, path, env=env, no_checkout=True)
checkout_git_worktree(path, sha, env=env)

execute_transport_plan(repo_url_base, target, dep_ref=dep_ref, clone_action=_action)


def bare_clone_with_fallback(
execute_transport_plan: Callable[..., None],
repo_url_base: str,
Expand Down
3 changes: 2 additions & 1 deletion src/apm_cli/deps/git_reference_resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -632,7 +632,8 @@ def resolve(self, repo_ref: str | DependencyReference) -> ResolvedReference:
if not (ref or "").startswith("refs/"):
try:
shallow = self._resolve_shallow(dep_ref, ref, temp_dir)
except git_command_error():
except (git_command_error(), RuntimeError):
# The clone engine reports a failed plan as RuntimeError.
shallow = None
if shallow is not None:
ref_type, resolved_commit, ref_name = shallow
Expand Down
46 changes: 22 additions & 24 deletions src/apm_cli/deps/github_downloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

from ..cache.cached_repo import validate_cached_links
from ..cache.checkout_verify import require_verified_checkout, require_verified_copy
from ..cache.commit_reachability import name_a_lost_admitted_commit
from ..cache.git_cache import dir_size, raise_if_tampered
from ..core.auth import AuthContext, AuthResolver
from ..models.apm_package import (
Expand Down Expand Up @@ -53,6 +54,7 @@
from .bare_cache import (
bare_clone_with_fallback,
clone_with_fallback,
fetch_commit_worktree,
fetch_sha_into_bare,
materialize_from_bare,
)
Expand Down Expand Up @@ -1390,9 +1392,9 @@ def download_subdirectory_package(
# calling get_checkout so the cache skips its internal
# ls-remote. Same pattern as the non-subdir path at
# line ~1604 which passes locked_sha=resolved.
try:
_resolved = self.resolve_git_reference(dep_ref)
_resolved_sha_for_cache = _resolved.resolved_commit
try: # A declared ref is already its admitted commit; never resolve it again.
_resolved = None if dep_ref.reference else self.resolve_git_reference(dep_ref)
_resolved_sha_for_cache = _resolved.resolved_commit if _resolved else ref
except Exception:
_resolved_sha_for_cache = None
# Sparse-cone (#1433): keying the persistent shard by
Expand Down Expand Up @@ -1779,6 +1781,7 @@ def _download_package_from_artifactory(
progress_obj=progress_obj,
)

@name_a_lost_admitted_commit
def download_package(
self,
repo_ref: Union[str, "DependencyReference"],
Expand Down Expand Up @@ -1953,19 +1956,12 @@ def download_package(
package_display_name = repo_segments[-1] if repo_segments else dep_ref.repo_url

try:
# Clone the repository using fallback authentication methods
# Use shallow clone for performance if we have a specific commit
if resolved_ref.ref_type == GitReferenceType.COMMIT or resolved_ref.ref_name.startswith(
"refs/"
):
# Commits and fully qualified refs: clone, then check out the resolved commit
progress_reporter = (
_git_progress_reporter_class()(
progress_task_id, progress_obj, package_display_name
)
if progress_task_id and progress_obj
else None
)
progress_reporter = (
_git_progress_reporter_class()(progress_task_id, progress_obj, package_display_name)
if progress_task_id and progress_obj
else None
)
if resolved_ref.ref_type == GitReferenceType.COMMIT:
self._clone_with_fallback(
dep_ref.repo_url,
target_path,
Expand All @@ -1974,15 +1970,17 @@ def download_package(
verbose_callback=verbose_callback,
)
checkout_git_worktree(target_path, resolved_ref.resolved_commit, env=self.git_env)
else:
# For branches and tags, we can use shallow clone
progress_reporter = (
_git_progress_reporter_class()(
progress_task_id, progress_obj, package_display_name
)
if progress_task_id and progress_obj
else None
elif dep_ref.reference:
# A named ref: its admitted commit, fetched shallowly by commit (#5138)
fetch_commit_worktree(
self._execute_transport_plan,
dep_ref.repo_url,
target_path,
dep_ref=dep_ref,
sha=resolved_ref.resolved_commit,
verbose_callback=verbose_callback,
)
else:
self._clone_with_fallback(
dep_ref.repo_url,
target_path,
Expand Down
78 changes: 44 additions & 34 deletions tests/integration/test_anonymous_https_git_suffix_e2e.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

from __future__ import annotations

import importlib
from pathlib import Path
from unittest.mock import MagicMock
from urllib.parse import urlparse

import pytest
Expand Down Expand Up @@ -63,13 +63,13 @@ def _write_manifest(project: Path) -> Path:
return apm_yml


def _resolved_main() -> ResolvedReference:
def _resolved_main(commit: str) -> ResolvedReference:
"""Return a deterministic branch resolution with no network access."""
return ResolvedReference(
original_ref="main",
ref_name="main",
ref_type=GitReferenceType.BRANCH,
resolved_commit="a" * 40,
resolved_commit=commit,
)


Expand Down Expand Up @@ -105,42 +105,41 @@ def test_generic_anonymous_https_clone_url_keeps_git_suffix_end_to_end(
package = APMPackage.from_apm_yml(apm_yml)
dep_ref = package.get_apm_dependencies()[0]
captured: dict[str, object] = {}
# The package the origin serves, at the commit admission resolves "main" to.
served = tmp_path / "served"
skill_dir = served / ".apm" / "skills" / "demo"
skill_dir.mkdir(parents=True)
(served / "apm.yml").write_text(
"name: cloned-gitbucket-package\nversion: '1.0.0'\n",
encoding="utf-8",
)
(skill_dir / "SKILL.md").write_text("# Demo\n", encoding="utf-8")
git("init", "-q", "-b", "main", "--template=", str(served))
git("-C", str(served), "add", "-A")
git("-C", str(served), "commit", "-q", "-m", "served")
commit = git("-C", str(served), "rev-parse", "HEAD").strip()
fetch_by_commit = importlib.import_module("apm_cli.deps.bare_cache").fetch_commit_worktree

def capture_fetch(execute_transport_plan, repo_url_base, target, *, dep_ref, sha, **kw):
"""Run the real transport plan; the origin's fetch is served locally."""

def fake_clone_from(
url: str,
target: Path,
*,
env: dict[str, str] | None = None,
progress: object | None = None,
**kwargs: object,
) -> _FakeRepo:
"""Capture the clone URL and materialise a valid package."""
captured["url"] = url
captured["env"] = env or {}
captured["kwargs"] = kwargs
target.mkdir(parents=True, exist_ok=True)
skill_dir = target / ".apm" / "skills" / "demo"
skill_dir.mkdir(parents=True)
(target / "apm.yml").write_text(
"name: cloned-gitbucket-package\nversion: '1.0.0'\n",
encoding="utf-8",
)
(skill_dir / "SKILL.md").write_text("# Demo\n", encoding="utf-8")
# A real clone leaves a checkout whose links resolve from Git objects (#3457).
git("init", "-q", "-b", "main", "--template=", str(target))
git("-C", str(target), "add", "-A")
git("-C", str(target), "commit", "-q", "-m", "fake clone")
return _FakeRepo()
def plan(base, path, *, dep_ref, clone_action, **plan_kw):
def serve(url: str, env: dict[str, str], dest: Path) -> None:
captured["url"] = url
captured["env"] = dict(env)
captured["sha"] = sha
clone_action(served.as_uri(), {}, dest)

execute_transport_plan(base, path, dep_ref=dep_ref, clone_action=serve, **plan_kw)

fetch_by_commit(plan, repo_url_base, target, dep_ref=dep_ref, sha=sha, **kw)

monkeypatch.setattr(
GitHubPackageDownloader,
"resolve_git_reference",
lambda self, repo_ref: _resolved_main(),
lambda self, repo_ref: _resolved_main(commit),
)

repo_cls = MagicMock()
repo_cls.clone_from.side_effect = fake_clone_from
monkeypatch.setattr("apm_cli.deps.github_downloader.Repo", repo_cls)
monkeypatch.setattr("apm_cli.deps.github_downloader.fetch_commit_worktree", capture_fetch)
downloader = GitHubPackageDownloader()
result = downloader.download_package(
dep_ref,
Expand All @@ -155,5 +154,16 @@ def fake_clone_from(
assert parsed.username is None
assert parsed.password is None
assert parsed.path == "/owner/repo.git"
assert captured["kwargs"] == {"depth": 1, "branch": "main"}
# Fetched by the admitted commit, anonymously: no credential reaches Git.
assert captured["sha"] == commit
env = captured["env"]
assert isinstance(env, dict)
assert "GIT_HTTP_EXTRAHEADER" not in env
entries = [
(env[f"GIT_CONFIG_KEY_{index}"], env.get(f"GIT_CONFIG_VALUE_{index}", ""))
for index in range(int(env.get("GIT_CONFIG_COUNT", "0")))
]
# An empty extraheader only resets inherited headers; none may carry a value.
assert all(not value for key, value in entries if "extraheader" in key.lower())
assert not [value for _key, value in entries if "authorization" in value.lower()]
assert result.package.name == "cloned-gitbucket-package"
Loading
Loading