#!/usr/bin/env python3 """Grade-4 checks that the public smoke does not cover.""" import base64 import sys import uuid from concurrent.futures import ThreadPoolExecutor from pathlib import Path from urllib.parse import quote ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tests")) from client import Client, Failure, arguments, check, run def walk(client, actor, chat, limit): path = "/api/v1/chats/" + chat["id"] + "/messages?limit=%d" % limit items = [] cursor = None guard = 0 while True: guard += 1 check(guard < 10000, "pagination did not finish") target = path if cursor is None else path + "&cursor=" + quote(cursor, safe="") page = client.call("GET", target, actor=actor, schema="MessagePage")["json"] check(len(page["items"]) <= limit, "page is larger than limit") items.extend(page["items"]) if page["next_cursor"] is None: return items check(page["items"], "cursor was returned for an empty page") cursor = page["next_cursor"] def test_input(client): client.call("POST", "/api/v1/users", 400, raw=b"{", headers={"Content-Type": "application/json"}) client.call( "POST", "/api/v1/users", 400, raw=b'{"username":"shortpwuser","display_name":"Name","password":"short"}', headers={"Content-Type": "application/json"}, ) client.call( "POST", "/api/v1/users", 400, raw=b'{"Username":"caseuserx","display_name":"Name","password":"long-enough-password"}', headers={"Content-Type": "application/json"}, ) client.call( "POST", "/api/v1/users", 400, raw=b'{"username":"utf8userx","display_name":"a\xff","password":"long-enough-password"}', headers={"Content-Type": "application/json"}, ) client.call( "POST", "/api/v1/users", 400, raw=b'{"username":"extra_userx","display_name":"Name","password":"long-enough-password","role":"admin"}', headers={"Content-Type": "application/json"}, ) def test_duplicate_and_race(client): username = "race_" + uuid.uuid4().hex[:8] body = {"username": username, "display_name": "Race", "password": "long-enough-password"} client.call("POST", "/api/v1/users", 201, body=body, schema="User") conflict = client.call("POST", "/api/v1/users", 409, body=body) check(conflict["json"]["error"]["code"] == "conflict", "duplicate username code") shared = "par_" + uuid.uuid4().hex[:8] payload = {"username": shared, "display_name": "Parallel", "password": "long-enough-password"} def once(_): return client.call("POST", "/api/v1/users", [201, 409], body=payload)["status"] with ThreadPoolExecutor(max_workers=8) as pool: codes = list(pool.map(once, range(8))) check(codes.count(201) == 1, "parallel registration created %s users" % codes.count(201)) check(all(code in (201, 409) for code in codes), "parallel registration returned %s" % codes) def test_auth(client): alice = client.user("auth") bad_user = client.call( "POST", "/api/v1/auth/sessions", 401, headers={"Authorization": "Basic " + base64.b64encode(b"missing_user_name:long-enough-password").decode()}, ) bad_pass = client.call( "POST", "/api/v1/auth/sessions", 401, headers={"Authorization": "Basic " + base64.b64encode( (alice["registration"]["username"] + ":wrong-password-value").encode() ).decode()}, ) check(bad_user["json"]["error"]["message"] == bad_pass["json"]["error"]["message"], "credential errors differ") client.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": alice["id"]}) me = client.call( "GET", "/api/v1/users/me", actor=alice, headers={"X-User-Id": "00000000-0000-4000-8000-000000000001"}, schema="User", )["json"] check(me["id"] == alice["id"], "X-User-Id changed the session user") client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice) client.call("GET", "/api/v1/users/me", 401, actor=alice) def test_chat_rollback_and_history(client): alice = client.user("chat") bob = client.user("peer") missing = str(uuid.uuid4()) client.call( "POST", "/api/v1/chats", 400, actor=alice, body={"title": "broken", "member_ids": [alice["id"], missing]}, ) listed = client.call("GET", "/api/v1/chats?limit=100", actor=alice, schema="ChatPage")["json"] check(listed["items"] == [], "rolled back chat is visible") chat = client.call( "POST", "/api/v1/chats", 201, actor=alice, body={"title": "ok", "member_ids": [alice["id"], bob["id"]]}, schema="Chat", )["json"] eve = client.user("outsider") client.call("GET", "/api/v1/chats/" + chat["id"], 404, actor=eve) client.call("POST", "/api/v1/chats/" + chat["id"] + "/messages", 400, actor=alice, body={"text": " "}) for n in range(25): client.message(alice, chat, "m%02d" % n) items = walk(client, bob, chat, 10) check(len(items) == 25, "history length") check(len({item["id"] for item in items}) == 25, "duplicate ids") check([item["text"] for item in items] == ["m%02d" % n for n in range(25)], "history order") foreign = walk(client, bob, chat, 10) cursor = client.call( "GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=1", actor=alice, schema="MessagePage", )["json"]["next_cursor"] other = client.call( "POST", "/api/v1/chats", 201, actor=alice, body={"title": "second", "member_ids": [alice["id"]]}, schema="Chat", )["json"] client.call( "GET", "/api/v1/chats/" + other["id"] + "/messages?limit=10&cursor=" + quote(cursor, safe=""), 400, actor=alice, ) check(len(foreign) == 25, "second walk") def main(): args = arguments("Student checks for lab2") client = Client(args.base_url, args.ca_file, timeout=20) client.call("GET", "/health/ready", schema="Health") test_input(client) test_duplicate_and_race(client) test_auth(client) test_chat_rollback_and_history(client) print("PASS: student checks") if __name__ == "__main__": run(main)