#!/usr/bin/env python3 """Image contract checks using synthetic fixtures and real decoding in ImageMagick.""" import hashlib import json from pathlib import Path import struct import subprocess import sys import urllib.parse import zlib ROOT=Path(__file__).resolve().parents[1] sys.path.insert(0,str(ROOT/'tests')) from client import Client,check from image_probe import jpeg_size def magick(args,data=None): r=subprocess.run([str(ROOT/'scripts/compose.sh'),'run','--rm','--no-deps','-T','--entrypoint','magick','operator']+args,input=data,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=30) check(r.returncode==0,'fixture decoder failed') return r.stdout def png(w,h,rgba): def chunk(t,b):return struct.pack('>I',len(b))+t+b+struct.pack('>I',zlib.crc32(t+b)) return b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',w,h,8,6,0,0,0))+chunk(b'IDAT',zlib.compress(b''.join(b'\0'+b''.join(bytes(rgba(x,y)) for x in range(w)) for y in range(h)) if callable(rgba) else (b'\0'+bytes(rgba)*w)*h))+chunk(b'IEND',b'') def main(): c=Client('http://localhost:18086');alice,bob,eve,chat=c.bootstrap();results=[] jpeg=magick(['png:-','jpeg:-'],png(300,150,(255,0,0,255))) # EXIF TIFF orientation 6: display rotates the stored 300x150 pixels clockwise. tiff=b'II'+struct.pack('H',len(exif)+2)+exif+jpeg[2:] for name,data,mime,dimensions in [('small',png(16,8,(255,0,0,255)),'image/png',(16,8)),('floor',png(333,100,(255,0,0,255)),'image/png',(256,76)),('alpha',png(40,20,(0,0,0,0)),'image/png',(40,20)),('orientation',oriented,'image/jpeg',(128,256)),('thin',png(1,300,(0,0,0,255)),'image/png',(1,256)),('center_crop',png(300,100,lambda x,y:(255,0,0,255) if 100<=x<200 else (0,0,255,255)),'image/png',(256,85))]: att=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename='+name,202,actor=alice,raw=data,headers={'Content-Type':mime},schema='Attachment')['json'];ready=c.wait_ready(bob,att) original=c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes'];check(original==data,'original changed') for v in ready['variants']: b=c.call('GET','/api/v1/attachments/'+att['id']+'/content?variant='+v['name'],actor=bob)['bytes'];check(hashlib.sha256(b).hexdigest()==v['sha256'],'checksum mismatch') actual=tuple(map(int,magick(['identify','-format','%w %h','-'],b).split())) check(actual==(v['width'],v['height']),'actual dimensions differ') if v['name']=='thumbnail': check(jpeg_size(b)==dimensions,'thumbnail geometry differs') if name=='alpha':check(magick(['identify','-format','%[pixel:p{0,0}]','jpeg:-'],b).strip() in (b'gray(255)',b'srgb(255,255,255)'),'alpha was not composited on white') if v['name']=='crop': check(actual==(128,128),'crop geometry differs') if name=='center_crop': import re color=tuple(map(int,re.findall(rb'\d+',magick(['identify','-format','%[pixel:p{0,0}]','jpeg:-'],b)))) check(len(color)==3 and color[0]>=250 and color[1]<=5 and color[2]<=5,'crop is not centered') check(b'Exif\0\0' not in b,'EXIF retained in derivative') c.call('GET','/api/v1/attachments/'+att['id']+'/content',404,actor=eve) results.append({'case':name,'result':'PASS','thumbnail':dimensions}) for data,mime,status in [(b'not image','image/png',415),(png(2,2,(0,0,0,255)),'image/jpeg',415),(png(2,2,(0,0,0,255))[:40],'image/png',415),(b'x'*10485761,'image/png',413)]: c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=bad',status,actor=alice,raw=data,headers={'Content-Type':mime}) (ROOT/'evidence/images.json').write_text(json.dumps({'results':results,'negative_cases':4},indent=2)+'\n');print('PASS: image geometry, EXIF, alpha, real formats, checksums, ACL and negative inputs') if __name__=='__main__':main()