diff --git a/.apm/architecture/owners/transport-auth-platform.json b/.apm/architecture/owners/transport-auth-platform.json index 49e30a07a2..bbdd110f96 100644 --- a/.apm/architecture/owners/transport-auth-platform.json +++ b/.apm/architecture/owners/transport-auth-platform.json @@ -83,6 +83,13 @@ "selectors": ["install.ps1"], "guards": ["transport-platform-windows-stable-path"] }, + { + "id": "deploy-store", + "decision": "Content-addressed store of deployed file bytes: hex-digest keys, verify on every read, no symlink following, atomic owner-only writes", + "owner": "cache/deploy_store.py (DeployStore)", + "selectors": ["src/apm_cli/cache/deploy_store.py"], + "guards": ["transport-platform-deploy-store-verified-reads"] + }, { "id": "git-cache-key-normalization", "decision": "Git repository cache-key normalization", diff --git a/changelog.d/4846.added.md b/changelog.d/4846.added.md new file mode 100644 index 0000000000..922cad76db --- /dev/null +++ b/changelog.d/4846.added.md @@ -0,0 +1 @@ +- Installs now keep a verified copy of each deployed file in the machine cache, keyed by its lockfile hash, for faster future reinstalls (#4846) diff --git a/docs/src/content/docs/reference/cli/cache.md b/docs/src/content/docs/reference/cli/cache.md index 1be8f45705..fe950736db 100644 --- a/docs/src/content/docs/reference/cli/cache.md +++ b/docs/src/content/docs/reference/cli/cache.md @@ -19,12 +19,18 @@ apm cache prune [--days N] ## Description `apm cache` groups three subcommands that operate on the local cache -root. The cache holds two independent stores: +root. The cache holds three independent stores: - **Git cache** -- bare repository databases plus per-SHA worktree checkouts, keyed by resolved commit. - **HTTP cache** -- conditional-GET responses for MCP registry endpoints. +- **Deploy store** -- the exact bytes of every file a successful install + deployed, keyed by the file's `deployed_file_hashes` digest in + `apm.lock.yaml`. Every read re-hashes the entry, and a mismatch counts + as a miss. A refused or failed install stores nothing. Entries above + 4 MiB are not stored, and when the store passes 256 MiB the least + recently used entries are evicted down to 80% of that. A fresh, integrity-verified HTTP cache hit updates only the entry directory's `mtime`. This recency marker drives LRU eviction; it does @@ -76,7 +82,7 @@ Output: ### `apm cache clean` -Remove every entry from both the git and HTTP caches. Prompts for +Remove every entry from the git cache, the HTTP cache and the deploy store. Prompts for confirmation unless a skip flag is passed. ```bash @@ -184,6 +190,7 @@ Inside the cache root: # 16 hex of # sha256(paths)) http_v1/ # conditional-GET response cache + deploy_v1/ # deployed file bytes: / ``` The `full/` and `sparse-/` subdirs let two consumers of the diff --git a/packages/apm-guide/.apm/skills/apm-usage/commands.md b/packages/apm-guide/.apm/skills/apm-usage/commands.md index 1ec694002f..6b8caff71a 100644 --- a/packages/apm-guide/.apm/skills/apm-usage/commands.md +++ b/packages/apm-guide/.apm/skills/apm-usage/commands.md @@ -562,7 +562,7 @@ drift check without starting Codex or changing native state. | Command | Purpose | Key flags | |---------|---------|-----------| | `apm cache info` | Show the cache root and counts of Git repositories, Git checkouts, and HTTP entries, plus total size | -- | -| `apm cache clean` | Remove every entry from the git and HTTP caches. If a deletion fails, it still removes every other entry, reports the affected paths, and exits nonzero; successful removals are not rolled back. Close locking processes or fix permissions, then retry. | `--force`/`-f`, `--yes`/`-y` skip the confirmation prompt only -- they do not suppress deletion failures or make the command succeed | +| `apm cache clean` | Remove every entry from the git cache, the HTTP cache and the deploy store. If a deletion fails, it still removes every other entry, reports the affected paths, and exits nonzero; successful removals are not rolled back. Close locking processes or fix permissions, then retry. | `--force`/`-f`, `--yes`/`-y` skip the confirmation prompt only -- they do not suppress deletion failures or make the command succeed | | `apm cache prune` | Remove Git checkout SHA groups not accessed within `--days`; full and sparse variants share recency and are evicted together, and `0` makes every group eligible. Partial failures exit `1`; fix permissions or release locks and rerun | `--days N` (default `30`; negative values are rejected before the cache is touched) | ## Compilation diff --git a/scripts/architecture_linter/checks/transport_cache_cleanup.py b/scripts/architecture_linter/checks/transport_cache_cleanup.py index fe8893479a..61a86f9ca6 100644 --- a/scripts/architecture_linter/checks/transport_cache_cleanup.py +++ b/scripts/architecture_linter/checks/transport_cache_cleanup.py @@ -17,7 +17,11 @@ _RULE_ID = "transport-platform-cache-cleanup-outcome" _OWNER = "src/apm_cli/cache/cleanup.py" -_CONSUMERS = ("src/apm_cli/cache/git_cache.py", "src/apm_cli/cache/http_cache.py") +_CONSUMERS = ( + "src/apm_cli/cache/git_cache.py", + "src/apm_cli/cache/http_cache.py", + "src/apm_cli/cache/deploy_store.py", +) def _check_cache_cleanup(provider: FactsProvider) -> tuple[Violation, ...]: diff --git a/scripts/architecture_linter/checks/transport_deploy_store.py b/scripts/architecture_linter/checks/transport_deploy_store.py new file mode 100644 index 0000000000..21d3aa2114 --- /dev/null +++ b/scripts/architecture_linter/checks/transport_deploy_store.py @@ -0,0 +1,64 @@ +"""Keep the deployed-file byte store behind its verifying owner.""" + +from __future__ import annotations + +import re + +from scripts.architecture_linter.checks.transport_platform_shared import ( + GROUP, + _forbid_scan, + _require_subs, + _src_python, +) +from scripts.architecture_linter.facts import FactsProvider +from scripts.architecture_linter.models import Rule, Violation + +_RULE_ID = "transport-platform-deploy-store-verified-reads" +_OWNER = "src/apm_cli/cache/deploy_store.py" + + +def _check_deploy_store(provider: FactsProvider) -> tuple[Violation, ...]: + """Only the owner addresses the bucket; it re-hashes reads and never follows links.""" + inventory = frozenset(provider.inventory) + findings: list[Violation] = [] + findings.extend( + _forbid_scan( + provider, + inventory, + _RULE_ID, + _src_python(provider, exclude={_OWNER}), + re.compile(r"[\"']deploy_v1[\"']"), + "The deploy store bucket must be addressed only through cache/deploy_store.py", + exempt=False, + ) + ) + findings.extend( + _require_subs( + provider, + inventory, + _RULE_ID, + _OWNER, + ( + "_KEY_RE.fullmatch(key)", + "os.O_RDONLY | _NOFOLLOW", + "if not stat.S_ISREG(info.st_mode)", + "if data is None or canonical_digest(data) != key:", + "tempfile.mkstemp(dir=entry.parent", + "os.replace(temp, entry)", + ), + "Deploy store reads must verify the digest and refuse links; writes stay atomic", + ) + ) + return tuple(findings) + + +RULES = ( + Rule( + id=_RULE_ID, + group=GROUP, + guard_ids=(_RULE_ID,), + description="Deployed-file bytes have one owner that verifies every read.", + check=_check_deploy_store, + ), +) +COLLECTORS: tuple[object, ...] = () diff --git a/scripts/architecture_linter/groups/transport_platform.py b/scripts/architecture_linter/groups/transport_platform.py index 29aaa6e44b..a42b7067b9 100644 --- a/scripts/architecture_linter/groups/transport_platform.py +++ b/scripts/architecture_linter/groups/transport_platform.py @@ -24,6 +24,7 @@ from scripts.architecture_linter.checks.transport_credential_value_rendering import ( RULES as _CREDENTIAL_RENDERING_RULES, ) +from scripts.architecture_linter.checks.transport_deploy_store import RULES as _DEPLOY_STORE_RULES from scripts.architecture_linter.checks.transport_egress_route import ( RULES as _EGRESS_ROUTE_RULES, ) @@ -74,6 +75,7 @@ + _EGRESS_ROUTE_RULES + _CACHE_RULES + _CLEANUP_RULES + + _DEPLOY_STORE_RULES + _SPARSE_RULES + _GITLAB_SPARSE_RULES + _REVISION_PIN_RULES diff --git a/src/apm_cli/cache/deploy_store.py b/src/apm_cli/cache/deploy_store.py new file mode 100644 index 0000000000..bd4b232013 --- /dev/null +++ b/src/apm_cli/cache/deploy_store.py @@ -0,0 +1,307 @@ +"""Content-addressed store of deployed file bytes (the deploy store). + +Every full install records each deployed file's exact bytes here, keyed by +the file's canonical content digest: the same ``sha256`` hex that the +lockfile records as its ``deployed_file_hashes`` value. A later command can +then rebuild a deployed file from the lockfile hash alone. + +The store is a cache, never a trust root: + +- Keys are exactly 64 lowercase hex characters, so a key cannot carry a path. +- Every read re-hashes the entry and rejects (and evicts) one whose bytes no + longer hash to its key; callers treat a rejection as a miss and run the + full pipeline. +- Neither the bucket directories nor the entries are followed when they are + symbolic links, and only regular files are read. +- Entries are written to an exclusive owner-only temp file and renamed into + place, so readers never see a partial entry. + +Two byte images that differ only in CRLF/LF line endings share a key (the +digest is line-ending-normalized, apm#1952); either may be the one kept. + +Size bound: an entry larger than :data:`MAX_DEPLOY_ENTRY_BYTES` is never +stored, and after a command adds entries the store evicts least recently +used entries (a verified read refreshes recency) once it exceeds +:data:`MAX_DEPLOY_STORE_BYTES`, down to 80% of it. ``apm cache clean`` +empties it; an empty store only means the next command does the full work. +""" + +from __future__ import annotations + +import contextlib +import hashlib +import os +import re +import stat +import tempfile +from pathlib import Path + +from ..core.invocation_memo import invocation_memo +from ..utils.content_hash import canonical_digest +from .paths import get_cache_root + +DEPLOY_BUCKET = "deploy_v1" +MAX_DEPLOY_STORE_BYTES = 256 * 1024 * 1024 +MAX_DEPLOY_ENTRY_BYTES = 4 * 1024 * 1024 + +_KEY_RE = re.compile(r"[0-9a-f]{64}") +_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0) +_BINARY = getattr(os, "O_BINARY", 0) +# A FIFO planted at an entry path must be a miss, not a blocked open. +_NONBLOCK = getattr(os, "O_NONBLOCK", 0) +# Windows junctions and other reparse points pass lstat as directories. +_REPARSE = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400) + + +def _is_reparse(info: os.stat_result) -> bool: + return bool(getattr(info, "st_file_attributes", 0) & _REPARSE) + + +def _oversized(entry: Path) -> bool: + try: + info = os.lstat(entry) + except OSError: + return False + return stat.S_ISREG(info.st_mode) and info.st_size > MAX_DEPLOY_ENTRY_BYTES + + +def _read_bounded(entry: Path) -> bytes | None: + """Read a regular, non-linked entry of at most the entry bound; ``None`` otherwise. + + Opens without following links and without blocking (a FIFO is refused by + the descriptor type check), and reads at most one byte past the bound so + an entry grown out of band cannot exhaust memory. + """ + try: + fd = os.open(entry, os.O_RDONLY | _NOFOLLOW | _BINARY | _NONBLOCK) + except OSError: + return None + try: + info = os.fstat(fd) + if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_DEPLOY_ENTRY_BYTES: + return None + if os.path.islink(entry) or _is_reparse(os.lstat(entry)): + return None + with os.fdopen(fd, "rb", closefd=False) as handle: + data = handle.read(MAX_DEPLOY_ENTRY_BYTES + 1) + except OSError: + return None + finally: + os.close(fd) + return data if len(data) <= MAX_DEPLOY_ENTRY_BYTES else None + + +class DeployStore: + """Read and write deployed-file bytes under ``/deploy_v1``.""" + + def __init__(self, cache_root: Path) -> None: + self._root = Path(cache_root) / DEPLOY_BUCKET + self.written = 0 + + @classmethod + def open_default(cls) -> DeployStore | None: + """Return the store in the machine cache, or ``None`` when caching is off.""" + if os.environ.get("APM_NO_CACHE", "").strip() in ("1", "true", "yes"): + return None + try: + return cls(get_cache_root()) + except (OSError, ValueError): + return None + + def _entry(self, key: str) -> Path | None: + if not isinstance(key, str) or not _KEY_RE.fullmatch(key): + return None + return self._root / key[:2] / key + + @staticmethod + def _real_dir(path: Path) -> bool: + try: + info = os.lstat(path) + except OSError: + return False + return stat.S_ISDIR(info.st_mode) and not _is_reparse(info) + + def get(self, key: str, *, raw_sha256: str | None = None) -> bytes | None: + """Return the verified bytes stored under *key*, or ``None``. + + ``None`` covers a malformed key, a missing entry, a symbolic link or + reparse point anywhere in the store path, a non-regular file and an + entry whose bytes do not hash to *key* (which is also evicted). With + *raw_sha256*, the exact bytes must also match it, so a caller that + must restore a byte-identical file never gets the other line-ending + image that shares the line-ending-normalized key. + """ + entry = self._entry(key) + if entry is None or not (self._real_dir(self._root) and self._real_dir(entry.parent)): + return None + data = _read_bounded(entry) + if data is None or canonical_digest(data) != key: + if data is not None or _oversized(entry): + with contextlib.suppress(OSError): + entry.unlink() + return None + if raw_sha256 is not None and hashlib.sha256(data).hexdigest() != raw_sha256: + return None + with contextlib.suppress(OSError): + os.utime(entry, None) + return data + + def _holds(self, entry: Path, key: str) -> bool: + """Whether the existing entry is a regular file whose bytes still hash to *key*.""" + data = _read_bounded(entry) + return data is not None and canonical_digest(data) == key + + def _prepare(self, entry: Path, size: int) -> bool | None: + """Create the bucket dirs; ``True`` if a same-size entry exists, ``None`` to refuse.""" + for directory in (self._root, entry.parent): + if not os.path.lexists(directory): + directory.mkdir(mode=0o700, parents=True, exist_ok=True) + if not self._real_dir(directory): + return None + try: + existing = os.lstat(entry) + except FileNotFoundError: + return False + # A same-size regular entry is verified before it is kept; a damaged + # or different-size one is atomically replaced. + return stat.S_ISREG(existing.st_mode) and existing.st_size == size + + def put(self, key: str, data: bytes) -> bool: + """Store *data* under *key*; return whether a usable entry is present. + + *data* must hash to *key*; a mismatch is refused and nothing is written. + """ + entry = self._entry(key) + if entry is None or len(data) > MAX_DEPLOY_ENTRY_BYTES or key != canonical_digest(data): + return False + try: + ready = self._prepare(entry, len(data)) + if ready is None: + return False + if ready and self._holds(entry, key): + return True + fd, temp = tempfile.mkstemp(dir=entry.parent, prefix=".tmp-", suffix=".part") + except OSError: + return False + try: + with os.fdopen(fd, "wb") as handle: + handle.write(data) + os.replace(temp, entry) + except OSError: + with contextlib.suppress(OSError): + os.unlink(temp) + return False + self.written += 1 + return True + + def put_file(self, key: str, path: Path) -> bool: + """Store the regular file at *path* under *key*, reading it only when needed.""" + entry = self._entry(key) + if entry is None: + return False + try: + info = os.lstat(path) + if not stat.S_ISREG(info.st_mode) or _is_reparse(info): + return False + if info.st_size > MAX_DEPLOY_ENTRY_BYTES: + return False + ready = self._prepare(entry, info.st_size) + if ready is None: + return False + if ready and self._holds(entry, key): + return True + data = path.read_bytes() + except OSError: + return False + return self.put(key, data) + + def _scan(self) -> list[tuple[float, int, str]]: + """``(mtime, size, path)`` of every key-named entry in its own real shard.""" + found: list[tuple[float, int, str]] = [] + if not self._real_dir(self._root): + return found + try: + with os.scandir(self._root) as shards: + for shard in shards: + # Windows junctions pass is_dir(follow_symlinks=False); refuse them. + if len(shard.name) != 2 or not self._real_dir(Path(shard.path)): + continue + with os.scandir(shard.path) as files: + for item in files: + if not ( + _KEY_RE.fullmatch(item.name) + and item.name.startswith(shard.name) + and item.is_file(follow_symlinks=False) + ): + continue + info = item.stat(follow_symlinks=False) + found.append((info.st_mtime, info.st_size, item.path)) + except OSError: + return [] + return found + + def get_stats(self) -> dict[str, int]: + """Entry count and total size of the stored deployed bytes.""" + entries = self._scan() + return {"entry_count": len(entries), "total_size_bytes": sum(e[1] for e in entries)} + + def enforce_size_cap(self, limit: int = MAX_DEPLOY_STORE_BYTES) -> int: + """Evict least recently used entries above *limit*, down to 80% of it; return count.""" + entries = self._scan() + total = sum(size for _mtime, size, _path in entries) + if total <= limit: + return 0 + evicted = 0 + for _mtime, size, path in sorted(entries): + if total <= limit * 0.8: + break + with contextlib.suppress(OSError): + os.unlink(path) + total -= size + evicted += 1 + return evicted + + def clean_all(self) -> list[str]: + """Remove every entry, returning details of every incomplete removal.""" + from .cleanup import clean_cache_buckets + + return clean_cache_buckets((self._root,)) + + +# Deployed files hashed during an install wait here, per command run, until +# the install commits: a refused or failed install never reaches the store. +_STAGED = "deploy-store-staged" + + +def stage(path: Path, key: str) -> None: + """Remember a deployed file for :func:`commit_staged` (no-op outside a command run).""" + staged = invocation_memo(_STAGED) + if staged is not None: + staged[str(path)] = key + + +def discard_staged() -> None: + """Forget every staged file without storing it.""" + staged = invocation_memo(_STAGED) + if staged: + staged.clear() + + +def commit_staged() -> int: + """Store every staged file now that the install committed; return how many are present. + + Each file is re-read and must still hash to its staged key, so bytes that + changed after hashing are never stored under the old digest. + """ + staged = invocation_memo(_STAGED) + if not staged: + return 0 + items = list(staged.items()) + staged.clear() + store = DeployStore.open_default() + if store is None: + return 0 + present = sum(store.put_file(key, Path(path)) for path, key in items) + if store.written: + store.enforce_size_cap() + return present diff --git a/src/apm_cli/commands/cache.py b/src/apm_cli/commands/cache.py index 8d6b0a7b2e..4c2358e31a 100644 --- a/src/apm_cli/commands/cache.py +++ b/src/apm_cli/commands/cache.py @@ -38,12 +38,21 @@ def info() -> None: http_cache = HttpCache(root) http_stats = http_cache.get_stats() - total_bytes = git_stats["total_size_bytes"] + http_stats["total_size_bytes"] + from ..cache.deploy_store import DeployStore + + deploy_stats = DeployStore(root).get_stats() + + total_bytes = ( + git_stats["total_size_bytes"] + + http_stats["total_size_bytes"] + + deploy_stats["total_size_bytes"] + ) click.echo() _rich_echo(f" Git repositories (db): {git_stats['db_count']}", symbol="list") _rich_echo(f" Git checkouts: {git_stats['checkout_count']}", symbol="list") _rich_echo(f" HTTP cache entries: {http_stats['entry_count']}", symbol="list") + _rich_echo(f" Deployed file entries: {deploy_stats['entry_count']}", symbol="list") click.echo() _rich_echo(f" Total size: {_format_size(total_bytes)}", symbol="list") _rich_echo( @@ -52,13 +61,17 @@ def info() -> None: _rich_echo( f" HTTP: {_format_size(http_stats['total_size_bytes'])}", symbol="list" ) + _rich_echo( + f" Deployed files: {_format_size(deploy_stats['total_size_bytes'])}", + symbol="list", + ) @cache.command(help="Remove all cached content") @click.option("--force", "-f", is_flag=True, help="Skip confirmation prompt") @click.option("--yes", "-y", is_flag=True, help="Skip confirmation prompt") def clean(force: bool, yes: bool) -> None: - """Remove all cache content (git repos, checkouts, HTTP responses).""" + """Remove all cache content (git repos, checkouts, HTTP responses, deployed bytes).""" from ..cache.paths import get_cache_root from ..core.command_logger import CommandLogger @@ -77,11 +90,12 @@ def clean(force: bool, yes: bool) -> None: logger.start("Cleaning cache...", symbol="gear") + from ..cache.deploy_store import DeployStore from ..cache.git_cache import GitCache from ..cache.http_cache import HttpCache failures: list[str] = [] - for cache_type in (GitCache, HttpCache): + for cache_type in (GitCache, HttpCache, DeployStore): try: failures.extend(cache_type(root).clean_all()) except OSError as exc: diff --git a/src/apm_cli/install/phases/lockfile.py b/src/apm_cli/install/phases/lockfile.py index e41962ce58..f57ab7d791 100644 --- a/src/apm_cli/install/phases/lockfile.py +++ b/src/apm_cli/install/phases/lockfile.py @@ -19,6 +19,7 @@ from pathlib import Path from typing import TYPE_CHECKING +from apm_cli.cache.deploy_store import stage as stage_deployed_bytes from apm_cli.core.scope import is_user_scope from apm_cli.install.package_resolution import effective_dependency_selection, is_implicit_local from apm_cli.install.phases.lockfile_cache_pins import ( @@ -26,7 +27,7 @@ sync_cache_pin_markers_from_disk, sync_cache_pin_markers_from_existing, ) -from apm_cli.utils.content_hash import compute_file_hash +from apm_cli.utils.content_hash import canonical_digest if TYPE_CHECKING: from apm_cli.deps.lockfile import LockFile @@ -74,10 +75,14 @@ def compute_deployed_hashes(rel_paths, project_root: Path) -> dict: else: _full = project_root / _rel if _full.is_file() and not _full.is_symlink(): - try: # noqa: SIM105 - out[_rel] = compute_file_hash(_full) - except Exception: - pass + try: + data = _full.read_bytes() + except OSError: + continue + digest = canonical_digest(data) + out[_rel] = f"sha256:{digest}" + # Stored by the deploy store only once the install commits. + stage_deployed_bytes(_full, digest) return out diff --git a/src/apm_cli/install/service.py b/src/apm_cli/install/service.py index 084041f417..3b8740bb96 100644 --- a/src/apm_cli/install/service.py +++ b/src/apm_cli/install/service.py @@ -338,6 +338,9 @@ def run(self, request: InstallRequest) -> InstallResult: # A changed local-catalog selection refuses before any script (#4639). self._verify_frozen_local_catalogs(request) runner.fire("pre-install", event) + from apm_cli.cache.deploy_store import discard_staged + + discard_staged() if request.frozen: # req-lk-006: the lockfile is never written in frozen mode. # Suppress at the chokepoint, then decide from what was @@ -364,6 +367,10 @@ def run(self, request: InstallRequest) -> InstallResult: self._enforce_frozen_no_rewrite(request, withheld, result.active_package_keys) if install_worked: + from apm_cli.cache.deploy_store import commit_staged + + # The install committed: only now may its deployed bytes enter the store. + commit_staged() post_event = self._build_event("post-install", request) if request.post_install_after_services: result.post_install = lambda: runner.fire("post-install", post_event) diff --git a/src/apm_cli/utils/content_hash.py b/src/apm_cli/utils/content_hash.py index 3a39d95f63..a427ec01e4 100644 --- a/src/apm_cli/utils/content_hash.py +++ b/src/apm_cli/utils/content_hash.py @@ -303,9 +303,12 @@ def compute_file_hash(file_path: Path) -> str: """ if not file_path.is_file() or file_path.is_symlink(): return _EMPTY_HASH - hasher = hashlib.sha256() - hasher.update(_canonical_hash_bytes(file_path.read_bytes())) - return f"sha256:{hasher.hexdigest()}" + return f"sha256:{canonical_digest(file_path.read_bytes())}" + + +def canonical_digest(raw: bytes) -> str: + """Return the hex digest :func:`compute_file_hash` records for *raw* bytes.""" + return hashlib.sha256(_canonical_hash_bytes(raw)).hexdigest() def verify_package_hash( diff --git a/tests/integration/test_architecture_owner_rule_mutations.py b/tests/integration/test_architecture_owner_rule_mutations.py index b63877920b..b19d7f11dc 100644 --- a/tests/integration/test_architecture_owner_rule_mutations.py +++ b/tests/integration/test_architecture_owner_rule_mutations.py @@ -3622,6 +3622,14 @@ class MutationCase: ), intent="apm config echoes a stored registry token outside the owner's mask.", ), + MutationCase( + guard_id="transport-platform-deploy-store-verified-reads", + rule_id="transport-platform-deploy-store-verified-reads", + path="src/apm_cli/cache/deploy_store.py", + old="if data is None or canonical_digest(data) != key:", + new="if data is None:", + intent="A deploy store read returns bytes without re-hashing them against the key.", + ), MutationCase( guard_id="transport-platform-egress-route-policy", rule_id="transport-platform-egress-route-policy", diff --git a/tests/integration/test_deploy_store_lifecycle.py b/tests/integration/test_deploy_store_lifecycle.py new file mode 100644 index 0000000000..6927b07bb3 --- /dev/null +++ b/tests/integration/test_deploy_store_lifecycle.py @@ -0,0 +1,192 @@ +"""A full install stores every deployed file's bytes under its lockfile hash. + +After ``apm install`` on the tree-10 offline mirror, each ``sha256:`` value in +the lockfile's ``deployed_file_hashes`` has a deploy-store entry whose bytes +re-hash to it, so a later command can rebuild any deployed file from the +lockfile alone. A tampered entry is a miss, and the next full install heals it. +""" + +from __future__ import annotations + +import shutil +import subprocess +from pathlib import Path + +import pytest + +from apm_cli.utils.content_hash import canonical_digest +from apm_cli.utils.yaml_io import dump_yaml, load_yaml +from tests.fixtures.perf import TREE_RECIPES, build_tree, serve_offline + +pytestmark = [ + pytest.mark.integration, + pytest.mark.e2e, + pytest.mark.requires_apm_binary, + pytest.mark.promise("P-LAW-source.ref_cache_coherent"), +] + +_BUCKET = "deploy_v1" + + +def _deployed_digests(lockfile: Path) -> set[str]: + digests: set[str] = set() + + def walk(node: object) -> None: + if isinstance(node, dict): + for key, value in node.items(): + if str(key).endswith("deployed_file_hashes") and isinstance(value, dict): + digests.update(v.removeprefix("sha256:") for v in value.values()) + else: + walk(value) + elif isinstance(node, list): + for item in node: + walk(item) + + walk(load_yaml(lockfile)) + return digests + + +def _install(apm: Path, project: Path, env: dict[str, str]) -> None: + result = subprocess.run( + [str(apm), "install"], cwd=project, env=env, capture_output=True, text=True, timeout=600 + ) + assert result.returncode == 0, result.stdout[-3000:] + result.stderr[-3000:] + + +def test_every_deployed_file_hash_has_a_verified_store_entry( + apm_binary_path: Path, tmp_path: Path +) -> None: + tree = build_tree(TREE_RECIPES["tree-10"], tmp_path / "fixture") + with serve_offline(tree, tmp_path / "world") as world: + project = tmp_path / "project" + shutil.copytree(tree.project, project) + _install(apm_binary_path, project, world.env) + store = world.cache_dir / _BUCKET + + digests = _deployed_digests(project / "apm.lock.yaml") + + assert digests, "the fixture deploys files" + for digest in sorted(digests): + entry = store / digest[:2] / digest + assert canonical_digest(entry.read_bytes()) == digest, entry + + victim = sorted(digests)[0] + entry = store / victim[:2] / victim + entry.write_bytes(entry.read_bytes() + b"\ntampered\n") + fresh = tmp_path / "fresh" + shutil.copytree(tree.project, fresh) + _install(apm_binary_path, fresh, world.env) + + assert canonical_digest(entry.read_bytes()) == victim, "a full install heals the entry" + + +# A per-install identifier that differs on every run by design. +_PER_RUN = {".apm-local/installation"} + + +def _tree(root: Path) -> dict[str, bytes]: + files = { + path.relative_to(root).as_posix(): path.read_bytes() + for path in sorted(root.rglob("*")) + if path.is_file() and ".git" not in path.parts + } + return {rel: data for rel, data in files.items() if rel not in _PER_RUN} + + +def test_an_empty_or_deleted_store_changes_nothing(apm_binary_path: Path, tmp_path: Path) -> None: + tree = build_tree(TREE_RECIPES["tree-10"], tmp_path / "fixture") + with serve_offline(tree, tmp_path / "world") as world: + with_store = tmp_path / "with-store" + shutil.copytree(tree.project, with_store) + _install(apm_binary_path, with_store, world.env) + assert any((world.cache_dir / _BUCKET).rglob("*")) + + shutil.rmtree(world.cache_dir / _BUCKET) + without_store = tmp_path / "without-store" + shutil.copytree(tree.project, without_store) + _install(apm_binary_path, without_store, world.env) + + assert _tree(without_store) == _tree(with_store) + + +def test_cache_clean_after_an_install_empties_the_store( + apm_binary_path: Path, tmp_path: Path +) -> None: + tree = build_tree(TREE_RECIPES["tree-10"], tmp_path / "fixture") + with serve_offline(tree, tmp_path / "world") as world: + project = tmp_path / "project" + shutil.copytree(tree.project, project) + _install(apm_binary_path, project, world.env) + store = world.cache_dir / _BUCKET + stored = [path for path in store.rglob("*") if path.is_file()] + assert stored + + info = subprocess.run( + [str(apm_binary_path), "cache", "info"], + cwd=project, + env=world.env, + capture_output=True, + text=True, + timeout=120, + ) + assert info.returncode == 0, info.stdout + info.stderr + assert "Deployed file entries:" in info.stdout + cleaned = subprocess.run( + [str(apm_binary_path), "cache", "clean", "--force"], + cwd=project, + env=world.env, + capture_output=True, + text=True, + timeout=120, + ) + + assert cleaned.returncode == 0, cleaned.stdout + cleaned.stderr + assert not [path for path in store.rglob("*") if path.is_file()] + + +def _cache(root: Path) -> dict[str, bytes]: + return { + path.relative_to(root).as_posix(): path.read_bytes() + for path in sorted(root.rglob("*")) + if path.is_file() + } + + +def test_a_policy_refused_install_stores_nothing(apm_binary_path: Path, tmp_path: Path) -> None: + """QL binding property: a refused install never reaches the deploy store.""" + tree = build_tree(TREE_RECIPES["tree-10"], tmp_path / "fixture") + denied = sorted(tree.packages)[0] + policy = { + "name": "deny-one", + "version": "1.0.0", + "enforcement": "block", + "dependencies": {"deny": [f"{tree.recipe.owner}/{denied}"]}, + } + with serve_offline(tree, tmp_path / "world") as world: + project = tmp_path / "project" + shutil.copytree(tree.project, project) + dump_yaml(policy, project / "org-policy.yml") + store = world.cache_dir / _BUCKET + + def refused() -> None: + result = subprocess.run( + [str(apm_binary_path), "install", "--policy", "./org-policy.yml"], + cwd=project, + env=world.env, + capture_output=True, + text=True, + timeout=600, + ) + assert result.returncode != 0, result.stdout + result.stderr + assert denied in result.stdout + result.stderr + + refused() + assert not [path for path in store.rglob("*") if path.is_file()], "cold refusal stored" + + warm = tmp_path / "warm" + shutil.copytree(tree.project, warm) + _install(apm_binary_path, warm, world.env) + before = _cache(world.cache_dir) + refused() + + assert _cache(world.cache_dir) == before, "a refused install changed the cache" diff --git a/tests/integration/test_frozen_local_path_lifecycle.py b/tests/integration/test_frozen_local_path_lifecycle.py index 0c934fb785..2ea8611034 100644 --- a/tests/integration/test_frozen_local_path_lifecycle.py +++ b/tests/integration/test_frozen_local_path_lifecycle.py @@ -9,6 +9,7 @@ import pytest +from apm_cli.utils.content_hash import canonical_digest from apm_cli.utils.yaml_io import dump_yaml, load_yaml from tests.utils.apm_lifecycle_runner import ApmLifecycleRunner from tests.utils.isolated_apm_environment import IsolatedApmEnvironment @@ -130,11 +131,19 @@ def assert_rejected_without_mutation() -> None: assert accepted_lock != locked_bytes accepted_deployment = deployed.read_bytes() assert b"accepted change" in accepted_deployment + accepted_cache = _snapshot(isolated.cache_root) replay = run(consumer.root, "install", "--frozen", "--no-policy") assert replay.returncode == 0, replay.stdout + replay.stderr assert lockfile.read_bytes() == accepted_lock assert deployed.read_bytes() == accepted_deployment - assert _snapshot(isolated.cache_root) == before_cache + after_cache = _snapshot(isolated.cache_root) + assert after_cache == accepted_cache, "a no-op frozen replay stores nothing new" + added = {path: data for path, data in after_cache.items() if path not in before_cache} + assert {path: after_cache[path] for path in before_cache} == before_cache + # Only the committed accepted install may add cache content: deploy-store + # entries named by the digest of the bytes they hold, among them the new deployment. + assert all(path == _store_path(data) for path, data in added.items()), sorted(added) + assert _store_path(accepted_deployment) in added @pytest.mark.parametrize("transitive", [False, True], ids=["direct", "transitive"]) @@ -194,6 +203,11 @@ def test_frozen_local_declared_deleted_source_is_rejected_without_mutation( assert not list(isolated.temp_root.iterdir()) +def _store_path(data: bytes) -> str: + digest = canonical_digest(data) + return f"deploy_v1/{digest[:2]}/{digest}" + + def _snapshot(root: Path) -> dict[str, bytes]: """Read independent byte evidence for all managed files and cached packages.""" return { diff --git a/tests/unit/cache/test_deploy_store.py b/tests/unit/cache/test_deploy_store.py new file mode 100644 index 0000000000..f4a09d6a50 --- /dev/null +++ b/tests/unit/cache/test_deploy_store.py @@ -0,0 +1,300 @@ +"""The deploy store keeps deployed bytes by canonical digest and verifies every read.""" + +from __future__ import annotations + +import hashlib +import os +import stat +import sys +from pathlib import Path + +import pytest + +from apm_cli.cache.deploy_store import ( + DEPLOY_BUCKET, + MAX_DEPLOY_ENTRY_BYTES, + DeployStore, +) +from apm_cli.utils.content_hash import canonical_digest, compute_file_hash + +pytestmark = [pytest.mark.unit, pytest.mark.promise("P-LAW-source.ref_cache_coherent")] + +_TEXT = b"---\ndescription: demo\n---\nDo the thing.\n" + + +def _store(tmp_path: Path) -> tuple[DeployStore, Path]: + return DeployStore(tmp_path / "cache"), tmp_path / "cache" / DEPLOY_BUCKET + + +def test_the_key_is_the_lockfile_hash_of_the_deployed_file(tmp_path: Path) -> None: + deployed = tmp_path / "AGENTS.md" + deployed.write_bytes(b"line one\r\nline two\r\n") + key = canonical_digest(deployed.read_bytes()) + + assert compute_file_hash(deployed) == f"sha256:{key}" + + +def test_a_stored_entry_reads_back_verified(tmp_path: Path) -> None: + store, root = _store(tmp_path) + key = canonical_digest(_TEXT) + + assert store.put(key, _TEXT) + assert store.get(key) == _TEXT + entry = root / key[:2] / key + assert entry.read_bytes() == _TEXT + if sys.platform != "win32": + assert stat.S_IMODE(entry.stat().st_mode) == 0o600 + assert [p.name for p in entry.parent.iterdir()] == [key], "no temp file is left behind" + + +def test_a_tampered_entry_is_rejected_and_evicted_on_read(tmp_path: Path) -> None: + store, root = _store(tmp_path) + key = canonical_digest(_TEXT) + store.put(key, _TEXT) + entry = root / key[:2] / key + entry.write_bytes(_TEXT + b"injected\n") + + assert store.get(key) is None + assert not entry.exists() + assert store.put(key, _TEXT) and store.get(key) == _TEXT, "the next full install heals it" + + +def test_bytes_that_do_not_hash_to_the_key_are_never_stored(tmp_path: Path) -> None: + store, root = _store(tmp_path) + key = hashlib.sha256(b"something else").hexdigest() + + assert not store.put(key, _TEXT) + assert not (root / key[:2] / key).exists() + + +@pytest.mark.parametrize( + "key", ["../../etc/passwd", "AB" * 32, "ab" * 31, "ab" * 32 + "\n", "g" * 64, ""] +) +def test_a_key_that_is_not_a_lowercase_hex_digest_is_refused(tmp_path: Path, key: str) -> None: + store, root = _store(tmp_path) + + assert not store.put(key, _TEXT) + assert store.get(key) is None + assert not root.exists() + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX symlinks") +def test_a_linked_entry_or_bucket_is_never_followed(tmp_path: Path) -> None: + store, root = _store(tmp_path) + key = canonical_digest(_TEXT) + outside = tmp_path / "outside" + outside.mkdir() + (outside / key).write_bytes(_TEXT) + root.mkdir(parents=True) + (root / key[:2]).symlink_to(outside, target_is_directory=True) + + assert store.get(key) is None + assert not store.put(key, _TEXT) + + (root / key[:2]).unlink() + (root / key[:2]).mkdir() + (root / key[:2] / key).symlink_to(outside / key) + assert store.get(key) is None + assert (outside / key).read_bytes() == _TEXT, "the link target is untouched" + + +def test_a_directory_in_place_of_an_entry_is_not_read(tmp_path: Path) -> None: + store, root = _store(tmp_path) + key = canonical_digest(_TEXT) + (root / key[:2] / key).mkdir(parents=True) + + assert store.get(key) is None + assert (root / key[:2] / key).is_dir() + + +def test_no_store_without_a_cache(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + monkeypatch.setenv("APM_NO_CACHE", "1") + assert DeployStore.open_default() is None + monkeypatch.delenv("APM_NO_CACHE") + monkeypatch.setenv("APM_CACHE_DIR", str(tmp_path / "c")) + store = DeployStore.open_default() + key = canonical_digest(_TEXT) + assert store is not None and store.put(key, _TEXT) + assert (tmp_path / "c" / DEPLOY_BUCKET / key[:2] / key).read_bytes() == _TEXT + + +def test_an_exact_byte_reader_never_gets_the_other_line_ending_image(tmp_path: Path) -> None: + store, root = _store(tmp_path) + crlf = _TEXT.replace(b"\n", b"\r\n") + key = canonical_digest(_TEXT) + assert canonical_digest(crlf) == key + store.put(key, crlf) + + assert store.get(key) == crlf + assert store.get(key, raw_sha256=hashlib.sha256(_TEXT).hexdigest()) is None + assert store.get(key, raw_sha256=hashlib.sha256(crlf).hexdigest()) == crlf + assert (root / key[:2] / key).read_bytes() == crlf, "a raw mismatch is a miss, not an eviction" + + +@pytest.mark.parametrize("value", ["0", "false", ""]) +def test_the_store_follows_the_cache_root_no_cache_parsing( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, value: str +) -> None: + monkeypatch.setenv("APM_NO_CACHE", value) + monkeypatch.setenv("APM_CACHE_DIR", str(tmp_path / "c")) + store = DeployStore.open_default() + key = canonical_digest(_TEXT) + + assert store is not None and store.put(key, _TEXT) + assert (tmp_path / "c" / DEPLOY_BUCKET / key[:2] / key).read_bytes() == _TEXT + + +def test_deployed_bytes_wait_for_the_install_to_commit( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from apm_cli.cache.deploy_store import commit_staged, discard_staged, stage + from apm_cli.core.invocation_memo import invocation_scope + + monkeypatch.setenv("APM_CACHE_DIR", str(tmp_path / "c")) + deployed = tmp_path / "AGENTS.md" + deployed.write_bytes(_TEXT) + key = canonical_digest(_TEXT) + entry = tmp_path / "c" / DEPLOY_BUCKET / key[:2] / key + + stage(deployed, key) + assert commit_staged() == 0, "outside a command run nothing is staged" + with invocation_scope(): + stage(deployed, key) + assert not entry.exists(), "hashing alone stores nothing" + discard_staged() + assert commit_staged() == 0 + stage(deployed, key) + assert commit_staged() == 1 + assert entry.read_bytes() == _TEXT + + +def test_bytes_that_changed_after_hashing_are_not_stored( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from apm_cli.cache.deploy_store import commit_staged, stage + from apm_cli.core.invocation_memo import invocation_scope + + monkeypatch.setenv("APM_CACHE_DIR", str(tmp_path / "c")) + deployed = tmp_path / "AGENTS.md" + deployed.write_bytes(_TEXT) + key = canonical_digest(_TEXT) + with invocation_scope(): + stage(deployed, key) + deployed.write_bytes(_TEXT + b"changed after hashing\n") + assert commit_staged() == 0 + assert not (tmp_path / "c" / DEPLOY_BUCKET / key[:2] / key).exists() + + +def test_the_store_evicts_least_recently_used_entries_above_its_bound(tmp_path: Path) -> None: + store, root = _store(tmp_path) + blobs = [f"entry {n}\n".encode() * 100 for n in range(5)] + keys = [canonical_digest(blob) for blob in blobs] + for age, (key, blob) in enumerate(zip(keys, blobs, strict=True)): + store.put(key, blob) + os.utime(root / key[:2] / key, (1000 + age, 1000 + age)) + store.get(keys[0]) # a verified read refreshes recency + limit = sum(len(blob) for blob in blobs[:3]) + + assert store.enforce_size_cap(limit) == 3 + kept = {path.name for path in root.rglob("*") if path.is_file()} + assert kept == {keys[0], keys[4]} + + +def test_an_entry_above_the_entry_bound_is_never_stored(tmp_path: Path) -> None: + store, root = _store(tmp_path) + big = b"x" * (MAX_DEPLOY_ENTRY_BYTES + 1) + key = canonical_digest(big) + source = tmp_path / "big.bin" + source.write_bytes(big) + + assert not store.put(key, big) + assert not store.put_file(key, source) + assert not (root / key[:2] / key).exists() + + +def test_cache_clean_empties_the_store(tmp_path: Path) -> None: + store, root = _store(tmp_path) + key = canonical_digest(_TEXT) + store.put(key, _TEXT) + + assert store.clean_all() == [] + assert list(root.iterdir()) == [] + assert DeployStore(tmp_path / "never-used").clean_all() == [] + + +@pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="POSIX FIFOs") +def test_a_fifo_at_an_entry_path_is_a_miss_not_a_hang(tmp_path: Path) -> None: + store, root = _store(tmp_path) + key = canonical_digest(_TEXT) + (root / key[:2]).mkdir(parents=True) + os.mkfifo(root / key[:2] / key) + + assert store.get(key) is None + assert stat.S_ISFIFO(os.lstat(root / key[:2] / key).st_mode), "the FIFO was only refused" + + +def test_a_same_size_tampered_entry_is_healed_by_the_next_store(tmp_path: Path) -> None: + store, root = _store(tmp_path) + key = canonical_digest(_TEXT) + store.put(key, _TEXT) + entry = root / key[:2] / key + entry.write_bytes(bytes(reversed(_TEXT))) # same length, other bytes + + assert store.put(key, _TEXT) + assert entry.read_bytes() == _TEXT + entry.write_bytes(bytes(reversed(_TEXT))) + source = tmp_path / "deployed.md" + source.write_bytes(_TEXT) + assert store.put_file(key, source) + assert entry.read_bytes() == _TEXT + + +def test_same_length_bytes_for_another_digest_are_refused(tmp_path: Path) -> None: + store, root = _store(tmp_path) + key = canonical_digest(_TEXT) + store.put(key, _TEXT) + + assert not store.put(key, bytes(reversed(_TEXT))) + assert (root / key[:2] / key).read_bytes() == _TEXT + + +def test_an_entry_grown_past_the_bound_is_a_miss_and_evicted(tmp_path: Path) -> None: + store, root = _store(tmp_path) + key = canonical_digest(_TEXT) + store.put(key, _TEXT) + entry = root / key[:2] / key + with entry.open("ab") as handle: + handle.truncate(MAX_DEPLOY_ENTRY_BYTES + 1) + + assert store.get(key) is None + assert not entry.exists() + + +def test_eviction_touches_only_key_named_entries_in_their_shard(tmp_path: Path) -> None: + store, root = _store(tmp_path) + key = canonical_digest(_TEXT) + store.put(key, _TEXT) + shard = root / key[:2] + strays = [shard / ".tmp-abc.part", shard / "notes.txt", root / "ff" / key] + for stray in strays: + stray.parent.mkdir(parents=True, exist_ok=True) + stray.write_bytes(b"x" * 4096) + + assert store.get_stats() == {"entry_count": 1, "total_size_bytes": len(_TEXT)} + assert store.enforce_size_cap(limit=1) == 1 + assert not (shard / key).exists() + assert all(stray.read_bytes() == b"x" * 4096 for stray in strays) + + +@pytest.mark.skipif(sys.platform == "win32", reason="POSIX symlinks") +def test_eviction_never_follows_a_linked_shard(tmp_path: Path) -> None: + store, root = _store(tmp_path) + key = canonical_digest(_TEXT) + outside = tmp_path / "outside" + outside.mkdir() + (outside / key).write_bytes(_TEXT) + root.mkdir(parents=True) + (root / key[:2]).symlink_to(outside, target_is_directory=True) + + assert store.enforce_size_cap(limit=0) == 0 + assert (outside / key).read_bytes() == _TEXT diff --git a/tests/unit/scripts/test_architecture_runner.py b/tests/unit/scripts/test_architecture_runner.py index 923c7c710d..5c133dddbc 100644 --- a/tests/unit/scripts/test_architecture_runner.py +++ b/tests/unit/scripts/test_architecture_runner.py @@ -846,6 +846,7 @@ def exiting_import( transport-platform-credential-origin-scope transport-platform-credential-report-owner transport-platform-credential-value-rendering +transport-platform-deploy-store-verified-reads transport-platform-egress-route-policy transport-platform-git-cache-identity transport-platform-git-child-environment