import copy import errno import hashlib import json import os from pathlib import Path import stat import tempfile import unittest from unittest.mock import patch import archive class ArchiveTests(unittest.TestCase): def setUp(self): self.temp=tempfile.TemporaryDirectory();self.addCleanup(self.temp.cleanup);self.base=Path(self.temp.name) self.root=self.base/'project';self.destination=self.base/'archive';self.output=self.base/'restored' self.root.mkdir();self.destination.mkdir();(self.root/'sealed').mkdir() (self.root/'sealed/large.bin').write_bytes(bytes(range(256))*(archive.CHUNK//256*3)+b'end') (self.root/'sealed/run.sh').write_bytes(b'#!/bin/sh\nexit 0\n');(self.root/'sealed/run.sh').chmod(0o750) (self.root/'sealed/empty.bin').write_bytes(b'');(self.root/'sealed/empty.bin').chmod(0o400) self.selection=dict(schema='turkos-archive-selection/v1',storageClass='sealed-evidence',files=[dict(path=str(p.relative_to(self.root)),sha256=hashlib.sha256(p.read_bytes()).hexdigest())for p in sorted((self.root/'sealed').iterdir())]) self.before=self.source() def source(self):return {str(p.relative_to(self.root)):(p.read_bytes(),stat.S_IMODE(p.stat().st_mode),p.stat().st_ino)for p in (self.root/'sealed').iterdir()if p.is_file()} def backup(self,**kwargs):return archive.backup(self.root,self.selection,self.destination,require_external=False,**kwargs) def restore(self,result,**kwargs):return archive.restore(self.destination,result['archiveId'],self.output,completion_sha256=result['completionSha256'],require_external=False,**kwargs) def batch(self,result):return self.destination/archive.PREFIX/result['archiveId'] def assert_source(self):self.assertEqual(self.source(),self.before) def stop(self,event,code=errno.EIO): fired=[] def fail(kind,path,count): if kind==event and not fired and (kind!='chunk'or count>=2*archive.CHUNK):fired.append(True);raise OSError(code,'injected I/O failure') return fail def test_roundtrip_bytes_paths_permissions_and_zero_length(self): result=self.backup();restored=self.restore(result) self.assertEqual(result['status'],'ARCHIVE_COPY_VERIFIED');self.assertFalse(result['externalStorageVerified']);self.assertFalse(restored['restoredAcrossFilesystems']) for path,(data,mode,_)in self.before.items():self.assertEqual((self.output/path).read_bytes(),data);self.assertEqual(stat.S_IMODE((self.output/path).stat().st_mode),mode) self.assert_source() def test_repeated_copy_and_restore_reverify_existing_files(self): first=self.backup();second=self.backup();self.restore(first);restored=self.restore(second) self.assertEqual(second['copiedBytes'],0);self.assertEqual(second['reusedFiles'],3);self.assertEqual(restored['reusedFiles'],3);self.assert_source() def test_copy_resumes_after_connection_loss(self): with self.assertRaises(OSError):self.backup(_fault=self.stop('chunk')) self.assert_source();self.assertFalse(list(self.destination.rglob('complete.json'))) result=self.backup();self.assertGreaterEqual(result['resumedBytes'],2*archive.CHUNK);self.restore(result);self.assert_source() def test_disk_full_keeps_sources_and_no_complete_record(self): with self.assertRaises(OSError)as e:self.backup(_fault=self.stop('chunk',errno.ENOSPC)) self.assertEqual(e.exception.errno,errno.ENOSPC);self.assert_source();self.assertFalse(list(self.destination.rglob('complete.json'))) self.restore(self.backup()) def test_interrupt_after_readonly_mode_can_resume(self): with self.assertRaises(OSError):self.backup(_fault=self.stop('after-mode')) self.assertFalse(list(self.destination.rglob('complete.json')));result=self.backup();self.restore(result);self.assert_source() def test_corrupt_partial_is_rejected_without_source_change(self): with self.assertRaises(OSError):self.backup(_fault=self.stop('chunk')) partial=next(p for p in self.destination.rglob('*')if p.is_file()and p.parent.name=='partial'and p.stat().st_size>0) with partial.open('r+b')as f:f.write(b'bad') before=partial.read_bytes() with self.assertRaises(ValueError):self.backup() self.assertEqual(partial.read_bytes(),before);self.assertFalse(list(self.destination.rglob('complete.json')));self.assert_source() def test_corrupt_completed_object_is_rejected_before_restore_creation(self): result=self.backup();path=next((self.batch(result)/'objects').iterdir());path.chmod(0o600);path.write_bytes(b'broken');path.chmod(0o400) with self.assertRaises(ValueError):self.restore(result) self.assertFalse(self.output.exists());self.assert_source() def test_wrong_manifest_hash_and_traversal_rejected(self): for mutate in [lambda s:s['files'][0].update(sha256='0'*64),lambda s:s['files'][0].update(path='../outside'),lambda s:s['files'][0].update(path='/absolute'),lambda s:s['files'][0].update(path='sealed//empty.bin')]: s=copy.deepcopy(self.selection);mutate(s) with self.assertRaises((ValueError,OSError)):archive.backup(self.root,s,self.destination,require_external=False) self.assertEqual(list(self.destination.iterdir()),[]);self.assert_source() def test_duplicate_path_and_nonsealed_class_rejected(self): s=copy.deepcopy(self.selection);s['files'].append(s['files'][0]) with self.assertRaises(ValueError):archive.backup(self.root,s,self.destination,require_external=False) s=copy.deepcopy(self.selection);s['storageClass']='active-run' with self.assertRaises(ValueError):archive.backup(self.root,s,self.destination,require_external=False) self.assert_source() def test_symlink_source_and_intermediate_directory_are_refused(self): (self.root/'alias').symlink_to(self.root/'sealed',target_is_directory=True) s=copy.deepcopy(self.selection);s['files'][0]['path']='alias/empty.bin' with self.assertRaises((ValueError,OSError)):archive.backup(self.root,s,self.destination,require_external=False) (self.root/'linked.bin').symlink_to(self.root/'sealed/empty.bin');s['files'][0]['path']='linked.bin' with self.assertRaises((ValueError,OSError)):archive.backup(self.root,s,self.destination,require_external=False) self.assert_source() def test_target_partial_symlink_is_refused(self): with self.assertRaises(OSError):self.backup(_fault=self.stop('chunk')) partial=next(p for p in self.destination.rglob('*')if p.is_file()and p.parent.name=='partial'and p.stat().st_size>0) partial.unlink();partial.symlink_to(self.root/'sealed/large.bin') with self.assertRaises((ValueError,OSError)):self.backup() self.assert_source() def test_source_change_before_seal_prevents_completion(self): def change(kind,path,count): if kind=='before-seal':(self.root/'sealed/run.sh').write_bytes(b'changed by test writer') with self.assertRaises(ValueError):self.backup(_fault=change) self.assertFalse(list(self.destination.rglob('complete.json')));self.assertEqual((self.root/'sealed/run.sh').read_bytes(),b'changed by test writer') def test_existing_restore_content_is_not_overwritten(self): result=self.backup();self.restore(result);path=self.output/'sealed/run.sh';path.write_bytes(b'user content');before=path.read_bytes() with self.assertRaises(ValueError):self.restore(result) self.assertEqual(path.read_bytes(),before);self.assert_source() def test_existing_restore_permissions_are_not_silently_repaired(self): result=self.backup();self.restore(result);path=self.output/'sealed/run.sh';path.chmod(0o600) with self.assertRaises(ValueError):self.restore(result) self.assertEqual(stat.S_IMODE(path.stat().st_mode),0o600);self.assert_source() def test_unrelated_restore_directory_is_untouched(self): result=self.backup();self.output.mkdir();(self.output/'mine').write_text('keep') with self.assertRaises((ValueError,OSError)):self.restore(result) self.assertEqual(list(p.name for p in self.output.iterdir()),['mine']);self.assert_source() def test_restore_resumes_after_io_failure(self): result=self.backup() with self.assertRaises(OSError):self.restore(result,_fault=self.stop('chunk')) resumed=self.restore(result);self.assertGreaterEqual(resumed['resumedBytes'],2*archive.CHUNK);self.assert_source() def test_same_filesystem_cannot_claim_external_acceptance(self): with self.assertRaises(ValueError):archive.backup(self.root,self.selection,self.destination) result=self.backup() with self.assertRaises(ValueError):archive.restore(self.destination,result['archiveId'],self.output,completion_sha256=result['completionSha256']) self.assertFalse(self.output.exists());self.assert_source() def test_archive_cannot_be_inside_source_tree(self): target=self.root/'backup';target.mkdir() with self.assertRaises(ValueError):archive.backup(self.root,self.selection,target,require_external=False) self.assertEqual(list(target.iterdir()),[]);self.assert_source() def test_archive_writer_lock_refuses_second_writer(self): with archive.Tree(self.root)as source:plan=archive.selection_plan(source,self.selection) archive_id=archive.digest(archive.encode(plan));base=archive.PREFIX+'/'+archive_id with archive.Tree(self.destination)as target: target.mkdir(base) with target.lock(base+'/.lock'): with self.assertRaises(RuntimeError):self.backup() self.assert_source() def test_missing_completion_and_modified_plan_are_refused(self): result=self.backup();base=self.batch(result);complete=base/'complete.json';saved=complete.read_bytes();complete.unlink() with self.assertRaises(FileNotFoundError):self.restore(result) complete.write_bytes(saved);complete.chmod(0o400);plan=base/'plan.json';plan.chmod(0o600);plan.write_bytes(plan.read_bytes()+b' ');plan.chmod(0o400) with self.assertRaises(ValueError):self.restore(result) self.assertFalse(self.output.exists());self.assert_source() def test_duplicate_json_keys_and_oversized_selection_are_rejected(self): with self.assertRaises(ValueError):archive.decode(b'{"x":1,"x":2}') with self.assertRaises(ValueError):archive.decode(b' '*(archive.MAX_JSON+1)) s=copy.deepcopy(self.selection);s['files']=s['files']*(archive.MAX_FILES+1) with self.assertRaises(ValueError):archive.backup(self.root,s,self.destination,require_external=False) def test_oversized_file_is_rejected_before_reading(self): with patch.object(archive,'MAX_FILE_BYTES',1): with self.assertRaises(ValueError):self.backup() self.assert_source() def test_wrong_completion_digest_and_changed_metadata_are_refused(self): result=self.backup();wrong=dict(result,completionSha256='0'*64) with self.assertRaises(ValueError):self.restore(wrong) p=self.batch(result)/'complete.json';complete=json.loads(p.read_bytes());complete['archiveFilesystem']+=1;complete['externalStorageVerified']=True p.chmod(0o600);p.write_bytes(archive.encode(complete));p.chmod(0o400) with self.assertRaises(ValueError):self.restore(result) self.assertFalse(self.output.exists());self.assert_source() def test_hardlinked_partial_cannot_modify_source(self): with self.assertRaises(OSError):self.backup(_fault=self.stop('chunk')) partial=next(p for p in self.destination.rglob('*')if p.is_file()and p.parent.name=='partial'and p.stat().st_size>0) partial.unlink();os.link(self.root/'sealed/large.bin',partial) with self.assertRaises(ValueError):self.backup() self.assert_source() def test_recomputed_completion_hash_cannot_bind_wrong_plan(self): result=self.backup();p=self.batch(result)/'complete.json';complete=json.loads(p.read_bytes());complete['planSha256']='0'*64 p.chmod(0o600);data=archive.encode(complete);p.write_bytes(data);p.chmod(0o400) changed=dict(result,completionSha256=archive.digest(data)) with self.assertRaises(ValueError):self.restore(changed) self.assertFalse(self.output.exists());self.assert_source() def test_restore_symlink_parent_cannot_escape(self): result=self.backup();self.restore(result);outside=self.base/'outside';outside.mkdir();(outside/'mine').write_text('keep') for p in (self.output/'sealed').iterdir():p.unlink() (self.output/'sealed').rmdir();(self.output/'sealed').symlink_to(outside,target_is_directory=True) with self.assertRaises((ValueError,OSError)):self.restore(result) self.assertEqual((outside/'mine').read_text(),'keep');self.assertEqual(list(p.name for p in outside.iterdir()),['mine']);self.assert_source() if __name__=='__main__':unittest.main(verbosity=2)