This commit is contained in:
2026-11-26 23:34:55 +03:00
parent 20afc2c790
commit a25f357314
167 changed files with 33202 additions and 89 deletions
+19
View File
@@ -0,0 +1,19 @@
#include "auth.hpp"
#include <sodium.h>
#include <cassert>
#include <chrono>
#include <iostream>
int main() {
const auto start = std::chrono::steady_clock::now();
const auto hash = hash_password("correct horse battery staple");
assert(hash.rfind("$argon2id$v=19$m=65536,t=2,p=1$",0)==0);
assert(verify_password("correct horse battery staple",hash));
assert(!verify_password("wrong",hash));
assert(!verify_password("wrong","$argon2id$malformed"));
assert(!password_needs_rehash(hash));
char old[crypto_pwhash_STRBYTES];
assert(crypto_pwhash_str_alg(old,"password",8,1,19*1024*1024,crypto_pwhash_ALG_ARGON2ID13)==0);
assert(password_needs_rehash(old));
std::cout << "PASS: Argon2id m=65536 KiB,t=2,p=1; verify/malformed/rehash; total_ms="
<< std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now()-start).count() << '\n';
}
@@ -0,0 +1,73 @@
#include "bao.hpp"
#include "db.hpp"
#include "redis_pool.hpp"
#include "s3_client.hpp"
#include "session_repo.hpp"
#include <sodium.h>
#include <thread>
#include <chrono>
#include <cstdlib>
#include <pqxx/pqxx>
#include <cassert>
#include <iostream>
#include <sstream>
#include <memory>
int main() {
try {
const auto& secrets=service_secrets();
if (std::string(std::getenv("BAO_SERVICE"))=="api") {
RedisPool redis(secrets.redis_url,1);
SessionRepo short_sessions(redis,1);
auto created=short_sessions.create("security-session-user");
assert(short_sessions.lookup(created.token)=="security-session-user");
unsigned char digest[32];char hex[65];
crypto_hash_sha256(digest,reinterpret_cast<const unsigned char*>(created.token.data()),created.token.size());
sodium_bin2hex(hex,sizeof(hex),digest,sizeof(digest));
{
auto lease=redis.acquire();
std::unique_ptr<redisReply,decltype(&freeReplyObject)> raw(
static_cast<redisReply*>(redisCommand(lease.ctx(),"GET session:%s",created.token.c_str())),freeReplyObject);
assert(raw && raw->type==REDIS_REPLY_NIL);
std::unique_ptr<redisReply,decltype(&freeReplyObject)> hashed(
static_cast<redisReply*>(redisCommand(lease.ctx(),"GET session:%s",hex)),freeReplyObject);
assert(hashed && hashed->type==REDIS_REPLY_STRING);
}
std::this_thread::sleep_for(std::chrono::milliseconds(1200));
assert(!short_sessions.lookup(created.token));
SessionRepo sessions(redis,60);
auto logout=sessions.create("security-session-user");
assert(sessions.revoke(logout.token) && !sessions.lookup(logout.token));
std::cout << "PASS: session token hashed at rest; real Redis TTL expiry; logout revocation\n";
return 0;
}
auto pg=open_pg_connection(secrets.database_url,true);
{
pqxx::nontransaction tx(*pg);
const auto r=tx.exec("SELECT rolsuper,rolcreaterole FROM pg_roles WHERE rolname=current_user");
assert(!r[0][0].as<bool>() && !r[0][1].as<bool>());
assert(tx.exec("SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()")[0][0].as<bool>());
}
bool denied=false;
try { pqxx::work tx(*pg); tx.exec("SELECT password_hash FROM users LIMIT 1"); }
catch(const pqxx::insufficient_privilege&) { denied=true; }
assert(denied);
RedisPool redis(secrets.redis_url,1);
auto lease=redis.acquire();
for(const char* command : {"GET session:probe", "CONFIG GET *", "XADD jobs:attachments * payload unauthorized"}) {
std::unique_ptr<redisReply,decltype(&freeReplyObject)> r(
static_cast<redisReply*>(redisCommand(lease.ctx(),command)),freeReplyObject);
assert(r && r->type==REDIS_REPLY_ERROR && std::string(r->str).find("NOPERM")!=std::string::npos);
}
S3Client s3(secrets.s3);
std::int64_t size=0;std::string etag;
denied=false;
try { s3.stat_object("other-tenant/private",size,etag); }
catch(const std::exception& e) { denied=std::string(e.what()).find("AccessDenied")!=std::string::npos; }
assert(denied);
std::istringstream bytes("test");
s3.put_object("staging/security-test",bytes,4,"text/plain");
assert(s3.stat_object("staging/security-test",size,etag) && size==4);
s3.delete_object("staging/security-test");
std::cout << "PASS: worker DB TLS+least privilege; Redis session/admin/producer denied; S3 allowed/forbidden prefix\n";
} catch (...) { std::cerr << "FAIL: dependency security test (details withheld)\n"; return 1; }
}
+178
View File
@@ -0,0 +1,178 @@
#!/usr/bin/env python3
"""Controlled lab6 failures, with unconditional service recovery and sanitized evidence."""
import argparse
from datetime import datetime, timezone
import json
import os
from pathlib import Path
import shlex
import subprocess
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, check
sys.path.insert(0, str(ROOT / 'student-tests'))
from observability import get, eventually
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--base-url', default='http://localhost:8080')
parser.add_argument('--prometheus-url', default='http://localhost:9090')
parser.add_argument('--only', choices=['all', 'retry', 'backend'], default='all')
args = parser.parse_args()
compose = shlex.split(os.environ.get('COMPOSE', 'docker compose'))
def command(*cmd):
subprocess.run(compose + list(cmd), cwd=ROOT, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def query(expr):
return get(args.prometheus_url + '/api/v1/query?' + urllib.parse.urlencode({'query': expr}))['data']['result']
def value(expr):
rows = query(expr)
return float(rows[0]['value'][1]) if rows else 0
def firing(name):
alerts = get(args.prometheus_url + '/api/v1/alerts')['data']['alerts']
return any(a['labels']['alertname'] == name and a['state'] == 'firing' for a in alerts)
c = Client(args.base_url)
alice, bob, _, chat = c.bootstrap()
events = json.loads((ROOT / "evidence/incidents.json").read_text()) if args.only != "all" else []
def record(name, **fields):
events.append({'event': name, 'timestamp': datetime.now(timezone.utc).isoformat(), **fields})
(ROOT / 'evidence/incidents.json').write_text(json.dumps(events, indent=2) + '\n')
print(name, flush=True)
if args.only == "all":
# 1. Durable queue ages while worker is stopped; resume drains the same job.
command('stop', 'worker')
try:
att, _ = c.attachment(alice, chat)
record('worker_stopped_upload_accepted')
eventually(lambda: firing('QueueLagGrowing'), timeout=120)
record('QueueLagGrowing_firing', depth=value('max(queue_depth)'), oldest_seconds=value('max(queue_oldest_age)'))
finally:
command('start', 'worker')
c.wait_ready(bob, att)
eventually(lambda: not firing('QueueLagGrowing') and value('max(queue_depth)') == 0, timeout=90)
record('QueueLagGrowing_resolved_backlog_drained')
# 2. PostgreSQL unavailable: valid authenticated reads must yield 5xx, never successful phantom writes.
command('stop', 'db')
statuses = {}
try:
record('database_stopped')
deadline = time.monotonic() + 100
while time.monotonic() < deadline:
request = urllib.request.Request(args.base_url + '/api/v1/chats/' + chat['id'] + '/messages',
headers={'Authorization': 'Bearer ' + alice['token']})
try:
response = urllib.request.urlopen(request, timeout=12)
except urllib.error.HTTPError as error:
response = error
with response:
code = response.status
statuses[str(code)] = statuses.get(str(code), 0) + 1
if firing('ApiHighErrorRate'):
break
time.sleep(0.5)
check(firing('ApiHighErrorRate'), 'API error alert did not fire')
check(any(int(code) >= 500 for code in statuses), 'No server errors observed')
record('ApiHighErrorRate_firing', response_counts=statuses)
finally:
command('start', 'db')
def recovered():
return c.call('GET', '/health/ready', schema='Health')['status'] == 200
eventually(recovered, timeout=90)
# New traffic moves the one-minute failure window out of the rate calculation.
deadline = time.monotonic() + 100
while time.monotonic() < deadline:
c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=alice, schema='MessagePage')
if not firing('ApiHighErrorRate'):
break
time.sleep(1)
check(not firing('ApiHighErrorRate'), 'API alert did not resolve')
record('ApiHighErrorRate_resolved_database_recovered')
if args.only != "backend":
# A retriable S3 failure must preserve the upload trace across the next outbox row.
import base64
import uuid
trace = uuid.uuid4().hex
command('pause', 'worker')
paused = True
try:
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
att = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png', 202,
actor=alice, raw=content, headers={'Content-Type': 'image/png',
'traceparent': '00-' + trace + '-0123456789abcdef-01'}, schema='Attachment')['json']
auth = os.environ.get('GRAFANA_ADMIN_USER', 'admin') + ':' + (ROOT / 'secrets/grafana_admin_password').read_text().strip()
grafana = os.environ.get('GRAFANA_URL', 'http://localhost:3000')
def retry_observed():
data = get(grafana + '/api/datasources/proxy/uid/tempo/api/traces/' + trace, auth)
def contains(obj):
if isinstance(obj, dict):
if obj.get('key') == 'job.outcome' and obj.get('value', {}).get('stringValue') == 'retry':
return True
return any(contains(v) for v in obj.values())
return isinstance(obj, list) and any(contains(v) for v in obj)
return contains(data)
command('stop', 'minio')
command('unpause', 'worker')
paused = False
eventually(retry_observed, timeout=45)
record('s3_failure_scheduled_retry', trace_id=trace)
finally:
command('start', 'minio')
if paused:
command('unpause', 'worker')
c.wait_ready(bob, att)
auth = os.environ.get('GRAFANA_ADMIN_USER', 'admin') + ':' + (ROOT / 'secrets/grafana_admin_password').read_text().strip()
grafana = os.environ.get('GRAFANA_URL', 'http://localhost:3000')
def retry_trace():
data = get(grafana + '/api/datasources/proxy/uid/tempo/api/traces/' + trace, auth)
spans = []
def walk(obj):
if isinstance(obj, dict):
if 'spanId' in obj and 'name' in obj:
spans.append(obj)
for value_ in obj.values():
walk(value_)
elif isinstance(obj, list):
for value_ in obj:
walk(value_)
walk(data)
by_id = {s['spanId']: s for s in spans}
# consumer -> enqueue -> publish -> next consumer (all inside the same trace)
for child in spans:
if child['name'] != 'attachment.process':
continue
producer = by_id.get(child.get('parentSpanId'), {})
enqueue = by_id.get(producer.get('parentSpanId'), {})
prior = by_id.get(enqueue.get('parentSpanId'), {})
if producer.get('name') == 'jobs:attachments publish' and enqueue.get('name') == 'attachment.enqueue' and prior.get('name') == 'attachment.process':
return True
return False
eventually(retry_trace)
record('retry_same_trace_ready_verified', trace_id=trace)
# 3. Broken telemetry storage must not break either application process.
before = value('sum(otelcol_exporter_send_failed_spans)')
command('stop', 'tempo', 'loki')
try:
record('tempo_loki_stopped')
att, _ = c.attachment(alice, chat)
c.wait_ready(bob, att)
for _ in range(20):
c.message(alice, chat, 'Synthetic telemetry outage probe')
time.sleep(1)
eventually(lambda: value('sum(otelcol_exporter_send_failed_spans)') > before, timeout=45)
record('telemetry_outage_api_worker_healthy',
failed_span_exports=value('sum(otelcol_exporter_send_failed_spans)')-before,
collector_rss_bytes=value('max(otelcol_process_memory_rss)'))
finally:
command('start', 'tempo', 'loki')
record('tempo_loki_restarted')
print('PASS: worker lag and DB error alerts fired/resolved; API and worker survived telemetry backend outage.')
if __name__ == '__main__':
main()
+133
View File
@@ -0,0 +1,133 @@
#!/usr/bin/env python3
"""Live lab6 checks. No tokens, message contents or backend dumps are printed."""
import argparse
import base64
from datetime import datetime, timezone
import json
import math
import os
from pathlib import Path
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'tests'))
from client import Client, check
def get(url, auth=None):
headers = {'Accept': 'application/json'}
if auth:
headers['Authorization'] = 'Basic ' + base64.b64encode(auth.encode()).decode()
with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=15) as response:
return json.load(response)
def eventually(fn, timeout=90):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
result = fn()
if result:
return result
except (urllib.error.URLError, AssertionError, KeyError, ValueError):
pass
time.sleep(2)
raise AssertionError('Telemetry check timed out')
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--base-url', default='http://localhost:8080')
parser.add_argument('--prometheus-url', default='http://localhost:9090')
parser.add_argument('--grafana-url', default='http://localhost:3000')
parser.add_argument('--output', default='evidence/observability.json')
args = parser.parse_args()
auth = os.environ.get('GRAFANA_ADMIN_USER', 'admin') + ':' + (ROOT / 'secrets/grafana_admin_password').read_text().strip()
proxy = args.grafana_url + '/api/datasources/proxy/uid/'
def prom(query):
return get(args.prometheus_url + '/api/v1/query?' + urllib.parse.urlencode({'query': query}))['data']['result']
c = Client(args.base_url)
alice, bob, _, chat = c.bootstrap()
trace = uuid.uuid4().hex
parent = '00-' + trace + '-0123456789abcdef-01'
secret_marker = 'private-' + uuid.uuid4().hex
c.message(alice, chat, secret_marker)
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
att = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=sample.png', 202,
actor=alice, raw=content, headers={'Content-Type': 'image/png', 'traceparent': parent}, schema='Attachment')['json']
c.wait_ready(bob, att)
def trace_complete():
data = get(proxy + 'tempo/api/traces/' + trace, auth)
spans = []
def walk(obj):
if isinstance(obj, dict):
if 'spanId' in obj and 'name' in obj:
spans.append(obj)
for value in obj.values():
walk(value)
elif isinstance(obj, list):
for value in obj:
walk(value)
walk(data)
names = {span['name'] for span in spans}
return (data, spans) if {'attachment.enqueue', 'jobs:attachments publish', 'attachment.process', 's3.put_object', 'postgresql.publish_ready'} <= names else None
trace_data, spans = eventually(trace_complete)
by_id = {span['spanId']: span for span in spans}
consumer = next(span for span in spans if span['name'] == 'attachment.process')
publish = by_id.get(consumer['parentSpanId'])
check(publish and publish['name'] == 'jobs:attachments publish', 'consumer parent must be producer')
enqueue = by_id.get(publish['parentSpanId'])
check(enqueue and enqueue['name'] == 'attachment.enqueue', 'publish must continue durable outbox context')
server = by_id.get(enqueue['parentSpanId'])
check(server and server['name'].startswith('POST '), 'enqueue parent must be HTTP server')
query = '{service_name=~"messenger-api|messenger-worker"} | trace_id="' + trace + '"'
def correlated_logs():
result = get(proxy + 'loki/loki/api/v1/query_range?' + urllib.parse.urlencode({'query': query, 'limit': 1000}), auth)['data']['result']
services = {stream['stream'].get('service_name') for stream in result}
return result if {'messenger-api', 'messenger-worker'} <= services else None
logs = eventually(correlated_logs)
required = ['http_server_requests_total', 'http_server_request_duration_seconds_bucket', 'worker_jobs_total',
'worker_job_duration_seconds_bucket', 'attachment_ready_duration_seconds_bucket', 'queue_depth',
'queue_oldest_age', 'db_pool_used', 'db_pool_waiting', 'worker_busy', 'worker_capacity',
'process_memory_usage', 'process_cpu_time']
for name in required:
eventually(lambda: prom(name))
panel_count = 0
dashboard = get(args.grafana_url + '/api/dashboards/uid/messenger-observability', auth)['dashboard']
check(len(dashboard['panels']) == len(json.loads((ROOT / 'infra/grafana/dashboards/messenger.json').read_text())['panels']), 'Provisioned dashboard differs')
for panel in dashboard['panels']:
if panel['datasource']['uid'] != 'prometheus':
continue
for target in panel['targets']:
expr = target['expr'].replace('$__rate_interval', '1m')
result = prom(expr)
# Diagnostics are allowed to be absent when no failure has occurred.
if 'otelcol_' not in expr:
result = eventually(lambda: prom(expr), timeout=45)
panel_count += 1
for item in prom('http_server_requests_total'):
labels = item['metric']
check(not {'user_id','chat_id','message_id','attachment_id','request_id','filename'} & labels.keys(), 'High cardinality metric label')
check(chat['id'] not in json.dumps(labels), 'Raw chat ID in labels')
# Inspect full recent log/trace data in memory, never save private test values.
all_logs = get(proxy + 'loki/loki/api/v1/query_range?' + urllib.parse.urlencode({
'query': '{service_name=~"messenger-api|messenger-worker"}', 'limit': 5000}), auth)
exported = json.dumps([all_logs, trace_data])
for forbidden in [secret_marker, alice['token'], alice['registration']['password'], base64.b64encode(content).decode()]:
check(forbidden not in exported, 'Private test data leaked to telemetry')
report = {'timestamp': datetime.now(timezone.utc).isoformat(), 'result': 'PASS', 'trace_id': trace,
'span_names': sorted({s['name'] for s in spans}), 'consumer_parent_is_producer': True,
'log_services': sorted({s['stream']['service_name'] for s in logs}),
'metric_names_checked': required, 'dashboard_queries_checked': panel_count,
'privacy_canaries': 'absent in recent logs and upload trace'}
(ROOT / args.output).write_text(json.dumps(report, indent=2) + '\n')
print('PASS: real API -> outbox -> Redis -> worker -> S3/DB trace, correlated logs, metrics and dashboard queries; privacy canaries absent.')
if __name__ == '__main__':
main()
+33
View File
@@ -0,0 +1,33 @@
#include "telemetry.hpp"
#include <cassert>
#include <regex>
int main() {
telemetry::Runtime runtime("messenger-test");
assert(telemetry::route_template("/api/v1/chats/private-id/messages") == "/api/v1/chats/{chat_id}/messages");
assert(telemetry::route_template("/secret-token") == "unmatched");
assert(telemetry::route_template("/api/v1/attachments/private/content") == "/api/v1/attachments/{attachment_id}/content");
const std::string parent = "00-11223344556677889900aabbccddeeff-0123456789abcdef-01";
std::string producer;
{
telemetry::Span request("test.server", opentelemetry::trace::SpanKind::kServer, parent);
assert(telemetry::inject().substr(3,32) == parent.substr(3,32));
{
telemetry::Span publish("test.publish", opentelemetry::trace::SpanKind::kProducer);
producer = telemetry::inject();
assert(producer.substr(3,32) == parent.substr(3,32));
assert(producer != parent);
}
assert(telemetry::inject() != producer);
}
{
telemetry::Span consumer("test.consume", opentelemetry::trace::SpanKind::kConsumer, producer);
assert(telemetry::inject().substr(3,32) == parent.substr(3,32));
}
for (const auto& invalid : {"garbage", "00-00000000000000000000000000000000-0000000000000000-01"}) {
telemetry::Span span("test.invalid", opentelemetry::trace::SpanKind::kConsumer, invalid);
const auto actual = telemetry::inject();
assert(std::regex_match(actual, std::regex("00-[a-f0-9]{32}-[a-f0-9]{16}-01")));
assert(actual.substr(3,32) != parent.substr(3,32));
}
}
+34
View File
@@ -0,0 +1,34 @@
import unittest
from pathlib import Path
import yaml
ROOT=Path(__file__).resolve().parents[1]
class SecureConfig(unittest.TestCase):
def test_boundaries(self):
d=yaml.safe_load((ROOT/'compose.yaml').read_text())
for name,s in d['services'].items():
self.assertTrue(s['read_only'],name)
self.assertIn('no-new-privileges:true',s['security_opt'],name)
self.assertEqual(s['cap_drop'],['ALL'],name)
self.assertNotIn(str(s['user']).split(':')[0],['0','root'],name)
self.assertIn('mem_limit',s,name)
if name not in ['lb','openbao','grafana-tls']:self.assertNotIn('ports',s,name)
for name in ['api','api2','worker']:
s=d['services'][name]
self.assertNotIn('secrets/operator',str(s))
self.assertNotIn('DATABASE_URL_FILE',str(s))
self.assertNotIn('S3_SECRET_ACCESS_KEY_FILE',str(s))
for name in ['api','api2']:
self.assertEqual(d['services'][name]['environment']['APP_HOST'],'127.0.0.1')
self.assertTrue(d['services'][name]['network_mode'].startswith('service:'))
def test_identity_allowlists(self):
for identity,expected in [('api',{'client-api'}),('otel-collector',{'api','worker','prometheus'})]:
d=yaml.safe_load((ROOT/f'infra/envoy/{identity}.yaml').read_text())
actual=set()
for listener in d['static_resources']['listeners']:
for f in listener['filter_chains']:
tls=f['transport_socket']['typed_config']
self.assertTrue(tls['require_client_certificate'])
for san in tls['common_tls_context']['validation_context']['match_typed_subject_alt_names']:
self.assertEqual(san['san_type'],'DNS');actual.add(san['matcher']['exact'])
self.assertEqual(actual,expected)
if __name__=='__main__':unittest.main()