Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 2 additions & 1 deletion .apm/architecture/owners/contracts-tooling.json
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,8 @@
"src/apm_cli/core/invocation_memo.py",
"src/apm_cli/policy/discovery.py",
"src/apm_cli/policy/_cache_verify.py",
"src/apm_cli/policy/_cached_candidates.py"
"src/apm_cli/policy/_cached_candidates.py",
"src/apm_cli/core/policy_fetch_ledger.py"
],
"guards": [
"contracts-tooling-cached-policy-shape",
Expand Down
1 change: 1 addition & 0 deletions changelog.d/5331.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- Repeat `apm install` no-ops on GitLab and Azure DevOps projects now replay the verified no-op when their org policy came from a fresh cache. (#5331)
22 changes: 22 additions & 0 deletions src/apm_cli/core/policy_fetch_ledger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
"""Org-policy fetch attempts made by this process.

Each fetch channel notes its attempt when it decides to fetch, before any
credential lookup or request, so a run whose policy came only from the cache
can be told apart from one that went to the network (the verified-state record
replays only the former). Import-light on purpose: nothing here may pull in
the HTTP stack.
"""

from __future__ import annotations

_ATTEMPTS: list[str] = []


def note_fetch_attempt(channel: str) -> None:
"""Record that *channel* (``github``, ``gitlab``, ``ado`` or ``http``) is about to fetch."""
_ATTEMPTS.append(channel)


def fetch_attempts() -> int:
"""How many policy fetch attempts this process has made so far."""
return len(_ATTEMPTS)
34 changes: 34 additions & 0 deletions src/apm_cli/install/verdict_inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,3 +149,37 @@ def _key_modules(digest: Any, root: Path) -> None:
if MARKER_FILENAME in names:
continue # a package copy: its bytes are proven against the lock
stack += [(f"{rel}/{e.name}", e.path) for e in entries if e.is_dir(follow_symlinks=False)]


def entry_stamp() -> list[Any]:
"""The recorded run's start: its wall time, the org-policy fetch attempts this
process had made, and the policy cache's shape, so the writer knows whether the
run's discovery fetched and whether the cache it read is still the one keyed."""
import time

from apm_cli.core.policy_fetch_ledger import fetch_attempts

return [time.time(), fetch_attempts(), policy_cache_shape()]


def policy_cache_shape() -> str | None:
"""Every policy cache file's path, mtime and content digest (the cache discovery
reads), read no-follow; None when any of it cannot be read (no record)."""
import hashlib

from apm_cli.install.verdict_record import _cache_root, _read_nofollow

try:
cache = _cache_root()
if cache is None:
return ""
rows = []
for rel, files, _dirs in _tree(str(cache / "policy_v1")):
for entry in files:
data = _read_nofollow(entry.path)
digest = "absent" if data is None else hashlib.sha256(data).hexdigest()
mtime = entry.stat(follow_symlinks=False).st_mtime_ns
rows.append(f"{rel}/{entry.name}:{mtime}:{digest}")
return "\n".join(rows)
except (OSError, ValueError):
return None
20 changes: 17 additions & 3 deletions src/apm_cli/install/verdict_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,10 @@ def _discovery_unproven(root: Path, identity: Any) -> bool:
Discovery tries the candidates in order and fetches each one with no fresh
cached entry for this project (it caches no absence), so only a fresh entry
for the first candidate proves it returns without a fetch. GitLab ancestry
and Azure DevOps have no such proof: no record. *identity* is the remote's
org, host and port (None without one).
and Azure DevOps record only when this run's discovery fetched nothing: every
candidate it consulted came from a fresh cached entry, all of them keyed and
bounding the record's expiry (#5075). *identity* is the remote's org, host
and port (None without one).
"""
if identity is None:
return False
Expand All @@ -138,7 +140,19 @@ def _discovery_unproven(root: Path, identity: Any) -> bool:

org, host, _port = identity
if is_azure_devops_hostname(host) or is_gitlab_hostname(host):
return True
from apm_cli.core.policy_fetch_ledger import fetch_attempts
from apm_cli.install.verdict_inputs import policy_cache_shape
from apm_cli.install.verdict_record import _ENTRY_TIME

# The cache discovery read must still be the cache the record keys.
shape = policy_cache_shape()
return (
len(_ENTRY_TIME) < 3
or fetch_attempts() != _ENTRY_TIME[1]
or _ENTRY_TIME[2] is None
or shape is None
or shape != _ENTRY_TIME[2]
)
refs = candidate_refs(org, host, discovery._policy_repo_candidates(host))
pin = read_project_policy_hash_pin(root)
expected = pin.normalized if pin is not None else None
Expand Down
12 changes: 6 additions & 6 deletions src/apm_cli/install/verdict_record.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,10 +296,9 @@ def __getitem__(self, key: Any) -> Any:


_PROVEN_LOCK: list[bytes | None] = []
# apm.yml and the lock as the run found them: an edit while the run was proving
# its verdict (an editor saving apm.yml) means its verdict is not the record's (W3d R4).
# apm.yml and the lock as the run found them (W3d R4), and its start (verdict_inputs).
_ENTRY_FILES: list[bytes | None] = []
_ENTRY_TIME: list[float] = []
_ENTRY_TIME: list[Any] = []


def _entry_bytes(name: str) -> bytes | None:
Expand Down Expand Up @@ -803,7 +802,9 @@ def recording(argv: list[str]) -> Iterator[None]:
_ENV_READS.clear()
entry = (_env_snapshot(), _presentation())
_ENTRY_FILES[:] = [_entry_bytes("apm.yml"), _entry_bytes("apm.lock.yaml")]
_ENTRY_TIME[:] = [time.time()]
from apm_cli.install.verdict_inputs import entry_stamp

_ENTRY_TIME[:] = entry_stamp()
Comment thread
danielmeppiel marked this conversation as resolved.
Resolved
out, err = _Tee(sys.stdout), _Tee(sys.stderr)
sys.stdout, sys.stderr = out, err # type: ignore[assignment]
_ACTIVE.append(out)
Expand Down Expand Up @@ -865,8 +866,7 @@ def _record_after(argv: list[str], entry: Any, out: _Tee, err: _Tee) -> None:
from apm_cli.core.lifecycle_scripts import discover_scripts

if discover_scripts(str(Path.cwd())):
# Scripts fire on every install (and may change any input after it was read);
# a replay fires none, so a run with scripts is never recorded (W3d R1).
# Scripts fire on every install; a replay fires none, so never record (W3d R1).
_trace("no record (lifecycle scripts)")
return
lock = _committed_lock()
Expand Down
3 changes: 3 additions & 0 deletions src/apm_cli/policy/_gitlab.py
Original file line number Diff line number Diff line change
Expand Up @@ -697,6 +697,9 @@ def _authenticated_gitlab_request(
project_path: str,
) -> requests.Response:
"""Run the GitLab REST request through the selected AuthResolver credential."""
from ..core.policy_fetch_ledger import note_fetch_attempt

note_fetch_attempt("gitlab") # before the credential lookup
from ..core.auth import AuthResolver
from ..core.auth_outcome import AuthAttemptFailed

Expand Down
3 changes: 3 additions & 0 deletions src/apm_cli/policy/_policy_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,9 @@ def policy_get(
egress-route owner, which keeps this governance channel direct in
registry-only mode.
"""
from ..core.policy_fetch_ledger import note_fetch_attempt

note_fetch_attempt("http")
route = route_for(EgressSurface.POLICY_FETCH)
if route is not EgressRoute.DIRECT:
raise requests.RequestException(f"policy fetch route is {route.value}")
Expand Down
5 changes: 3 additions & 2 deletions src/apm_cli/policy/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -1380,9 +1380,10 @@ def _request(token: str | None, _git_env: dict[str, str]):

def _policy_auth_resolver():
"""Return the AuthResolver every policy repository fetch routes through."""
from ..core.auth import AuthResolver
from ..core import auth, policy_fetch_ledger

return AuthResolver()
policy_fetch_ledger.note_fetch_attempt("repository") # before any credential lookup
return auth.AuthResolver()


# ---------------------------------------------------------------------------
Expand Down
140 changes: 140 additions & 0 deletions tests/integration/test_verdict_record.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from __future__ import annotations

import ast
import contextlib
import hashlib
import os
import re
Expand Down Expand Up @@ -1002,3 +1003,142 @@ def test_a_linked_worktree_is_never_recorded(project: Path) -> None:
_record()

assert not (_home(project) / "verdicts").exists()


_HOSTED_REMOTES = {
"gitlab": "https://gitlab.com/acme/app.git",
"ado": "https://dev.azure.com/acme/proj/_git/app",
}


def _hosted_project(project: Path, host: str) -> None:
import subprocess

subprocess.run(["git", "init", "-q", str(project)], check=True)
subprocess.run(
["git", "-C", str(project), "remote", "add", "origin", _HOSTED_REMOTES[host]], check=True
)


@pytest.mark.skipif(shutil.which("git") is None, reason="needs git")
@pytest.mark.parametrize("host", sorted(_HOSTED_REMOTES))
def test_a_gitlab_or_ado_run_whose_policy_came_from_the_cache_records_and_hits(
project: Path, capsys, host: str
) -> None:
"""#5075: discovery fetched nothing, so its result rests only on keyed cache state."""
_hosted_project(project, host)
_record()
capsys.readouterr()

assert verdict_record.replay(["install"]) is True
assert "up to date in " in capsys.readouterr().out


@pytest.mark.skipif(shutil.which("git") is None, reason="needs git")
@pytest.mark.parametrize("host", sorted(_HOSTED_REMOTES))
def test_a_gitlab_or_ado_run_that_attempted_a_policy_fetch_never_records(
project: Path, host: str
) -> None:
"""A fetch (or its credential lookup) this run means the next run fetches too."""
from apm_cli.core.policy_fetch_ledger import note_fetch_attempt

_hosted_project(project, host)
with verdict_record.recording(["install"]):
sys.stdout.write(_OUTPUT)
note_fetch_attempt(host)
verdict_record.note_verified_noop()

assert not (_home(project) / "verdicts").exists()


@pytest.mark.skipif(shutil.which("git") is None, reason="needs git")
def test_a_pinned_gitlab_project_never_records_even_with_a_fresh_cache(
project: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A policy.hash pin makes GitLab discovery read the source, never the cache (W3d R1)."""
from apm_cli.policy import discovery
from apm_cli.policy.parser import load_policy

def _offline(*_args, **_kwargs):
raise OSError("offline")

_hosted_project(project, "gitlab")
(project / "apm.yml").write_text(
f"name: demo\nversion: 1.0.0\npolicy:\n hash: sha256:{'a' * 64}\n", encoding="utf-8"
)
policy, _warnings = load_policy("enforcement: warn\ncache:\n ttl: 3600\n")
discovery._write_cache("gitlab.com/acme/apm-policy", policy, project)
monkeypatch.setattr("apm_cli.core.auth.AuthResolver.try_with_fallback", _offline)
with verdict_record.recording(["install"]):
with contextlib.suppress(OSError): # the stubbed transport fails; the run goes on
discovery.discover_policy(project, expected_hash=f"sha256:{'a' * 64}")
sys.stdout.write(_OUTPUT)
verdict_record.note_verified_noop()

assert not (_home(project) / "verdicts").exists()


@pytest.mark.skipif(shutil.which("git") is None, reason="needs git")
def test_a_policy_cache_changed_after_discovery_is_never_recorded(project: Path) -> None:
"""The cache discovery read must still be the one the record keys (Copilot, #5331)."""
from apm_cli.policy import discovery
from apm_cli.policy.parser import load_policy

_hosted_project(project, "ado")
policy, _warnings = load_policy("enforcement: warn\ncache:\n ttl: 3600\n")
discovery._write_cache("dev.azure.com/acme/apm/apm-policy", policy, project)
with verdict_record.recording(["install"]):
sys.stdout.write(_OUTPUT)
verdict_record.note_verified_noop()
shutil.rmtree(project.parent / "cache" / "policy_v1")

assert not (_home(project) / "verdicts").exists()


def _cached_ado_project(project: Path) -> Path:
from apm_cli.policy import discovery
from apm_cli.policy.parser import load_policy

_hosted_project(project, "ado")
policy, _warnings = load_policy("enforcement: warn\ncache:\n ttl: 3600\n")
discovery._write_cache("dev.azure.com/acme/apm/apm-policy", policy, project)
(cached,) = (p for p in (project.parent / "cache" / "policy_v1").rglob("*.yml"))
return cached


@pytest.mark.skipif(shutil.which("git") is None, reason="needs git")
def test_a_policy_cache_rewritten_in_place_after_discovery_is_never_recorded(
project: Path,
) -> None:
"""Same size and mtime, other bytes: the cache's content is bound too."""
cached = _cached_ado_project(project)
with verdict_record.recording(["install"]):
sys.stdout.write(_OUTPUT)
verdict_record.note_verified_noop()
info = cached.stat()
data = cached.read_bytes()
cached.write_bytes(data.replace(b"warn", b"bloc"))
os.utime(cached, ns=(info.st_atime_ns, info.st_mtime_ns))

assert not (_home(project) / "verdicts").exists()


@pytest.mark.skipif(
shutil.which("git") is None or os.name == "nt" or os.geteuid() == 0,
reason="needs git and a POSIX non-root user",
)
def test_an_unreadable_policy_cache_at_entry_records_nothing_and_runs_on(
project: Path, capsys
) -> None:
"""W3d R3: a cache the snapshot cannot read never aborts the install."""
cached = _cached_ado_project(project)
cached.chmod(0)
try:
with verdict_record.recording(["install"]):
sys.stdout.write(_OUTPUT)
verdict_record.note_verified_noop()
finally:
cached.chmod(0o600)

assert capsys.readouterr().out == _OUTPUT
assert not (_home(project) / "verdicts").exists()
70 changes: 70 additions & 0 deletions tests/unit/policy/test_policy_fetch_ledger.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
"""Every org-policy fetch channel notes its attempt before its credential lookup (#5075).

The verified-state record lets a GitLab or Azure DevOps project replay a no-op
only when its run made no fetch attempt, so an attempt that fails at the
credential lookup or the transport must still be counted.
"""

from __future__ import annotations

import contextlib

import pytest

from apm_cli.core.policy_fetch_ledger import fetch_attempts
from apm_cli.policy import _gitlab, discovery
from apm_cli.policy._policy_http import policy_get

pytestmark = [pytest.mark.component, pytest.mark.promise("P-INV-I2")]


class _NoCredential(Exception):
pass


def _refuse(*_args, **_kwargs):
raise _NoCredential


def _github() -> None:
discovery._fetch_github_contents("acme/.github", "apm-policy.yml")


def _ado() -> None:
discovery._fetch_ado_contents("acme", "apm", "apm-policy", "apm-policy.yml")


def _gitlab_rest() -> None:
class _Resolver:
try_with_fallback = staticmethod(_refuse)

_gitlab._authenticated_gitlab_request(
_Resolver(),
api_url="https://gitlab.com/api/v4/projects/acme%2Fapm-policy",
host="gitlab.com",
org="acme",
port=None,
project_path="acme/apm-policy",
)


def _http() -> None:
policy_get("not a url")


@pytest.mark.parametrize(
"channel", [_github, _ado, _gitlab_rest, _http], ids=["github", "ado", "gitlab", "http"]
)
def test_a_failed_fetch_is_still_counted(monkeypatch: pytest.MonkeyPatch, channel) -> None:
monkeypatch.setattr("apm_cli.core.auth.AuthResolver.try_with_fallback", _refuse)
before = fetch_attempts()

with contextlib.suppress(Exception): # the channel's own error handling is not under test
channel()

_assert_counted(before)


def _assert_counted(before: int) -> None:
"""The ledger is the durable state the record writer reads."""
assert fetch_attempts() > before
Loading