lab7: BROKER_URL из окружения, Redis operator для регрессии ACL, исправления тестов, no-new-privileges tempo-init; перенос исправлений lab6

This commit is contained in:
2026-11-12 14:19:15 +03:00
parent b5b55fda89
commit 1c453e9f0a
16 changed files with 104 additions and 33 deletions
+2
View File
@@ -174,6 +174,8 @@ def scenario_db_gap(c):
def scenario_security(c):
alice, _, _, chat = c.bootstrap()
att = upload(c, alice, chat, fixture('small.png'))['json']
# С lab5 worker переносит оригинал staging s/ → o/: ключ берём после ready.
wait_status(c, alice, att['id'], ('ready',))
key = object_key(att['id'])
url = 'http://s3:9000/%s/%s' % (BUCKET, key)
# Анонимно изнутри сети стенда (из контейнера API): объект и листинг закрыты.
+2 -2
View File
@@ -89,7 +89,7 @@ class Uploader:
while not self.stop_ev.is_set():
try:
r = self.c.call('POST', '/api/v1/chats/%s/attachments?filename=u.png' % self.chat['id'], 202,
actor=self.actor, raw=SAMPLE, headers={'Content-Type': 'image/png'})
actor=self.actor, raw=SAMPLE, headers={'Content-Type': 'image/png'}, schema='Attachment')
self.ids.append((time.time(), r['json']['id']))
except Failure:
self.errors += 1
@@ -156,7 +156,7 @@ def main():
# первое задание, принятое после реакции, — когда стало ready (восстановление обработки)
probe_att = c.call('POST', '/api/v1/chats/%s/attachments?filename=after.png' % chat['id'], 202, actor=alice, raw=SAMPLE,
headers={'Content-Type': 'image/png'})['json']
headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
meta = wait_status(c, bob, probe_att['id'], ('ready', 'failed'), timeout=240)
res['processing_restored_seconds_after_response'] = round(time.time() - t_done, 1)
check(meta['status'] == 'ready', 'worker did not recover with the new identity')
+24 -7
View File
@@ -114,7 +114,7 @@ def scenario_signals(c):
spans, _ = o.tempo_trace(tid)
server = [s for s in spans if s['kind'] in ('SPAN_KIND_SERVER', 2, '2') or s['name'].startswith('POST /api')]
check(server, 'no server span')
logs = o.wait_until(lambda: o.loki('{service_name="messenger-api"} | trace_id="%s"' % tid, t0), 60)
logs = o.wait_until(lambda: o.loki('{service_name="messenger-api"} | trace_id="%s"' % tid, t0), 120)
check(logs, 'no API log with trace_id ' + tid)
log_line = logs[0][1]
res['request'] = {'request_id': rid_msg, 'trace_id': tid, 'spans': tree(spans)[:12],
@@ -141,7 +141,7 @@ def scenario_signals(c):
db_in_worker = sorted({s['name'] for s in spans2 if s['service'] == 'messenger-worker' and s['name'] not in
('attachment.process process', 'image.decode', 'image.variants') and not s['name'].startswith('S3')})
check(all(links.values()), 'broken causal chain: %s' % links)
wlogs = o.wait_until(lambda: o.loki('{service_name="messenger-worker"} | trace_id="%s"' % tid2, t0), 60)
wlogs = o.wait_until(lambda: o.loki('{service_name="messenger-worker"} | trace_id="%s"' % tid2, t0), 120)
check(wlogs, 'no worker log with the upload trace_id')
res['upload'] = {'request_id': rid_up, 'trace_id': tid2, 'services': services, 'links': links,
'span_count': len(spans2), 'worker_db_spans': db_in_worker[:10], 'tree': tree(spans2)[:40],
@@ -399,13 +399,30 @@ def scenario_backend_down(c):
compose('up', '-d', '--wait', '--no-deps', 'tempo', 'loki', timeout=180)
t_up = time.time()
rid = 'obs-after-' + uuid.uuid4().hex[:8]
c.call('POST', '/api/v1/chats/%s/messages' % chat['id'], 201, actor=alice, body={'text': 'after'},
headers={'Idempotency-Key': uuid.uuid4().hex, 'X-Request-Id': rid})
# gRPC-клиент Collector переподключается к Tempo с экспоненциальной паузой (до 120 s):
# измеряем, через сколько секунд после возврата Tempo новые трассы снова доступны.
got = o.find_trace('{span.request_id="%s"}' % rid, t_up - 2, timeout=240)
sent0 = q('sum({__name__=~"otelcol_exporter_sent_spans(_total)?", exporter="otlp/tempo"})')
# Новые запросы после возврата Tempo; трасса ищется по ID из заголовка traceresponse
# (минуя поиск) — сначала каждые 5 s новый запрос, пока трасса не появится.
got, tids = None, []
end = time.time() + 240
while time.time() < end and not got:
r = c.call('POST', '/api/v1/chats/%s/messages' % chat['id'], 201, actor=alice, body={'text': 'after'},
headers={'Idempotency-Key': uuid.uuid4().hex, 'X-Request-Id': rid})
tid = (r['headers'].get('traceresponse') or '--').split('-')[1]
tids.append(tid)
for t in tids:
try:
if o.tempo_trace(t)[0]:
got = t
break
except Exception:
pass
if not got:
time.sleep(5)
phase['tempo_spans_exported_after_up'] = q('sum({__name__=~"otelcol_exporter_sent_spans(_total)?", exporter="otlp/tempo"})') - sent0
phase['refused_spans_total'] = q('sum({__name__=~"otelcol_receiver_refused_spans(_total)?"})')
phase['new_trace_after_recovery'] = bool(got)
phase['traces_visible_seconds_after_tempo_up'] = round(time.time() - t_up, 1) if got else None
phase['probe_requests_after_up'] = len(tids)
# Фаза 2: остановлен сам Collector — SDK отбрасывает по ограниченной очереди
compose('stop', 'otel-collector')
t_cd = time.time()
+12
View File
@@ -25,6 +25,18 @@ def _auth():
def grafana(path, params=None, method='GET', body=None, timeout=30):
"""Запрос к Grafana; 502/503/504 (backend перезапускается) — повтор до ~60 s."""
import urllib.error
for attempt in range(12):
try:
return _grafana(path, params, method, body, timeout)
except urllib.error.HTTPError as e:
if e.code not in (502, 503, 504) or attempt == 11:
raise
time.sleep(5)
def _grafana(path, params=None, method='GET', body=None, timeout=30):
url = GRAFANA + path
if params:
url += ('&' if '?' in url else '?') + urllib.parse.urlencode(params)
+8 -4
View File
@@ -23,7 +23,11 @@ WHITESPACE_PASSWORDS = (' ' * 12, '\t' * 12, '  ' * 8)
def redis_cli(*args):
r = subprocess.run(['docker', 'compose', 'exec', '-T', 'redis', 'redis-cli', *args],
# Lab7: Redis только по TLS, пользователь default выключен — операторская учётка
# (пароль из secrets/operator, передаётся через окружение exec, не аргументом).
pw = (ROOT / 'secrets' / 'operator' / 'redis_operator_password').read_text().strip()
r = subprocess.run(['docker', 'compose', 'exec', '-T', '-e', 'REDISCLI_AUTH=' + pw, 'redis', 'redis-cli', '--tls',
'--cacert', '/run/secrets/ca.crt', '-h', 'redis', '--user', 'operator', '--no-auth-warning', *args],
cwd=ROOT, capture_output=True, text=True, timeout=30)
check(r.returncode == 0, 'redis-cli failed: ' + r.stderr.strip())
return r.stdout.strip()
@@ -35,7 +39,7 @@ def visibility_case(c, alice, bob, chat, denied):
# Прогреваем кэш на обеих репликах.
for _ in range(4):
c.call('GET', path, actor=bob, schema='MessagePage')
redis_cli('ACL', 'SETUSER', 'default', *('-' + cmd for cmd in denied))
redis_cli('ACL', 'SETUSER', 'api', *('-' + cmd for cmd in denied)) # lab7: пользователь API — api
try:
sent = c.message(alice, chat, 'после запрета ' + '+'.join(denied))['json']
# Каждое следующее чтение (через любую реплику) видит подтверждённую запись.
@@ -47,8 +51,8 @@ def visibility_case(c, alice, bob, chat, denied):
# встать раньше старых, поэтому проверяем наличие, а не префикс.
check(set(before) <= set(ids), 'previously confirmed messages missing')
finally:
# reset — чтобы снять и точечные запреты, независимо от порядка правил.
redis_cli('ACL', 'SETUSER', 'default', 'reset', 'on', 'nopass', '~*', '&*', '+@all')
# Исходные права api — из ACL-файла оператора (там же hash пароля).
redis_cli('ACL', 'LOAD')
return len(before) + 1
+6 -6
View File
@@ -129,7 +129,7 @@ def scenario_mtls(c):
'trusted_ca_cn_lb': probe('amqp', '-cert', p + 'lb.crt', '-key', p + 'lb.key'),
'worker': probe('amqp', '-cert', p + 'worker.crt', '-key', p + 'worker.key'),
'relay': probe('amqp', '-cert', p + 'relay.crt', '-key', p + 'relay.key'),
'plaintext_5672': probe('plain', '-addr', 'rabbitmq:5672', '-send', 'AMQP\x00\x00\x09\x01'),
'plaintext_5672': probe('plain', '-addr', 'rabbitmq:5672', '-send', 'AMQP'),
}
for k in ('foreign_ca', 'trusted_ca_cn_attacker', 'trusted_ca_cn_lb'):
check(denied(broker[k].get('connect')), 'broker %s not rejected: %s' % (k, broker[k]))
@@ -190,7 +190,7 @@ def scenario_mtls(c):
def scenario_acl(c):
alice, bob, eve, chat = c.bootstrap()
att = c.call('POST', '/api/v1/chats/%s/attachments?filename=a.png' % chat['id'], 202, actor=alice, raw=SAMPLE,
headers={'Content-Type': 'image/png'})['json']
headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
wait_status(c, bob, att['id'], ('ready',))
res = {}
res['outsider_metadata'] = c.call('GET', '/api/v1/attachments/' + att['id'], (404,), actor=eve)['status']
@@ -350,7 +350,7 @@ def scenario_rotation(c):
time.sleep(35) # SECRETS_REFRESH 30 s
# Старые соединения закрываются (как при отзыве); новые открываются с новым паролем
psql("SELECT count(pg_terminate_backend(pid)) FROM pg_stat_activity WHERE usename = 'app_api'")
time.sleep(5)
time.sleep(35) # pgx health check (30 s) выбрасывает разорванные соединения
res['db_old_password'] = probe('db', '-user', 'app_api', '-stdin', stdin=old_pw).get('connect')
check(denied(res['db_old_password']), 'old db password still works')
res['api_after_db_rotation'] = c.call('GET', '/api/v1/chats', actor=alice)['status']
@@ -358,7 +358,7 @@ def scenario_rotation(c):
bootstrap('rotate-s3', 'worker')
time.sleep(35)
att = c.call('POST', '/api/v1/chats/%s/attachments?filename=r.png' % chat['id'], 202, actor=alice, raw=SAMPLE,
headers={'Content-Type': 'image/png'})['json']
headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
res['upload_after_s3_rotation'] = wait_status(c, bob, att['id'], ('ready', 'failed'), timeout=150)['status']
check(res['upload_after_s3_rotation'] == 'ready', 'worker did not pick rotated S3 key')
# 3) leaf API: перевыпуск на месте, без рестарта; LB видит новый serial
@@ -409,14 +409,14 @@ def scenario_lifecycle(c):
bootstrap('seal')
t_seal = time.time()
att = c.call('POST', '/api/v1/chats/%s/attachments?filename=s.png' % chat['id'], 202, actor=alice, raw=SAMPLE,
headers={'Content-Type': 'image/png'})['json']
headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
res['upload_while_sealed'] = wait_status(c, bob, att['id'], ('ready', 'failed'), timeout=120)['status']
compose('restart', 'worker')
time.sleep(25)
wlogs = compose('logs', '--no-color', '--since', '30s', 'worker').stdout
res['worker_restart_while_sealed'] = 'openbao not ready' in wlogs or 'sealed' in wlogs
att2 = c.call('POST', '/api/v1/chats/%s/attachments?filename=s2.png' % chat['id'], 202, actor=alice, raw=SAMPLE,
headers={'Content-Type': 'image/png'})['json']
headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
time.sleep(5)
res['upload_accepted_while_worker_blocked'] = att2['status']
bootstrap('unseal')