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
1 change: 1 addition & 0 deletions changelog.d/4644.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- `apm install` retires the hook files a denied package deployed even when `apm.lock.yaml` is missing; edited files stay and `apm audit --ci` reports them. (#4644)
4 changes: 3 additions & 1 deletion docs/src/content/docs/reference/cli/deny.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ selected store. To lift a deny, run `apm approve <pkg>` against the same store
The next `apm install` or `apm update` stops deploying the denied package's
hooks and removes the hook entries and scripts it deployed earlier from every
harness config. Removing an approval while the gate is on has the same effect.
Until then, `apm audit --ci` reports the leftover hooks as drift.
Hook files are removed this way even when `apm.lock.yaml` is missing: APM
finds what it deployed from this machine's deployment records. Edited files
stay, and `apm audit --ci` reports them. Until then, `apm audit --ci` reports the leftover hooks as drift.
`apm install --frozen` also removes them, but cannot update `apm.lock.yaml`,
so it exits `1` naming each retired file and the decision that retired it,
or the package whose recorded decision changed. Run `apm install` without
Expand Down
5 changes: 3 additions & 2 deletions src/apm_cli/core/deployment_ledger.py
Original file line number Diff line number Diff line change
Expand Up @@ -374,12 +374,13 @@ def receipt_owner(package_info: Any) -> str:
dependency_ref = getattr(package_info, "dependency_ref", None)
return dependency_ref.get_unique_key() if dependency_ref is not None else "."

def receipt_hashes(self) -> dict[str, str]:
"""Map each receipted physical path to the hash APM wrote there (#3701)."""
def receipt_hashes(self, owner: str | None = None) -> dict[str, str]:
"""Map each receipted physical path (of *owner*, if given) to the hash APM wrote (#3701)."""
return {
physical: content_hash
for physical, key in self._physical_keys.items()
if (content_hash := self._records[key].content_hash) is not None
and (owner is None or owner in self._records[key].owners)
}

def receipt_held(self, path: Path) -> bool:
Expand Down
2 changes: 2 additions & 0 deletions src/apm_cli/install/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,8 @@ class InstallContext:
# Cleanup refusals retain the original lockfile hash, not a hash of
# user-edited bytes. Lockfile assembly consumes this after cleanup.
package_cleanup_retained: dict[str, dict[str, str | None]] = field(default_factory=dict)
# Receipted files and hashes standing in for a package the prior lock does not record.
receipted_prior_deployments: dict[str, dict[str, str]] = field(default_factory=dict)
# Managed files install kept without deployment evidence: (owner, entry) (#4360).
kept_overwrites: list[tuple[str, str]] = field(default_factory=list)
# Kept entries a pre-0.37 lock proves edited: "drift" or "blocked" (#4398).
Expand Down
57 changes: 51 additions & 6 deletions src/apm_cli/install/phases/cleanup.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Any

from apm_cli.core.deployment_ledger import DeploymentMaterializationSession
from apm_cli.core.remediation import ORPHANED_PACKAGES_PRUNE, kept_note
Expand Down Expand Up @@ -139,19 +140,21 @@ def _run_cleanup(
set(existing_lockfile.dependencies)
- partial_dropped # architecture-authority-exempt: survivor intent input, not a removal predicate
)
if existing_lockfile:
if existing_lockfile or package_deployed_files:
from apm_cli.install.manifest_reconcile import surviving_deployed_paths
from apm_cli.install.phases.targets import declared_target_profiles

# Without a prior lock the survivors are this run's claims (packages and
# root-local content); they protect them when receipts stand in.
surviving_files = surviving_deployed_paths(
existing_lockfile,
existing_lockfile or _run_local_basis(ctx),
package_deployed_files,
_targets or [],
declared_target_profiles(ctx),
desired_owners=desired_owners,
failed_owners=frozenset(
key
for key in existing_lockfile.dependencies
for key in (existing_lockfile.dependencies if existing_lockfile else ())
if diagnostics.count_for_package(key, "error") > 0
),
user_scope=user_scope,
Expand Down Expand Up @@ -243,15 +246,17 @@ def _run_cleanup(
# Complements the package-level orphan cleanup above, which handles
# packages that left the manifest entirely.
# ------------------------------------------------------------------
if existing_lockfile and package_deployed_files:
if package_deployed_files:
for dep_key, new_deployed in package_deployed_files.items():
# Skip packages whose integration reported errors this run --
# a file that failed to re-deploy would look stale and get
# wrongly deleted.
if diagnostics.count_for_package(dep_key, "error") > 0:
continue

prev_dep = existing_lockfile.get_dependency(dep_key)
prev_dep = (
existing_lockfile.get_dependency(dep_key) if existing_lockfile else None
) or _receipted_stand_in(ctx, dep_key)
if not prev_dep:
continue # new package this install -- nothing stale yet
stale = set(detect_stale_files(prev_dep.deployed_files, new_deployed))
Expand Down Expand Up @@ -327,6 +332,46 @@ def _run_cleanup(
logger.stale_cleanup(dep_key, cleanup_result)


def _run_local_basis(ctx: InstallContext) -> Any:
"""An empty prior lock carrying this run's root-local claims as survivors."""
from apm_cli.deps.lockfile import LockFile

return LockFile(local_deployed_files=list(getattr(ctx, "local_deployed_files", None) or ()))


@dataclass(frozen=True)
class _ReceiptedDeployment:
"""A package's prior deployment as this installation's receipts record it."""

deployed_files: list[str]
deployed_file_hashes: dict[str, str]


def _receipted_stand_in(ctx: InstallContext, dep_key: str) -> _ReceiptedDeployment | None:
"""Stand in for a prior lock record the lock does not hold (it was lost or regenerated).

Only for a package whose executables this run's gate withholds: its
deployment receipts here are the prior deployment, so a lost lock retires
what the gate no longer deploys like a kept one; lockfile assembly
reconciles the same record. A path this run skipped as an existing local
file is never stale. Deletion stays gated by deployment evidence.
"""
from apm_cli.security.executables import TRUST_DEPLOYED
from apm_cli.utils.diagnostics import CATEGORY_COLLISION

if getattr(ctx, "package_exec_status", {}).get(dep_key) in (None, TRUST_DEPLOYED):
return None
receipted = deployment_evidence(ctx).receipted_claims(dep_key, ctx.targets or ())
skipped = {item.message for item in ctx.diagnostics.by_category().get(CATEGORY_COLLISION, ())}
receipted = {path: digest for path, digest in receipted.items() if path not in skipped}
if not receipted:
return None
stand_ins = getattr(ctx, "receipted_prior_deployments", None)
if isinstance(stand_ins, dict):
stand_ins[dep_key] = receipted
return _ReceiptedDeployment(sorted(receipted), dict(receipted))


def _orphan_decision(
ctx: InstallContext,
desired_owners: frozenset[str],
Expand Down
6 changes: 4 additions & 2 deletions src/apm_cli/install/phases/lockfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -327,13 +327,15 @@ def _attach_deployed_files(self, lockfile: LockFile) -> None:
prior_ledger = DeploymentLedgerCodec.from_lockfile(existing)
prior_files_by_package: dict[str, list[str]] = {}
prior_hashes_by_package: dict[str, dict[str, str]] = {}
receipted = getattr(self.ctx, "receipted_prior_deployments", {})
for dep_key in lockfile.dependencies:
previous = existing.get_dependency(dep_key) if existing is not None else None
stand_in = receipted.get(dep_key, {})
prior_files_by_package[dep_key] = (
previous.deployed_files if previous is not None else []
previous.deployed_files if previous is not None else sorted(stand_in)
)
prior_hashes_by_package[dep_key] = (
previous.deployed_file_hashes if previous is not None else {}
previous.deployed_file_hashes if previous is not None else dict(stand_in)
)
from apm_cli.core.deployment_state import DeploymentReconciler

Expand Down
36 changes: 35 additions & 1 deletion src/apm_cli/integration/cleanup.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@

if TYPE_CHECKING:
from apm_cli.deps.lockfile import LockFile
from apm_cli.integration.targets import TargetProfile

AUTHORIZED = "authorized"
EDITED = "edited"
Expand Down Expand Up @@ -88,8 +89,10 @@ def __init__(
owners: Mapping[str, tuple[str, ...]] | None = None,
user_scope: bool = False,
kept: Iterable[str],
owned_receipts: Callable[[str], Mapping[str, str]] | None = None,
) -> None:
self._deploy_root = deploy_root
self._owned_receipts = owned_receipts
self.user_scope = user_scope
self._kept: frozenset[str] = frozenset()
self._kept_parents: frozenset[str] = frozenset()
Expand Down Expand Up @@ -127,8 +130,11 @@ def collect(
from apm_cli.core.scope import InstallScope

scope = InstallScope.USER if user_scope else InstallScope.PROJECT
owned_receipts = None
try:
receipts = DeploymentMaterializationSession(deploy_root, scope, None).receipt_hashes()
session = DeploymentMaterializationSession(deploy_root, scope, None)
receipts = session.receipt_hashes()
owned_receipts = session.receipt_hashes
except (OSError, ValueError) as exc:
diagnostics.warn(f"Ignored local deployment receipts: {exc}")
receipts = {}
Expand All @@ -139,6 +145,7 @@ def collect(
render=None,
user_scope=user_scope,
kept=kept,
owned_receipts=owned_receipts,
)
# Freeze the pre-transition lock: callers mutate theirs before rendering.
locked = copy.deepcopy(lockfile)
Expand All @@ -157,8 +164,35 @@ def render(owner: str | None) -> Path | None:
owners={path: tuple(keys) for path, keys in owners.items()},
user_scope=user_scope,
kept=kept,
owned_receipts=owned_receipts,
)

def receipted_claims(self, owner: str, targets: Iterable[TargetProfile]) -> dict[str, str]:
"""Map each lock value this installation receipted for *owner* to the hash APM wrote.

Stands in for a package's prior ``deployed_files`` and hashes when the
lock has no record of it (for example after the lockfile was lost), so
stale-file cleanup still retires what the package no longer deploys.
Each receipt is spelled by the canonical deployment-path codec for
*targets* (``cowork://`` for an external root), as current claims are;
a receipt no target can spell is left to the lock. Deletion stays
gated by :meth:`verdict`.
"""
from apm_cli.install.deployed_paths import deployed_path_entry
from apm_cli.utils.path_security import PathTraversalError

if self._owned_receipts is None:
return {}
targets = list(targets)
claims: dict[str, str] = {}
for physical, content_hash in sorted(self._owned_receipts(owner).items()):
try:
value = deployed_path_entry(Path(physical), self._deploy_root, targets)
except (PathTraversalError, RuntimeError, ValueError):
continue
claims[value] = content_hash
return claims

def add_rendered(self, rendered: Mapping[Path, str]) -> None:
"""Add hashes this install rendered from the source it holds (#4360).

Expand Down
140 changes: 140 additions & 0 deletions tests/integration/test_deny_retirement_without_lock_lifecycle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
"""APMLifecycle: deny retirement is the same with or without apm.lock.yaml.

PROMISE: P-INV-I4 -- a gate decision is monotonic: once a package's
executables are withheld, install retires what APM deployed for them.
A project whose lockfile was lost (not committed, deleted, regenerated)
converges exactly like one that kept it, and ``apm audit --ci`` agrees.
"""

from __future__ import annotations

import json
from pathlib import Path

import pytest
import yaml

from tests.lifecycle import driver
from tests.lifecycle.world import World
from tests.lifecycle.world.fixtures import ( # noqa: F401
_world_dir,
lifecycle_template,
lifecycle_world,
)
from tests.utils.apm_lifecycle_runner import CommandResult

pytestmark = [
pytest.mark.integration,
pytest.mark.e2e,
pytest.mark.requires_apm_binary,
pytest.mark.promise("P-INV-I4"),
pytest.mark.promise("P-INV-I3"),
]

_HOOK = Path(".github") / "hooks" / "p-gate-session.json"
_SERVER = "p-gate-mcp"
_SESSION_HOOK = {
"hooks": {"SessionStart": [{"hooks": [{"type": "command", "command": "echo p-gate"}]}]}
}


def _package(world: World) -> str:
"""A local package with one hook and one self-defined stdio MCP server."""
root = world.root / "authored" / "p-gate"
(root / ".apm" / "hooks").mkdir(parents=True)
manifest = {
"name": "p-gate",
"version": "1.0.0",
"dependencies": {
"mcp": [{"name": _SERVER, "registry": False, "transport": "stdio", "command": "p-gate"}]
},
}
(root / "apm.yml").write_text(yaml.safe_dump(manifest), encoding="utf-8")
(root / ".apm" / "hooks" / "session.json").write_text(
json.dumps(_SESSION_HOOK, indent=2) + "\n", encoding="ascii"
)
return root.as_posix()


def _evidence(result: CommandResult) -> str:
return (
f"command={result.command!r}\nexit={result.returncode}\n"
f"stdout={result.stdout!r}\nstderr={result.stderr!r}"
)


def _apm(world: World, *args: str) -> CommandResult:
return driver.run(world, list(args), entry_point=driver.driver_command("binary"))


def _ok(world: World, *args: str) -> CommandResult:
result = _apm(world, *args)
assert result.returncode == 0, _evidence(result)
return result


def _servers(world: World) -> set[str]:
path = world.project / ".mcp.json"
if not path.is_file():
return set()
return set(json.loads(path.read_text(encoding="utf-8")).get("mcpServers") or {})


def _deploy_approved(world: World) -> str:
"""Install, approve and deploy the package's hook and MCP server for copilot."""
manifest = world.project / "apm.yml"
data = yaml.safe_load(manifest.read_text(encoding="utf-8"))
data["targets"] = ["copilot"]
manifest.write_text(yaml.safe_dump(data), encoding="utf-8")
spec = _package(world)
_ok(world, "install", spec, "--trust-transitive-mcp")
_ok(world, "approve", spec)
_ok(world, "install", "--trust-transitive-mcp")
assert (world.project / _HOOK).is_file(), "the approved hook must deploy"
assert _SERVER in _servers(world), "the approved MCP server must deploy"
return spec


@pytest.mark.parametrize("lock", ["kept", "lost"])
def test_deny_retires_the_hook_with_or_without_the_lockfile(
lifecycle_world: World, # noqa: F811
lock: str,
) -> None:
world = lifecycle_world
spec = _deploy_approved(world)

_ok(world, "deny", spec)
if lock == "lost":
(world.project / "apm.lock.yaml").unlink()

_ok(world, "install", "--trust-transitive-mcp")

assert not (world.project / _HOOK).exists(), "a denied hook stays deployed"
if lock == "kept":
assert _SERVER not in _servers(world), "a denied MCP server stays deployed"
_ok(world, "install", "--trust-transitive-mcp")
assert not (world.project / _HOOK).exists()
_ok(world, "audit", "--ci")


@pytest.mark.parametrize("lock", ["kept", "lost"])
def test_deny_keeps_an_edited_hook_and_audit_names_it_with_or_without_the_lockfile(
lifecycle_world: World, # noqa: F811
lock: str,
) -> None:
"""Edited bytes are the user's: install keeps them, and audit --ci reports the file."""
world = lifecycle_world
spec = _deploy_approved(world)
hook = world.project / _HOOK
edited = hook.read_text(encoding="utf-8").replace("echo p-gate", "echo edited")
hook.write_text(edited, encoding="utf-8")

_ok(world, "deny", spec)
if lock == "lost":
(world.project / "apm.lock.yaml").unlink()
_ok(world, "install", "--trust-transitive-mcp")

assert hook.read_text(encoding="utf-8") == edited, "install must keep edited bytes"
audit = _apm(world, "audit", "--ci")
assert audit.returncode != 0, _evidence(audit)
assert _HOOK.as_posix() in audit.stdout + audit.stderr, _evidence(audit)
Loading
Loading