forked from mtusi2026/mtusi2026lab2
121 lines
5.7 KiB
Python
121 lines
5.7 KiB
Python
#!/usr/bin/env python3
|
|
"""Additional lab2 acceptance checks. Never print credentials or session tokens."""
|
|
import base64
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
import uuid
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
|
from client import Client, Failure, check, run
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
|
|
|
|
def compose(*args, ttl=None):
|
|
env = dict(os.environ)
|
|
if ttl is not None:
|
|
env['SESSION_TTL_SECONDS'] = str(ttl)
|
|
result = subprocess.run([str(ROOT / 'scripts/compose.sh'), *args], env=env,
|
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=180)
|
|
check(result.returncode == 0, 'compose operation failed: ' + args[0])
|
|
|
|
|
|
def login(c, username, password, expected=201):
|
|
basic = base64.b64encode((username + ':' + password).encode()).decode()
|
|
return c.call('POST', '/api/v1/auth/sessions', expected,
|
|
headers={'Authorization': 'Basic ' + basic}, schema='Session' if expected == 201 else None)
|
|
|
|
|
|
def main():
|
|
c = Client(timeout=5)
|
|
alice, bob, eve, chat = c.bootstrap()
|
|
credentials = alice['registration']
|
|
login(c, credentials['username'], 'incorrect-password', 401)
|
|
login(c, 'unknown_' + uuid.uuid4().hex[:12], 'incorrect-password', 401)
|
|
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': alice['id']})
|
|
basic = base64.b64encode((credentials['username'] + ':' + credentials['password']).encode()).decode()
|
|
c.call('GET', '/api/v1/users/me', 401, headers={'Authorization': 'Basic ' + basic})
|
|
response = c.call('GET', '/api/v1/users/me', actor=alice, headers={'X-User-Id': bob['id']}, schema='User')
|
|
check(response['json']['id'] == alice['id'], 'X-User-Id changed session owner')
|
|
c.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=alice)
|
|
c.call('GET', '/api/v1/users/me', 401, actor=alice)
|
|
c.call('DELETE', '/api/v1/auth/sessions/current', 401, actor=alice)
|
|
print('PASS: wrong password, unknown user, Bearer-only access, X-User-Id ignored, logout')
|
|
|
|
# Maximum UTF-8 password length and a colon are supported without truncation.
|
|
username = 'unicode_' + uuid.uuid4().hex[:12]
|
|
password = '🔑' * 127 + ':'
|
|
c.call('POST', '/api/v1/users', 201, body={'username': username, 'display_name': 'Unicode', 'password': password}, schema='User')
|
|
login(c, username, password)
|
|
login(c, username, '🔑' * 127 + 'x', 401)
|
|
print('PASS: 128-code-point Unicode password including colon; suffix verified')
|
|
|
|
username = 'race_' + uuid.uuid4().hex[:12]
|
|
def register(_):
|
|
return Client().call('POST', '/api/v1/users', [201, 409], body={
|
|
'username': username, 'display_name': 'Concurrent', 'password': 'synthetic-password-123'
|
|
})['status']
|
|
with ThreadPoolExecutor(max_workers=8) as pool:
|
|
statuses = list(pool.map(register, range(8)))
|
|
check(statuses.count(201) == 1 and statuses.count(409) == 7, 'registration race broken')
|
|
print('PASS: HTTP registration race: one 201, seven 409')
|
|
|
|
# Revoke before restart: absence must also survive AOF recovery.
|
|
for service in ('redis', 'postgres'):
|
|
compose('stop', service)
|
|
try:
|
|
c.call('GET', '/health/live', schema='Health')
|
|
start = time.monotonic()
|
|
c.call('GET', '/health/ready', 503)
|
|
check(time.monotonic() - start < 4, 'readiness error exceeded timeout budget')
|
|
c.call('GET', '/api/v1/users/me', 503, actor=bob)
|
|
c.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': bob['id']})
|
|
login(c, bob['registration']['username'], bob['registration']['password'], 503)
|
|
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 503, actor=bob, body={'text': 'must fail'})
|
|
finally:
|
|
compose('up', '-d', '--wait', service)
|
|
c.call('GET', '/health/ready', schema='Health')
|
|
c.call('GET', '/api/v1/users/me', actor=bob, schema='User')
|
|
c.call('GET', '/api/v1/users/me', 401, actor=alice)
|
|
print('PASS: ' + service + ' outage bounded; live=200, ready=503, protected=503, anonymous=401; session recovered, logout retained')
|
|
|
|
# The same signed cursor remains valid across an API process restart.
|
|
c.message(bob, chat, 'cursor before restart 1')
|
|
c.message(bob, chat, 'cursor before restart 2')
|
|
page = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?limit=1', actor=bob, schema='MessagePage')['json']
|
|
check(page['next_cursor'] is not None, 'missing cursor')
|
|
compose('restart', 'api')
|
|
deadline = time.monotonic() + 30
|
|
while True:
|
|
try:
|
|
c.call('GET', '/health/ready', schema='Health')
|
|
break
|
|
except Failure:
|
|
check(time.monotonic() < deadline, 'API did not recover')
|
|
time.sleep(.2)
|
|
from urllib.parse import quote
|
|
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages?cursor=' + quote(page['next_cursor']), actor=bob, schema='MessagePage')
|
|
print('PASS: cursor and existing session survive API restart')
|
|
|
|
try:
|
|
compose('up', '-d', '--wait', '--force-recreate', 'api', ttl=2)
|
|
short = c.user('expiry')
|
|
c.call('GET', '/api/v1/users/me', actor=short, schema='User')
|
|
time.sleep(2.2)
|
|
c.call('GET', '/api/v1/users/me', 401, actor=short)
|
|
compose('restart', 'redis')
|
|
compose('up', '-d', '--wait', 'redis')
|
|
c.call('GET', '/api/v1/users/me', 401, actor=short)
|
|
print('PASS: SESSION_TTL_SECONDS=2 expires; Redis restart does not revive expired session')
|
|
finally:
|
|
compose('up', '-d', '--wait', '--force-recreate', 'api', ttl=3600)
|
|
print('PASS: all grade-4 HTTP checks; normal TTL restored to 3600')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
run(main)
|