176 lines
11 KiB
Python
176 lines
11 KiB
Python
#!/usr/bin/env python3
|
|
import hashlib
|
|
from pathlib import Path
|
|
import struct
|
|
import sys
|
|
import unittest
|
|
from unittest.mock import patch
|
|
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'ops'))
|
|
import casc_local_archive as archive
|
|
from casc_asset_package import blte_uncompressed,blte_framed,blte_encoding_key
|
|
|
|
|
|
def fixture(api):
|
|
header=struct.pack('<H6BQ',7,1,0,4,5,9,30,1098437885952)
|
|
row=b'\x10'+bytes(8)+(123).to_bytes(5,'big')+struct.pack('<I',100)
|
|
data=struct.pack('<II',16,api.hashlittle(header,16,0))+header+bytes(8)+struct.pack('<II',len(row),archive._entry_hash(api,row))+row
|
|
return data+bytes(archive.INDEX_ALLOCATION-len(data))
|
|
|
|
|
|
class ArchiveTest(unittest.TestCase):
|
|
def vendor_fixture(self,entries):
|
|
page=b''.join(key+size.to_bytes(4,'big')+offset.to_bytes(4,'big')for key,size,offset in entries).ljust(4096,b'\0')
|
|
fields=bytes((1,0,0,4,4,4,16,8))+len(entries).to_bytes(4,'little')
|
|
return page+bytes(16)+fields+hashlib.md5(fields+bytes(8)).digest()[:8]
|
|
|
|
def test_vendor_index_uses_exact_keys_checked_footer_and_big_endian_archive_ranges(self):
|
|
key=bytes(range(16));raw=self.vendor_fixture([(key,51646,21526303)])
|
|
self.assertEqual(archive.vendor_archive_entry(raw,key),dict(offset=21526303,encoded_size=51646))
|
|
self.assertIsNone(archive.vendor_archive_entry(raw,b'X'*16))
|
|
for bad in (raw[:-1],raw[:-1]+bytes([raw[-1]^1]),raw[:-16]+bytes(16)):
|
|
with self.assertRaises(ValueError):archive.vendor_archive_entry(bad,key)
|
|
with self.assertRaisesRegex(ValueError,'Ambiguous'):archive.vendor_archive_entry(self.vendor_fixture([(key,1,0),(key,2,10)]),key)
|
|
with self.assertRaisesRegex(ValueError,'range bound'):archive.vendor_archive_entry(self.vendor_fixture([(key,100,0x10000000-1)]),key)
|
|
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
if not(archive.ROOT.parent/'tools/casc-tool/vendor/CascLib/src/jenkins/lookup3.c').is_file():
|
|
raise unittest.SkipTest('Local CascLib lookup3 source is not installed')
|
|
cls.api,cls.pin=archive.lookup3_api()
|
|
|
|
def test_exact_native_index_layout_and_additive_preservation(self):
|
|
api=self.api;raw=fixture(api);old=archive.parse_index(raw,1,api)
|
|
row=dict(encoding_key=b'\x01'+bytes(15),segment=66,offset=0,span_size=100)
|
|
result,audit=archive.extend_index(raw,1,[row],api)
|
|
new=archive.parse_index(result,1,api)
|
|
self.assertEqual(len(new['rows']),2);self.assertIn(old['rows'][0],new['rows'])
|
|
self.assertTrue(audit['original_entries_bit_identical'])
|
|
self.assertEqual(len(result),len(raw))
|
|
|
|
def test_native_update_reserve_grows_at_allocation_boundary(self):
|
|
api=self.api;raw=fixture(api);header=archive.parse_index(raw,1,api)['header']
|
|
# One additional entry would leave less than the native 32KiB update
|
|
# area, despite satisfying the independent CascLib sorted-entry reader.
|
|
rows=[i.to_bytes(9,'big')+bytes(5)+struct.pack('<I',100)for i in range(1819)]
|
|
entries=b''.join(rows)
|
|
raw=struct.pack('<II',16,api.hashlittle(header,16,0))+header+bytes(8)+struct.pack('<II',len(entries),archive._entry_hash(api,entries))+entries
|
|
raw=raw.ljust(archive.INDEX_ALLOCATION,b'\0')
|
|
result,audit=archive.extend_index(raw,1,[dict(encoding_key=b'\x01'+bytes(15),segment=72,offset=0,span_size=100)],api)
|
|
self.assertEqual(len(result),2*archive.INDEX_ALLOCATION)
|
|
self.assertGreaterEqual(audit['update_reserve_bytes'],archive.INDEX_UPDATE_RESERVE)
|
|
self.assertEqual(archive.parse_index(result,1,api)['rows'][:1819],rows)
|
|
self.assertFalse(any(result[40+18*1820:]))
|
|
|
|
def test_nonempty_update_area_is_rejected_instead_of_erased(self):
|
|
raw=bytearray(fixture(self.api));raw[-1]=1
|
|
with self.assertRaisesRegex(ValueError,'Nonempty native index update area'):
|
|
archive.extend_index(bytes(raw),1,[dict(encoding_key=b'\x01'+bytes(15),segment=72,offset=0,span_size=100)],self.api)
|
|
|
|
def test_invalid_bucket_collision_and_span_bounds_reject(self):
|
|
api=self.api;raw=fixture(api);row=dict(encoding_key=b'\x01'+bytes(15),segment=66,offset=0,span_size=100)
|
|
for change in(dict(encoding_key=b'\x02'+bytes(15)),dict(encoding_key=b'\x10'+bytes(15)),dict(segment=1024),dict(offset=(1<<30)-50),dict(span_size=1)):
|
|
with self.assertRaises(ValueError):archive.extend_index(raw,1,[dict(row,**change)],api)
|
|
with self.assertRaises(ValueError):archive.extend_index(raw,1,[row,row],api)
|
|
bad=bytearray(raw);bad[42]^=1
|
|
with self.assertRaisesRegex(ValueError,'entry checksum'):archive.parse_index(bytes(bad),1,api)
|
|
|
|
def existing_fixture(self):
|
|
blte,_=blte_framed([(b'candidate payload '*20,'Z')]);key=blte_encoding_key(blte)
|
|
bucket=archive.encoding_bucket(key);header=struct.pack('<H6BQ',7,bucket,0,4,5,9,30,1098437885952)
|
|
span,_=archive.archive_span(blte,64,self.api);row=key[:9]+((66<<30)|64).to_bytes(5,'big')+struct.pack('<I',len(span))
|
|
index=struct.pack('<II',16,self.api.hashlittle(header,16,0))+header+bytes(8)+struct.pack('<II',len(row),archive._entry_hash(self.api,row))+row
|
|
return blte,bucket,span,index
|
|
|
|
def test_existing_span_requires_full_exact_payload_and_preserves_index(self):
|
|
blte,bucket,span,index=self.existing_fixture();calls=[]
|
|
def read(segment,offset,size):calls.append((segment,offset,size));return span
|
|
found=archive.verified_existing_span(index,bucket,blte,read,self.api)
|
|
self.assertTrue(found['exact_bytes_verified']);self.assertEqual(calls,[(66,64,len(span))])
|
|
with self.assertRaisesRegex(ValueError,'prefix collision'):
|
|
archive.extend_index(index,bucket,[dict(encoding_key=bytes.fromhex(found['encoding_key']),segment=67,offset=0,span_size=len(span))],self.api)
|
|
|
|
def test_existing_span_rejects_truncation_full_key_and_payload_changes(self):
|
|
blte,bucket,span,index=self.existing_fixture()
|
|
for actual in (span[:-1],bytes([span[0]^1])+span[1:],span[:-1]+bytes([span[-1]^1])):
|
|
with self.assertRaisesRegex(ValueError,'different archive bytes'):
|
|
archive.verified_existing_span(index,bucket,blte,lambda *args:actual,self.api)
|
|
with self.assertRaisesRegex(ValueError,'bucket'):
|
|
archive.verified_existing_span(index,bucket^1,blte,lambda *args:span,self.api)
|
|
|
|
def test_multiple_span_proofs_validate_the_index_once_and_keep_exact_checks(self):
|
|
blte,bucket,span,index=self.existing_fixture()
|
|
with patch.object(archive,'parse_index',wraps=archive.parse_index)as parsed:
|
|
rows=archive.verified_existing_spans(index,bucket,[blte]*20,lambda *args:span,self.api)
|
|
self.assertEqual(parsed.call_count,1);self.assertEqual(len(rows),20)
|
|
self.assertTrue(all(r['exact_bytes_verified']for r in rows))
|
|
with self.assertRaisesRegex(ValueError,'different archive bytes'):
|
|
archive.verified_existing_spans(index,bucket,[blte],lambda *args:span+b'wrong',self.api)
|
|
|
|
def test_existing_indexed_prefix_header_requires_exact_payload_and_jenkins_hash(self):
|
|
blte,bucket,span,index=self.existing_fixture();key=blte_encoding_key(blte)
|
|
short=archive._archive_span_with_key(blte,64,self.api,key[:9]+bytes(7))
|
|
found=archive.verified_existing_span(index,bucket,blte,lambda *args:short,self.api)
|
|
self.assertEqual(found['archive_header_form'],'indexed-prefix-zero-tail')
|
|
self.assertTrue(found['exact_bytes_verified'])
|
|
self.assertEqual(short[30:],blte)
|
|
self.assertEqual(archive.archive_span(blte,64,self.api)[0],span)
|
|
# Include a wrong key with valid checksums, plus individually corrupted
|
|
# prefix, unused tail, size, Jenkins hash and encoded body.
|
|
badkey=bytes([key[0]^1])+key[1:9]+bytes(7)
|
|
wrong=archive._archive_span_with_key(blte,64,self.api,badkey)
|
|
variants=[wrong]
|
|
for at in (0,7,16,22,len(short)-1):
|
|
changed=bytearray(short);changed[at]^=1;variants.append(bytes(changed))
|
|
for actual in variants:
|
|
with self.subTest(header=actual[:30].hex()):
|
|
with self.assertRaisesRegex(ValueError,'different archive bytes'):
|
|
archive.verified_existing_span(index,bucket,blte,lambda *args:actual,self.api)
|
|
opaque=bytearray(short);opaque[26]^=1;opaque=bytes(opaque)
|
|
found=archive.verified_existing_span(index,bucket,blte,lambda *args:opaque,self.api)
|
|
self.assertEqual(found['opaque_header_tail_preserved'],opaque[26:30].hex())
|
|
self.assertEqual(found['existing_span_sha256'],hashlib.sha256(opaque).hexdigest())
|
|
|
|
def test_unindexed_payload_is_not_claimed_present(self):
|
|
blte,bucket,span,index=self.existing_fixture();other=None
|
|
for i in range(256):
|
|
candidate,_=blte_framed([(b'different candidate '+str(i).encode(),'N')])
|
|
if archive.encoding_bucket(blte_encoding_key(candidate))==bucket:
|
|
other=candidate;break
|
|
self.assertIsNotNone(other)
|
|
self.assertIsNone(archive.verified_existing_span(index,bucket,other,lambda *args:self.fail('Unindexed payload must not be read'),self.api))
|
|
|
|
def test_archive_span_has_full_reversed_key_and_correct_length(self):
|
|
headerless, _ = blte_uncompressed(b'actual converted equipment')
|
|
with self.assertRaisesRegex(ValueError, 'chunk table'):
|
|
archive.archive_span(headerless, 64, self.api)
|
|
blte,r=blte_framed([(b'actual converted equipment', 'N')])
|
|
span,key=archive.archive_span(blte,64,self.api)
|
|
self.assertEqual(key,hashlib.md5(blte[:36]).digest());self.assertEqual(span[:16],key[::-1])
|
|
self.assertEqual(struct.unpack_from('<I',span,16)[0],len(span))
|
|
self.assertEqual(span[30:],blte)
|
|
self.assertEqual(struct.unpack_from('<I',span,22)[0],self.api.hashlittle(span[:22],22,0x3D6BE971))
|
|
self.assertEqual(key.hex(),r['encoding_key'])
|
|
|
|
def test_framed_metadata_archive_uses_header_key_for_index_and_span(self):
|
|
blte,r=blte_framed([(b'header','N'),(b'metadata '*100,'Z')])
|
|
span,key=archive.archive_span(blte,80,self.api)
|
|
self.assertEqual(span[:16],key[::-1]);self.assertEqual(span[30:],blte)
|
|
self.assertEqual(key.hex(),r['encoding_key'])
|
|
self.assertNotEqual(key,hashlib.md5(blte).digest())
|
|
|
|
def test_rebase_moves_existing_span_and_retains_native_index_contract(self):
|
|
blte,bucket,span,index=self.existing_fixture()
|
|
moved_header=archive.relocate_archive_header(span[:30],archive.parse_index(index,bucket,self.api)['rows'][0][:9],len(span),128,self.api)
|
|
self.assertEqual(moved_header+blte,archive.archive_span(blte,128,self.api)[0])
|
|
old=archive.parse_index(index,bucket,self.api)['rows'][0]
|
|
row=old[:9]+((67<<30)|128).to_bytes(5,'big')+old[14:]
|
|
rebased,audit=archive.rebase_index_rows(index,bucket,[row],self.api)
|
|
self.assertEqual(archive.parse_index(rebased,bucket,self.api)['rows'],[row])
|
|
self.assertEqual(audit['source_rows'],audit['retained_rows'])
|
|
self.assertEqual(archive.parse_index(index,bucket,self.api)['rows'],[old])
|
|
with self.assertRaisesRegex(ValueError,'existing key-prefix multiplicities'):
|
|
archive.rebase_index_rows(index,bucket,[bytes(9)+row[9:]],self.api)
|
|
|
|
|
|
if __name__=='__main__':unittest.main()
|