forked from mtusi2026/mtusi2026lab4
94 lines
3.9 KiB
Python
94 lines
3.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Live HTTP negative checks and an actual client disconnect, without pytest."""
|
|
|
|
import argparse
|
|
from datetime import datetime, timezone
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import socket
|
|
import sys
|
|
import time
|
|
from urllib.parse import urlsplit
|
|
import uuid
|
|
|
|
from evidence_utils import exec_json, save_json
|
|
from replicas import ROOT
|
|
sys.path.insert(0, str(ROOT / 'tests'))
|
|
from client import Client, check
|
|
|
|
INVENTORY = r'''
|
|
import asyncio,json,sys
|
|
from sqlalchemy import text
|
|
from app.config import Settings
|
|
from app.db import create_engine
|
|
from app.storage import MinioStorage
|
|
p=json.load(sys.stdin)
|
|
s=Settings.from_env()
|
|
async def count():
|
|
e=create_engine(s)
|
|
try:
|
|
async with e.connect() as c:
|
|
return (await c.execute(text('SELECT count(*) FROM attachments WHERE filename=:name'), {'name':p['filename']})).scalar_one()
|
|
finally:
|
|
await e.dispose()
|
|
storage=MinioStorage(s)
|
|
try:
|
|
print(json.dumps({'matching_metadata':asyncio.run(count()),'s3_objects':sum(1 for _ in storage.client.list_objects(storage.bucket,prefix='originals/',recursive=True))}))
|
|
finally:
|
|
storage.close()
|
|
'''
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--base-url', default='http://localhost:8080')
|
|
parser.add_argument('--output', type=Path, default=ROOT / 'evidence/lab4/manual_http.json')
|
|
args = parser.parse_args()
|
|
c = Client(args.base_url, timeout=30)
|
|
alice, bob, eve, chat = c.bootstrap()
|
|
data = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
|
path = '/api/v1/chats/' + chat['id'] + '/attachments?filename=manual.png'
|
|
cases = [
|
|
('corrupt', data[:48], 'image/png', 415),
|
|
('mime_spoof', data, 'image/jpeg', 415),
|
|
('too_large', data + b'x' * (10 * 1024 * 1024), 'image/png', 413),
|
|
]
|
|
results = []
|
|
for label, raw, mime, status in cases:
|
|
reply = c.call('POST', path, status, actor=alice, raw=raw, headers={'Content-Type':mime})
|
|
results.append({'case':label, 'status':reply['status'], 'error_code':reply['json']['error']['code']})
|
|
attachment, content = c.attachment(alice, chat)
|
|
actual = c.call('GET','/api/v1/attachments/' + attachment['id'] + '/content',actor=bob)['bytes']
|
|
check(actual == content, 'manual download mismatch')
|
|
label = 'interrupted-' + uuid.uuid4().hex + '.png'
|
|
before = exec_json('api-a', INVENTORY, {'filename':label})
|
|
endpoint = urlsplit(args.base_url)
|
|
check(endpoint.scheme == 'http', 'disconnect probe requires isolated local HTTP stand')
|
|
host, port = endpoint.hostname, endpoint.port or 80
|
|
header = (
|
|
'POST /api/v1/chats/' + chat['id'] + '/attachments?filename=' + label + ' HTTP/1.1\r\n'
|
|
'Host: ' + endpoint.netloc + '\r\n'
|
|
'Authorization: Bearer ' + alice['token'] + '\r\n'
|
|
'Content-Type: image/png\r\nContent-Length: ' + str(len(data)) + '\r\n'
|
|
'Connection: close\r\n\r\n'
|
|
).encode('ascii')
|
|
with socket.create_connection((host, port), timeout=5) as connection:
|
|
connection.sendall(header + data[:1024])
|
|
time.sleep(0.2)
|
|
# Close before declared Content-Length. The server must not publish an object.
|
|
time.sleep(1)
|
|
after = exec_json('api-a', INVENTORY, {'filename':label})
|
|
check(after['matching_metadata'] == 0, 'interrupted upload persisted metadata')
|
|
check(before['s3_objects'] == after['s3_objects'], 'interrupted upload left an S3 object')
|
|
result = {'status':'PASS','at_utc':datetime.now(timezone.utc).isoformat(), 'negative_cases':results,
|
|
'original_sha256':hashlib.sha256(actual).hexdigest(), 'download_equal':True,
|
|
'disconnect':{'actual_tcp_close':True,'metadata_rows_after':0,
|
|
's3_objects_before':before['s3_objects'],'s3_objects_after':after['s3_objects']}}
|
|
save_json(args.output,result)
|
|
print('PASS: live upload/download, negative files and interrupted TCP upload')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|