#!/usr/bin/env python3 """Track 1: negative scenarios, expiry, and API traffic/RAM at 1 and 8 MiB.""" import hashlib import json import subprocess import time import urllib.error import urllib.request from urllib.parse import urlsplit, urlunsplit from common import Client, SAMPLE_PNG, arguments, check, run from memory_concurrent import Sampler, anon_bytes, container_read, replicas def put(upload, data, expected=200): req = urllib.request.Request(upload['url'], data=data, headers=upload['headers'], method='PUT') try: response = urllib.request.urlopen(req, timeout=60) except urllib.error.HTTPError as exc: response = exc with response: response.read() check(response.status == expected, 'S3 PUT: expected %d, got %d' % (expected, response.status)) def traffic(containers): rx = tx = 0 for container in containers: for line in container_read(container, '/proc/net/dev').splitlines(): if ':' in line and line.split(':')[0].strip() != 'lo': values = line.split(':')[1].split() rx += int(values[0]) tx += int(values[8]) return rx, tx def main(): def configure(parser): parser.add_argument('--skip-expiry', action='store_true', help='Skip real-clock expiry during a quick contract recheck') args = arguments(__doc__, configure) c = Client(args.base_url, args.ca_file, timeout=90) alice, bob, eve, chat = c.bootstrap() path = '/api/v1/chats/' + chat['id'] + '/attachments' def init(data=SAMPLE_PNG, expected=201, actor=alice, **overrides): body = dict(filename='direct.png', content_type='image/png', size_bytes=len(data), sha256=hashlib.sha256(data).hexdigest()) body.update(overrides) out = c.call('POST', path+'/direct/init', expected, actor=actor, body=body) return json.loads(out['bytes']) def complete(u, expected=201, actor=alice, target=path): return c.call('POST', target+'/direct/complete', expected, actor=actor, body={'token':u['token']}, schema='Attachment' if expected == 201 else None) started = time.monotonic() expired = init() abandoned = init() put(abandoned, SAMPLE_PNG) init(expected=401, actor=None) init(expected=404, actor=eve) init(expected=413, size_bytes=10*1024*1024+1) init(expected=400, sha256='bad') init(expected=415, content_type='image/png; charset=utf-8') init(expected=400, extra='unknown field') init(expected=400, size_bytes=True) c.call('POST', path+'/direct/complete', 400, actor=alice, body={'token':'x', 'extra':1}) c.call('POST', path+'/direct/complete', 400, actor=alice, raw=b'{"token":"x"} {}', headers={'Content-Type':'application/json'}) missing = init() complete(missing, 409) put(missing, SAMPLE_PNG) complete(missing, 404, actor=bob) # Even another member cannot complete this ticket. complete(missing, 404, actor=eve) other = c.call('POST', '/api/v1/chats', 201, actor=alice, body={'title':'other', 'member_ids':[alice['id']]}, schema='Chat')['json'] complete(missing, 404, target='/api/v1/chats/'+other['id']+'/attachments') complete(dict(missing, token='A'+missing['token'][1:]), 400) altered = dict(missing) parts = urlsplit(missing['url']) altered['url'] = urlunsplit(parts._replace(path=parts.path+'x')) put(altered, SAMPLE_PNG, 403) wrong_sum = init(sha256='0'*64) put(wrong_sum, SAMPLE_PNG) complete(wrong_sum, 400) wrong_size = init(size_bytes=len(SAMPLE_PNG)+1) # Signed content length must be enforced by the actual S3 implementation. put(wrong_size, SAMPLE_PNG, 403) invalid = init(data=b'not an image') put(invalid, b'not an image') complete(invalid, 415) good = complete(missing)['json'] check(complete(missing)['json']['id'] == good['id'], 'complete is not idempotent') put(missing, b'x'*len(SAMPLE_PNG)) downloaded = c.call('GET', '/api/v1/attachments/'+good['id']+'/content', actor=alice)['bytes'] check(downloaded == SAMPLE_PNG, 'presigned replay modified a ready attachment') print('PASS: auth, membership/owner/chat, limit, missing PUT, tampered token/key, checksum, size, invalid image, retry, overwrite protection', flush=True) containers = replicas() print('mode size_bytes api_rx_bytes api_tx_bytes anon_before_MiB anon_peak_MiB', flush=True) for size in (1024*1024, 8*1024*1024): # Same tiny image, different payload sizes: isolate buffering from decoder RAM. data = SAMPLE_PNG + b'\0'*(size-len(SAMPLE_PNG)) for mode in ('proxy', 'direct'): before_ram = max(anon_bytes(x) for x in containers) sampler = Sampler(containers) sampler.start() before = traffic(containers) try: if mode == 'proxy': c.call('POST', path+'?filename=proxy.png', 201, actor=alice, raw=data, headers={'Content-Type':'image/png'}, schema='Attachment') else: u = init(data) put(u, data) complete(u) after = traffic(containers) finally: sampler.done.set() sampler.join() peak = max(before_ram, *sampler.peak.values()) print(mode, size, after[0]-before[0], after[1]-before[1], round(before_ram/2**20,2), round(peak/2**20,2), flush=True) if args.skip_expiry: print('SKIP: real-clock expiry; run without --skip-expiry for the full check', flush=True) return print('Waiting for real signature/ticket expiration...', flush=True) time.sleep(max(0, 62-(time.monotonic()-started))) put(expired, SAMPLE_PNG, 403) time.sleep(max(0, 122-(time.monotonic()-started))) complete(abandoned, 409) print('PASS: expired PUT -> 403; abandoned upload complete after 120s -> 409; no ready metadata created', flush=True) print('Abandoned staging key (janitor after grace):', urlsplit(abandoned['url']).path, flush=True) if __name__ == '__main__': run(main)