feat: import lab 7 security implementation
This commit is contained in:
@@ -0,0 +1,526 @@
|
||||
"""Лаба 7, защита входа: настройки `ARGON2_*` / `KDF_*` / `LOGIN_*`, бюджет
|
||||
хэшей, пересчёт старого хэша, предел неудачных входов (Valkey и счётчики
|
||||
процесса), адрес клиента от LB, порядок проверок входа, предел тела.
|
||||
|
||||
Без стенда. Valkey — подделка `Cache`, которая выполняет те же два сценария
|
||||
Lua на словаре (их смысл; сами сценарии против настоящего Valkey проверяют
|
||||
тесты `make failure-checks` и `student-tests/test_login_protection.py`).
|
||||
Argon2id — настоящий, с минимальными параметрами рубрики (быстро).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from argon2 import PasswordHasher, profiles
|
||||
|
||||
from src.api.body_limit import BODY_TOO_LARGE, BodyLimitMiddleware
|
||||
from src.api.deps import client_address
|
||||
from src.config import Auth, ConfigError, Settings
|
||||
from src.domain import Credentials, Session, User
|
||||
from src.errors import (
|
||||
InvalidCredentials,
|
||||
LoginRateLimited,
|
||||
PasswordHashingBusy,
|
||||
Unavailable,
|
||||
)
|
||||
from src.login_limit import (
|
||||
ACQUIRE_SCRIPT,
|
||||
LocalLoginLimiter,
|
||||
LoginLimiter,
|
||||
address_part,
|
||||
login_keys,
|
||||
)
|
||||
from src.passwords import KdfBudget, Passwords, hash_parameters
|
||||
from src.services.sessions import SessionService
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
FAST = Auth(argon2_memory_kib=19456, argon2_iterations=2, argon2_parallelism=1)
|
||||
|
||||
|
||||
# --- настройки ---------------------------------------------------------------
|
||||
|
||||
|
||||
def test_auth_defaults_and_bounds() -> None:
|
||||
auth = Settings.from_env({}).auth
|
||||
assert auth.argon2_iterations >= 2
|
||||
assert auth.argon2_memory_kib >= 19456
|
||||
assert auth.argon2_parallelism >= 1
|
||||
assert (
|
||||
auth.login_window,
|
||||
auth.login_max_failures_per_account,
|
||||
auth.login_max_failures_per_address,
|
||||
) == (300, 10, 200)
|
||||
for name, value in (
|
||||
("ARGON2_MEMORY_KIB", "19455"),
|
||||
("ARGON2_ITERATIONS", "1"),
|
||||
("ARGON2_PARALLELISM", "0"),
|
||||
("KDF_CONCURRENCY", "0"),
|
||||
("KDF_MAX_WAITING", "-1"),
|
||||
("KDF_WAIT_TIMEOUT", "0"),
|
||||
("KDF_WAIT_TIMEOUT", "6"),
|
||||
("LOGIN_WINDOW_SECONDS", "0"),
|
||||
("LOGIN_MAX_FAILURES_PER_ACCOUNT", "-1"),
|
||||
):
|
||||
with pytest.raises(ConfigError, match=name):
|
||||
Settings.from_env({name: value})
|
||||
override = Settings.from_env(
|
||||
{"LOGIN_MAX_FAILURES_PER_ACCOUNT": "3", "ARGON2_MEMORY_KIB": "19456"}
|
||||
).auth
|
||||
assert override.login_max_failures_per_account == 3
|
||||
assert override.argon2_memory_kib == 19456
|
||||
|
||||
|
||||
# --- Argon2id и бюджет -------------------------------------------------------
|
||||
|
||||
|
||||
def test_hash_carries_configured_parameters_and_rehash_flag() -> None:
|
||||
passwords = Passwords(FAST)
|
||||
password = "correct horse battery"
|
||||
|
||||
async def scenario() -> None:
|
||||
current = await passwords.hash(password)
|
||||
assert current.startswith("$argon2id$v=19$m=19456,t=2,p=1$")
|
||||
assert hash_parameters(current) == passwords.parameters
|
||||
check = await passwords.verify(password=password, password_hash=current)
|
||||
assert (check.valid, check.needs_rehash) == (True, False)
|
||||
# прежние параметры лабы 6 (RFC 9106 low memory) — верен, нужен пересчёт
|
||||
old = PasswordHasher.from_parameters(profiles.RFC_9106_LOW_MEMORY).hash(
|
||||
password
|
||||
)
|
||||
check = await passwords.verify(password=password, password_hash=old)
|
||||
assert (check.valid, check.needs_rehash) == (True, True)
|
||||
wrong = await passwords.verify(password="wrong password!", password_hash=old)
|
||||
assert (wrong.valid, wrong.needs_rehash) == (False, False)
|
||||
unknown = await passwords.verify(password=password, password_hash=None)
|
||||
assert unknown.valid is False
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_kdf_budget_limits_threads_and_queue() -> None:
|
||||
budget = KdfBudget(concurrency=1, max_waiting=1, wait_timeout=0.3)
|
||||
active = {"now": 0, "peak": 0}
|
||||
lock = threading.Lock()
|
||||
|
||||
def slow() -> int:
|
||||
with lock:
|
||||
active["now"] += 1
|
||||
active["peak"] = max(active["peak"], active["now"])
|
||||
time.sleep(0.2)
|
||||
with lock:
|
||||
active["now"] -= 1
|
||||
return 1
|
||||
|
||||
async def scenario() -> list:
|
||||
return await asyncio.gather(
|
||||
*(budget.run(slow) for _ in range(4)), return_exceptions=True
|
||||
)
|
||||
|
||||
results = asyncio.run(scenario())
|
||||
busy = [r for r in results if isinstance(r, PasswordHashingBusy)]
|
||||
# одно место и одно ждущее: двое выполнены, двое сразу — 429
|
||||
assert results.count(1) == 2, results
|
||||
assert len(busy) == 2
|
||||
assert all(error.waited_ms == 0 for error in busy)
|
||||
assert active["peak"] == 1
|
||||
|
||||
|
||||
def test_kdf_budget_wait_timeout_and_cancelled_waiter() -> None:
|
||||
budget = KdfBudget(concurrency=1, max_waiting=4, wait_timeout=0.2)
|
||||
|
||||
async def scenario() -> None:
|
||||
holder = asyncio.create_task(budget.run(time.sleep, 0.6))
|
||||
await asyncio.sleep(0.05)
|
||||
started = time.monotonic()
|
||||
with pytest.raises(PasswordHashingBusy) as caught:
|
||||
await budget.run(time.sleep, 0)
|
||||
assert time.monotonic() - started >= 0.19
|
||||
assert caught.value.waited_ms >= 190
|
||||
# отменённый ждущий место не занимает
|
||||
waiter = asyncio.create_task(budget.run(time.sleep, 0))
|
||||
await asyncio.sleep(0.05)
|
||||
waiter.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await waiter
|
||||
await holder
|
||||
assert budget._waiting == 0
|
||||
await budget.run(time.sleep, 0)
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
# --- предел неудачных входов -------------------------------------------------
|
||||
|
||||
|
||||
@dataclass
|
||||
class FakeCache:
|
||||
"""Сценарии `login_limit` на словаре: значение и срок ключа."""
|
||||
|
||||
namespace: str = "messenger"
|
||||
down: bool = False
|
||||
data: dict[str, list] = field(default_factory=dict)
|
||||
calls: int = 0
|
||||
|
||||
async def run_script(self, script, *, keys, args): # noqa: ANN001
|
||||
self.calls += 1
|
||||
if self.down:
|
||||
return None
|
||||
now = time.monotonic()
|
||||
for key in list(self.data):
|
||||
if self.data[key][1] <= now:
|
||||
del self.data[key]
|
||||
if script == ACQUIRE_SCRIPT:
|
||||
window, limits = int(args[0]), [int(a) for a in args[1:]]
|
||||
wait = 0
|
||||
for key, limit in zip(keys, limits, strict=True):
|
||||
value = self.data.get(key)
|
||||
if value and value[0] >= limit:
|
||||
wait = max(wait, max(1, int(value[1] - now)))
|
||||
if wait:
|
||||
return wait
|
||||
for key in keys:
|
||||
value = self.data.setdefault(key, [0, now + window])
|
||||
value[0] += 1
|
||||
return 0
|
||||
for key, mode in zip(keys, args, strict=True):
|
||||
value = self.data.get(key)
|
||||
if value is None:
|
||||
continue
|
||||
value[0] -= 1
|
||||
if mode == "del" or value[0] <= 0:
|
||||
del self.data[key]
|
||||
return 1
|
||||
|
||||
|
||||
def _limiter(cache: FakeCache, account: int = 3, address: int = 6) -> LoginLimiter:
|
||||
return LoginLimiter(
|
||||
cache,
|
||||
window=10,
|
||||
max_failures_per_account=account,
|
||||
max_failures_per_address=address,
|
||||
)
|
||||
|
||||
|
||||
def test_keys_hold_no_username_or_address() -> None:
|
||||
account, address = login_keys(
|
||||
namespace="messenger", username="alice_1", address="198.51.100.7"
|
||||
)
|
||||
assert account.startswith("messenger:v1:messenger:login:ua:")
|
||||
assert address.startswith("messenger:v1:messenger:login:a:")
|
||||
for key in (account, address):
|
||||
assert "alice_1" not in key
|
||||
assert "198.51.100.7" not in key
|
||||
assert address_part("2001:db8:1:2:3:4:5:6") == "2001:db8:1:2::/64"
|
||||
assert address_part("::ffff:192.0.2.1") == "192.0.2.1"
|
||||
assert address_part("192.0.2.1") == "192.0.2.1"
|
||||
|
||||
|
||||
def test_account_limit_reserve_and_reset() -> None:
|
||||
cache = FakeCache()
|
||||
limiter = _limiter(cache)
|
||||
|
||||
async def scenario() -> None:
|
||||
for _ in range(3):
|
||||
attempt = await limiter.acquire(username="u", address="192.0.2.1")
|
||||
assert attempt.allowed
|
||||
await limiter.settle(attempt, "failed")
|
||||
limited = await limiter.acquire(username="u", address="192.0.2.1")
|
||||
assert not limited.allowed
|
||||
assert 1 <= limited.retry_after <= 10
|
||||
# другой username с того же адреса — ещё можно (предел адреса 6)
|
||||
other = await limiter.acquire(username="v", address="192.0.2.1")
|
||||
assert other.allowed
|
||||
# успех возвращает резерв адреса и сбрасывает пару
|
||||
await limiter.settle(other, "succeeded")
|
||||
assert len(cache.data) == 2 # пара u и адрес, ключей v нет
|
||||
# обрыв (503, 429 бюджета) — тоже возврат
|
||||
aborted = await limiter.acquire(username="w", address="192.0.2.1")
|
||||
await limiter.settle(aborted, "aborted")
|
||||
assert len(cache.data) == 2
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_concurrent_attempts_do_not_overtake_limit() -> None:
|
||||
limiter = _limiter(FakeCache())
|
||||
|
||||
async def scenario() -> list:
|
||||
return await asyncio.gather(
|
||||
*(limiter.acquire(username="u", address="192.0.2.2") for _ in range(10))
|
||||
)
|
||||
|
||||
attempts = asyncio.run(scenario())
|
||||
assert sum(a.allowed for a in attempts) == 3
|
||||
|
||||
|
||||
def test_address_limit_and_zero_disables() -> None:
|
||||
limiter = _limiter(FakeCache(), account=0, address=2)
|
||||
|
||||
async def scenario() -> None:
|
||||
for name in ("a", "b"):
|
||||
attempt = await limiter.acquire(username=name, address="192.0.2.3")
|
||||
assert attempt.allowed
|
||||
assert attempt.account_key is None
|
||||
assert not (await limiter.acquire(username="c", address="192.0.2.3")).allowed
|
||||
assert (await limiter.acquire(username="c", address="192.0.2.4")).allowed
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_valkey_down_uses_process_counters_and_back(
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
cache = FakeCache(down=True)
|
||||
limiter = _limiter(cache)
|
||||
|
||||
async def scenario() -> None:
|
||||
for _ in range(3):
|
||||
attempt = await limiter.acquire(username="u", address="192.0.2.5")
|
||||
assert attempt.allowed
|
||||
assert not attempt.shared
|
||||
limited = await limiter.acquire(username="u", address="192.0.2.5")
|
||||
assert not limited.allowed
|
||||
assert limited.retry_after >= 1
|
||||
cache.down = False
|
||||
attempt = await limiter.acquire(username="x", address="192.0.2.6")
|
||||
assert attempt.shared
|
||||
|
||||
with caplog.at_level("INFO", logger="src.login_limit"):
|
||||
asyncio.run(scenario())
|
||||
messages = [record.getMessage() for record in caplog.records]
|
||||
assert sum("uses process counters" in m for m in messages) == 1
|
||||
assert sum("uses shared counters" in m for m in messages) == 1
|
||||
|
||||
|
||||
def test_local_limiter_window_release_and_overflow() -> None:
|
||||
local = LocalLoginLimiter(window=1, max_keys=2)
|
||||
wait, keys = local.acquire({"a": 1})
|
||||
assert (wait, keys) == (0, ("a",))
|
||||
wait, _ = local.acquire({"a": 1})
|
||||
assert wait == 1
|
||||
local.release({"a": "decr"})
|
||||
assert len(local) == 0 # дошедшая до 0 запись удалена
|
||||
local.acquire({"b": 5, "c": 5})
|
||||
# словарь полон: новый ключ не заводится, попытка разрешена
|
||||
wait, keys = local.acquire({"d": 5})
|
||||
assert (wait, keys) == (0, ())
|
||||
time.sleep(1.05)
|
||||
wait, keys = local.acquire({"d": 5})
|
||||
assert keys == ("d",)
|
||||
|
||||
|
||||
# --- адрес клиента -----------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("forwarded", "trusted", "expected"),
|
||||
[
|
||||
("198.51.100.1", True, "198.51.100.1"),
|
||||
(" 2001:db8::1 ", True, "2001:db8::1"),
|
||||
("198.51.100.1, 10.0.0.1", True, "10.9.8.7"),
|
||||
("garbage", True, "10.9.8.7"),
|
||||
(None, True, "10.9.8.7"),
|
||||
("198.51.100.1", False, "10.9.8.7"),
|
||||
],
|
||||
)
|
||||
def test_client_address(forwarded: str | None, trusted: bool, expected: str) -> None:
|
||||
assert (
|
||||
client_address(forwarded=forwarded, peer="10.9.8.7", trusted=trusted)
|
||||
== expected
|
||||
)
|
||||
|
||||
|
||||
# --- порядок проверок входа --------------------------------------------------
|
||||
|
||||
|
||||
class FakeStorage:
|
||||
def __init__(self, password_hash: str | None) -> None:
|
||||
self.user = User(uuid.uuid4(), "alice_1", "Alice", datetime.now(UTC))
|
||||
self.password_hash = password_hash
|
||||
self.reads = 0
|
||||
self.down = False
|
||||
self.rehashed: tuple[str, str] | None = None
|
||||
|
||||
async def get_credentials(self, username: str) -> Credentials | None:
|
||||
self.reads += 1
|
||||
if self.down:
|
||||
raise Unavailable
|
||||
if self.password_hash is None:
|
||||
return None
|
||||
return Credentials(user=self.user, password_hash=self.password_hash)
|
||||
|
||||
def _session(self, ttl: timedelta) -> Session:
|
||||
now = datetime.now(UTC)
|
||||
return Session(uuid.uuid4(), self.user.id, now + ttl, now)
|
||||
|
||||
async def create_session(self, *, user_id, token_hash, ttl) -> Session: # noqa: ANN001
|
||||
return self._session(ttl)
|
||||
|
||||
async def create_session_with_rehash( # noqa: ANN201
|
||||
self,
|
||||
*,
|
||||
user_id, # noqa: ANN001
|
||||
token_hash, # noqa: ANN001
|
||||
ttl, # noqa: ANN001
|
||||
old_hash, # noqa: ANN001
|
||||
new_hash, # noqa: ANN001
|
||||
):
|
||||
updated = self.password_hash == old_hash
|
||||
if updated:
|
||||
self.password_hash = new_hash
|
||||
self.rehashed = (old_hash, new_hash)
|
||||
return self._session(ttl), updated
|
||||
|
||||
|
||||
def _service(
|
||||
storage: FakeStorage, passwords: Passwords, cache: FakeCache
|
||||
) -> SessionService:
|
||||
return SessionService(storage, passwords, _limiter(cache, account=2), ttl=60)
|
||||
|
||||
|
||||
def test_login_order_and_settle() -> None:
|
||||
passwords = Passwords(FAST)
|
||||
password = "correct horse battery"
|
||||
old = PasswordHasher.from_parameters(profiles.RFC_9106_LOW_MEMORY).hash(password)
|
||||
storage = FakeStorage(old)
|
||||
cache = FakeCache()
|
||||
service = _service(storage, passwords, cache)
|
||||
|
||||
async def login(pw: str) -> object:
|
||||
return await service.login(
|
||||
username="alice_1", password=pw, client_address="192.0.2.9"
|
||||
)
|
||||
|
||||
async def scenario() -> None:
|
||||
# неверная пара — резерв остаётся
|
||||
for _ in range(2):
|
||||
with pytest.raises(InvalidCredentials):
|
||||
await login("wrong password!")
|
||||
assert storage.password_hash == old
|
||||
# предел: ни чтения БД, ни хэша, верный пароль — тоже 429
|
||||
reads = storage.reads
|
||||
with pytest.raises(LoginRateLimited) as caught:
|
||||
await login(password)
|
||||
assert caught.value.retry_after >= 1
|
||||
assert storage.reads == reads
|
||||
cache.data.clear()
|
||||
# 503 БД — резерв возвращён
|
||||
storage.down = True
|
||||
with pytest.raises(Unavailable):
|
||||
await login(password)
|
||||
storage.down = False
|
||||
assert cache.data == {}
|
||||
# успех: пересчёт в одной транзакции с сессией, резерв возвращён
|
||||
issued = await login(password)
|
||||
assert issued.user == storage.user
|
||||
assert storage.rehashed is not None
|
||||
assert storage.password_hash.startswith("$argon2id$v=19$m=19456,t=2,p=1$")
|
||||
assert cache.data == {}
|
||||
storage.rehashed = None
|
||||
await login(password)
|
||||
assert storage.rehashed is None
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_busy_budget_skips_rehash_and_counts_as_aborted() -> None:
|
||||
password = "correct horse battery"
|
||||
old = PasswordHasher.from_parameters(profiles.RFC_9106_LOW_MEMORY).hash(password)
|
||||
storage = FakeStorage(old)
|
||||
cache = FakeCache()
|
||||
passwords = Passwords(FAST)
|
||||
service = _service(storage, passwords, cache)
|
||||
calls = {"n": 0}
|
||||
original = passwords.budget.run
|
||||
|
||||
async def second_busy(func, *args): # noqa: ANN001, ANN202
|
||||
calls["n"] += 1
|
||||
if calls["n"] == 2:
|
||||
raise PasswordHashingBusy(waited_ms=5)
|
||||
return await original(func, *args)
|
||||
|
||||
passwords.budget.run = second_busy # type: ignore[method-assign]
|
||||
|
||||
async def scenario() -> None:
|
||||
# проверка прошла, пересчёт — бюджет занят: вход 201 без пересчёта
|
||||
await service.login(username="alice_1", password=password, client_address="a")
|
||||
assert storage.rehashed is None
|
||||
assert storage.password_hash == old
|
||||
|
||||
async def always_busy(func, *args): # noqa: ANN001, ANN202
|
||||
raise PasswordHashingBusy(waited_ms=0)
|
||||
|
||||
passwords.budget.run = always_busy # type: ignore[method-assign]
|
||||
with pytest.raises(PasswordHashingBusy):
|
||||
await service.login(
|
||||
username="alice_1", password=password, client_address="a"
|
||||
)
|
||||
# 429 бюджета — не неудача: резерва нет
|
||||
assert cache.data == {}
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
# --- предел тела -------------------------------------------------------------
|
||||
|
||||
|
||||
async def _echo(scope, receive, send) -> None: # noqa: ANN001
|
||||
body = b""
|
||||
while True:
|
||||
message = await receive()
|
||||
if message["type"] == "http.disconnect":
|
||||
break
|
||||
body += message.get("body", b"")
|
||||
if not message.get("more_body"):
|
||||
break
|
||||
await send({"type": "http.response.start", "status": 200, "headers": []})
|
||||
await send({"type": "http.response.body", "body": str(len(body)).encode()})
|
||||
|
||||
|
||||
class _State:
|
||||
settings = type("S", (), {"instance_id": "test-instance"})()
|
||||
|
||||
|
||||
async def _app(scope, receive, send) -> None: # noqa: ANN001
|
||||
scope["app"] = type("App", (), {"state": _State()})()
|
||||
scope.setdefault("state", {})["request_id"] = "rid-1"
|
||||
await BodyLimitMiddleware(_echo, max_bytes=100)(scope, receive, send)
|
||||
|
||||
|
||||
def _post(path: str, content: object) -> httpx.Response:
|
||||
async def call() -> httpx.Response:
|
||||
transport = httpx.ASGITransport(app=_app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url="http://t") as c:
|
||||
return await c.post(path, content=content)
|
||||
|
||||
return asyncio.run(call())
|
||||
|
||||
|
||||
def test_body_limit() -> None:
|
||||
assert _post("/api/v1/chats", b"x" * 100).text == "100"
|
||||
declared = _post("/api/v1/chats", b"x" * 101)
|
||||
assert declared.status_code == 400
|
||||
body = json.loads(declared.text)["error"]
|
||||
assert body == {
|
||||
"code": "invalid_request",
|
||||
"message": BODY_TOO_LARGE,
|
||||
"request_id": "rid-1",
|
||||
}
|
||||
assert declared.headers["X-Instance-Id"] == "test-instance"
|
||||
|
||||
async def chunks(): # noqa: ANN202
|
||||
for _ in range(5):
|
||||
yield b"y" * 30
|
||||
|
||||
assert _post("/api/v1/auth/sessions", chunks()).status_code == 400
|
||||
# загрузка вложения — свой предел сервиса
|
||||
upload = "/api/v1/chats/0f0f/attachments"
|
||||
assert _post(upload, b"z" * 1000).text == "1000"
|
||||
@@ -0,0 +1,466 @@
|
||||
"""Лаба 7: mTLS клиентов relay и worker к RabbitMQ (перенос messaging-telemetry-mtls).
|
||||
|
||||
Без стенда. Настройки `BROKER_*` и проверка точки входа (`src/client_tls.py`:
|
||||
файлы identity, CRL, имя брокера), контекст `broker_context` и настоящие
|
||||
рукопожатия со своим TLS-сервером на loopback в потоке, который, как брокер,
|
||||
требует сертификат клиента: пары `rabbitmq`, `relay`, `worker` выпускает
|
||||
`infra/pki/pki.sh` во временный каталог (без OpenSSL ≥ 3 — пропуск с
|
||||
причиной). Соединение `src/broker.py` — аргументы `aio_pika.connect` (подмена):
|
||||
EXTERNAL без логина и пароля, ограниченное закрытие TLS; worker проверяет
|
||||
очередь пассивно, relay объявляет активно. Определения брокера — режим печати
|
||||
`infra/rabbitmq/start.sh`. Положительный путь AMQP, права и отказы на
|
||||
настоящем брокере — `make broker-mtls-check`.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from src import broker as broker_module
|
||||
from src.client_tls import (
|
||||
RELAY_STORAGES,
|
||||
REPLAY_STORAGES,
|
||||
WORKER_STORAGES,
|
||||
broker_context,
|
||||
check_or_exit,
|
||||
client_tls_problems,
|
||||
)
|
||||
from src.config import Broker, Settings
|
||||
from src.constants import BROKER_TLS_SHUTDOWN_TIMEOUT
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PKI = ROOT / "infra" / "pki" / "pki.sh"
|
||||
START = ROOT / "infra" / "rabbitmq" / "start.sh"
|
||||
COMPOSE = ROOT / "compose.yaml"
|
||||
# файлы входа в OpenBao: обязательны всем процессам с переноса openbao-secrets
|
||||
BAO_FILES = ("BAO_CERT_FILE", "BAO_KEY_FILE", "BAO_CRL_FILE")
|
||||
|
||||
|
||||
def _pki(env: dict[str, str], *args: str) -> None:
|
||||
done = subprocess.run(
|
||||
["sh", str(PKI), *args], env=env, capture_output=True, text=True, check=False
|
||||
)
|
||||
if done.returncode != 0:
|
||||
pytest.skip(f"infra/pki/pki.sh {args[0]} failed (OpenSSL 3+?): {done.stderr}")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def pki(tmp_path_factory: pytest.TempPathFactory) -> dict:
|
||||
"""Файлы стенда (CA, CRL, пары rabbitmq, relay, worker и прочие) и CA
|
||||
другого оператора с его парой rabbitmq; копия CRL до отзыва."""
|
||||
base = tmp_path_factory.mktemp("pki")
|
||||
env = {
|
||||
**os.environ,
|
||||
"PKI_OPERATOR_DIR": str(base / "operator"),
|
||||
"PKI_STAND_DIR": str(base / "stand"),
|
||||
}
|
||||
_pki(env, "stand")
|
||||
(base / "crl-before.pem").write_bytes((base / "stand" / "crl.pem").read_bytes())
|
||||
_pki(
|
||||
{
|
||||
**env,
|
||||
"PKI_OPERATOR_DIR": str(base / "other"),
|
||||
"PKI_STAND_DIR": str(base / "x"),
|
||||
},
|
||||
"stand",
|
||||
)
|
||||
return {"base": base, "stand": base / "stand", "other": base / "x", "env": env}
|
||||
|
||||
|
||||
def _env(stand: Path, identity: str = "worker", **extra: str) -> dict[str, str]:
|
||||
return {
|
||||
"CLIENT_TLS_CA_FILE": str(stand / "ca.crt"),
|
||||
"DB_HOST": "postgres",
|
||||
"S3_ENDPOINT": "https://s3:8333",
|
||||
"BROKER_HOST": "rabbitmq",
|
||||
"BROKER_CERT_FILE": str(stand / f"{identity}.crt"),
|
||||
"BROKER_KEY_FILE": str(stand / f"{identity}.key"),
|
||||
"BROKER_CRL_FILE": str(stand / "crl.pem"),
|
||||
# вход в OpenBao (перенос openbao-secrets) — той же парой
|
||||
"BAO_CERT_FILE": str(stand / f"{identity}.crt"),
|
||||
"BAO_KEY_FILE": str(stand / f"{identity}.key"),
|
||||
"BAO_CRL_FILE": str(stand / "crl.pem"),
|
||||
**extra,
|
||||
}
|
||||
|
||||
|
||||
# --- настройки и проверка точки входа ---------------------------------------
|
||||
|
||||
|
||||
def test_broker_settings_without_password() -> None:
|
||||
broker = Settings.from_env({}).broker
|
||||
assert (broker.host, broker.port) == ("localhost", 5671)
|
||||
assert (broker.cert_file, broker.key_file, broker.crl_file) == ("", "", "")
|
||||
# пароля и имени пользователя нет совсем: вход только по сертификату
|
||||
assert not hasattr(broker, "password")
|
||||
assert not hasattr(broker, "user")
|
||||
parsed = Broker.from_env(
|
||||
{
|
||||
"BROKER_CERT_FILE": " /run/secrets/relay.crt ",
|
||||
"BROKER_KEY_FILE": "/run/secrets/relay.key",
|
||||
"BROKER_CRL_FILE": "/run/secrets/crl.pem",
|
||||
"BROKER_PASSWORD": "ignored",
|
||||
}
|
||||
)
|
||||
assert parsed.cert_file == "/run/secrets/relay.crt"
|
||||
assert parsed.key_file == "/run/secrets/relay.key"
|
||||
assert parsed.crl_file == "/run/secrets/crl.pem"
|
||||
|
||||
|
||||
def test_storages_with_broker() -> None:
|
||||
assert "broker" in WORKER_STORAGES
|
||||
assert "broker" in RELAY_STORAGES
|
||||
# replay в брокер не ходит: файлы identity брокера ему не нужны
|
||||
assert REPLAY_STORAGES == ("database", "secret_store")
|
||||
|
||||
|
||||
def test_problems_without_files_and_with_ip() -> None:
|
||||
settings = Settings.from_env({"BROKER_HOST": "10.0.0.7"})
|
||||
problems = client_tls_problems(settings, RELAY_STORAGES)
|
||||
assert problems == [
|
||||
"CLIENT_TLS_CA_FILE",
|
||||
"BROKER_HOST",
|
||||
"BROKER_CERT_FILE",
|
||||
"BROKER_KEY_FILE",
|
||||
"BROKER_CRL_FILE",
|
||||
*BAO_FILES,
|
||||
]
|
||||
# процессу без брокера файлы брокера не нужны
|
||||
assert client_tls_problems(settings, REPLAY_STORAGES) == [
|
||||
"CLIENT_TLS_CA_FILE",
|
||||
*BAO_FILES,
|
||||
]
|
||||
|
||||
|
||||
def test_problems_on_real_files(pki: dict, tmp_path: Path) -> None:
|
||||
stand = pki["stand"]
|
||||
assert client_tls_problems(Settings.from_env(_env(stand)), WORKER_STORAGES) == []
|
||||
assert (
|
||||
client_tls_problems(Settings.from_env(_env(stand, "relay")), RELAY_STORAGES)
|
||||
== []
|
||||
)
|
||||
broken = tmp_path / "broken.pem"
|
||||
broken.write_text("not pem\n", encoding="ascii")
|
||||
cases = {
|
||||
# сертификат — не сертификат (CRL, мусор)
|
||||
"BROKER_CERT_FILE": [stand / "crl.pem", broken],
|
||||
# ключ другого сертификата, не ключ, нет файла
|
||||
"BROKER_KEY_FILE": [stand / "relay.key", broken, tmp_path / "missing.key"],
|
||||
# CRL — файл с сертификатом, мусор, нет файла
|
||||
"BROKER_CRL_FILE": [stand / "ca.crt", broken, tmp_path / "missing.pem"],
|
||||
}
|
||||
for variable, paths in cases.items():
|
||||
for path in paths:
|
||||
env = {**_env(stand), variable: str(path)}
|
||||
assert client_tls_problems(Settings.from_env(env), WORKER_STORAGES) == [
|
||||
variable
|
||||
], (variable, path.name)
|
||||
|
||||
|
||||
def test_check_or_exit_names_only(
|
||||
pki: dict, tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
secret = str(tmp_path / "secret-dir" / "worker.key")
|
||||
env = {**_env(pki["stand"]), "BROKER_KEY_FILE": secret, "BROKER_HOST": "::1"}
|
||||
with pytest.raises(SystemExit) as exit_info:
|
||||
check_or_exit(Settings.from_env(env), WORKER_STORAGES)
|
||||
assert exit_info.value.code == 2
|
||||
err = capsys.readouterr().err
|
||||
assert "BROKER_HOST, BROKER_KEY_FILE" in err
|
||||
assert "secret-dir" not in err
|
||||
assert "::1" not in err
|
||||
|
||||
|
||||
# --- контекст и рукопожатия -------------------------------------------------
|
||||
|
||||
|
||||
class _Broker:
|
||||
"""TLS-сервер в потоке «как брокер»: TLS 1.3, сертификат клиента по CA
|
||||
стенда обязателен; `peers` — DNS SAN принятых клиентов."""
|
||||
|
||||
def __init__(self, stand: Path, name: str = "rabbitmq") -> None:
|
||||
self.context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
self.context.minimum_version = ssl.TLSVersion.TLSv1_3
|
||||
self.context.load_cert_chain(stand / f"{name}.crt", stand / f"{name}.key")
|
||||
self.context.load_verify_locations(cafile=stand / "ca.crt")
|
||||
self.context.verify_mode = ssl.CERT_REQUIRED
|
||||
self.peers: list[str] = []
|
||||
self.listener = socket.create_server(("127.0.0.1", 0))
|
||||
self.port = self.listener.getsockname()[1]
|
||||
self.thread = threading.Thread(target=self._serve, daemon=True)
|
||||
|
||||
def _serve(self) -> None:
|
||||
while True:
|
||||
try:
|
||||
raw, _ = self.listener.accept()
|
||||
except OSError:
|
||||
return
|
||||
raw.settimeout(5)
|
||||
try:
|
||||
with self.context.wrap_socket(raw, server_side=True) as sock:
|
||||
san = dict(sock.getpeercert().get("subjectAltName", ()))
|
||||
self.peers.append(san.get("DNS", ""))
|
||||
sock.sendall(b"AMQP")
|
||||
except (OSError, ssl.SSLError):
|
||||
pass
|
||||
finally:
|
||||
raw.close()
|
||||
|
||||
def __enter__(self) -> "_Broker":
|
||||
self.thread.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, *_: object) -> None:
|
||||
self.listener.close()
|
||||
|
||||
|
||||
def _context(stand: Path, identity: str, crl: Path | bool | None = None):
|
||||
"""Контекст клиента брокера; CRL по умолчанию — копия до отзыва (рядом
|
||||
со `stand`): тест отзыва меняет `stand/crl.pem`, порядок тестов не важен."""
|
||||
before = stand.parent / "crl-before.pem"
|
||||
default = before if before.exists() else stand / "crl.pem"
|
||||
return broker_context(
|
||||
str(stand / "ca.crt"),
|
||||
cert_file=str(stand / f"{identity}.crt"),
|
||||
key_file=str(stand / f"{identity}.key"),
|
||||
crl_file="" if crl is False else str(crl or default),
|
||||
)
|
||||
|
||||
|
||||
def _handshake(port: int, context: ssl.SSLContext, name: str = "rabbitmq") -> str:
|
||||
try:
|
||||
with (
|
||||
socket.create_connection(("127.0.0.1", port), timeout=5) as raw,
|
||||
context.wrap_socket(raw, server_hostname=name) as sock,
|
||||
):
|
||||
sock.recv(4)
|
||||
return str(sock.version())
|
||||
except ssl.SSLCertVerificationError as error:
|
||||
return "revoked" if "revoked" in str(error) else f"verify: {error.reason}"
|
||||
except ssl.SSLError as error:
|
||||
return f"ssl: {error.reason}"
|
||||
|
||||
|
||||
def test_broker_context_flags(pki: dict) -> None:
|
||||
context = _context(pki["stand"], "worker")
|
||||
assert context.minimum_version == ssl.TLSVersion.TLSv1_3
|
||||
assert context.check_hostname is True
|
||||
assert context.verify_mode == ssl.CERT_REQUIRED
|
||||
assert context.verify_flags & ssl.VERIFY_X509_STRICT
|
||||
assert context.verify_flags & ssl.VERIFY_CRL_CHECK_LEAF
|
||||
# только CA стенда и его CRL: системные корни не загружены
|
||||
assert context.cert_store_stats() == {"x509_ca": 1, "x509": 1, "crl": 1}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("identity", ["relay", "worker"])
|
||||
def test_client_presents_its_identity(pki: dict, identity: str) -> None:
|
||||
stand = pki["stand"]
|
||||
with _Broker(stand) as server:
|
||||
assert _handshake(server.port, _context(stand, identity)) == "TLSv1.3"
|
||||
assert _handshake(server.port, _context(stand, identity), "localhost") == (
|
||||
"TLSv1.3"
|
||||
)
|
||||
assert server.peers == [identity, identity]
|
||||
|
||||
|
||||
def test_client_refuses_wrong_broker(pki: dict) -> None:
|
||||
stand, other = pki["stand"], pki["other"]
|
||||
context = _context(stand, "worker")
|
||||
# сервер другого CA с тем же именем
|
||||
with _Broker(other) as server:
|
||||
assert _handshake(server.port, context).startswith("verify:")
|
||||
with _Broker(stand) as server:
|
||||
# имя вне SAN и чужой сервер того же CA под именем брокера
|
||||
assert _handshake(server.port, context, "api").startswith("verify:")
|
||||
with _Broker(stand, "postgres") as server:
|
||||
assert _handshake(server.port, context).startswith("verify:")
|
||||
# TLS 1.2 у сервера — отказ клиента
|
||||
with _Broker(stand) as server:
|
||||
server.context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
server.context.maximum_version = ssl.TLSVersion.TLSv1_2
|
||||
assert _handshake(server.port, context).startswith("ssl:")
|
||||
|
||||
|
||||
def test_crl_is_required_and_checked(pki: dict) -> None:
|
||||
stand, base = pki["stand"], pki["base"]
|
||||
with _Broker(stand) as server:
|
||||
# без CRL проверка отзыва не пропускается: рукопожатия нет
|
||||
assert _handshake(server.port, _context(stand, "worker", crl=False)).startswith(
|
||||
"verify:"
|
||||
)
|
||||
_pki(pki["env"], "revoke", "rabbitmq")
|
||||
revoked = base / "crl-after.pem"
|
||||
revoked.write_bytes((stand / "crl.pem").read_bytes())
|
||||
with _Broker(stand) as server:
|
||||
assert _handshake(server.port, _context(stand, "worker", revoked)) == "revoked"
|
||||
assert (
|
||||
_handshake(server.port, _context(stand, "worker", base / "crl-before.pem"))
|
||||
== "TLSv1.3"
|
||||
)
|
||||
|
||||
|
||||
def test_context_files_read_once(pki: dict, tmp_path: Path) -> None:
|
||||
"""Контекст строится при старте: удалённые потом файлы (новый CRL пишется
|
||||
заменой) не мешают следующим соединениям."""
|
||||
stand = pki["stand"]
|
||||
copies = tmp_path / "copies"
|
||||
copies.mkdir()
|
||||
for name in ("ca.crt", "worker.crt", "worker.key"):
|
||||
(copies / name).write_bytes((stand / name).read_bytes())
|
||||
(copies / "crl.pem").write_bytes((pki["base"] / "crl-before.pem").read_bytes())
|
||||
context = _context(copies, "worker")
|
||||
for path in copies.iterdir():
|
||||
path.unlink()
|
||||
with _Broker(stand) as server:
|
||||
assert _handshake(server.port, context) == "TLSv1.3"
|
||||
assert _handshake(server.port, context) == "TLSv1.3"
|
||||
|
||||
|
||||
# --- соединение aio-pika ----------------------------------------------------
|
||||
|
||||
|
||||
def test_open_connection_uses_external_and_context(monkeypatch) -> None:
|
||||
seen: dict = {}
|
||||
|
||||
async def fake_connect(**kwargs):
|
||||
seen.update(kwargs)
|
||||
return "connection"
|
||||
|
||||
monkeypatch.setattr(broker_module.aio_pika, "connect", fake_connect)
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
settings = Broker(host="rabbitmq", port=5671, cert_file="c", key_file="k")
|
||||
assert (
|
||||
asyncio.run(broker_module.open_connection(settings, context=context))
|
||||
== "connection"
|
||||
)
|
||||
assert seen["ssl"] is True
|
||||
assert seen["ssl_context"] is context
|
||||
assert seen["auth"] == "external"
|
||||
assert (seen["host"], seen["port"]) == ("rabbitmq", 5671)
|
||||
assert seen["connection_class"] is broker_module._TlsConnection
|
||||
assert not {"login", "password", "url"} & set(seen)
|
||||
|
||||
|
||||
def test_tls_close_is_bounded() -> None:
|
||||
"""Срок закрытия TLS уходит в asyncio.open_connection через aiormq: без
|
||||
него закрытие при замороженном брокере ждало бы 30 с."""
|
||||
|
||||
async def build() -> dict:
|
||||
connection = broker_module._TlsConnection("amqps://rabbitmq:5671/")
|
||||
return connection.kwargs
|
||||
|
||||
kwargs = asyncio.run(build())
|
||||
assert kwargs["ssl_shutdown_timeout"] == BROKER_TLS_SHUTDOWN_TIMEOUT
|
||||
assert BROKER_TLS_SHUTDOWN_TIMEOUT <= 1
|
||||
|
||||
|
||||
class _Channel:
|
||||
def __init__(self) -> None:
|
||||
self.calls: list[tuple[str, dict]] = []
|
||||
|
||||
async def declare_queue(self, name: str, **kwargs):
|
||||
self.calls.append((name, kwargs))
|
||||
return "queue"
|
||||
|
||||
|
||||
def test_worker_checks_queue_passively_relay_declares() -> None:
|
||||
channel = _Channel()
|
||||
asyncio.run(broker_module._check(channel, "messenger.attachment-jobs"))
|
||||
asyncio.run(broker_module._declare(channel, "messenger.attachment-jobs"))
|
||||
(_, passive), (_, active) = channel.calls
|
||||
assert passive.get("passive") is True
|
||||
assert "arguments" not in passive
|
||||
assert not active.get("passive")
|
||||
assert active["durable"] is True
|
||||
assert active["arguments"] == {"x-queue-type": "quorum"}
|
||||
|
||||
|
||||
# --- определения брокера (start.sh) и compose --------------------------------
|
||||
|
||||
|
||||
def _definitions(namespace: str) -> subprocess.CompletedProcess:
|
||||
return subprocess.run(
|
||||
["sh", str(START), "--print-definitions"],
|
||||
env={"PATH": os.environ["PATH"], "RABBITMQ_QUEUE_NAMESPACE": namespace},
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
|
||||
|
||||
def test_definitions_users_rights_and_queue() -> None:
|
||||
done = _definitions("messenger")
|
||||
assert done.returncode == 0, done.stderr
|
||||
data = json.loads(done.stdout)
|
||||
queue = broker_module.queue_name("messenger")
|
||||
assert data["users"] == [
|
||||
{"name": "relay", "tags": []},
|
||||
{"name": "worker", "tags": []},
|
||||
]
|
||||
# пользователи без пароля: войти можно только сертификатом
|
||||
assert not any("password" in key for user in data["users"] for key in user)
|
||||
rights = {p["user"]: p for p in data["permissions"]}
|
||||
assert set(rights) == {"relay", "worker"}
|
||||
|
||||
def allows(pattern: str, name: str) -> bool:
|
||||
return re.search(pattern, name) is not None
|
||||
|
||||
relay, worker = rights["relay"], rights["worker"]
|
||||
assert allows(relay["configure"], queue)
|
||||
assert allows(relay["write"], "amq.default")
|
||||
assert not allows(relay["read"], queue)
|
||||
assert not allows(relay["configure"], "other.attachment-jobs")
|
||||
assert not allows(relay["write"], "amq.topic")
|
||||
assert allows(worker["read"], queue)
|
||||
assert not allows(worker["configure"], queue)
|
||||
assert not allows(worker["write"], "amq.default")
|
||||
assert not allows(worker["read"], "messengerXattachment-jobs")
|
||||
assert data["queues"] == [
|
||||
{
|
||||
"name": queue,
|
||||
"vhost": "/",
|
||||
"durable": True,
|
||||
"auto_delete": False,
|
||||
"arguments": broker_module._QUEUE_ARGUMENTS,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("namespace", ["", "Bad", "a.b", "x;y"])
|
||||
def test_definitions_refuse_bad_namespace(namespace: str) -> None:
|
||||
done = _definitions(namespace)
|
||||
assert done.returncode == 1
|
||||
assert done.stdout == ""
|
||||
assert "RABBITMQ_QUEUE_NAMESPACE" in done.stderr
|
||||
|
||||
|
||||
def test_compose_has_no_broker_password_and_own_pairs() -> None:
|
||||
text = COMPOSE.read_text(encoding="utf-8")
|
||||
for word in ("BROKER_PASSWORD", "BROKER_USER", "RABBITMQ_DEFAULT_"):
|
||||
assert word not in text, word
|
||||
|
||||
def block(name: str) -> str:
|
||||
match = re.search(
|
||||
rf"^ {name}:\n(.*?)(?=^ [a-z0-9-]+:\n|^\S)", text, re.M | re.S
|
||||
)
|
||||
assert match, name
|
||||
return match.group(1)
|
||||
|
||||
for service in ("relay", "worker", "rabbitmq"):
|
||||
secrets = set(re.findall(r"^ - ([a-z0-9.]+)$", block(service), re.M))
|
||||
pairs = {s for s in secrets if s.endswith((".crt", ".key")) and s != "ca.crt"}
|
||||
assert pairs == {f"{service}.crt", f"{service}.key"}, service
|
||||
assert {"ca.crt", "crl.pem"} <= secrets, service
|
||||
# у реплик API и уборщика брокера нет вовсе
|
||||
for service in ("api", "cleaner"):
|
||||
assert "BROKER_" not in block(service), service
|
||||
@@ -0,0 +1,398 @@
|
||||
"""Лаба 7: ограничения контейнеров (перенос container-hardening).
|
||||
|
||||
Без стенда: инварианты `compose.yaml` и override стендов. У каждого сервиса —
|
||||
якорь `x-hardened` (cap_drop ALL, no-new-privileges, корень только на чтение);
|
||||
отклонение — только строкой `x-hardening-exceptions` с причиной, процессам
|
||||
приложения и bootstrap — никогда; лимиты CPU, памяти и `pids` (не меньше 64, у Go —
|
||||
128); tmpfs — только ключом `tmpfs:` с `size=` и `mode=`; хранилища — от своего
|
||||
пользователя; нет privileged, cap_add, пространств хоста, устройств, сокета
|
||||
Docker, портов не на 127.0.0.1; опубликованные порты = таблица
|
||||
`scripts/lab7.py` (HC_PUBLISHED); gRPC шлюза S3 — mTLS (`infra/s3/security.toml`),
|
||||
CN — только имя разовой пробы `make s3-check`, которого нет среди identity стенда;
|
||||
override временных стендов и bench/ ничего из этого не снимают. Проверки —
|
||||
функции над корнем репозитория: их зовут на рабочем дереве и на копии с внесённой
|
||||
ошибкой (контроль). Поведение на настоящих контейнерах — `make hardening-check`.
|
||||
|
||||
YAML разбирается построчно: PyYAML — не прямая зависимость проекта.
|
||||
"""
|
||||
|
||||
import importlib.util
|
||||
import re
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
COMPOSE = "compose.yaml"
|
||||
OVERRIDES = ("student-tests/stand.compose.yml", "bench/bench.compose.yml")
|
||||
SECURITY = "infra/s3/security.toml"
|
||||
IDENTITIES = "infra/pki/identities.conf"
|
||||
LAB7 = "scripts/lab7.py"
|
||||
ANCHOR = "hardened"
|
||||
# хранилища — сразу от пользователя образа (uid:gid), без шагов от root
|
||||
STORAGE_USERS = {
|
||||
"postgres": "999:999",
|
||||
"valkey": "999:999",
|
||||
"rabbitmq": "100:101",
|
||||
"s3": "1000:1000",
|
||||
}
|
||||
# процессы приложения и bootstrap: исключений из якоря нет никогда
|
||||
NO_EXCEPTIONS = (
|
||||
"api", "worker", "relay", "cleaner", "migrate", "postgres-bootstrap",
|
||||
"s3-bootstrap",
|
||||
) # fmt: skip
|
||||
EXCEPTION_KEYS = ("read_only", "cap_add")
|
||||
# рантайм Go: GOMAXPROCS потоков и потоки в системных вызовах, отказ создать поток
|
||||
# — фатальная ошибка процесса; нижняя граница pids — 128
|
||||
GO_SERVICES = (
|
||||
"s3", "s3-bootstrap", "openbao", "otel-collector", "prometheus", "loki",
|
||||
"tempo", "grafana",
|
||||
) # fmt: skip
|
||||
# ключи, которые override стенда трогать не может (снимут ограничения)
|
||||
OVERRIDE_FORBIDDEN = (
|
||||
"read_only", "cap_add", "cap_drop", "security_opt", "privileged", "user",
|
||||
"network_mode", "pid", "ipc", "devices", "pids",
|
||||
) # fmt: skip
|
||||
|
||||
|
||||
def _read(root: Path, rel: str) -> str:
|
||||
"""Файл без строк-комментариев."""
|
||||
lines = (root / rel).read_text(encoding="utf-8").splitlines()
|
||||
return "\n".join(line for line in lines if not line.lstrip().startswith("#")) + "\n"
|
||||
|
||||
|
||||
def _blocks(text: str, indent: int) -> dict[str, str]:
|
||||
"""Ключи YAML с отступом `indent` → их тела (до следующего ключа того же
|
||||
уровня или меньше)."""
|
||||
pad = " " * indent
|
||||
out: dict[str, str] = {}
|
||||
pattern = rf"^{pad}([A-Za-z0-9_.-]+):(.*)\n((?:(?:{pad} .*)?\n)*)"
|
||||
for match in re.finditer(pattern, text, re.M):
|
||||
out[match.group(1)] = match.group(2) + "\n" + match.group(3)
|
||||
return out
|
||||
|
||||
|
||||
def _services(root: Path, rel: str) -> dict[str, str]:
|
||||
section = re.search(r"^services:\n((?:(?: .*)?\n)*)", _read(root, rel), re.M)
|
||||
return _blocks(section.group(1), 2) if section else {}
|
||||
|
||||
|
||||
def _anchors(text: str) -> dict[str, str]:
|
||||
"""Якорь → тело верхнеуровневого `x-…: &якорь`."""
|
||||
out = {}
|
||||
for match in re.finditer(r"^x-[a-z-]+: &([a-z-]+)\n((?:(?: .*)?\n)*)", text, re.M):
|
||||
out[match.group(1)] = match.group(2)
|
||||
return out
|
||||
|
||||
|
||||
def _merged(block: str, anchors: dict[str, str]) -> tuple[list[str], str]:
|
||||
"""Якоря из `<<:` сервиса и его текст вместе с их телами."""
|
||||
match = re.search(r"^ <<: (\[.*\]|\*\S+)", block, re.M)
|
||||
names = re.findall(r"\*([a-z-]+)", match.group(1)) if match else []
|
||||
return names, block + "".join(anchors.get(name, "") for name in names)
|
||||
|
||||
|
||||
def _items(block: str, key: str) -> list[str]:
|
||||
"""Элементы списка `key:` сервиса (` key:` и ` - …`)."""
|
||||
match = re.search(rf"^ {key}:(.*)\n((?: - .*\n)*)", block, re.M)
|
||||
if not match:
|
||||
return []
|
||||
return [line.strip()[2:].strip("\"'") for line in match.group(2).splitlines()]
|
||||
|
||||
|
||||
def _exceptions(text: str) -> dict[str, dict[str, str]]:
|
||||
match = re.search(r"^x-hardening-exceptions:(.*)\n((?:(?: .*)?\n)*)", text, re.M)
|
||||
if not match:
|
||||
return {}
|
||||
out: dict[str, dict[str, str]] = {}
|
||||
for service, body in _blocks(match.group(2), 2).items():
|
||||
out[service] = {
|
||||
key: value.strip().strip("\"'")
|
||||
for key, value in re.findall(r"^ ([a-z_]+):(.*)$", body, re.M)
|
||||
}
|
||||
return out
|
||||
|
||||
|
||||
def _lab7():
|
||||
spec = importlib.util.spec_from_file_location("lab7", ROOT / LAB7)
|
||||
assert spec is not None
|
||||
assert spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def anchor_problems(root: Path) -> list[str]:
|
||||
text = _read(root, COMPOSE)
|
||||
body = _anchors(text).get(ANCHOR, "")
|
||||
problems = []
|
||||
for needed in (
|
||||
" read_only: true\n",
|
||||
" cap_drop:\n - ALL\n",
|
||||
" security_opt:\n - no-new-privileges:true\n",
|
||||
):
|
||||
if needed not in body:
|
||||
problems.append(f"{COMPOSE}: x-{ANCHOR} without {needed.strip()!r}")
|
||||
if not re.search(r"^x-hardening-exceptions:", text, re.M):
|
||||
problems.append(f"{COMPOSE}: no x-hardening-exceptions table")
|
||||
for service, keys in _exceptions(text).items():
|
||||
if service in NO_EXCEPTIONS:
|
||||
problems.append(f"{COMPOSE}: exception for {service}")
|
||||
for key, reason in keys.items():
|
||||
if key not in EXCEPTION_KEYS or not reason:
|
||||
problems.append(f"{COMPOSE}: exception {service}.{key} {reason!r}")
|
||||
return problems
|
||||
|
||||
|
||||
def service_problems(root: Path) -> list[str]:
|
||||
"""Каждый сервис: якорь, ничего, что его снимает, лимиты, tmpfs, порты."""
|
||||
text = _read(root, COMPOSE)
|
||||
anchors = _anchors(text)
|
||||
exceptions = _exceptions(text)
|
||||
problems = []
|
||||
for service, block in _services(root, COMPOSE).items():
|
||||
where = f"{COMPOSE}: {service}"
|
||||
names, merged = _merged(block, anchors)
|
||||
if ANCHOR not in names:
|
||||
problems.append(f"{where} without <<: *{ANCHOR}")
|
||||
allowed = exceptions.get(service, {})
|
||||
for key in ("cap_drop", "security_opt", "privileged", "devices"):
|
||||
if re.search(rf"^ {key}:", block, re.M):
|
||||
problems.append(f"{where} sets {key} itself")
|
||||
if re.search(r"^ cap_add:", block, re.M) and "cap_add" not in allowed:
|
||||
problems.append(f"{where} adds capabilities")
|
||||
if re.search(r"^ read_only:", block, re.M) and "read_only" not in allowed:
|
||||
problems.append(f"{where} sets read_only itself")
|
||||
for key in ("network_mode", "pid", "ipc"):
|
||||
if re.search(rf"^ {key}: \"?host", block, re.M):
|
||||
problems.append(f"{where} {key}: host")
|
||||
if "docker.sock" in block:
|
||||
problems.append(f"{where} mounts the Docker socket")
|
||||
if re.search(r"^ volumes:\n(?: .*\n)* - type: tmpfs", block, re.M):
|
||||
problems.append(f"{where} tmpfs in volumes (override would drop it)")
|
||||
user = re.search(r"^ user: \"?([^\"\n]+)", block, re.M)
|
||||
if user and user.group(1).split(":")[0] in ("0", "root"):
|
||||
problems.append(f"{where} runs as root")
|
||||
if service in STORAGE_USERS and (
|
||||
not user or user.group(1) != STORAGE_USERS[service]
|
||||
):
|
||||
problems.append(f"{where} user is not {STORAGE_USERS[service]}")
|
||||
for key in ("cpus", "memory", "pids"):
|
||||
if not re.search(rf"^ +{key}: ", merged, re.M):
|
||||
problems.append(f"{where} without limit {key}")
|
||||
pids = re.search(r"^ +pids: (\d+)", merged, re.M)
|
||||
floor = 128 if service in GO_SERVICES else 64
|
||||
if pids and int(pids.group(1)) < floor:
|
||||
problems.append(f"{where} pids {pids.group(1)} < {floor}")
|
||||
tmpfs = re.search(r"^ tmpfs:(.*)\n((?: - .*\n)*)", block, re.M)
|
||||
if tmpfs and tmpfs.group(1).strip():
|
||||
problems.append(f"{where} tmpfs is not a list")
|
||||
for item in _items(block, "tmpfs"):
|
||||
options = item.split(":", 1)[1].split(",") if ":" in item else []
|
||||
keys = {option.split("=", 1)[0] for option in options}
|
||||
if not {"size", "mode"} <= keys:
|
||||
problems.append(f"{where} tmpfs {item} without size= and mode=")
|
||||
for port in _items(block, "ports"):
|
||||
if not port.startswith("127.0.0.1:"):
|
||||
problems.append(f"{where} port {port} not on 127.0.0.1")
|
||||
return problems
|
||||
|
||||
|
||||
def published_problems(root: Path) -> list[str]:
|
||||
"""Опубликованные порты = таблица HC_PUBLISHED проверки (сервис → порт
|
||||
контейнера)."""
|
||||
got = {}
|
||||
for service, block in _services(root, COMPOSE).items():
|
||||
for port in _items(block, "ports"):
|
||||
got[service] = int(port.rsplit(":", 1)[1])
|
||||
want = _lab7().HC_PUBLISHED
|
||||
if got != want:
|
||||
return [f"{COMPOSE}: published ports {got} != {LAB7} HC_PUBLISHED {want}"]
|
||||
return []
|
||||
|
||||
|
||||
def storage_problems(root: Path) -> list[str]:
|
||||
"""Хранилища без шагов от root: healthcheck брокера без su-exec, Grafana —
|
||||
журнал только в stdout, gRPC шлюза S3 — mTLS из security.toml."""
|
||||
services = _services(root, COMPOSE)
|
||||
problems = []
|
||||
for service, block in services.items():
|
||||
if re.search(r"\b(su-exec|gosu|setpriv)\b", block):
|
||||
problems.append(f"{COMPOSE}: {service} switches users in its commands")
|
||||
if "GF_LOG_MODE: console" not in services.get("grafana", ""):
|
||||
problems.append(f"{COMPOSE}: grafana writes its log to a file")
|
||||
if f"source: ./{SECURITY}" not in services.get("s3", "") or (
|
||||
"target: /etc/seaweedfs/security.toml" not in services.get("s3", "")
|
||||
):
|
||||
problems.append(f"{COMPOSE}: s3 does not mount {SECURITY}")
|
||||
security = _read(root, SECURITY)
|
||||
for needed in (
|
||||
'[grpc]\nca = "/run/secrets/ca.crt"',
|
||||
'[grpc.s3]\ncert = "/run/secrets/s3.crt"\nkey = "/run/secrets/s3.key"',
|
||||
):
|
||||
if needed not in security:
|
||||
problems.append(f"{SECURITY}: no {needed.splitlines()[0]}")
|
||||
if "[grpc.client]" in security:
|
||||
problems.append(f"{SECURITY}: [grpc.client] breaks the filer (split leaf)")
|
||||
# CRL порт не читает: допущено только имя разовой пробы s3-check, а не
|
||||
# identity стенда (перенос 15); ключ — только в секции слушателя шлюза
|
||||
section = security.split("[grpc.s3]", 1)[-1].split("\n[", 1)[0]
|
||||
names = re.findall(r'^allowed_commonNames = "([^"]*)"$', section, re.M)
|
||||
probe = re.search(r'^S3_GRPC_PROBE = "([^"]+)"$', _read(root, LAB7), re.M)
|
||||
allowed = names[0].split(",") if len(names) == 1 else []
|
||||
if security.count("allowed_commonNames") != len(names):
|
||||
problems.append(f"{SECURITY}: allowed_commonNames outside [grpc.s3]")
|
||||
if not probe or allowed != [probe.group(1)]:
|
||||
problems.append(
|
||||
f"{SECURITY}: [grpc.s3] allowed_commonNames {names} != the s3-check "
|
||||
f"probe {probe.group(1) if probe else None}"
|
||||
)
|
||||
listed = {
|
||||
line.split()[0] for line in _read(root, IDENTITIES).splitlines() if line.strip()
|
||||
}
|
||||
for name in sorted(set(allowed) & listed):
|
||||
problems.append(f"{SECURITY}: stand identity {name} is allowed on gRPC")
|
||||
return problems
|
||||
|
||||
|
||||
def override_problems(root: Path) -> list[str]:
|
||||
"""Override стендов не снимают ограничений: ни ключей якоря и пользователя,
|
||||
ни tmpfs, ни pids, ни сокета Docker, ни bind на запись, ни портов не на
|
||||
127.0.0.1."""
|
||||
problems = []
|
||||
for rel in OVERRIDES:
|
||||
for service, block in _services(root, rel).items():
|
||||
where = f"{rel}: {service}"
|
||||
for key in OVERRIDE_FORBIDDEN:
|
||||
if re.search(rf"^ +{key}:", block, re.M):
|
||||
problems.append(f"{where} sets {key}")
|
||||
if re.search(r"^ tmpfs: !(reset|override)", block, re.M):
|
||||
problems.append(f"{where} resets tmpfs")
|
||||
for item in _items(block, "tmpfs"):
|
||||
if "size=" not in item or "mode=" not in item:
|
||||
problems.append(f"{where} tmpfs {item} without size= and mode=")
|
||||
if "docker.sock" in block:
|
||||
problems.append(f"{where} mounts the Docker socket")
|
||||
if re.search(r"^ +read_only: false", block, re.M) or re.search(
|
||||
r"^ - \.?/?[^:\n]+:[^:\n]+:rw", block, re.M
|
||||
):
|
||||
problems.append(f"{where} bind mount for writing")
|
||||
for port in _items(block, "ports"):
|
||||
if not port.startswith("127.0.0.1:"):
|
||||
problems.append(f"{where} port {port} not on 127.0.0.1")
|
||||
return problems
|
||||
|
||||
|
||||
CHECKS = (
|
||||
anchor_problems,
|
||||
service_problems,
|
||||
published_problems,
|
||||
storage_problems,
|
||||
override_problems,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("check", CHECKS, ids=lambda check: check.__name__)
|
||||
def test_configuration(check) -> None:
|
||||
assert check(ROOT) == []
|
||||
|
||||
|
||||
def test_every_service_is_parsed() -> None:
|
||||
"""Разбор видит все сервисы compose: пропущенный сервис прошёл бы молча."""
|
||||
names = set(_services(ROOT, COMPOSE))
|
||||
for needed in ("postgres", "api", "worker", "haproxy", "grafana", "tempo"):
|
||||
assert needed in names
|
||||
section = _read(ROOT, COMPOSE).split("\nservices:\n", 1)[1].split("\nnetworks:")[0]
|
||||
assert names == set(re.findall(r"^ ([a-z0-9-]+):$", section, re.M))
|
||||
|
||||
|
||||
def test_check_tables_cover_the_stand() -> None:
|
||||
"""Слушатели HC_LISTENERS — сервисы compose без network_mode (владельцы
|
||||
сетевых пространств), кроме процессов без портов."""
|
||||
lab7 = _lab7()
|
||||
services = _services(ROOT, COMPOSE)
|
||||
owners = {
|
||||
name
|
||||
for name, block in services.items()
|
||||
if not re.search(r"^ network_mode:", block, re.M)
|
||||
}
|
||||
silent = {"relay", "worker", "cleaner", "migrate", "postgres-bootstrap"}
|
||||
assert set(lab7.HC_LISTENERS) == owners - silent
|
||||
assert set(lab7.HC_NO_EXCEPTIONS) == set(NO_EXCEPTIONS)
|
||||
assert lab7.HC_LISTENERS["s3"] == (8333, 18333)
|
||||
|
||||
|
||||
def test_s3_grpc_cases_name_the_allowlist() -> None:
|
||||
"""`make s3-check`: leaf CA стенда с допущенным именем — ответ HTTP/2, с
|
||||
любым другим — отказ; ни одно из двух имён — не identity стенда (перенос 15)."""
|
||||
lab7 = _lab7()
|
||||
listed = {
|
||||
line.split()[0] for line in _read(ROOT, IDENTITIES).splitlines() if line.strip()
|
||||
}
|
||||
assert {lab7.S3_GRPC_PROBE, lab7.S3_GRPC_DENIED}.isdisjoint(listed)
|
||||
assert lab7.S3_GRPC_PROBE != lab7.S3_GRPC_DENIED
|
||||
outcomes = {material: want for _, material, want in lab7.S3_GRPC_CASES}
|
||||
assert outcomes["probe"] == lab7.S3_GRPC_ANSWER
|
||||
assert outcomes["denied"] == lab7.S3_GRPC_REFUSED
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("check", "rel", "old", "new"),
|
||||
[
|
||||
(anchor_problems, COMPOSE, " read_only: true\n cap_drop:",
|
||||
" read_only: false\n cap_drop:"),
|
||||
(anchor_problems, COMPOSE, "x-hardening-exceptions: {}",
|
||||
"x-hardening-exceptions:\n worker:\n read_only: render"),
|
||||
(service_problems, COMPOSE, " postgres:\n <<: *hardened\n",
|
||||
" postgres:\n"),
|
||||
(service_problems, COMPOSE, "volume tempodata\n <<: *hardened\n",
|
||||
"volume tempodata\n <<: *hardened\n cap_add:\n - NET_RAW\n"),
|
||||
(service_problems, COMPOSE, ' user: "999:999"\n entrypoint: ["sh", '
|
||||
'"/opt/valkey', ' entrypoint: ["sh", "/opt/valkey'),
|
||||
(service_problems, COMPOSE, " - /run/valkey:size=1m,uid=999,gid=999,"
|
||||
"mode=0700", " - /run/valkey"),
|
||||
(service_problems, COMPOSE, " memory: 384M\n pids: 128\n",
|
||||
" memory: 384M\n"),
|
||||
(service_problems, COMPOSE, '"127.0.0.1:${GRAFANA_HOST_PORT:-3180}:3000"',
|
||||
'"${GRAFANA_HOST_PORT:-3180}:3000"'),
|
||||
(service_problems, COMPOSE, " grafana:\n <<: *hardened\n",
|
||||
" grafana:\n <<: *hardened\n pid: host\n"),
|
||||
(published_problems, COMPOSE,
|
||||
" - \"127.0.0.1:${BROKER_HOST_PORT:-5673}:5671\"\n", ""),
|
||||
(storage_problems, COMPOSE, '["CMD", "rabbitmq-diagnostics"',
|
||||
'["CMD", "su-exec", "rabbitmq", "rabbitmq-diagnostics"'),
|
||||
(storage_problems, COMPOSE, "GF_LOG_MODE: console", "GF_LOG_MODE: file"),
|
||||
(storage_problems, SECURITY, "\n[grpc.s3]\n", "\n[grpc.filer]\n"),
|
||||
# перенос 15: пустой список, identity стенда, написание, которое
|
||||
# SeaweedFS не видит, ключ вне секции слушателя шлюза
|
||||
(storage_problems, SECURITY, 'allowed_commonNames = "s3-grpc-probe"',
|
||||
'allowed_commonNames = ""'),
|
||||
(storage_problems, SECURITY, 'allowed_commonNames = "s3-grpc-probe"',
|
||||
'allowed_commonNames = "s3-grpc-probe,worker"'),
|
||||
(storage_problems, SECURITY, 'allowed_commonNames = "s3-grpc-probe"',
|
||||
'allowed_commonnames = "s3-grpc-probe"'),
|
||||
(storage_problems, SECURITY, 'ca = "/run/secrets/ca.crt"\n',
|
||||
'ca = "/run/secrets/ca.crt"\nallowed_commonNames = "s3-grpc-probe"\n'),
|
||||
(override_problems, OVERRIDES[0], " openbao:\n restart: \"no\"\n",
|
||||
" openbao:\n restart: \"no\"\n read_only: false\n"),
|
||||
(override_problems, OVERRIDES[1], " container_name: vlad-bench-worker\n",
|
||||
" container_name: vlad-bench-worker\n cap_add:\n - SYS_ADMIN\n"),
|
||||
(override_problems, OVERRIDES[1], " container_name: vlad-bench-lb\n",
|
||||
" container_name: vlad-bench-lb\n volumes:\n"
|
||||
" - /var/run/docker.sock:/var/run/docker.sock\n"),
|
||||
],
|
||||
) # fmt: skip
|
||||
def test_control_is_red(tmp_path: Path, check, rel: str, old: str, new: str) -> None:
|
||||
for name in (COMPOSE, *OVERRIDES, SECURITY, IDENTITIES, LAB7):
|
||||
target = tmp_path / name
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(ROOT / name, target)
|
||||
assert check(tmp_path) == []
|
||||
text = (tmp_path / rel).read_text(encoding="utf-8")
|
||||
assert old in text, (rel, old)
|
||||
(tmp_path / rel).write_text(text.replace(old, new, 1), encoding="utf-8")
|
||||
problems = check(tmp_path)
|
||||
assert any(rel in problem for problem in problems), problems
|
||||
@@ -0,0 +1,603 @@
|
||||
"""Лаба 7: роли PostgreSQL процессов и ACL Valkey (перенос storage-roles).
|
||||
|
||||
Без стенда. Матрица `src/db_roles.py` сверяется:
|
||||
|
||||
- со схемой (`src/storage/tables.py`): строка на каждую таблицу, колонки
|
||||
`UPDATE` есть в таблице;
|
||||
- с SQL хранилища: `METHOD_NEEDS` — что делает SQL каждого метода
|
||||
`PostgresStorage` и `PostgresPipeline` (S — SELECT, I — INSERT, D — DELETE, U
|
||||
— UPDATE колонок, L — блокировка строки); у нового метода нет строки — тест
|
||||
красный. Записи (`update(…).values(…)`, `insert`, `delete`, `ON CONFLICT DO
|
||||
UPDATE`, `with_for_update`) таблица сверяет с исходным кодом метода сама
|
||||
(AST), чтения — вручную;
|
||||
- с процессами: какие методы зовёт процесс, тест находит в его модулях (AST
|
||||
вызовов `storage.` / `pipeline.`), и права роли должны быть **равны**
|
||||
объединению потребностей этих методов — недостающее и лишнее право красные.
|
||||
|
||||
Ещё: построители SQL (кавычки, имена базы, верификатор), SCRAM-верификатор,
|
||||
проверка настроек bootstrap (имена без значений), клиент Valkey (пользователь
|
||||
ACL, без `CLIENT SETINFO`) и учётные данные сервисов в `compose.yaml` — каждому
|
||||
своя роль, суперпользователь только у `postgres` и `postgres-bootstrap`.
|
||||
Права на настоящем PostgreSQL — `make storage-roles-check` на стенде и
|
||||
`make test-isolated` / `make failure-checks` (журнал без «permission denied»).
|
||||
"""
|
||||
|
||||
import ast
|
||||
import inspect
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import textwrap
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from src import db_roles
|
||||
from src.cache import create_cache
|
||||
from src.config import Cache, Settings
|
||||
from src.db_bootstrap import settings_problems
|
||||
from src.storage.pipeline import PostgresPipeline
|
||||
from src.storage.postgres import PostgresStorage
|
||||
from src.storage.tables import metadata
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def need(
|
||||
*,
|
||||
s: bool = False,
|
||||
i: bool = False,
|
||||
d: bool = False,
|
||||
u: tuple[str, ...] = (),
|
||||
lock: bool = False,
|
||||
) -> dict:
|
||||
return {"S": s, "I": i, "D": d, "U": frozenset(u), "L": lock}
|
||||
|
||||
|
||||
_JOB_RETRY = ("state", "lease_until", "published_at", "next_attempt_at", "last_error")
|
||||
|
||||
# метод хранилища → таблица → что делает его SQL
|
||||
METHOD_NEEDS: dict[str, dict[str, dict]] = {
|
||||
# --- PostgresStorage: API ---
|
||||
"ping": {},
|
||||
"create_user": {"users": need(s=True, i=True)},
|
||||
"get_credentials": {"users": need(s=True)},
|
||||
"create_session": {"sessions": need(i=True)},
|
||||
"create_session_with_rehash": {
|
||||
"users": need(s=True, u=("password_hash",)),
|
||||
"sessions": need(i=True),
|
||||
},
|
||||
"get_identity": {"sessions": need(s=True), "users": need(s=True)},
|
||||
"delete_session": {"sessions": need(s=True, d=True)},
|
||||
"create_chat": {
|
||||
"users": need(s=True),
|
||||
"chats": need(i=True),
|
||||
"chat_members": need(i=True),
|
||||
},
|
||||
"get_chat": {"chats": need(s=True), "chat_members": need(s=True)},
|
||||
"list_chats_of": {"chats": need(s=True), "chat_members": need(s=True)},
|
||||
"create_message": {
|
||||
"attachments": need(s=True),
|
||||
"idempotency_keys": need(
|
||||
s=True, i=True, u=("request_hash", "message_id", "created_at")
|
||||
),
|
||||
"messages": need(s=True, i=True),
|
||||
"message_attachments": need(s=True, i=True),
|
||||
},
|
||||
"list_messages": {"messages": need(s=True), "message_attachments": need(s=True)},
|
||||
"create_pending_attachment": {"attachments": need(i=True)},
|
||||
"queue_attachment": {
|
||||
"attachments": need(s=True, u=("status", "updated_at")),
|
||||
"attachment_jobs": need(i=True),
|
||||
},
|
||||
"count_unfinished_jobs": {"attachment_jobs": need(s=True)},
|
||||
"get_attachment": {
|
||||
"attachments": need(s=True),
|
||||
"attachment_variants": need(s=True),
|
||||
},
|
||||
# --- PostgresStorage: уборщик и сверка ---
|
||||
"list_stale_pending": {"attachments": need(s=True)},
|
||||
"mark_pending_removing": {
|
||||
"attachments": need(s=True, u=("updated_at",), lock=True)
|
||||
},
|
||||
"remove_stale_pending": {"attachments": need(s=True, d=True, lock=True)},
|
||||
"list_staging_done": {"attachments": need(s=True)},
|
||||
"clear_staging": {"attachments": need(s=True, u=("staging_key",), lock=True)},
|
||||
"attachments_by_ids": {"attachments": need(s=True)},
|
||||
"attachment_references": {"attachments": need(s=True)},
|
||||
"ready_page": {"attachments": need(s=True)},
|
||||
"mark_attachment_lost": {"attachments": need(s=True, u=("lost_at",))},
|
||||
"clear_attachment_lost": {"attachments": need(s=True, u=("lost_at",))},
|
||||
# --- PostgresPipeline: worker ---
|
||||
"claim_job": {
|
||||
"attachment_jobs": need(
|
||||
s=True, u=("state", "lease_until", "updated_at"), lock=True
|
||||
),
|
||||
"attachments": need(s=True, u=("status", "updated_at")),
|
||||
},
|
||||
"finish_job": {
|
||||
"attachment_jobs": need(
|
||||
s=True, u=("state", "lease_until", "last_error", "updated_at"), lock=True
|
||||
),
|
||||
# ON CONFLICT (ключ эффекта) DO NOTHING читает цель конфликта
|
||||
"attachment_variants": need(s=True, i=True),
|
||||
"attachments": need(s=True, u=("status", "error_code", "updated_at")),
|
||||
},
|
||||
"retry_job": {
|
||||
"attachment_jobs": need(s=True, u=(*_JOB_RETRY, "updated_at"), lock=True),
|
||||
"attachments": need(s=True, u=("status", "updated_at")),
|
||||
},
|
||||
"fail_job": {
|
||||
"attachment_jobs": need(
|
||||
s=True, u=("state", "lease_until", "last_error", "updated_at"), lock=True
|
||||
),
|
||||
"attachments": need(s=True, u=("status", "error_code", "updated_at")),
|
||||
},
|
||||
# --- PostgresPipeline: relay и replay ---
|
||||
"publish_due": {
|
||||
"attachment_jobs": need(
|
||||
s=True, u=("attempt", "published_at", "updated_at"), lock=True
|
||||
)
|
||||
},
|
||||
"recover_leases": {
|
||||
"attachment_jobs": need(s=True, u=(*_JOB_RETRY, "updated_at"), lock=True),
|
||||
"attachments": need(s=True, u=("status", "error_code", "updated_at")),
|
||||
},
|
||||
"republish_lost": {
|
||||
"attachment_jobs": need(s=True, u=("published_at", "updated_at"), lock=True)
|
||||
},
|
||||
"list_failed": {"attachment_jobs": need(s=True), "attachments": need(s=True)},
|
||||
"replay_job": {
|
||||
"attachment_jobs": need(
|
||||
s=True, u=(*_JOB_RETRY, "attempt_base", "updated_at"), lock=True
|
||||
),
|
||||
"attachments": need(
|
||||
s=True, u=("status", "error_code", "updated_at"), lock=True
|
||||
),
|
||||
"attachment_job_replays": need(i=True),
|
||||
},
|
||||
"pipeline_counts": {"attachment_jobs": need(s=True)},
|
||||
}
|
||||
|
||||
# модули процесса: в них тест ищет вызовы методов хранилища
|
||||
PROCESS_MODULES = {
|
||||
"api": (
|
||||
"src/services/users.py",
|
||||
"src/services/sessions.py",
|
||||
"src/services/chats.py",
|
||||
"src/services/messages.py",
|
||||
"src/services/attachments.py",
|
||||
"src/services/access.py",
|
||||
"src/api/routes/health.py",
|
||||
),
|
||||
"worker": ("src/services/processing.py", "src/worker/main.py"),
|
||||
"relay": ("src/services/relay.py", "src/services/replay.py", "src/relay/main.py"),
|
||||
"cleaner": (
|
||||
"src/services/cleanup.py",
|
||||
"src/services/reconcile.py",
|
||||
"src/cleaner/main.py",
|
||||
),
|
||||
}
|
||||
# имена, через которые процессы держат хранилище
|
||||
_HOLDERS = {"storage", "_storage", "pipeline", "_pipeline"}
|
||||
_STORAGE_CLASSES = (PostgresStorage, PostgresPipeline)
|
||||
|
||||
|
||||
def _storage_methods() -> set[str]:
|
||||
return {
|
||||
name
|
||||
for cls in _STORAGE_CLASSES
|
||||
for name, member in vars(cls).items()
|
||||
if not name.startswith("_") and inspect.iscoroutinefunction(member)
|
||||
}
|
||||
|
||||
|
||||
def _called_methods(path: str) -> set[str]:
|
||||
"""`<…>.storage.<метод>(` и т. п. в модуле процесса."""
|
||||
tree = ast.parse((ROOT / path).read_text(encoding="utf-8"))
|
||||
found = set()
|
||||
for node in ast.walk(tree):
|
||||
if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)):
|
||||
continue
|
||||
holder = node.func.value
|
||||
name = (
|
||||
holder.attr
|
||||
if isinstance(holder, ast.Attribute)
|
||||
else getattr(holder, "id", None)
|
||||
)
|
||||
if name in _HOLDERS:
|
||||
found.add(node.func.attr)
|
||||
return found
|
||||
|
||||
|
||||
def _process_methods(process: str) -> set[str]:
|
||||
methods = set()
|
||||
for path in PROCESS_MODULES[process]:
|
||||
methods |= _called_methods(path)
|
||||
return methods & _storage_methods()
|
||||
|
||||
|
||||
def _grant_of(needs: list[dict]) -> db_roles.TableGrant:
|
||||
update: set[str] = set()
|
||||
for item in needs:
|
||||
update |= item["U"]
|
||||
return db_roles.TableGrant(
|
||||
select=any(item["S"] for item in needs),
|
||||
insert=any(item["I"] for item in needs),
|
||||
delete=any(item["D"] for item in needs),
|
||||
update=frozenset(update),
|
||||
)
|
||||
|
||||
|
||||
def test_matrix_covers_schema() -> None:
|
||||
assert set(db_roles.TABLES) == set(metadata.tables)
|
||||
for role, tables in db_roles.MATRIX.items():
|
||||
assert set(tables) == set(db_roles.TABLES), role
|
||||
for table, grant in tables.items():
|
||||
columns = set(metadata.tables[table].c.keys())
|
||||
assert grant.update <= columns, (role, table, grant.update - columns)
|
||||
|
||||
|
||||
def test_every_storage_method_has_needs() -> None:
|
||||
assert _storage_methods() == set(METHOD_NEEDS)
|
||||
for method, tables in METHOD_NEEDS.items():
|
||||
for table, item in tables.items():
|
||||
assert table in metadata.tables, (method, table)
|
||||
assert item["U"] <= set(metadata.tables[table].c.keys()), (method, table)
|
||||
|
||||
|
||||
# имена таблиц в исходном коде хранилища (переменные tables.py)
|
||||
_TABLE_NAMES = set(metadata.tables)
|
||||
|
||||
|
||||
def _method_tree(method: str) -> ast.Module:
|
||||
"""Исходный код метода вместе с вспомогательными `self._x(…)` класса и
|
||||
`_x(…)` модуля (`_new_session`, `_stale_lock`, `_fenced`): запрос часто
|
||||
строит помощник."""
|
||||
cls = next(c for c in _STORAGE_CLASSES if method in vars(c))
|
||||
module = sys.modules[cls.__module__]
|
||||
seen: set[str] = set()
|
||||
bodies: list[ast.stmt] = []
|
||||
queue = [vars(cls)[method]]
|
||||
while queue:
|
||||
func = queue.pop()
|
||||
tree = ast.parse(textwrap.dedent(inspect.getsource(func)))
|
||||
bodies.extend(tree.body)
|
||||
for node in ast.walk(tree):
|
||||
if not isinstance(node, ast.Call):
|
||||
continue
|
||||
name, helper = None, None
|
||||
if isinstance(node.func, ast.Attribute) and isinstance(
|
||||
node.func.value, ast.Name
|
||||
):
|
||||
if node.func.value.id == "self" and node.func.attr.startswith("_"):
|
||||
name = node.func.attr
|
||||
helper = vars(cls).get(name)
|
||||
elif isinstance(node.func, ast.Name) and node.func.id.startswith("_"):
|
||||
name = node.func.id
|
||||
helper = getattr(module, name, None)
|
||||
if name and name not in seen and inspect.isfunction(helper):
|
||||
seen.add(name)
|
||||
queue.append(helper)
|
||||
return ast.Module(body=bodies, type_ignores=[])
|
||||
|
||||
|
||||
def _method_writes(method: str) -> dict[str, dict]:
|
||||
"""Записи метода по его исходному коду: таблица → I / D / U колонок, и
|
||||
есть ли в нём блокировка строки (`with_for_update`)."""
|
||||
tree = _method_tree(method)
|
||||
writes: dict[str, dict] = {}
|
||||
|
||||
def table(node: ast.AST) -> str | None:
|
||||
return (
|
||||
node.id if isinstance(node, ast.Name) and node.id in _TABLE_NAMES else None
|
||||
)
|
||||
|
||||
def base_table(call: ast.AST) -> str | None:
|
||||
# update(t).where(…).values(…): спуститься по цепочке до update(t)
|
||||
while isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute):
|
||||
call = call.func.value
|
||||
if (
|
||||
isinstance(call, ast.Call)
|
||||
and isinstance(call.func, ast.Name)
|
||||
and call.func.id == "update"
|
||||
and call.args
|
||||
):
|
||||
return table(call.args[0])
|
||||
return None
|
||||
|
||||
def insert_table(call: ast.AST) -> str | None:
|
||||
# pg_insert(t).values(…).on_conflict_…(…): до pg_insert(t)
|
||||
while isinstance(call, ast.Call) and isinstance(call.func, ast.Attribute):
|
||||
call = call.func.value
|
||||
if (
|
||||
isinstance(call, ast.Call)
|
||||
and isinstance(call.func, ast.Name)
|
||||
and call.func.id in ("insert", "pg_insert")
|
||||
and call.args
|
||||
):
|
||||
return table(call.args[0])
|
||||
return None
|
||||
|
||||
def entry(name: str) -> dict:
|
||||
return writes.setdefault(name, {"I": False, "D": False, "U": set(), "S": False})
|
||||
|
||||
lock = False
|
||||
for node in ast.walk(tree):
|
||||
if not isinstance(node, ast.Call):
|
||||
continue
|
||||
func = node.func
|
||||
if isinstance(func, ast.Name) and func.id in (
|
||||
"insert",
|
||||
"pg_insert",
|
||||
"sa_delete",
|
||||
):
|
||||
name = table(node.args[0]) if node.args else None
|
||||
if name:
|
||||
entry(name)["D" if func.id == "sa_delete" else "I"] = True
|
||||
if isinstance(func, ast.Attribute):
|
||||
if func.attr == "insert" and table(func.value):
|
||||
entry(func.value.id)["I"] = True
|
||||
if func.attr == "values":
|
||||
name = base_table(func.value)
|
||||
if name:
|
||||
entry(name)["U"] |= {kw.arg for kw in node.keywords if kw.arg}
|
||||
if func.attr == "on_conflict_do_update":
|
||||
for kw in node.keywords:
|
||||
if kw.arg == "set_" and isinstance(kw.value, ast.Dict):
|
||||
keys = {
|
||||
k.value
|
||||
for k in kw.value.keys
|
||||
if isinstance(k, ast.Constant)
|
||||
}
|
||||
writes.setdefault("on_conflict", {"U": set()})["U"] |= keys
|
||||
# ON CONFLICT (цель) читает колонки цели: нужен SELECT (на стенде
|
||||
# без него — «permission denied for table attachment_variants»)
|
||||
if func.attr in ("on_conflict_do_nothing", "on_conflict_do_update") and any(
|
||||
kw.arg == "index_elements" for kw in node.keywords
|
||||
):
|
||||
name = insert_table(func.value)
|
||||
if name:
|
||||
entry(name)["S"] = True
|
||||
if func.attr == "with_for_update":
|
||||
lock = True
|
||||
writes["lock"] = {"L": lock}
|
||||
return writes
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", sorted(METHOD_NEEDS))
|
||||
def test_method_needs_match_source_writes(method: str) -> None:
|
||||
writes = _method_writes(method)
|
||||
needs = METHOD_NEEDS[method]
|
||||
assert writes.pop("lock")["L"] == any(item["L"] for item in needs.values())
|
||||
conflict = writes.pop("on_conflict", {"U": set()})["U"]
|
||||
if conflict:
|
||||
assert any(conflict <= item["U"] and item["I"] for item in needs.values())
|
||||
for name, write in writes.items():
|
||||
item = needs.get(name)
|
||||
assert item is not None, (method, name)
|
||||
assert write["I"] == item["I"], (method, name, "INSERT")
|
||||
assert write["D"] == item["D"], (method, name, "DELETE")
|
||||
assert write["U"] <= item["U"], (method, name, write["U"] - item["U"])
|
||||
if write["S"]:
|
||||
assert item["S"], (method, name, "SELECT for ON CONFLICT")
|
||||
for name, item in needs.items():
|
||||
if item["I"] or item["D"]:
|
||||
assert name in writes, (method, name)
|
||||
|
||||
|
||||
def test_processes_use_only_their_storage() -> None:
|
||||
storage = {name for name in vars(PostgresStorage) if not name.startswith("_")}
|
||||
pipeline = {name for name in vars(PostgresPipeline) if not name.startswith("_")}
|
||||
assert _process_methods("api") <= storage
|
||||
assert _process_methods("cleaner") <= storage
|
||||
assert _process_methods("worker") <= pipeline
|
||||
assert _process_methods("relay") <= pipeline
|
||||
# каждый метод хранилища зовёт хоть один процесс (иначе матрица неполна)
|
||||
used = set().union(*(_process_methods(p) for p in PROCESS_MODULES))
|
||||
assert used == set(METHOD_NEEDS)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("role", db_roles.PROCESS_ROLES)
|
||||
def test_role_grants_equal_needs_of_its_queries(role: str) -> None:
|
||||
methods = _process_methods(role)
|
||||
assert methods, role
|
||||
for table in db_roles.TABLES:
|
||||
needs = [METHOD_NEEDS[m][table] for m in methods if table in METHOD_NEEDS[m]]
|
||||
expected = _grant_of(needs) if needs else db_roles.NO_GRANT
|
||||
assert db_roles.MATRIX[role][table] == expected, (role, table)
|
||||
# блокировке строки (FOR UPDATE / NO KEY UPDATE) нужен UPDATE хотя бы
|
||||
# одной колонки этой таблицы у роли
|
||||
if any(item["L"] for item in needs):
|
||||
assert db_roles.MATRIX[role][table].update, (role, table)
|
||||
|
||||
|
||||
def test_privilege_statements() -> None:
|
||||
full = db_roles.privilege_statements()
|
||||
assert full[0] == (
|
||||
'REVOKE ALL ON ALL TABLES IN SCHEMA "public" FROM PUBLIC, "api", '
|
||||
'"worker", "relay", "cleaner"'
|
||||
)
|
||||
assert any(s.startswith('REVOKE CREATE ON SCHEMA "public"') for s in full[:3])
|
||||
assert 'GRANT SELECT, INSERT, DELETE ON "public"."sessions" TO "api"' in full
|
||||
assert 'GRANT UPDATE ("password_hash") ON "public"."users" TO "api"' in full
|
||||
assert not any('"migrate"' in s for s in full)
|
||||
# на ревизии ниже head: только существующие таблицы и колонки
|
||||
partial = db_roles.privilege_statements(
|
||||
{"users": {"id", "password_hash"}, "attachments": {"id", "status"}}
|
||||
)
|
||||
assert not any('"sessions"' in s for s in partial)
|
||||
assert 'GRANT UPDATE ("status") ON "public"."attachments" TO "api"' in partial
|
||||
assert not any("updated_at" in s for s in partial)
|
||||
|
||||
|
||||
def test_sql_builders_reject_bad_input() -> None:
|
||||
assert db_roles.quote_ident('a"b') == '"a""b"'
|
||||
with pytest.raises(ValueError, match="must match"):
|
||||
db_roles.check_database_name("messenger; DROP")
|
||||
with pytest.raises(ValueError, match="must match"):
|
||||
db_roles.database_access_sql("Bad-Name")
|
||||
with pytest.raises(ValueError, match="not a SCRAM"):
|
||||
db_roles.set_password_sql("api", "plain password")
|
||||
with pytest.raises(ValueError, match="unknown object kind"):
|
||||
db_roles.object_owner_sql("FUNCTION", "f")
|
||||
with pytest.raises(ValueError, match="not a maintenance"):
|
||||
db_roles.maintenance_database_sql("messenger")
|
||||
with pytest.raises(ValueError, match="printable ASCII"):
|
||||
db_roles.check_role_password("")
|
||||
with pytest.raises(ValueError, match="printable ASCII"):
|
||||
db_roles.check_role_password("пароль")
|
||||
assert db_roles.revoke_membership_sql("relay", "pg_read_all_data", "boss") == (
|
||||
'REVOKE "pg_read_all_data" FROM "relay" GRANTED BY "boss"'
|
||||
)
|
||||
assert "NOINHERIT" in db_roles.create_role_sql("api")
|
||||
assert "NOSUPERUSER" in db_roles.alter_role_sql("api")
|
||||
assert db_roles.QUIET_SESSION_SQL[0] == "SET search_path = pg_catalog"
|
||||
|
||||
|
||||
def test_scram_verifier() -> None:
|
||||
verifier = db_roles.scram_verifier("s3cret pass", salt=b"0123456789abcdef")
|
||||
assert re.fullmatch(db_roles.SCRAM_VERIFIER_PATTERN, verifier)
|
||||
assert verifier.startswith("SCRAM-SHA-256$4096:MDEyMzQ1Njc4OWFiY2RlZg==$")
|
||||
assert db_roles.verifier_matches(verifier, "s3cret pass")
|
||||
assert not db_roles.verifier_matches(verifier, "other")
|
||||
assert not db_roles.verifier_matches(None, "s3cret pass")
|
||||
assert not db_roles.verifier_matches("md5abc", "s3cret pass")
|
||||
# соль случайная: два верификатора одного пароля разные
|
||||
assert db_roles.scram_verifier("x") != db_roles.scram_verifier("x")
|
||||
assert "s3cret" not in db_roles.set_password_sql("api", verifier)
|
||||
|
||||
|
||||
_ROLE_ENV = {
|
||||
f"DB_ROLE_{role.upper()}_PASSWORD": f"{role}-password"
|
||||
for role in db_roles.ALL_ROLES
|
||||
}
|
||||
|
||||
|
||||
def test_bootstrap_settings_problems_name_variables_only() -> None:
|
||||
good = Settings.from_env(
|
||||
{
|
||||
**_ROLE_ENV,
|
||||
"DB_USER": "messenger",
|
||||
"DB_PASSWORD": "x",
|
||||
"DB_NAME": "messenger",
|
||||
}
|
||||
)
|
||||
assert settings_problems(good) == []
|
||||
assert "api-password" not in repr(good)
|
||||
bad = Settings.from_env(
|
||||
{
|
||||
**_ROLE_ENV,
|
||||
"DB_ROLE_API_PASSWORD": "",
|
||||
"DB_ROLE_WORKER_PASSWORD": "пароль",
|
||||
"DB_USER": "api",
|
||||
"DB_NAME": "Bad",
|
||||
}
|
||||
)
|
||||
assert settings_problems(bad) == [
|
||||
"DB_ROLE_API_PASSWORD",
|
||||
"DB_ROLE_WORKER_PASSWORD",
|
||||
"DB_NAME",
|
||||
"DB_USER",
|
||||
"DB_PASSWORD",
|
||||
]
|
||||
|
||||
|
||||
def test_bootstrap_exits_2_without_values() -> None:
|
||||
env = {
|
||||
"PATH": os.environ.get("PATH", ""),
|
||||
**_ROLE_ENV,
|
||||
"DB_ROLE_RELAY_PASSWORD": "",
|
||||
"DB_PASSWORD": "superuser-secret",
|
||||
}
|
||||
done = subprocess.run(
|
||||
[sys.executable, "-m", "src.db_bootstrap"],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=60,
|
||||
check=False,
|
||||
)
|
||||
assert done.returncode == 2
|
||||
assert "DB_ROLE_RELAY_PASSWORD" in done.stderr
|
||||
assert "password" not in done.stderr.replace("_PASSWORD", "")
|
||||
assert "superuser-secret" not in done.stdout + done.stderr
|
||||
|
||||
|
||||
def test_cache_user_and_no_client_setinfo() -> None:
|
||||
settings = Settings.from_env({"CACHE_USER": "api", "CACHE_PASSWORD": "pw"})
|
||||
assert settings.cache.user == "api"
|
||||
assert Cache().user == ""
|
||||
ca = ROOT / ".pki" / "stand" / "ca.crt"
|
||||
if not ca.is_file():
|
||||
pytest.skip("no stand CA (make pki-stand) to build the TLS context")
|
||||
cache = create_cache(settings.cache, namespace="messenger", ca_file=str(ca))
|
||||
kwargs = cache._client.connection_pool.connection_kwargs
|
||||
assert kwargs["username"] == "api"
|
||||
assert kwargs["driver_info"] is None
|
||||
|
||||
|
||||
def _compose_services() -> dict[str, str]:
|
||||
"""Блоки сервисов compose.yaml текстом (отступ в два пробела)."""
|
||||
text = (ROOT / "compose.yaml").read_text(encoding="utf-8")
|
||||
body = text.split("\nservices:\n", 1)[1].split("\nnetworks:\n", 1)[0]
|
||||
blocks: dict[str, str] = {}
|
||||
name = ""
|
||||
for line in body.splitlines():
|
||||
found = re.match(r"^ ([a-z0-9-]+):$", line)
|
||||
if found:
|
||||
name = found.group(1)
|
||||
blocks[name] = ""
|
||||
elif name:
|
||||
blocks[name] += line + "\n"
|
||||
return blocks
|
||||
|
||||
|
||||
def test_compose_credentials_per_service() -> None:
|
||||
blocks = _compose_services()
|
||||
for role, service in (
|
||||
("api", "api"),
|
||||
("worker", "worker"),
|
||||
("relay", "relay"),
|
||||
("cleaner", "cleaner"),
|
||||
("migrate", "migrate"),
|
||||
):
|
||||
block = blocks[service]
|
||||
assert f"DB_USER: {role}\n" in block, service
|
||||
# пароля роли в окружении нет ни своего, ни чужого: процесс читает его из
|
||||
# OpenBao (перенос openbao-secrets, test_openbao_config.py)
|
||||
assert "DB_PASSWORD" not in block, service
|
||||
for other in db_roles.ALL_ROLES:
|
||||
assert f"POSTGRES_{other.upper()}_PASSWORD" not in block, (service, other)
|
||||
with_superuser = {
|
||||
name for name, block in blocks.items() if "${POSTGRES_PASSWORD:" in block
|
||||
}
|
||||
assert with_superuser == {"postgres", "postgres-bootstrap"}
|
||||
with_operator = {
|
||||
name for name, block in blocks.items() if "VALKEY_OPERATOR_PASSWORD" in block
|
||||
}
|
||||
assert with_operator == {"valkey"}
|
||||
assert "CACHE_USER: api" in (ROOT / "compose.yaml").read_text(encoding="utf-8")
|
||||
assert (
|
||||
"postgres-bootstrap:\n condition: service_completed_successfully"
|
||||
in (blocks["migrate"])
|
||||
)
|
||||
|
||||
|
||||
def test_valkey_acl_script() -> None:
|
||||
script = (ROOT / "infra" / "valkey" / "start.sh").read_text(encoding="utf-8")
|
||||
assert "user default off" in script
|
||||
assert "+get +set +eval +evalsha +ttl +expire +incr +decr +del" in script
|
||||
# ключи api — префикс кэша и счётчиков входа своей базы (src/constants.py)
|
||||
from src.constants import CACHE_KEY_PREFIX
|
||||
|
||||
assert f'CACHE_KEY_PREFIX="{CACHE_KEY_PREFIX}"' in script
|
||||
assert "+@all" not in script.split("user api", 1)[1].split("\n", 1)[0]
|
||||
done = subprocess.run(
|
||||
["sh", "-n", str(ROOT / "infra" / "valkey" / "start.sh")], check=False
|
||||
)
|
||||
assert done.returncode == 0
|
||||
@@ -0,0 +1,474 @@
|
||||
"""Лаба 7: согласованность OpenBao (перенос openbao-secrets), без стенда.
|
||||
|
||||
Политика процесса = пути его кода (`src/secrets_store.py`), роли входа = строки
|
||||
`infra/pki/identities.conf`, пути наполнения — ровно их объединение, значения — те
|
||||
переменные, которые compose отдаёт хранилищам; в `compose.yaml` у процессов нет
|
||||
секретов в окружении, файлы — только свои, OpenBao закреплён, не dev-mode и ждёт
|
||||
его каждый процесс. Команды оператора (`infra/openbao/bao.py`): материалы временного
|
||||
стенда только в его каталоге, вывод без токенов, запечатанный — код 2. Контроли:
|
||||
лишний путь и чужой SAN краснят сверку.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import importlib.util
|
||||
import os
|
||||
import re
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
|
||||
import pytest
|
||||
|
||||
from src.secrets_store import KV_MOUNT, PROCESSES
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
BAO_DIR = ROOT / "infra" / "openbao"
|
||||
OWN_TOKEN = {
|
||||
"auth/token/lookup-self": "read",
|
||||
"auth/token/renew-self": "update",
|
||||
"auth/token/revoke-self": "update",
|
||||
}
|
||||
# пара identity процесса в OpenBao: сервис compose → имя строки identities.conf
|
||||
PAIRS = {
|
||||
"api": "api-client",
|
||||
"worker": "worker",
|
||||
"relay": "relay",
|
||||
"cleaner": "cleaner",
|
||||
"migrate": "migrate",
|
||||
}
|
||||
|
||||
|
||||
def _module() -> ModuleType:
|
||||
spec = importlib.util.spec_from_file_location("test_bao", BAO_DIR / "bao.py")
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules["test_bao"] = module
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
bao = _module()
|
||||
|
||||
|
||||
def _code_paths() -> dict[str, set[str]]:
|
||||
"""Роль входа → пути, которые читает код её процессов."""
|
||||
paths: dict[str, set[str]] = {}
|
||||
for spec in PROCESSES.values():
|
||||
paths.setdefault(spec.role, set()).update(spec.paths)
|
||||
return paths
|
||||
|
||||
|
||||
def _policy(text: str) -> dict[str, str]:
|
||||
"""Путь → права файла политики (комментарии убраны)."""
|
||||
code = "\n".join(line.split("#", 1)[0] for line in text.splitlines())
|
||||
rules = re.findall(
|
||||
r'path\s+"([^"]+)"\s*\{\s*capabilities\s*=\s*\[([^\]]*)\]\s*\}', code
|
||||
)
|
||||
assert len(rules) == code.count("path "), "unparsed policy rule"
|
||||
return {path: rights.replace('"', "").strip() for path, rights in rules}
|
||||
|
||||
|
||||
def _policy_problems(role: str, text: str, paths: set[str]) -> list[str]:
|
||||
want = {f"{KV_MOUNT}/data/{path}": "read" for path in paths} | OWN_TOKEN
|
||||
got = _policy(text)
|
||||
problems = [f"extra {p}" for p in sorted(set(got) - set(want))]
|
||||
problems += [f"missing {p}" for p in sorted(set(want) - set(got))]
|
||||
problems += [f"rights {p}" for p in got if p in want and got[p] != want[p]]
|
||||
problems += [f"wildcard {p}" for p in got if set("*+") & set(p)]
|
||||
return problems
|
||||
|
||||
|
||||
def _identities() -> dict[str, tuple[str, str]]:
|
||||
rows = {}
|
||||
text = (ROOT / "infra" / "pki" / "identities.conf").read_text(encoding="utf-8")
|
||||
for line in text.splitlines():
|
||||
if line.strip() and not line.startswith("#"):
|
||||
name, profile, sans, _ = line.split()
|
||||
rows[name] = (profile, sans)
|
||||
return rows
|
||||
|
||||
|
||||
def _role_problems(rows: dict[str, tuple[str, str]]) -> list[str]:
|
||||
problems = []
|
||||
for role, spec in bao.ROLES.items():
|
||||
if rows.get(spec["cn"]) != ("client", spec["san"]):
|
||||
problems.append(f"{role}: {spec['cn']} {rows.get(spec['cn'])}")
|
||||
return problems
|
||||
|
||||
|
||||
def _services() -> dict[str, str]:
|
||||
"""Блоки сервисов compose.yaml текстом (отступ в два пробела)."""
|
||||
text = (ROOT / "compose.yaml").read_text(encoding="utf-8")
|
||||
body = text.split("\nservices:\n", 1)[1].split("\nnetworks:\n", 1)[0]
|
||||
blocks: dict[str, str] = {}
|
||||
name = ""
|
||||
for line in body.splitlines():
|
||||
found = re.match(r"^ ([a-z0-9-]+):$", line)
|
||||
if found:
|
||||
name = found.group(1)
|
||||
blocks[name] = ""
|
||||
elif name and not line.lstrip().startswith("#"):
|
||||
blocks[name] += line + "\n"
|
||||
return blocks
|
||||
|
||||
|
||||
# --- политики, роли, пути ---------------------------------------------------------
|
||||
|
||||
|
||||
def test_policies_equal_code_needs() -> None:
|
||||
needs = _code_paths()
|
||||
files = {path.stem for path in (BAO_DIR / "policies").glob("*.hcl")}
|
||||
assert files == set(needs) == set(bao.ROLES)
|
||||
for role, paths in needs.items():
|
||||
text = (BAO_DIR / "policies" / f"{role}.hcl").read_text(encoding="utf-8")
|
||||
assert _policy_problems(role, text, paths) == [], role
|
||||
assert set(bao.policy_paths(role)) == paths
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"extra",
|
||||
[
|
||||
'path "messenger/data/postgres/api" {\n capabilities = ["read"]\n}\n',
|
||||
'path "messenger/data/*" {\n capabilities = ["read"]\n}\n',
|
||||
'path "sys/mounts" {\n capabilities = ["read"]\n}\n',
|
||||
],
|
||||
)
|
||||
def test_control_extra_policy_rule_is_red(extra: str) -> None:
|
||||
text = (BAO_DIR / "policies" / "worker.hcl").read_text(encoding="utf-8")
|
||||
assert _policy_problems("worker", text + extra, _code_paths()["worker"])
|
||||
|
||||
|
||||
def test_control_wider_rights_are_red() -> None:
|
||||
text = (BAO_DIR / "policies" / "relay.hcl").read_text(encoding="utf-8")
|
||||
wide = text.replace('["read"]', '["read", "update"]', 1)
|
||||
assert _policy_problems("relay", wide, _code_paths()["relay"])
|
||||
|
||||
|
||||
def test_roles_equal_identity_rows() -> None:
|
||||
rows = _identities()
|
||||
assert _role_problems(rows) == []
|
||||
assert rows["openbao"] == ("server", "openbao,localhost")
|
||||
assert rows["bao-operator"] == ("client", "bao-operator")
|
||||
# CN разных ролей различны: одного leaf на две роли нет
|
||||
assert len({spec["cn"] for spec in bao.ROLES.values()}) == len(bao.ROLES)
|
||||
|
||||
|
||||
def test_control_changed_san_is_red() -> None:
|
||||
rows = {**_identities(), "cleaner": ("client", "cleaner,api")}
|
||||
assert _role_problems(rows) == ["cleaner: cleaner ('client', 'cleaner,api')"]
|
||||
|
||||
|
||||
def test_role_needs_both_cn_and_san_and_no_default_policy(tmp_path: Path) -> None:
|
||||
(tmp_path / "ca.crt").write_text("ca", encoding="ascii")
|
||||
operator = object.__new__(bao.Operator)
|
||||
operator.pki_dir = tmp_path
|
||||
operator.args = argparse.Namespace(token_ttl=600, token_max_ttl=3600)
|
||||
role = operator._desired_role("api")
|
||||
assert role["allowed_common_names"] == ["api-client"]
|
||||
assert role["allowed_dns_sans"] == ["api"]
|
||||
assert role["token_policies"] == ["api"]
|
||||
assert role["token_no_default_policy"] is True
|
||||
assert role["token_type"] == "service"
|
||||
assert (role["token_ttl"], role["token_max_ttl"]) == (600, 3600)
|
||||
assert (bao.TOKEN_TTL, bao.TOKEN_MAX_TTL) == (600, 3600)
|
||||
|
||||
|
||||
def test_seed_covers_code_paths_and_fields() -> None:
|
||||
fields: dict[str, set[str]] = {}
|
||||
for spec in PROCESSES.values():
|
||||
for item in spec.fields:
|
||||
fields.setdefault(item.path, set()).add(item.key)
|
||||
assert {path: set(keys) for path, keys in bao.SEED.items()} == fields
|
||||
|
||||
|
||||
def test_seed_takes_what_compose_gives_to_storages() -> None:
|
||||
blocks = _services()
|
||||
for path, keys in bao.SEED.items():
|
||||
for service, variable in keys.values():
|
||||
assert f" {variable}: ${{" in blocks[service], (path, variable)
|
||||
|
||||
|
||||
def test_seed_has_no_administrative_secrets() -> None:
|
||||
text = repr(bao.SEED)
|
||||
for name in ("S3_ROOT", "JWT", "OPERATOR", "GRAFANA", "POSTGRES_PASSWORD"):
|
||||
assert name not in text
|
||||
|
||||
|
||||
# --- compose ----------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_processes_have_no_secrets_in_environment() -> None:
|
||||
blocks = _services()
|
||||
for service, pair in PAIRS.items():
|
||||
block = blocks[service]
|
||||
for name in (
|
||||
"PASSWORD",
|
||||
"ACCESS_KEY",
|
||||
"SECRET_KEY",
|
||||
"SIGNING_KEY",
|
||||
"BAO_TOKEN",
|
||||
"VAULT_TOKEN",
|
||||
):
|
||||
assert name not in block, (service, name)
|
||||
assert "*bao-env" in block, service
|
||||
assert f"BAO_CERT_FILE: /run/secrets/{pair}.crt\n" in block, service
|
||||
assert f"BAO_KEY_FILE: /run/secrets/{pair}.key\n" in block, service
|
||||
files = set(re.findall(r"^ - ([a-z-]+\.(?:crt|key|pem))$", block, re.M))
|
||||
own = {"ca.crt", "crl.pem", f"{pair}.crt", f"{pair}.key"}
|
||||
if service == "api":
|
||||
own |= {"api.crt", "api.key"}
|
||||
assert files == own, service
|
||||
assert "openbao:\n condition: service_healthy" in block, service
|
||||
anchors = (
|
||||
(ROOT / "compose.yaml").read_text(encoding="utf-8").split("\nservices:")[0]
|
||||
)
|
||||
assert "BAO_ADDR: https://openbao:8200\n" in anchors
|
||||
assert "PASSWORD:" not in anchors
|
||||
|
||||
|
||||
def test_storages_and_bootstraps_do_not_wait_for_openbao() -> None:
|
||||
blocks = _services()
|
||||
for service in ("postgres", "valkey", "s3", "rabbitmq", "postgres-bootstrap",
|
||||
"s3-bootstrap", "haproxy"): # fmt: skip
|
||||
assert "openbao:" not in blocks[service], service
|
||||
|
||||
|
||||
def test_openbao_service() -> None:
|
||||
blocks = _services()
|
||||
block = blocks["openbao"]
|
||||
assert re.search(
|
||||
r"image: openbao/openbao:\d+\.\d+\.\d+@sha256:[0-9a-f]{64}\n", block
|
||||
)
|
||||
assert '"-dev' not in block
|
||||
assert "DEV_ROOT" not in block
|
||||
assert '- "127.0.0.1:${BAO_HOST_PORT:-8200}:8200"' in block
|
||||
assert "- openbao_data:/openbao/file" in block
|
||||
assert "<<: *hardened" in block
|
||||
files = set(re.findall(r"^ - ([a-z-]+\.(?:crt|key|pem))$", block, re.M))
|
||||
assert files == {"ca.crt", "openbao.crt", "openbao.key"}
|
||||
# пара оператора и его каталог — ни у одного сервиса
|
||||
text = (ROOT / "compose.yaml").read_text(encoding="utf-8")
|
||||
code = "\n".join(line.split("#", 1)[0] for line in text.splitlines())
|
||||
for word in ("bao-operator", "vladimirceva-lab7/operator", "unseal", "root-token"):
|
||||
assert word not in code, word
|
||||
|
||||
|
||||
def test_openbao_config_is_not_dev_and_requires_client_certificates() -> None:
|
||||
text = (BAO_DIR / "config.hcl").read_text(encoding="utf-8")
|
||||
code = "\n".join(line.split("#", 1)[0] for line in text.splitlines())
|
||||
listeners = re.findall(r'listener "tcp" \{(.*?)\n\}', code, re.S)
|
||||
assert len(listeners) == 2
|
||||
main = next(item for item in listeners if '"0.0.0.0:8200"' in item)
|
||||
health = next(item for item in listeners if '"127.0.0.1:8210"' in item)
|
||||
assert re.search(r"tls_require_and_verify_client_cert\s*=\s*true", main)
|
||||
assert "tls_client_ca_file" in main
|
||||
for item in listeners:
|
||||
assert re.search(r'tls_min_version\s*=\s*"tls13"', item)
|
||||
assert "tls_disable " not in item
|
||||
assert re.search(r'cluster_address\s*=\s*"127\.0\.0\.1:', item)
|
||||
assert "tls_disable_client_certs" in health
|
||||
assert 'storage "raft"' in code
|
||||
assert re.search(r"ui\s*=\s*false", code)
|
||||
assert 'audit "file" "stdout"' in code
|
||||
|
||||
|
||||
# --- команды оператора ---------------------------------------------------------------
|
||||
|
||||
|
||||
def _args(tmp_path: Path, **extra: object) -> argparse.Namespace:
|
||||
pki = tmp_path / "pki"
|
||||
pki.mkdir(exist_ok=True)
|
||||
for name in ("ca.crt", "bao-operator.crt", "bao-operator.key"):
|
||||
(pki / name).write_text("x", encoding="ascii")
|
||||
values = {
|
||||
"command": "bao-status",
|
||||
"address": "https://localhost:1",
|
||||
"project": "test",
|
||||
"operator_dir": str(tmp_path / "operator" / "openbao" / "test"),
|
||||
"pki_dir": str(pki),
|
||||
"inside": None,
|
||||
"wait": 0.0,
|
||||
}
|
||||
return argparse.Namespace(**{**values, **extra})
|
||||
|
||||
|
||||
class _Http:
|
||||
"""Подмена API: ответы по пути, журнал запросов без тел."""
|
||||
|
||||
address = "https://localhost:1"
|
||||
|
||||
def __init__(self, state: dict) -> None:
|
||||
self.state = state
|
||||
self.calls: list[str] = []
|
||||
|
||||
def request(self, method, path, body=None, *, token=None, ok=(), timeout=None):
|
||||
self.calls.append(f"{method} {path}")
|
||||
if path == "sys/seal-status":
|
||||
return 200, dict(self.state)
|
||||
if path == "sys/health":
|
||||
return 200, {}
|
||||
if path == "sys/init":
|
||||
self.state |= {"initialized": True, "sealed": True, "t": 3, "n": 5}
|
||||
return 200, {"keys": [f"share-value-{n}" for n in range(5)],
|
||||
"root_token": "root-value"} # fmt: skip
|
||||
if path == "sys/unseal":
|
||||
if "key" in (body or {}):
|
||||
self.state["progress"] = self.state.get("progress", 0) + 1
|
||||
self.state["sealed"] = self.state["progress"] < 3
|
||||
return 200, {"sealed": self.state["sealed"]}
|
||||
raise AssertionError(path)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def operator(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):
|
||||
def build(state: dict, **extra: object):
|
||||
http = _Http(state)
|
||||
monkeypatch.setattr(bao, "BaoHttp", lambda *_a, **_k: http)
|
||||
return bao.Operator(_args(tmp_path, **extra)), http
|
||||
|
||||
return build
|
||||
|
||||
|
||||
def test_init_writes_0600_files_and_prints_no_secrets(
|
||||
operator, tmp_path, capsys
|
||||
) -> None:
|
||||
target, http = operator({"initialized": False, "sealed": True})
|
||||
assert target.init() == 0
|
||||
directory = target.operator_dir
|
||||
assert stat.S_IMODE(directory.stat().st_mode) == 0o700
|
||||
names = sorted(path.name for path in directory.iterdir())
|
||||
assert names == [
|
||||
"init-info",
|
||||
"root-token",
|
||||
*(f"unseal-share-{n}" for n in range(1, 6)),
|
||||
]
|
||||
for path in directory.iterdir():
|
||||
assert stat.S_IMODE(path.stat().st_mode) == 0o600, path.name
|
||||
out = capsys.readouterr().out
|
||||
assert "5 unseal shares, threshold 3" in out
|
||||
assert "unsealed OpenBao with 3 shares" in out
|
||||
assert "share-value" not in out
|
||||
assert "root-value" not in out
|
||||
# повтор ничего не меняет
|
||||
before = [path.read_bytes() for path in sorted(directory.iterdir())]
|
||||
assert target.init() == 0
|
||||
assert [path.read_bytes() for path in sorted(directory.iterdir())] == before
|
||||
assert http.calls.count("PUT sys/init") == 1
|
||||
|
||||
|
||||
def test_init_moves_stale_materials(operator, capsys) -> None:
|
||||
target, _ = operator({"initialized": False, "sealed": True})
|
||||
target.operator_dir.mkdir(parents=True)
|
||||
(target.operator_dir / "root-token").write_text("old", encoding="ascii")
|
||||
assert target.init() == 0
|
||||
stale = next(target.operator_dir.glob("stale-*"))
|
||||
assert (stale / "root-token").read_text(encoding="ascii") == "old"
|
||||
assert "moved materials of a previous initialization" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_ready_does_not_unseal(operator) -> None:
|
||||
target, http = operator({"initialized": True, "sealed": True, "t": 3})
|
||||
with pytest.raises(bao.Sealed, match="run make bao-unseal"):
|
||||
target.ready()
|
||||
assert http.calls == ["GET sys/seal-status"]
|
||||
|
||||
|
||||
def test_unseal_needs_materials(operator) -> None:
|
||||
target, http = operator({"initialized": True, "sealed": True, "t": 3})
|
||||
with pytest.raises(bao.BaoError, match="not enough unseal shares"):
|
||||
target.unseal()
|
||||
assert "PUT sys/unseal" not in http.calls
|
||||
target, _ = operator({"initialized": True, "sealed": False})
|
||||
assert target.unseal() == 0
|
||||
|
||||
|
||||
def test_materials_outside_the_run_are_refused(operator, tmp_path: Path) -> None:
|
||||
run = tmp_path / "run"
|
||||
inside = run / "operator" / "openbao" / "test"
|
||||
operator({}, operator_dir=str(inside), inside=str(run))
|
||||
outside = (
|
||||
tmp_path / "operator",
|
||||
run,
|
||||
run / ".." / "operator",
|
||||
Path.home() / ".config" / "vladimirceva-lab7" / "operator" / "openbao" / "x",
|
||||
)
|
||||
for directory in outside:
|
||||
with pytest.raises(bao.Usage, match="is not inside"):
|
||||
operator({}, operator_dir=str(directory), inside=str(run))
|
||||
# даже если «каталог прогона» — сам каталог оператора рабочего стенда
|
||||
home = Path.home() / ".config" / "vladimirceva-lab7" / "operator"
|
||||
with pytest.raises(bao.Usage, match="is not inside"):
|
||||
operator({}, operator_dir=str(home / "openbao" / "x"), inside=str(home))
|
||||
|
||||
|
||||
def test_command_codes(monkeypatch: pytest.MonkeyPatch, tmp_path, capsys) -> None:
|
||||
def run(error: Exception | None) -> int:
|
||||
class Operator:
|
||||
def __init__(self, _args: argparse.Namespace) -> None:
|
||||
if error is not None:
|
||||
raise error
|
||||
|
||||
def status(self) -> int:
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr(bao, "Operator", Operator)
|
||||
return bao.run(_args(tmp_path))
|
||||
|
||||
assert run(None) == 0
|
||||
assert run(bao.Sealed("OpenBao is sealed: run make bao-unseal")) == 2
|
||||
assert run(bao.Usage("no file")) == 2
|
||||
assert run(bao.BaoError("HTTP 500")) == 1
|
||||
assert "bao: OpenBao is sealed: run make bao-unseal" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_lab7_has_operator_commands_and_missing_files_are_code_2(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
for name in bao.COMMANDS:
|
||||
done = subprocess.run(
|
||||
[sys.executable, "scripts/lab7.py", f"bao-{name}", "--pki-dir",
|
||||
str(tmp_path)],
|
||||
cwd=ROOT,
|
||||
env={"PATH": os.environ["PATH"], "HOME": str(tmp_path)},
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
timeout=60,
|
||||
) # fmt: skip
|
||||
assert done.returncode == 2, (name, done.stderr)
|
||||
assert "run make pki-stand" in done.stdout, name
|
||||
|
||||
|
||||
def test_make_up_is_explicit_about_unseal() -> None:
|
||||
text = (ROOT / "Makefile").read_text(encoding="utf-8")
|
||||
up = text.split("\nup: ", 1)[1].split("\n\n", 1)[0]
|
||||
# перенос rotation-revocation: первой — проверка, что команда ротации не идёт
|
||||
assert up.splitlines()[0] == "rotation-idle env pki-stand bao-ready"
|
||||
assert "bao-unseal" not in up
|
||||
ready = text.split("\nbao-ready: ", 1)[1].split("\n\n", 1)[0]
|
||||
assert "bao-unseal" not in ready
|
||||
|
||||
|
||||
def test_instant_parses_docker_and_openbao_timestamps() -> None:
|
||||
first = bao._instant("2026-12-02T00:00:01.123456789Z")
|
||||
assert first < bao._instant("2026-12-02T00:00:01.2Z")
|
||||
assert first > bao._instant("2026-12-02T00:00:01Z")
|
||||
with pytest.raises(bao.BaoError):
|
||||
bao._instant("now")
|
||||
|
||||
|
||||
def test_temporary_stands_use_the_operator_command_of_their_run() -> None:
|
||||
for rel in ("student-tests/stand.py", "bench/common.py"):
|
||||
text = (ROOT / rel).read_text(encoding="utf-8")
|
||||
call = text.split('"bao-ready",', 1)[1].split("env=", 1)[0]
|
||||
for option in (
|
||||
"--address",
|
||||
"--operator-dir",
|
||||
"--pki-dir",
|
||||
"--project",
|
||||
"--inside",
|
||||
):
|
||||
assert option in call, (rel, option)
|
||||
@@ -0,0 +1,362 @@
|
||||
"""Лаба 7, перенос openbao-tooling: OpenBao прогона у временных стендов, без стенда.
|
||||
|
||||
Сводка секретов стенда отказов (`student-tests/secrets_log.py`): разбор строк
|
||||
журнала, промежутки без повторного входа (поток продления, умерший после первого
|
||||
входа, — нарушение; простой OpenBao вычитается), конец жизни при новом процессе,
|
||||
записи-проблемы и токены открытым текстом, аудит по ролям («audit parsed nothing»).
|
||||
Каталог материалов прогона: вне каталога прогона или в каталоге оператора рабочего
|
||||
стенда — отказ (`secrets_log`, hook, bench). `bao-rewrite` — те же значения новой
|
||||
версией, без значений в выводе; путь вне таблицы — код 2. Сроки ролей стенда
|
||||
отказов и их подмена; SIGTERM у `stand.py` и `bench/` — та же уборка, что Ctrl+C.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import datetime
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
T0 = datetime.datetime(2026, 12, 2, 0, 0, 0, tzinfo=datetime.UTC)
|
||||
LIMIT_S = 80 # max_ttl 60 + ttl 20 стенда отказов
|
||||
|
||||
|
||||
def _load(name: str, path: Path) -> ModuleType:
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
assert spec is not None
|
||||
assert spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules[name] = module
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
secrets_log = _load("tooling_secrets_log", ROOT / "student-tests" / "secrets_log.py")
|
||||
bao = _load("tooling_bao", ROOT / "infra" / "openbao" / "bao.py")
|
||||
hook = _load("tooling_fault_hook", ROOT / "student-tests" / "fault_hook.py")
|
||||
stand = _load("tooling_stand", ROOT / "student-tests" / "stand.py")
|
||||
common = _load("tooling_bench_common", ROOT / "bench" / "common.py")
|
||||
|
||||
|
||||
def _line(seconds: float, level: str, message: str) -> str:
|
||||
moment = T0 + datetime.timedelta(seconds=seconds)
|
||||
stamp = moment.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
|
||||
return f"{stamp} {level:<7} src.secrets_store [rid=-] {message}"
|
||||
|
||||
|
||||
LOADED = (
|
||||
"process secrets loaded process=api role=api address=https://openbao:8200 "
|
||||
"versions=postgres/api:1,valkey/api:1,s3/api:1 token_ttl=20s policies=api "
|
||||
"waited=0.0s"
|
||||
)
|
||||
|
||||
|
||||
def _relogin(reason: str) -> str:
|
||||
return (
|
||||
"logged in to secret store again process=api role=api "
|
||||
f"reason={reason} token_ttl=20s"
|
||||
)
|
||||
|
||||
|
||||
def _summary(lines: list[str], end_s: float | None):
|
||||
end = None if end_s is None else T0 + datetime.timedelta(seconds=end_s)
|
||||
return secrets_log.summarize_process(
|
||||
"api", "\n".join(lines), end=end, limit_s=LIMIT_S
|
||||
)
|
||||
|
||||
|
||||
# --- разбор журнала и сводка процесса ----------------------------------------------
|
||||
|
||||
|
||||
def test_parse_reads_time_level_message_and_fields() -> None:
|
||||
(record,) = secrets_log.parse(
|
||||
_line(1.5, "INFO", LOADED) + " trace_id=abc span_id=def\nTraceback:"
|
||||
)
|
||||
assert record["at"] == T0 + datetime.timedelta(seconds=1.5)
|
||||
assert record["level"] == "INFO"
|
||||
assert record["message"] == "process secrets loaded"
|
||||
assert record["fields"]["token_ttl"] == "20s"
|
||||
assert record["fields"]["versions"] == "postgres/api:1,valkey/api:1,s3/api:1"
|
||||
|
||||
|
||||
def test_regular_relogins_pass() -> None:
|
||||
lines = [_line(0, "INFO", LOADED)] + [
|
||||
_line(58 * n, "INFO", _relogin("max_ttl")) for n in (1, 2, 3)
|
||||
]
|
||||
line, problems, counts = _summary(lines, 200)
|
||||
assert problems == []
|
||||
assert counts["lives"] == 1
|
||||
assert counts["max_ttl"] == 3
|
||||
assert "longest gap without relogin 58 s" in line
|
||||
|
||||
|
||||
def test_renewal_thread_that_died_after_the_first_relogin_is_a_problem() -> None:
|
||||
lines = [_line(0, "INFO", LOADED), _line(58, "INFO", _relogin("max_ttl"))]
|
||||
_, problems, _ = _summary(lines, 300)
|
||||
assert len(problems) == 1
|
||||
assert "242 s without logging in again" in problems[0]
|
||||
assert "logged in to secret store again" in problems[0]
|
||||
|
||||
|
||||
def test_openbao_outage_is_excluded_from_the_gap() -> None:
|
||||
lines = [
|
||||
_line(0, "INFO", LOADED),
|
||||
_line(58, "INFO", _relogin("max_ttl")),
|
||||
_line(
|
||||
70,
|
||||
"WARNING",
|
||||
"secret store is unavailable process=api error=ConnectionRefusedError "
|
||||
"token_expires_in=6.0s",
|
||||
),
|
||||
_line(150, "INFO", "secret store is available again process=api"),
|
||||
_line(150, "INFO", _relogin("expired")),
|
||||
]
|
||||
_, problems, counts = _summary(lines, 200)
|
||||
# без вычитания простоя: 150 - 58 = 92 > 80
|
||||
assert problems == []
|
||||
assert counts["unavailable"] == 1
|
||||
assert counts["available_again"] == 1
|
||||
assert counts["expired"] == 1
|
||||
|
||||
|
||||
def test_a_new_process_closes_the_previous_life() -> None:
|
||||
lines = [
|
||||
_line(0, "INFO", LOADED),
|
||||
# kill: новый процесс ждёт OpenBao — прежняя жизнь кончилась раньше
|
||||
_line(
|
||||
300,
|
||||
"WARNING",
|
||||
"waiting for secret store process=api address=https://openbao:8200 "
|
||||
"error=sealed timeout=15s",
|
||||
),
|
||||
_line(310, "INFO", LOADED),
|
||||
_line(368, "INFO", _relogin("max_ttl")),
|
||||
]
|
||||
_, problems, counts = _summary(lines, 380)
|
||||
assert problems == []
|
||||
assert counts["lives"] == 2
|
||||
|
||||
|
||||
def test_refusals_and_tokens_are_problems() -> None:
|
||||
lines = [
|
||||
_line(0, "INFO", LOADED),
|
||||
_line(
|
||||
10,
|
||||
"ERROR",
|
||||
"secret store refused access process=api role=api reason=denied "
|
||||
"status=403 path=messenger/data/postgres/worker",
|
||||
),
|
||||
_line(11, "INFO", "token s.ABCDEFGHIJKLMNOPQRSTUVWXYZ012345 leaked"),
|
||||
]
|
||||
_, problems, counts = _summary(lines, 20)
|
||||
assert counts["issues"] == 1
|
||||
assert counts["tokens"] == 1
|
||||
assert any("refused access" in problem for problem in problems)
|
||||
assert any("s.-tokens in plaintext" in problem for problem in problems)
|
||||
assert not any("ABCDEFGH" in problem for problem in problems)
|
||||
|
||||
|
||||
def _audit(role: str, path: str, error: str = "") -> str:
|
||||
record = {
|
||||
"type": "response",
|
||||
"auth": {"display_name": f"cert-{role}"},
|
||||
"request": {"path": path, "operation": "update"},
|
||||
"error": error,
|
||||
}
|
||||
return json.dumps(record, separators=(",", ":"))
|
||||
|
||||
|
||||
def test_audit_summary_counts_renewals_by_role() -> None:
|
||||
renew = secrets_log.AUDIT_RENEW_PATH
|
||||
lines = [_audit(role, renew) for role in secrets_log.RENEWING_ROLES]
|
||||
lines += [
|
||||
_audit("api", secrets_log.AUDIT_LOGIN_PATH),
|
||||
_audit("worker", renew, "permission denied"),
|
||||
]
|
||||
line, problems = secrets_log.summarize_audit("\n".join(lines))
|
||||
assert problems == []
|
||||
assert "renewals api=1 cleaner=1 relay=1 worker=1" in line
|
||||
assert "error responses auth/token/renew-self=1" in line
|
||||
_, problems = secrets_log.summarize_audit("\n".join(lines[1:]))
|
||||
assert problems == ["roles without renewals in the audit: api"]
|
||||
_, problems = secrets_log.summarize_audit("not json\n")
|
||||
assert problems[0].startswith("audit parsed nothing")
|
||||
|
||||
|
||||
# --- каталог материалов прогона ---------------------------------------------------
|
||||
|
||||
|
||||
def test_operator_dir_must_be_inside_the_run(tmp_path: Path) -> None:
|
||||
run = tmp_path / "vladimirceva-lab7-failures-pki-x"
|
||||
inside = run / "operator" / "openbao" / "vladimirceva-lab7-failures"
|
||||
assert secrets_log.operator_dir_problem(inside, run) is None
|
||||
assert "outside the run" in str(
|
||||
secrets_log.operator_dir_problem(tmp_path / "operator", run)
|
||||
)
|
||||
assert "outside the run" in str(secrets_log.operator_dir_problem(run, run))
|
||||
working = tmp_path / "home-operator"
|
||||
nested = working / "openbao" / "x"
|
||||
assert "working operator" in str(
|
||||
secrets_log.operator_dir_problem(nested, working, working)
|
||||
)
|
||||
|
||||
|
||||
def test_hook_refuses_materials_outside_the_run(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
project = "vladimirceva-lab7-failures"
|
||||
run = tmp_path / f"{project}-pki-abc"
|
||||
inside = run / "operator" / "openbao" / project
|
||||
monkeypatch.setenv("FAULT_BAO_OPERATOR_DIR", str(inside))
|
||||
monkeypatch.setenv("FAULT_BAO_RUN_DIR", str(run))
|
||||
assert hook.bao_operator_dir(project) == (str(inside), str(run))
|
||||
for wrong_run in (tmp_path / "other", tmp_path / "vladimirceva-lab7-pki-x"):
|
||||
monkeypatch.setenv("FAULT_BAO_RUN_DIR", str(wrong_run))
|
||||
with pytest.raises(hook.HookError, match="run directory"):
|
||||
hook.bao_operator_dir(project)
|
||||
monkeypatch.setenv("FAULT_BAO_RUN_DIR", str(run))
|
||||
monkeypatch.setenv("FAULT_BAO_OPERATOR_DIR", str(tmp_path / "operator"))
|
||||
with pytest.raises(hook.HookError, match="outside the run"):
|
||||
hook.bao_operator_dir(project)
|
||||
monkeypatch.delenv("FAULT_BAO_OPERATOR_DIR")
|
||||
with pytest.raises(hook.HookError, match="make failure-checks"):
|
||||
hook.bao_operator_dir(project)
|
||||
|
||||
|
||||
def test_bench_clears_materials_only_inside_the_run(tmp_path: Path) -> None:
|
||||
base = tmp_path / "vlad-bench-pki-x"
|
||||
materials = base / "operator" / "openbao" / "vlad-bench"
|
||||
materials.mkdir(parents=True)
|
||||
(materials / "root-token").write_text("x", encoding="ascii")
|
||||
common.clear_bao_materials(materials, base)
|
||||
assert not materials.exists()
|
||||
common.clear_bao_materials(materials, base) # нет каталога — ничего
|
||||
outside = tmp_path / "operator"
|
||||
outside.mkdir()
|
||||
with pytest.raises(common.StandError, match="outside the run"):
|
||||
common.clear_bao_materials(outside, base)
|
||||
assert outside.exists()
|
||||
|
||||
|
||||
# --- bao-rewrite ------------------------------------------------------------------
|
||||
|
||||
|
||||
class _KvHttp:
|
||||
"""Подмена API OpenBao: распечатан, путь KV с версией 3."""
|
||||
|
||||
address = "https://localhost:1"
|
||||
|
||||
def __init__(self, data: dict | None) -> None:
|
||||
self.data = data
|
||||
self.written: list[dict] = []
|
||||
|
||||
def request(self, method, path, body=None, *, token=None, ok=(), timeout=None):
|
||||
if path == "sys/seal-status":
|
||||
return 200, {"initialized": True, "sealed": False}
|
||||
if path == "sys/health":
|
||||
return 200, {}
|
||||
if method == "GET" and path == "messenger/data/postgres/api":
|
||||
if self.data is None:
|
||||
return 404, {}
|
||||
return 200, {"data": {"data": self.data, "metadata": {"version": 3}}}
|
||||
if method == "POST" and path == "messenger/data/postgres/api":
|
||||
self.written.append(body)
|
||||
return 200, {"data": {"version": 4}}
|
||||
raise AssertionError(f"{method} {path}")
|
||||
|
||||
|
||||
def _operator(tmp_path: Path, monkeypatch, http: _KvHttp, secret_path: str | None):
|
||||
pki = tmp_path / "pki"
|
||||
pki.mkdir(exist_ok=True)
|
||||
for name in ("ca.crt", "bao-operator.crt", "bao-operator.key"):
|
||||
(pki / name).write_text("x", encoding="ascii")
|
||||
operator_dir = tmp_path / "operator"
|
||||
operator_dir.mkdir(exist_ok=True)
|
||||
(operator_dir / "root-token").write_text("root-value", encoding="ascii")
|
||||
monkeypatch.setattr(bao, "BaoHttp", lambda *_a, **_k: http)
|
||||
return argparse.Namespace(
|
||||
command="bao-rewrite",
|
||||
address="https://localhost:1",
|
||||
project="test",
|
||||
operator_dir=str(operator_dir),
|
||||
pki_dir=str(pki),
|
||||
inside=None,
|
||||
wait=0.0,
|
||||
path=secret_path,
|
||||
)
|
||||
|
||||
|
||||
def test_rewrite_writes_the_same_values_as_a_new_version(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys
|
||||
) -> None:
|
||||
http = _KvHttp({"password": "secret-value"})
|
||||
args = _operator(tmp_path, monkeypatch, http, "postgres/api")
|
||||
assert bao.run(args) == 0
|
||||
assert http.written == [{"data": {"password": "secret-value"}}]
|
||||
out = capsys.readouterr().out
|
||||
assert "kv messenger/postgres/api: version 3 -> 4, rewritten" in out
|
||||
assert "secret-value" not in out
|
||||
assert "root-value" not in out
|
||||
|
||||
|
||||
def test_rewrite_codes(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
for path in (None, "postgres/unknown", "../sys"):
|
||||
args = _operator(tmp_path, monkeypatch, _KvHttp({}), path)
|
||||
assert bao.run(args) == 2, path
|
||||
args = _operator(tmp_path, monkeypatch, _KvHttp(None), "postgres/api")
|
||||
assert bao.run(args) == 1
|
||||
|
||||
|
||||
def test_lab7_has_bao_rewrite_with_a_path() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
commands = parser.add_subparsers(dest="command")
|
||||
bao.add_commands(commands, host_port="8200", pki_dir=ROOT / ".pki" / "stand")
|
||||
args = parser.parse_args(["bao-rewrite", "s3/api"])
|
||||
assert args.path == "s3/api"
|
||||
assert "rewrite" in bao.COMMANDS
|
||||
|
||||
|
||||
# --- сроки ролей стенда отказов и сигналы ------------------------------------------
|
||||
|
||||
|
||||
def test_failure_stand_token_ttls_and_their_override() -> None:
|
||||
assert stand.bao_token_ttls({}) == (20, 60)
|
||||
env = {"FAULT_BAO_TOKEN_TTL": "10m", "FAULT_BAO_TOKEN_MAX_TTL": "1h"}
|
||||
assert stand.bao_token_ttls(env) == (600, 3600)
|
||||
for bad in ({"FAULT_BAO_TOKEN_TTL": "x"}, {"FAULT_BAO_TOKEN_MAX_TTL": "5s"}):
|
||||
with pytest.raises(ValueError, match="FAULT_BAO_TOKEN"):
|
||||
stand.bao_token_ttls(bad)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"rel", ["student-tests/stand.py", "bench/common.py"], ids=["stand", "bench"]
|
||||
)
|
||||
def test_sigterm_interrupts_like_ctrl_c(rel: str) -> None:
|
||||
"""SIGTERM (kill, остановка CI) — KeyboardInterrupt: та же уборка в finally."""
|
||||
code = (
|
||||
"import importlib.util, os, signal, sys, time\n"
|
||||
f"spec = importlib.util.spec_from_file_location('m', {str(ROOT / rel)!r})\n"
|
||||
"m = importlib.util.module_from_spec(spec); spec.loader.exec_module(m)\n"
|
||||
"m.interrupt_on_sigterm()\n"
|
||||
"try:\n"
|
||||
" os.kill(os.getpid(), signal.SIGTERM); time.sleep(5)\n"
|
||||
"except KeyboardInterrupt:\n"
|
||||
" print('interrupted')\n"
|
||||
)
|
||||
done = subprocess.run(
|
||||
[sys.executable, "-c", code],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=30,
|
||||
check=False,
|
||||
env={**os.environ, "PYTHONPATH": str(ROOT / Path(rel).parent)},
|
||||
)
|
||||
assert done.stdout.strip() == "interrupted", done.stderr
|
||||
@@ -0,0 +1,550 @@
|
||||
"""Лаба 7, перенос rotation-revocation: команды оператора без стенда.
|
||||
|
||||
Таблицы `infra/rotation/rotation.py` против файлов стенда (identities.conf,
|
||||
secrets compose, SEED и политики OpenBao, .env.example); порядок шагов команд
|
||||
на подставном стенде (`FakeStand`): leaf — выпуск → владелец → отзыв прежних →
|
||||
CRL проверяющим; отзыв — с удержанием; секрет — .env → хранилище и OpenBao →
|
||||
процессы → прежнее отвергнуто; предусловие — код 2 без изменений, сбой — код 1
|
||||
с фазой и командой, которая сводит; сигнал после начала — отложен. Чистые
|
||||
функции (.env, версии в журнале, брокер). `pki.sh` с OpenSSL ≥ 3 на временном CA:
|
||||
ротация без отзыва, отзыв прежних, удержание, отказ без базы CA. Мелкие правки
|
||||
соседей: 28P01 — недоступность, ROLLOUT_CHECK, --install-*, S3_KEEP_STALE_KEYS,
|
||||
`:8404` LB, цели make и правила Codex.
|
||||
"""
|
||||
|
||||
import importlib.util
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PKI = ROOT / "infra" / "pki" / "pki.sh"
|
||||
|
||||
|
||||
def _load(name: str, path: Path) -> ModuleType:
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
assert spec is not None
|
||||
assert spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules[name] = module
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
rotation = _load("unit_rotation", ROOT / "infra" / "rotation" / "rotation.py")
|
||||
bao = _load("unit_rotation_bao", ROOT / "infra" / "openbao" / "bao.py")
|
||||
|
||||
|
||||
def _text(rel: str) -> str:
|
||||
lines = (ROOT / rel).read_text(encoding="utf-8").splitlines()
|
||||
return "\n".join(line for line in lines if not line.lstrip().startswith("#")) + "\n"
|
||||
|
||||
|
||||
def _identities() -> dict[str, tuple[str, str]]:
|
||||
"""Имя строки identities.conf → (профиль, форма)."""
|
||||
out = {}
|
||||
for line in _text("infra/pki/identities.conf").splitlines():
|
||||
fields = line.split()
|
||||
if fields:
|
||||
out[fields[0]] = (fields[1], fields[3])
|
||||
return out
|
||||
|
||||
|
||||
def _service_secrets() -> dict[str, list[str]]:
|
||||
"""Сервис compose.yaml → его `secrets` (короткая запись списком)."""
|
||||
text = _text("compose.yaml")
|
||||
section = re.search(r"^services:\n((?:(?: .*)?\n)*)", text, re.M)
|
||||
assert section is not None
|
||||
out = {}
|
||||
for match in re.finditer(
|
||||
r"^ ([a-z0-9-]+):\n((?:(?: .*)?\n)*)", section.group(1), re.M
|
||||
):
|
||||
listed = re.search(r"^ secrets:\n((?: - .*\n)*)", match.group(2), re.M)
|
||||
out[match.group(1)] = re.findall(r"- (\S+)", listed.group(1)) if listed else []
|
||||
return out
|
||||
|
||||
|
||||
# --- таблицы против файлов стенда --------------------------------------------
|
||||
|
||||
|
||||
def test_leaves_are_the_identity_list() -> None:
|
||||
assert set(rotation.LEAVES) == set(_identities())
|
||||
|
||||
|
||||
def test_owner_holds_the_leaf_file() -> None:
|
||||
secrets = _service_secrets()
|
||||
for identity, leaf in rotation.LEAVES.items():
|
||||
if leaf.owner is None:
|
||||
continue
|
||||
files = secrets.get(leaf.owner, [])
|
||||
assert f"{identity}.crt" in files or f"{identity}.pem" in files, identity
|
||||
|
||||
|
||||
def test_every_crl_reader_is_a_checker() -> None:
|
||||
"""Сервис с crl.pem (кроме одноразового migrate) — чей-то проверяющий;
|
||||
проверяющий без crl.pem — только OpenBao (CRL ему грузит bao-configure)."""
|
||||
secrets = _service_secrets()
|
||||
readers = {s for s, files in secrets.items() if "crl.pem" in files} - {"migrate"}
|
||||
checkers = {c for leaf in rotation.LEAVES.values() for c in leaf.checkers}
|
||||
assert readers <= checkers, sorted(readers - checkers)
|
||||
assert {c for c in checkers if "crl.pem" not in secrets.get(c, [])} == {"openbao"}
|
||||
|
||||
|
||||
def test_secrets_are_the_seed_and_the_env_template() -> None:
|
||||
assert set(rotation.SECRETS) == set(bao.SEED)
|
||||
template = (ROOT / ".env.example").read_text(encoding="utf-8")
|
||||
for path, secret in rotation.SECRETS.items():
|
||||
assert set(secret.variables) == set(bao.SEED[path]), path
|
||||
for name in secret.variables.values():
|
||||
assert re.search(rf"^{name}=", template, re.M), name
|
||||
|
||||
|
||||
def test_broker_users_and_processes_are_roles() -> None:
|
||||
cns = {str(spec["cn"]) for spec in bao.ROLES.values()}
|
||||
assert set(rotation.BROKER_USERS) <= cns
|
||||
services = {spec["service"] for spec in bao.ROLES.values() if spec["service"]}
|
||||
assert set(rotation.PROCESSES) == services
|
||||
|
||||
|
||||
def test_revoke_only_by_rotation() -> None:
|
||||
for identity in ("haproxy", "api", "openbao", "ingress", "postgres", "grafana"):
|
||||
assert "make rotate-leaf" in (rotation.revoke_refusal(identity) or ""), identity
|
||||
for identity in ("relay", "worker", "api-client", "cleaner", "rabbitmq"):
|
||||
assert rotation.revoke_refusal(identity) is None, identity
|
||||
|
||||
|
||||
def test_recreated_steps_match_pki_sh() -> None:
|
||||
text = PKI.read_text(encoding="utf-8")
|
||||
assert "; ".join(rotation.RECREATED_STEPS) in text
|
||||
|
||||
|
||||
def test_broker_late_covers_its_login_timeouts() -> None:
|
||||
"""Сроки входа брокера — умолчания (5 с TLS + 10 с AMQP): конфигурация их не
|
||||
меняет, иначе BROKER_LATE_SECONDS меняется вместе с ними."""
|
||||
conf = _text("infra/rabbitmq/rabbitmq.conf") + _text(
|
||||
"infra/rabbitmq/advanced.config"
|
||||
)
|
||||
assert "handshake_timeout" not in conf
|
||||
assert rotation.BROKER_LATE_SECONDS >= 5 + 10
|
||||
|
||||
|
||||
# --- подставной стенд: порядок шагов ---------------------------------------
|
||||
|
||||
|
||||
class FakeStand(rotation.Stand):
|
||||
"""Стенд без docker: шаги — в журнал `calls`."""
|
||||
|
||||
def __init__(self, *, revoked: set[str] | None = None) -> None: # noqa: D107
|
||||
self.started = 0.0
|
||||
self.changed = False
|
||||
self.pending = None
|
||||
self.phase = "preconditions"
|
||||
self.repeat = ""
|
||||
self.converge = ""
|
||||
self.exposed = ""
|
||||
self.revoked = set(revoked or ())
|
||||
self.missing: set[str] = set()
|
||||
self.down: set[str] = set()
|
||||
self.lock_file = None
|
||||
self.pki_dir = Path("/nonexistent")
|
||||
self.env_file = Path("/nonexistent/.env")
|
||||
self.bao = bao
|
||||
self.openssl = "openssl"
|
||||
self.window = []
|
||||
self.calls: list[str] = []
|
||||
self.fail_at: str | None = None
|
||||
self.not_ready = False
|
||||
|
||||
def elapsed(self) -> float:
|
||||
return 0.0
|
||||
|
||||
def say(self, text: str) -> None:
|
||||
self.calls.append("say " + text)
|
||||
|
||||
def _step(self, name: str) -> None:
|
||||
self.calls.append(name)
|
||||
if self.fail_at and name.startswith(self.fail_at):
|
||||
raise rotation.Failed(f"{name} failed")
|
||||
|
||||
def read_status(self) -> None:
|
||||
self.calls.append("status")
|
||||
|
||||
def require(self, services, **kwargs) -> None:
|
||||
self.calls.append("require " + " ".join(sorted(services)))
|
||||
if self.not_ready:
|
||||
raise rotation.NotReady("a service is unhealthy")
|
||||
|
||||
def pki(self, *args: str) -> str:
|
||||
self._step("pki " + " ".join(args))
|
||||
return "revoked x: serial 01"
|
||||
|
||||
def serial(self, identity: str) -> str:
|
||||
return "0A"
|
||||
|
||||
def validity(self, identity: str) -> str:
|
||||
return "v"
|
||||
|
||||
def apply_owner(self, identity: str) -> None:
|
||||
self._step(f"owner {identity}")
|
||||
|
||||
def owner_current(self, identity: str) -> bool:
|
||||
return True
|
||||
|
||||
def apply_crl(self, services, identities) -> None:
|
||||
self._step("crl " + " ".join(sorted(services)) + " " + repr(identities))
|
||||
|
||||
def seed(self):
|
||||
self._step("seed")
|
||||
return {"postgres/api": 2, "s3/api": 2}
|
||||
|
||||
def require_consistent(self, path: str) -> None:
|
||||
self.calls.append("consistent")
|
||||
|
||||
def one_off(self, service: str) -> None:
|
||||
self._step(f"one-off {service}")
|
||||
|
||||
def s3_bootstrap_keep(self) -> None:
|
||||
self._step("s3 keep")
|
||||
|
||||
def recreate_valkey(self) -> None:
|
||||
self._step("valkey")
|
||||
|
||||
def database_time(self) -> str:
|
||||
return "t"
|
||||
|
||||
def close_sessions(self, role: str, before: str) -> None:
|
||||
self._step(f"sessions {role}")
|
||||
|
||||
def apply_secret(self, service: str, path: str, version: int) -> None:
|
||||
self._step(f"processes {service}")
|
||||
|
||||
def check_values(self, path, old, new) -> None:
|
||||
self._step("verify")
|
||||
|
||||
|
||||
def _steps(stand: FakeStand) -> list[str]:
|
||||
return [
|
||||
c
|
||||
for c in stand.calls
|
||||
if not c.startswith(("say ", "status", "require ", "consistent"))
|
||||
]
|
||||
|
||||
|
||||
def test_leaf_order_issue_owner_revoke_crl() -> None:
|
||||
stand = FakeStand()
|
||||
assert rotation.execute(stand, lambda: rotation.cmd_leaf(stand, "relay")) == 0
|
||||
steps = _steps(stand)
|
||||
assert steps[0] == "pki rotate relay"
|
||||
assert steps[1] == "owner relay"
|
||||
assert steps[2] == "pki revoke relay --superseded"
|
||||
assert steps[3].startswith("crl openbao otel-gateway rabbitmq ")
|
||||
# ротация: закрываются соединения и токены только прежнего leaf
|
||||
assert "{'relay': '0A'}" in steps[3]
|
||||
|
||||
|
||||
def test_revoke_holds_and_closes_everything() -> None:
|
||||
stand = FakeStand()
|
||||
assert rotation.execute(stand, lambda: rotation.cmd_revoke(stand, "worker")) == 0
|
||||
steps = _steps(stand)
|
||||
assert steps[0] == "pki revoke worker --hold"
|
||||
assert steps[1] == "crl openbao otel-gateway rabbitmq {'worker': None}"
|
||||
assert any("make rotate-secret SECRET=s3/worker" in c for c in stand.calls)
|
||||
|
||||
|
||||
def test_revoke_refused_before_any_change() -> None:
|
||||
stand = FakeStand()
|
||||
code = rotation.execute(stand, lambda: rotation.cmd_revoke(stand, "haproxy"))
|
||||
assert code == 2
|
||||
assert not _steps(stand)
|
||||
|
||||
|
||||
def test_precondition_is_exit_2_and_nothing_changed() -> None:
|
||||
stand = FakeStand()
|
||||
stand.not_ready = True
|
||||
assert rotation.execute(stand, lambda: rotation.cmd_leaf(stand, "relay")) == 2
|
||||
assert not stand.changed
|
||||
assert not _steps(stand)
|
||||
|
||||
|
||||
def test_failure_names_phase_and_repeat() -> None:
|
||||
stand = FakeStand()
|
||||
stand.fail_at = "owner"
|
||||
assert rotation.execute(stand, lambda: rotation.cmd_leaf(stand, "worker")) == 1
|
||||
last = stand.calls[-1]
|
||||
assert "FAILED in phase 'owner'" in last
|
||||
assert "make rotate-leaf IDENTITY=worker" in last
|
||||
# прежний leaf не отозван: владелец мог не перейти
|
||||
assert not any(c.startswith("pki revoke") for c in stand.calls)
|
||||
|
||||
|
||||
def test_revoked_owner_process_is_left_alone() -> None:
|
||||
stand = FakeStand(revoked={"worker"})
|
||||
assert rotation.execute(stand, lambda: rotation.cmd_revoke(stand, "rabbitmq")) == 0
|
||||
assert any("crl relay {'rabbitmq': None}" in c for c in stand.calls)
|
||||
|
||||
|
||||
def test_signal_after_the_first_change_is_deferred() -> None:
|
||||
stand = FakeStand()
|
||||
stand.begin_change("issue")
|
||||
stand.on_signal(signal.SIGINT, None)
|
||||
assert stand.pending == signal.SIGINT
|
||||
fresh = FakeStand()
|
||||
with pytest.raises(SystemExit) as exit_info:
|
||||
fresh.on_signal(signal.SIGTERM, None)
|
||||
assert exit_info.value.code == 130
|
||||
|
||||
|
||||
def _env_file(tmp_path: Path) -> Path:
|
||||
path = tmp_path / ".env"
|
||||
path.write_text(
|
||||
"POSTGRES_API_PASSWORD=0123456789abcdef0123456789abcdef\n"
|
||||
"S3_API_ACCESS_KEY=" + "a" * 64 + "\nS3_API_SECRET_KEY=" + "b" * 64 + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
path.chmod(0o600)
|
||||
return path
|
||||
|
||||
|
||||
def test_postgres_secret_order(tmp_path: Path) -> None:
|
||||
stand = FakeStand()
|
||||
stand.env_file = _env_file(tmp_path)
|
||||
code = rotation.execute(stand, lambda: rotation.cmd_secret(stand, "postgres/api"))
|
||||
assert code == 0
|
||||
assert _steps(stand) == [
|
||||
"seed",
|
||||
"one-off postgres-bootstrap",
|
||||
"processes api",
|
||||
"sessions api",
|
||||
"verify",
|
||||
]
|
||||
assert "0123456789abcdef" not in stand.env_file.read_text(encoding="utf-8")
|
||||
assert stand.env_file.stat().st_mode & 0o777 == 0o600
|
||||
|
||||
|
||||
def test_s3_secret_keeps_both_keys_until_processes_move(tmp_path: Path) -> None:
|
||||
stand = FakeStand()
|
||||
stand.env_file = _env_file(tmp_path)
|
||||
assert rotation.execute(stand, lambda: rotation.cmd_secret(stand, "s3/api")) == 0
|
||||
assert _steps(stand) == [
|
||||
"s3 keep",
|
||||
"seed",
|
||||
"processes api",
|
||||
"one-off s3-bootstrap",
|
||||
"verify",
|
||||
]
|
||||
|
||||
|
||||
def test_postgres_secret_failure_names_open_sessions(tmp_path: Path) -> None:
|
||||
stand = FakeStand()
|
||||
stand.env_file = _env_file(tmp_path)
|
||||
stand.fail_at = "processes"
|
||||
code = rotation.execute(stand, lambda: rotation.cmd_secret(stand, "postgres/api"))
|
||||
assert code == 1
|
||||
assert "may stay open" in stand.calls[-1]
|
||||
assert "make rotate-secret SECRET=postgres/api" in stand.calls[-1]
|
||||
|
||||
|
||||
# --- чистые функции ------------------------------------------------------------
|
||||
|
||||
|
||||
def test_env_replace_keeps_other_lines(tmp_path: Path) -> None:
|
||||
path = _env_file(tmp_path)
|
||||
old = rotation.env_value(path, "POSTGRES_API_PASSWORD")
|
||||
new = rotation.new_value(old)
|
||||
assert len(new) == len(old)
|
||||
assert re.fullmatch("[0-9a-f]+", new)
|
||||
assert new != old
|
||||
rotation.replace_env_values(path, {"POSTGRES_API_PASSWORD": new})
|
||||
text = path.read_text(encoding="utf-8")
|
||||
assert f"POSTGRES_API_PASSWORD={new}\n" in text
|
||||
assert "S3_API_ACCESS_KEY=" + "a" * 64 in text
|
||||
with pytest.raises(rotation.NotReady):
|
||||
rotation.env_value(path, "MISSING_VARIABLE")
|
||||
|
||||
|
||||
def test_loaded_versions_from_her_log_line() -> None:
|
||||
log = (
|
||||
"2026-12-02T05:00:00.000Z INFO src.secrets_store [rid=-] process secrets "
|
||||
"loaded process=api role=api address=https://openbao:8200 "
|
||||
"versions=postgres/api:1,valkey/api:1,s3/api:1 token_ttl=600s policies=api "
|
||||
"waited=0.1s\n"
|
||||
"2026-12-02T05:01:00.000Z INFO src.secrets_store [rid=-] process secrets "
|
||||
"loaded process=api role=api address=https://openbao:8200 "
|
||||
"versions=postgres/api:2,valkey/api:1,s3/api:3 token_ttl=600s policies=api "
|
||||
"waited=0.1s\n"
|
||||
)
|
||||
assert rotation.loaded_versions(log) == {
|
||||
"postgres/api": 2,
|
||||
"valkey/api": 1,
|
||||
"s3/api": 3,
|
||||
}
|
||||
|
||||
|
||||
def test_broker_connections_of_previous_leaf() -> None:
|
||||
listing = "<0.1.0>\trelay\told\n<0.2.0>\trelay\tnew\n<0.3.0>\tworker\told\n"
|
||||
assert rotation.old_connections(listing, "relay", "new") == ["<0.1.0>"]
|
||||
assert rotation.old_connections(listing, "relay", None) == ["<0.1.0>", "<0.2.0>"]
|
||||
|
||||
|
||||
def test_converging_hint() -> None:
|
||||
assert (
|
||||
rotation.converging(["postgres/api"])
|
||||
== "make rotate-secret SECRET=postgres/api"
|
||||
)
|
||||
assert rotation.converging(["s3/api", "postgres/worker"]).startswith("make up; ")
|
||||
|
||||
|
||||
def test_lb_payload_has_no_empty_lines() -> None:
|
||||
payload = rotation.Stand.lb_payload("cert", "/run/secrets/x.pem", "A\n\nB\n")
|
||||
assert "\n\n" not in payload.rstrip("\n")
|
||||
|
||||
|
||||
# --- pki.sh на временном CA -------------------------------------------------
|
||||
|
||||
|
||||
def _openssl() -> str | None:
|
||||
for candidate in (
|
||||
os.environ.get("OPENSSL") or "",
|
||||
"openssl",
|
||||
"/opt/homebrew/opt/openssl@3/bin/openssl",
|
||||
"/usr/local/opt/openssl@3/bin/openssl",
|
||||
):
|
||||
path = shutil.which(candidate) if candidate else None
|
||||
if path:
|
||||
out = subprocess.run([path, "version"], capture_output=True, text=True)
|
||||
if re.match(r"OpenSSL [3-9]", out.stdout):
|
||||
return path
|
||||
return None
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def pki(tmp_path: Path):
|
||||
binary = _openssl()
|
||||
if binary is None:
|
||||
pytest.skip("no OpenSSL 3+ (macOS: brew install openssl@3)")
|
||||
identities = tmp_path / "identities.conf"
|
||||
identities.write_text("worker client worker split\n", encoding="utf-8")
|
||||
env = {
|
||||
**os.environ,
|
||||
"OPENSSL": binary,
|
||||
"PKI_OPERATOR_DIR": str(tmp_path / "operator"),
|
||||
"PKI_STAND_DIR": str(tmp_path / "stand"),
|
||||
"PKI_IDENTITIES": str(identities),
|
||||
}
|
||||
|
||||
def run(*args: str) -> subprocess.CompletedProcess:
|
||||
return subprocess.run(
|
||||
["sh", str(PKI), *args], env=env, capture_output=True, text=True
|
||||
)
|
||||
|
||||
assert run("stand").returncode == 0
|
||||
run.dir = tmp_path # type: ignore[attr-defined]
|
||||
return run
|
||||
|
||||
|
||||
def test_rotate_keeps_the_previous_leaf_valid(pki) -> None:
|
||||
first = pki("status").stdout
|
||||
assert "older leaf" not in first
|
||||
out = pki("rotate", "worker")
|
||||
assert out.returncode == 0
|
||||
assert "not revoked yet" in out.stdout
|
||||
assert "older leaf worker: 1 still valid" in pki("status").stdout
|
||||
revoked = pki("revoke", "worker", "--superseded")
|
||||
assert revoked.returncode == 0
|
||||
assert revoked.stdout.count("revoked worker") == 1
|
||||
status = pki("status").stdout
|
||||
assert "older leaf" not in status
|
||||
assert "REVOKED" not in status
|
||||
again = pki("revoke", "worker", "--superseded")
|
||||
assert again.returncode == 0
|
||||
assert "nothing to revoke" in again.stdout
|
||||
|
||||
|
||||
def test_hold_blocks_stand_until_rotate(pki) -> None:
|
||||
out = pki("revoke", "worker", "--hold")
|
||||
assert out.returncode == 0
|
||||
assert "make revoke-identity" in out.stdout
|
||||
stand = pki("stand").stdout
|
||||
assert "held worker: revoked" in stand
|
||||
assert "reissue worker" not in stand
|
||||
assert (
|
||||
"REVOKED, held until make rotate-leaf IDENTITY=worker" in pki("status").stdout
|
||||
)
|
||||
assert pki("rotate", "worker").returncode == 0
|
||||
status = pki("status").stdout
|
||||
assert "held" not in status
|
||||
assert "REVOKED" not in status
|
||||
|
||||
|
||||
def test_hold_refuses_a_name_not_in_the_list(pki) -> None:
|
||||
out = pki("revoke", "stranger", "--hold")
|
||||
assert out.returncode == 1
|
||||
assert "not in" in out.stderr
|
||||
assert not (pki.dir / "operator" / "revoked" / "stranger").exists()
|
||||
|
||||
|
||||
def test_lost_ca_database_is_refused(pki) -> None:
|
||||
index = pki.dir / "operator" / "index.txt"
|
||||
shutil.copyfile(index, str(index) + ".old")
|
||||
index.unlink()
|
||||
for command in (("status",), ("crl",), ("stand",), ("revoke", "worker")):
|
||||
out = pki(*command)
|
||||
assert out.returncode == 1, command
|
||||
assert "index.txt is missing" in out.stderr, command
|
||||
assert "cp -n" in out.stderr, command
|
||||
assert not index.exists()
|
||||
|
||||
|
||||
# --- соседние правки ---------------------------------------------------------
|
||||
|
||||
|
||||
def test_role_password_refusal_is_unavailable() -> None:
|
||||
from sqlalchemy import exc as sa_exc
|
||||
|
||||
from src.db import is_unavailable
|
||||
|
||||
class Refused(Exception):
|
||||
sqlstate = "28P01"
|
||||
|
||||
error = sa_exc.DBAPIError("connect", None, Refused())
|
||||
assert is_unavailable(error)
|
||||
|
||||
|
||||
def test_neighbour_files() -> None:
|
||||
rollout = (ROOT / "scripts" / "rolling-update.sh").read_text(encoding="utf-8")
|
||||
assert 'check_only="${ROLLOUT_CHECK:-0}"' in rollout
|
||||
assert "com.docker.compose.image" in rollout
|
||||
start = (ROOT / "infra" / "rabbitmq" / "start.sh").read_text(encoding="utf-8")
|
||||
assert '"--install-crl"' in start
|
||||
assert '"--install-leaf"' in start
|
||||
boot = (ROOT / "infra" / "s3" / "bootstrap.sh").read_text(encoding="utf-8")
|
||||
assert 'if [ "$KEEP_STALE_KEYS" = 1 ]; then' in boot
|
||||
monitor = _text("infra/haproxy/haproxy.cfg").split("frontend monitor", 1)[1]
|
||||
monitor = monitor.split("\nfrontend ", 1)[0]
|
||||
assert "option httpclose" in monitor
|
||||
assert "timeout client-hs 5s" in monitor
|
||||
|
||||
|
||||
def test_make_targets_and_codex_rules() -> None:
|
||||
makefile = (ROOT / "Makefile").read_text(encoding="utf-8")
|
||||
rules = (ROOT / ".codex" / "rules" / "messenger.rules").read_text(encoding="utf-8")
|
||||
for target in (
|
||||
"rotate-leaf",
|
||||
"revoke-identity",
|
||||
"pki-renew",
|
||||
"rotate-secret",
|
||||
"rotation-check",
|
||||
):
|
||||
assert re.search(rf"^{target}:", makefile, re.M), target
|
||||
assert f'"{target}"' in rules, target
|
||||
assert re.search(r"^up: rotation-idle ", makefile, re.M)
|
||||
assert "@$(ROTATION) idle\n\tAPI_REPLICAS" in makefile
|
||||
@@ -0,0 +1,873 @@
|
||||
"""Лаба 7: `make scan` без Docker и сети (перенос vulnerability-scan).
|
||||
|
||||
Правила — `infra/AGENTS.md`, «Scan образов и зависимостей». Проверяется
|
||||
`infra/scan/scan.py` (импорт по пути):
|
||||
|
||||
- разбор JSON Trivy и pip-audit (урезанные фрагменты настоящих ответов; дубли
|
||||
pip-audit — одна находка), правило обязательных находок;
|
||||
- покрытие записью разбора (ID и алиасы, образы, пакеты, пути), истёкший срок —
|
||||
код 1, устаревшая запись — без влияния на код;
|
||||
- формат файла разбора: каждое нарушение — TriageError с ключом и полем (код 2),
|
||||
горизонты 90 / 30 суток; файл разбора репозитория проходит проверки;
|
||||
- сверка хэшей экспорта `uv.lock` с файлами версии на PyPI (без сети),
|
||||
pip-audit — каждая запись lock без маркеров, пропуск — код 2;
|
||||
- образы из модели compose: образ приложения, отказ незакреплённому образу,
|
||||
сторонние образы `compose.yaml` закреплены;
|
||||
- контейнеры сканера: scan без сети и сокета Docker, корень только на чтение,
|
||||
без capabilities, не root, с пределами; загрузка базы — без архивов;
|
||||
- пины инструментов: Trivy — тег и digest, pip-audit — точная версия.
|
||||
|
||||
Контроль: горизонт `accepted` 90 суток вместо 30 — `test_accepted_horizon`
|
||||
красный. Настоящий scan — `make scan` (Docker, сеть).
|
||||
"""
|
||||
|
||||
import datetime as dt
|
||||
import importlib.util
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import tomllib
|
||||
import urllib.error
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SCAN_PY = ROOT / "infra" / "scan" / "scan.py"
|
||||
TODAY = dt.date(2026, 12, 2)
|
||||
APP = "mtusi-messenger-vladimirceva"
|
||||
|
||||
|
||||
def _load() -> ModuleType:
|
||||
spec = importlib.util.spec_from_file_location("vladimirceva_scan", SCAN_PY)
|
||||
assert spec is not None
|
||||
assert spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules.setdefault("vladimirceva_scan", module)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
scan = _load()
|
||||
|
||||
TRIVY_DOC = {
|
||||
"Trivy": {"Version": "0.76.2"},
|
||||
"Metadata": {"OS": {"Family": "debian", "Name": "13.7"}},
|
||||
"Results": [
|
||||
{
|
||||
"Target": "/images/x.tar (debian 13.7)",
|
||||
"Class": "os-pkgs",
|
||||
"Type": "debian",
|
||||
"Vulnerabilities": [
|
||||
{
|
||||
"VulnerabilityID": "CVE-2026-1",
|
||||
"PkgName": "libssl3t64",
|
||||
"InstalledVersion": "3.5.1-1",
|
||||
"FixedVersion": "",
|
||||
"Status": "affected",
|
||||
"Severity": "HIGH",
|
||||
"VendorIDs": ["DSA-1-1"],
|
||||
"Title": "openssl: quic",
|
||||
},
|
||||
{
|
||||
"VulnerabilityID": "CVE-2026-1",
|
||||
"PkgName": "libssl3t64",
|
||||
"InstalledVersion": "3.5.1-1",
|
||||
"Status": "affected",
|
||||
"Severity": "HIGH",
|
||||
},
|
||||
{
|
||||
"VulnerabilityID": "CVE-2026-1",
|
||||
"PkgName": "openssl",
|
||||
"InstalledVersion": "3.5.1-1",
|
||||
"Status": "affected",
|
||||
"Severity": "HIGH",
|
||||
},
|
||||
{
|
||||
"VulnerabilityID": "CVE-2026-2",
|
||||
"PkgName": "ncurses-base",
|
||||
"InstalledVersion": "6.5",
|
||||
"Status": "affected",
|
||||
"Severity": "MEDIUM",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
"Target": "usr/local/bin/gosu",
|
||||
"Class": "lang-pkgs",
|
||||
"Type": "gobinary",
|
||||
"Vulnerabilities": [
|
||||
{
|
||||
"VulnerabilityID": "CVE-2025-68121",
|
||||
"PkgName": "stdlib",
|
||||
"InstalledVersion": "v1.24.6",
|
||||
"FixedVersion": "1.24.13",
|
||||
"Status": "fixed",
|
||||
"Severity": "CRITICAL",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
"Target": "Python",
|
||||
"Class": "lang-pkgs",
|
||||
"Type": "python-pkg",
|
||||
"Vulnerabilities": [
|
||||
{
|
||||
"VulnerabilityID": "GHSA-6q48-6c7w-9gw2",
|
||||
"PkgName": "certifi",
|
||||
"PkgPath": "opt/venv/lib/python3.13/site-packages/"
|
||||
"certifi-2026.7.22.dist-info/METADATA",
|
||||
"InstalledVersion": "2026.7.22",
|
||||
"FixedVersion": "2026.10.18",
|
||||
"Status": "fixed",
|
||||
"Severity": "CRITICAL",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
"Target": "/app/.env",
|
||||
"Class": "secret",
|
||||
"Secrets": [
|
||||
{
|
||||
"RuleID": "project-env-secret",
|
||||
"Severity": "CRITICAL",
|
||||
"Title": "Secret value assigned in an environment file",
|
||||
"StartLine": 2,
|
||||
"Match": "S3_SECRET_KEY=****",
|
||||
"Layer": {"CreatedBy": "COPY probe.env /app/.env"},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
PIP_AUDIT_DOC = {
|
||||
"dependencies": [
|
||||
{
|
||||
"name": "certifi",
|
||||
"version": "2026.7.22",
|
||||
"vulns": [
|
||||
{
|
||||
"id": "PYSEC-2026-4320",
|
||||
"fix_versions": ["2026.10.18"],
|
||||
"aliases": ["GHSA-6q48-6c7w-9gw2"],
|
||||
"description": "emSign root",
|
||||
},
|
||||
{
|
||||
"id": "GHSA-6q48-6c7w-9gw2",
|
||||
"fix_versions": ["2026.10.18"],
|
||||
"aliases": ["PYSEC-2026-4320"],
|
||||
"description": "emSign root",
|
||||
},
|
||||
],
|
||||
},
|
||||
{"name": "pydantic", "version": "2.13.1", "vulns": []},
|
||||
{
|
||||
"name": "dnspython",
|
||||
"version": "2.8.0",
|
||||
"vulns": [
|
||||
{
|
||||
"id": "CVE-2026-114605",
|
||||
"fix_versions": ["2.9.0"],
|
||||
"aliases": ["GHSA-45c3-73f7-pv4m"],
|
||||
"description": "### Impact\nCPU",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
"fixes": [],
|
||||
}
|
||||
|
||||
|
||||
def _entry(**overrides: object) -> dict:
|
||||
entry: dict = {
|
||||
"key": "openssl-quic",
|
||||
"ids": ["CVE-2026-1"],
|
||||
"targets": ["haproxy"],
|
||||
"verdict": "not_affected",
|
||||
"reason": "no QUIC listeners",
|
||||
"control": "make hardening-check: TCP listeners only",
|
||||
"review_by": TODAY + dt.timedelta(days=30),
|
||||
}
|
||||
entry.update(overrides)
|
||||
return {k: v for k, v in entry.items() if v is not None}
|
||||
|
||||
|
||||
TARGETS = {"haproxy", "postgres", APP, "uv.lock"}
|
||||
|
||||
|
||||
def _entries(*items: dict) -> list:
|
||||
return scan.parse_triage({"entry": list(items)}, TARGETS, TODAY)
|
||||
|
||||
|
||||
# --- разбор JSON ---------------------------------------------------------------
|
||||
|
||||
|
||||
def test_parse_trivy() -> None:
|
||||
os_name, findings = scan.parse_trivy(TRIVY_DOC, "postgres")
|
||||
assert os_name == "debian 13.7"
|
||||
vulns = [f for f in findings if f.kind == "vuln"]
|
||||
# дубль строки (тот же ID, пакет, версия, путь) — одна находка
|
||||
assert len(vulns) == 5
|
||||
gosu = next(f for f in vulns if f.package == "stdlib")
|
||||
assert gosu.path == "usr/local/bin/gosu"
|
||||
assert gosu.severity == "CRITICAL"
|
||||
assert gosu.fixed == "1.24.13"
|
||||
certifi = next(f for f in vulns if f.package == "certifi")
|
||||
assert certifi.path.endswith("METADATA")
|
||||
ssl = next(f for f in vulns if f.package == "libssl3t64")
|
||||
assert ssl.path == ""
|
||||
assert ssl.aliases == ("DSA-1-1",)
|
||||
(secret,) = [f for f in findings if f.kind == "secret"]
|
||||
assert secret.vuln_id == "project-env-secret"
|
||||
assert (secret.path, secret.line) == ("app/.env", 2)
|
||||
assert secret.layer == "COPY probe.env /app/.env"
|
||||
# значение совпадения в находку не попадает
|
||||
assert "****" not in repr(secret)
|
||||
|
||||
|
||||
def test_parse_pip_audit_merges_duplicates() -> None:
|
||||
packages, findings = scan.parse_pip_audit(PIP_AUDIT_DOC, "runtime")
|
||||
assert packages == 3
|
||||
assert len(findings) == 2
|
||||
certifi = next(f for f in findings if f.package == "certifi")
|
||||
assert certifi.ids == {"PYSEC-2026-4320", "GHSA-6q48-6c7w-9gw2"}
|
||||
assert (certifi.fixed, certifi.group) == ("2026.10.18", "runtime")
|
||||
assert certifi.target == "uv.lock"
|
||||
dns = next(f for f in findings if f.package == "dnspython")
|
||||
assert dns.title == "### Impact"
|
||||
|
||||
|
||||
def test_parse_pip_audit_skipped_dependency() -> None:
|
||||
doc = {
|
||||
"dependencies": [
|
||||
{"name": "pydantic", "version": "2.13.1", "vulns": []},
|
||||
{"name": "local-pkg", "skip_reason": "Dependency not found on PyPI"},
|
||||
],
|
||||
}
|
||||
with pytest.raises(scan.ScanError) as info:
|
||||
scan.parse_pip_audit(doc, "dev")
|
||||
assert info.value.step == "pip-audit dev"
|
||||
assert "local-pkg" in info.value.reason
|
||||
assert "Dependency not found on PyPI" in info.value.reason
|
||||
|
||||
|
||||
def test_mandatory_rule() -> None:
|
||||
_, findings = scan.parse_trivy(TRIVY_DOC, "postgres")
|
||||
by_pkg = {f.package or f.vuln_id: f for f in findings}
|
||||
assert by_pkg["libssl3t64"].mandatory
|
||||
assert by_pkg["stdlib"].mandatory
|
||||
assert not by_pkg["ncurses-base"].mandatory
|
||||
assert by_pkg["project-env-secret"].mandatory
|
||||
_, deps = scan.parse_pip_audit(PIP_AUDIT_DOC, "dev")
|
||||
assert all(f.mandatory for f in deps)
|
||||
|
||||
|
||||
# --- сверка хэшей uv.lock с PyPI -------------------------------------------------
|
||||
|
||||
H1, H2, H3 = "a" * 64, "b" * 64, "c" * 64
|
||||
|
||||
EXPORT = f"""\
|
||||
# This file was autogenerated by uv via the following command:
|
||||
# uv export --locked --no-emit-project --format requirements-txt
|
||||
annotated-types==0.7.0 \\
|
||||
--hash=sha256:{H1} \\
|
||||
--hash=sha256:{H2}
|
||||
# via pydantic
|
||||
Certifi==2026.10.18 ; sys_platform != 'emscripten' \\
|
||||
--hash=sha256:{H3}
|
||||
# via
|
||||
# httpcore
|
||||
uvicorn[standard]==0.40.0 \\
|
||||
--hash=sha256:{H1}
|
||||
"""
|
||||
|
||||
# урезанный ответ https://pypi.org/pypi/<имя>/<версия>/json
|
||||
PYPI_DOC = {
|
||||
"info": {"name": "annotated-types", "version": "0.7.0"},
|
||||
"urls": [
|
||||
{"filename": "a.whl", "digests": {"md5": "x", "sha256": H1}},
|
||||
{"filename": "a.tar.gz", "digests": {"sha256": H2}},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def test_parse_requirements() -> None:
|
||||
reqs = scan.parse_requirements(EXPORT)
|
||||
assert reqs == [
|
||||
("annotated-types", "0.7.0", frozenset({H1, H2})),
|
||||
("Certifi", "2026.10.18", frozenset({H3})),
|
||||
("uvicorn", "0.40.0", frozenset({H1})),
|
||||
]
|
||||
assert scan.published_digests(PYPI_DOC) == {H1, H2}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"line",
|
||||
["-e ./local", "./wheels/x.whl", "pkg @ https://x/pkg.whl"],
|
||||
)
|
||||
def test_requirement_without_version_rejected(line: str) -> None:
|
||||
with pytest.raises(scan.ScanError) as info:
|
||||
scan.parse_requirements(f"{line} \\\n --hash=sha256:{H1}\n")
|
||||
assert info.value.step == "hashes"
|
||||
|
||||
|
||||
def _fetcher(published: dict) -> tuple:
|
||||
calls: list = []
|
||||
|
||||
def fetch(name: str, version: str) -> frozenset:
|
||||
calls.append((name, version))
|
||||
return frozenset(published[(name, version)])
|
||||
|
||||
return fetch, calls
|
||||
|
||||
|
||||
def test_lock_hashes_match() -> None:
|
||||
fetch, calls = _fetcher(
|
||||
{
|
||||
("annotated-types", "0.7.0"): {H1, H2, H3},
|
||||
("certifi", "2026.10.18"): {H3},
|
||||
("uvicorn", "0.40.0"): {H1},
|
||||
},
|
||||
)
|
||||
reqs = scan.parse_requirements(EXPORT)
|
||||
# пакет обеих групп сверяется один раз
|
||||
assert scan.verify_lock_hashes([*reqs, reqs[1]], fetch) == (3, 3)
|
||||
assert sorted(calls) == [
|
||||
("annotated-types", "0.7.0"),
|
||||
("certifi", "2026.10.18"),
|
||||
("uvicorn", "0.40.0"),
|
||||
]
|
||||
|
||||
|
||||
ZERO = "0" * 64
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("lock", "published", "needle"),
|
||||
[
|
||||
# хэши lock обнулены — ни одного совпадения
|
||||
({ZERO}, {H1, H2}, "1 of 1 uv.lock hashes are not published"),
|
||||
# один хэш lock есть на PyPI, второго нет — тоже расхождение
|
||||
({H3, ZERO}, {H3}, "1 of 2 uv.lock hashes are not published"),
|
||||
# у версии нет файлов
|
||||
({H3}, set(), "1 of 1 uv.lock hashes are not published"),
|
||||
],
|
||||
)
|
||||
def test_lock_hash_mismatch(lock: set, published: set, needle: str) -> None:
|
||||
reqs = [("Certifi", "2026.10.18", frozenset(lock))]
|
||||
fetch, _ = _fetcher({("certifi", "2026.10.18"): published})
|
||||
with pytest.raises(scan.ScanError) as info:
|
||||
scan.verify_lock_hashes(reqs, fetch)
|
||||
assert info.value.step == "hashes"
|
||||
assert info.value.reason.startswith("Certifi 2026.10.18: ")
|
||||
assert needle in info.value.reason
|
||||
|
||||
|
||||
def test_lock_without_hashes() -> None:
|
||||
problems = scan.hash_problems(
|
||||
[("idna", "3.11", frozenset())],
|
||||
{("idna", "3.11"): frozenset({H1})},
|
||||
)
|
||||
assert problems == ["idna 3.11: no hashes in uv.lock"]
|
||||
|
||||
|
||||
def test_fetch_failures_are_one_line(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
def refused(*_a: object, **_k: object) -> None:
|
||||
raise urllib.error.URLError(ConnectionRefusedError(61, "refused"))
|
||||
|
||||
monkeypatch.setattr(scan.urllib.request, "urlopen", refused)
|
||||
with pytest.raises(scan.ScanError) as info:
|
||||
scan.fetch_digests("certifi", "2026.10.18")
|
||||
assert info.value.step == "hashes"
|
||||
assert info.value.reason.startswith("PyPI request for certifi 2026.10.18 failed:")
|
||||
assert "\n" not in info.value.reason
|
||||
|
||||
def missing(request: object, **_k: object) -> None:
|
||||
raise urllib.error.HTTPError("https://pypi.org/x", 404, "Not Found", None, None) # type: ignore[arg-type]
|
||||
|
||||
monkeypatch.setattr(scan.urllib.request, "urlopen", missing)
|
||||
with pytest.raises(scan.ScanError) as info:
|
||||
scan.fetch_digests("Certifi", "2026.10.18")
|
||||
assert info.value.reason == "Certifi 2026.10.18: release is not on PyPI"
|
||||
|
||||
|
||||
def test_first_fetch_error_does_not_wait_for_hanging_request() -> None:
|
||||
release = threading.Event()
|
||||
daemons: list[bool] = []
|
||||
|
||||
def fetch(name: str, version: str) -> frozenset:
|
||||
daemons.append(threading.current_thread().daemon)
|
||||
if name == "certifi":
|
||||
release.wait(5) # висящий запрос к PyPI
|
||||
return frozenset({H3})
|
||||
raise scan.ScanError("hashes", f"PyPI request for {name} failed")
|
||||
|
||||
reqs = scan.parse_requirements(EXPORT)
|
||||
started = time.monotonic()
|
||||
try:
|
||||
with pytest.raises(scan.ScanError):
|
||||
scan.verify_lock_hashes(reqs, fetch)
|
||||
assert time.monotonic() - started < 2
|
||||
# потоки-демоны не держат выход процесса после Ctrl+C или сбоя
|
||||
assert daemons
|
||||
assert all(daemons)
|
||||
finally:
|
||||
release.set()
|
||||
|
||||
|
||||
# --- pip-audit: каждая запись lock независимо от маркеров -------------------------
|
||||
|
||||
MARKED_EXPORT = (
|
||||
EXPORT
|
||||
+ f"""\
|
||||
colorama==0.4.6 ; sys_platform == 'win32' \\
|
||||
--hash=sha256:{H2}
|
||||
# via click
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def _audit_doc(*skip: str) -> dict:
|
||||
deps = [
|
||||
{"name": "annotated-types", "version": "0.7.0", "vulns": []},
|
||||
{"name": "certifi", "version": "2026.10.18", "vulns": []},
|
||||
{"name": "Uvicorn", "version": "0.40.0", "vulns": []},
|
||||
{"name": "colorama", "version": "0.4.6", "vulns": []},
|
||||
]
|
||||
return {"dependencies": [d for d in deps if d["name"] not in skip]}
|
||||
|
||||
|
||||
def test_audit_requirements_without_markers() -> None:
|
||||
reqs = scan.parse_requirements(MARKED_EXPORT)
|
||||
text = scan.audit_requirements(reqs)
|
||||
# маркер чужой платформы не доходит до pip-audit: хост его не вычислит
|
||||
assert ";" not in text
|
||||
assert "[" not in text
|
||||
assert f"colorama==0.4.6 \\\n --hash=sha256:{H2}" in text
|
||||
# те же записи и хэши, что в экспорте
|
||||
assert scan.parse_requirements(text) == reqs
|
||||
|
||||
|
||||
def test_dependency_missing_in_pip_audit_output() -> None:
|
||||
reqs = scan.parse_requirements(MARKED_EXPORT)
|
||||
# имя по PEP 503: регистр вывода pip-audit не важен
|
||||
scan.check_audited(reqs, _audit_doc(), "runtime")
|
||||
with pytest.raises(scan.ScanError) as info:
|
||||
scan.check_audited(reqs, _audit_doc("colorama"), "runtime")
|
||||
assert info.value.step == "pip-audit runtime"
|
||||
assert info.value.reason.startswith("colorama 0.4.6 from uv.lock")
|
||||
with pytest.raises(scan.ScanError) as info:
|
||||
scan.check_audited(reqs, _audit_doc("colorama", "certifi"), "dev")
|
||||
assert info.value.reason.endswith("(and 1 more)")
|
||||
|
||||
|
||||
def _fake_tools(monkeypatch: pytest.MonkeyPatch, doc: dict) -> list[str]:
|
||||
"""uv export и pip-audit без сети: экспорт — MARKED_EXPORT, вывод — doc."""
|
||||
audited: list[str] = []
|
||||
|
||||
def run(args: list[str], step: str, **_k: object) -> object:
|
||||
if args[0] == "uv":
|
||||
out = Path(args[args.index("-o") + 1])
|
||||
out.write_text(MARKED_EXPORT, encoding="utf-8")
|
||||
return subprocess.CompletedProcess(args, 0, "", "")
|
||||
audited.append(Path(args[args.index("-r") + 1]).read_text(encoding="utf-8"))
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps(doc), "")
|
||||
|
||||
monkeypatch.setattr(scan, "run", run)
|
||||
monkeypatch.setattr(scan, "verify_lock_hashes", lambda _reqs: (4, 4))
|
||||
return audited
|
||||
|
||||
|
||||
def test_scan_python_audits_every_lock_entry(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
audited = _fake_tools(monkeypatch, _audit_doc())
|
||||
groups, _ = scan.scan_python(tmp_path, tmp_path, None)
|
||||
assert [(g.group, g.packages) for g in groups] == [("runtime", 4), ("dev", 4)]
|
||||
assert len(audited) == 2
|
||||
assert all(";" not in text for text in audited)
|
||||
assert all("colorama==0.4.6" in text for text in audited)
|
||||
|
||||
|
||||
def test_scan_python_missing_dependency_is_code_2(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
# pip-audit вычислил маркер на хосте и пропустил запись без skip_reason
|
||||
_fake_tools(monkeypatch, _audit_doc("colorama"))
|
||||
with pytest.raises(scan.ScanError) as info:
|
||||
scan.scan_python(tmp_path, tmp_path, None)
|
||||
assert info.value.step == "pip-audit runtime"
|
||||
assert "colorama 0.4.6" in info.value.reason
|
||||
|
||||
|
||||
def test_groups() -> None:
|
||||
groups = dict(scan.GROUPS)
|
||||
# runtime — то, что ставит requirements.txt образа (`--no-dev`)
|
||||
assert groups["runtime"] == ("--no-dev",)
|
||||
# dev — окружение хоста: группа dev, extras и время выполнения
|
||||
assert "--all-extras" in groups["dev"]
|
||||
assert "--only-dev" not in groups["dev"]
|
||||
|
||||
|
||||
# --- покрытие ----------------------------------------------------------------
|
||||
|
||||
|
||||
def _finding(**kw: object):
|
||||
base = {
|
||||
"target": "haproxy",
|
||||
"kind": "vuln",
|
||||
"vuln_id": "CVE-2026-1",
|
||||
"package": "libssl3t64",
|
||||
"version": "3.5.1-1",
|
||||
"severity": "HIGH",
|
||||
}
|
||||
base.update(kw)
|
||||
return scan.Finding(**base)
|
||||
|
||||
|
||||
def test_coverage_alias_target_package_path() -> None:
|
||||
entries = _entries(
|
||||
_entry(ids=["DSA-1-1"]),
|
||||
_entry(
|
||||
key="gosu",
|
||||
ids=["CVE-2025-68121"],
|
||||
targets=["postgres"],
|
||||
packages=["stdlib"],
|
||||
paths=["usr/local/bin/*"],
|
||||
),
|
||||
)
|
||||
by_alias = _finding(aliases=("DSA-1-1",))
|
||||
other_image = _finding(target="postgres", aliases=("DSA-1-1",))
|
||||
gosu = _finding(
|
||||
target="postgres",
|
||||
vuln_id="CVE-2025-68121",
|
||||
package="stdlib",
|
||||
path="usr/local/bin/gosu",
|
||||
severity="CRITICAL",
|
||||
)
|
||||
other_path = _finding(
|
||||
target="postgres",
|
||||
vuln_id="CVE-2025-68121",
|
||||
package="stdlib",
|
||||
path="usr/lib/postgresql/bin/x",
|
||||
severity="CRITICAL",
|
||||
)
|
||||
other_pkg = _finding(
|
||||
target="postgres",
|
||||
vuln_id="CVE-2025-68121",
|
||||
package="golang.org/x/net",
|
||||
path="usr/local/bin/gosu",
|
||||
)
|
||||
cov = scan.apply_triage(
|
||||
[by_alias, other_image, gosu, other_path, other_pkg],
|
||||
entries,
|
||||
TODAY,
|
||||
{"haproxy", "postgres"},
|
||||
)
|
||||
assert cov.covered == {by_alias: "openssl-quic", gosu: "gosu"}
|
||||
# запись называет только haproxy: находка postgres с тем же ID непокрыта
|
||||
assert cov.uncovered == [other_image, other_path, other_pkg]
|
||||
assert scan.verdict_code(False, cov) == 1
|
||||
assert scan.verdict_code(True, cov) == 0
|
||||
|
||||
|
||||
def test_below_threshold_needs_no_triage() -> None:
|
||||
medium = _finding(severity="MEDIUM")
|
||||
cov = scan.apply_triage([medium], [], TODAY, {"haproxy"})
|
||||
assert cov.uncovered == []
|
||||
assert scan.verdict_code(False, cov) == 0
|
||||
|
||||
|
||||
def test_expired_entry_covers_nothing() -> None:
|
||||
entries = _entries(_entry(review_by=TODAY - dt.timedelta(days=1)))
|
||||
finding = _finding()
|
||||
cov = scan.apply_triage([finding], entries, TODAY, {"haproxy"})
|
||||
assert cov.uncovered == [finding]
|
||||
assert cov.expired_hits == {finding: "openssl-quic"}
|
||||
assert cov.states["openssl-quic"] == "EXPIRED"
|
||||
assert scan.verdict_code(False, cov) == 1
|
||||
# срок сегодня — ещё действует
|
||||
entries = _entries(_entry(review_by=TODAY))
|
||||
cov = scan.apply_triage([finding], entries, TODAY, {"haproxy"})
|
||||
assert cov.covered == {finding: "openssl-quic"}
|
||||
|
||||
|
||||
def test_stale_and_skipped_entries() -> None:
|
||||
entries = _entries(
|
||||
_entry(),
|
||||
_entry(key="lock", ids=["PYSEC-1"], targets=["uv.lock"]),
|
||||
)
|
||||
cov = scan.apply_triage([], entries, TODAY, {"haproxy"})
|
||||
assert cov.states == {"openssl-quic": "stale", "lock": "skipped"}
|
||||
assert scan.verdict_code(False, cov) == 0
|
||||
|
||||
|
||||
# --- формат файла разбора ---------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("overrides", "field"),
|
||||
[
|
||||
({"key": "Bad Key"}, "key"),
|
||||
({"ids": []}, "ids"),
|
||||
({"ids": None}, "ids"),
|
||||
({"ids": [""]}, "ids"),
|
||||
({"targets": None}, "targets"),
|
||||
({"targets": ["grafana/grafana"]}, "targets"),
|
||||
({"packages": "stdlib"}, "packages"),
|
||||
({"paths": [1]}, "paths"),
|
||||
({"verdict": "ignored"}, "verdict"),
|
||||
({"verdict": None}, "verdict"),
|
||||
({"reason": " "}, "reason"),
|
||||
({"reason": None}, "reason"),
|
||||
({"control": ""}, "control"),
|
||||
({"control": None}, "control"),
|
||||
({"reason": "todo: check later"}, "reason"),
|
||||
({"review_by": None}, "review_by"),
|
||||
({"review_by": "2027-01-01"}, "review_by"),
|
||||
({"review_by": dt.datetime(2027, 1, 1)}, "review_by"),
|
||||
({"review_by": TODAY + dt.timedelta(days=91)}, "review_by"),
|
||||
({"comment": "x"}, "comment"),
|
||||
],
|
||||
)
|
||||
def test_invalid_entry(overrides: dict, field: str) -> None:
|
||||
with pytest.raises(scan.TriageError) as info:
|
||||
_entries(_entry(**overrides))
|
||||
assert info.value.field == field
|
||||
assert "openssl-quic" in str(info.value) or field == "key"
|
||||
|
||||
|
||||
def test_duplicate_key() -> None:
|
||||
with pytest.raises(scan.TriageError) as info:
|
||||
_entries(_entry(), _entry())
|
||||
assert (info.value.key, info.value.field) == ("openssl-quic", "key")
|
||||
|
||||
|
||||
def test_review_horizon() -> None:
|
||||
(entry,) = _entries(_entry(review_by=TODAY + dt.timedelta(days=90)))
|
||||
assert entry.review_by == TODAY + dt.timedelta(days=90)
|
||||
|
||||
|
||||
def test_accepted_horizon() -> None:
|
||||
_entries(_entry(verdict="accepted", review_by=TODAY + dt.timedelta(days=30)))
|
||||
with pytest.raises(scan.TriageError) as info:
|
||||
_entries(_entry(verdict="accepted", review_by=TODAY + dt.timedelta(days=31)))
|
||||
assert info.value.field == "review_by"
|
||||
|
||||
|
||||
def test_unknown_top_level_key() -> None:
|
||||
with pytest.raises(scan.TriageError):
|
||||
scan.parse_triage({"entries": []}, TARGETS, TODAY)
|
||||
|
||||
|
||||
def test_triage_toml_errors_are_code_2(tmp_path: Path) -> None:
|
||||
broken = tmp_path / "triage.toml"
|
||||
broken.write_text("[[entry]\n", encoding="utf-8")
|
||||
with pytest.raises(scan.ScanError) as info:
|
||||
scan.load_triage(broken, TARGETS, TODAY)
|
||||
assert info.value.step == "triage"
|
||||
with pytest.raises(scan.ScanError):
|
||||
scan.load_triage(tmp_path / "missing.toml", TARGETS, TODAY)
|
||||
|
||||
|
||||
# --- образы compose ------------------------------------------------------------
|
||||
|
||||
PIN = "postgres:18.6-trixie@sha256:" + "a" * 64
|
||||
|
||||
|
||||
def test_images_from_model() -> None:
|
||||
model = {
|
||||
"services": {
|
||||
"api": {"build": {"context": "."}, "image": f"{APP}:x"},
|
||||
"worker": {"image": f"{APP}:x"},
|
||||
"postgres": {"image": PIN},
|
||||
"replica": {"image": PIN},
|
||||
},
|
||||
}
|
||||
third, app = scan.images_from_model(model)
|
||||
assert app == ["api", "worker"]
|
||||
assert third == {PIN: ["postgres", "replica"]}
|
||||
assert scan.target_name(PIN) == "postgres"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"image",
|
||||
[
|
||||
"postgres:latest",
|
||||
"postgres:18.6-trixie",
|
||||
"postgres:latest@sha256:" + "a" * 64,
|
||||
"postgres@sha256:" + "a" * 64,
|
||||
"",
|
||||
],
|
||||
)
|
||||
def test_unpinned_image_rejected(image: str) -> None:
|
||||
model = {
|
||||
"services": {
|
||||
"api": {"build": {}, "image": f"{APP}:x"},
|
||||
"db": {"image": image},
|
||||
},
|
||||
}
|
||||
with pytest.raises(scan.ScanError) as info:
|
||||
scan.images_from_model(model)
|
||||
assert info.value.step == "compose"
|
||||
assert "service db" in info.value.reason
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("ref", "name"),
|
||||
[
|
||||
("valkey/valkey:9.1.2-trixie@sha256:" + "b" * 64, "valkey/valkey"),
|
||||
("docker.io/library/postgres:18.6", "postgres"),
|
||||
("ghcr.io/org/tool:1.0", "org/tool"),
|
||||
(f"{APP}:scan", APP),
|
||||
],
|
||||
)
|
||||
def test_target_name(ref: str, name: str) -> None:
|
||||
assert scan.target_name(ref) == name
|
||||
|
||||
|
||||
def _compose_images() -> set[str]:
|
||||
"""Ссылки `image:` в `compose.yaml` с раскрытыми якорями (построчно)."""
|
||||
text = (ROOT / "compose.yaml").read_text(encoding="utf-8")
|
||||
anchors = dict(re.findall(r"^\S+: &([\w-]+) (\S+)$", text, re.M))
|
||||
refs = set()
|
||||
for ref in re.findall(r"^\s+image: (\S+)$", text, re.M):
|
||||
refs.add(anchors[ref[1:]] if ref.startswith("*") else ref)
|
||||
return refs
|
||||
|
||||
|
||||
def test_compose_images_pinned() -> None:
|
||||
refs = _compose_images()
|
||||
third = {r for r in refs if not r.startswith(f"{APP}:")}
|
||||
assert refs - third == {f"{APP}:lab7"}
|
||||
assert len(third) >= 11
|
||||
for ref in third:
|
||||
assert scan.PIN_RE.match(ref), ref
|
||||
assert scan.COMPOSE_FILE == ROOT / "compose.yaml"
|
||||
assert scan.target_name(scan.APP_SCAN_TAG) == scan.APP_TARGET == APP
|
||||
|
||||
|
||||
def test_repository_triage_is_valid() -> None:
|
||||
targets = {APP, "uv.lock", *map(scan.target_name, _compose_images())}
|
||||
data = tomllib.loads(scan.TRIAGE_FILE.read_text(encoding="utf-8"))
|
||||
# день scan — сегодня: срок записи не дальше горизонта от сегодняшнего дня
|
||||
entries = scan.parse_triage(data, targets, dt.date.today())
|
||||
assert len({e.key for e in entries}) == len(entries)
|
||||
|
||||
|
||||
# --- контейнеры сканера и пины ---------------------------------------------------
|
||||
|
||||
|
||||
def _mounts(args: list[str]) -> list[str]:
|
||||
return [args[i + 1] for i, a in enumerate(args) if a == "--mount"]
|
||||
|
||||
|
||||
def _opt(args: list[str], name: str) -> str:
|
||||
return args[args.index(name) + 1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("rules", [None, Path("/repo/infra/scan/s.yaml")])
|
||||
def test_scan_container_isolated(rules: Path | None) -> None:
|
||||
args = scan.scan_args(
|
||||
archive_dir=Path("/tmp/vladimirceva-scan-x/images"),
|
||||
archive="a.tar",
|
||||
cache_dir=Path("/cache"),
|
||||
uid=501,
|
||||
gid=20,
|
||||
name="vladimirceva-scan-r1-1",
|
||||
run_id="r1",
|
||||
secret_rules=rules,
|
||||
)
|
||||
image_at = args.index(scan.TRIVY_IMAGE)
|
||||
docker_args = args[:image_at]
|
||||
assert _opt(docker_args, "--network") == "none"
|
||||
assert "--read-only" in docker_args
|
||||
assert _opt(docker_args, "--cap-drop") == "ALL"
|
||||
assert _opt(docker_args, "--security-opt") == "no-new-privileges"
|
||||
assert _opt(docker_args, "--user") == "501:20"
|
||||
assert _opt(docker_args, "--memory") == _opt(docker_args, "--memory-swap")
|
||||
assert int(_opt(docker_args, "--pids-limit")) > 0
|
||||
assert _opt(docker_args, "--name").startswith("vladimirceva-scan-")
|
||||
assert _opt(docker_args, "--label") == f"{scan.LABEL}=r1"
|
||||
assert "--privileged" not in docker_args
|
||||
mounts = _mounts(docker_args)
|
||||
assert all(m.endswith(",readonly") for m in mounts)
|
||||
assert not any("docker.sock" in m for m in mounts)
|
||||
assert "-v" not in docker_args
|
||||
assert "--volume" not in docker_args
|
||||
assert len(mounts) == (3 if rules else 2)
|
||||
tail = args[image_at:]
|
||||
for flag in ("--skip-db-update", "--offline-scan", "--skip-java-db-update"):
|
||||
assert flag in tail
|
||||
assert ("--secret-config" in tail) == (rules is not None)
|
||||
assert _opt(tail, "--scanners") == ("vuln,secret" if rules else "vuln")
|
||||
|
||||
|
||||
def test_root_operator_refused() -> None:
|
||||
assert scan.scanner_user(501, 20) == "501:20"
|
||||
with pytest.raises(scan.ScanError) as info:
|
||||
scan.scanner_user(0, 0)
|
||||
assert info.value.step == "user"
|
||||
with pytest.raises(scan.ScanError):
|
||||
scan.db_args(Path("/cache"), 0, 0, "vladimirceva-scan-r1-db", "r1")
|
||||
with pytest.raises(scan.ScanError):
|
||||
scan.scan_args(
|
||||
archive_dir=Path("/tmp/x"),
|
||||
archive="a.tar",
|
||||
cache_dir=Path("/cache"),
|
||||
uid=0,
|
||||
gid=0,
|
||||
name="vladimirceva-scan-r1-1",
|
||||
run_id="r1",
|
||||
secret_rules=None,
|
||||
)
|
||||
|
||||
|
||||
def test_db_container_has_no_images() -> None:
|
||||
args = scan.db_args(Path("/cache"), 501, 20, "vladimirceva-scan-r1-db", "r1")
|
||||
docker_args = args[: args.index(scan.TRIVY_IMAGE)]
|
||||
(mount,) = _mounts(docker_args)
|
||||
assert "dst=/cache" in mount
|
||||
assert "images" not in mount
|
||||
assert "--read-only" in docker_args
|
||||
assert _opt(docker_args, "--cap-drop") == "ALL"
|
||||
assert "--network" not in docker_args # сеть нужна только загрузке базы
|
||||
assert "--download-db-only" in args
|
||||
|
||||
|
||||
def test_tool_pins() -> None:
|
||||
assert re.fullmatch(
|
||||
r"aquasec/trivy:\d+\.\d+\.\d+@sha256:[0-9a-f]{64}",
|
||||
scan.TRIVY_IMAGE,
|
||||
)
|
||||
project = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8"))
|
||||
pins = [d for d in project["dependency-groups"]["dev"] if "pip-audit" in d]
|
||||
assert pins == ["pip-audit==2.10.1"]
|
||||
lock = tomllib.loads((ROOT / "uv.lock").read_text(encoding="utf-8"))
|
||||
(pkg,) = [p for p in lock["package"] if p["name"] == "pip-audit"]
|
||||
assert pkg["version"] == "2.10.1"
|
||||
assert pkg["wheels"][0]["hash"]
|
||||
|
||||
|
||||
def test_out_and_cache_outside_repository() -> None:
|
||||
assert scan.inside(ROOT / "evidence" / "x", ROOT)
|
||||
assert not scan.inside(Path("/tmp/scan-out"), ROOT)
|
||||
assert not scan.inside(scan.DEFAULT_CACHE, ROOT)
|
||||
|
||||
|
||||
def test_scan_is_in_makefile_and_codex_rules() -> None:
|
||||
makefile = (ROOT / "Makefile").read_text(encoding="utf-8")
|
||||
assert re.search(
|
||||
r"^scan:\n\tuv run --frozen python infra/scan/scan.py", makefile, re.M
|
||||
)
|
||||
rules = (ROOT / ".codex" / "rules" / "messenger.rules").read_text(encoding="utf-8")
|
||||
assert '"scan"' in rules
|
||||
@@ -0,0 +1,701 @@
|
||||
"""Лаба 7: секреты процесса из OpenBao (перенос openbao-secrets).
|
||||
|
||||
Без стенда. Подставной OpenBao — HTTPS-сервер в потоке с временной PKI
|
||||
(`infra/pki/pki.sh stand`; без OpenSSL ≥ 3 — пропуск с причиной): обязательный
|
||||
сертификат клиента CA стенда, вход по DNS SAN, KV v2, продление, срок и предел роли,
|
||||
запечатанное состояние. Проверяются вход и чтение, отказы 400 / 403 / 404 / 503,
|
||||
TLS (сервер другого CA, имя вне SAN, отозванный сервер, только TLS 1.2 — отказ до
|
||||
запроса), ожидание и коды старта, продление и повторный вход, сверка версий, журнал
|
||||
без значений и токенов. Настоящий OpenBao — `make bao-check`, `make bao-outage`.
|
||||
"""
|
||||
|
||||
import contextlib
|
||||
import http.server
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import secrets
|
||||
import shutil
|
||||
import signal
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from collections.abc import Iterator
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from src.client_tls import (
|
||||
API_STORAGES,
|
||||
BOOTSTRAP_STORAGES,
|
||||
CLEANER_STORAGES,
|
||||
MIGRATION_STORAGES,
|
||||
RELAY_STORAGES,
|
||||
REPLAY_STORAGES,
|
||||
WORKER_STORAGES,
|
||||
client_tls_problems,
|
||||
)
|
||||
from src.config import ConfigError, SecretStore, Settings
|
||||
from src.secrets_renewal import SecretsRenewal
|
||||
from src.secrets_store import (
|
||||
EXIT_REFUSED,
|
||||
EXIT_UNAVAILABLE,
|
||||
ProcessSecrets,
|
||||
SecretsStartupError,
|
||||
load,
|
||||
load_or_exit,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PKI = ROOT / "infra" / "pki" / "pki.sh"
|
||||
BAO_FILES = ("BAO_CERT_FILE", "BAO_KEY_FILE", "BAO_CRL_FILE")
|
||||
|
||||
|
||||
def _pki(env: dict[str, str], *args: str) -> None:
|
||||
done = subprocess.run(
|
||||
["sh", str(PKI), *args], env=env, capture_output=True, text=True, check=False
|
||||
)
|
||||
# пропуск — только без OpenSSL 3+ (первый вызов); дальше — ошибка
|
||||
if done.returncode != 0 and args[0] == "stand":
|
||||
pytest.skip(f"infra/pki/pki.sh stand failed (OpenSSL 3+?): {done.stderr}")
|
||||
assert done.returncode == 0, done.stderr
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def pki(tmp_path_factory: pytest.TempPathFactory) -> Path:
|
||||
"""`stand` — файлы стенда с CRL, `revoked` — отозванная пара openbao (CRL её
|
||||
называет), `other` — файлы другого оператора."""
|
||||
base = tmp_path_factory.mktemp("bao-pki")
|
||||
env = {
|
||||
**os.environ,
|
||||
"PKI_OPERATOR_DIR": str(base / "operator"),
|
||||
"PKI_STAND_DIR": str(base / "stand"),
|
||||
}
|
||||
_pki(env, "stand")
|
||||
(base / "revoked").mkdir()
|
||||
for name in ("openbao.crt", "openbao.key"):
|
||||
shutil.copy(base / "stand" / name, base / "revoked" / name)
|
||||
_pki(env, "revoke", "openbao")
|
||||
# перевыпуск: у стенда действующая пара, прежняя — в CRL
|
||||
_pki(env, "stand")
|
||||
other = {
|
||||
**env,
|
||||
"PKI_OPERATOR_DIR": str(base / "other-operator"),
|
||||
"PKI_STAND_DIR": str(base / "other"),
|
||||
}
|
||||
_pki(other, "stand")
|
||||
return base
|
||||
|
||||
|
||||
@dataclass
|
||||
class Bao:
|
||||
"""Состояние подставного OpenBao; тест меняет его между запросами."""
|
||||
|
||||
port: int = 0
|
||||
ttl: float = 600
|
||||
max_ttl: float = 3600
|
||||
sealed: bool = False
|
||||
# статус входа вместо 200 (None — по сертификату)
|
||||
login_status: int | None = None
|
||||
kv: dict[str, tuple[dict[str, str], int]] = field(default_factory=dict)
|
||||
policies: dict[str, set[str]] = field(default_factory=dict)
|
||||
# токен → (роль, SAN, срок, предел)
|
||||
tokens: dict[str, list] = field(default_factory=dict)
|
||||
requests: list[tuple[str, str]] = field(default_factory=list)
|
||||
|
||||
|
||||
def _handler(bao: Bao) -> type[http.server.BaseHTTPRequestHandler]:
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def _san(self) -> str:
|
||||
names = dict(self.connection.getpeercert().get("subjectAltName", ()))
|
||||
return names.get("DNS", "")
|
||||
|
||||
def _answer(self, status: int, payload: dict | None = None) -> None:
|
||||
body = json.dumps(payload or {"errors": ["secret body"]}).encode()
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def _auth(self, token: str, role: str, ttl: float) -> None:
|
||||
auth = {
|
||||
"client_token": token,
|
||||
"lease_duration": int(ttl),
|
||||
"renewable": True,
|
||||
"token_policies": [role],
|
||||
}
|
||||
self._answer(200, {"auth": auth})
|
||||
|
||||
def _current(self) -> list | None:
|
||||
token = bao.tokens.get(self.headers.get("X-Vault-Token", ""))
|
||||
return token if token and time.monotonic() < token[2] else None
|
||||
|
||||
def do_POST(self) -> None: # noqa: N802 - имя задаёт http.server
|
||||
size = int(self.headers.get("Content-Length") or 0)
|
||||
body = json.loads(self.rfile.read(size) or b"{}")
|
||||
bao.requests.append(("POST", self.path))
|
||||
now = time.monotonic()
|
||||
if bao.sealed:
|
||||
self._answer(503)
|
||||
elif self.path == "/v1/auth/cert/login":
|
||||
role = body["name"]
|
||||
if bao.login_status is not None:
|
||||
self._answer(bao.login_status)
|
||||
elif self._san() != role:
|
||||
self._answer(400)
|
||||
else:
|
||||
token = "s." + secrets.token_hex(12)
|
||||
bao.tokens[token] = [
|
||||
role,
|
||||
self._san(),
|
||||
now + bao.ttl,
|
||||
now + bao.max_ttl,
|
||||
]
|
||||
self._auth(token, role, bao.ttl)
|
||||
elif self.path == "/v1/auth/token/renew-self":
|
||||
token = self._current()
|
||||
if token is None or token[1] != self._san():
|
||||
self._answer(403)
|
||||
else:
|
||||
token[2] = min(now + bao.ttl, token[3])
|
||||
self._auth(self.headers["X-Vault-Token"], token[0], token[2] - now)
|
||||
else:
|
||||
self._answer(404)
|
||||
|
||||
def do_GET(self) -> None: # noqa: N802 - имя задаёт http.server
|
||||
bao.requests.append(("GET", self.path))
|
||||
path = self.path.removeprefix("/v1/messenger/data/")
|
||||
token = self._current()
|
||||
if bao.sealed:
|
||||
self._answer(503)
|
||||
elif token is None or path not in bao.policies.get(token[0], set()):
|
||||
self._answer(403)
|
||||
elif path not in bao.kv:
|
||||
self._answer(404)
|
||||
else:
|
||||
data, version = bao.kv[path]
|
||||
self._answer(
|
||||
200, {"data": {"data": data, "metadata": {"version": version}}}
|
||||
)
|
||||
|
||||
def log_message(self, *_args: object) -> None:
|
||||
return None
|
||||
|
||||
return Handler
|
||||
|
||||
|
||||
SECRET_VALUES = {
|
||||
"postgres/api": {"password": "pg-" + secrets.token_hex(8)},
|
||||
"valkey/api": {"password": "vk-" + secrets.token_hex(8)},
|
||||
"s3/api": {
|
||||
"access_key_id": "id-" + secrets.token_hex(8),
|
||||
"secret_access_key": "sk-" + secrets.token_hex(8),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _openbao(
|
||||
pki: Path, *, pair: str = "stand", tls12: bool = False, port: int = 0
|
||||
) -> Iterator[Bao]:
|
||||
bao = Bao()
|
||||
bao.kv = {
|
||||
path: (dict(data), number)
|
||||
for number, (path, data) in enumerate(SECRET_VALUES.items(), start=1)
|
||||
}
|
||||
bao.policies = {"api": set(SECRET_VALUES)}
|
||||
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
context.load_cert_chain(pki / pair / "openbao.crt", pki / pair / "openbao.key")
|
||||
context.load_verify_locations(cafile=pki / "stand" / "ca.crt")
|
||||
context.verify_mode = ssl.CERT_REQUIRED
|
||||
if tls12:
|
||||
context.maximum_version = ssl.TLSVersion.TLSv1_2
|
||||
server = http.server.ThreadingHTTPServer(("127.0.0.1", port), _handler(bao))
|
||||
server.daemon_threads = True
|
||||
server.handle_error = lambda *_args: None # type: ignore[method-assign]
|
||||
server.socket = context.wrap_socket(server.socket, server_side=True)
|
||||
bao.port = server.server_address[1]
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
try:
|
||||
yield bao
|
||||
finally:
|
||||
server.shutdown()
|
||||
server.server_close()
|
||||
|
||||
|
||||
def _env(
|
||||
pki: Path, port: int, identity: str = "api-client", **extra: str
|
||||
) -> dict[str, str]:
|
||||
stand = pki / "stand"
|
||||
return {
|
||||
"CLIENT_TLS_CA_FILE": str(stand / "ca.crt"),
|
||||
"BAO_ADDR": f"https://localhost:{port}",
|
||||
"BAO_CERT_FILE": str(stand / f"{identity}.crt"),
|
||||
"BAO_KEY_FILE": str(stand / f"{identity}.key"),
|
||||
"BAO_CRL_FILE": str(stand / "crl.pem"),
|
||||
"BAO_CONNECT_TIMEOUT": "2",
|
||||
"BAO_STARTUP_TIMEOUT": "0",
|
||||
"BAO_RETRY_SECONDS": "0.1",
|
||||
**extra,
|
||||
}
|
||||
|
||||
|
||||
def _load(pki: Path, bao: Bao, **extra: str) -> ProcessSecrets:
|
||||
return load("api", Settings.from_env(_env(pki, bao.port, **extra)))
|
||||
|
||||
|
||||
def _refuse(pki: Path, bao: Bao, **extra: str) -> int:
|
||||
with pytest.raises(SecretsStartupError) as error:
|
||||
_load(pki, bao, **extra)
|
||||
return error.value.exit_code
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def journal(caplog: pytest.LogCaptureFixture) -> pytest.LogCaptureFixture:
|
||||
"""Журнал модулей секретов (их логгер `src` не пишет в корневой)."""
|
||||
logger = logging.getLogger("src")
|
||||
propagate, level = logger.propagate, logger.level
|
||||
logger.propagate = True
|
||||
logger.setLevel(logging.DEBUG)
|
||||
caplog.set_level(logging.DEBUG)
|
||||
yield caplog
|
||||
logger.propagate = propagate
|
||||
logger.setLevel(level)
|
||||
|
||||
|
||||
def _no_secrets(text: str, bao: Bao) -> None:
|
||||
values = [value for data in SECRET_VALUES.values() for value in data.values()]
|
||||
for value in (*values, *bao.tokens, "secret body"):
|
||||
assert value not in text
|
||||
|
||||
|
||||
# --- настройки и проверка точки входа ---------------------------------------------
|
||||
|
||||
|
||||
def test_settings_and_skeleton_names_not_read() -> None:
|
||||
store = Settings.from_env({}).secret_store
|
||||
assert store == SecretStore()
|
||||
assert store.address == "https://localhost:8200"
|
||||
assert (store.startup_timeout, store.retry) == (30.0, 2.0)
|
||||
# токен и CA имён skeleton не читаются: постоянного секрета входа нет
|
||||
other = Settings.from_env(
|
||||
{"BAO_TOKEN": "s.x", "BAO_CACERT": "/x", "VAULT_TOKEN": "y"}
|
||||
)
|
||||
assert other.secret_store == SecretStore()
|
||||
for value in ("http://openbao:8200", "openbao:8200", "https://openbao:8200/v1"):
|
||||
with pytest.raises(ConfigError, match="BAO_ADDR"):
|
||||
Settings.from_env({"BAO_ADDR": value})
|
||||
|
||||
|
||||
def test_every_process_checks_files(pki: Path, tmp_path: Path) -> None:
|
||||
for storages in (
|
||||
API_STORAGES,
|
||||
WORKER_STORAGES,
|
||||
CLEANER_STORAGES,
|
||||
RELAY_STORAGES,
|
||||
REPLAY_STORAGES,
|
||||
MIGRATION_STORAGES,
|
||||
):
|
||||
assert "secret_store" in storages
|
||||
problems = client_tls_problems(Settings.from_env({}), storages)
|
||||
assert problems[-3:] == list(BAO_FILES)
|
||||
# bootstrap ролей OpenBao не использует
|
||||
assert BOOTSTRAP_STORAGES == ("database",)
|
||||
good = _env(pki, 8200)
|
||||
assert client_tls_problems(Settings.from_env(good), MIGRATION_STORAGES) == []
|
||||
stand = pki / "stand"
|
||||
for variable, path in (
|
||||
("BAO_CERT_FILE", stand / "crl.pem"),
|
||||
("BAO_KEY_FILE", stand / "worker.key"),
|
||||
("BAO_KEY_FILE", tmp_path / "missing"),
|
||||
("BAO_CRL_FILE", stand / "ca.crt"),
|
||||
("BAO_ADDR", "https://127.0.0.1:8200"),
|
||||
):
|
||||
settings = Settings.from_env({**good, variable: str(path)})
|
||||
assert client_tls_problems(settings, MIGRATION_STORAGES) == [variable]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"command",
|
||||
[
|
||||
["-m", "src"],
|
||||
["-m", "src.worker"],
|
||||
["-m", "src.relay"],
|
||||
["-m", "src.relay", "replay"],
|
||||
["-m", "src.cleaner", "--once"],
|
||||
["-m", "alembic", "upgrade", "head"],
|
||||
],
|
||||
ids=["api", "worker", "relay", "replay", "cleaner", "migrate"],
|
||||
)
|
||||
def test_entry_points_without_crl_exit_2(
|
||||
pki: Path, command: list[str], tmp_path: Path
|
||||
) -> None:
|
||||
"""Процесс целиком: без CRL — код 2 и имя переменной, OpenBao не спрошен."""
|
||||
stand = pki / "stand"
|
||||
env = {
|
||||
"PATH": os.environ["PATH"],
|
||||
**_env(pki, 1, identity="relay"),
|
||||
"BAO_CRL_FILE": str(tmp_path / "no-such.pem"),
|
||||
"DB_HOST": "postgres",
|
||||
"CACHE_HOST": "valkey",
|
||||
"S3_ENDPOINT": "https://s3:8333",
|
||||
"BROKER_HOST": "rabbitmq",
|
||||
"BROKER_CERT_FILE": str(stand / "relay.crt"),
|
||||
"BROKER_KEY_FILE": str(stand / "relay.key"),
|
||||
"BROKER_CRL_FILE": str(stand / "crl.pem"),
|
||||
}
|
||||
done = subprocess.run(
|
||||
[sys.executable, *command],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
timeout=60,
|
||||
)
|
||||
assert done.returncode == 2, done.stderr
|
||||
assert "invalid client TLS settings: BAO_CRL_FILE" in done.stderr
|
||||
assert "no-such" not in done.stderr
|
||||
|
||||
|
||||
# --- вход и чтение ------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_load_gives_a_copy_of_settings(pki: Path, journal) -> None:
|
||||
with _openbao(pki) as bao:
|
||||
settings = Settings.from_env(_env(pki, bao.port))
|
||||
loaded = load("api", settings)
|
||||
assert (
|
||||
loaded.settings.database.password
|
||||
== SECRET_VALUES["postgres/api"]["password"]
|
||||
)
|
||||
assert loaded.settings.cache.password == SECRET_VALUES["valkey/api"]["password"]
|
||||
keys = SECRET_VALUES["s3/api"]
|
||||
assert loaded.settings.s3.access_key_id == keys["access_key_id"]
|
||||
assert loaded.settings.s3.secret_access_key == keys["secret_access_key"]
|
||||
assert loaded.versions == {"postgres/api": 1, "valkey/api": 2, "s3/api": 3}
|
||||
# исходные настройки и окружение прежние, остальные поля копии — те же
|
||||
assert settings.database.password == settings.s3.access_key_id == ""
|
||||
assert "DB_PASSWORD" not in os.environ
|
||||
assert loaded.settings.database.host == settings.database.host
|
||||
text = journal.text
|
||||
assert "process secrets loaded process=api role=api" in text
|
||||
assert "versions=postgres/api:1,valkey/api:2,s3/api:3 token_ttl=600s" in text
|
||||
_no_secrets(text + repr(loaded), bao)
|
||||
|
||||
|
||||
def test_environment_secret_is_ignored(pki: Path, journal) -> None:
|
||||
with _openbao(pki) as bao:
|
||||
loaded = _load(pki, bao, DB_PASSWORD="wrong-value", S3_ACCESS_KEY_ID="wrong-id")
|
||||
assert (
|
||||
loaded.settings.database.password
|
||||
== SECRET_VALUES["postgres/api"]["password"]
|
||||
)
|
||||
assert (
|
||||
"secret settings ignored process=api variables=DB_PASSWORD,S3_ACCESS_KEY_ID"
|
||||
in journal.text
|
||||
)
|
||||
assert "wrong-" not in journal.text
|
||||
_no_secrets(journal.text, bao)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status", [400, 401, 403])
|
||||
def test_login_refused_is_code_2_without_retries(
|
||||
pki: Path, journal, status: int
|
||||
) -> None:
|
||||
with _openbao(pki) as bao:
|
||||
bao.login_status = status
|
||||
code = _refuse(pki, bao, BAO_STARTUP_TIMEOUT="5")
|
||||
assert code == EXIT_REFUSED
|
||||
assert bao.requests == [("POST", "/v1/auth/cert/login")]
|
||||
assert f"reason=login status={status} path=auth/cert/login" in journal.text
|
||||
_no_secrets(journal.text, bao)
|
||||
|
||||
|
||||
def test_foreign_identity_is_refused(pki: Path, journal) -> None:
|
||||
with _openbao(pki) as bao:
|
||||
env = _env(pki, bao.port, identity="worker")
|
||||
with pytest.raises(SecretsStartupError) as error:
|
||||
load("api", Settings.from_env(env))
|
||||
assert error.value.exit_code == EXIT_REFUSED
|
||||
assert "reason=login status=400" in journal.text
|
||||
|
||||
|
||||
def test_denied_and_missing_path_and_field(pki: Path, journal) -> None:
|
||||
with _openbao(pki) as bao:
|
||||
bao.policies["api"] = {"postgres/api"}
|
||||
assert _refuse(pki, bao) == EXIT_REFUSED
|
||||
assert (
|
||||
"reason=permission status=403 path=messenger/data/valkey/api"
|
||||
in journal.text
|
||||
)
|
||||
bao.policies["api"] = set(SECRET_VALUES)
|
||||
data, version = bao.kv.pop("valkey/api")
|
||||
assert _refuse(pki, bao) == EXIT_REFUSED
|
||||
assert (
|
||||
"reason=missing status=404 path=messenger/data/valkey/api" in journal.text
|
||||
)
|
||||
bao.kv["valkey/api"] = ({"other": "x", **dict.fromkeys(data, "")}, version)
|
||||
assert _refuse(pki, bao) == EXIT_REFUSED
|
||||
assert (
|
||||
"secret field is missing process=api path=messenger/data/valkey/api "
|
||||
"field=password" in journal.text
|
||||
)
|
||||
_no_secrets(journal.text, bao)
|
||||
|
||||
|
||||
def test_server_error_and_bad_answer_are_unavailable(pki: Path, journal) -> None:
|
||||
with _openbao(pki) as bao:
|
||||
bao.login_status = 500
|
||||
assert _refuse(pki, bao) == EXIT_UNAVAILABLE
|
||||
assert "error=http_500" in journal.text
|
||||
# 200 без токена — не вход
|
||||
bao.login_status = 200
|
||||
assert _refuse(pki, bao) == EXIT_UNAVAILABLE
|
||||
assert "error=bad_response" in journal.text
|
||||
|
||||
|
||||
# --- TLS ----------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"case", ["other CA", "revoked server", "TLS 1.2", "name outside SAN", "no CRL"]
|
||||
)
|
||||
def test_bad_server_gets_no_request(pki: Path, case: str) -> None:
|
||||
pair = {"other CA": "other", "revoked server": "revoked"}.get(case, "stand")
|
||||
with _openbao(pki, pair=pair, tls12=case == "TLS 1.2") as bao:
|
||||
extra = {}
|
||||
if case == "name outside SAN":
|
||||
# IP отвергла бы проверка точки входа; здесь — сам клиент
|
||||
extra["BAO_ADDR"] = f"https://127.0.0.1:{bao.port}"
|
||||
if case == "no CRL":
|
||||
extra["BAO_CRL_FILE"] = ""
|
||||
assert _refuse(pki, bao, **extra) == EXIT_UNAVAILABLE
|
||||
assert bao.requests == []
|
||||
|
||||
|
||||
def test_client_without_certificate_of_stand_ca_is_rejected(pki: Path) -> None:
|
||||
with _openbao(pki) as bao:
|
||||
other = pki / "other"
|
||||
code = _refuse(
|
||||
pki,
|
||||
bao,
|
||||
BAO_CERT_FILE=str(other / "api-client.crt"),
|
||||
BAO_KEY_FILE=str(other / "api-client.key"),
|
||||
)
|
||||
assert code == EXIT_UNAVAILABLE
|
||||
assert bao.requests == []
|
||||
|
||||
|
||||
def test_proxy_of_environment_is_not_used(pki: Path, monkeypatch) -> None:
|
||||
monkeypatch.setenv("HTTPS_PROXY", "http://127.0.0.1:1")
|
||||
monkeypatch.setenv("https_proxy", "http://127.0.0.1:1")
|
||||
with _openbao(pki) as bao:
|
||||
assert _load(pki, bao).versions["postgres/api"] == 1
|
||||
|
||||
|
||||
# --- ожидание на старте --------------------------------------------------------
|
||||
|
||||
|
||||
def test_sealed_waits_then_code_1(pki: Path, journal) -> None:
|
||||
with _openbao(pki) as bao:
|
||||
bao.sealed = True
|
||||
started = time.monotonic()
|
||||
assert _refuse(pki, bao, BAO_STARTUP_TIMEOUT="0.6") == EXIT_UNAVAILABLE
|
||||
assert 0.4 <= time.monotonic() - started < 3
|
||||
assert len(bao.requests) >= 3
|
||||
# одна строка на ожидание и одна на отказ
|
||||
assert journal.text.count("waiting for secret store process=api") == 1
|
||||
assert journal.text.count("secret store is unavailable process=api") == 1
|
||||
assert "error=sealed" in journal.text
|
||||
|
||||
|
||||
def test_unsealed_while_waiting(pki: Path, journal) -> None:
|
||||
with _openbao(pki) as bao:
|
||||
bao.sealed = True
|
||||
threading.Timer(0.5, lambda: setattr(bao, "sealed", False)).start()
|
||||
loaded = _load(pki, bao, BAO_STARTUP_TIMEOUT="10")
|
||||
assert loaded.versions["postgres/api"] == 1
|
||||
assert "waiting for secret store" in journal.text
|
||||
|
||||
|
||||
def test_nobody_listens_is_code_1(pki: Path, capsys) -> None:
|
||||
with _openbao(pki) as bao:
|
||||
port = bao.port
|
||||
settings = Settings.from_env(_env(pki, port))
|
||||
with pytest.raises(SystemExit) as error:
|
||||
load_or_exit("api", settings)
|
||||
assert error.value.code == EXIT_UNAVAILABLE
|
||||
|
||||
|
||||
def test_sigterm_while_waiting_is_code_0(pki: Path) -> None:
|
||||
"""Процесс уборщика целиком: SIGTERM во время ожидания OpenBao — ранний
|
||||
обработчик, код 0 сразу."""
|
||||
with _openbao(pki) as bao:
|
||||
bao.sealed = True
|
||||
env = {
|
||||
"PATH": os.environ["PATH"],
|
||||
**_env(pki, bao.port, identity="cleaner", BAO_STARTUP_TIMEOUT="60"),
|
||||
"DB_HOST": "postgres",
|
||||
"S3_ENDPOINT": "https://s3:8333",
|
||||
}
|
||||
process = subprocess.Popen(
|
||||
[sys.executable, "-m", "src.cleaner"],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
text=True,
|
||||
)
|
||||
try:
|
||||
deadline = time.monotonic() + 30
|
||||
while not bao.requests and time.monotonic() < deadline:
|
||||
time.sleep(0.05)
|
||||
assert bao.requests, "the process did not reach OpenBao"
|
||||
time.sleep(0.3)
|
||||
stopped = time.monotonic()
|
||||
process.send_signal(signal.SIGTERM)
|
||||
out, _ = process.communicate(timeout=10)
|
||||
assert time.monotonic() - stopped < 3
|
||||
finally:
|
||||
process.kill()
|
||||
assert process.returncode == 0, out
|
||||
assert "waiting for secret store process=cleaner" in out
|
||||
assert "stopped before startup signal=SIGTERM" in out
|
||||
|
||||
|
||||
# --- продление -----------------------------------------------------------------
|
||||
|
||||
|
||||
def _logins(bao: Bao) -> int:
|
||||
return bao.requests.count(("POST", "/v1/auth/cert/login"))
|
||||
|
||||
|
||||
def test_renews_at_two_thirds(pki: Path, journal) -> None:
|
||||
with _openbao(pki) as bao:
|
||||
loaded = _load(pki, bao)
|
||||
renewal = SecretsRenewal(loaded)
|
||||
assert 390 < renewal._next_delay() <= 400
|
||||
delay = renewal.step()
|
||||
assert 390 < delay <= 400
|
||||
assert _logins(bao) == 1
|
||||
assert ("POST", "/v1/auth/token/renew-self") in bao.requests
|
||||
assert (
|
||||
"secret token renewed process=api token_ttl=600s capped=false"
|
||||
in journal.text
|
||||
)
|
||||
_no_secrets(journal.text, bao)
|
||||
|
||||
|
||||
def test_login_again_at_max_ttl(pki: Path, journal) -> None:
|
||||
with _openbao(pki) as bao:
|
||||
bao.ttl, bao.max_ttl = 10, 11
|
||||
renewal = SecretsRenewal(_load(pki, bao))
|
||||
# за 2 с от предела ответ короче запрошенного
|
||||
next(iter(bao.tokens.values()))[3] = time.monotonic() + 2
|
||||
renewal.step()
|
||||
assert _logins(bao) == 1
|
||||
assert "capped=true" in journal.text
|
||||
renewal.step()
|
||||
assert _logins(bao) == 2
|
||||
assert "again process=api role=api reason=max_ttl token_ttl=10s" in journal.text
|
||||
|
||||
|
||||
def test_login_again_after_expiry_and_revocation(pki: Path, journal) -> None:
|
||||
with _openbao(pki) as bao:
|
||||
bao.ttl = 1
|
||||
renewal = SecretsRenewal(_load(pki, bao))
|
||||
time.sleep(1.1)
|
||||
renewal.step()
|
||||
assert "reason=expired" in journal.text
|
||||
bao.tokens.clear()
|
||||
renewal.step()
|
||||
assert "reason=renew_refused" in journal.text
|
||||
assert _logins(bao) == 3
|
||||
|
||||
|
||||
def test_outage_is_one_line_and_return_is_one_line(pki: Path, journal) -> None:
|
||||
with _openbao(pki) as bao:
|
||||
renewal = SecretsRenewal(_load(pki, bao))
|
||||
bao.sealed = True
|
||||
assert [renewal.step(), renewal.step(), renewal.step()] == [0.1, 0.1, 0.1]
|
||||
assert journal.text.count("secret store is unavailable process=api") == 1
|
||||
bao.sealed = False
|
||||
assert renewal.step() > 300
|
||||
renewal.step()
|
||||
assert journal.text.count("secret store is available again") == 1
|
||||
|
||||
|
||||
def test_refused_login_is_an_error_and_the_process_lives(pki: Path, journal) -> None:
|
||||
with _openbao(pki) as bao:
|
||||
renewal = SecretsRenewal(_load(pki, bao))
|
||||
bao.tokens.clear()
|
||||
bao.login_status = 400
|
||||
assert renewal.step() == 0.1
|
||||
assert "ERROR" in journal.text
|
||||
assert (
|
||||
"refused access process=api role=api reason=login status=400"
|
||||
in journal.text
|
||||
)
|
||||
bao.login_status = None
|
||||
assert renewal.step() > 300
|
||||
|
||||
|
||||
def test_new_version_is_a_warning_once(pki: Path, journal) -> None:
|
||||
with _openbao(pki) as bao:
|
||||
loaded = _load(pki, bao)
|
||||
renewal = SecretsRenewal(loaded)
|
||||
bao.kv["valkey/api"] = ({"password": "new"}, 5)
|
||||
renewal.step()
|
||||
renewal.step()
|
||||
line = (
|
||||
"secret version changed process=api path=messenger/data/valkey/api "
|
||||
"loaded=2 current=5"
|
||||
)
|
||||
assert journal.text.count(line) == 1
|
||||
assert loaded.settings.cache.password == SECRET_VALUES["valkey/api"]["password"]
|
||||
|
||||
|
||||
def test_thread_renews_and_stops_without_network(pki: Path) -> None:
|
||||
with _openbao(pki) as bao:
|
||||
bao.ttl, bao.max_ttl = 1, 3
|
||||
renewal = SecretsRenewal(_load(pki, bao))
|
||||
renewal.start()
|
||||
deadline = time.monotonic() + 15
|
||||
while _logins(bao) < 3 and time.monotonic() < deadline:
|
||||
time.sleep(0.05)
|
||||
started = time.monotonic()
|
||||
renewal.stop()
|
||||
assert time.monotonic() - started < 0.2
|
||||
assert _logins(bao) >= 3
|
||||
time.sleep(0.5)
|
||||
quiet = len(bao.requests)
|
||||
time.sleep(1.5)
|
||||
assert len(bao.requests) == quiet
|
||||
|
||||
|
||||
def test_thread_survives_unexpected_error(pki: Path, journal, monkeypatch) -> None:
|
||||
with _openbao(pki) as bao:
|
||||
bao.ttl = 1
|
||||
renewal = SecretsRenewal(_load(pki, bao))
|
||||
calls = []
|
||||
|
||||
def step() -> float:
|
||||
calls.append(1)
|
||||
raise RuntimeError("unexpected")
|
||||
|
||||
monkeypatch.setattr(renewal, "step", step)
|
||||
renewal.start()
|
||||
deadline = time.monotonic() + 10
|
||||
while len(calls) < 3 and time.monotonic() < deadline:
|
||||
time.sleep(0.05)
|
||||
renewal.stop()
|
||||
assert len(calls) >= 3
|
||||
assert "secret renewal failed process=api error=RuntimeError" in journal.text
|
||||
@@ -0,0 +1,193 @@
|
||||
"""Лаба 7, перенос 15: аудит матрицы доверия `make security-audit` без стенда
|
||||
(`infra/audit/audit.py`).
|
||||
|
||||
- Каждая строка таблицы `contracts/trust-matrix.md` — строка сводки, лишних
|
||||
нет; у каждой строки есть проверки, проверки известны.
|
||||
- Подкоманды `scripts/lab7.py`, которые зовёт аудит, есть в его argparse.
|
||||
- «Отказ» и «нет данных» различаются: код 1 — только нарушение, код 2 — проверка
|
||||
без вердикта (сбой, стенда нет, проба приватности без записей журнала).
|
||||
- Строка утечек берёт из вывода `telemetry-check` только пробу приватности.
|
||||
- Цель make и правило Codex.
|
||||
|
||||
Контроли: строка матрицы без строки аудита (или лишняя строка аудита) —
|
||||
`test_missing_or_extra_row_is_named` называет её; ноль записей журнала,
|
||||
посчитанный утечкой или PASS, — `test_no_log_records_is_no_data`.
|
||||
"""
|
||||
|
||||
import importlib.util
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
AUDIT_PY = ROOT / "infra" / "audit" / "audit.py"
|
||||
LAB7_PY = ROOT / "scripts" / "lab7.py"
|
||||
|
||||
|
||||
def _load() -> ModuleType:
|
||||
spec = importlib.util.spec_from_file_location("vladimirceva_audit", AUDIT_PY)
|
||||
assert spec is not None
|
||||
assert spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules["vladimirceva_audit"] = module
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
audit = _load()
|
||||
|
||||
|
||||
def test_matrix_rows_match_audit() -> None:
|
||||
matrix = audit.matrix_edges()
|
||||
assert len(matrix) == 12
|
||||
assert audit.coverage_problems(matrix) == []
|
||||
assert [edge.name for edge in audit.MATRIX_EDGES] == matrix
|
||||
|
||||
|
||||
def test_missing_or_extra_row_is_named() -> None:
|
||||
matrix = audit.matrix_edges()
|
||||
assert audit.coverage_problems([*matrix, "Новая связь → X"]) == [
|
||||
"matrix row without audit row: Новая связь → X",
|
||||
]
|
||||
assert audit.coverage_problems(matrix[1:]) == [
|
||||
f"audit row not in matrix: {matrix[0]}",
|
||||
]
|
||||
broken = (
|
||||
audit.Edge("Клиент → ingress/LB", (("x", "no-such-check"),)),
|
||||
*audit.MATRIX_EDGES[1:],
|
||||
)
|
||||
assert audit.coverage_problems(matrix, broken) == [
|
||||
"unknown check no-such-check in row Клиент → ingress/LB",
|
||||
]
|
||||
empty = (audit.Edge("Клиент → ingress/LB", ()), *audit.MATRIX_EDGES[1:])
|
||||
assert audit.coverage_problems(matrix, empty) == [
|
||||
"row without checks: Клиент → ingress/LB",
|
||||
]
|
||||
|
||||
|
||||
def test_matrix_parser(tmp_path: Path) -> None:
|
||||
path = tmp_path / "m.md"
|
||||
path.write_text(
|
||||
"# M\n\n| Связь | A |\n| --- | --- |\n| X → Y | a |\n| Z | b |\n\n"
|
||||
"| Связь | other |\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
assert audit.matrix_edges(path) == ["X → Y", "Z"]
|
||||
|
||||
|
||||
def test_lab7_commands_exist() -> None:
|
||||
"""Каждая проверка аудита — подкоманда scripts/lab7.py; каждая проверка
|
||||
списка доказывает хотя бы одну строку."""
|
||||
text = LAB7_PY.read_text(encoding="utf-8")
|
||||
parsers = set(re.findall(r'add_parser\("([a-z0-9-]+)"', text))
|
||||
parsers |= {"mtls-check"} # заводится циклом уровня 4 с --base-url
|
||||
assert re.search(
|
||||
r'"trace-chain", "alerts-check", "telemetry-outage", "mtls-check"', text
|
||||
)
|
||||
commands = {command for command, _ in audit.LAB7_CHECKS.values()}
|
||||
assert commands <= parsers
|
||||
assert set(audit.LAB7_CHECKS) <= audit.CHECKS
|
||||
used = {check for edge in audit.EDGES for _, check in edge.checks}
|
||||
assert used == audit.CHECKS
|
||||
assert audit.LEAK_ROW in text
|
||||
|
||||
|
||||
PRIVACY = "no password, token, message text, filename or Authorization in telemetry"
|
||||
TELEMETRY_OUT = """\
|
||||
PASS provisioning
|
||||
FAIL resource attributes: service.version 0.6.0
|
||||
{row}
|
||||
telemetry-check: FAIL (n/m checks)
|
||||
"""
|
||||
|
||||
|
||||
def _out(row: str) -> str:
|
||||
return TELEMETRY_OUT.format(row=row)
|
||||
|
||||
|
||||
def test_leaks_only_privacy_row() -> None:
|
||||
clean = _out(f"PASS {PRIVACY}: 41 log records, 5123 bytes of traces")
|
||||
result = audit.leaks_result(1, clean, 1.0)
|
||||
assert result.code == 0
|
||||
assert "resource attributes" in result.note
|
||||
leaked = _out(
|
||||
f"FAIL {PRIVACY}: 41 log records, 5123 bytes of traces, leaked: token in logs"
|
||||
)
|
||||
result = audit.leaks_result(1, leaked, 1.0)
|
||||
assert result.code == 1
|
||||
assert result.fails == (leaked.splitlines()[2],)
|
||||
authorization = _out(
|
||||
f"FAIL {PRIVACY}: 41 log records, 9 bytes of traces, Authorization in traces"
|
||||
)
|
||||
assert audit.leaks_result(1, authorization, 1.0).code == 1
|
||||
|
||||
|
||||
def test_no_log_records_is_no_data() -> None:
|
||||
"""Пустой Loki — не утечка (1) и не PASS (0): нет данных (2)."""
|
||||
empty = _out(f"FAIL {PRIVACY}: 0 log records, 2 bytes of traces")
|
||||
result = audit.leaks_result(1, empty, 1.0)
|
||||
assert result.code == 2
|
||||
assert "no log records" in result.note
|
||||
# команда не дошла до пробы или упала без вердикта
|
||||
assert audit.leaks_result(1, "FAIL provisioning\n", 1.0).code == 2
|
||||
assert audit.leaks_result(2, "", 1.0).code == 2
|
||||
assert audit.leaks_result(137, _out(f"PASS {PRIVACY}: 4 log"), 1.0).code == 2
|
||||
|
||||
|
||||
def test_refusal_and_no_data_are_different_codes() -> None:
|
||||
"""Код 1 проверки — FAIL строки, любой другой ненулевой — ERROR (нет
|
||||
вердикта), аудит в целом: 1 важнее 2."""
|
||||
fail = audit.check_result("mtls-check", 1, "FAIL identity haproxy\n", 1.0)
|
||||
assert (fail.code, fail.fails) == (1, ("FAIL identity haproxy",))
|
||||
assert audit.check_result("bao-check", 2, "OpenBao is sealed\n", 1.0).code == 2
|
||||
assert audit.check_result("s3-check", 137, "", 1.0).code == 2
|
||||
assert audit.check_result("test-security", 1, "FAIL: unexpected\n", 1.0).code == 1
|
||||
assert audit.check_result("test-security", 1, "Traceback\n", 1.0).code == 2
|
||||
ok, bad, err = audit.Result(0, 1.0), audit.Result(1, 1.0), audit.Result(2, 1.0)
|
||||
assert audit.audit_code({"a": ok, "b": ok}) == 0
|
||||
assert audit.audit_code({"a": ok, "b": err}) == 2
|
||||
assert audit.audit_code({"a": err, "b": bad}) == 1
|
||||
assert audit.verdict(2) == "ERROR"
|
||||
|
||||
|
||||
def test_fail_lines_both_formats() -> None:
|
||||
"""Строки нарушения в обоих форматах scripts/lab7.py: `FAIL …` (Checks) и
|
||||
строка таблицы, кончающаяся на FAIL; итоговая строка — не нарушение."""
|
||||
out = (
|
||||
"PASS ok row\n"
|
||||
"FAIL bad row: detail\n"
|
||||
"host localhost anonymous get object 403 200 FAIL\n"
|
||||
"host localhost anonymous put object 403 403 ok\n"
|
||||
"mtls-check: FAIL (1/3 checks, 2 s)\n"
|
||||
)
|
||||
assert audit.fail_lines(out) == (
|
||||
"FAIL bad row: detail",
|
||||
"host localhost anonymous get object 403 200 FAIL",
|
||||
)
|
||||
|
||||
|
||||
def test_row_verdict() -> None:
|
||||
edge = audit.Edge("e", (("a", "mtls-check"), ("b", "s3-check")))
|
||||
ok = audit.Result(0, 1.0)
|
||||
assert audit.row_verdict(edge, {}) == "not run"
|
||||
assert audit.row_verdict(edge, {"mtls-check": ok}) == "PASS (partial)"
|
||||
assert audit.row_verdict(edge, {"mtls-check": ok, "s3-check": ok}) == "PASS"
|
||||
bad = audit.Result(1, 1.0)
|
||||
err = audit.Result(2, 1.0)
|
||||
assert audit.row_verdict(edge, {"mtls-check": err, "s3-check": bad}) == "FAIL"
|
||||
assert audit.row_verdict(edge, {"mtls-check": err, "s3-check": ok}) == "ERROR"
|
||||
|
||||
|
||||
def test_make_target_and_codex_rule() -> None:
|
||||
makefile = (ROOT / "Makefile").read_text(encoding="utf-8")
|
||||
rules = (ROOT / ".codex" / "rules" / "messenger.rules").read_text(encoding="utf-8")
|
||||
assert re.search(
|
||||
r"^security-audit:\n\t\$\(PYTHON\) infra/audit/audit.py ", makefile, re.M
|
||||
)
|
||||
assert '"security-audit"' in rules
|
||||
assert '"make security-audit"' in rules
|
||||
@@ -0,0 +1,192 @@
|
||||
"""Лаба 7, трек 1: уборщик не верит слову worker «готово».
|
||||
|
||||
`CleanupService.clean_staging` убирает исходник готового вложения только
|
||||
после своей сверки оригинала в конечном ключе (размер и SHA-256 строки). Нет
|
||||
объекта, другой размер или другие байты — исходник остаётся, строка ошибки в
|
||||
журнале, остальные строки прохода убираются. У `failed` сверки нет (результата
|
||||
нет): срок хранения. Хранилище и объекты — подставные, транзакция строки —
|
||||
как у PostgresStorage.clear_staging (исключение откатывает шаг).
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
from dataclasses import dataclass, replace
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from src.constants import ATTACHMENT_FAILED, ATTACHMENT_READY
|
||||
from src.domain import Attachment
|
||||
from src.services.cleanup import CleanupService
|
||||
from src.storage.objects import StoredObjectMissing
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
NOW = datetime(2026, 12, 2, tzinfo=UTC)
|
||||
SOURCE = b"\x89PNG source bytes"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Stored:
|
||||
size: int
|
||||
data: bytes
|
||||
|
||||
async def iter_chunks(self):
|
||||
for start in range(0, len(self.data), 4):
|
||||
yield self.data[start : start + 4]
|
||||
|
||||
|
||||
class Objects:
|
||||
def __init__(self, store: dict[str, bytes]) -> None:
|
||||
self.store = store
|
||||
self.deleted: list[str] = []
|
||||
|
||||
def variant_keys(self, attachment_id):
|
||||
return [f"db/attachments/{attachment_id}/p1/thumbnail.jpg"]
|
||||
|
||||
@asynccontextmanager
|
||||
async def _open(self, key):
|
||||
if key not in self.store:
|
||||
raise StoredObjectMissing(key)
|
||||
data = self.store[key]
|
||||
yield Stored(size=len(data), data=data)
|
||||
|
||||
def open(self, key):
|
||||
return self._open(key)
|
||||
|
||||
async def delete(self, key):
|
||||
self.deleted.append(key)
|
||||
self.store.pop(key, None)
|
||||
|
||||
|
||||
class Storage:
|
||||
"""Строки и clear_staging: шаг строки — «транзакция» (исключение — откат)."""
|
||||
|
||||
def __init__(self, rows: list[Attachment]) -> None:
|
||||
self.rows = {row.id: row for row in rows}
|
||||
|
||||
async def list_staging_done(self, *, failed_before, after, limit):
|
||||
found = [
|
||||
row
|
||||
for row in self.rows.values()
|
||||
if row.staging_key is not None
|
||||
and (
|
||||
row.status == ATTACHMENT_READY
|
||||
or (row.status == ATTACHMENT_FAILED and row.updated_at < failed_before)
|
||||
)
|
||||
]
|
||||
return found[:limit] if after is None else []
|
||||
|
||||
async def clear_staging(self, attachment_id, *, failed_before, delete_objects):
|
||||
row = self.rows[attachment_id]
|
||||
await delete_objects(row)
|
||||
self.rows[attachment_id] = replace(row, staging_key=None)
|
||||
return row
|
||||
|
||||
|
||||
def attachment(status: str, data: bytes = SOURCE, **changes) -> Attachment:
|
||||
ident = uuid4()
|
||||
row = Attachment(
|
||||
id=ident,
|
||||
chat_id=uuid4(),
|
||||
owner_id=uuid4(),
|
||||
filename="a.png",
|
||||
content_type="image/png",
|
||||
size_bytes=len(data),
|
||||
sha256=hashlib.sha256(data).digest(),
|
||||
object_key=f"db/attachments/{ident}/original",
|
||||
status=status,
|
||||
created_at=NOW - timedelta(days=2),
|
||||
updated_at=NOW - timedelta(days=2),
|
||||
lost_at=None,
|
||||
staging_key=f"db/staging/{ident}",
|
||||
error_code="processing_failed" if status == ATTACHMENT_FAILED else None,
|
||||
)
|
||||
return replace(row, **changes)
|
||||
|
||||
|
||||
def run(rows, store):
|
||||
storage, objects = Storage(rows), Objects(store)
|
||||
result = asyncio.run(
|
||||
CleanupService(storage, objects).clean_staging( # type: ignore[arg-type]
|
||||
failed_before=NOW - timedelta(days=1), batch=10
|
||||
)
|
||||
)
|
||||
return storage, objects, result
|
||||
|
||||
|
||||
def test_ready_source_removed_after_its_original_matches() -> None:
|
||||
row = attachment(ATTACHMENT_READY)
|
||||
store = {row.object_key: SOURCE, row.staging_key: SOURCE}
|
||||
storage, objects, result = run([row], store)
|
||||
assert objects.deleted == [row.staging_key]
|
||||
assert storage.rows[row.id].staging_key is None
|
||||
assert result.removed == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"original",
|
||||
[None, SOURCE + b"x", b"\x00" * len(SOURCE)],
|
||||
ids=["missing", "size", "sha256"],
|
||||
)
|
||||
def test_false_ready_keeps_the_source(original, caplog) -> None:
|
||||
"""Ложный ready (worker записал статус без результата или с чужими
|
||||
байтами): исходник на месте, строка staging не обнулена, ошибка в журнале;
|
||||
соседняя законная строка убрана."""
|
||||
false = attachment(ATTACHMENT_READY)
|
||||
good = attachment(ATTACHMENT_READY, data=b"other source")
|
||||
store = {
|
||||
false.staging_key: SOURCE,
|
||||
good.staging_key: b"other source",
|
||||
good.object_key: b"other source",
|
||||
}
|
||||
if original is not None:
|
||||
store[false.object_key] = original
|
||||
with caplog.at_level(logging.ERROR):
|
||||
storage, objects, result = run([false, good], store)
|
||||
assert false.staging_key in store
|
||||
assert storage.rows[false.id].staging_key == false.staging_key
|
||||
assert good.staging_key not in store
|
||||
assert result.removed == 1
|
||||
assert result.skipped == 1
|
||||
assert "staging kept" in caplog.text
|
||||
assert str(false.id) in caplog.text
|
||||
|
||||
|
||||
def test_failed_is_removed_by_retention_without_a_check() -> None:
|
||||
row = attachment(ATTACHMENT_FAILED)
|
||||
store = {row.staging_key: SOURCE}
|
||||
storage, objects, result = run([row], store)
|
||||
assert row.staging_key in objects.deleted
|
||||
assert result.removed == 1
|
||||
|
||||
|
||||
def test_stream_is_not_read_for_another_size() -> None:
|
||||
row = attachment(ATTACHMENT_READY)
|
||||
|
||||
class Exploding(Objects):
|
||||
@asynccontextmanager
|
||||
async def _open(self, key):
|
||||
if key == row.object_key:
|
||||
stored = Stored(size=1, data=b"")
|
||||
|
||||
async def boom():
|
||||
raise AssertionError("body of another size is read")
|
||||
yield b"" # pragma: no cover
|
||||
|
||||
stored.iter_chunks = boom # type: ignore[method-assign]
|
||||
yield stored
|
||||
return
|
||||
yield Stored(size=0, data=b"")
|
||||
|
||||
storage = Storage([row])
|
||||
objects = Exploding({row.staging_key: SOURCE})
|
||||
result = asyncio.run(
|
||||
CleanupService(storage, objects).clean_staging( # type: ignore[arg-type]
|
||||
failed_before=NOW, batch=10
|
||||
)
|
||||
)
|
||||
assert result.skipped == 1
|
||||
@@ -0,0 +1,384 @@
|
||||
"""Лаба 7: TLS клиентов к PostgreSQL, Valkey и S3 (перенос storage-tls).
|
||||
|
||||
Без стенда. Настройки и проверка точки входа (`src/client_tls.py`), контекст
|
||||
клиента и настоящие рукопожатия со своим TLS-сервером на loopback в потоке:
|
||||
сертификаты `postgres`, `valkey`, `s3` выпускает `infra/pki/pki.sh` во
|
||||
временный каталог (без OpenSSL ≥ 3 — пропуск с причиной). Проводка клиентов
|
||||
приложения: `Db` (asyncpg), `create_cache` (redis-py, `TlsConnection`),
|
||||
`create_object_store` (aiobotocore) — по CA стенда и имени; чужой CA и
|
||||
адрес вне SAN — та же недоступность (503 у PostgreSQL и S3, обход у кэша).
|
||||
Положительный путь протоколов хранилищ — `make storage-tls-check` на стенде.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from src.cache import TlsConnection, create_cache
|
||||
from src.client_tls import (
|
||||
API_STORAGES,
|
||||
MIGRATION_STORAGES,
|
||||
RELAY_STORAGES,
|
||||
WORKER_STORAGES,
|
||||
check_or_exit,
|
||||
client_context,
|
||||
client_tls_problems,
|
||||
)
|
||||
from src.config import Cache, ClientTls, Database, ObjectStorage, Settings
|
||||
from src.db import Db
|
||||
from src.errors import ObjectStorageUnavailable, Unavailable
|
||||
from src.s3 import create_object_store
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PKI = ROOT / "infra" / "pki" / "pki.sh"
|
||||
# файлы входа в OpenBao: обязательны всем процессам с переноса openbao-secrets
|
||||
BAO_FILES = ("BAO_CERT_FILE", "BAO_KEY_FILE", "BAO_CRL_FILE")
|
||||
|
||||
|
||||
def _pki(env: dict[str, str], *args: str) -> None:
|
||||
done = subprocess.run(
|
||||
["sh", str(PKI), *args], env=env, capture_output=True, text=True, check=False
|
||||
)
|
||||
if done.returncode != 0:
|
||||
pytest.skip(f"infra/pki/pki.sh {args[0]} failed (OpenSSL 3+?): {done.stderr}")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def pki(tmp_path_factory: pytest.TempPathFactory) -> dict[str, Path]:
|
||||
"""Файлы стенда (CA, пары postgres, valkey, s3, api) и CA другого
|
||||
оператора (его ключ — во временном каталоге теста)."""
|
||||
base = tmp_path_factory.mktemp("pki")
|
||||
env = {
|
||||
**os.environ,
|
||||
"PKI_OPERATOR_DIR": str(base / "operator"),
|
||||
"PKI_STAND_DIR": str(base / "stand"),
|
||||
}
|
||||
_pki(env, "stand")
|
||||
_pki({**env, "PKI_OPERATOR_DIR": str(base / "other")}, "init")
|
||||
return {"stand": base / "stand", "foreign": base / "other" / "ca.crt"}
|
||||
|
||||
|
||||
def _settings(env: dict[str, str]) -> Settings:
|
||||
return Settings.from_env(env)
|
||||
|
||||
|
||||
# --- настройки и проверка точки входа ---------------------------------------
|
||||
|
||||
|
||||
def test_client_tls_settings_and_defaults() -> None:
|
||||
settings = Settings.from_env({})
|
||||
assert settings.client_tls == ClientTls(ca_file="")
|
||||
assert ClientTls.from_env({"CLIENT_TLS_CA_FILE": " /ca.crt "}).ca_file == "/ca.crt"
|
||||
# умолчания — имена и https: без окружения нечему уйти открытым текстом
|
||||
assert settings.database.host == "localhost"
|
||||
assert settings.cache.host == "localhost"
|
||||
assert settings.s3.endpoint == "https://localhost:8334"
|
||||
|
||||
|
||||
def test_storages_by_process() -> None:
|
||||
# с переноса messaging-telemetry-mtls у worker и relay ещё брокер
|
||||
# (student-tests/unit/test_broker_tls.py), с переноса telemetry-mtls у всех
|
||||
# троих — приём Collector (test_telemetry_tls.py), с переноса openbao-secrets у
|
||||
# всех — OpenBao (test_secrets_store.py)
|
||||
assert API_STORAGES == ("database", "cache", "s3", "telemetry", "secret_store")
|
||||
assert WORKER_STORAGES == (
|
||||
"database",
|
||||
"s3",
|
||||
"broker",
|
||||
"telemetry",
|
||||
"secret_store",
|
||||
)
|
||||
assert RELAY_STORAGES == ("database", "broker", "telemetry", "secret_store")
|
||||
assert MIGRATION_STORAGES == ("database", "secret_store")
|
||||
|
||||
|
||||
def test_problems_without_ca_and_with_ip_addresses(tmp_path: Path) -> None:
|
||||
assert client_tls_problems(_settings({}), API_STORAGES) == [
|
||||
"CLIENT_TLS_CA_FILE",
|
||||
*BAO_FILES,
|
||||
]
|
||||
missing = str(tmp_path / "missing.crt")
|
||||
env = {
|
||||
"CLIENT_TLS_CA_FILE": missing,
|
||||
"DB_HOST": "127.0.0.1",
|
||||
"CACHE_HOST": "::1",
|
||||
"S3_ENDPOINT": "https://10.0.0.5:8333",
|
||||
}
|
||||
assert client_tls_problems(_settings(env), API_STORAGES) == [
|
||||
"CLIENT_TLS_CA_FILE",
|
||||
"DB_HOST",
|
||||
"CACHE_HOST",
|
||||
"S3_ENDPOINT",
|
||||
*BAO_FILES,
|
||||
]
|
||||
# процесс проверяет только свои хранилища (у relay с переноса
|
||||
# messaging-telemetry-mtls — ещё файлы брокера, поэтому здесь migrate)
|
||||
assert client_tls_problems(_settings(env), MIGRATION_STORAGES) == [
|
||||
"CLIENT_TLS_CA_FILE",
|
||||
"DB_HOST",
|
||||
*BAO_FILES,
|
||||
]
|
||||
plain = {"S3_ENDPOINT": "http://s3:8333"}
|
||||
assert "S3_ENDPOINT" in client_tls_problems(_settings(plain), WORKER_STORAGES)
|
||||
|
||||
|
||||
def test_problems_on_real_files(pki: dict, tmp_path: Path) -> None:
|
||||
stand = pki["stand"]
|
||||
good = {
|
||||
"CLIENT_TLS_CA_FILE": str(stand / "ca.crt"),
|
||||
"DB_HOST": "postgres",
|
||||
"CACHE_HOST": "valkey",
|
||||
"S3_ENDPOINT": "https://s3:8333",
|
||||
"BAO_CERT_FILE": str(stand / "api-client.crt"),
|
||||
"BAO_KEY_FILE": str(stand / "api-client.key"),
|
||||
"BAO_CRL_FILE": str(stand / "crl.pem"),
|
||||
}
|
||||
assert client_tls_problems(_settings(good), API_STORAGES) == []
|
||||
# файл читается, но сертификата CA в нём нет: leaf, CRL, не PEM
|
||||
broken = tmp_path / "broken.crt"
|
||||
broken.write_text("not a certificate\n", encoding="ascii")
|
||||
for path in (stand / "postgres.crt", stand / "crl.pem", broken):
|
||||
env = {**good, "CLIENT_TLS_CA_FILE": str(path)}
|
||||
assert client_tls_problems(_settings(env), API_STORAGES) == [
|
||||
"CLIENT_TLS_CA_FILE"
|
||||
], path.name
|
||||
|
||||
|
||||
def test_check_or_exit_names_only(
|
||||
tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
secret_path = str(tmp_path / "secret-dir" / "ca.crt")
|
||||
env = {"CLIENT_TLS_CA_FILE": secret_path, "DB_HOST": "192.0.2.1"}
|
||||
with pytest.raises(SystemExit) as exit_info:
|
||||
check_or_exit(_settings(env), MIGRATION_STORAGES)
|
||||
assert exit_info.value.code == 2
|
||||
err = capsys.readouterr().err
|
||||
assert err.strip() == (
|
||||
"configuration error: invalid client TLS settings: CLIENT_TLS_CA_FILE, "
|
||||
"DB_HOST, BAO_CERT_FILE, BAO_KEY_FILE, BAO_CRL_FILE"
|
||||
)
|
||||
assert "secret-dir" not in err
|
||||
assert "192.0.2.1" not in err
|
||||
|
||||
|
||||
def test_client_context_flags(pki: dict) -> None:
|
||||
context = client_context(str(pki["stand"] / "ca.crt"))
|
||||
assert context.minimum_version == ssl.TLSVersion.TLSv1_3
|
||||
assert context.check_hostname is True
|
||||
assert context.verify_mode == ssl.CERT_REQUIRED
|
||||
assert context.verify_flags & ssl.VERIFY_X509_STRICT
|
||||
# только CA стенда: системные корни не загружены
|
||||
assert context.cert_store_stats()["x509_ca"] == 1
|
||||
# без пути — ни одного доверенного CA (fail-closed), а не системные
|
||||
assert client_context("").cert_store_stats()["x509_ca"] == 0
|
||||
|
||||
|
||||
# --- свой TLS-сервер на loopback ------------------------------------------------
|
||||
|
||||
|
||||
class _Server:
|
||||
"""TLS-сервер в потоке: `pg` — сначала SSLRequest PostgreSQL и ответ «S»;
|
||||
`reply(sock)` — что ответить после рукопожатия. `handshakes` — число
|
||||
успешных рукопожатий."""
|
||||
|
||||
def __init__(self, stand: Path, name: str, *, pg: bool = False, reply=None):
|
||||
self.context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
self.context.load_cert_chain(stand / f"{name}.crt", stand / f"{name}.key")
|
||||
self.pg = pg
|
||||
self.reply = reply
|
||||
self.handshakes = 0
|
||||
self.listener = socket.create_server(("127.0.0.1", 0))
|
||||
self.port = self.listener.getsockname()[1]
|
||||
self.thread = threading.Thread(target=self._serve, daemon=True)
|
||||
|
||||
def _serve(self) -> None:
|
||||
while True:
|
||||
try:
|
||||
raw, _ = self.listener.accept()
|
||||
except OSError:
|
||||
return
|
||||
threading.Thread(target=self._one, args=(raw,), daemon=True).start()
|
||||
|
||||
def _one(self, raw: socket.socket) -> None:
|
||||
raw.settimeout(5)
|
||||
try:
|
||||
if self.pg:
|
||||
raw.recv(8)
|
||||
raw.sendall(b"S")
|
||||
with self.context.wrap_socket(raw, server_side=True) as sock:
|
||||
self.handshakes += 1
|
||||
if self.reply is not None:
|
||||
self.reply(sock)
|
||||
except (OSError, ssl.SSLError):
|
||||
pass
|
||||
finally:
|
||||
raw.close()
|
||||
|
||||
def __enter__(self) -> "_Server":
|
||||
self.thread.start()
|
||||
return self
|
||||
|
||||
def __exit__(self, *_: object) -> None:
|
||||
self.listener.close()
|
||||
|
||||
|
||||
def _connect(port: int, ca: Path, name: str) -> str:
|
||||
try:
|
||||
with (
|
||||
socket.create_connection(("127.0.0.1", port), timeout=5) as raw,
|
||||
client_context(str(ca)).wrap_socket(raw, server_hostname=name) as sock,
|
||||
):
|
||||
return str(sock.version())
|
||||
except ssl.SSLCertVerificationError as error:
|
||||
return "name" if "mismatch" in str(error) else "certificate"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("identity", ["postgres", "valkey", "s3"])
|
||||
def test_handshakes(pki: dict, identity: str) -> None:
|
||||
stand = pki["stand"]
|
||||
with _Server(stand, identity) as server:
|
||||
assert _connect(server.port, stand / "ca.crt", "localhost") == "TLSv1.3"
|
||||
assert _connect(server.port, stand / "ca.crt", identity) == "TLSv1.3"
|
||||
assert _connect(server.port, pki["foreign"], "localhost") == "certificate"
|
||||
assert _connect(server.port, stand / "ca.crt", "127.0.0.1") == "name"
|
||||
# сертификат другой identity того же CA под этим именем не проходит
|
||||
assert _connect(server.port, stand / "ca.crt", "api") == "name"
|
||||
|
||||
|
||||
def test_client_refuses_tls_below_1_3(pki: dict) -> None:
|
||||
stand = pki["stand"]
|
||||
with _Server(stand, "postgres") as server:
|
||||
server.context.maximum_version = ssl.TLSVersion.TLSv1_2
|
||||
with pytest.raises(ssl.SSLError):
|
||||
_connect(server.port, stand / "ca.crt", "localhost")
|
||||
|
||||
|
||||
# --- проводка клиентов приложения -------------------------------------------
|
||||
|
||||
|
||||
def test_db_tls_failure_is_unavailable(pki: dict) -> None:
|
||||
stand = pki["stand"]
|
||||
|
||||
async def scenario(db: Db) -> None:
|
||||
try:
|
||||
with pytest.raises(Unavailable):
|
||||
async with db.read():
|
||||
pass
|
||||
with pytest.raises(Unavailable):
|
||||
await db.ping()
|
||||
finally:
|
||||
await db.dispose()
|
||||
|
||||
with _Server(stand, "postgres", pg=True) as server:
|
||||
base = Database(host="localhost", port=server.port, connect_timeout=2)
|
||||
asyncio.run(scenario(Db(base, ca_file=str(pki["foreign"]))))
|
||||
# чужой CA: рукопожатие не прошло
|
||||
assert server.handshakes == 0
|
||||
ip = Database(host="127.0.0.1", port=server.port, connect_timeout=2)
|
||||
asyncio.run(scenario(Db(ip, ca_file=str(stand / "ca.crt"))))
|
||||
# имя вне SAN: клиент отверг сертификат до конца рукопожатия
|
||||
assert server.handshakes == 0
|
||||
asyncio.run(scenario(Db(base, ca_file=str(stand / "ca.crt"))))
|
||||
# CA стенда и имя: рукопожатие прошло (дальше протокол PostgreSQL
|
||||
# сервер пробы не знает и закрывает соединение — тоже недоступность)
|
||||
assert server.handshakes > 0
|
||||
|
||||
|
||||
def _resp_reply(sock: ssl.SSLSocket) -> None:
|
||||
"""RESP: на GET — `value`, на прочее (CLIENT SETINFO и т. п.) — +OK."""
|
||||
buffer = b""
|
||||
while True:
|
||||
chunk = sock.recv(4096)
|
||||
if not chunk:
|
||||
return
|
||||
buffer += chunk
|
||||
while buffer.startswith(b"*"):
|
||||
lines = buffer.split(b"\r\n")
|
||||
count = int(lines[0][1:])
|
||||
if len(lines) < 1 + 2 * count + 1:
|
||||
break
|
||||
parts = lines[2 : 2 + 2 * count : 2]
|
||||
consumed = sum(len(line) + 2 for line in lines[: 1 + 2 * count])
|
||||
buffer = buffer[consumed:]
|
||||
if parts[0].upper() == b"GET":
|
||||
sock.sendall(b"$5\r\nvalue\r\n")
|
||||
else:
|
||||
sock.sendall(b"+OK\r\n")
|
||||
|
||||
|
||||
def test_cache_over_tls_and_bypass(pki: dict, caplog: pytest.LogCaptureFixture) -> None:
|
||||
stand = pki["stand"]
|
||||
|
||||
async def get(cache) -> str | None:
|
||||
try:
|
||||
return await cache.get("chat")
|
||||
finally:
|
||||
await cache.close()
|
||||
|
||||
with _Server(stand, "valkey", reply=_resp_reply) as server:
|
||||
settings = Cache(host="localhost", port=server.port, timeout=2)
|
||||
cache = create_cache(settings, namespace="t", ca_file=str(stand / "ca.crt"))
|
||||
assert cache._client.connection_pool.connection_class is TlsConnection
|
||||
assert asyncio.run(get(cache)) == "value"
|
||||
with caplog.at_level(logging.WARNING, logger="src.cache"):
|
||||
foreign = create_cache(settings, namespace="t", ca_file=str(pki["foreign"]))
|
||||
assert asyncio.run(get(foreign)) is None
|
||||
ip = Cache(host="127.0.0.1", port=server.port, timeout=2)
|
||||
by_ip = create_cache(ip, namespace="t", ca_file=str(stand / "ca.crt"))
|
||||
assert asyncio.run(get(by_ip)) is None
|
||||
warnings = [r.getMessage() for r in caplog.records]
|
||||
assert sum("cache unavailable" in line for line in warnings) == 2
|
||||
|
||||
|
||||
def _http_404(sock: ssl.SSLSocket) -> None:
|
||||
data = b""
|
||||
while b"\r\n\r\n" not in data:
|
||||
chunk = sock.recv(4096)
|
||||
if not chunk:
|
||||
return
|
||||
data += chunk
|
||||
sock.sendall(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n")
|
||||
|
||||
|
||||
def test_object_store_over_https(pki: dict) -> None:
|
||||
stand = pki["stand"]
|
||||
|
||||
async def head(store, key: str = "missing"):
|
||||
try:
|
||||
return await store.head(key)
|
||||
finally:
|
||||
await store.close()
|
||||
|
||||
with _Server(stand, "s3", reply=_http_404) as server:
|
||||
settings = ObjectStorage(
|
||||
endpoint=f"https://localhost:{server.port}", connect_timeout=2, timeout=3
|
||||
)
|
||||
good = create_object_store(
|
||||
settings, namespace="t", ca_file=str(stand / "ca.crt")
|
||||
)
|
||||
# подписанный HEAD по TLS дошёл до сервера: 404 — «объекта нет»
|
||||
assert asyncio.run(head(good)) is None
|
||||
foreign = create_object_store(
|
||||
settings, namespace="t", ca_file=str(pki["foreign"])
|
||||
)
|
||||
with pytest.raises(ObjectStorageUnavailable):
|
||||
asyncio.run(head(foreign))
|
||||
ip = ObjectStorage(endpoint=f"https://127.0.0.1:{server.port}", timeout=3)
|
||||
by_ip = create_object_store(ip, namespace="t", ca_file=str(stand / "ca.crt"))
|
||||
with pytest.raises(ObjectStorageUnavailable):
|
||||
asyncio.run(head(by_ip))
|
||||
|
||||
|
||||
def test_object_store_without_ca_refuses() -> None:
|
||||
store = create_object_store(ObjectStorage(), namespace="t", ca_file="")
|
||||
with pytest.raises(ValueError, match="CLIENT_TLS_CA_FILE"):
|
||||
asyncio.run(store.start())
|
||||
@@ -0,0 +1,455 @@
|
||||
"""Юнит-тесты телеметрии (лаба 6): настройки, SDK, middleware, журнал.
|
||||
|
||||
Без стенда и сети: SDK собирается с in-memory экспортёрами
|
||||
(`sdk.Exporters`), приложение — маленький FastAPI с теми же middleware,
|
||||
что у API. Запуск — `make unit-test`; в `make student-test` и
|
||||
`make test-isolated` они идут вместе с остальными.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from collections.abc import Iterator
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from opentelemetry.sdk._logs.export import InMemoryLogRecordExporter
|
||||
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
|
||||
from opentelemetry.sdk.trace.export import SpanExportResult
|
||||
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
|
||||
from opentelemetry.trace import SpanKind
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
from src import log as app_log
|
||||
from src import telemetry
|
||||
from src.api.request_id import RequestIdMiddleware
|
||||
from src.api.tracing import HttpTelemetryMiddleware, RouteTemplates
|
||||
from src.config import ConfigError, Settings
|
||||
from src.config import Telemetry as TelemetrySettings
|
||||
from src.constants import APP_VERSION, SERVICE_API
|
||||
from src.telemetry import sdk
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
# лаба 7, перенос telemetry-mtls: только https; файлы TLS при подмене экспортёров
|
||||
# не читаются
|
||||
ENDPOINT = {"OTEL_EXPORTER_OTLP_ENDPOINT": "https://otel-collector:4318"}
|
||||
UUID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-")
|
||||
# метки, которых не должно быть у метрик (contracts/observability.md)
|
||||
FORBIDDEN_LABEL_PARTS = ("user", "chat", "message", "attachment", "request_id", "url")
|
||||
|
||||
|
||||
class Pipeline:
|
||||
"""Собранный SDK с in-memory экспортёрами и доступ к результату."""
|
||||
|
||||
def __init__(self, settings: TelemetrySettings) -> None:
|
||||
self.spans = InMemorySpanExporter()
|
||||
self.metrics = InMemoryMetricReader()
|
||||
self.logs = InMemoryLogRecordExporter()
|
||||
session = sdk.start(
|
||||
settings,
|
||||
service_name=SERVICE_API,
|
||||
instance_id="test-instance",
|
||||
exporters=sdk.Exporters(self.spans, self.metrics, self.logs),
|
||||
)
|
||||
assert session is not None
|
||||
self.session = session
|
||||
|
||||
def points(self, name: str) -> list:
|
||||
data = self.metrics.get_metrics_data()
|
||||
found = []
|
||||
for resource in data.resource_metrics if data else ():
|
||||
for scope in resource.scope_metrics:
|
||||
for metric in scope.metrics:
|
||||
if metric.name == name:
|
||||
found.extend(metric.data.data_points)
|
||||
return found
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def pipeline() -> Iterator[Pipeline]:
|
||||
built = Pipeline(TelemetrySettings.from_env(ENDPOINT))
|
||||
yield built
|
||||
built.session.shutdown(1.0)
|
||||
assert not telemetry.enabled()
|
||||
|
||||
|
||||
def make_app(session) -> FastAPI:
|
||||
"""Мини-API: те же middleware и шаблоны маршрутов, что в src.main."""
|
||||
app = FastAPI()
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
async def history(chat_id: str) -> dict:
|
||||
return {"items": []}
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}/content")
|
||||
async def content(attachment_id: str) -> dict:
|
||||
return {}
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}")
|
||||
async def meta(attachment_id: str) -> dict:
|
||||
return {}
|
||||
|
||||
@app.get("/health/live")
|
||||
async def live() -> dict:
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.get("/api/v1/boom")
|
||||
async def boom() -> dict:
|
||||
raise RuntimeError("secret detail must not leak")
|
||||
|
||||
app.add_middleware(RequestIdMiddleware, instance_id="test-instance")
|
||||
if session is not None:
|
||||
app.add_middleware(HttpTelemetryMiddleware, routes=RouteTemplates(app))
|
||||
return app
|
||||
|
||||
|
||||
# --- настройки ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_settings_default_is_off() -> None:
|
||||
settings = Settings.from_env({})
|
||||
assert not settings.telemetry.enabled
|
||||
assert sdk.start(settings.telemetry, service_name="x", instance_id="y") is None
|
||||
assert not telemetry.enabled()
|
||||
|
||||
|
||||
def test_settings_full_telemetry_by_default_when_endpoint_set() -> None:
|
||||
settings = TelemetrySettings.from_env(ENDPOINT)
|
||||
assert settings.enabled
|
||||
assert settings.sample_ratio == 1.0
|
||||
assert settings.buckets == "default"
|
||||
assert settings.metric_interval_ms == 15_000
|
||||
assert settings.environment == "lab"
|
||||
|
||||
|
||||
def test_settings_knobs() -> None:
|
||||
settings = TelemetrySettings.from_env(
|
||||
{
|
||||
**ENDPOINT,
|
||||
"OTEL_TRACES_SAMPLER_ARG": "0.1",
|
||||
"OTEL_METRIC_EXPORT_INTERVAL": "30000",
|
||||
"TELEMETRY_HISTOGRAM_BUCKETS": "coarse",
|
||||
"OTEL_RESOURCE_ATTRIBUTES": "deployment.environment.name=bench",
|
||||
}
|
||||
)
|
||||
assert (settings.sample_ratio, settings.metric_interval_ms) == (0.1, 30_000)
|
||||
assert (settings.buckets, settings.environment) == ("coarse", "bench")
|
||||
off = TelemetrySettings.from_env({**ENDPOINT, "OTEL_SDK_DISABLED": "true"})
|
||||
assert not off.enabled
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("name", "value"),
|
||||
[
|
||||
("OTEL_EXPORTER_OTLP_PROTOCOL", "grpc"),
|
||||
("OTEL_EXPORTER_OTLP_ENDPOINT", "otel-collector:4318"),
|
||||
("OTEL_EXPORTER_OTLP_ENDPOINT", "http://otel-collector:4318/v1/traces"),
|
||||
("OTEL_SDK_DISABLED", "yes"),
|
||||
("OTEL_TRACES_SAMPLER_ARG", "1.5"),
|
||||
("OTEL_METRIC_EXPORT_INTERVAL", "10"),
|
||||
("TELEMETRY_HISTOGRAM_BUCKETS", "fine"),
|
||||
("OTEL_RESOURCE_ATTRIBUTES", "service.name=evil"),
|
||||
("OTEL_RESOURCE_ATTRIBUTES", "deployment.environment.name=Bad Name"),
|
||||
],
|
||||
)
|
||||
def test_settings_reject_bad_values(name: str, value: str) -> None:
|
||||
with pytest.raises(ConfigError, match=name.split("_")[0]):
|
||||
Settings.from_env({**ENDPOINT, name: value})
|
||||
|
||||
|
||||
# --- HTTP --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_http_span_and_metric_use_route_template(pipeline: Pipeline) -> None:
|
||||
chat_id = str(uuid.uuid4())
|
||||
with TestClient(make_app(pipeline.session)) as client:
|
||||
response = client.get(
|
||||
f"/api/v1/chats/{chat_id}/messages?cursor=abc",
|
||||
headers={"X-Request-Id": "unit-rid-1", "Authorization": "Bearer t0ken"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
(span,) = pipeline.spans.get_finished_spans()
|
||||
assert span.kind == SpanKind.SERVER
|
||||
assert span.name == "GET /api/v1/chats/{chat_id}/messages"
|
||||
attrs = dict(span.attributes)
|
||||
assert attrs["http.route"] == "/api/v1/chats/{chat_id}/messages"
|
||||
assert attrs["http.response.status_code"] == 200
|
||||
assert attrs["messenger.request_id"] == "unit-rid-1"
|
||||
flat = repr(attrs)
|
||||
for leaked in (chat_id, "t0ken", "cursor"):
|
||||
assert leaked not in flat
|
||||
resource = dict(span.resource.attributes)
|
||||
assert resource == {
|
||||
"service.name": SERVICE_API,
|
||||
"service.version": APP_VERSION,
|
||||
"service.instance.id": "test-instance",
|
||||
"deployment.environment.name": "lab",
|
||||
}
|
||||
|
||||
(point,) = pipeline.points(telemetry.HTTP_DURATION)
|
||||
assert dict(point.attributes) == {
|
||||
"http.request.method": "GET",
|
||||
"http.route": "/api/v1/chats/{chat_id}/messages",
|
||||
"http.response.status_code": 200,
|
||||
"http.response.status_class": "2xx",
|
||||
}
|
||||
assert point.count == 1
|
||||
assert point.explicit_bounds == tuple(
|
||||
sdk.BUCKETS["default"][telemetry.HTTP_DURATION]
|
||||
)
|
||||
|
||||
|
||||
def test_more_specific_template_wins(pipeline: Pipeline) -> None:
|
||||
with TestClient(make_app(pipeline.session)) as client:
|
||||
client.get(f"/api/v1/attachments/{uuid.uuid4()}/content")
|
||||
client.get(f"/api/v1/attachments/{uuid.uuid4()}")
|
||||
names = sorted(span.name for span in pipeline.spans.get_finished_spans())
|
||||
assert names == [
|
||||
"GET /api/v1/attachments/{attachment_id}",
|
||||
"GET /api/v1/attachments/{attachment_id}/content",
|
||||
]
|
||||
|
||||
|
||||
def test_unknown_path_and_method_do_not_create_labels(pipeline: Pipeline) -> None:
|
||||
with TestClient(make_app(pipeline.session)) as client:
|
||||
client.get(f"/scanner/{uuid.uuid4()}")
|
||||
client.request("PROPFIND", "/api/v1/boom")
|
||||
for point in pipeline.points(telemetry.HTTP_DURATION):
|
||||
attrs = dict(point.attributes)
|
||||
assert attrs["http.request.method"] in ("GET", "_OTHER")
|
||||
assert not UUID_RE.search(repr(attrs))
|
||||
unknown = [s for s in pipeline.spans.get_finished_spans() if s.name == "GET"]
|
||||
assert len(unknown) == 1
|
||||
assert "http.route" not in unknown[0].attributes
|
||||
|
||||
|
||||
def test_health_is_not_traced(pipeline: Pipeline) -> None:
|
||||
with TestClient(make_app(pipeline.session)) as client:
|
||||
assert client.get("/health/live").status_code == 200
|
||||
assert pipeline.spans.get_finished_spans() == ()
|
||||
assert pipeline.points(telemetry.HTTP_DURATION) == []
|
||||
|
||||
|
||||
def test_server_error_marks_span_without_message(pipeline: Pipeline) -> None:
|
||||
with TestClient(make_app(pipeline.session), raise_server_exceptions=False) as c:
|
||||
assert c.get("/api/v1/boom").status_code == 500
|
||||
(span,) = pipeline.spans.get_finished_spans()
|
||||
assert span.status.is_ok is False
|
||||
assert span.attributes["error.type"] == "RuntimeError"
|
||||
assert span.attributes["http.response.status_code"] == 500
|
||||
assert "secret detail" not in repr(span.attributes)
|
||||
assert span.events == ()
|
||||
(point,) = pipeline.points(telemetry.HTTP_DURATION)
|
||||
assert point.attributes["http.response.status_class"] == "5xx"
|
||||
|
||||
|
||||
def test_metric_labels_are_low_cardinality(pipeline: Pipeline) -> None:
|
||||
with TestClient(make_app(pipeline.session)) as client:
|
||||
for _ in range(5):
|
||||
client.get(
|
||||
f"/api/v1/chats/{uuid.uuid4()}/messages",
|
||||
headers={"X-Request-Id": uuid.uuid4().hex},
|
||||
)
|
||||
points = pipeline.points(telemetry.HTTP_DURATION)
|
||||
assert len(points) == 1
|
||||
assert points[0].count == 5
|
||||
for key in points[0].attributes:
|
||||
assert not any(part in key for part in FORBIDDEN_LABEL_PARTS), key
|
||||
|
||||
|
||||
def test_disabled_app_has_no_telemetry_middleware() -> None:
|
||||
app = make_app(None)
|
||||
with TestClient(app) as client:
|
||||
assert client.get("/health/live").status_code == 200
|
||||
assert not any(m.cls is HttpTelemetryMiddleware for m in app.user_middleware)
|
||||
|
||||
|
||||
# --- span хранилищ, задания, relay -------------------------------------------------
|
||||
|
||||
|
||||
def test_child_span_only_under_a_root(pipeline: Pipeline) -> None:
|
||||
with telemetry.child_span("postgresql read", {"db.system.name": "postgresql"}):
|
||||
pass
|
||||
assert pipeline.spans.get_finished_spans() == ()
|
||||
with (
|
||||
telemetry.root_span("process q", kind=SpanKind.CONSUMER, attributes={}),
|
||||
telemetry.child_span("S3 GetObject", {"rpc.method": "GetObject"}),
|
||||
):
|
||||
pass
|
||||
child, root = pipeline.spans.get_finished_spans()
|
||||
assert child.parent is not None
|
||||
assert child.parent.span_id == root.context.span_id
|
||||
assert child.context.trace_id == root.context.trace_id
|
||||
|
||||
|
||||
def test_child_span_records_error_type(pipeline: Pipeline) -> None:
|
||||
with (
|
||||
pytest.raises(TimeoutError),
|
||||
telemetry.root_span("process q", kind=SpanKind.CONSUMER, attributes={}),
|
||||
telemetry.child_span("S3 PutObject", {}),
|
||||
):
|
||||
raise TimeoutError("key attachments/123 in text")
|
||||
child, root = pipeline.spans.get_finished_spans()
|
||||
assert child.attributes["error.type"] == "TimeoutError"
|
||||
assert root.attributes["error.type"] == "TimeoutError"
|
||||
assert "attachments/123" not in repr(child.attributes) + repr(child.events)
|
||||
|
||||
|
||||
def test_job_histogram_by_type_and_outcome(pipeline: Pipeline) -> None:
|
||||
for outcome in ("ready", "ready", "failed"):
|
||||
with telemetry.root_span(
|
||||
"process q", kind=SpanKind.CONSUMER, attributes={}
|
||||
) as span:
|
||||
telemetry.record_job(
|
||||
span, job_type="attachment.process.v1", outcome=outcome, seconds=0.3
|
||||
)
|
||||
counts = {
|
||||
p.attributes["messenger.job.outcome"]: p.count
|
||||
for p in pipeline.points(telemetry.JOB_DURATION)
|
||||
}
|
||||
assert counts == {"ready": 2, "failed": 1}
|
||||
outcomes = [
|
||||
s.attributes["messenger.job.outcome"]
|
||||
for s in pipeline.spans.get_finished_spans()
|
||||
]
|
||||
assert sorted(outcomes) == ["failed", "ready", "ready"]
|
||||
|
||||
|
||||
def test_relay_counter_skips_zero(pipeline: Pipeline) -> None:
|
||||
telemetry.count_relay({"published": 3, "requeued": 0})
|
||||
telemetry.count_relay({"published": 2})
|
||||
(point,) = pipeline.points(telemetry.RELAY_JOBS)
|
||||
assert point.value == 5
|
||||
assert dict(point.attributes) == {"messenger.relay.action": "published"}
|
||||
|
||||
|
||||
# --- журнал ------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_log_record_carries_trace_and_request_id(pipeline: Pipeline) -> None:
|
||||
logger = logging.getLogger("src.unit")
|
||||
logger.setLevel(logging.INFO)
|
||||
logger.addHandler(pipeline.session.log_handler)
|
||||
token = app_log.request_id_var.set("unit-rid-2")
|
||||
try:
|
||||
with telemetry.root_span("GET /x", kind=SpanKind.SERVER, attributes={}) as span:
|
||||
logger.info("chat created chat_id=%s members=%d", "c1", 2)
|
||||
suffix = telemetry.trace_fields()
|
||||
finally:
|
||||
app_log.request_id_var.reset(token)
|
||||
logger.removeHandler(pipeline.session.log_handler)
|
||||
(exported,) = pipeline.logs.get_finished_logs()
|
||||
record = exported.log_record
|
||||
assert record.body == "chat created chat_id=c1 members=2"
|
||||
assert record.trace_id == span.get_span_context().trace_id
|
||||
assert record.span_id == span.get_span_context().span_id
|
||||
assert dict(record.attributes) == {
|
||||
"event": "chat created",
|
||||
"logger": "src.unit",
|
||||
"request_id": "unit-rid-2",
|
||||
}
|
||||
assert record.severity_text == "INFO"
|
||||
trace_id = f"{span.get_span_context().trace_id:032x}"
|
||||
assert suffix.startswith(f" trace_id={trace_id} span_id=")
|
||||
|
||||
|
||||
def test_stdout_line_gets_trace_fields_only_inside_span(pipeline: Pipeline) -> None:
|
||||
record = logging.LogRecord("src.x", logging.INFO, __file__, 1, "hello", (), None)
|
||||
app_log.RequestIdFilter().filter(record)
|
||||
assert record.trace == ""
|
||||
with telemetry.root_span("GET /x", kind=SpanKind.SERVER, attributes={}):
|
||||
app_log.RequestIdFilter().filter(record)
|
||||
assert re.fullmatch(r" trace_id=[0-9a-f]{32} span_id=[0-9a-f]{16}", record.trace)
|
||||
|
||||
|
||||
def test_unsampled_root_has_no_trace_fields() -> None:
|
||||
built = Pipeline(
|
||||
TelemetrySettings.from_env({**ENDPOINT, "OTEL_TRACES_SAMPLER_ARG": "0"})
|
||||
)
|
||||
try:
|
||||
with telemetry.root_span("GET /x", kind=SpanKind.SERVER, attributes={}):
|
||||
assert telemetry.trace_fields() == ""
|
||||
assert built.spans.get_finished_spans() == ()
|
||||
finally:
|
||||
built.session.shutdown(1.0)
|
||||
|
||||
|
||||
def test_exception_traceback_is_not_exported(pipeline: Pipeline) -> None:
|
||||
logger = logging.getLogger("src.unit.exc")
|
||||
logger.addHandler(pipeline.session.log_handler)
|
||||
try:
|
||||
try:
|
||||
raise ValueError("password=hunter2")
|
||||
except ValueError:
|
||||
logger.error("job delivery failed job_id=%s", "j1", exc_info=True)
|
||||
finally:
|
||||
logger.removeHandler(pipeline.session.log_handler)
|
||||
(exported,) = pipeline.logs.get_finished_logs()
|
||||
assert exported.log_record.attributes["exception.type"] == "ValueError"
|
||||
assert "hunter2" not in repr(exported.log_record.attributes)
|
||||
|
||||
|
||||
def test_event_name_from_template() -> None:
|
||||
def record(msg: str, **extra: str) -> logging.LogRecord:
|
||||
item = logging.LogRecord("src.x", logging.INFO, __file__, 1, msg, (), None)
|
||||
item.__dict__.update(extra)
|
||||
return item
|
||||
|
||||
assert sdk.event_name(record("attachment processed attachment_id=%s")) == (
|
||||
"attachment processed"
|
||||
)
|
||||
assert sdk.event_name(record("%s %s -> %d", event="http request")) == "http request"
|
||||
assert sdk.event_name(record("Started server process [%d]")) == (
|
||||
"Started server process"
|
||||
)
|
||||
assert sdk.event_name(record("%s")) == "src.x"
|
||||
|
||||
|
||||
# --- наборы границ и закрытие ------------------------------------------------------
|
||||
|
||||
|
||||
def test_coarse_buckets_are_applied() -> None:
|
||||
built = Pipeline(
|
||||
TelemetrySettings.from_env(
|
||||
{**ENDPOINT, "TELEMETRY_HISTOGRAM_BUCKETS": "coarse"}
|
||||
)
|
||||
)
|
||||
try:
|
||||
telemetry.record_job(None, job_type="t", outcome="ready", seconds=1.0)
|
||||
(point,) = built.points(telemetry.JOB_DURATION)
|
||||
assert point.explicit_bounds == tuple(
|
||||
sdk.BUCKETS["coarse"][telemetry.JOB_DURATION]
|
||||
)
|
||||
finally:
|
||||
built.session.shutdown(1.0)
|
||||
|
||||
|
||||
class _StuckExporter(InMemorySpanExporter):
|
||||
"""Экспортёр, который «висит», как замороженный Collector."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.release = threading.Event()
|
||||
|
||||
def export(self, spans) -> SpanExportResult:
|
||||
self.release.wait(10)
|
||||
return SpanExportResult.SUCCESS
|
||||
|
||||
|
||||
def test_shutdown_respects_deadline() -> None:
|
||||
built = Pipeline(TelemetrySettings.from_env(ENDPOINT))
|
||||
stuck = _StuckExporter()
|
||||
built.session.tracer_provider.add_span_processor(
|
||||
sdk.BatchSpanProcessor(stuck, schedule_delay_millis=10)
|
||||
)
|
||||
with telemetry.root_span("GET /x", kind=SpanKind.SERVER, attributes={}):
|
||||
pass
|
||||
time.sleep(0.1)
|
||||
started = time.monotonic()
|
||||
assert built.session.shutdown(0.3) is False
|
||||
assert time.monotonic() - started < 1.0
|
||||
assert not telemetry.enabled()
|
||||
stuck.release.set()
|
||||
@@ -0,0 +1,655 @@
|
||||
"""Лаба 7: TLS хранилищ телеметрии, метрик и Grafana (перенос telemetry-backends-tls).
|
||||
|
||||
Без стенда: согласованность конфигураций. Allowlist и права шлюзов Loki, Tempo,
|
||||
Prometheus, портов метрик Collector и LB — DNS SAN строк
|
||||
`infra/pki/identities.conf`; каждый `bind … ssl` (кроме ingress) — обязательный
|
||||
сертификат клиента, CRL и TLS 1.3, остальные слушатели — loopback; хранилища
|
||||
слушают только `127.0.0.1` в пространстве своего шлюза; цели Prometheus, экспорт
|
||||
Collector и источники Grafana — `https` со своей парой и CA стенда; файлы PKI — у
|
||||
каждого сервиса свои. Проверки — функции над корнем репозитория: их зовут на рабочем
|
||||
дереве и на копии с внесённой ошибкой (контроль). Поведение на настоящих шлюзах —
|
||||
`make telemetry-tls-check`.
|
||||
|
||||
YAML разбирается построчно: PyYAML — не прямая зависимость проекта.
|
||||
"""
|
||||
|
||||
import importlib.util
|
||||
import re
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
LOKI = "infra/otel/loki-gateway.cfg"
|
||||
TEMPO = "infra/otel/tempo-gateway.cfg"
|
||||
PROM = "infra/otel/prometheus-gateway.cfg"
|
||||
OTEL = "infra/otel/gateway.cfg"
|
||||
LB = "infra/haproxy/haproxy.cfg"
|
||||
LOKI_YAML = "infra/otel/loki/loki.yaml"
|
||||
TEMPO_YAML = "infra/otel/tempo/tempo.yaml"
|
||||
COLLECTOR = "infra/otel/collector.yaml"
|
||||
SOURCES = "infra/otel/grafana/datasources.yaml"
|
||||
SCRAPES = ("infra/otel/prometheus/prometheus.yml", "bench/otel/prometheus-lean.yml")
|
||||
IDENTITIES = "infra/pki/identities.conf"
|
||||
|
||||
# (файл, frontend) → строки identities.conf, чьи DNS SAN — allowlist порта
|
||||
ALLOWLISTS = {
|
||||
(LOKI, "loki_in"): ("otel-collector-client", "grafana-client", "prometheus-client"),
|
||||
(TEMPO, "otlp_in"): ("otel-collector-client",),
|
||||
(TEMPO, "query_in"): ("grafana-client", "prometheus-client"),
|
||||
(PROM, "prometheus_in"): ("grafana-client",),
|
||||
(OTEL, "metrics_own"): ("prometheus-client",),
|
||||
(OTEL, "metrics_app"): ("prometheus-client",),
|
||||
(LB, "monitor"): ("otel-collector-client",),
|
||||
}
|
||||
# права: frontend → правила allow (identity, метод, путь или список путей) и шлюз
|
||||
RIGHTS = {
|
||||
(LOKI, "loki_in"): (
|
||||
"loki-gateway",
|
||||
["allow if id_collector METH_POST { path /otlp/v1/logs }",
|
||||
"allow if id_grafana METH_GET read_path",
|
||||
"allow if id_prometheus METH_GET { path /metrics }"],
|
||||
),
|
||||
(TEMPO, "otlp_in"): (
|
||||
"tempo-gateway",
|
||||
["allow if id_collector METH_POST { path /v1/traces }"],
|
||||
),
|
||||
(TEMPO, "query_in"): (
|
||||
"tempo-gateway",
|
||||
["allow if id_grafana METH_GET read_path",
|
||||
"allow if id_prometheus METH_GET { path /metrics }"],
|
||||
),
|
||||
(PROM, "prometheus_in"): (
|
||||
"prometheus-gateway",
|
||||
["allow if id_grafana METH_GET read_path",
|
||||
"allow if id_grafana METH_POST read_path"],
|
||||
),
|
||||
} # fmt: skip
|
||||
ACL_NAMES = {
|
||||
"id_collector": "otel-collector",
|
||||
"id_grafana": "grafana",
|
||||
"id_prometheus": "prometheus",
|
||||
}
|
||||
# чего нет ни в одном списке чтения
|
||||
FORBIDDEN_WORDS = ("push", "delete", "compactor", "config$", "flush", "admin", "write")
|
||||
# сегмент . или .. (без обратной косой: HAProxy снимает её в словах без кавычек)
|
||||
DOT_SEGMENT = "/[.][.]?(/|$)"
|
||||
# %3A у порта запросов Tempo: им Grafana кодирует двоеточие встроенных тегов
|
||||
PERCENT_EXCEPTION = {(TEMPO, "query_in"): "%(?!3[Aa])"}
|
||||
# серверный .pem каждого файла
|
||||
PEMS = {
|
||||
LOKI: "loki",
|
||||
TEMPO: "tempo",
|
||||
PROM: "prometheus",
|
||||
OTEL: "otel-collector",
|
||||
LB: "ingress",
|
||||
}
|
||||
# хранилище → (шлюз, его конфигурация, порты backend на loopback)
|
||||
STORAGES = {
|
||||
"loki": ("loki-gateway", LOKI, {"13100"}),
|
||||
"tempo": ("tempo-gateway", TEMPO, {"13200", "14318"}),
|
||||
"prometheus": ("prometheus-gateway", PROM, {"19090"}),
|
||||
}
|
||||
# сервис → его файлы PKI, кроме ca.crt и crl.pem
|
||||
FILES = {
|
||||
"loki-gateway": {"loki.pem"},
|
||||
"tempo-gateway": {"tempo.pem"},
|
||||
"prometheus-gateway": {"prometheus.pem"},
|
||||
"otel-collector": {"otel-collector-client.crt", "otel-collector-client.key"},
|
||||
"prometheus": {"prometheus-client.crt", "prometheus-client.key"},
|
||||
"grafana": {
|
||||
"grafana.crt",
|
||||
"grafana.key",
|
||||
"grafana-client.crt",
|
||||
"grafana-client.key",
|
||||
},
|
||||
"loki": set(),
|
||||
"tempo": set(),
|
||||
}
|
||||
|
||||
|
||||
def _read(root: Path, rel: str) -> str:
|
||||
"""Файл без строк-комментариев."""
|
||||
lines = (root / rel).read_text(encoding="utf-8").splitlines()
|
||||
return "\n".join(line for line in lines if not line.lstrip().startswith("#")) + "\n"
|
||||
|
||||
|
||||
def _identities(root: Path) -> dict[str, tuple[str, list[str], str]]:
|
||||
rows = {}
|
||||
for line in _read(root, IDENTITIES).splitlines():
|
||||
if line.strip():
|
||||
name, profile, sans, form = line.split()
|
||||
rows[name] = (profile, sans.split(","), form)
|
||||
return rows
|
||||
|
||||
|
||||
def _sections(root: Path, rel: str) -> dict[tuple[str, str], list[str]]:
|
||||
"""Разделы HAProxy: (тип, имя) → строки без отступа."""
|
||||
out: dict[tuple[str, str], list[str]] = {}
|
||||
current: list[str] = []
|
||||
for raw in _read(root, rel).splitlines():
|
||||
if not raw.strip():
|
||||
continue
|
||||
if not raw[0].isspace():
|
||||
words = raw.split()
|
||||
current = out.setdefault((words[0], (words + [""])[1]), [])
|
||||
else:
|
||||
current.append(raw.strip())
|
||||
return out
|
||||
|
||||
|
||||
def _block(text: str, name: str, indent: int = 2) -> str:
|
||||
"""Тело ключа YAML по отступу (блок сервиса compose, экспортёр, задание)."""
|
||||
pad = " " * indent
|
||||
match = re.search(
|
||||
rf"^{pad}{re.escape(name)}:\n(.*?)(?=^ {{0,{indent}}}\S|\Z)", text, re.M | re.S
|
||||
)
|
||||
return match.group(1) if match else ""
|
||||
|
||||
|
||||
def _items(block: str, key: str) -> list[str]:
|
||||
match = re.search(rf"^ {key}:\n((?: - .*\n)+)", block, re.M)
|
||||
return re.findall(r"- (\S+)", match.group(1)) if match else []
|
||||
|
||||
|
||||
def allowlist_problems(root: Path) -> list[str]:
|
||||
rows = _identities(root)
|
||||
problems = []
|
||||
for (rel, frontend), names in ALLOWLISTS.items():
|
||||
lines = _sections(root, rel).get(("frontend", frontend), [])
|
||||
expected = []
|
||||
for name in names:
|
||||
profile, sans, _ = rows.get(name, ("missing", [], ""))
|
||||
if profile != "client" or len(sans) != 1:
|
||||
problems.append(f"{IDENTITIES}: {name} is not a client with one name")
|
||||
expected += [f"DNS:{san}" for san in sans]
|
||||
want = [
|
||||
"tcp-request session set-var(sess.refusal) str(identity_not_allowed) "
|
||||
f"unless {{ ssl_c_san -m str {' '.join(expected)} }}",
|
||||
"tcp-request session reject if { var(sess.refusal) -m found }",
|
||||
]
|
||||
got = [line for line in lines if line.startswith("tcp-request")]
|
||||
if got != want:
|
||||
problems.append(f"{rel}: frontend {frontend}: {got} != {want}")
|
||||
return problems
|
||||
|
||||
|
||||
def rights_problems(root: Path) -> list[str]:
|
||||
problems = []
|
||||
for (rel, frontend), (gateway, allows) in RIGHTS.items():
|
||||
lines = _sections(root, rel).get(("frontend", frontend), [])
|
||||
deny = f"http-request deny deny_status 403 hdr X-Gateway-Refused {gateway}"
|
||||
want = [
|
||||
f"{deny} if unsafe_path",
|
||||
*(f"http-request {rule}" for rule in allows),
|
||||
deny,
|
||||
]
|
||||
got = [line for line in lines if line.startswith("http-request")]
|
||||
if got != want:
|
||||
problems.append(f"{rel}: frontend {frontend}: rules {got}")
|
||||
acls = [line.split(maxsplit=2)[1:] for line in lines if line.startswith("acl ")]
|
||||
for name, body in acls:
|
||||
if name in ACL_NAMES and body != f"ssl_c_san -m str DNS:{ACL_NAMES[name]}":
|
||||
problems.append(f"{rel}: frontend {frontend}: acl {name} {body}")
|
||||
if name == "read_path" and not (
|
||||
body.startswith("path_reg ^/") and body.endswith(")$")
|
||||
):
|
||||
problems.append(f"{rel}: frontend {frontend}: read_path not anchored")
|
||||
if name == "read_path" and any(word in body for word in FORBIDDEN_WORDS):
|
||||
problems.append(f"{rel}: frontend {frontend}: read_path {body}")
|
||||
unsafe = [body for name, body in acls if name == "unsafe_path"]
|
||||
percent = PERCENT_EXCEPTION.get((rel, frontend))
|
||||
expected = (
|
||||
["path_sub % //", f"path_reg {DOT_SEGMENT}"]
|
||||
if percent is None
|
||||
else ["path_sub //", f"path_reg {percent}", f"path_reg {DOT_SEGMENT}"]
|
||||
)
|
||||
if unsafe != expected:
|
||||
problems.append(f"{rel}: frontend {frontend}: unsafe_path {unsafe}")
|
||||
for rel, frontend in ((OTEL, "metrics_own"), (OTEL, "metrics_app")):
|
||||
lines = _sections(root, rel).get(("frontend", frontend), [])
|
||||
rule = "http-request deny deny_status 404 unless METH_GET { path /metrics }"
|
||||
if [line for line in lines if line.startswith("http-request")] != [rule]:
|
||||
problems.append(f"{rel}: frontend {frontend}: more than GET /metrics")
|
||||
monitor = _sections(root, LB).get(("frontend", "monitor"), [])
|
||||
if [line for line in monitor if line.startswith(("http-request", "stats"))] != [
|
||||
"http-request use-service prometheus-exporter if METH_GET { path /metrics }",
|
||||
"http-request deny deny_status 404",
|
||||
]:
|
||||
problems.append(f"{LB}: frontend monitor: more than GET /metrics")
|
||||
return problems
|
||||
|
||||
|
||||
def bind_problems(root: Path) -> list[str]:
|
||||
rows = _identities(root)
|
||||
problems = []
|
||||
for rel, pem in PEMS.items():
|
||||
if rows.get(pem, ("",))[0] != "server" or rows[pem][2] != "bundle":
|
||||
problems.append(f"{IDENTITIES}: {pem} is not a server bundle")
|
||||
for (kind, name), lines in _sections(root, rel).items():
|
||||
for line in lines:
|
||||
if kind != "frontend" or not line.startswith("bind "):
|
||||
continue
|
||||
if " ssl " not in line:
|
||||
if not line.startswith("bind 127.0.0.1:"):
|
||||
problems.append(f"{rel}: {name}: {line} without TLS")
|
||||
elif (rel, name) != (LB, "entry") and not line.endswith(
|
||||
f" ssl crt /run/secrets/{pem}.pem ca-file /run/secrets/ca.crt "
|
||||
"crl-file /run/secrets/crl.pem verify required "
|
||||
"ssl-min-ver TLSv1.3 alpn http/1.1"
|
||||
):
|
||||
problems.append(f"{rel}: {name}: {line}")
|
||||
# отказы шлюза видны: журнал отказов рукопожатия и identity не выключен
|
||||
text = _read(root, rel)
|
||||
if "option dontlognull" in text or "error-log-format" not in text:
|
||||
problems.append(f"{rel}: refusals are not logged")
|
||||
return problems
|
||||
|
||||
|
||||
def storage_problems(root: Path) -> list[str]:
|
||||
compose = _read(root, "compose.yaml")
|
||||
problems = []
|
||||
for storage, (gateway, rel, ports) in STORAGES.items():
|
||||
block = _block(compose, storage)
|
||||
for needed in (
|
||||
f"network_mode: service:{gateway}",
|
||||
f" {gateway}:\n condition: service_healthy\n"
|
||||
" restart: true",
|
||||
):
|
||||
if needed not in block:
|
||||
problems.append(f"compose.yaml: {storage} without {needed!r}")
|
||||
if re.search(r"^ (networks|ports):", block, re.M):
|
||||
problems.append(f"compose.yaml: {storage} has networks or ports")
|
||||
owner = _block(compose, gateway)
|
||||
alias = f" telemetry:\n aliases:\n - {storage}\n"
|
||||
if alias not in owner or "default:" in owner or "ports:" in owner:
|
||||
problems.append(f"compose.yaml: networks of {gateway}")
|
||||
if "<<: [*storage-gateway, *hardened]" not in owner:
|
||||
problems.append(f"compose.yaml: {gateway} without the shared anchors")
|
||||
if f"source: ./{rel}\n" not in owner:
|
||||
problems.append(f"compose.yaml: {gateway} does not mount {rel}")
|
||||
servers = [
|
||||
line.split()[2]
|
||||
for (kind, _), lines in _sections(root, rel).items()
|
||||
if kind == "backend"
|
||||
for line in lines
|
||||
if line.startswith("server ")
|
||||
]
|
||||
if set(servers) != {f"127.0.0.1:{port}" for port in ports}:
|
||||
problems.append(f"{rel}: backends {servers}")
|
||||
if "- --web.listen-address=127.0.0.1:19090\n" not in _block(compose, "prometheus"):
|
||||
problems.append("compose.yaml: prometheus listens outside loopback")
|
||||
for rel, port in ((LOKI_YAML, "13100"), (TEMPO_YAML, "13200")):
|
||||
server = _block(_read(root, rel), "server", 0)
|
||||
for needed in (
|
||||
"http_listen_address: 127.0.0.1\n",
|
||||
f"http_listen_port: {port}\n",
|
||||
"grpc_listen_address: 127.0.0.1\n",
|
||||
):
|
||||
if needed not in server:
|
||||
problems.append(f"{rel}: server without {needed.strip()}")
|
||||
tempo = _read(root, TEMPO_YAML)
|
||||
if "endpoint: 127.0.0.1:14318\n" not in tempo or "0.0.0.0" in tempo:
|
||||
problems.append(f"{TEMPO_YAML}: OTLP receiver outside loopback")
|
||||
if "stream_over_http_enabled: false\n" not in tempo:
|
||||
problems.append(f"{TEMPO_YAML}: streaming over HTTP is on")
|
||||
return problems
|
||||
|
||||
|
||||
def scrape_problems(root: Path) -> list[str]:
|
||||
tls = (
|
||||
" scheme: https\n tls_config:\n ca_file: /run/secrets/ca.crt\n"
|
||||
" cert_file: /run/secrets/prometheus-client.crt\n"
|
||||
" key_file: /run/secrets/prometheus-client.key\n"
|
||||
" min_version: TLS13\n"
|
||||
)
|
||||
problems = []
|
||||
for rel in SCRAPES:
|
||||
jobs = _read(root, rel).split(" - job_name: ")[1:]
|
||||
targets = {}
|
||||
for job in jobs:
|
||||
name = job.split("\n", 1)[0]
|
||||
targets[name] = re.findall(r'targets: \["(\S+)"\]', job)
|
||||
if name == "prometheus":
|
||||
continue
|
||||
if tls not in job:
|
||||
problems.append(f"{rel}: job {name} without https and its identity")
|
||||
if targets != {
|
||||
"messenger": ["otel-collector:8889"],
|
||||
"otel-collector": ["otel-collector:8888"],
|
||||
"loki": ["loki:3100"],
|
||||
"tempo": ["tempo:3200"],
|
||||
"prometheus": ["127.0.0.1:19090"],
|
||||
}:
|
||||
problems.append(f"{rel}: targets {targets}")
|
||||
if "insecure_skip_verify" in "".join(jobs):
|
||||
problems.append(f"{rel}: verification is off")
|
||||
return problems
|
||||
|
||||
|
||||
def collector_problems(root: Path) -> list[str]:
|
||||
text = _read(root, COLLECTOR)
|
||||
problems = []
|
||||
pair = (
|
||||
"{0}ca_file: /run/secrets/ca.crt\n"
|
||||
"{0}cert_file: /run/secrets/otel-collector-client.crt\n"
|
||||
"{0}key_file: /run/secrets/otel-collector-client.key\n"
|
||||
)
|
||||
for name, endpoint in (
|
||||
("otlp_http/loki", "https://loki:3100/otlp"),
|
||||
("otlp_http/tempo", "https://tempo:4318"),
|
||||
):
|
||||
block = _block(text, name)
|
||||
tls = " tls:\n" + pair.format(" " * 6) + ' min_version: "1.3"\n'
|
||||
if f" endpoint: {endpoint}\n" not in block or tls not in block:
|
||||
problems.append(f"{COLLECTOR}: exporter {name}")
|
||||
scrape = _block(text, "prometheus/haproxy")
|
||||
for needed in (
|
||||
" scheme: https\n",
|
||||
" tls_config:\n" + pair.format(" " * 12),
|
||||
" server_name: ingress\n min_version: TLS13\n",
|
||||
'- targets: ["haproxy:8404"]\n',
|
||||
):
|
||||
if needed not in scrape:
|
||||
problems.append(f"{COLLECTOR}: scrape of the LB without {needed!r}")
|
||||
if "insecure" in text:
|
||||
problems.append(f"{COLLECTOR}: verification is off")
|
||||
if " endpoint: 127.0.0.1:18889\n" not in _block(text, "prometheus"):
|
||||
problems.append(f"{COLLECTOR}: exporter prometheus outside loopback")
|
||||
if "host: 127.0.0.1\n port: 18888\n" not in text:
|
||||
problems.append(f"{COLLECTOR}: own metrics outside loopback")
|
||||
return problems
|
||||
|
||||
|
||||
def grafana_problems(root: Path) -> list[str]:
|
||||
raw = (root / SOURCES).read_text(encoding="utf-8")
|
||||
problems = []
|
||||
if "BEGIN " in raw or "tlsSkipVerify: true" in raw:
|
||||
problems.append(f"{SOURCES}: PEM content or verification is off")
|
||||
secure = (
|
||||
" secureJsonData:\n"
|
||||
" tlsCACert: $__file{/run/secrets/ca.crt}\n"
|
||||
" tlsClientCert: $__file{/run/secrets/grafana-client.crt}\n"
|
||||
" tlsClientKey: $__file{/run/secrets/grafana-client.key}\n"
|
||||
" jsonData:\n tlsAuth: true\n tlsAuthWithCACert: true\n"
|
||||
)
|
||||
urls = {}
|
||||
for source in _read(root, SOURCES).split("\n - name: ")[1:]:
|
||||
uid = re.findall(r"^ uid: (\S+)$", source, re.M)[0]
|
||||
urls[uid] = re.findall(r"^ url: (\S+)$", source, re.M)[0]
|
||||
if secure not in source:
|
||||
problems.append(f"{SOURCES}: source {uid} without mTLS")
|
||||
off = " streamingEnabled:\n search: false\n metrics: false\n"
|
||||
if uid == "traces" and off not in source:
|
||||
problems.append(f"{SOURCES}: Tempo streaming is on")
|
||||
if urls != {
|
||||
"metrics": "https://prometheus:9090",
|
||||
"logs": "https://loki:3100",
|
||||
"traces": "https://tempo:3200",
|
||||
}:
|
||||
problems.append(f"{SOURCES}: urls {urls}")
|
||||
compose = _block(_read(root, "compose.yaml"), "grafana")
|
||||
for needed in (
|
||||
"GF_SERVER_PROTOCOL: https\n",
|
||||
"GF_SERVER_CERT_FILE: /run/secrets/grafana.crt\n",
|
||||
"GF_SERVER_CERT_KEY: /run/secrets/grafana.key\n",
|
||||
'- "127.0.0.1:${GRAFANA_HOST_PORT:-3180}:3000"\n',
|
||||
'"--cacert", "/run/secrets/ca.crt"',
|
||||
"https://localhost:3000/api/health",
|
||||
):
|
||||
if needed not in compose:
|
||||
problems.append(f"compose.yaml: grafana without {needed.strip()}")
|
||||
return problems
|
||||
|
||||
|
||||
def files_problems(root: Path) -> list[str]:
|
||||
"""Файлы PKI новых identity — только своим сервисам."""
|
||||
compose = _read(root, "compose.yaml")
|
||||
services = compose[compose.index("\nservices:") : compose.index("\nnetworks:")]
|
||||
problems = []
|
||||
got = {
|
||||
name: set(_items(_block(services, name), "secrets"))
|
||||
for name in re.findall(r"^ ([a-z0-9-]+):\n", services, re.M)
|
||||
}
|
||||
for service, files in FILES.items():
|
||||
want = set(files)
|
||||
if files:
|
||||
want |= {"ca.crt"} | (
|
||||
{"crl.pem"} if service.endswith("-gateway") else set()
|
||||
)
|
||||
if got.get(service) != want:
|
||||
problems.append(f"compose.yaml: {service} secrets {got.get(service)}")
|
||||
for name in sorted(set().union(*FILES.values())):
|
||||
owners = {service for service, files in got.items() if name in files}
|
||||
expected = {service for service, files in FILES.items() if name in files}
|
||||
if owners != expected:
|
||||
problems.append(f"compose.yaml: {name} is given to {sorted(owners)}")
|
||||
if f" {name}:\n file: ${{PKI_STAND_DIR:-./.pki/stand}}/{name}" not in (
|
||||
compose
|
||||
):
|
||||
problems.append(f"compose.yaml: no secret {name}")
|
||||
return problems
|
||||
|
||||
|
||||
CHECKS = (
|
||||
allowlist_problems,
|
||||
rights_problems,
|
||||
bind_problems,
|
||||
storage_problems,
|
||||
scrape_problems,
|
||||
collector_problems,
|
||||
grafana_problems,
|
||||
files_problems,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("check", CHECKS, ids=lambda check: check.__name__)
|
||||
def test_configuration(check) -> None:
|
||||
assert check(ROOT) == []
|
||||
|
||||
|
||||
def test_identity_rows() -> None:
|
||||
rows = _identities(ROOT)
|
||||
expected = {
|
||||
"loki": ("server", ["loki"], "bundle"),
|
||||
"tempo": ("server", ["tempo"], "bundle"),
|
||||
"prometheus": ("server", ["prometheus"], "bundle"),
|
||||
"grafana": ("server", ["grafana", "localhost"], "split"),
|
||||
"otel-collector-client": ("client", ["otel-collector"], "split"),
|
||||
"prometheus-client": ("client", ["prometheus"], "split"),
|
||||
"grafana-client": ("client", ["grafana"], "split"),
|
||||
}
|
||||
# по именам, а не «последние семь»: следующие переносы дописывают строки
|
||||
assert {name: rows.get(name) for name in expected} == expected
|
||||
|
||||
|
||||
def test_lb_statistics_only_on_loopback() -> None:
|
||||
health = _sections(ROOT, LB)[("frontend", "health")]
|
||||
assert "bind 127.0.0.1:8405" in health
|
||||
assert "monitor-uri /lb/ready" in health
|
||||
assert "stats uri /stats" in health
|
||||
# все читатели статистики — на loopback-слушателе
|
||||
for rel in ("compose.yaml", "scripts/lab7.py", "bench/common.py"):
|
||||
text = (ROOT / rel).read_text(encoding="utf-8")
|
||||
assert "/dev/tcp/127.0.0.1/8404" not in text, rel
|
||||
assert "/dev/tcp/127.0.0.1/8405" in text, rel
|
||||
|
||||
|
||||
def test_stopped_collector_is_a_closed_connection() -> None:
|
||||
"""503 шлюза SDK не считает исключением экспорта: у приёма OTLP вместо него —
|
||||
закрытие без ответа; метрики отвечают 503 (отказ scrape)."""
|
||||
sections = _sections(ROOT, OTEL)
|
||||
assert "errorfile 503 /dev/null" in sections[("backend", "collector")]
|
||||
for name in ("collector_own", "collector_app"):
|
||||
assert not any("errorfile" in line for line in sections[("backend", name)])
|
||||
|
||||
|
||||
def test_check_covers_the_same_allowlists() -> None:
|
||||
"""`telemetry-tls-check` ждёт те же allowlist, что у конфигураций, а каналы
|
||||
проверки — все TLS-порты шлюзов, кроме приёма OTLP и ingress."""
|
||||
spec = importlib.util.spec_from_file_location("lab7", ROOT / "scripts" / "lab7.py")
|
||||
assert spec is not None
|
||||
assert spec.loader is not None
|
||||
lab7 = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(lab7)
|
||||
files = {
|
||||
"otel-gateway": OTEL,
|
||||
"loki-gateway": LOKI,
|
||||
"tempo-gateway": TEMPO,
|
||||
"prometheus-gateway": PROM,
|
||||
"haproxy": LB,
|
||||
}
|
||||
ports = set()
|
||||
for service, rel in files.items():
|
||||
got = lab7._tm_allowlists(
|
||||
{"volumes": [{"target": "/x/haproxy.cfg", "source": str(ROOT / rel)}]}
|
||||
)
|
||||
assert got == lab7.TB_ALLOWLISTS[service]
|
||||
for (kind, name), lines in _sections(ROOT, rel).items():
|
||||
for line in lines:
|
||||
if kind == "frontend" and line.startswith("bind :"):
|
||||
ports.add((service, int(line.split()[1][1:]), name))
|
||||
covered = {(c["host"], c["port"]) for c in lab7.TB_CHANNELS}
|
||||
hosts = {service: tenant for service, tenant, _, _ in lab7.TB_NAMESPACES}
|
||||
assert {
|
||||
(hosts[service], port)
|
||||
for service, port, name in ports
|
||||
if name not in ("otlp", "entry")
|
||||
} == covered
|
||||
|
||||
|
||||
def _grafana_reaches(rel: str, frontend: str, path: str) -> bool:
|
||||
"""Решение шлюза для `GET <path>` от grafana: отказ `unsafe_path`, затем список
|
||||
чтения. Регулярные выражения HAProxy (PCRE2) здесь — те же, что для `re`."""
|
||||
refuse, read = [], []
|
||||
for line in _sections(ROOT, rel)[("frontend", frontend)]:
|
||||
if not line.startswith("acl "):
|
||||
continue
|
||||
_, name, kind, *words = line.split()
|
||||
if name == "unsafe_path" and kind == "path_sub":
|
||||
refuse += [re.escape(word) for word in words]
|
||||
elif name == "unsafe_path":
|
||||
refuse.append(" ".join(words))
|
||||
elif name == "read_path":
|
||||
read.append(" ".join(words))
|
||||
return not any(re.search(r, path) for r in refuse) and any(
|
||||
re.search(r, path) for r in read
|
||||
)
|
||||
|
||||
|
||||
REACHES = (
|
||||
(PROM, "prometheus_in", "/api/v1/query"),
|
||||
(PROM, "prometheus_in", "/api/v1/label/__name__/values"),
|
||||
(PROM, "prometheus_in", "/api/v1/status/buildinfo"),
|
||||
(PROM, "prometheus_in", "/api/v1/alerts"),
|
||||
(PROM, "prometheus_in", "/api/v1/series"),
|
||||
(LOKI, "loki_in", "/loki/api/v1/label/service_name/values"),
|
||||
(LOKI, "loki_in", "/loki/api/v1/query_range"),
|
||||
(TEMPO, "query_in", "/api/v2/search/tag/.service.name/values"),
|
||||
(TEMPO, "query_in", "/api/v2/search/tag/span%3Aname/values"),
|
||||
(TEMPO, "query_in", "/api/v2/traces/0123456789abcdef"),
|
||||
)
|
||||
REFUSED = (
|
||||
*((PROM, "prometheus_in", path) for path in (
|
||||
"/api/v1/admin/tsdb/snapshot",
|
||||
"/api/v1/%61dmin/tsdb/snapshot",
|
||||
"/api/v1/admin%2Ftsdb/snapshot",
|
||||
"/api/v1/ADMIN/tsdb/snapshot",
|
||||
"/api/v1/write",
|
||||
"/api/v1/otlp/v1/metrics",
|
||||
"/api/v1/query/../admin/tsdb/snapshot",
|
||||
"/api/v1//admin/tsdb/snapshot",
|
||||
"/api/v1/query/",
|
||||
"/federate",
|
||||
"/metrics",
|
||||
)),
|
||||
*((LOKI, "loki_in", path) for path in (
|
||||
"/loki/api/v1/label/..%2F..%2Fconfig/values",
|
||||
"/loki/api/v1/labels/../../../config",
|
||||
"/loki/api/v1/label/%2e%2e/values",
|
||||
"/loki/api/v1/push",
|
||||
"/loki/api/v1/delete",
|
||||
)),
|
||||
*((TEMPO, "query_in", path) for path in (
|
||||
"/api/search/%2F..%2F..%2Fstatus/config",
|
||||
"/api/v2/search/tag/span%253Aname/values",
|
||||
"/api/v2/search/tag/%3A%2e%2e/values",
|
||||
"/api/search/../../status/config",
|
||||
"/api/search/./x",
|
||||
"/api/search/..",
|
||||
"/api/search//x",
|
||||
"/status/config",
|
||||
)),
|
||||
) # fmt: skip
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("rel", "frontend", "path", "reaches"),
|
||||
[*((*row, True) for row in REACHES), *((*row, False) for row in REFUSED)],
|
||||
)
|
||||
def test_gateway_path_decision(
|
||||
rel: str, frontend: str, path: str, reaches: bool
|
||||
) -> None:
|
||||
assert _grafana_reaches(rel, frontend, path) is reaches
|
||||
|
||||
|
||||
# --- контроль: копия с ошибкой — красная проверка --------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("check", "rel", "old", "new"),
|
||||
[
|
||||
(allowlist_problems, LOKI, "DNS:prometheus }", "DNS:prometheus DNS:haproxy }"),
|
||||
(allowlist_problems, OTEL, "unless { ssl_c_san -m str DNS:prometheus }",
|
||||
"unless { ssl_c_san -m str DNS:prometheus DNS:grafana }"),
|
||||
(allowlist_problems, IDENTITIES, "client grafana split",
|
||||
"client grafana,localhost split"),
|
||||
(rights_problems, LOKI, " http-request allow if id_grafana METH_GET read",
|
||||
" http-request allow if id_grafana METH_POST { path /otlp/v1/logs }\n"
|
||||
" http-request allow if id_grafana METH_GET read"),
|
||||
(rights_problems, PROM, " http-request deny deny_status 403 hdr "
|
||||
"X-Gateway-Refused prometheus-gateway if unsafe_path\n", ""),
|
||||
(rights_problems, LOKI, "path_sub % //", "path_sub %"),
|
||||
(rights_problems, PROM, "METH_GET read_path", "METH_GET { path_beg /api/v1/ }"),
|
||||
(rights_problems, TEMPO, "path_reg ^/api/(echo", "path_reg /api/(echo"),
|
||||
(rights_problems, LB, "if METH_GET { path /metrics }", "if METH_GET"),
|
||||
(bind_problems, TEMPO, "verify required", "verify optional"),
|
||||
(bind_problems, OTEL, "bind :8888 ssl crt /run/secrets/otel-collector.pem "
|
||||
"ca-file /run/secrets/ca.crt crl-file /run/secrets/crl.pem",
|
||||
"bind :8888 ssl crt /run/secrets/otel-collector.pem "
|
||||
"ca-file /run/secrets/ca.crt"),
|
||||
(bind_problems, LB, "bind 127.0.0.1:8405", "bind :8405"),
|
||||
(storage_problems, LOKI_YAML, "http_listen_address: 127.0.0.1",
|
||||
"http_listen_address: 0.0.0.0"),
|
||||
(storage_problems, TEMPO_YAML, "grpc_listen_address: 127.0.0.1\n", ""),
|
||||
(storage_problems, "compose.yaml", "network_mode: service:tempo-gateway",
|
||||
"networks: [telemetry]"),
|
||||
(storage_problems, "compose.yaml", "--web.listen-address=127.0.0.1:19090",
|
||||
"--web.listen-address=0.0.0.0:19090"),
|
||||
(scrape_problems, SCRAPES[0], " - job_name: loki\n scheme: https",
|
||||
" - job_name: loki\n scheme: http"),
|
||||
(collector_problems, COLLECTOR, "https://loki:3100", "http://loki:3100"),
|
||||
(collector_problems, COLLECTOR, "server_name: ingress", "server_name: api"),
|
||||
(grafana_problems, SOURCES, "https://tempo:3200", "http://tempo:3200"),
|
||||
(grafana_problems, SOURCES, " tlsAuthWithCACert: true\n", ""),
|
||||
(grafana_problems, "compose.yaml", "GF_SERVER_PROTOCOL: https",
|
||||
"GF_SERVER_PROTOCOL: http"),
|
||||
(files_problems, "compose.yaml", " - otel-collector-client.key\n",
|
||||
" - otel-collector-client.key\n - grafana-client.key\n"),
|
||||
],
|
||||
) # fmt: skip
|
||||
def test_control_is_red(tmp_path: Path, check, rel: str, old: str, new: str) -> None:
|
||||
for name in (*PEMS, LOKI_YAML, TEMPO_YAML, COLLECTOR, SOURCES, *SCRAPES,
|
||||
IDENTITIES, "compose.yaml"): # fmt: skip
|
||||
target = tmp_path / name
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(ROOT / name, target)
|
||||
assert check(tmp_path) == []
|
||||
text = (tmp_path / rel).read_text(encoding="utf-8")
|
||||
assert old in text, (rel, old)
|
||||
(tmp_path / rel).write_text(text.replace(old, new, 1), encoding="utf-8")
|
||||
problems = check(tmp_path)
|
||||
assert any(rel in problem for problem in problems), problems
|
||||
@@ -0,0 +1,637 @@
|
||||
"""Лаба 7: mTLS отправки телеметрии в Collector (перенос telemetry-mtls).
|
||||
|
||||
Без стенда. Настройки `TELEMETRY_*_FILE` и проверка точки входа
|
||||
(`src/client_tls.py`: только при включённой телеметрии), сессия экспортёра
|
||||
(`src/telemetry/sdk.py`) и настоящие рукопожатия со своим HTTPS-сервером на
|
||||
loopback, который, как шлюз, требует сертификат клиента: leaf выпускает
|
||||
`infra/pki/pki.sh` во временный каталог (без OpenSSL ≥ 3 — пропуск с причиной).
|
||||
Согласованность allowlist `infra/otel/gateway.cfg` со списком identity, выдача
|
||||
файлов сервисам в `compose.yaml`. Allowlist, пути и отказы на настоящем шлюзе —
|
||||
`make telemetry-tls-check`.
|
||||
"""
|
||||
|
||||
import http.server
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
from collections.abc import Iterator
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
from opentelemetry.trace import SpanKind
|
||||
|
||||
from src import telemetry
|
||||
from src.client_tls import (
|
||||
API_STORAGES,
|
||||
CLEANER_STORAGES,
|
||||
MIGRATION_STORAGES,
|
||||
RELAY_STORAGES,
|
||||
REPLAY_STORAGES,
|
||||
WORKER_STORAGES,
|
||||
check_or_exit,
|
||||
client_tls_problems,
|
||||
)
|
||||
from src.config import ConfigError, Settings
|
||||
from src.config import Telemetry as TelemetrySettings
|
||||
from src.constants import SERVICE_API
|
||||
from src.telemetry import sdk
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PKI_DIR = ROOT / "infra" / "pki"
|
||||
GATEWAY = ROOT / "infra" / "otel" / "gateway.cfg"
|
||||
COLLECTOR_YAML = ROOT / "infra" / "otel" / "collector.yaml"
|
||||
COMPOSE = ROOT / "compose.yaml"
|
||||
NAME = "otel-collector"
|
||||
TRACES = "/v1/traces"
|
||||
# identity приёма: строка списка → DNS SAN, который видит шлюз
|
||||
ALLOWED = {"api-client": "api", "worker": "worker", "relay": "relay"}
|
||||
TELEMETRY_FILES = ("TELEMETRY_CERT_FILE", "TELEMETRY_KEY_FILE", "TELEMETRY_CRL_FILE")
|
||||
|
||||
|
||||
def _pki(env: dict[str, str], *args: str) -> None:
|
||||
done = subprocess.run(
|
||||
["sh", str(PKI_DIR / "pki.sh"), *args],
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
# пропуск — только без OpenSSL 3+ (первый вызов, stand); дальше — ошибка
|
||||
if done.returncode != 0 and args[0] == "stand":
|
||||
pytest.skip(f"infra/pki/pki.sh stand failed (OpenSSL 3+?): {done.stderr}")
|
||||
assert done.returncode == 0, done.stderr
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def pki(tmp_path_factory: pytest.TempPathFactory) -> dict:
|
||||
"""Файлы стенда, копия CRL до отзыва `otel-collector` (`crl-before.pem`) и
|
||||
CRL после него, файлы другого оператора (`other`)."""
|
||||
base = tmp_path_factory.mktemp("telemetry-pki")
|
||||
env = {
|
||||
**os.environ,
|
||||
"PKI_OPERATOR_DIR": str(base / "operator"),
|
||||
"PKI_STAND_DIR": str(base / "stand"),
|
||||
}
|
||||
_pki(env, "stand")
|
||||
stand = base / "stand"
|
||||
(base / "crl-before.pem").write_bytes((stand / "crl.pem").read_bytes())
|
||||
_pki(env, "revoke", "otel-collector")
|
||||
(base / "crl-after.pem").write_bytes((stand / "crl.pem").read_bytes())
|
||||
_pki(
|
||||
{
|
||||
**env,
|
||||
"PKI_OPERATOR_DIR": str(base / "other-operator"),
|
||||
"PKI_STAND_DIR": str(base / "other"),
|
||||
},
|
||||
"stand",
|
||||
)
|
||||
return {"base": base, "stand": stand, "other": base / "other"}
|
||||
|
||||
|
||||
def _env(pki: dict, identity: str = "api-client", **extra: str) -> dict[str, str]:
|
||||
"""Окружение процесса со включённой телеметрией (и всем остальным)."""
|
||||
stand = pki["stand"]
|
||||
return {
|
||||
"CLIENT_TLS_CA_FILE": str(stand / "ca.crt"),
|
||||
"DB_HOST": "postgres",
|
||||
"CACHE_HOST": "valkey",
|
||||
"S3_ENDPOINT": "https://s3:8333",
|
||||
"BROKER_HOST": "rabbitmq",
|
||||
"BROKER_CERT_FILE": str(stand / "relay.crt"),
|
||||
"BROKER_KEY_FILE": str(stand / "relay.key"),
|
||||
"BROKER_CRL_FILE": str(stand / "crl.pem"),
|
||||
"OTEL_EXPORTER_OTLP_ENDPOINT": f"https://{NAME}:4318",
|
||||
"TELEMETRY_CERT_FILE": str(stand / f"{identity}.crt"),
|
||||
"TELEMETRY_KEY_FILE": str(stand / f"{identity}.key"),
|
||||
"TELEMETRY_CRL_FILE": str(pki["base"] / "crl-before.pem"),
|
||||
# вход в OpenBao (перенос openbao-secrets) — той же парой
|
||||
"BAO_CERT_FILE": str(stand / f"{identity}.crt"),
|
||||
"BAO_KEY_FILE": str(stand / f"{identity}.key"),
|
||||
"BAO_CRL_FILE": str(stand / "crl.pem"),
|
||||
**extra,
|
||||
}
|
||||
|
||||
|
||||
def _telemetry(pki: dict, identity: str = "api-client", **extra: str):
|
||||
return TelemetrySettings.from_env(_env(pki, identity, **extra))
|
||||
|
||||
|
||||
def _context(pki: dict, settings: TelemetrySettings) -> ssl.SSLContext:
|
||||
return sdk.export_context(settings, str(pki["stand"] / "ca.crt"))
|
||||
|
||||
|
||||
# --- настройки ---------------------------------------------------------------
|
||||
|
||||
|
||||
def test_endpoint_is_https_only() -> None:
|
||||
for value in ("http://otel-collector:4318", "HTTP://otel-collector:4318"):
|
||||
with pytest.raises(ConfigError, match="OTEL_EXPORTER_OTLP_ENDPOINT"):
|
||||
Settings.from_env({"OTEL_EXPORTER_OTLP_ENDPOINT": value})
|
||||
settings = Settings.from_env(
|
||||
{"OTEL_EXPORTER_OTLP_ENDPOINT": "https://otel-collector:4318"}
|
||||
)
|
||||
assert settings.telemetry.enabled
|
||||
assert settings.telemetry.endpoint == "https://otel-collector:4318"
|
||||
|
||||
|
||||
def test_file_settings_and_otel_names_not_read() -> None:
|
||||
parsed = TelemetrySettings.from_env(
|
||||
{
|
||||
"TELEMETRY_CERT_FILE": " /run/secrets/api-client.crt ",
|
||||
"TELEMETRY_KEY_FILE": "/run/secrets/api-client.key",
|
||||
"TELEMETRY_CRL_FILE": "/run/secrets/crl.pem",
|
||||
}
|
||||
)
|
||||
assert parsed.cert_file == "/run/secrets/api-client.crt"
|
||||
assert parsed.key_file == "/run/secrets/api-client.key"
|
||||
assert parsed.crl_file == "/run/secrets/crl.pem"
|
||||
other = TelemetrySettings.from_env(
|
||||
{
|
||||
"OTEL_EXPORTER_OTLP_CERTIFICATE": "/x/ca.crt",
|
||||
"OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE": "/x/client.crt",
|
||||
"OTEL_EXPORTER_OTLP_CLIENT_KEY": "/x/client.key",
|
||||
}
|
||||
)
|
||||
assert (other.cert_file, other.key_file, other.crl_file) == ("", "", "")
|
||||
|
||||
|
||||
# --- проверка точки входа ------------------------------------------------------
|
||||
|
||||
|
||||
def test_who_checks_telemetry() -> None:
|
||||
for storages in (API_STORAGES, WORKER_STORAGES, RELAY_STORAGES):
|
||||
assert "telemetry" in storages
|
||||
# replay, уборщик и миграции SDK не собирают: файлы им не нужны
|
||||
for storages in (REPLAY_STORAGES, CLEANER_STORAGES, MIGRATION_STORAGES):
|
||||
assert "telemetry" not in storages
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"storages", [API_STORAGES, WORKER_STORAGES, RELAY_STORAGES], ids=["a", "w", "r"]
|
||||
)
|
||||
def test_enabled_telemetry_requires_files(pki: dict, storages: tuple) -> None:
|
||||
assert client_tls_problems(Settings.from_env(_env(pki)), storages) == []
|
||||
empty = dict.fromkeys(TELEMETRY_FILES, "")
|
||||
problems = client_tls_problems(Settings.from_env(_env(pki, **empty)), storages)
|
||||
assert problems == list(TELEMETRY_FILES)
|
||||
# выключенная телеметрия (консоль, временные стенды) файлов не требует
|
||||
off = _env(pki, OTEL_SDK_DISABLED="true", **empty)
|
||||
assert client_tls_problems(Settings.from_env(off), storages) == []
|
||||
none = _env(pki, OTEL_EXPORTER_OTLP_ENDPOINT="", **empty)
|
||||
assert client_tls_problems(Settings.from_env(none), storages) == []
|
||||
|
||||
|
||||
def test_replay_does_not_check_telemetry(pki: dict) -> None:
|
||||
broken = _env(pki, **dict.fromkeys(TELEMETRY_FILES, "/missing"))
|
||||
settings = Settings.from_env(broken)
|
||||
assert client_tls_problems(settings, REPLAY_STORAGES) == []
|
||||
assert client_tls_problems(settings, RELAY_STORAGES) == list(TELEMETRY_FILES)
|
||||
|
||||
|
||||
def test_problems_on_real_files(pki: dict, tmp_path: Path) -> None:
|
||||
stand = pki["stand"]
|
||||
broken = tmp_path / "broken.pem"
|
||||
broken.write_text("not pem\n", encoding="ascii")
|
||||
cases = {
|
||||
"TELEMETRY_CERT_FILE": [pki["base"] / "crl-before.pem", broken],
|
||||
# ключ другого сертификата, не ключ, нет файла
|
||||
"TELEMETRY_KEY_FILE": [stand / "worker.key", broken, tmp_path / "missing"],
|
||||
# файл с сертификатом вместо CRL, мусор, нет файла
|
||||
"TELEMETRY_CRL_FILE": [stand / "ca.crt", broken, tmp_path / "missing"],
|
||||
}
|
||||
for variable, paths in cases.items():
|
||||
for path in paths:
|
||||
settings = Settings.from_env(_env(pki, **{variable: str(path)}))
|
||||
assert client_tls_problems(settings, API_STORAGES) == [variable], path.name
|
||||
|
||||
|
||||
def test_check_or_exit_names_only(
|
||||
pki: dict, tmp_path: Path, capsys: pytest.CaptureFixture[str]
|
||||
) -> None:
|
||||
env = _env(
|
||||
pki,
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT="https://172.18.0.5:4318",
|
||||
TELEMETRY_KEY_FILE=str(tmp_path / "secret-dir" / "api-client.key"),
|
||||
)
|
||||
with pytest.raises(SystemExit) as exit_info:
|
||||
check_or_exit(Settings.from_env(env), API_STORAGES)
|
||||
assert exit_info.value.code == 2
|
||||
err = capsys.readouterr().err
|
||||
assert "OTEL_EXPORTER_OTLP_ENDPOINT, TELEMETRY_KEY_FILE" in err
|
||||
assert "secret-dir" not in err
|
||||
assert "172.18.0.5" not in err
|
||||
|
||||
|
||||
@pytest.mark.parametrize("module", ["src", "src.worker", "src.relay"])
|
||||
def test_entry_points_exit_2(pki: dict, module: str) -> None:
|
||||
"""Процесс целиком: включённая телеметрия без файла CRL — код 2 и имя
|
||||
переменной, до соединений."""
|
||||
env = {
|
||||
"PATH": os.environ["PATH"],
|
||||
**_env(pki, TELEMETRY_CRL_FILE=str(pki["base"] / "no-such-crl.pem")),
|
||||
}
|
||||
done = subprocess.run(
|
||||
[sys.executable, "-m", module],
|
||||
cwd=ROOT,
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
timeout=60,
|
||||
)
|
||||
assert done.returncode == 2, done.stderr
|
||||
assert "invalid client TLS settings: TELEMETRY_CRL_FILE" in done.stderr
|
||||
assert "no-such-crl" not in done.stderr
|
||||
|
||||
|
||||
def test_check_module_loads_neither_requests_nor_sdk() -> None:
|
||||
"""Модуль проверки — только stdlib; точки входа до `sdk.start` не грузят
|
||||
экспортёр, `requests` и наш `sdk` (метрики `opentelemetry.sdk` тянет сам
|
||||
FastAPI — это не наш SDK)."""
|
||||
for modules, forbidden in (
|
||||
("src.client_tls", ("requests", "urllib3", "opentelemetry")),
|
||||
(
|
||||
"src.relay.main, src.worker.main, src.main",
|
||||
("requests", "src.telemetry.sdk", "opentelemetry.exporter"),
|
||||
),
|
||||
):
|
||||
code = (
|
||||
f"import sys; import {modules};"
|
||||
f"print([m for m in sys.modules if m.startswith({forbidden!r})])"
|
||||
)
|
||||
done = subprocess.run(
|
||||
[sys.executable, "-c", code],
|
||||
cwd=ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
timeout=60,
|
||||
)
|
||||
assert done.stdout.strip() == "[]", modules
|
||||
|
||||
|
||||
# --- контекст и рукопожатия ------------------------------------------------------
|
||||
|
||||
|
||||
class _Gateway:
|
||||
"""HTTPS на loopback «как шлюз»: TLS 1.3, обязательный сертификат клиента CA
|
||||
стенда; `seen` — (SAN клиента, версия TLS, путь) принятых запросов."""
|
||||
|
||||
def __init__(self, stand: Path, ca: Path, name: str = NAME) -> None:
|
||||
self.seen: list[tuple[str, str, str]] = []
|
||||
self.context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
self.context.minimum_version = ssl.TLSVersion.TLSv1_3
|
||||
self.context.load_cert_chain(stand / f"{name}.crt", stand / f"{name}.key")
|
||||
self.context.load_verify_locations(cafile=ca)
|
||||
self.context.verify_mode = ssl.CERT_REQUIRED
|
||||
seen = self.seen
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def do_POST(self) -> None: # noqa: N802 - имя задаёт http.server
|
||||
self.rfile.read(int(self.headers.get("Content-Length") or 0))
|
||||
san = dict(self.connection.getpeercert().get("subjectAltName", ()))
|
||||
seen.append(
|
||||
(san.get("DNS", ""), str(self.connection.version()), self.path)
|
||||
)
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/x-protobuf")
|
||||
self.send_header("Content-Length", "0")
|
||||
self.end_headers()
|
||||
|
||||
def log_message(self, *_args: object) -> None:
|
||||
return None
|
||||
|
||||
class Server(http.server.ThreadingHTTPServer):
|
||||
daemon_threads = True
|
||||
|
||||
def handle_error(self, *_args: object) -> None:
|
||||
return None
|
||||
|
||||
self.server = Server(("127.0.0.1", 0), Handler)
|
||||
self.port = self.server.server_address[1]
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _gateway(pki: dict, owner: str = "stand", name: str = NAME) -> Iterator[_Gateway]:
|
||||
gateway = _Gateway(pki[owner], pki["stand"] / "ca.crt", name)
|
||||
gateway.server.socket = gateway.context.wrap_socket(
|
||||
gateway.server.socket, server_side=True, do_handshake_on_connect=False
|
||||
)
|
||||
threading.Thread(target=gateway.server.serve_forever, daemon=True).start()
|
||||
try:
|
||||
yield gateway
|
||||
finally:
|
||||
gateway.server.shutdown()
|
||||
gateway.server.server_close()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def resolve(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Имена `otel-collector` и `wrong-name` — на loopback (как DNS стенда)."""
|
||||
original = socket.getaddrinfo
|
||||
|
||||
def getaddrinfo(host, *args, **kwargs):
|
||||
if host in (NAME, "wrong-name"):
|
||||
host = "127.0.0.1"
|
||||
return original(host, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(socket, "getaddrinfo", getaddrinfo)
|
||||
|
||||
|
||||
def _post(session: requests.Session, port: int, host: str = NAME, **kwargs) -> str:
|
||||
try:
|
||||
response = session.post(
|
||||
f"https://{host}:{port}{TRACES}", data=b"", timeout=5, **kwargs
|
||||
)
|
||||
except requests.exceptions.RequestException as error:
|
||||
return f"{type(error).__name__}: {error}"
|
||||
return str(response.status_code)
|
||||
|
||||
|
||||
def test_context_flags(pki: dict) -> None:
|
||||
context = _context(pki, _telemetry(pki))
|
||||
assert context.minimum_version == ssl.TLSVersion.TLSv1_3
|
||||
assert context.check_hostname is True
|
||||
assert context.verify_mode == ssl.CERT_REQUIRED
|
||||
assert context.verify_flags & ssl.VERIFY_X509_STRICT
|
||||
assert context.verify_flags & ssl.VERIFY_CRL_CHECK_LEAF
|
||||
assert context.cert_store_stats() == {"x509_ca": 1, "x509": 1, "crl": 1}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(("identity", "san"), ALLOWED.items())
|
||||
def test_process_presents_its_identity(pki: dict, identity: str, san: str) -> None:
|
||||
session = sdk.export_session(_context(pki, _telemetry(pki, identity)))
|
||||
with _gateway(pki) as gateway:
|
||||
assert _post(session, gateway.port) == "200"
|
||||
assert gateway.seen == [(san, "TLSv1.3", TRACES)]
|
||||
|
||||
|
||||
def test_sdk_exports_all_signals_over_mtls(pki: dict) -> None:
|
||||
"""SDK целиком (`sdk.start` без подмены экспортёров): трасса, запись и
|
||||
метрики приходят по mTLS парой процесса."""
|
||||
with _gateway(pki) as gateway:
|
||||
settings = _telemetry(
|
||||
pki, OTEL_EXPORTER_OTLP_ENDPOINT=f"https://{NAME}:{gateway.port}"
|
||||
)
|
||||
session = sdk.start(
|
||||
settings,
|
||||
service_name=SERVICE_API,
|
||||
instance_id="test-instance",
|
||||
ca_file=str(pki["stand"] / "ca.crt"),
|
||||
)
|
||||
assert session is not None
|
||||
try:
|
||||
with telemetry.root_span("probe", kind=SpanKind.SERVER, attributes={}):
|
||||
session.log_handler.emit(
|
||||
logging.LogRecord("src.x", 20, "x", 1, "probe", None, None)
|
||||
)
|
||||
session.flush()
|
||||
finally:
|
||||
assert session.shutdown(10.0)
|
||||
assert {path for _, _, path in gateway.seen} >= {
|
||||
"/v1/traces",
|
||||
"/v1/metrics",
|
||||
"/v1/logs",
|
||||
}
|
||||
assert {(san, version) for san, version, _ in gateway.seen} == {("api", "TLSv1.3")}
|
||||
|
||||
|
||||
def test_request_verify_cert_and_environment_do_not_change_context(
|
||||
pki: dict, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""`verify` и `cert` запроса и окружение (прокси, набор CA) не действуют:
|
||||
в контексте один CA, запрос идёт парой процесса напрямую."""
|
||||
monkeypatch.setenv("HTTPS_PROXY", "http://127.0.0.1:9")
|
||||
monkeypatch.setenv("REQUESTS_CA_BUNDLE", str(pki["other"] / "ca.crt"))
|
||||
missing = str(tmp_path / "missing.pem")
|
||||
context = _context(pki, _telemetry(pki))
|
||||
session = sdk.export_session(context)
|
||||
with _gateway(pki) as gateway:
|
||||
assert _post(session, gateway.port, verify=True) == "200"
|
||||
assert _post(session, gateway.port, verify=False) == "200"
|
||||
assert _post(session, gateway.port, cert=(missing, missing)) == "200"
|
||||
assert context.cert_store_stats()["x509_ca"] == 1
|
||||
assert context.verify_mode == ssl.CERT_REQUIRED
|
||||
assert [san for san, _, _ in gateway.seen] == ["api"] * 3
|
||||
# и выключенная запросом проверка чужой сервер не пускает
|
||||
with _gateway(pki, "other") as foreign:
|
||||
assert "certificate verify failed" in _post(
|
||||
sdk.export_session(context), foreign.port, verify=False
|
||||
)
|
||||
assert foreign.seen == []
|
||||
|
||||
|
||||
def test_files_read_once(pki: dict, tmp_path: Path) -> None:
|
||||
"""Файлы удалены после старта (`pki-stand` заменяет `crl.pem`, bind mount
|
||||
даёт ENOENT) — новые соединения проходят."""
|
||||
copies = tmp_path / "copies"
|
||||
copies.mkdir()
|
||||
for name in ("ca.crt", "worker.crt", "worker.key"):
|
||||
(copies / name).write_bytes((pki["stand"] / name).read_bytes())
|
||||
(copies / "crl.pem").write_bytes((pki["base"] / "crl-before.pem").read_bytes())
|
||||
settings = _telemetry(
|
||||
pki,
|
||||
TELEMETRY_CERT_FILE=str(copies / "worker.crt"),
|
||||
TELEMETRY_KEY_FILE=str(copies / "worker.key"),
|
||||
TELEMETRY_CRL_FILE=str(copies / "crl.pem"),
|
||||
)
|
||||
context = sdk.export_context(settings, str(copies / "ca.crt"))
|
||||
for path in copies.iterdir():
|
||||
path.unlink()
|
||||
with _gateway(pki) as gateway:
|
||||
assert _post(sdk.export_session(context), gateway.port) == "200"
|
||||
assert _post(sdk.export_session(context), gateway.port) == "200"
|
||||
assert [san for san, _, _ in gateway.seen] == ["worker"] * 2
|
||||
|
||||
|
||||
def test_foreign_collector_is_refused(pki: dict) -> None:
|
||||
context = _context(pki, _telemetry(pki))
|
||||
|
||||
def refused(gateway: _Gateway, reason: str, host: str = NAME) -> None:
|
||||
outcome = _post(sdk.export_session(context), gateway.port, host)
|
||||
assert outcome != "200"
|
||||
assert reason in outcome, outcome
|
||||
|
||||
# другой CA под тем же именем
|
||||
with _gateway(pki, "other") as gateway:
|
||||
refused(gateway, "certificate verify failed")
|
||||
assert gateway.seen == []
|
||||
# имя вне SAN и чужой сервер того же CA под именем Collector
|
||||
with _gateway(pki) as gateway:
|
||||
refused(gateway, "Hostname mismatch", "wrong-name")
|
||||
assert gateway.seen == []
|
||||
with _gateway(pki, name="postgres") as gateway:
|
||||
refused(gateway, "Hostname mismatch")
|
||||
assert gateway.seen == []
|
||||
# клиентский leaf сервером не станет (назначение)
|
||||
with _gateway(pki, name="api-client") as gateway:
|
||||
refused(gateway, "certificate verify failed")
|
||||
assert gateway.seen == []
|
||||
# сервер без TLS 1.3
|
||||
with _gateway(pki) as gateway:
|
||||
gateway.context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
gateway.context.maximum_version = ssl.TLSVersion.TLSv1_2
|
||||
refused(gateway, "")
|
||||
assert gateway.seen == []
|
||||
|
||||
|
||||
def test_revoked_gateway_is_refused(pki: dict) -> None:
|
||||
after = _telemetry(pki, TELEMETRY_CRL_FILE=str(pki["base"] / "crl-after.pem"))
|
||||
with _gateway(pki) as gateway:
|
||||
assert "certificate revoked" in _post(
|
||||
sdk.export_session(_context(pki, after)), gateway.port
|
||||
)
|
||||
assert gateway.seen == []
|
||||
assert (
|
||||
_post(sdk.export_session(_context(pki, _telemetry(pki))), gateway.port)
|
||||
== "200"
|
||||
)
|
||||
|
||||
|
||||
def test_without_crl_there_is_no_handshake(pki: dict) -> None:
|
||||
settings = _telemetry(pki, TELEMETRY_CRL_FILE="")
|
||||
with _gateway(pki) as gateway:
|
||||
assert "certificate verify failed" in _post(
|
||||
sdk.export_session(_context(pki, settings)), gateway.port
|
||||
)
|
||||
assert gateway.seen == []
|
||||
|
||||
|
||||
# --- согласованность конфигураций -------------------------------------------------
|
||||
|
||||
|
||||
def _identities() -> dict[str, tuple[str, list[str], str]]:
|
||||
rows = {}
|
||||
for line in (PKI_DIR / "identities.conf").read_text(encoding="utf-8").splitlines():
|
||||
if line.strip() and not line.startswith("#"):
|
||||
name, profile, sans, form = line.split()
|
||||
rows[name] = (profile, sans.split(","), form)
|
||||
return rows
|
||||
|
||||
|
||||
def _directives(text: str) -> str:
|
||||
return "\n".join(
|
||||
line for line in text.splitlines() if not line.lstrip().startswith("#")
|
||||
)
|
||||
|
||||
|
||||
def _otlp(config: str) -> str:
|
||||
"""Раздел приёма OTLP: у шлюза с переноса telemetry-backends-tls ещё порты
|
||||
метрик (их проверяет test_telemetry_backends_tls.py)."""
|
||||
return config[config.index("frontend otlp\n") : config.index("frontend metrics")]
|
||||
|
||||
|
||||
def test_gateway_allowlist_matches_identities() -> None:
|
||||
rows = _identities()
|
||||
assert rows["otel-collector"] == ("server", ["otel-collector"], "bundle")
|
||||
for row, san in ALLOWED.items():
|
||||
# у клиента ровно одно имя: шлюз сравнивает всю строку SAN
|
||||
assert rows[row][:2] == ("client", [san]), row
|
||||
config = _otlp(_directives(GATEWAY.read_text(encoding="utf-8")))
|
||||
lists = re.findall(r"ssl_c_san -m str ([^}]+)\}", config)
|
||||
assert len(lists) == 1
|
||||
assert set(lists[0].split()) == {f"DNS:{san}" for san in ALLOWED.values()}
|
||||
|
||||
|
||||
def test_gateway_accepts_only_mtls_and_export_paths() -> None:
|
||||
config = _directives(GATEWAY.read_text(encoding="utf-8"))
|
||||
binds = [line.split() for line in config.splitlines() if "bind " in line]
|
||||
# health на loopback, приём и метрики Collector с обязательным сертификатом
|
||||
assert [bind[1] for bind in binds] == ["127.0.0.1:8405", ":4318", ":8888", ":8889"]
|
||||
otlp = " ".join(binds[1])
|
||||
for option in (
|
||||
"crt /run/secrets/otel-collector.pem",
|
||||
"ca-file /run/secrets/ca.crt",
|
||||
"crl-file /run/secrets/crl.pem",
|
||||
"verify required",
|
||||
"ssl-min-ver TLSv1.3",
|
||||
):
|
||||
assert option in otlp, option
|
||||
config = _otlp(config) + config[config.index("backend collector\n") :]
|
||||
assert "tcp-request session reject if { var(sess.refusal) -m found }" in config
|
||||
deny = next(line for line in config.splitlines() if "METH_POST" in line)
|
||||
assert deny.strip() == (
|
||||
"http-request deny deny_status 404 unless METH_POST "
|
||||
"{ path /v1/traces /v1/metrics /v1/logs }"
|
||||
)
|
||||
# приёмник Collector — тот же loopback, что у backend шлюза
|
||||
assert "server collector 127.0.0.1:14318" in config
|
||||
collector = _directives(COLLECTOR_YAML.read_text(encoding="utf-8"))
|
||||
receiver = re.findall(
|
||||
r"receivers:\n otlp:\n protocols:\n http:\n endpoint: (\S+)",
|
||||
collector,
|
||||
)
|
||||
assert receiver == ["127.0.0.1:14318"]
|
||||
assert "grpc:" not in collector
|
||||
|
||||
|
||||
def _block(name: str) -> str:
|
||||
match = re.search(
|
||||
rf"^ {name}:\n(.*?)(?=^ [a-z0-9-]+:\n|^\S)",
|
||||
COMPOSE.read_text(encoding="utf-8"),
|
||||
re.M | re.S,
|
||||
)
|
||||
assert match, name
|
||||
return match.group(1)
|
||||
|
||||
|
||||
def test_compose_gateway_owns_collector_namespace() -> None:
|
||||
gateway = _block("otel-gateway")
|
||||
secrets = re.findall(r"^ - ([a-z0-9.-]+)$", gateway, re.M)
|
||||
assert {"ca.crt", "crl.pem", "otel-collector.pem"} <= set(secrets)
|
||||
assert not any(s.endswith(".key") for s in secrets)
|
||||
# алиас — в обеих сетях; портов наружу нет
|
||||
for network in ("default", "telemetry"):
|
||||
alias = f" {network}:\n aliases:\n - otel-collector\n"
|
||||
assert alias in gateway, network
|
||||
assert "ports:" not in gateway
|
||||
# тот же образ с digest, что у LB, и без билетов сессии
|
||||
images = re.findall(r"image: (haproxy:\S+@sha256:\S+)", gateway)
|
||||
assert len(images) == 1
|
||||
assert images[0] in _block("haproxy")
|
||||
assert "OPENSSL_CONF:" in gateway
|
||||
collector = _block("otel-collector")
|
||||
assert "network_mode: service:otel-gateway" in collector
|
||||
assert re.search(
|
||||
r"otel-gateway:\n\s+condition: service_healthy\n\s+restart: true", collector
|
||||
)
|
||||
assert "networks:" not in collector
|
||||
|
||||
|
||||
def test_compose_gives_each_process_its_own_files() -> None:
|
||||
text = COMPOSE.read_text(encoding="utf-8")
|
||||
assert "http://otel-collector" not in text
|
||||
assert "OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318" in text
|
||||
for service, identity in (
|
||||
("api", "api-client"),
|
||||
("relay", "relay"),
|
||||
("worker", "worker"),
|
||||
):
|
||||
block = _block(service)
|
||||
assert f"TELEMETRY_CERT_FILE: /run/secrets/{identity}.crt" in block
|
||||
assert f"TELEMETRY_KEY_FILE: /run/secrets/{identity}.key" in block
|
||||
for name in (f"{identity}.crt", f"{identity}.key", "ca.crt", "crl.pem"):
|
||||
assert f" - {name}\n" in block, (service, name)
|
||||
# ключ клиента API — только у реплик, ключ шлюза — только у шлюза
|
||||
services = text[text.index("\nservices:") : text.index("\nnetworks:")]
|
||||
for name, owners in (
|
||||
("api-client.key", {"api"}),
|
||||
("otel-collector.pem", {"otel-gateway"}),
|
||||
):
|
||||
users = {
|
||||
service
|
||||
for service in re.findall(r"^ ([a-z0-9-]+):\n", services, re.M)
|
||||
if f" - {name}\n" in _block(service)
|
||||
}
|
||||
assert users == owners, name
|
||||
@@ -0,0 +1,569 @@
|
||||
"""Лаба 7: TLS сервера API, allowlist identity, alias процесса, слушатель health.
|
||||
|
||||
Без стенда. Рукопожатия — настоящие: uvicorn с `src.tls` на loopback в
|
||||
потоке, сертификаты выпускает `infra/pki/pki.sh` во временный каталог (без
|
||||
OpenSSL ≥ 3 эти тесты пропускаются с причиной). Клиент — `ssl` stdlib, как
|
||||
у HAProxy: проверка сервера по CA стенда и имени `api`.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import re
|
||||
import signal
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import uvicorn
|
||||
|
||||
from src import early_stop
|
||||
from src import health_listener as listener_module
|
||||
from src.config import ConfigError, Settings, Tls
|
||||
from src.health_listener import HealthListener
|
||||
from src.tls import (
|
||||
allowlist_protocol,
|
||||
client_identities,
|
||||
context_factory,
|
||||
is_allowed,
|
||||
server_context,
|
||||
tls_problems,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
PKI = ROOT / "infra" / "pki" / "pki.sh"
|
||||
ALIAS = re.compile(r"[0-9a-f]{16}")
|
||||
REQUEST = b"GET /health/live HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n"
|
||||
# исходы «HTTP-ответа нет»
|
||||
NO_HTTP = ("tls_error", "closed")
|
||||
|
||||
|
||||
# --- настройки и alias -------------------------------------------------------
|
||||
|
||||
|
||||
def test_instance_id_defaults_to_random_alias() -> None:
|
||||
first = Settings.from_env({}).instance_id
|
||||
second = Settings.from_env({}).instance_id
|
||||
assert ALIAS.fullmatch(first)
|
||||
assert first != second
|
||||
|
||||
|
||||
def test_explicit_instance_id_and_bad_one() -> None:
|
||||
assert Settings.from_env({"APP_INSTANCE_ID": "api-a"}).instance_id == "api-a"
|
||||
with pytest.raises(ConfigError, match="APP_INSTANCE_ID"):
|
||||
Settings.from_env({"APP_INSTANCE_ID": "api a"})
|
||||
|
||||
|
||||
def test_health_port_must_differ_from_app_port() -> None:
|
||||
assert Settings.from_env({}).health_port == 8081
|
||||
assert Settings.from_env({"APP_HEALTH_PORT": "0"}).health_port == 0
|
||||
with pytest.raises(ConfigError, match="APP_HEALTH_PORT"):
|
||||
Settings.from_env({"APP_PORT": "8081"})
|
||||
|
||||
|
||||
def test_tls_settings_parse() -> None:
|
||||
tls = Settings.from_env({}).tls
|
||||
assert tls.client_auth is True
|
||||
assert tls.allowed_clients == ("haproxy",)
|
||||
tls = Tls.from_env(
|
||||
{"TLS_CLIENT_AUTH": "false", "TLS_ALLOWED_CLIENTS": "haproxy, mtls-probe"}
|
||||
)
|
||||
assert tls.client_auth is False
|
||||
assert tls.allowed_clients == ("haproxy", "mtls-probe")
|
||||
with pytest.raises(ConfigError, match="TLS_ALLOWED_CLIENTS"):
|
||||
Tls.from_env({"TLS_ALLOWED_CLIENTS": "haproxy,Bad Name"})
|
||||
with pytest.raises(ConfigError, match="TLS_CLIENT_AUTH"):
|
||||
Tls.from_env({"TLS_CLIENT_AUTH": "yes"})
|
||||
|
||||
|
||||
def test_early_stop_puts_one_alias_into_environment(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.delenv("APP_INSTANCE_ID", raising=False)
|
||||
handlers = {s: signal.getsignal(s) for s in (signal.SIGTERM, signal.SIGINT)}
|
||||
try:
|
||||
early_stop.install()
|
||||
alias = os.environ["APP_INSTANCE_ID"]
|
||||
early_stop.install()
|
||||
assert os.environ["APP_INSTANCE_ID"] == alias
|
||||
finally:
|
||||
early_stop.disarm()
|
||||
for signum, handler in handlers.items():
|
||||
signal.signal(signum, handler)
|
||||
assert ALIAS.fullmatch(alias)
|
||||
assert alias in early_stop._line(signal.SIGTERM).decode()
|
||||
assert Settings.from_env(os.environ).instance_id == alias
|
||||
|
||||
|
||||
def test_explicit_instance_id_survives_early_stop(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
monkeypatch.setenv("APP_INSTANCE_ID", "api-a")
|
||||
handlers = {s: signal.getsignal(s) for s in (signal.SIGTERM, signal.SIGINT)}
|
||||
try:
|
||||
early_stop.install()
|
||||
finally:
|
||||
early_stop.disarm()
|
||||
for signum, handler in handlers.items():
|
||||
signal.signal(signum, handler)
|
||||
assert os.environ["APP_INSTANCE_ID"] == "api-a"
|
||||
|
||||
|
||||
# --- allowlist и проверка настроек ------------------------------------------
|
||||
|
||||
|
||||
def test_client_identities_are_dns_san_only() -> None:
|
||||
peercert = {
|
||||
"subject": ((("commonName", "api"),),),
|
||||
"subjectAltName": (("DNS", "haproxy"), ("IP Address", "10.0.0.1")),
|
||||
}
|
||||
assert client_identities(peercert) == ("haproxy",)
|
||||
assert client_identities(None) == ()
|
||||
assert is_allowed(("haproxy",), ("haproxy",))
|
||||
assert not is_allowed(("mtls-probe",), ("haproxy",))
|
||||
assert not is_allowed((), ("haproxy",))
|
||||
|
||||
|
||||
def test_tls_problems_without_files() -> None:
|
||||
assert tls_problems(Settings.from_env({})) == [
|
||||
"TLS_CERT_FILE",
|
||||
"TLS_KEY_FILE",
|
||||
"TLS_CA_FILE",
|
||||
"TLS_CRL_FILE",
|
||||
]
|
||||
|
||||
|
||||
# --- настоящие рукопожатия ---------------------------------------------------
|
||||
|
||||
|
||||
def _pki(env: dict[str, str], *args: str) -> None:
|
||||
done = subprocess.run(
|
||||
["sh", str(PKI), *args], env=env, capture_output=True, text=True, check=False
|
||||
)
|
||||
if done.returncode != 0:
|
||||
pytest.skip(f"infra/pki/pki.sh {args[0]} failed (OpenSSL 3+?): {done.stderr}")
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def pki(tmp_path_factory: pytest.TempPathFactory) -> dict[str, Path]:
|
||||
"""CA стенда и файлы стенда, разовая mtls-probe, haproxy другого CA и
|
||||
копия CRL до отзыва (её берёт тест отзыва)."""
|
||||
base = tmp_path_factory.mktemp("pki")
|
||||
env = {
|
||||
**os.environ,
|
||||
"PKI_OPERATOR_DIR": str(base / "operator"),
|
||||
"PKI_STAND_DIR": str(base / "stand"),
|
||||
}
|
||||
_pki(env, "stand")
|
||||
_pki(env, "issue", "mtls-probe", "--profile", "client", "--san", "mtls-probe",
|
||||
"--days", "1", "--out", str(base / "probe"), "--bundle") # fmt: skip
|
||||
(base / "crl-before.pem").write_bytes((base / "stand" / "crl.pem").read_bytes())
|
||||
other = {**env, "PKI_OPERATOR_DIR": str(base / "other")}
|
||||
_pki(other, "init")
|
||||
_pki(other, "issue", "haproxy", "--profile", "client", "--san", "haproxy",
|
||||
"--days", "1", "--out", str(base / "foreign"), "--bundle") # fmt: skip
|
||||
return {"base": base, "stand": base / "stand", "env": env} # type: ignore[dict-item]
|
||||
|
||||
|
||||
def _revoke_haproxy(pki: dict) -> Path:
|
||||
"""Отозвать haproxy (действующие пары identity) и вернуть новый CRL."""
|
||||
_pki(pki["env"], "revoke", "haproxy")
|
||||
return pki["stand"] / "crl.pem"
|
||||
|
||||
|
||||
async def _app(scope, receive, send) -> None: # noqa: ANN001
|
||||
if scope["type"] != "http":
|
||||
return
|
||||
await send({"type": "http.response.start", "status": 200, "headers": []})
|
||||
await send({"type": "http.response.body", "body": b"ok"})
|
||||
|
||||
|
||||
class _Server:
|
||||
def __init__(self, tls: Tls, app=_app) -> None: # noqa: ANN001
|
||||
sock = socket.socket()
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
self.port = sock.getsockname()[1]
|
||||
sock.close()
|
||||
config = uvicorn.Config(
|
||||
app,
|
||||
host="127.0.0.1",
|
||||
port=self.port,
|
||||
ssl_context_factory=context_factory(tls),
|
||||
http=allowlist_protocol(tls),
|
||||
log_config=None,
|
||||
lifespan="off",
|
||||
)
|
||||
self.server = uvicorn.Server(config)
|
||||
self.thread = threading.Thread(target=self.server.run, daemon=True)
|
||||
|
||||
def __enter__(self) -> "_Server":
|
||||
self.thread.start()
|
||||
deadline = time.monotonic() + 10
|
||||
while not self.server.started and time.monotonic() < deadline:
|
||||
time.sleep(0.05)
|
||||
assert self.server.started
|
||||
return self
|
||||
|
||||
def __exit__(self, *_: object) -> None:
|
||||
self.server.should_exit = True
|
||||
self.thread.join(10)
|
||||
|
||||
|
||||
def _connect(port: int, ca: Path, pair: Path | None) -> str:
|
||||
"""Исход для клиента: `http 200`, `closed` или `tls_error`."""
|
||||
context = ssl.create_default_context(cafile=str(ca))
|
||||
if pair is not None:
|
||||
context.load_cert_chain(str(pair))
|
||||
raw = socket.create_connection(("127.0.0.1", port), timeout=5)
|
||||
try:
|
||||
try:
|
||||
sock = context.wrap_socket(raw, server_hostname="api")
|
||||
except (ssl.SSLError, OSError):
|
||||
return "tls_error"
|
||||
try:
|
||||
sock.sendall(REQUEST)
|
||||
data = sock.recv(4096)
|
||||
except (ssl.SSLError, OSError):
|
||||
return "tls_error"
|
||||
if data.startswith(b"HTTP/1.1 "):
|
||||
return "http " + data.split()[1].decode()
|
||||
return "closed"
|
||||
finally:
|
||||
raw.close()
|
||||
|
||||
|
||||
def _tls(stand: Path, crl: Path | None = None) -> Tls:
|
||||
return Tls(
|
||||
cert_file=str(stand / "api.crt"),
|
||||
key_file=str(stand / "api.key"),
|
||||
ca_file=str(stand / "ca.crt"),
|
||||
crl_file=str(crl or stand / "crl.pem"),
|
||||
client_auth=True,
|
||||
allowed_clients=("haproxy",),
|
||||
)
|
||||
|
||||
|
||||
def test_mtls_handshakes(pki: dict, caplog: pytest.LogCaptureFixture) -> None:
|
||||
"""Без сертификата, другой CA, серверный сертификат — отказ рукопожатия
|
||||
(в TLS 1.3 клиент узнаёт о нём алертом или закрытием уже после своей
|
||||
половины), строки «tls client rejected» о них нет; identity того же CA
|
||||
вне allowlist — закрыто без ответа и строка; haproxy — 200."""
|
||||
stand, base = pki["stand"], pki["base"]
|
||||
ca = stand / "ca.crt"
|
||||
with _Server(_tls(stand)) as server, caplog.at_level("WARNING"):
|
||||
assert _connect(server.port, ca, None) in NO_HTTP
|
||||
assert _connect(server.port, ca, base / "foreign" / "haproxy.pem") in NO_HTTP
|
||||
assert _connect(server.port, ca, stand / "ingress.pem") in NO_HTTP
|
||||
time.sleep(0.2)
|
||||
assert "tls client rejected" not in caplog.text
|
||||
assert _connect(server.port, ca, base / "probe" / "mtls-probe.pem") in NO_HTTP
|
||||
time.sleep(0.2)
|
||||
assert "tls client rejected identity=mtls-probe" in caplog.text
|
||||
assert _connect(server.port, ca, stand / "haproxy.pem") == "http 200"
|
||||
# без TLS: HTTP-ответа нет
|
||||
with _Server(_tls(stand)) as server:
|
||||
raw = socket.create_connection(("127.0.0.1", server.port), timeout=5)
|
||||
try:
|
||||
raw.sendall(REQUEST)
|
||||
try:
|
||||
data = raw.recv(4096)
|
||||
except OSError:
|
||||
data = b""
|
||||
finally:
|
||||
raw.close()
|
||||
assert not data.startswith(b"HTTP/1.1 200")
|
||||
|
||||
|
||||
def test_revoked_client_is_rejected(pki: dict) -> None:
|
||||
stand, base = pki["stand"], pki["base"]
|
||||
crl = _revoke_haproxy(pki)
|
||||
with _Server(_tls(stand, crl)) as server:
|
||||
assert _connect(server.port, stand / "ca.crt", stand / "haproxy.pem") in NO_HTTP
|
||||
# тот же сервер со старым CRL принимает ту же пару: отказ дал именно CRL
|
||||
with _Server(_tls(stand, base / "crl-before.pem")) as server:
|
||||
assert _connect(server.port, stand / "ca.crt", stand / "haproxy.pem") == (
|
||||
"http 200"
|
||||
)
|
||||
|
||||
|
||||
def test_tls_problems_on_real_files(pki: dict) -> None:
|
||||
stand = pki["stand"]
|
||||
files = {
|
||||
"TLS_CERT_FILE": str(stand / "api.crt"),
|
||||
"TLS_KEY_FILE": str(stand / "api.key"),
|
||||
"TLS_CA_FILE": str(stand / "ca.crt"),
|
||||
"TLS_CRL_FILE": str(stand / "crl.pem"),
|
||||
}
|
||||
assert tls_problems(Settings.from_env({**files, "APP_HOST": "0.0.0.0"})) == []
|
||||
# без проверки клиента — только loopback
|
||||
no_auth = {**files, "TLS_CLIENT_AUTH": "false"}
|
||||
assert tls_problems(Settings.from_env({**no_auth, "APP_HOST": "127.0.0.1"})) == []
|
||||
assert tls_problems(Settings.from_env({**no_auth, "APP_HOST": "0.0.0.0"})) == [
|
||||
"TLS_CLIENT_AUTH"
|
||||
]
|
||||
# ключ не от сертификата — отказ сборки контекста
|
||||
broken = {**files, "TLS_KEY_FILE": str(stand / "haproxy.key")}
|
||||
assert "TLS_KEY_FILE" in tls_problems(Settings.from_env(broken))
|
||||
|
||||
|
||||
# --- билеты сессии и обрыв тела (перенос https-tooling) ----------------------
|
||||
|
||||
|
||||
def _bytes_after_handshake(
|
||||
server: ssl.SSLContext, client: ssl.SSLContext, server_hostname: str
|
||||
) -> int:
|
||||
"""Рукопожатие в памяти до конца с обеих сторон; сколько байт сервер
|
||||
отдал клиенту сверх прочитанного в рукопожатии (билеты TLS 1.3)."""
|
||||
s_in, s_out, c_in, c_out = (ssl.MemoryBIO() for _ in range(4))
|
||||
server_conn = server.wrap_bio(s_in, s_out, server_side=True)
|
||||
client_conn = client.wrap_bio(c_in, c_out, server_hostname=server_hostname)
|
||||
done = {"client": False, "server": False}
|
||||
for _ in range(10):
|
||||
for name, conn in (("client", client_conn), ("server", server_conn)):
|
||||
if not done[name]:
|
||||
try:
|
||||
conn.do_handshake()
|
||||
done[name] = True
|
||||
except ssl.SSLWantReadError:
|
||||
pass
|
||||
s_in.write(c_out.read())
|
||||
c_in.write(s_out.read())
|
||||
if all(done.values()):
|
||||
break
|
||||
assert all(done.values()), done
|
||||
return c_in.pending
|
||||
|
||||
|
||||
@pytest.mark.parametrize("client_auth", [True, False])
|
||||
def test_no_messages_after_handshake(pki: dict, client_auth: bool) -> None:
|
||||
"""Билеты сессии TLS 1.3 после рукопожатия — непрочитанные байты у
|
||||
клиента, который только пишет тело; его обрыв тогда — RST, и процесс API
|
||||
его не замечал (докстринг `src/tls.py`)."""
|
||||
stand, base = pki["stand"], pki["base"]
|
||||
client = ssl.create_default_context(cafile=str(stand / "ca.crt"))
|
||||
if client_auth:
|
||||
tls = _tls(stand, base / "crl-before.pem")
|
||||
client.load_cert_chain(str(stand / "haproxy.pem"))
|
||||
name = "api"
|
||||
else:
|
||||
tls = Tls(
|
||||
cert_file=str(stand / "ingress.crt"),
|
||||
key_file=str(stand / "ingress.key"),
|
||||
client_auth=False,
|
||||
)
|
||||
name = "localhost"
|
||||
assert _bytes_after_handshake(server_context(tls), client, name) == 0
|
||||
|
||||
|
||||
# тело обрываемой загрузки и срок, за который сервер обязан заметить обрыв
|
||||
ABORTED_BODY = b"\x89PNG\r\n\x1a\n" + bytes(1024 * 1024)
|
||||
ABORT_NOTICED_S = 1.0
|
||||
ABORT_ROUNDS = 3
|
||||
|
||||
|
||||
def _aborted_upload(port: int, stand: Path) -> None:
|
||||
"""Клиент в роли LB: заголовки, 1 MiB тела частью chunked, закрытие
|
||||
сокета без чтения ответа (как httpx на исключении итератора тела)."""
|
||||
context = ssl.create_default_context(cafile=str(stand / "ca.crt"))
|
||||
context.load_cert_chain(str(stand / "haproxy.pem"))
|
||||
with (
|
||||
socket.create_connection(("127.0.0.1", port), timeout=5) as raw,
|
||||
context.wrap_socket(raw, server_hostname="api") as conn,
|
||||
):
|
||||
conn.sendall(
|
||||
b"POST /upload HTTP/1.1\r\nHost: api\r\nTransfer-Encoding: chunked\r\n\r\n"
|
||||
)
|
||||
conn.sendall(f"{len(ABORTED_BODY):x}\r\n".encode() + ABORTED_BODY + b"\r\n")
|
||||
|
||||
|
||||
def test_aborted_body_noticed(pki: dict) -> None:
|
||||
"""Обрыв тела по mTLS доходит до приложения как `http.disconnect` сразу,
|
||||
а не по сроку тела."""
|
||||
stand, base = pki["stand"], pki["base"]
|
||||
outcomes: list[str] = []
|
||||
|
||||
async def body_app(scope, receive, send) -> None: # noqa: ANN001
|
||||
if scope["type"] != "http":
|
||||
return
|
||||
outcome = "complete"
|
||||
try:
|
||||
async with asyncio.timeout(ABORT_NOTICED_S * 5):
|
||||
while True:
|
||||
message = await receive()
|
||||
if message["type"] == "http.disconnect":
|
||||
outcome = "disconnect"
|
||||
break
|
||||
if not message.get("more_body"):
|
||||
break
|
||||
except TimeoutError:
|
||||
outcome = "timeout"
|
||||
outcomes.append(outcome)
|
||||
try:
|
||||
await send({"type": "http.response.start", "status": 200, "headers": []})
|
||||
await send({"type": "http.response.body", "body": b""})
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
with _Server(_tls(stand, base / "crl-before.pem"), app=body_app) as server:
|
||||
for attempt in range(ABORT_ROUNDS):
|
||||
_aborted_upload(server.port, stand)
|
||||
deadline = time.monotonic() + ABORT_NOTICED_S
|
||||
while len(outcomes) <= attempt and time.monotonic() < deadline:
|
||||
time.sleep(0.02)
|
||||
assert outcomes[attempt:] == ["disconnect"], (attempt, outcomes)
|
||||
|
||||
|
||||
# --- перевыпуск leaf по списку identity (перенос https-tooling) -------------
|
||||
|
||||
|
||||
def _serial(path: Path) -> str:
|
||||
done = subprocess.run(
|
||||
["openssl", "x509", "-in", str(path), "-noout", "-serial"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
return done.stdout.strip()
|
||||
|
||||
|
||||
def test_stand_reissues_leaf_that_differs_from_list(tmp_path: Path) -> None:
|
||||
"""`pki.sh stand` перевыпускает leaf, чьи DNS SAN или назначение разошлись
|
||||
со строкой списка; остальные и повтор без правки — без перевыпуска."""
|
||||
old = tmp_path / "old.conf"
|
||||
old.write_text(
|
||||
"haproxy client haproxy bundle\napi server api split\n"
|
||||
"ingress server localhost bundle\n"
|
||||
)
|
||||
new = tmp_path / "new.conf"
|
||||
new.write_text(
|
||||
"haproxy client haproxy bundle\napi server api split\n"
|
||||
"ingress server ingress,localhost bundle\n"
|
||||
)
|
||||
swapped = tmp_path / "swapped.conf"
|
||||
swapped.write_text(
|
||||
"haproxy client haproxy bundle\napi client api split\n"
|
||||
"ingress server ingress,localhost bundle\n"
|
||||
)
|
||||
env = {
|
||||
**os.environ,
|
||||
"PKI_OPERATOR_DIR": str(tmp_path / "operator"),
|
||||
"PKI_STAND_DIR": str(tmp_path / "stand"),
|
||||
}
|
||||
stand = tmp_path / "stand"
|
||||
|
||||
def run(identities: Path) -> str:
|
||||
done = subprocess.run(
|
||||
["sh", str(PKI), "stand"],
|
||||
env={**env, "PKI_IDENTITIES": str(identities)},
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
if done.returncode != 0:
|
||||
pytest.skip(f"infra/pki/pki.sh stand failed (OpenSSL 3+?): {done.stderr}")
|
||||
assert "PRIVATE KEY" not in done.stdout + done.stderr
|
||||
return done.stdout
|
||||
|
||||
def reissued(identities: Path) -> list[str]:
|
||||
out = run(identities).splitlines()
|
||||
return [line for line in out if line.startswith("reissue ")]
|
||||
|
||||
run(old)
|
||||
serials = {name: _serial(stand / f"{name}.crt") for name in ("haproxy", "api")}
|
||||
assert reissued(new) == ["reissue ingress: SAN differ from the list"]
|
||||
assert {name: _serial(stand / f"{name}.crt") for name in serials} == serials
|
||||
assert reissued(new) == []
|
||||
assert reissued(swapped) == ["reissue api: purpose differs from the list"]
|
||||
|
||||
|
||||
# --- слушатель health ---------------------------------------------------------
|
||||
|
||||
|
||||
async def _ask(port: int, line: str) -> bytes:
|
||||
reader, writer = await asyncio.open_connection("127.0.0.1", port)
|
||||
writer.write(f"{line}\r\nHost: x\r\n\r\n".encode())
|
||||
await writer.drain()
|
||||
data = await reader.read()
|
||||
writer.close()
|
||||
return data
|
||||
|
||||
|
||||
def _listen(ready, *requests: str) -> list[bytes]: # noqa: ANN001
|
||||
async def scenario() -> list[bytes]:
|
||||
listener = HealthListener(ready=ready, instance_id="0123456789abcdef", port=0)
|
||||
await listener.start()
|
||||
try:
|
||||
return [await _ask(listener.port, line) for line in requests]
|
||||
finally:
|
||||
await listener.close()
|
||||
|
||||
return asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_health_listener_answers_only_live_and_ready() -> None:
|
||||
calls: list[int] = []
|
||||
|
||||
async def ready() -> bool:
|
||||
calls.append(1)
|
||||
return True
|
||||
|
||||
live, ready_ok, me, register, head = _listen(
|
||||
ready,
|
||||
"GET /health/live HTTP/1.1",
|
||||
"GET /health/ready HTTP/1.1",
|
||||
"GET /api/v1/users/me HTTP/1.1",
|
||||
"POST /api/v1/users HTTP/1.1",
|
||||
"HEAD /health/live HTTP/1.1",
|
||||
)
|
||||
assert live.startswith(b"HTTP/1.1 200 ")
|
||||
assert ready_ok.startswith(b"HTTP/1.1 200 ")
|
||||
assert b"X-Instance-Id: 0123456789abcdef" in live
|
||||
assert b"Connection: close" in live
|
||||
for answer in (me, register, head):
|
||||
assert answer.startswith(b"HTTP/1.1 404 ")
|
||||
assert b'"code": "not_found"' in answer
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
def test_health_listener_not_ready_and_slow_ready(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
async def not_ready() -> bool:
|
||||
return False
|
||||
|
||||
(answer,) = _listen(not_ready, "GET /health/ready HTTP/1.1")
|
||||
assert answer.startswith(b"HTTP/1.1 503 ")
|
||||
assert b'"code": "unavailable"' in answer
|
||||
|
||||
# проверка готовности дольше своего срока — 503, а не обрыв
|
||||
monkeypatch.setattr(listener_module, "HEALTH_LISTENER_READY_TIMEOUT", 0.2)
|
||||
|
||||
async def frozen() -> bool:
|
||||
await asyncio.sleep(5)
|
||||
return True
|
||||
|
||||
started = time.monotonic()
|
||||
(answer,) = _listen(frozen, "GET /health/ready HTTP/1.1")
|
||||
assert answer.startswith(b"HTTP/1.1 503 ")
|
||||
assert time.monotonic() - started < 2
|
||||
|
||||
|
||||
def test_health_listener_timeouts_are_chained() -> None:
|
||||
from src.constants import (
|
||||
DB_CLOSE_TIMEOUT,
|
||||
HEALTH_LISTENER_READY_TIMEOUT,
|
||||
READINESS_TIMEOUT,
|
||||
)
|
||||
from src.healthcheck import TIMEOUT
|
||||
|
||||
assert HEALTH_LISTENER_READY_TIMEOUT > READINESS_TIMEOUT + DB_CLOSE_TIMEOUT
|
||||
assert TIMEOUT > HEALTH_LISTENER_READY_TIMEOUT
|
||||
dockerfile = (ROOT / "Dockerfile").read_text(encoding="utf-8")
|
||||
match = re.search(r"HEALTHCHECK .*--timeout=(\d+)s", dockerfile)
|
||||
assert match
|
||||
assert int(match.group(1)) > TIMEOUT
|
||||
@@ -0,0 +1,170 @@
|
||||
"""Лаба 6, уровень 4: перенос контекста через задание, насыщение, журнал SDK.
|
||||
|
||||
Без стенда: SDK с in-memory экспортёрами из `test_telemetry.py`. Цепочка
|
||||
загрузка → строка задания → producer span → заголовки → consumer span
|
||||
собирается из тех же функций, что зовут API, relay и worker.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from collections.abc import Iterator
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from opentelemetry.trace import SpanKind
|
||||
from test_telemetry import ENDPOINT, Pipeline
|
||||
|
||||
from src import telemetry
|
||||
from src.broker import trace_headers
|
||||
from src.config import Telemetry as TelemetrySettings
|
||||
from src.log import ThrottleFilter
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
TRACEPARENT = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def pipeline() -> Iterator[Pipeline]:
|
||||
built = Pipeline(TelemetrySettings.from_env(ENDPOINT))
|
||||
yield built
|
||||
built.session.shutdown(1.0)
|
||||
|
||||
|
||||
def _upload_carrier() -> dict[str, str]:
|
||||
"""Что сохранила бы загрузка: контекст её server span."""
|
||||
with telemetry.root_span(
|
||||
"POST /api/v1/chats/{chat_id}/attachments",
|
||||
kind=SpanKind.SERVER,
|
||||
attributes={},
|
||||
):
|
||||
return telemetry.carrier()
|
||||
|
||||
|
||||
def test_chain_upload_relay_worker_is_one_trace(pipeline: Pipeline) -> None:
|
||||
stored = _upload_carrier()
|
||||
assert set(stored) == {"traceparent"}
|
||||
# две публикации одной строки: первая попытка и повтор после backoff
|
||||
for attempt in (1, 2):
|
||||
with telemetry.producer_span(
|
||||
"publish q", stored, {"messenger.job.attempt": attempt}
|
||||
) as headers:
|
||||
pass
|
||||
with (
|
||||
telemetry.root_span(
|
||||
"process q",
|
||||
kind=SpanKind.CONSUMER,
|
||||
attributes={"messenger.job.attempt": attempt},
|
||||
parent=telemetry.extract(headers),
|
||||
),
|
||||
telemetry.child_span("S3 put_object", {}),
|
||||
):
|
||||
pass
|
||||
finished = pipeline.spans.get_finished_spans()
|
||||
spans = {(s.name, s.attributes.get("messenger.job.attempt")): s for s in finished}
|
||||
assert len({s.context.trace_id for s in finished}) == 1
|
||||
server = next(s for s in finished if s.kind == SpanKind.SERVER)
|
||||
for attempt in (1, 2):
|
||||
producer = spans[("publish q", attempt)]
|
||||
consumer = spans[("process q", attempt)]
|
||||
assert producer.kind == SpanKind.PRODUCER
|
||||
assert producer.parent.span_id == server.context.span_id
|
||||
assert consumer.parent.span_id == producer.context.span_id
|
||||
put = [s for s in finished if s.name == "S3 put_object"]
|
||||
assert {s.parent.span_id for s in put} == {
|
||||
spans[("process q", 1)].context.span_id,
|
||||
spans[("process q", 2)].context.span_id,
|
||||
}
|
||||
|
||||
|
||||
def test_relay_without_stored_context_starts_no_trace(pipeline: Pipeline) -> None:
|
||||
with telemetry.producer_span("publish q", {}, {}) as headers:
|
||||
assert headers == {}
|
||||
assert pipeline.spans.get_finished_spans() == ()
|
||||
|
||||
|
||||
def test_disabled_relay_passes_stored_context_through() -> None:
|
||||
assert not telemetry.enabled()
|
||||
stored = {"traceparent": TRACEPARENT, "tracestate": "vendor=1"}
|
||||
with telemetry.producer_span("publish q", stored, {}) as headers:
|
||||
assert headers == stored
|
||||
assert telemetry.carrier() == {}
|
||||
|
||||
|
||||
def test_unsampled_upload_stays_unsampled_downstream() -> None:
|
||||
built = Pipeline(
|
||||
TelemetrySettings.from_env({**ENDPOINT, "OTEL_TRACES_SAMPLER_ARG": "0"})
|
||||
)
|
||||
try:
|
||||
stored = _upload_carrier()
|
||||
with telemetry.producer_span("publish q", stored, {}) as headers:
|
||||
pass
|
||||
# бит sampled (0x01) в trace-flags снят у обоих
|
||||
assert int(stored["traceparent"][-2:], 16) & 1 == 0
|
||||
assert int(headers["traceparent"][-2:], 16) & 1 == 0
|
||||
assert built.spans.get_finished_spans() == ()
|
||||
finally:
|
||||
built.session.shutdown(1.0)
|
||||
|
||||
|
||||
def test_trace_headers_accept_bytes_and_ignore_rest() -> None:
|
||||
message = SimpleNamespace(
|
||||
headers={"traceparent": TRACEPARENT.encode(), "x-other": "1", "tracestate": ""}
|
||||
)
|
||||
assert trace_headers(message) == {"traceparent": TRACEPARENT}
|
||||
assert trace_headers(SimpleNamespace(headers=None)) == {}
|
||||
|
||||
|
||||
def test_saturation_gauges(pipeline: Pipeline) -> None:
|
||||
telemetry.watch_pool(lambda: (3, 7, 2, 15))
|
||||
telemetry.worker_capacity(2)
|
||||
telemetry.queue_snapshot("db.attachment-jobs", {"outbox": 4, "processing": 1}, 42.5)
|
||||
with telemetry.busy():
|
||||
used = {
|
||||
p.attributes["db.client.connection.state"]: p.value
|
||||
for p in pipeline.points("db.client.connection.count")
|
||||
}
|
||||
busy = pipeline.points("messenger.worker.busy")
|
||||
assert used == {"used": 3, "idle": 7}
|
||||
assert [
|
||||
p.value for p in pipeline.points("db.client.connection.pending_requests")
|
||||
] == [2]
|
||||
assert [p.value for p in busy] == [1]
|
||||
assert [p.value for p in pipeline.points("messenger.worker.capacity")] == [2]
|
||||
depth = {
|
||||
p.attributes["messenger.job.state"]: p.value
|
||||
for p in pipeline.points("messenger.job.queue.depth")
|
||||
}
|
||||
assert depth == {"outbox": 4, "processing": 1}
|
||||
(age,) = pipeline.points("messenger.job.queue.oldest_age")
|
||||
assert age.value == 42.5
|
||||
assert pipeline.points("process.memory.usage")[0].value > 0
|
||||
modes = {p.attributes["cpu.mode"] for p in pipeline.points("process.cpu.time")}
|
||||
assert modes == {"user", "system"}
|
||||
telemetry.gauges.capacity = 0
|
||||
telemetry.gauges.depth = {}
|
||||
telemetry.gauges.oldest_age = None
|
||||
|
||||
|
||||
def test_time_to_ready_histogram(pipeline: Pipeline) -> None:
|
||||
telemetry.record_ready(3.2)
|
||||
telemetry.record_ready(-0.1) # часы разошлись — не отрицательное
|
||||
(point,) = pipeline.points(telemetry.TIME_TO_READY)
|
||||
assert point.count == 2
|
||||
assert point.min == 0.0
|
||||
assert dict(point.attributes) == {}
|
||||
|
||||
|
||||
def test_throttle_filter_lets_one_record_per_window() -> None:
|
||||
throttle = ThrottleFilter(window=60)
|
||||
|
||||
def record(text: str) -> logging.LogRecord:
|
||||
return logging.LogRecord(
|
||||
"opentelemetry.x", logging.WARNING, "", 0, text, (), None
|
||||
)
|
||||
|
||||
assert throttle.filter(record("first"))
|
||||
assert not any(throttle.filter(record("again")) for _ in range(5))
|
||||
throttle._last["opentelemetry.x"] -= 61
|
||||
late = record("later")
|
||||
assert throttle.filter(late)
|
||||
assert "suppressed=5" in late.getMessage()
|
||||
@@ -0,0 +1,362 @@
|
||||
"""Лаба 7, трек 1 «Компрометация worker»: всё, что проверяется без стенда.
|
||||
|
||||
Таблица операций `infra/track1/operations.py` против источников прав (матрица
|
||||
ролей `src/db_roles.py`, права брокера `infra/rabbitmq/start.sh`, политика
|
||||
OpenBao `worker.hcl`, политика S3 worker в `infra/s3/bootstrap.sh`): ожидание
|
||||
«после» не может разойтись с правами и не подгоняется под прогон. Политика S3
|
||||
— только префиксы своей базы. Ревизия 0006: функции триггеров без SECURITY
|
||||
DEFINER, `search_path = pg_catalog`, перечень кодов = константы кода, вид ключа
|
||||
варианта = ключ, который строит `AttachmentObjects`. Чистые функции учений
|
||||
(окна, вердикты, сводка таблицы), override «до» и «после», гипотезы, цели make и
|
||||
правила Codex.
|
||||
"""
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import ModuleType
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from src import constants, db_roles
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
TRACK1 = ROOT / "infra" / "track1"
|
||||
|
||||
|
||||
def _load(name: str, path: Path) -> ModuleType:
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
assert spec is not None
|
||||
assert spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
sys.modules[name] = module
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
operations = _load("operations", TRACK1 / "operations.py")
|
||||
sys.path.insert(0, str(ROOT / "student-tests"))
|
||||
track1 = _load("track1_drill", TRACK1 / "track1.py")
|
||||
revision = _load(
|
||||
"revision_0006", ROOT / "migrations" / "versions" / "0006_pipeline_value_rules.py"
|
||||
)
|
||||
|
||||
|
||||
def _row(op_id: str):
|
||||
return operations.by_id()[op_id]
|
||||
|
||||
|
||||
# --- таблица против источников прав -------------------------------------------
|
||||
|
||||
|
||||
def test_postgres_rows_match_the_worker_matrix() -> None:
|
||||
grants = db_roles.MATRIX[db_roles.WORKER_ROLE]
|
||||
assert set(operations.PG_TABLES) == set(db_roles.TABLES)
|
||||
for table in operations.PG_TABLES:
|
||||
grant = grants[table]
|
||||
assert (table in operations.PG_SELECT) == grant.select, table
|
||||
assert (table in operations.PG_INSERT) == grant.insert, table
|
||||
assert (table in operations.PG_DELETE) == grant.delete, table
|
||||
assert set(operations.PG_UPDATE.get(table, ())) == set(grant.update), table
|
||||
assert operations.PG_FOREIGN_COLUMN[table] not in grant.update, table
|
||||
for verb in ("select", "insert", "delete"):
|
||||
row = _row(f"pg.{verb}.{table}")
|
||||
allowed = getattr(grant, verb)
|
||||
assert row.after == (operations.OK if allowed else operations.INSUFFICIENT)
|
||||
for row in operations.OPERATIONS:
|
||||
if row.id.startswith("pg.update."):
|
||||
table, column = row.id.split(".")[2:]
|
||||
allowed = column in grants[table].update
|
||||
assert row.after == (operations.OK if allowed else operations.INSUFFICIENT)
|
||||
|
||||
|
||||
def _worker_permissions() -> dict[str, str]:
|
||||
text = (ROOT / "infra" / "rabbitmq" / "start.sh").read_text(encoding="utf-8")
|
||||
block = re.search(r'\{"user": "worker",(.*?)\}', text, re.S)
|
||||
assert block is not None
|
||||
# heredoc без кавычек: «\$» в файле — «$» в определениях брокера
|
||||
found = re.findall(r'"(configure|write|read)": "([^"]*)"', block.group(1))
|
||||
return {verb: value.replace("\\$", "$") for verb, value in found}
|
||||
|
||||
|
||||
def test_broker_rows_match_the_worker_permissions() -> None:
|
||||
permissions = _worker_permissions()
|
||||
assert permissions["configure"] == "^$"
|
||||
assert permissions["write"] == "^$"
|
||||
assert permissions["read"] == "$queue_pattern"
|
||||
# read на свою очередь: получение и очистка; запись и настройка — нет
|
||||
for action in ("passive", "get", "purge"):
|
||||
assert _row(f"amqp.{action}").after == operations.OK
|
||||
for action in ("publish", "declare", "bind", "get_other", "delete_other"):
|
||||
assert _row(f"amqp.{action}").after == operations.REFUSED
|
||||
|
||||
|
||||
def test_openbao_rows_match_the_worker_policy() -> None:
|
||||
text = (ROOT / "infra" / "openbao" / "policies" / "worker.hcl").read_text()
|
||||
readable = set(re.findall(r'path "(messenger/data/[^"]+)"', text))
|
||||
assert readable == {"messenger/data/postgres/worker", "messenger/data/s3/worker"}
|
||||
for row in operations.OPERATIONS:
|
||||
if row.kind != "bao":
|
||||
continue
|
||||
path = row.args["path"]
|
||||
expected = (
|
||||
operations.OK
|
||||
if row.args["method"] == "GET" and path in readable
|
||||
else operations.BAO_FORBIDDEN
|
||||
)
|
||||
assert row.after == expected, row.id
|
||||
|
||||
|
||||
def _worker_policy() -> dict:
|
||||
text = (ROOT / "infra" / "s3" / "bootstrap.sh").read_text(encoding="utf-8")
|
||||
body = re.search(
|
||||
r"write_worker_policy\(\) \{\n cat >[^\n]*<<EOF\n(.*?)\nEOF", text, re.S
|
||||
)
|
||||
assert body is not None, "write_worker_policy is missing"
|
||||
raw = body.group(1).replace("${BUCKET}", "bucket").replace("${DATABASE}", "db")
|
||||
return json.loads(raw)
|
||||
|
||||
|
||||
def test_s3_worker_policy_is_prefix_scoped() -> None:
|
||||
"""Чтение — только staging своей базы, запись — только attachments; ни
|
||||
удаления, ни списка, ни ресурса шире префикса (мутация «весь bucket»)."""
|
||||
statements = _worker_policy()["Statement"]
|
||||
rights = {tuple(s["Action"]): s["Resource"] for s in statements}
|
||||
assert rights == {
|
||||
("s3:GetObject",): ["arn:aws:s3:::bucket/db/staging/*"],
|
||||
("s3:PutObject",): ["arn:aws:s3:::bucket/db/attachments/*"],
|
||||
}
|
||||
assert _row("s3.get.staging").after == operations.OK
|
||||
assert _row("s3.put.attachments").after == operations.OK
|
||||
for op_id in (
|
||||
"s3.get.attachments",
|
||||
"s3.head.attachments",
|
||||
"s3.put.staging",
|
||||
"s3.get.other_db",
|
||||
"s3.put.other_db",
|
||||
"s3.get.root",
|
||||
"s3.put.root",
|
||||
"s3.copy.from_attachments",
|
||||
"s3.multipart.staging",
|
||||
):
|
||||
assert _row(op_id).after == operations.S3_DENIED, op_id
|
||||
|
||||
|
||||
def test_every_available_row_is_explained() -> None:
|
||||
for row in operations.OPERATIONS:
|
||||
if row.after == operations.OK:
|
||||
assert row.why, row.id
|
||||
assert row.why[0] in (operations.CODE, operations.RESIDUAL), row.id
|
||||
assert row.scope in (operations.OWN, operations.PROCESS), row.id
|
||||
assert len({row.id for row in operations.OPERATIONS}) == len(operations.OPERATIONS)
|
||||
|
||||
|
||||
# --- ревизия 0006 -------------------------------------------------------------
|
||||
|
||||
|
||||
def test_trigger_functions_are_not_security_definer() -> None:
|
||||
for sql in (revision.NOT_PENDING_FUNCTION, revision.NAMESPACE_FUNCTION):
|
||||
assert "SECURITY DEFINER" not in sql.upper()
|
||||
assert "SET search_path = pg_catalog" in sql
|
||||
assert "public.attachments" in sql or "RAISE" in sql
|
||||
|
||||
|
||||
def test_error_codes_are_the_code_constants() -> None:
|
||||
codes = {
|
||||
constants.ERROR_INVALID_IMAGE,
|
||||
constants.ERROR_TOO_LARGE,
|
||||
constants.ERROR_SOURCE_MISSING,
|
||||
constants.ERROR_RETRY_EXHAUSTED,
|
||||
constants.ERROR_PROCESSING_FAILED,
|
||||
}
|
||||
condition = {name: cond for name, _table, cond in revision.CHECKS}
|
||||
assert (
|
||||
set(re.findall(r"'([a-z_]+)'", condition["ck_attachments_error_code_known"]))
|
||||
== codes
|
||||
)
|
||||
|
||||
|
||||
def test_tables_repeat_the_revision_checks() -> None:
|
||||
from src.storage import tables
|
||||
|
||||
found = {
|
||||
c.name: str(c.sqltext)
|
||||
for table in (tables.attachments, tables.attachment_variants)
|
||||
for c in table.constraints
|
||||
if c.name in {name for name, _t, _c in revision.CHECKS}
|
||||
}
|
||||
assert found == {name: cond for name, _table, cond in revision.CHECKS}
|
||||
|
||||
|
||||
def _variant_pattern(attachment_id: str, version: int, name: str) -> str:
|
||||
# то же выражение, что CHECK ck_attachment_variants_object_key_own
|
||||
return (
|
||||
"^[a-z0-9_]+/attachments/"
|
||||
+ attachment_id
|
||||
+ "/p"
|
||||
+ str(version)
|
||||
+ "/"
|
||||
+ name
|
||||
+ "[.](jpg|webp)$"
|
||||
)
|
||||
|
||||
|
||||
def test_variant_key_rule_accepts_own_keys_only() -> None:
|
||||
from src.s3 import ObjectStore
|
||||
from src.storage.objects import AttachmentObjects
|
||||
|
||||
class Store:
|
||||
namespace = "messenger"
|
||||
|
||||
objects = AttachmentObjects(Store()) # type: ignore[arg-type]
|
||||
own, other = uuid4(), uuid4()
|
||||
for name in constants.VARIANT_FORMATS:
|
||||
key = objects.variant_key(own, name)
|
||||
assert re.search(
|
||||
_variant_pattern(str(own), constants.PIPELINE_VERSION, name), key
|
||||
)
|
||||
pattern = _variant_pattern(str(own), 1, "thumbnail")
|
||||
for foreign in (
|
||||
objects.key_of(other),
|
||||
objects.variant_key(other, "thumbnail"),
|
||||
f"messenger/attachments/{own}/p1/../../{other}/original",
|
||||
objects.key_of(own),
|
||||
):
|
||||
assert not re.search(pattern, foreign), foreign
|
||||
assert ObjectStore # модуль клиента импортируется без стенда
|
||||
|
||||
|
||||
# --- чистые функции учений ----------------------------------------------------
|
||||
|
||||
|
||||
def test_windows_from_marks_and_last_success() -> None:
|
||||
events = [
|
||||
{"mark": "start", "t": 100.0},
|
||||
{"mark": "end", "t": 190.0},
|
||||
{
|
||||
"done": True,
|
||||
"last_ok": {"amqp_new": 103.5, "pg_open": 90.0, "s3_key": 191.0},
|
||||
},
|
||||
]
|
||||
found = track1.windows(events)
|
||||
assert found["amqp_new"] == {"window": 3.5, "after_end": False}
|
||||
assert found["pg_open"] == {"window": 0.0, "after_end": False}
|
||||
assert found["s3_key"]["after_end"] is True
|
||||
|
||||
|
||||
def _thresholds() -> dict:
|
||||
return json.loads((TRACK1 / "hypotheses.json").read_text())["hypotheses"]
|
||||
|
||||
|
||||
def test_verdicts_follow_the_thresholds() -> None:
|
||||
materials = _thresholds()["H2"]["thresholds"]["windows_seconds"]
|
||||
good = {
|
||||
"H2": {
|
||||
"rounds": [{m: {"window": 3.0, "after_end": False} for m in materials}],
|
||||
"failed_requests": 0,
|
||||
},
|
||||
"H3": {
|
||||
"accepted": 10,
|
||||
"lost": 0,
|
||||
"duplicated": 0,
|
||||
"wrong_sha256": 0,
|
||||
"ready_seconds": 30.0,
|
||||
},
|
||||
"H4": {
|
||||
"damaged": 6,
|
||||
"found": 6,
|
||||
"missed_damage": 0,
|
||||
"left_after_repair": 0,
|
||||
"overwrites": 1,
|
||||
"missed_overwrites": 0,
|
||||
},
|
||||
"H5": {"lost": {"a": 1, "b": 2}, "failed_actions": 0},
|
||||
}
|
||||
assert all(ok for ok, _ in track1.verdicts(_thresholds(), good).values())
|
||||
bad = json.loads(json.dumps(good))
|
||||
bad["H2"]["rounds"][0]["amqp_new"] = {"window": 16.0, "after_end": False}
|
||||
bad["H3"]["lost"] = 1
|
||||
bad["H4"]["missed_damage"] = 1
|
||||
bad["H5"]["lost"]["a"] = 0
|
||||
results = track1.verdicts(_thresholds(), bad)
|
||||
assert not any(ok for ok, _ in results.values())
|
||||
after_end = json.loads(json.dumps(good))
|
||||
after_end["H2"]["rounds"][0]["amqp_new"] = {"window": 1.0, "after_end": True}
|
||||
assert not track1.verdicts(_thresholds(), after_end)["H2"][0]
|
||||
# материал без единого успеха не измерен — гипотеза не подтверждается
|
||||
missing = json.loads(json.dumps(good))
|
||||
del missing["H2"]["rounds"][0]["pg_open"]
|
||||
ok, text = track1.verdicts(_thresholds(), missing)["H2"]
|
||||
assert not ok
|
||||
assert "pg_open not measured" in text
|
||||
|
||||
|
||||
def test_table_summary_counts_closed_and_outside() -> None:
|
||||
before = {op.id: op.before for op in operations.OPERATIONS}
|
||||
after = {op.id: op.after for op in operations.OPERATIONS}
|
||||
summary = track1.table_summary(before, after)
|
||||
assert summary["unexpected_after"] == []
|
||||
assert summary["outside_available"] == []
|
||||
assert summary["closed_share"] >= 0.67
|
||||
widened = dict(after, **{"pg.select.users": "ok"})
|
||||
summary = track1.table_summary(before, widened)
|
||||
assert summary["outside_available"] == ["pg.select.users"]
|
||||
assert [x[0] for x in summary["unexpected_after"]] == ["pg.select.users"]
|
||||
verdict = track1.verdicts(_thresholds(), {"H1": summary})["H1"]
|
||||
assert not verdict[0]
|
||||
|
||||
|
||||
def test_png_is_distinct_per_seed() -> None:
|
||||
first, second = track1.png(1), track1.png(2)
|
||||
assert first.startswith(b"\x89PNG\r\n\x1a\n")
|
||||
assert first != second
|
||||
|
||||
|
||||
# --- override, гипотезы, цели make, Codex --------------------------------------
|
||||
|
||||
|
||||
def test_overrides_do_not_touch_the_working_stand() -> None:
|
||||
working_image = "mtusi-messenger-vladimirceva:lab7"
|
||||
for name, tag in (
|
||||
("stand.compose.yml", ":track1"),
|
||||
("before.compose.yml", ":track1-before"),
|
||||
):
|
||||
text = (TRACK1 / name).read_text(encoding="utf-8")
|
||||
assert not re.search(r"^name:", text, re.M), name
|
||||
assert f"image: {working_image}\n" not in text
|
||||
assert f"mtusi-messenger-vladimirceva{tag}" in text
|
||||
assert "10.207." not in "".join(
|
||||
line for line in text.splitlines() if not line.lstrip().startswith("#")
|
||||
)
|
||||
assert re.findall(r"subnet: (10\.217\.\d+\.0/24)", text)
|
||||
before = (TRACK1 / "before.compose.yml").read_text(encoding="utf-8")
|
||||
for service in ("postgres", "valkey", "s3", "rabbitmq", "grafana"):
|
||||
assert re.search(rf"^ {service}:\n ports: !reset \[\]", before, re.M), (
|
||||
service
|
||||
)
|
||||
assert '"127.0.0.1:${TRACK1_LB_PORT:-0}:8080"' in before
|
||||
|
||||
|
||||
def test_hypotheses_cover_h1_to_h5() -> None:
|
||||
data = json.loads((TRACK1 / "hypotheses.json").read_text())
|
||||
assert set(data["hypotheses"]) == {"H1", "H2", "H3", "H4", "H5"}
|
||||
assert data["min_rounds"] >= 3
|
||||
assert data["before_commit"] == "3e8493b"
|
||||
assert all(
|
||||
item["text"] and item["thresholds"] for item in data["hypotheses"].values()
|
||||
)
|
||||
|
||||
|
||||
def test_make_targets_and_codex_rules() -> None:
|
||||
makefile = (ROOT / "Makefile").read_text(encoding="utf-8")
|
||||
rules = (ROOT / ".codex" / "rules" / "messenger.rules").read_text(encoding="utf-8")
|
||||
for target in ("jobs-audit", "worker-compromise"):
|
||||
assert re.search(rf"^{target}:", makefile, re.M), target
|
||||
assert f'"{target}"' in rules, target
|
||||
assert 'pattern = ["make", "jobs-audit", "REPAIR=1"]' in rules
|
||||
assert "infra/incident/jobs.sh $(if $(REPAIR),repair,audit)" in makefile
|
||||
Reference in New Issue
Block a user