from pathlib import Path import hashlib,json,subprocess,sys,zipfile import pytest from types import SimpleNamespace from tools import package_archive as a def make_base(path,payload): items=[{'path':n,'sha256':a.digest(d),'size':len(d),'role':'fixture'} for n,d in sorted(payload.items())] bid=a.digest(''.join(x['path']+'\0'+x['sha256']+'\0'+x['role']+'\n' for x in items).encode())[:12] bm=a.encode({'schema':'prod2u-base-package-manifest-v1','base_id':bid,'items':items}) data={**payload,'BASE-PACKAGE-MANIFEST.json':bm,'BASE-IDENTITY.json':a.encode({'base_id':bid,'base_manifest_sha256':a.digest(bm)}), 'PACKAGE-SELF-CHECK.py':Path(a.__file__).read_bytes(),'START-HERE.zh-CN.md':b'base guide','EXCLUSIONS.json':b'{}'} files,modes=a.finalize(data,{'schema':'prod2u-package-manifest-v1','profile':'base','base_id':bid}) return a.write_archive(path,files,modes) def make_current(path,base_path,desired): base=a.read_archive(base_path);bid,bmh=a.base_identity(base) old={n:d for n,d in base['files'].items() if n not in a.META} modes={n:a.mode_for(n,d) for n,d in desired.items()} changed={n:d for n,d in desired.items() if n not in old or d!=old[n] or modes[n]!=base['modes'][n]} reps=[{'path':n,'base_sha256':a.digest(old[n]),'current_sha256':a.digest(d)} for n,d in changed.items() if n in old] payload={**changed,'BASE-REQUIRED.json':a.encode({'base_id':bid,'base_manifest_sha256':bmh,'base_zip_sha256':base['sha256']}), 'OVERLAY-REPLACEMENTS.json':a.encode({'replacements':reps}), 'OVERLAY-ADDITIONS.json':a.encode({'additions':sorted(set(changed)-set(old))}), 'OVERLAY-DELETIONS.json':a.encode({'deletions':[{'path':n,'base_sha256':a.digest(d)} for n,d in old.items() if n not in desired]}), 'COMBINED-SOURCE-MANIFEST.json':a.encode({'items':[{'path':n,'sha256':a.digest(d),'size':len(d),'mode':modes[n]} for n,d in sorted(desired.items())]}), 'PACKAGE-SELF-CHECK.py':Path(a.__file__).read_bytes(),'START-HERE.zh-CN.md':b'current guide','EXCLUSIONS.json':b'{}'} files,pm=a.finalize(payload,{'schema':'prod2u-dual-current-manifest-v2','profile':'current','base_id':bid}) return a.write_archive(path,files,pm) @pytest.fixture def pair(tmp_path): base=make_base(tmp_path/'base.zip',{'keep.txt':b'stable','change.txt':b'old','delete.txt':b'retired'}) desired={'keep.txt':b'stable','change.txt':b'new','tools/run':b'#!/bin/sh\nexit 0\n'} current=make_current(tmp_path/'current.zip',base,desired) return base,current,desired def test_overlay_requires_real_base_and_preserves_both_layers(pair,tmp_path): base,current,desired=pair assert 'keep.txt' not in a.read_archive(current)['files'] out=a.overlay(base,current,tmp_path/'overlay') assert not (out/'delete.txt').exists() for name,data in desired.items():assert (out/name).read_bytes()==data assert (out/'_package/base/PACKAGE-MANIFEST.json').is_file() assert (out/'_package/current/PACKAGE-MANIFEST.json').is_file() assert (out/'tools/run').stat().st_mode&0o111 result=subprocess.run([sys.executable,str(out/'PACKAGE-SELF-CHECK.py')],capture_output=True,text=True) assert result.returncode==0,result.stdout+result.stderr (out/'_package/base/archive.zip').unlink() assert subprocess.run([sys.executable,str(out/'PACKAGE-SELF-CHECK.py')],capture_output=True).returncode!=0 def test_current_standalone_returns_base_required(pair,tmp_path): _,current,_=pair;archive=a.read_archive(current);out=tmp_path/'current';out.mkdir() for n,d in archive['files'].items(): p=out/n;p.parent.mkdir(parents=True,exist_ok=True);p.write_bytes(d);p.chmod(archive['modes'][n]) assert a.standalone_check(out)==3 (out/'START-HERE.zh-CN.md').write_bytes(b'tamper') with pytest.raises(ValueError,match='HASH_MISMATCH'):a.standalone_check(out) def test_wrong_base_rejected_before_output(pair,tmp_path): _,current,_=pair;wrong=make_base(tmp_path/'wrong.zip',{'keep.txt':b'wrong'}) with pytest.raises(ValueError,match='BASE_ID_MISMATCH'):a.overlay(wrong,current,tmp_path/'out') assert not (tmp_path/'out').exists() def rewrite(path,edit): data=a.read_archive(path);payload={n:d for n,d in data['files'].items() if n not in ('PACKAGE-MANIFEST.json','SHA256SUMS')} edit(payload) m={k:v for k,v in data['manifest'].items() if k!='items'} files,modes=a.finalize(payload,m);new=path.with_name('changed-'+path.name);a.write_archive(new,files,modes);return new @pytest.mark.parametrize('kind',['undeclared','deletion','base_hash']) def test_invalid_overlay_declarations_rejected(pair,tmp_path,kind): base,current,_=pair def edit(payload): if kind=='undeclared':payload['OVERLAY-REPLACEMENTS.json']=a.encode({'replacements':[]}) elif kind=='deletion':payload['OVERLAY-DELETIONS.json']=a.encode({'deletions':[{'path':'not-present','base_sha256':'0'*64}]}) else: req=json.loads(payload['BASE-REQUIRED.json']);req['base_zip_sha256']='0'*64;payload['BASE-REQUIRED.json']=a.encode(req) changed=rewrite(current,edit) with pytest.raises(ValueError):a.overlay(base,changed,tmp_path/'out') @pytest.mark.parametrize('name',['../escape','/absolute','C:/drive','a\\b','a//b','./x','NUL.txt','x:stream']) def test_nonportable_paths_rejected(name): with pytest.raises(ValueError):a.safe_name(name) def test_changed_combined_payload_is_detected(pair,tmp_path): base,current,_=pair;out=a.overlay(base,current,tmp_path/'out');(out/'change.txt').write_bytes(b'changed later') with pytest.raises(ValueError,match='OVERLAY_CONTENT_MISMATCH'):a.check_overlay(out) def test_existing_archive_is_never_silently_replaced(pair): base,_,_=pair;before=base.read_bytes() with pytest.raises(ValueError):a.write_archive(base,{'different':b'new'}) assert base.read_bytes()==before def test_windows_directory_check_does_not_invent_posix_permissions(pair,tmp_path,monkeypatch): _,current,_=pair;data=a.read_archive(current);out=tmp_path/'windows-extract';out.mkdir() for name,content in data['files'].items(): path=out/name;path.parent.mkdir(parents=True,exist_ok=True);path.write_bytes(content);path.chmod(0o666) monkeypatch.setattr(a,'os',SimpleNamespace(name='nt')) assert a.standalone_check(out)==3 def test_archive_permission_tamper_is_detected(pair,tmp_path): _,current,_=pair;changed=tmp_path/'mode-tamper.zip' with zipfile.ZipFile(current) as old,zipfile.ZipFile(changed,'w') as new: for info in old.infolist(): if info.filename=='PACKAGE-MANIFEST.json':info.external_attr=(0o100000|0o777)<<16 new.writestr(info,old.read(info.filename)) with pytest.raises(ValueError,match='MODE_MISMATCH'):a.read_archive(changed)