forked from mtusi2026/mtusi2026lab7
88 lines
4.4 KiB
Python
88 lines
4.4 KiB
Python
#!/usr/bin/env python3
|
|
import base64
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
import ssl
|
|
import socket
|
|
from urllib.parse import urlsplit
|
|
import sys
|
|
import time
|
|
from collections import Counter
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
|
from client import Client, ROOT, arguments, check, run
|
|
from worker_compromise import sql
|
|
|
|
CA = ROOT / 'secrets/tls/service-ca/ca.crt'
|
|
|
|
|
|
def main():
|
|
args = arguments('TLS, ACL, Argon2id и сессии')
|
|
c = Client(args.base_url, args.ca_file or CA)
|
|
alice, bob, eve, chat = c.bootstrap()
|
|
att, _ = c.attachment(alice, chat)
|
|
c.wait_ready(alice, att)
|
|
path = '/api/v1/attachments/' + att['id']
|
|
for suffix in ('', '/content'):
|
|
c.call('GET', path + suffix, 404, actor=eve, headers={'X-User-Id': alice['id']})
|
|
own = c.call('POST', '/api/v1/chats', 201, actor=eve, body={'title': 'ACL', 'member_ids': [eve['id'], bob['id']]}, schema='Chat')['json']
|
|
c.call('POST', '/api/v1/chats/' + own['id'] + '/messages', 404, actor=eve,
|
|
body={'text': 'blocked', 'attachment_ids': [att['id']]}, headers={'Idempotency-Key': 'acl-test-' + att['id']})
|
|
print('PASS outsider: metadata, bytes and reuse of foreign attachment denied')
|
|
|
|
session_hash = hashlib.sha256(alice['token'].encode()).hexdigest()
|
|
sql(f"UPDATE sessions SET expires_at = now() - interval '1 second' WHERE token_hash = decode('{session_hash}', 'hex')")
|
|
c.call('GET', '/api/v1/users/me', 401, actor=alice)
|
|
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=bob)
|
|
c.call('GET', '/api/v1/users/me', 401, actor=bob)
|
|
print('PASS expired and logged-out sessions rejected')
|
|
|
|
registration = alice['registration']
|
|
salt = bytes(range(16))
|
|
legacy = 'scrypt$16384$8$1$' + base64.b64encode(salt).decode() + '$' + base64.b64encode(
|
|
hashlib.scrypt(registration['password'].encode(), salt=salt, n=16384, r=8, p=1, dklen=32, maxmem=64 << 20)
|
|
).decode()
|
|
sql(f"UPDATE users SET password_hash = '{legacy}' WHERE id = '{alice['id']}'")
|
|
auth = base64.b64encode((registration['username'] + ':' + registration['password']).encode()).decode()
|
|
c.call('POST', '/api/v1/auth/sessions', 201, headers={'Authorization': 'Basic ' + auth})
|
|
check(sql(f"SELECT password_hash LIKE '$argon2id$v=19$%' FROM users WHERE id = '{alice['id']}'") == 't', 'rehash missing')
|
|
print('PASS successful scrypt login rehashes to Argon2id')
|
|
|
|
endpoint = urlsplit(c.base)
|
|
ctx = ssl.create_default_context(cafile=CA)
|
|
try:
|
|
with socket.create_connection((endpoint.hostname, endpoint.port or 443), timeout=5) as raw:
|
|
with ctx.wrap_socket(raw, server_hostname='invalid.lab'):
|
|
raise AssertionError('wrong hostname accepted')
|
|
except ssl.SSLCertVerificationError as exc:
|
|
check(exc.verify_code == 62, 'expected hostname mismatch')
|
|
print('PASS ingress rejects an incorrect hostname')
|
|
|
|
# Exercise password work with a known user and valid-length wrong password.
|
|
sql("UPDATE login_rate SET window_start='-infinity', attempts=0")
|
|
invalid = base64.b64encode((registration['username'] + ':wrong-password-for-lab').encode()).decode()
|
|
start = time.monotonic()
|
|
with ThreadPoolExecutor(max_workers=4) as pool:
|
|
samples = list(pool.map(lambda _: c.call('POST', '/api/v1/auth/sessions', [401, 429],
|
|
headers={'Authorization': 'Basic ' + invalid}), range(64)))
|
|
counts = Counter(r['status'] for r in samples)
|
|
for item in samples:
|
|
if item['status'] == 429:
|
|
check(int(item['headers']['Retry-After']) >= 1, 'Retry-After missing')
|
|
check(401 in counts and 429 in counts, 'rate limit test did not see both status codes')
|
|
check(len({item['headers']['X-Instance-Id'] for item in samples if item['status'] == 429}) >= 2,
|
|
'429 was not observed on both API replicas')
|
|
elapsed = sorted(r['elapsed'] for r in samples if r['status'] == 401)
|
|
print('PASS shared login budget ' + json.dumps({
|
|
'codes': counts, 'requests': 64, 'concurrency': 4, 'seconds': round(time.monotonic() - start, 2),
|
|
'401_p50_ms': round(elapsed[len(elapsed) // 2] * 1000, 1),
|
|
'401_p95_ms': round(elapsed[int((len(elapsed) - 1) * .95)] * 1000, 1),
|
|
}))
|
|
sql("UPDATE login_rate SET window_start='-infinity', attempts=0")
|
|
|
|
|
|
if __name__ == '__main__':
|
|
run(main)
|