Реализовать ЛР 7 на оценку 4
Skeleton contracts / contracts (pull_request) Blocked by required conditions

This commit is contained in:
2026-12-04 16:15:18 +03:00
parent 7996ebbb48
commit 94a8a5c1da
29 changed files with 918 additions and 85 deletions
+26 -2
View File
@@ -70,8 +70,9 @@ make test-security-api
```
Первая команда запускает одноразовый операторский контейнер и выдаёт ему
только сертификаты для теста. Контейнер проверяет обе API-реплики, scoped
tokens OpenBao, ACL PostgreSQL, Redis, MinIO, RabbitMQ и отказ входа в OTLP.
сертификаты для теста. Контейнер проверяет обе API-реплики, scoped tokens OpenBao,
ACL PostgreSQL, Redis, MinIO, RabbitMQ и отказ входа в OTLP. В текущей реализации
команда также проверяет расширенную TLS-матрицу, rehash и очистку телеметрии.
Вторая измеряет Argon2id в контейнере API. Последняя исчерпывает login budget
источника, поэтому запускайте её после остальных сценариев с этого же клиента.
Перед повторным запуском дождитесь сброса окна входа, по умолчанию 60 секунд.
@@ -85,6 +86,29 @@ make test-expiry
docker compose up -d --wait --no-deps api lb
```
## Проверки уровня «4»
На выделенном проекте, после `make up`:
```sh
make test test-security test-observability test-security-internal test-hardening
make test-lifecycle
make test-persistence test-failover-both
make test-login-budget
SCAN_DIR=/tmp/lab7-security-scan make scan-security
```
`test-lifecycle` реально меняет пароль PostgreSQL для worker и клиентский
сертификат HAProxy. Он использует операторскую конфигурацию соответствующего
проекта и проверяет сохранившие работоспособность контейнеры. В случае ошибки
на этапе ротации восстанавливает прежнюю конфигурацию. Проводить сценарий
следует на своём тестовом стенде. `test-login-budget` исчерпывает окно входа,
поэтому перед следующим сценарием входа дождитесь сброса лимита.
Сканер записывает JSON вне репозитория. Он получает архив образа и отдельный
файл зависимостей. Docker socket и локальные секреты в контейнер сканера
не монтируются. Сканирование обновляет базу уязвимостей из реестра Trivy.
## Наблюдаемость
После `make test` запустите `make test-observability`. Проверка находит в Grafana
+65
View File
@@ -0,0 +1,65 @@
"""Network-side probes for the operator's rotation demonstration."""
import asyncio
import json
from pathlib import Path
import socket
import ssl
import sys
import tempfile
import asyncpg
from security_internal import require, tls
async def check_passwords(values):
for label, url in values.items():
dsn = url.replace('postgresql+asyncpg://', 'postgresql://', 1)
try:
connection = await asyncpg.connect(dsn, ssl=tls(), timeout=5)
except asyncpg.InvalidPasswordError:
require(label == 'old', 'PostgreSQL refused the replacement credential')
else:
try:
require(label == 'new', 'PostgreSQL accepted the old credential on a fresh connection')
require(await connection.fetchval('SELECT current_user') == 'messenger_worker',
'Unexpected PostgreSQL identity')
finally:
await connection.close()
print('PASS: worker password rotated; fresh PostgreSQL connections reject the old password')
def check_leaves(previous):
request = b'GET /health/ready HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n'
addresses = {info[4][0] for info in socket.getaddrinfo('api', 8443, type=socket.SOCK_STREAM)}
require(len(addresses) == 2, 'Expected both API replicas after leaf rotation')
with tempfile.TemporaryDirectory() as directory:
key, cert = Path(directory) / 'old.key', Path(directory) / 'old.crt'
key.write_text(previous['private.key'])
key.chmod(0o600)
cert.write_text(previous['public.crt'])
for host in addresses:
old = tls()
old.load_cert_chain(cert, key)
for context, permitted in ((tls('lb'), True), (old, False)):
with socket.create_connection((host, 8443), timeout=5) as conn:
try:
with context.wrap_socket(conn, server_hostname='api') as channel:
channel.sendall(request)
result = channel.recv(4096)
except ssl.SSLCertVerificationError:
raise
except (ssl.SSLError, BrokenPipeError, ConnectionResetError):
result = b''
require(result.startswith(b'HTTP/1.1 200 ') if permitted else not result,
'API leaf trust did not switch from the old LB certificate to the new one')
print('PASS: both API replicas reject the old LB leaf and accept the new leaf')
if __name__ == '__main__':
payload = json.load(sys.stdin)
if sys.argv[1] == 'postgres':
asyncio.run(check_passwords(payload))
else:
check_leaves(payload)
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
"""Measure concurrent bad passwords and healthy authenticated reads on the lab."""
import base64
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
import json
from statistics import quantiles
from client import Client, arguments, check, run
LOGIN = '/api/v1/auth/sessions'
READ = '/api/v1/users/me'
def p95(samples):
return round(1000 * quantiles(samples, n=20, method='inclusive')[18], 2)
def main():
def options(parser):
parser.add_argument('--budget', type=int, default=20)
args = arguments(__doc__, options)
client = Client(args.base_url, args.ca_file)
actor = client.user('budget')
username = actor['registration']['username']
invalid = base64.b64encode(f'{username}:wrong-synthetic-password'.encode()).decode()
def wrong():
return client.call('POST', LOGIN, [401, 429], headers={'Authorization': 'Basic ' + invalid})
def normal():
return client.call('GET', READ, 200, actor=actor, schema='User')
baseline = [normal()['elapsed'] for _ in range(20)]
with ThreadPoolExecutor(max_workers=16) as pool:
attempts, reads = [], []
for _ in range(24):
attempts.extend(pool.submit(wrong) for _ in range(3))
reads.append(pool.submit(normal))
results = [future.result() for future in attempts]
regular = [future.result() for future in reads]
statuses = Counter(item['status'] for item in results)
replicas = {item['headers']['X-Instance-Id'] for item in results}
shared = [item for item in results if item['status'] == 429 and
item['json']['error']['message'] == 'слишком много попыток входа']
check(0 < statuses[401] < args.budget, 'Expected some password work within the shared budget')
check(shared and len(replicas) == 2, 'Expected shared throttling with two replicas')
check(all(int(item['headers']['Retry-After']) > 0 for item in results if item['status'] == 429),
'Retry-After must be positive')
print(json.dumps({
'parallel_clients': 16,
'bad_logins': len(results),
'password_verifications': statuses[401],
'shared_limit_429': len(shared),
'slot_limit_429': statuses[429] - len(shared),
'api_replicas': len(replicas),
'healthy_reads_under_load': len(regular),
'read_p95_ms_baseline': p95(baseline),
'read_p95_ms_under_load': p95([item['elapsed'] for item in regular]),
}))
if __name__ == '__main__':
run(main)
+157 -11
View File
@@ -7,18 +7,22 @@ import json
import os
from pathlib import Path
import socket
import struct
import ssl
import time
from urllib.error import HTTPError
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import HTTPSHandler, ProxyHandler, Request, build_opener
from uuid import uuid4
import aio_pika
from aiormq.exceptions import ChannelAccessRefused
from argon2 import PasswordHasher, extract_parameters
import asyncpg
from minio import Minio
from minio.error import S3Error
from opentelemetry.proto.collector.logs.v1.logs_service_pb2 import ExportLogsServiceRequest
from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest
from urllib3 import PoolManager
from app.config.bao import BaoClient, BaoError
@@ -43,6 +47,33 @@ def require(condition, description):
raise RuntimeError(description)
def audit_server_certificates():
services = (
('api', 8443, 'lb'), ('postgres', 5432, None), ('redis', 6379, None),
('s3', 9000, None), ('broker', 5671, 'worker'), ('openbao', 8200, 'worker'),
('otel-collector', 4318, 'api'), ('otel-collector', 8888, 'scrape'),
('otel-collector', 8889, 'scrape'), ('loki', 3100, 'query'),
('tempo', 3200, 'query'), ('tempo', 4318, 'export'),
('prometheus', 9090, 'query'), ('grafana', 3000, None),
)
for host, port, role in services:
for context, name, expected in (
(tls(role), host, True),
(tls(role), 'wrong-name.invalid', False),
(ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT), host, False),
):
with socket.create_connection((host, port), timeout=5) as conn:
if host == 'postgres':
conn.sendall(struct.pack('!II', 8, 80877103))
require(conn.recv(1) == b'S', 'PostgreSQL refused SSLRequest')
try:
with context.wrap_socket(conn, server_hostname=name):
require(expected, f'{host}:{port} accepted invalid server trust')
except ssl.SSLCertVerificationError:
require(not expected, f'{host}:{port} rejected the configured CA or hostname')
print(f'PASS: CA and hostname verified on all {len(services)} internal TLS endpoints')
def check_api_replicas():
addresses = {item[4][0] for item in socket.getaddrinfo('api', 8443, type=socket.SOCK_STREAM)}
require(len(addresses) == 2, f'Expected two API replicas, found {len(addresses)}')
@@ -135,7 +166,7 @@ async def check_store_permissions(bundles):
await redis.aclose()
for role in ('publisher', 'worker'):
async with await aio_pika.connect(bundles[role]['BROKER_URL'], ssl_context=tls(), timeout=5) as broker:
async with await aio_pika.connect(bundles[role]['BROKER_URL'], ssl_context=tls(role), timeout=5) as broker:
channel = await broker.channel()
try:
await channel.declare_queue(f'negative-test-{uuid4().hex}', auto_delete=True, exclusive=True)
@@ -143,9 +174,32 @@ async def check_store_permissions(bundles):
pass
else:
raise RuntimeError(f'{role} can create unrelated RabbitMQ queues')
await check_broker_identity(bundles['publisher']['BROKER_URL'])
print('PASS: PostgreSQL, Redis and RabbitMQ accept scoped TLS identities and deny unrelated access')
async def check_broker_identity(url: str):
for role in (None, 'foreign', 'query'):
try:
connection = await aio_pika.connect(url, ssl_context=tls(role), timeout=5)
except (OSError, aio_pika.exceptions.AMQPException):
continue
await connection.close()
raise RuntimeError(f'RabbitMQ admitted unexpected certificate {role!r}')
claimed_publisher = url.replace('://', '://messenger-publisher@', 1)
async with await aio_pika.connect(claimed_publisher, ssl_context=tls('worker'), timeout=5) as broker:
channel = await broker.channel()
exchange = await channel.get_exchange('attachments', ensure=False)
try:
await exchange.publish(aio_pika.Message(b'{}'), routing_key='negative-test')
except ChannelAccessRefused:
pass
else:
raise RuntimeError('The worker certificate may publish as the publisher')
print('PASS: broker requires a certificate and derives publisher/worker ACL from its CN')
def check_s3(bundles):
clients = {
role: Minio('s3:9000', credentials['S3_ACCESS_KEY_ID'], credentials['S3_SECRET_ACCESS_KEY'],
@@ -169,17 +223,107 @@ def check_s3(bundles):
print('PASS: MinIO TLS, API stages data, worker can read but not overwrite staging')
def check_telemetry_roles():
opener = build_opener(ProxyHandler({}), HTTPSHandler(context=tls('query')))
request = Request('https://otel-collector:4318/v1/logs', data=b'',
headers={'Content-Type': 'application/x-protobuf'})
def http_status(url, role, *, data=None, headers=None):
opener = build_opener(ProxyHandler({}), HTTPSHandler(context=tls(role)))
try:
opener.open(request, timeout=5).close()
with opener.open(Request(url, data=data, headers=headers or {}), timeout=6) as response:
return response.status
except HTTPError as error:
require(error.code == 403, 'Expected 403 for a Grafana identity on OTLP ingest')
else:
raise RuntimeError('Grafana identity can send OTLP')
print('PASS: query identity cannot submit telemetry')
error.close()
return error.code
def check_telemetry_roles():
otlp = {'Content-Type': 'application/x-protobuf'}
ingest = 'https://otel-collector:4318/v1/logs'
for role in ('api', 'publisher', 'worker'):
require(http_status(ingest, role, data=b'', headers=otlp) == 200,
f'Collector refuses the registered {role} identity')
for role in (None, 'foreign'):
try:
http_status(ingest, role, data=b'', headers=otlp)
except (ssl.SSLError, BrokenPipeError, ConnectionResetError):
continue
except URLError as error:
require(isinstance(error.reason, (ssl.SSLError, BrokenPipeError, ConnectionResetError)),
'Collector failure was not a TLS rejection')
else:
raise RuntimeError('Collector returned HTTP to an untrusted TLS client')
require(http_status(ingest, 'query', data=b'', headers=otlp) == 403,
'Grafana identity can write OTLP')
for port in (8888, 8889):
target = f'https://otel-collector:{port}/metrics'
require(http_status(target, 'scrape') == 200, 'Prometheus scrape denied')
require(http_status(target, 'query') == 403, 'Grafana can bypass Prometheus')
logs = ExportLogsServiceRequest()
log_resource = logs.resource_logs.add()
label = log_resource.resource.attributes.add(key='service.name')
label.value.string_value = 'lab7-audit'
record = log_resource.scope_logs.add().log_records.add(time_unix_nano=time.time_ns())
record.body.string_value = 'synthetic TLS audit'
traces = ExportTraceServiceRequest()
trace_resource = traces.resource_spans.add()
label = trace_resource.resource.attributes.add(key='service.name')
label.value.string_value = 'lab7-audit'
trace_resource.scope_spans.add().spans.add(
trace_id=uuid4().bytes, span_id=uuid4().bytes[:8], name='synthetic TLS audit',
start_time_unix_nano=time.time_ns(), end_time_unix_nano=time.time_ns(),
)
for target, payload in (
('https://loki:3100/otlp/v1/logs', logs.SerializeToString()),
('https://tempo:4318/v1/traces', traces.SerializeToString()),
):
result = http_status(target, 'export', data=payload, headers=otlp)
require(result in (200, 204), f'Collector identity got HTTP {result} from {target}')
require(http_status(target, 'query', data=payload, headers=otlp) == 403,
'Grafana identity may write to a telemetry backend')
query_targets = (
('https://prometheus:9090/api/v1/query?query=vector%281%29', 200),
('https://loki:3100/loki/api/v1/labels', 200),
('https://tempo:3200/api/traces/' + 'f' * 32, 404),
)
for target, expected in query_targets:
require(http_status(target, 'query') == expected, 'Grafana query failed')
require(http_status(target, 'export') == 403, 'Collector can query telemetry backends')
require(http_status('https://grafana:3000/api/org', None) == 401,
'Grafana granted anonymous org access')
print('PASS: OTLP, scrape and query TLS identities are separated in both directions')
async def check_password_upgrade(dsn):
api_url = 'https://api:8443/api/v1'
username = 'rehash_' + uuid4().hex[:16]
password = 'synthetic-' + uuid4().hex
data = json.dumps({'username': username, 'display_name': 'Rehash fixture', 'password': password})
require(http_status(f'{api_url}/users', 'lb', data=data.encode(),
headers={'Content-Type': 'application/json'}) == 201,
'Rehash fixture registration failed')
def login(value):
auth = base64.b64encode(f'{username}:{value}'.encode()).decode()
return http_status(f'{api_url}/auth/sessions', 'lb', data=b'',
headers={'Authorization': 'Basic ' + auth})
conn = await asyncpg.connect(dsn.replace('postgresql+asyncpg://', 'postgresql://', 1),
ssl=tls(), timeout=5)
try:
legacy = PasswordHasher(memory_cost=8192, time_cost=2, parallelism=1).hash(password)
await conn.execute('UPDATE users SET password_hash=$1 WHERE username=$2', legacy, username)
select = 'SELECT password_hash FROM users WHERE username=$1'
require(login('incorrect') == 401, 'Incorrect fixture password was accepted')
require(await conn.fetchval(select, username) == legacy, 'Rejected login changed the hash')
require(login(password) == 201, 'Legacy fixture password was refused')
actual = await conn.fetchval(select, username)
require(actual != legacy and extract_parameters(actual).memory_cost >= 19456,
'Successful login did not upgrade the stored hash')
require(login(password) == 201, 'The new hash is invalid')
finally:
await conn.close()
print('PASS: only a successful login upgrades a legacy Argon2id hash')
def check_telemetry_privacy():
@@ -238,10 +382,12 @@ def check_telemetry_privacy():
if __name__ == '__main__':
audit_server_certificates()
check_api_replicas()
values = check_bao()
check_s3(values)
os.environ['TLS_CA_FILE'] = CA
asyncio.run(check_store_permissions(values))
asyncio.run(check_password_upgrade(values['api']['DATABASE_URL']))
check_telemetry_roles()
check_telemetry_privacy()