#!/usr/bin/env python3 """Inject an attachment metadata error and verify the S3 PUT is compensated.""" import os, subprocess from pathlib import Path import boto3 from botocore.config import Config from client import Client, arguments, check, run def main(): args=arguments('Lab 4 S3/DB compensation check') c=Client(args.base_url,args.ca_file); alice,bob,eve,chat=c.bootstrap() s3=boto3.client('s3',endpoint_url=os.getenv('S3_ENDPOINT','http://rustfs:9000'),region_name=os.getenv('S3_REGION','us-east-1'),aws_access_key_id=os.environ['S3_ACCESS_KEY_ID'],aws_secret_access_key=os.environ['S3_SECRET_ACCESS_KEY'],config=Config(s3={'addressing_style':'path'})) bucket=os.getenv('S3_BUCKET','messenger-attachments') before={x['Key'] for x in s3.list_objects_v2(Bucket=bucket,Prefix='attachments/').get('Contents',[])} sql="""CREATE OR REPLACE FUNCTION lab4_reject_attachment() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN IF NEW.filename='force-db-failure.png' THEN RAISE EXCEPTION 'injected lab4 metadata failure'; END IF; RETURN NEW; END $$; CREATE TRIGGER lab4_reject_attachment BEFORE INSERT ON attachments FOR EACH ROW EXECUTE FUNCTION lab4_reject_attachment();""" conn=subprocess.run(['python','-c','import os,psycopg; c=psycopg.connect(os.environ["DATABASE_URL"]); c.execute('+repr(sql)+'); c.commit(); c.close()'],check=True,capture_output=True,text=True) try: payload=(Path(__file__).parent/'fixtures'/'sample.png').read_bytes() result=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=force-db-failure.png',503,actor=alice,raw=payload,headers={'Content-Type':'image/png'}) after={x['Key'] for x in s3.list_objects_v2(Bucket=bucket,Prefix='attachments/').get('Contents',[])} check(after==before,'S3 object remained after injected PostgreSQL insert failure') print('PASS: injected metadata failure returned 503 and compensating S3 delete left no orphan object') finally: drop="DROP TRIGGER IF EXISTS lab4_reject_attachment ON attachments; DROP FUNCTION IF EXISTS lab4_reject_attachment();" subprocess.run(['python','-c','import os,psycopg; c=psycopg.connect(os.environ["DATABASE_URL"]); c.execute('+repr(drop)+'); c.commit(); c.close()'],check=True,capture_output=True,text=True) if __name__=='__main__': run(main)