"""Capture a real APT v3 hook, always veto, and run pure validators only. Copied dpkg database/private scratch; a second guard forbids every dpkg effect. Never calls the provider hook/execute/native-acceptance or writes its handoff. """ import dataclasses import hashlib import importlib.util import json import os from pathlib import Path import subprocess import sys import tempfile def sha(data):return hashlib.sha256(data).hexdigest() def preserved(): base=Path('/var/lib/rmm-apt-transaction') paths=[Path('/var/lib/dpkg/status'),base/'bootstrap-attempt-rmm-apt-fixture-install-1.0.json'] paths.extend(p for p in (base/'active').rglob('*') if p.is_file()) return {str(p):sha(p.read_bytes()) for p in paths} def main(): os.umask(0o077) base=Path('/var/lib/rmm-apt-transaction');before=preserved() spec=importlib.util.spec_from_file_location('rmm_apt_hook_diagnostic','/usr/lib/rmm-apt-transaction/apt_transaction.py') provider=importlib.util.module_from_spec(spec);sys.modules[spec.name]=provider;spec.loader.exec_module(provider) transaction=provider.ResolvedAptTransaction.parse(json.loads((base/'active/expectation.json').read_text())) assert transaction.recipe_id=='rmm-apt-fixture-install-1.0' package=transaction.packages[0];assert sha(Path(package.archive_path).read_bytes())==package.sha256 result=dict(schema_version=1,diagnostic_only=True,transaction_executed=False,hook_always_veto=True,dpkg_effect_guard=True) with tempfile.TemporaryDirectory(prefix='rmm-apt-hook-') as temp: work=Path(temp) for name in ('empty','lists','cache','log','state','dpkg'):(work/name).mkdir(mode=0o700) (work/'dpkg/status').write_bytes(Path('/var/lib/dpkg/status').read_bytes()) collector=work/'collector';guard=work/'dpkg-guard' collector.write_text('#!/usr/bin/python3 -I\nimport os,sys,json\nfrom pathlib import Path\ntry:\n' ' data=sys.stdin.buffer.read(1048577)\n Path('+repr(str(work/'protocol'))+').write_bytes(data)\n' ' Path('+repr(str(work/'hook-env.json'))+').write_text(json.dumps({k:os.environ.get(k) for k in ("APT_HOOK_INFO_FD","DPKG_FRONTEND_LOCKED")}))\n' 'finally:\n os._exit(73)\n');collector.chmod(0o700) guard.write_text('#!/usr/bin/python3 -I\nimport os,re,sys\nfrom pathlib import Path\n' 'if len(sys.argv)==2 and (sys.argv[1] in ("--version","--print-architecture","--print-foreign-architectures") or re.fullmatch(r"--assert-[a-z0-9-]+",sys.argv[1])):\n' ' os.execve("/usr/bin/dpkg",["/usr/bin/dpkg",sys.argv[1]],dict(os.environ))\n' 'Path('+repr(str(work/'dpkg-effect-denied'))+').touch()\nsys.exit(75)\n');guard.chmod(0o700) original=(base/'active/apt.conf').read_text() text='\n'.join(line for line in original.splitlines() if not line.startswith(('DPkg::Pre-Install-Pkgs','DPkg::Tools::Options')))+'\n' text=text.replace(str(base/'active'),str(work)).replace(str(base/'log'),str(work/'log')).replace(str(base/'state'),str(work/'state')) text=text.replace('/var/lib/dpkg/status',str(work/'dpkg/status')).replace('Dir::Bin::dpkg "/usr/bin/dpkg";','Dir::Bin::dpkg "'+str(guard)+'";') text+='DPkg::Pre-Install-Pkgs { "'+str(collector)+'"; };\nDPkg::Tools::Options::'+str(collector)+'::Version "3";\nDPkg::Tools::Options::'+str(collector)+'::InfoFD "0";\n' (work/'apt.conf').write_text(text) env=dict(PATH='/usr/sbin:/usr/bin:/sbin:/bin',LC_ALL='C',HOME='/root',DEBIAN_FRONTEND='noninteractive',APT_CONFIG=str(work/'apt.conf')) with tempfile.TemporaryFile() as out,tempfile.TemporaryFile() as err: process=subprocess.run(['/usr/bin/apt-get','--yes','--no-remove','--no-install-recommends','--no-download','install','--',package.archive_path], env=env,stdin=subprocess.DEVNULL,stdout=out,stderr=err,timeout=25) result['apt_exit_code']=process.returncode result['dpkg_effect_requested']=(work/'dpkg-effect-denied').exists() result['hook_reached']=(work/'protocol').exists() if result['hook_reached']: raw=(work/'protocol').read_bytes();result['hook_env']=json.loads((work/'hook-env.json').read_text()) try: config,actions=provider.parse_protocol3(raw);result['protocol_parse']='passed' result['actions']=[dataclasses.asdict(a) for a in actions] normalized=[] for key,value in config: key=key.replace(str(collector),provider.HOOK) value=value.replace(str(collector),provider.HOOK).replace(str(guard),'/usr/bin/dpkg') value=value.replace(str(work/'dpkg/status'),'/var/lib/dpkg/status') normalized.append((key,value)) for name,function in (('config_validate',lambda:provider.check_hook_config(normalized)),('action_validate',lambda:provider.validate_actions(transaction,actions))): try:function();result[name]='passed' except provider.Veto as error:result[name]=str(error) except provider.Veto as error:result['protocol_parse']=str(error) assert process.returncode!=0 and not result['dpkg_effect_requested'] assert preserved()==before and not Path('/usr/share/rmm-mvp-test/version').exists() result['preserved_state']=True;print(json.dumps(result)) if __name__=='__main__':main()