#!/usr/bin/env python3 """Additional grade-4 negative and access tests. Requires running Compose stack.""" import hashlib import zlib import sys import uuid from pathlib import Path from concurrent.futures import ThreadPoolExecutor sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests")) from client import Client, check, arguments, run ROOT = Path(__file__).resolve().parents[1] def main(): args = arguments("Lab4: file validation, permissions, idempotency and isolation") c = Client(args.base_url, args.ca_file, timeout=35) alice, bob, eve, chat = c.bootstrap() file = (ROOT / "tests/fixtures/sample.png").read_bytes() path = "/api/v1/chats/" + chat["id"] upload = path + "/attachments?filename=photo.png" result = c.call("POST",upload,201,actor=alice,raw=file, headers={"Content-Type":"image/png"},schema="Attachment")["json"] obj = "/api/v1/attachments/" + result["id"] check(result["sha256"] == hashlib.sha256(file).hexdigest(),"checksum mismatch") check(c.call("GET",obj+"/content",actor=bob)["bytes"] == file,"original differs") c.call("GET",obj,404,actor=eve) c.call("GET",obj+"/content",404,actor=eve) c.call("GET","/api/v1/attachments/"+str(uuid.uuid4()),404,actor=bob) c.call("POST",upload,415,actor=alice,raw=b"not an image", headers={"Content-Type":"image/png"}) c.call("POST",upload,415,actor=alice,raw=file, headers={"Content-Type":"image/jpeg"}) c.call("POST",upload,413,actor=alice,raw=b"\0"*10485761, headers={"Content-Type":"image/png"}) huge = bytearray(file) huge[16:20] = (10000).to_bytes(4, "big") huge[20:24] = (5000).to_bytes(4, "big") huge[29:33] = (zlib.crc32(huge[12:29]) & 0xffffffff).to_bytes(4, "big") c.call("POST",upload,413,actor=alice,raw=bytes(huge), headers={"Content-Type":"image/png"}) c.call("POST",path+"/attachments?filename=..%2Fhidden.png",400,actor=alice, raw=file,headers={"Content-Type":"image/png"}) c.call("POST",path+"/attachments?filename=sample.txt",415,actor=alice, raw=file,headers={"Content-Type":"text/plain"}) second = c.call("POST","/api/v1/chats",201,actor=alice, body={"title":"Other Chat","member_ids":[alice["id"]]},schema="Chat")["json"] c.call("POST", "/api/v1/chats/"+second["id"]+"/messages",404, actor=alice,body={"text":"","attachment_ids":[result["id"]]}, headers={"Idempotency-Key":uuid.uuid4().hex}) attached = c.message(alice,chat,"",attachments=[result["id"]])["json"] check(attached["attachment_ids"] == [result["id"]],"message lost attachment") key = uuid.uuid4().hex one = c.message(alice,chat,"Фото",key=key,attachments=[result["id"]])["json"] check(c.message(alice,chat,"Фото",key=key,attachments=[result["id"]])["json"] == one, "repeated idempotency response mismatch") c.call("POST",path+"/messages",409,actor=alice, body={"text":"Фото", "attachment_ids":[]},headers={"Idempotency-Key":key}) print("PASS: private downloads, MIME spoof, corrupt image, oversize, dangerous filename, foreign chat, idempotency") if __name__ == "__main__": run(main)