#!/usr/bin/env python3 """Read-after-write of sessions under concurrency. Every iteration logs in (fresh token, cold cache), checks that the very first request with the token succeeds, starts READERS threads that call GET /users/me in a loop and logs out after a random 0-20 ms, i.e. while the first cache fills race with the revocation. A violation is a 200 for a request that started after the client had received the 204 of the logout. One second later the token is checked again: a stale cached copy must not bring it back. Prints a JSON summary; tokens are never printed. """ import base64 import http.client import json import random import sys import threading import time import urllib.parse import uuid PASSWORD = "track1-read-after-write" class Client: def __init__(self, base_url): url = urllib.parse.urlparse(base_url) self.connection = http.client.HTTPConnection(url.hostname, url.port, timeout=10) def call(self, method, path, headers=None, body=None): self.connection.request(method, path, body=body, headers=headers or {}) response = self.connection.getresponse() data = response.read() return response.status, data def main(): base_url, iterations, readers = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]) rng = random.Random(42) setup = Client(base_url) username = f"raw_{uuid.uuid4().hex[:12]}" status, _ = setup.call("POST", "/api/v1/users", {"Content-Type": "application/json"}, json.dumps({"username": username, "display_name": "RAW", "password": PASSWORD})) assert status == 201, status basic = "Basic " + base64.b64encode(f"{username}:{PASSWORD}".encode()).decode() reader_clients = [Client(base_url) for _ in range(readers)] revoked = [] totals = { "iterations": iterations, "readers": readers, "first_request_after_login_not_200": 0, "requests_started_before_logout_response": 0, "requests_started_after_logout_response": 0, "violations_200_after_logout": 0, "unexpected_statuses": {}, "token_alive_one_second_later": 0, "logout_not_204": 0, } for _ in range(iterations): status, body = setup.call("POST", "/api/v1/auth/sessions", {"Authorization": basic}) assert status == 201, status bearer = {"Authorization": "Bearer " + json.loads(body)["token"]} # Read-after-write of the login itself: no negative caching, the token works immediately. status, _ = setup.call("GET", "/api/v1/users/me", bearer) if status != 200: totals["first_request_after_login_not_200"] += 1 # The check above filled the cache; start the race from a cold key with a new session. status, body = setup.call("POST", "/api/v1/auth/sessions", {"Authorization": basic}) assert status == 201, status bearer = {"Authorization": "Bearer " + json.loads(body)["token"]} stop = threading.Event() results = [] lock = threading.Lock() def read(client): while not stop.is_set(): started = time.monotonic() status, _ = client.call("GET", "/api/v1/users/me", bearer) with lock: results.append((started, status)) threads = [threading.Thread(target=read, args=(c,)) for c in reader_clients] for t in threads: t.start() time.sleep(rng.uniform(0, 0.02)) status, _ = setup.call("DELETE", "/api/v1/auth/sessions/current", bearer) logout_done = time.monotonic() if status != 204: totals["logout_not_204"] += 1 time.sleep(0.1) stop.set() for t in threads: t.join() for started, status in results: if started > logout_done: totals["requests_started_after_logout_response"] += 1 if status == 200: totals["violations_200_after_logout"] += 1 elif status != 401: key = str(status) totals["unexpected_statuses"][key] = totals["unexpected_statuses"].get(key, 0) + 1 else: totals["requests_started_before_logout_response"] += 1 revoked.append(bearer) # Late check, one second after the last logout at the earliest: nothing cached resurrects a revoked token. time.sleep(1) for bearer in revoked: status, _ = setup.call("GET", "/api/v1/users/me", bearer) if status == 200: totals["token_alive_one_second_later"] += 1 print(json.dumps(totals, indent=2)) if __name__ == "__main__": main()