#!/usr/bin/env python3 """Lab 7 Application Security Verification Suite (Grade 3 + Grade 4). Verifies: - Argon2id PHC format (m>=19456, t>=2, p>=1) + live stand wall-clock benchmark - Transparent password rehash on login (weak Argon2id + legacy $scrypt$) - Hashed Redis session storage (session:sha256:*, zero raw Bearer tokens) - Negative ACLs (outsider chat/messages/attachment metadata & content/cross-chat attach) - Forged X-User-Id rejection, logout revocation, and session expiry - Request size limits (>64 KiB JSON -> 413; >10 MiB / >40M px image -> 413) - Shared Redis login rate limit across >=2 API replicas (429 + Retry-After) - Bounded Argon2id login DoS concurrency protection (0 OOMKill, bounded latency) - Telemetry & HTTP error redaction audit (Loki/Tempo/error bodies -> 0 leaks) Writes sanitized JSON + TXT report to evidence/lab7/app-security.{json,txt}. """ import argparse import base64 from concurrent.futures import ThreadPoolExecutor import hashlib import json import re import statistics import struct import sys import time import urllib.parse import uuid import zlib from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) import common # noqa: E402 from client import Client, Failure # noqa: E402 ARGON2_PHC_RE = re.compile( r'^\$argon2id\$v=(\d+)\$([a-z0-9,=]+)\$([^$]+)\$([^$]+)$' ) def _parse_argon2_phc(stored): """Parse an Argon2id PHC string regardless of m/t/p parameter order.""" m = ARGON2_PHC_RE.match(stored or '') if not m: return None params = {} for pair in m.group(2).split(','): if '=' not in pair: return None k, v = pair.split('=', 1) if not v.isdigit(): return None params[k] = int(v) if not all(k in params for k in ('m', 't', 'p')): return None return { 'v': int(m.group(1)), 'm': params['m'], 't': params['t'], 'p': params['p'], 'prefix': f"$argon2id$v={m.group(1)}$m={params['m']},t={params['t']},p={params['p']}", } def _basic_hdr(username, password): raw = base64.b64encode(f'{username}:{password}'.encode('utf-8')).decode('ascii') return {'Authorization': 'Basic ' + raw} def _make_png(width, height): """Build a valid minimal 1-bit grayscale PNG of (width x height) in stdlib.""" def chunk(tag, data): crc = zlib.crc32(tag + data) & 0xFFFFFFFF return struct.pack('>I', len(data)) + tag + data + struct.pack('>I', crc) ihdr = struct.pack('>IIBBBBB', width, height, 1, 0, 0, 0, 0) row_bytes = (width + 7) // 8 raw_row = b'\x00' + (b'\x00' * row_bytes) comp = zlib.compressobj(level=1) parts = [] # Feed in blocks to avoid allocating a huge uncompressed buffer in memory block = raw_row * 64 full_blocks, rem = divmod(height, 64) for _ in range(full_blocks): parts.append(comp.compress(block)) if rem: parts.append(comp.compress(raw_row * rem)) parts.append(comp.flush()) idat = b''.join(parts) return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', ihdr) + chunk(b'IDAT', idat) + chunk(b'IEND', b'') def _clear_rate_limit_keys(): """Remove rl:* keys created during rate-limit/DoS tests so subsequent tests stay clean.""" try: raw = common.redis_admin_cli('--scan', '--pattern', 'rl:*') keys = [k.strip() for k in raw.splitlines() if k.strip()] if keys: common.redis_admin_cli('DEL', *keys) except Failure: pass def _argon2_benchmark_in_api(): """Benchmark argon2@0.45.1 inside running API container for empirical parameter justification.""" js = """ const argon2 = require('argon2'); const { performance } = require('perf_hooks'); const configs = [ { label: 'floor_19MiB_t2_p1', memoryCost: 19456, timeCost: 2, parallelism: 1 }, { label: 'default_32MiB_t2_p1', memoryCost: 32768, timeCost: 2, parallelism: 1 }, { label: 'heavy_64MiB_t3_p1', memoryCost: 65536, timeCost: 3, parallelism: 1 }, ]; const out = []; for (const cfg of configs) { const times = []; for (let i = 0; i < 4; i++) { const t0 = performance.now(); await argon2.hash('Bench-P@ssw0rd-' + i, { type: argon2.argon2id, memoryCost: cfg.memoryCost, timeCost: cfg.timeCost, parallelism: cfg.parallelism, hashLength: 32, }); times.push(Number((performance.now() - t0).toFixed(2))); } times.sort((a, b) => a - b); out.push({ label: cfg.label, memory_kib: cfg.memoryCost, iterations: cfg.timeCost, parallelism: cfg.parallelism, samples_ms: times, median_ms: times[Math.floor(times.length / 2)], max_ms: times[times.length - 1], }); } return { rss_mib: Number((process.memoryUsage().rss / (1024 * 1024)).toFixed(1)), configs: out }; """ return common.run_node_probe(js, {}, exec_service='api', timeout=60) def _generate_legacy_hashes(password): js = """ const argon2 = require('argon2'); const crypto = require('crypto'); const weakArgon = await argon2.hash(payload.password, { type: argon2.argon2id, memoryCost: 4096, timeCost: 1, parallelism: 1, hashLength: 32, }); const salt = crypto.randomBytes(16); const dk = await new Promise((resolve, reject) => { crypto.scrypt(payload.password, salt, 32, { N: 16384, r: 8, p: 1 }, (err, key) => { if (err) reject(err); else resolve(key); }); }); const scryptPhc = `$scrypt$ln=14,r=8,p=1$${salt.toString('base64')}$${dk.toString('base64')}`; return { weakArgon, scryptPhc }; """ return common.run_node_probe(js, {'password': password}, exec_service='api', timeout=30) def test_argon2_and_rehash(client, rc): user = client.user('argon2') rc.register_secret(user['registration']['password']) rc.register_secret(user['token']) stored = common.psql_admin( f"SELECT password_hash FROM users WHERE id = '{user['id']}'" ) rc.register_secret(stored) parsed = _parse_argon2_phc(stored) if parsed: ver, mem, iters, par = parsed['v'], parsed['m'], parsed['t'], parsed['p'] prefix = parsed['prefix'] valid = ver == 19 and mem >= 19456 and iters >= 2 and par >= 1 rc.add('APP-1-ARGON2-PHC', 'password_storage', 'Stored password uses Argon2id PHC with m>=19456 KiB, t>=2, p>=1', valid, 'argon2id v=19, m>=19456, t>=2, p>=1', prefix, {'password_hash_prefix': prefix, 'm': mem, 't': iters, 'p': par}) else: rc.add('APP-1-ARGON2-PHC', 'password_storage', 'Stored password uses Argon2id PHC with m>=19456 KiB, t>=2, p>=1', False, 'argon2id PHC string', 'invalid format') mem, iters, par = 32768, 2, 1 # Empirical Argon2id benchmark inside running API container + live login latency bench_res = _argon2_benchmark_in_api() login_lat = [] hdr = _basic_hdr(user['registration']['username'], user['registration']['password']) for _ in range(3): t0 = time.monotonic() r = client.call('POST', '/api/v1/auth/sessions', 201, headers=hdr, schema='Session') login_lat.append(round((time.monotonic() - t0) * 1000, 1)) rc.register_secret(r['json']['token']) client.call('DELETE', '/api/v1/auth/sessions/current', 204, headers={'Authorization': 'Bearer ' + r['json']['token']}) bench_data = bench_res.get('result') if bench_res.get('ok') else None rc.add('APP-2-ARGON2-BENCHMARK', 'password_storage', 'Empirical Argon2id wall-clock benchmark captured on live stand', bool(bench_data) and len(login_lat) == 3, 'benchmark completed', f'live_login_median_ms={statistics.median(login_lat)}', {'in_container_benchmark': bench_data, 'live_https_login_ms': login_lat}) # Transparent rehash: weak Argon2id (m=4096,t=1) -> upgraded to configured Argon2id gen = _generate_legacy_hashes(user['registration']['password']) if not gen.get('ok'): rc.add('APP-3-REHASH-WEAK-ARGON2', 'password_storage', 'Transparent rehash of weak Argon2id hash on successful login', False, 'legacy hashes generated', gen.get('error')) return bench_data weak_hash = gen['result']['weakArgon'] scrypt_hash = gen['result']['scryptPhc'] rc.register_secret(weak_hash) rc.register_secret(scrypt_hash) escaped_weak = weak_hash.replace("'", "''") common.psql_admin(f"UPDATE users SET password_hash = '{escaped_weak}' WHERE id = '{user['id']}'") r_weak = client.call('POST', '/api/v1/auth/sessions', 201, headers=hdr, schema='Session') rc.register_secret(r_weak['json']['token']) upgraded_1 = common.psql_admin(f"SELECT password_hash FROM users WHERE id = '{user['id']}'") rc.register_secret(upgraded_1) p1 = _parse_argon2_phc(upgraded_1) rehashed_weak = bool(p1 and p1['m'] >= 19456 and p1['t'] >= 2 and upgraded_1 != weak_hash) # Prove subsequent login works with upgraded hash r_after1 = client.call('POST', '/api/v1/auth/sessions', 201, headers=hdr, schema='Session') rc.register_secret(r_after1['json']['token']) rc.add('APP-3-REHASH-WEAK-ARGON2', 'password_storage', 'Login with weak Argon2id (m=4096,t=1) transparently upgrades DB hash to active params', rehashed_weak and r_after1['status'] == 201, f'upgraded to m>={mem}, t>={iters}', f'password_rehashed={rehashed_weak}, after_prefix=' + (p1['prefix'] if p1 else 'invalid')) # Transparent rehash: legacy $scrypt$ -> upgraded to Argon2id escaped_scrypt = scrypt_hash.replace("'", "''") common.psql_admin(f"UPDATE users SET password_hash = '{escaped_scrypt}' WHERE id = '{user['id']}'") r_scrypt = client.call('POST', '/api/v1/auth/sessions', 201, headers=hdr, schema='Session') rc.register_secret(r_scrypt['json']['token']) upgraded_2 = common.psql_admin(f"SELECT password_hash FROM users WHERE id = '{user['id']}'") rc.register_secret(upgraded_2) p2 = _parse_argon2_phc(upgraded_2) rehashed_scrypt = bool(p2 and p2['m'] >= 19456 and p2['t'] >= 2) r_after2 = client.call('POST', '/api/v1/auth/sessions', 201, headers=hdr, schema='Session') rc.register_secret(r_after2['json']['token']) rc.add('APP-4-REHASH-LEGACY-SCRYPT', 'password_storage', 'Login with legacy $scrypt$ hash transparently upgrades DB hash to Argon2id', rehashed_scrypt and r_after2['status'] == 201, 'upgraded from $scrypt$ to $argon2id$', f'password_rehashed={rehashed_scrypt}, after_prefix=' + (p2['prefix'] if p2 else 'invalid')) return bench_data def test_acl_sessions_and_limits(client, rc): alice, bob, eve, chat = client.bootstrap() for a in (alice, bob, eve): rc.register_secret(a['registration']['password']) rc.register_secret(a['token']) # Upload attachment in (alice, bob) chat and wait ready att, _ = client.attachment(alice, chat) ready = client.wait_ready(bob, att, wait_seconds=60) eve_chat = client.call( 'POST', '/api/v1/chats', 201, actor=eve, body={'title': 'Eve private chat', 'member_ids': [eve['id']]}, schema='Chat', )['json'] alice_chat2 = client.call( 'POST', '/api/v1/chats', 201, actor=alice, body={'title': 'Alice second chat', 'member_ids': [alice['id']]}, schema='Chat', )['json'] # 1. Outsider ACL & cross-chat attachment negative tests acl_checks = [ ('GET', f"/api/v1/chats/{chat['id']}", eve, None), ('GET', f"/api/v1/chats/{chat['id']}/messages", eve, None), ('POST', f"/api/v1/chats/{chat['id']}/messages", eve, {'text': 'outsider'}), ('GET', f"/api/v1/attachments/{ready['id']}", eve, None), ('GET', f"/api/v1/attachments/{ready['id']}/content", eve, None), ('GET', f"/api/v1/attachments/{ready['id']}/content?variant=thumbnail", eve, None), ('POST', f"/api/v1/chats/{eve_chat['id']}/messages", eve, {'text': '', 'attachment_ids': [ready['id']]}), ('POST', f"/api/v1/chats/{alice_chat2['id']}/messages", alice, {'text': '', 'attachment_ids': [ready['id']]}), ] acl_results = [] all_acl_denied = True for method, path, actor, body in acl_checks: hdrs = {'Idempotency-Key': uuid.uuid4().hex} if method == 'POST' else None r = client.call(method, path, [403, 404], actor=actor, body=body, headers=hdrs) acl_results.append({'method': method, 'path': path.split('?')[0], 'status': r['status']}) all_acl_denied &= (r['status'] in (403, 404)) rc.add('APP-5-ACL-NEGATIVE', 'acl', 'Outsider chat/messages/attachment metadata & content and cross-chat attach return 403/404', all_acl_denied, 'all 8 probes 403/404', json.dumps(acl_results)) # 2. Forged X-User-Id ignored r_no_auth = client.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': alice['id']}) r_forged = client.call('GET', '/api/v1/users/me', 200, actor=eve, headers={'X-User-Id': alice['id']}, schema='User') rc.add('APP-6-FORGED-X-USER-ID', 'acl', 'Forged X-User-Id rejected without Bearer (401) and ignored with Bearer', r_no_auth['status'] == 401 and r_forged['json']['id'] == eve['id'], f"no_auth=401, forged_me={eve['id']}", f"no_auth={r_no_auth['status']}, forged_me={r_forged['json']['id']}") # 3. Hashed Redis sessions ONLY (session:sha256:*, zero raw Bearer token!) raw_token = alice['token'] token_sha = hashlib.sha256(raw_token.encode('utf-8')).hexdigest() expected_key = 'session:sha256:' + token_sha all_sess_keys = [ k.strip() for k in common.redis_admin_cli('--scan', '--pattern', 'session:*').splitlines() if k.strip() ] key_exists = expected_key in all_sess_keys raw_in_keys = any(raw_token in k for k in all_sess_keys) all_prefixed_sha256 = bool(all_sess_keys) and all(k.startswith('session:sha256:') for k in all_sess_keys) val = common.redis_admin_cli('GET', expected_key) if key_exists else '' raw_in_val = raw_token in val rc.add('APP-7-HASHED-REDIS-SESSIONS', 'session_security', 'Redis stores ONLY session:sha256:* keys with zero raw Bearer tokens in keys or values', key_exists and all_prefixed_sha256 and not raw_in_keys and not raw_in_val, 'key_exists=True, all_sha256=True, raw_token_in_redis=False', f'key_exists={key_exists}, all_sha256={all_prefixed_sha256}, raw_token_in_redis={raw_in_keys or raw_in_val}, count={len(all_sess_keys)}') # 4. Logout revocation & Session expiry r_out = client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=bob) r_after_out = client.call('GET', '/api/v1/users/me', 401, actor=bob) exp_user = client.user('expiry') rc.register_secret(exp_user['registration']['password']) rc.register_secret(exp_user['token']) exp_key = 'session:sha256:' + hashlib.sha256(exp_user['token'].encode('utf-8')).hexdigest() common.redis_admin_cli('PEXPIRE', exp_key, '800') time.sleep(1.3) r_expired = client.call('GET', '/api/v1/users/me', 401, actor=exp_user) rc.add('APP-8-LOGOUT-AND-EXPIRY', 'session_security', 'Logout immediately revokes session (204->401) and expired session returns 401', r_out['status'] == 204 and r_after_out['status'] == 401 and r_expired['status'] == 401, 'logout=204, after_logout=401, expired=401', f"logout={r_out['status']}, after_logout={r_after_out['status']}, expired={r_expired['status']}") # 5. Request size limits: >64 KiB JSON -> 413, >10 MiB upload -> 413, >40M px image -> 413 big_json = json.dumps({'text': 'A' * 70000}).encode('utf-8') r_json = client.call( 'POST', f"/api/v1/chats/{chat['id']}/messages", 413, actor=alice, raw=big_json, headers={'Content-Type': 'application/json', 'Idempotency-Key': uuid.uuid4().hex}, ) rc.add('APP-9-JSON-BODY-LIMIT', 'request_limits', 'Oversized JSON body (>64 KiB) rejected with 413 payload_too_large', r_json['status'] == 413 and r_json['json']['error']['code'] == 'payload_too_large', 'HTTP 413 payload_too_large', f"status={r_json['status']} code={r_json['json']['error']['code']}") oversize_bytes = (common.ROOT / 'tests/fixtures/sample.png').read_bytes() oversize_bytes = oversize_bytes + (b'\x00' * (10 * 1024 * 1024 + 4096 - len(oversize_bytes))) r_up_bytes = client.call( 'POST', f"/api/v1/chats/{chat['id']}/attachments?filename=huge.png", 413, actor=alice, raw=oversize_bytes, headers={'Content-Type': 'image/png'}, ) huge_px_png = _make_png(7000, 7000) # 49,000,000 px > 40M px limit r_up_px = client.call( 'POST', f"/api/v1/chats/{chat['id']}/attachments?filename=hugepx.png", 413, actor=alice, raw=huge_px_png, headers={'Content-Type': 'image/png'}, ) rc.add('APP-10-UPLOAD-SIZE-AND-PIXELS', 'request_limits', 'Oversized binary (>10 MiB) and pixel bomb (>40M px) rejected with 413', r_up_bytes['status'] == 413 and r_up_px['status'] == 413, 'bytes=413, pixels=413', f"bytes={r_up_bytes['status']} ({len(oversize_bytes)}B), pixels={r_up_px['status']} (7000x7000, {len(huge_px_png)}B)") return alice, chat def test_shared_ratelimit_and_dos(args, client, alice, rc): ca_file = args.ca_file base = args.base_url.rstrip('/') ctx = common.make_ssl_context(ca_file=ca_file) # 1. Shared login rate limit across >=2 API replicas _clear_rate_limit_keys() rl_user = client.user('ratelimit') rc.register_secret(rl_user['registration']['password']) rc.register_secret(rl_user['token']) bad_hdr = _basic_hdr(rl_user['registration']['username'], 'wrong-password-123') instances = set() statuses = [] first_429_attempt = None retry_after_val = None error_code_429 = None for i in range(1, 16): resp = common.https_request('POST', base + '/api/v1/auth/sessions', headers=bad_hdr, ssl_ctx=ctx) inst = resp['headers'].get('x-instance-id') if inst: instances.add(inst) statuses.append(resp['status']) if resp['status'] == 429 and first_429_attempt is None: first_429_attempt = i retry_after_val = resp['headers'].get('retry-after') try: body_j = json.loads(resp['body'].decode('utf-8')) error_code_429 = body_j.get('error', {}).get('code') except ValueError: error_code_429 = None break # Verify opaque X-Instance-Id format (no 12-char container IDs / IP / hostname) api_cids = [c[:12] for c in common.container_ids('api')] opaque_ok = bool(instances) and not any( any(cid in inst for cid in api_cids) or '.' in inst for inst in instances ) retry_ok = bool(retry_after_val and retry_after_val.isdigit() and int(retry_after_val) >= 1) shared_ok = ( len(instances) >= 2 and first_429_attempt is not None and first_429_attempt <= 11 and retry_ok and error_code_429 == 'rate_limited' and opaque_ok ) rc.add('APP-11-SHARED-RATE-LIMIT', 'rate_limit', 'Shared Redis login rate limit triggers 429+Retry-After across >=2 opaque API replicas', shared_ok, 'instances>=2, first_429<=11, Retry-After>=1, code=rate_limited, opaque X-Instance-Id', f'instances={sorted(instances)}, first_429={first_429_attempt}, retry_after={retry_after_val}, code={error_code_429}, opaque={opaque_ok}') # 2. Login DoS concurrency budget test (parallel invalid logins + concurrent authenticated traffic) _clear_rate_limit_keys() restarts_before = { cid[:12]: common.container_inspect(cid)['RestartCount'] for cid in common.container_ids('api') } def do_bad_login(idx): h = _basic_hdr(f'dos_nonexistent_{idx}_{uuid.uuid4().hex[:6]}', 'Wrong-DoS-Pass!') t0 = time.monotonic() r = common.https_request('POST', base + '/api/v1/auth/sessions', headers=h, ssl_ctx=ctx, timeout=15) return r['status'], round((time.monotonic() - t0) * 1000, 1), r['headers'].get('retry-after') def do_auth_me(_idx): h = {'Authorization': 'Bearer ' + alice['token']} t0 = time.monotonic() r = common.https_request('GET', base + '/api/v1/users/me', headers=h, ssl_ctx=ctx, timeout=10) return r['status'], round((time.monotonic() - t0) * 1000, 1) with ThreadPoolExecutor(max_workers=40) as pool: login_futs = [pool.submit(do_bad_login, i) for i in range(36)] time.sleep(0.15) auth_futs = [pool.submit(do_auth_me, i) for i in range(10)] login_results = [f.result() for f in login_futs] auth_results = [f.result() for f in auth_futs] login_codes = {} shed_retry_ok = True for st, _ms, ra in login_results: login_codes[st] = login_codes.get(st, 0) + 1 if st == 429 and not (ra and ra.isdigit() and int(ra) >= 1): shed_retry_ok = False auth_ok = all(st == 200 for st, _ in auth_results) auth_latencies = sorted(ms for _, ms in auth_results) auth_p95 = auth_latencies[int(0.95 * (len(auth_latencies) - 1))] if auth_latencies else None oom_any = False restarts_after = {} for cid in common.container_ids('api'): insp = common.container_inspect(cid) oom_any |= bool((insp.get('State') or {}).get('OOMKilled', False)) restarts_after[cid[:12]] = insp['RestartCount'] no_restarts = restarts_after == restarts_before # Clear rl:* right after DoS test so host IP isn't throttled for subsequent scripts _clear_rate_limit_keys() dos_ok = ( not oom_any and no_restarts and auth_ok and shed_retry_ok and all(code in (401, 429) for code in login_codes) and (login_codes.get(429, 0) >= 1 or max(ms for _, ms, _ in login_results) < 5000) ) rc.add('APP-12-LOGIN-DOS-BUDGET', 'dos_protection', 'Parallel login burst stays bounded under Argon2id semaphore with 0 OOMKill and unaffected /users/me', dos_ok, '0 OOMKill, 0 restarts, all auth=200, valid 401/429+Retry-After', f'login_codes={login_codes}, auth_p95_ms={auth_p95}, oom={oom_any}, restarts_unchanged={no_restarts}', {'login_codes': login_codes, 'auth_latencies_ms': auth_latencies, 'shed_retry_ok': shed_retry_ok}) def test_telemetry_redaction(args, client, alice, chat, rc): marker = 'LAB7-SECRET-CANARY-' + uuid.uuid4().hex[:12] fake_bao = 'hvs' + '.FAKECANARYTOKEN' + uuid.uuid4().hex[:12] wrong_pw = 'WrongSecret-' + marker rc.register_secret(fake_bao) rc.register_secret(wrong_pw) r_msg = client.call( 'POST', f"/api/v1/chats/{chat['id']}/messages", 201, actor=alice, body={'text': 'confidential ' + marker}, headers={'Idempotency-Key': uuid.uuid4().hex, 'X-Vault-Token': fake_bao}, schema='Message', ) r_bad = client.call( 'POST', '/api/v1/auth/sessions', 401, headers=_basic_hdr(alice['registration']['username'], wrong_pw), ) r_404 = client.call( 'GET', f"/api/v1/chats/{uuid.uuid4()}", 404, actor=alice, headers={'X-Vault-Token': fake_bao}, ) needles = { 'password': [alice['registration']['password'], wrong_pw], 'bearer_token': [alice['token']], 'bao_token': [fake_bao], 'message_body': [marker], 'argon2_hash': ['$argon2id$v='], 'private_key': [ '-----BEGIN ' + 'PRIVATE KEY-----', '-----BEGIN ' + 'EC PRIVATE KEY-----', ], } # Check HTTP error response bodies directly err_leaks = [] for label, resp in (('401_login', r_bad), ('404_chat', r_404)): txt = resp['bytes'].decode('utf-8', errors='replace') for cat, items in needles.items(): for n in items: if n and n in txt: err_leaks.append({'source': 'http_error:' + label, 'category': cat}) # Query Loki & Tempo through Grafana HTTPS proxy graf_pw = common.read_secret_file('grafana_admin_password') if graf_pw: rc.register_secret(graf_pw) telemetry_leaks = [] scanned_logs = 0 scanned_spans = 0 loki_checked = False tempo_checked = False if graf_pw: ctx = common.make_ssl_context(ca_file=args.ca_file) ghdr = common.basic_auth_header('admin', graf_pw) rids = [r_msg['headers']['X-Request-Id'], r_bad['headers']['X-Request-Id'], r_404['headers']['X-Request-Id']] trace_ids = set() # Wait up to 20s for logs to flush to Loki deadline = time.monotonic() + 20 loki_rows = [] while time.monotonic() < deadline: now_ns = time.time_ns() params = urllib.parse.urlencode({ 'query': '{service_name=~"messenger-.*"}', 'start': str(now_ns - 120 * 10**9), 'end': str(now_ns + 10 * 10**9), 'limit': '1000', }) resp = common.https_request( 'GET', args.grafana_url.rstrip('/') + '/api/datasources/proxy/uid/loki/loki/api/v1/query_range?' + params, headers=ghdr, ssl_ctx=ctx, ) if resp['status'] == 200: loki_checked = True body = json.loads(resp['body'].decode('utf-8')) loki_rows = [] for stream in body.get('data', {}).get('result', []): labels = stream.get('stream', {}) if labels.get('request_id') in rids and labels.get('trace_id'): trace_ids.add(labels['trace_id']) for _ts, line in stream.get('values', []): loki_rows.append(line + ' ' + json.dumps(labels, sort_keys=True)) if trace_ids: break time.sleep(2) scanned_logs = len(loki_rows) for text in loki_rows: for cat, items in needles.items(): for n in items: if n and n in text: telemetry_leaks.append({'source': 'loki', 'category': cat}) break for tid in trace_ids: resp = common.https_request( 'GET', args.grafana_url.rstrip('/') + '/api/datasources/proxy/uid/tempo/api/traces/' + tid, headers={**ghdr, 'Accept': 'application/json'}, ssl_ctx=ctx, ) if resp['status'] == 200: tempo_checked = True raw_trace = resp['body'].decode('utf-8', errors='replace') scanned_spans += 1 for cat, items in needles.items(): for n in items: if n and n in raw_trace: telemetry_leaks.append({'source': 'tempo:' + tid[:8], 'category': cat}) break total_leaks = len(err_leaks) + len(telemetry_leaks) rc.add('APP-13-TELEMETRY-AND-ERROR-REDACTION', 'redaction', 'Zero secret/token/password/Argon2/body leaks in HTTP errors, Loki logs, and Tempo traces', total_leaks == 0 and loki_checked, '0 leaks, loki_checked=True', f'leaks={total_leaks}, loki_checked={loki_checked} ({scanned_logs} logs), tempo_checked={tempo_checked} ({scanned_spans} traces)', {'leaks': err_leaks + telemetry_leaks}) def main(argv=None): parser = argparse.ArgumentParser(description=__doc__) common.add_common_args(parser) args = parser.parse_args(argv) rc = common.ResultCollector('lab7-app-security') client = Client(args.base_url, args.ca_file) try: bench = test_argon2_and_rehash(client, rc) alice, chat = test_acl_sessions_and_limits(client, rc) test_shared_ratelimit_and_dos(args, client, alice, rc) test_telemetry_redaction(args, client, alice, chat, rc) finally: _clear_rate_limit_keys() rc.summary = {'base_url': args.base_url, 'argon2_benchmark': bench} (json_path, txt_path), rep = rc.save(args.output_dir, 'app-security') print(f"Report written: {json_path} & {txt_path} (passed={rep['passed']} {rep['passed_count']}/{rep['total']})") return 0 if rep['passed'] else 1 if __name__ == '__main__': try: sys.exit(main()) except Failure as exc: print('FAIL:', common.redact_text(str(exc)), file=sys.stderr) sys.exit(1)