test_package_archive_v2.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. from pathlib import Path
  2. import hashlib,json,subprocess,sys,zipfile
  3. import pytest
  4. from types import SimpleNamespace
  5. from tools import package_archive as a
  6. def make_base(path,payload):
  7. items=[{'path':n,'sha256':a.digest(d),'size':len(d),'role':'fixture'} for n,d in sorted(payload.items())]
  8. bid=a.digest(''.join(x['path']+'\0'+x['sha256']+'\0'+x['role']+'\n' for x in items).encode())[:12]
  9. bm=a.encode({'schema':'prod2u-base-package-manifest-v1','base_id':bid,'items':items})
  10. data={**payload,'BASE-PACKAGE-MANIFEST.json':bm,'BASE-IDENTITY.json':a.encode({'base_id':bid,'base_manifest_sha256':a.digest(bm)}),
  11. 'PACKAGE-SELF-CHECK.py':Path(a.__file__).read_bytes(),'START-HERE.zh-CN.md':b'base guide','EXCLUSIONS.json':b'{}'}
  12. files,modes=a.finalize(data,{'schema':'prod2u-package-manifest-v1','profile':'base','base_id':bid})
  13. return a.write_archive(path,files,modes)
  14. def make_current(path,base_path,desired):
  15. base=a.read_archive(base_path);bid,bmh=a.base_identity(base)
  16. old={n:d for n,d in base['files'].items() if n not in a.META}
  17. modes={n:a.mode_for(n,d) for n,d in desired.items()}
  18. changed={n:d for n,d in desired.items() if n not in old or d!=old[n] or modes[n]!=base['modes'][n]}
  19. reps=[{'path':n,'base_sha256':a.digest(old[n]),'current_sha256':a.digest(d)} for n,d in changed.items() if n in old]
  20. payload={**changed,'BASE-REQUIRED.json':a.encode({'base_id':bid,'base_manifest_sha256':bmh,'base_zip_sha256':base['sha256']}),
  21. 'OVERLAY-REPLACEMENTS.json':a.encode({'replacements':reps}),
  22. 'OVERLAY-ADDITIONS.json':a.encode({'additions':sorted(set(changed)-set(old))}),
  23. 'OVERLAY-DELETIONS.json':a.encode({'deletions':[{'path':n,'base_sha256':a.digest(d)} for n,d in old.items() if n not in desired]}),
  24. '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())]}),
  25. 'PACKAGE-SELF-CHECK.py':Path(a.__file__).read_bytes(),'START-HERE.zh-CN.md':b'current guide','EXCLUSIONS.json':b'{}'}
  26. files,pm=a.finalize(payload,{'schema':'prod2u-dual-current-manifest-v2','profile':'current','base_id':bid})
  27. return a.write_archive(path,files,pm)
  28. @pytest.fixture
  29. def pair(tmp_path):
  30. base=make_base(tmp_path/'base.zip',{'keep.txt':b'stable','change.txt':b'old','delete.txt':b'retired'})
  31. desired={'keep.txt':b'stable','change.txt':b'new','tools/run':b'#!/bin/sh\nexit 0\n'}
  32. current=make_current(tmp_path/'current.zip',base,desired)
  33. return base,current,desired
  34. def test_overlay_requires_real_base_and_preserves_both_layers(pair,tmp_path):
  35. base,current,desired=pair
  36. assert 'keep.txt' not in a.read_archive(current)['files']
  37. out=a.overlay(base,current,tmp_path/'overlay')
  38. assert not (out/'delete.txt').exists()
  39. for name,data in desired.items():assert (out/name).read_bytes()==data
  40. assert (out/'_package/base/PACKAGE-MANIFEST.json').is_file()
  41. assert (out/'_package/current/PACKAGE-MANIFEST.json').is_file()
  42. assert (out/'tools/run').stat().st_mode&0o111
  43. result=subprocess.run([sys.executable,str(out/'PACKAGE-SELF-CHECK.py')],capture_output=True,text=True)
  44. assert result.returncode==0,result.stdout+result.stderr
  45. (out/'_package/base/archive.zip').unlink()
  46. assert subprocess.run([sys.executable,str(out/'PACKAGE-SELF-CHECK.py')],capture_output=True).returncode!=0
  47. def test_current_standalone_returns_base_required(pair,tmp_path):
  48. _,current,_=pair;archive=a.read_archive(current);out=tmp_path/'current';out.mkdir()
  49. for n,d in archive['files'].items():
  50. p=out/n;p.parent.mkdir(parents=True,exist_ok=True);p.write_bytes(d);p.chmod(archive['modes'][n])
  51. assert a.standalone_check(out)==3
  52. (out/'START-HERE.zh-CN.md').write_bytes(b'tamper')
  53. with pytest.raises(ValueError,match='HASH_MISMATCH'):a.standalone_check(out)
  54. def test_wrong_base_rejected_before_output(pair,tmp_path):
  55. _,current,_=pair;wrong=make_base(tmp_path/'wrong.zip',{'keep.txt':b'wrong'})
  56. with pytest.raises(ValueError,match='BASE_ID_MISMATCH'):a.overlay(wrong,current,tmp_path/'out')
  57. assert not (tmp_path/'out').exists()
  58. def rewrite(path,edit):
  59. data=a.read_archive(path);payload={n:d for n,d in data['files'].items() if n not in ('PACKAGE-MANIFEST.json','SHA256SUMS')}
  60. edit(payload)
  61. m={k:v for k,v in data['manifest'].items() if k!='items'}
  62. files,modes=a.finalize(payload,m);new=path.with_name('changed-'+path.name);a.write_archive(new,files,modes);return new
  63. @pytest.mark.parametrize('kind',['undeclared','deletion','base_hash'])
  64. def test_invalid_overlay_declarations_rejected(pair,tmp_path,kind):
  65. base,current,_=pair
  66. def edit(payload):
  67. if kind=='undeclared':payload['OVERLAY-REPLACEMENTS.json']=a.encode({'replacements':[]})
  68. elif kind=='deletion':payload['OVERLAY-DELETIONS.json']=a.encode({'deletions':[{'path':'not-present','base_sha256':'0'*64}]})
  69. else:
  70. req=json.loads(payload['BASE-REQUIRED.json']);req['base_zip_sha256']='0'*64;payload['BASE-REQUIRED.json']=a.encode(req)
  71. changed=rewrite(current,edit)
  72. with pytest.raises(ValueError):a.overlay(base,changed,tmp_path/'out')
  73. @pytest.mark.parametrize('name',['../escape','/absolute','C:/drive','a\\b','a//b','./x','NUL.txt','x:stream'])
  74. def test_nonportable_paths_rejected(name):
  75. with pytest.raises(ValueError):a.safe_name(name)
  76. def test_changed_combined_payload_is_detected(pair,tmp_path):
  77. base,current,_=pair;out=a.overlay(base,current,tmp_path/'out');(out/'change.txt').write_bytes(b'changed later')
  78. with pytest.raises(ValueError,match='OVERLAY_CONTENT_MISMATCH'):a.check_overlay(out)
  79. def test_existing_archive_is_never_silently_replaced(pair):
  80. base,_,_=pair;before=base.read_bytes()
  81. with pytest.raises(ValueError):a.write_archive(base,{'different':b'new'})
  82. assert base.read_bytes()==before
  83. def test_windows_directory_check_does_not_invent_posix_permissions(pair,tmp_path,monkeypatch):
  84. _,current,_=pair;data=a.read_archive(current);out=tmp_path/'windows-extract';out.mkdir()
  85. for name,content in data['files'].items():
  86. path=out/name;path.parent.mkdir(parents=True,exist_ok=True);path.write_bytes(content);path.chmod(0o666)
  87. monkeypatch.setattr(a,'os',SimpleNamespace(name='nt'))
  88. assert a.standalone_check(out)==3
  89. def test_archive_permission_tamper_is_detected(pair,tmp_path):
  90. _,current,_=pair;changed=tmp_path/'mode-tamper.zip'
  91. with zipfile.ZipFile(current) as old,zipfile.ZipFile(changed,'w') as new:
  92. for info in old.infolist():
  93. if info.filename=='PACKAGE-MANIFEST.json':info.external_attr=(0o100000|0o777)<<16
  94. new.writestr(info,old.read(info.filename))
  95. with pytest.raises(ValueError,match='MODE_MISMATCH'):a.read_archive(changed)