"""Run additional HTTPS ACL, expiry, size and login rate checks.""" import base64 import hashlib import os from pathlib import Path import ssl import subprocess import sys import urllib.error import urllib.request import uuid sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests')) from client import Client, arguments, check, run def expire(actor): digest = hashlib.sha256(actor['token'].encode()).hexdigest() sql = f"UPDATE sessions SET expires_at=now()-interval '1 second' WHERE token_hash='{digest}';\n" result = subprocess.run( ['docker', 'compose', 'exec', '-T', 'postgres', 'psql', '-v', 'ON_ERROR_STOP=1', '-U', 'db_operator', '-d', 'messenger'], cwd=Path(__file__).resolve().parents[1], input=sql, text=True, capture_output=True) check(result.returncode == 0 and 'UPDATE 1' in result.stdout, 'could not expire synthetic session') def hostname(ca): context = ssl.create_default_context(cafile=ca) try: with urllib.request.urlopen('https://127.0.0.1:8443/health/live', context=context, timeout=5): pass except urllib.error.URLError as exc: check(isinstance(exc.reason, ssl.SSLCertVerificationError), 'wrong hostname failed for a non-TLS reason') check(exc.reason.verify_code in (62, 64), 'certificate error was not a SAN/hostname mismatch') else: check(False, 'unexpected success using IP outside certificate SAN') def main(): args = arguments(__doc__) ca = args.ca_file or os.environ.get('CA_FILE', 'secrets/ca/ca.crt') client = Client(args.base_url, ca) client.call('GET', '/health/ready', schema='Health') hostname(ca) alice, _, eve, chat = client.bootstrap() attachment, _ = client.attachment(alice, chat) attachment = client.wait_ready(alice, attachment) path = '/api/v1/attachments/' + attachment['id'] spoofed = {'X-User-Id': alice['id']} client.call('GET', path, 404, actor=eve, headers=spoofed) client.call('GET', path + '/content', 404, actor=eve, headers=spoofed) own_chat = client.call('POST', '/api/v1/chats', 201, actor=eve, body={'title': 'ACL probe', 'member_ids': [eve['id']]}, schema='Chat')['json'] client.call('POST', '/api/v1/chats/' + own_chat['id'] + '/messages', 404, actor=eve, body={'text': '', 'attachment_ids': [attachment['id']]}, headers={'Idempotency-Key': uuid.uuid4().hex}) client.call('POST', '/api/v1/users', 413, raw=b' ' * 65537, headers={'Content-Type': 'application/json'}) upload = '/api/v1/chats/' + chat['id'] + '/attachments?filename=oversize.png' client.call('POST', upload, 413, actor=alice, raw=b'x' * (10 * 1024 * 1024 + 1), headers={'Content-Type': 'image/png'}) client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=eve) client.call('GET', '/api/v1/users/me', 401, actor=eve) expire(alice) client.call('GET', '/api/v1/users/me', 401, actor=alice) authorization = 'Basic ' + base64.b64encode(b'unknown:synthetic-password').decode() for _ in range(31): response = client.call('POST', '/api/v1/auth/sessions', (401, 429), headers={'Authorization': authorization}) if response['status'] == 429: wait = int(response['headers'].get('Retry-After', '0')) check(1 <= wait <= 60, 'invalid Retry-After') break else: check(False, 'login limiter never returned 429') print('PASS: hostname, attachment ACL/spoof, 413, logout, expired session, 429 and Retry-After') if __name__ == '__main__': run(main)