#!/usr/bin/env python3 """Measures the shared login rate-limit budget and checks credential non-disclosure. The test is intentionally black-box: it talks only through the public HTTPS ingress, records which API replica served each attempt, and never prints a password, session token or password hash. """ import base64 import concurrent.futures import json import math import socket import statistics import time import uuid from client import Client, arguments, check, run def prefer_ipv4_for_localhost(): """Avoid a ~2 s IPv6 fallback on Windows when localhost resolves to ::1 first.""" original = socket.getaddrinfo def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0): addresses = original(host, port, family, type, proto, flags) if host == 'localhost' and family in (0, socket.AF_UNSPEC): ipv4 = [address for address in addresses if address[0] == socket.AF_INET] return ipv4 or addresses return addresses socket.getaddrinfo = getaddrinfo def configure(parser): parser.add_argument('--minimum-instances', type=int, default=2, help='fail unless this many distinct X-Instance-Id values are observed') parser.add_argument('--username-limit', type=int, default=5) parser.add_argument('--source-limit', type=int, default=100) parser.add_argument('--window-seconds', type=int, default=60) parser.add_argument('--source-budget', action='store_true', help='also exhaust the per-source budget (takes about one window plus 100 verifies)') parser.add_argument('--wait-window', type=int, default=61, help='wait this long before the source-budget phase so its counter is empty') def register(client, label): username = 'dos_' + label.replace('-', '_') + '_' + uuid.uuid4().hex[:12] password = 'T3st-' + uuid.uuid4().hex client.call('POST', '/api/v1/users', 201, body={'username': username, 'display_name': 'DoS ' + label, 'password': password}, schema='User') return username, password def login(client, username, password): credential = base64.b64encode((username + ':' + password).encode()).decode() return client.call('POST', '/api/v1/auth/sessions', (200, 201, 401, 429), headers={'Authorization': 'Basic ' + credential}) def assert_no_secret(response, *secrets): body = response['bytes'].decode('utf-8', 'replace').lower() headers = ' '.join(f'{key}: {value}' for key, value in response['headers'].items()).lower() for secret in secrets: if not secret: continue check(secret.lower() not in body, 'error response leaked a credential') check(secret.lower() not in headers, 'error headers leaked a credential') def percentile(values, fraction): if not values: return 0.0 ordered = sorted(values) index = max(0, min(len(ordered) - 1, int(math.ceil(fraction * len(ordered))) - 1)) return ordered[index] def burst(base_url, ca_file, username, wrong_password, count): def attempt(_): return login(Client(base_url, ca_file), username, wrong_password) with concurrent.futures.ThreadPoolExecutor(max_workers=count) as pool: return list(pool.map(attempt, range(count))) def check_username_budget(args): client = Client(args.base_url, args.ca_file) username, password = register(client, 'known') wrong = 'wrong-' + uuid.uuid4().hex responses = burst(client.base, args.ca_file, username, wrong, args.username_limit) statuses = [response['status'] for response in responses] check(all(status == 401 for status in statuses), 'an attempt below the per-username budget was rejected') for response in responses: assert_no_secret(response, username, wrong, password) blocked = login(client, username, wrong) check(blocked['status'] == 429, 'attempt above the per-username budget was not rate limited') check(blocked['json']['error']['code'] == 'rate_limited', 'wrong rate-limit error code') retry_after = blocked['headers'].get('Retry-After', '') check(retry_after.isdigit() and 1 <= int(retry_after) <= args.window_seconds, 'missing or out-of-window Retry-After') assert_no_secret(blocked, username, wrong, password) instances = sorted({response['headers'].get('X-Instance-Id', '') for response in responses}) check(len(instances) >= args.minimum_instances, 'login attempts reached only ' + str(len(instances)) + ' API replica(s)') latencies = [response['elapsed'] for response in responses] check(blocked['elapsed'] < percentile(latencies, 0.50), 'rate-limited response was not cheaper than the Argon2 verification path') return { 'limit': args.username_limit, 'window_seconds': args.window_seconds, 'allowed_under_limit': statuses.count(401), 'blocked_status': blocked['status'], 'blocked_code': blocked['json']['error']['code'], 'retry_after_seconds': int(retry_after), 'argon2_path_p50_ms': round(statistics.median(latencies) * 1000, 3), 'argon2_path_p95_ms': round(percentile(latencies, 0.95) * 1000, 3), 'rate_limited_ms': round(blocked['elapsed'] * 1000, 3), 'observed_instances': instances, } def check_user_enumeration(args): client = Client(args.base_url, args.ca_file) known_name, known_password = register(client, 'enum-known') wrong_known = 'wrong-' + uuid.uuid4().hex known = login(client, known_name, wrong_known) unknown_name = 'dos_missing_' + uuid.uuid4().hex wrong_unknown = 'wrong-' + uuid.uuid4().hex unknown = login(client, unknown_name, wrong_unknown) check(known['status'] == 401 and unknown['status'] == 401, 'known and unknown users did not receive the same 401 class') check(known['json']['error']['code'] == unknown['json']['error']['code'], 'known and unknown users received different error codes') check(known['json']['error']['message'] == unknown['json']['error']['message'], 'known and unknown users received different error messages') for response in (known, unknown): assert_no_secret(response, known_name, unknown_name, wrong_known, wrong_unknown, known_password) return { 'known_status': known['status'], 'unknown_status': unknown['status'], 'error_code': known['json']['error']['code'], 'same_message': True, 'known_ms': round(known['elapsed'] * 1000, 3), 'unknown_ms': round(unknown['elapsed'] * 1000, 3), } def check_source_budget(args): if args.wait_window > 0: time.sleep(args.wait_window) client = Client(args.base_url, args.ca_file) latencies = [] instances = set() for _ in range(args.source_limit): username = 'dos_source_' + uuid.uuid4().hex wrong = 'wrong-' + uuid.uuid4().hex response = login(client, username, wrong) check(response['status'] == 401, 'an attempt below the per-source budget was rejected') assert_no_secret(response, username, wrong) latencies.append(response['elapsed']) instances.add(response['headers'].get('X-Instance-Id', '')) blocked_username = 'dos_source_blocked_' + uuid.uuid4().hex blocked_wrong = 'wrong-' + uuid.uuid4().hex blocked = login(client, blocked_username, blocked_wrong) check(blocked['status'] == 429, 'attempt above the per-source budget was not rate limited') check(blocked['json']['error']['code'] == 'rate_limited', 'wrong source rate-limit code') retry_after = blocked['headers'].get('Retry-After', '') check(retry_after.isdigit() and 1 <= int(retry_after) <= args.window_seconds, 'missing or out-of-window source Retry-After') assert_no_secret(blocked, blocked_username, blocked_wrong) return { 'limit': args.source_limit, 'window_seconds': args.window_seconds, 'allowed_under_limit': args.source_limit, 'blocked_status': blocked['status'], 'retry_after_seconds': int(retry_after), 'argon2_path_p50_ms': round(statistics.median(latencies) * 1000, 3), 'argon2_path_p95_ms': round(percentile(latencies, 0.95) * 1000, 3), 'rate_limited_ms': round(blocked['elapsed'] * 1000, 3), 'observed_instances': sorted(instances), } def main(): prefer_ipv4_for_localhost() args = arguments('Shared login rate-limit budget and credential non-disclosure', configure) check(args.username_limit >= 1 and args.source_limit >= args.username_limit, 'limits must be positive and source >= username') check(args.window_seconds >= 1, 'window must be positive') summary = { 'username_budget': check_username_budget(args), 'user_enumeration': check_user_enumeration(args), } if args.source_budget: summary['source_budget'] = check_source_budget(args) print(json.dumps(summary, indent=2, sort_keys=True)) print('PASS: shared login budget, generic errors and fast rate-limit rejection verified.') if __name__ == '__main__': run(main)