import io import os from pathlib import Path import tempfile import unittest from cryptography.exceptions import InvalidTag from xessenger_r2 import EncryptedR2, MAX_BYTES class MemoryS3: def __init__(self): self.objects={} def upload_fileobj(self,file,bucket,key,ExtraArgs=None): self.objects[key]=file.read() def get_object(self,Bucket,Key): data=self.objects[Key] return {"Body":io.BytesIO(data),"ContentLength":len(data)} class StorageTests(unittest.TestCase): def setUp(self): self.store=object.__new__(EncryptedR2) self.store.master=b"a"*32 self.store.prefix="fixture/" self.store.bucket="fixture" self.store.client=MemoryS3() def test_envelope_and_authenticated_path(self): with tempfile.TemporaryDirectory() as directory: path=Path(directory)/"source";path.write_bytes(b"synthetic attachment") self.store.store("local_content/ab/cd/ef",str(path)) data=self.store.client.objects["fixture/local_content/ab/cd/ef"] self.assertEqual(data[:4],b"BM02") self.assertNotIn(b"synthetic attachment",data) with self.store.download("local_content/ab/cd/ef") as file: self.assertEqual(file.read(),b"synthetic attachment") self.store.client.objects["fixture/local_content/ab/cd/other"]=data with self.assertRaises(InvalidTag): self.store.download("local_content/ab/cd/other") self.store.client.objects["fixture/local_content/ab/cd/ef"]=data[:-1]+bytes([data[-1]^1]) with self.assertRaises(InvalidTag): self.store.download("local_content/ab/cd/ef") def test_random_nonce_and_limits(self): with tempfile.TemporaryDirectory() as directory: path=Path(directory)/"source";path.write_bytes(b"fixture") self.store.store("local_content/ab/cd/ef",str(path)) first=self.store.client.objects["fixture/local_content/ab/cd/ef"] self.store.store("local_content/ab/cd/ef",str(path)) self.assertNotEqual(first,self.store.client.objects["fixture/local_content/ab/cd/ef"]) with path.open("wb") as file: file.truncate(MAX_BYTES+1) with self.assertRaises(ValueError): self.store.store("local_content/ab/cd/big",str(path)) for path in ["../secret","/secret","local_content/../../secret"]: with self.assertRaises(ValueError): self.store.object_key(path) if __name__=="__main__":unittest.main()