forked from mtusi2026/mtusi2026lab7
Storage servers accept only TLS 1.3 (pg_hba hostssl / hostnossl reject, Valkey port 0, S3 gateway HTTPS only) with stand identities postgres, valkey and s3. Clients trust only the stand CA from [client_tls] ca_file and check the host name; no switch to disable verification. Processes exit with code 2 without a CA or with an IP storage address. Temporary stands, CI and bench/ run on TLS storages; make storage_tls_check adds negative checks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
421 lines
15 KiB
Python
421 lines
15 KiB
Python
"""Значения `[uploads]` (спек `service-configuration`, «Неверный параметр
|
||
загрузок») и сочетание срока остановки API с телеметрией (спек
|
||
`graceful-shutdown`, «Остановка при недоступном Collector»). Секция или
|
||
`Settings` только из аргументов: настоящий читает `.env` и `config.toml`.
|
||
"""
|
||
|
||
import re
|
||
import socket
|
||
from typing import Any
|
||
|
||
import pytest
|
||
from pydantic import ValidationError
|
||
from pydantic_settings import (
|
||
BaseSettings,
|
||
PydanticBaseSettingsSource,
|
||
SettingsConfigDict,
|
||
TomlConfigSettingsSource,
|
||
)
|
||
|
||
from src.config.settings import (
|
||
BASE_DIR,
|
||
ApiTls,
|
||
App,
|
||
Auth,
|
||
Settings,
|
||
Telemetry,
|
||
Uploads,
|
||
Worker,
|
||
)
|
||
from src.schemas.enums import MetricBucketsEnum
|
||
from src.utils.constants import (
|
||
API_STOP_BUDGET_SECONDS,
|
||
CONTAINER_STOP_TIMEOUT_SECONDS,
|
||
HTTP_DURATION_BUCKETS,
|
||
HTTP_DURATION_BUCKETS_COARSE,
|
||
JOB_DURATION_BUCKETS,
|
||
JOB_DURATION_BUCKETS_COARSE,
|
||
TELEMETRY_EXPORTER_SERIES_EXPIRATION_SECONDS,
|
||
TELEMETRY_METRIC_EXPORT_INTERVAL_MAX_SECONDS,
|
||
TELEMETRY_SHUTDOWN_TIMEOUT_SECONDS,
|
||
TIME_TO_READY_BUCKETS,
|
||
TIME_TO_READY_BUCKETS_COARSE,
|
||
)
|
||
from src.worker import main as worker_main
|
||
|
||
EXAMPLE_TOML_PATH = BASE_DIR.joinpath("config_example.toml")
|
||
|
||
|
||
class _ArgumentsOnly(Settings):
|
||
"""`Settings` без окружения, `.env` и `config.toml`."""
|
||
|
||
model_config = SettingsConfigDict(
|
||
**{**Settings.model_config, "env_file": None, "toml_file": None},
|
||
)
|
||
|
||
@classmethod
|
||
def settings_customise_sources(
|
||
cls,
|
||
settings_cls: type[BaseSettings], # noqa: ARG003
|
||
init_settings: PydanticBaseSettingsSource,
|
||
*args: PydanticBaseSettingsSource, # noqa: ARG003
|
||
**kwargs: Any, # noqa: ARG003
|
||
) -> tuple[PydanticBaseSettingsSource, ...]:
|
||
return (init_settings,)
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("field", "value"),
|
||
[
|
||
("max_concurrent", 0),
|
||
("max_waiting", -1),
|
||
("max_unfinished_jobs", -1),
|
||
("body_timeout_seconds", "abc"),
|
||
],
|
||
)
|
||
def test_wrong_value_names_field(field: str, value: object) -> None:
|
||
with pytest.raises(ValidationError) as caught:
|
||
Uploads(**{field: value})
|
||
assert [error["loc"] for error in caught.value.errors()] == [(field,)]
|
||
|
||
|
||
def test_zero_turns_backlog_limit_off() -> None:
|
||
assert Uploads(max_unfinished_jobs=0).max_unfinished_jobs == 0
|
||
assert Uploads().max_unfinished_jobs == 250
|
||
|
||
|
||
def test_instance_id_defaults_to_random_alias() -> None:
|
||
"""Спек `service-configuration`, «Случайный alias по умолчанию»: 16
|
||
hex-символов, у каждой загрузки настроек свой, без hostname."""
|
||
first, second = App().instance_id, App().instance_id
|
||
assert re.fullmatch(r"[0-9a-f]{16}", first)
|
||
assert first != second
|
||
assert first != socket.gethostname()
|
||
|
||
|
||
def test_explicit_instance_id() -> None:
|
||
assert App(instance_id="api-a").instance_id == "api-a"
|
||
|
||
|
||
def test_wrong_instance_id_names_field() -> None:
|
||
with pytest.raises(ValidationError) as caught:
|
||
App(instance_id="api a")
|
||
assert [error["loc"] for error in caught.value.errors()] == [
|
||
("instance_id",),
|
||
]
|
||
|
||
|
||
def test_health_port_must_differ_from_port() -> None:
|
||
with pytest.raises(ValidationError) as caught:
|
||
App(port=9000, health_port=9000)
|
||
assert [error["loc"] for error in caught.value.errors()] == [
|
||
("health_port",),
|
||
]
|
||
assert App().health_port == 8081
|
||
|
||
|
||
def test_api_tls_defaults_require_client_certificate() -> None:
|
||
tls = ApiTls()
|
||
assert tls.client_auth is True
|
||
assert tls.allowed_clients == ["haproxy"]
|
||
|
||
|
||
def test_api_stop_with_telemetry_over_budget_names_field() -> None:
|
||
"""9 с дренажа + 1 с закрытия SDK — SIGKILL docker (verify W3)."""
|
||
with pytest.raises(ValidationError) as caught:
|
||
_ArgumentsOnly(
|
||
app={"graceful_shutdown_seconds": 9},
|
||
telemetry={"enabled": True},
|
||
)
|
||
errors = caught.value.errors(include_input=False)
|
||
assert [error["loc"] for error in errors] == [("telemetry",)]
|
||
assert "app.graceful_shutdown_seconds" in errors[0]["msg"]
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("graceful", "enabled"),
|
||
[(9, False), (8, True), (1, True)],
|
||
)
|
||
def test_api_stop_within_budget(graceful: int, enabled: bool) -> None:
|
||
loaded = _ArgumentsOnly(
|
||
app={"graceful_shutdown_seconds": graceful},
|
||
telemetry={"enabled": enabled},
|
||
)
|
||
assert loaded.app.graceful_shutdown_seconds == graceful
|
||
|
||
|
||
def test_budgets_fit_container_stop() -> None:
|
||
"""API: дренаж до 8 с + закрытие SDK; worker: ожидание до 8 с, отмена,
|
||
потребитель и одно окно `gather` с закрытием SDK — по 0,5 с."""
|
||
assert API_STOP_BUDGET_SECONDS < CONTAINER_STOP_TIMEOUT_SECONDS
|
||
assert 8 + TELEMETRY_SHUTDOWN_TIMEOUT_SECONDS <= API_STOP_BUDGET_SECONDS
|
||
with pytest.raises(ValidationError):
|
||
Worker(graceful_shutdown_seconds=8.01)
|
||
worker_worst = 8 + 3 * worker_main._CLOSE_TIMEOUT_SECONDS
|
||
assert worker_worst < CONTAINER_STOP_TIMEOUT_SECONDS
|
||
|
||
|
||
# выбор трасс в голове и набор границ (design change `track1-telemetry-cost`,
|
||
# решения 3–4; спек `service-configuration`, «Параметры телеметрии»)
|
||
|
||
|
||
class _EnvironmentOnly(_ArgumentsOnly):
|
||
"""`Settings` из окружения процесса, без `.env` и `config.toml`."""
|
||
|
||
@classmethod
|
||
def settings_customise_sources(
|
||
cls,
|
||
settings_cls: type[BaseSettings], # noqa: ARG003
|
||
init_settings: PydanticBaseSettingsSource,
|
||
env_settings: PydanticBaseSettingsSource,
|
||
*args: PydanticBaseSettingsSource, # noqa: ARG003
|
||
**kwargs: Any, # noqa: ARG003
|
||
) -> tuple[PydanticBaseSettingsSource, ...]:
|
||
return (init_settings, env_settings)
|
||
|
||
|
||
class _ExampleToml(_ArgumentsOnly):
|
||
"""`Settings` только из `config_example.toml`, как из `config.toml`."""
|
||
|
||
model_config = SettingsConfigDict(
|
||
**{**_ArgumentsOnly.model_config, "toml_file": EXAMPLE_TOML_PATH},
|
||
)
|
||
|
||
@classmethod
|
||
def settings_customise_sources(
|
||
cls,
|
||
settings_cls: type[BaseSettings],
|
||
init_settings: PydanticBaseSettingsSource,
|
||
*args: PydanticBaseSettingsSource, # noqa: ARG003
|
||
**kwargs: Any, # noqa: ARG003
|
||
) -> tuple[PydanticBaseSettingsSource, ...]:
|
||
return (init_settings, TomlConfigSettingsSource(settings_cls))
|
||
|
||
|
||
def test_telemetry_defaults_keep_previous_behaviour() -> None:
|
||
loaded = Telemetry()
|
||
assert loaded.trace_sample_ratio == 1
|
||
assert loaded.metric_buckets is MetricBucketsEnum.DEFAULT
|
||
assert loaded.metric_export_interval_seconds == 15
|
||
|
||
|
||
@pytest.mark.parametrize("ratio", [0, 0.1, 0.5, 1])
|
||
def test_trace_sample_ratio_accepts_range(ratio: float) -> None:
|
||
assert Telemetry(trace_sample_ratio=ratio).trace_sample_ratio == ratio
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("field", "value"),
|
||
[
|
||
("trace_sample_ratio", 1.5),
|
||
("trace_sample_ratio", -0.1),
|
||
("trace_sample_ratio", float("nan")),
|
||
("trace_sample_ratio", "nan"),
|
||
("metric_buckets", "fine"),
|
||
("metric_export_interval_seconds", 60),
|
||
("metric_export_interval_seconds", -1),
|
||
],
|
||
)
|
||
def test_wrong_telemetry_value_names_field(field: str, value: object) -> None:
|
||
with pytest.raises(ValidationError) as caught:
|
||
Telemetry(**{field: value})
|
||
assert [error["loc"] for error in caught.value.errors()] == [(field,)]
|
||
|
||
|
||
def test_export_interval_up_to_half_of_series_expiration() -> None:
|
||
limit = TELEMETRY_METRIC_EXPORT_INTERVAL_MAX_SECONDS
|
||
assert limit * 2 == TELEMETRY_EXPORTER_SERIES_EXPIRATION_SECONDS
|
||
assert Telemetry(metric_export_interval_seconds=limit)
|
||
with pytest.raises(ValidationError):
|
||
Telemetry(metric_export_interval_seconds=limit + 0.1)
|
||
|
||
|
||
def test_coarse_buckets_keep_slo_bounds() -> None:
|
||
assert 0.25 in HTTP_DURATION_BUCKETS_COARSE
|
||
assert 30 in TIME_TO_READY_BUCKETS_COARSE
|
||
assert HTTP_DURATION_BUCKETS_COARSE[-1] == HTTP_DURATION_BUCKETS[-1]
|
||
assert JOB_DURATION_BUCKETS_COARSE[-1] == JOB_DURATION_BUCKETS[-1]
|
||
assert TIME_TO_READY_BUCKETS_COARSE[-1] == TIME_TO_READY_BUCKETS[-1]
|
||
|
||
|
||
def test_telemetry_from_environment(monkeypatch: pytest.MonkeyPatch) -> None:
|
||
monkeypatch.setenv("TELEMETRY__TRACE_SAMPLE_RATIO", "0.1")
|
||
monkeypatch.setenv("TELEMETRY__METRIC_BUCKETS", "coarse")
|
||
loaded = _EnvironmentOnly()
|
||
assert loaded.telemetry.trace_sample_ratio == 0.1
|
||
assert loaded.telemetry.metric_buckets is MetricBucketsEnum.COARSE
|
||
|
||
|
||
def test_client_tls_from_environment(monkeypatch: pytest.MonkeyPatch) -> None:
|
||
"""Спек `service-configuration`, «Доверие к серверам зависимостей»: CA —
|
||
из окружения процесса (compose и цели make), по умолчанию пусто."""
|
||
assert _EnvironmentOnly().client_tls.ca_file == ""
|
||
monkeypatch.setenv("CLIENT_TLS__CA_FILE", "/run/secrets/ca.crt")
|
||
assert _EnvironmentOnly().client_tls.ca_file == "/run/secrets/ca.crt"
|
||
|
||
|
||
def test_s3_endpoint_is_https() -> None:
|
||
"""Шлюз S3 — только HTTPS (change `storage-tls`): URL с именем хоста."""
|
||
s3 = _ArgumentsOnly(s3={"host": "s3", "port": 8333}).s3
|
||
assert s3.endpoint_url == "https://s3:8333"
|
||
|
||
|
||
def test_example_toml_has_no_client_tls() -> None:
|
||
"""Путь CA задают compose и цели make, в `config_example.toml` его нет:
|
||
toml смонтирован и в консоль, и в контейнеры с разными путями."""
|
||
assert "client_tls" not in EXAMPLE_TOML_PATH.read_text()
|
||
|
||
|
||
def test_wrong_ratio_from_environment_names_field(
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
) -> None:
|
||
monkeypatch.setenv("TELEMETRY__TRACE_SAMPLE_RATIO", "1.5")
|
||
with pytest.raises(ValidationError) as caught:
|
||
_EnvironmentOnly()
|
||
assert [error["loc"] for error in caught.value.errors()] == [
|
||
("telemetry", "trace_sample_ratio"),
|
||
]
|
||
|
||
|
||
def test_example_toml_loads_as_config_toml() -> None:
|
||
"""`config_example.toml` — рабочий `config.toml` (задача 2.4)."""
|
||
loaded = _ExampleToml()
|
||
assert loaded.telemetry.trace_sample_ratio == 1
|
||
assert loaded.telemetry.metric_buckets is MetricBucketsEnum.DEFAULT
|
||
|
||
|
||
# параметры пароля и входа (design change `auth-hardening`, решения 1, 3, 5;
|
||
# спек `service-configuration`, «Параметры пароля и входа»)
|
||
|
||
# итог замеров: строка «Выбрано» evidence/auth/argon2-params.md и сводка
|
||
# метки профиля login (QUESTIONS.md, раздел auth-hardening)
|
||
MEASURED_AUTH_DEFAULTS = {
|
||
"argon2_time_cost": 2,
|
||
"argon2_memory_kib": 65536,
|
||
"argon2_parallelism": 1,
|
||
"kdf_concurrency": 1,
|
||
"kdf_max_waiting": 16,
|
||
"kdf_wait_timeout_seconds": 2,
|
||
"login_window_seconds": 300,
|
||
"login_max_failures_per_account": 10,
|
||
"login_max_failures_per_address": 200,
|
||
}
|
||
EVIDENCE_ARGON2 = BASE_DIR.joinpath("evidence/auth/argon2-params.md")
|
||
|
||
|
||
def test_auth_defaults_match_measurements() -> None:
|
||
loaded = Auth()
|
||
assert {
|
||
field: getattr(loaded, field) for field in MEASURED_AUTH_DEFAULTS
|
||
} == MEASURED_AUTH_DEFAULTS
|
||
|
||
|
||
def test_argon2_defaults_named_in_evidence() -> None:
|
||
"""Строка выбора evidence совпадает с умолчаниями (задача 2.3)."""
|
||
text = EVIDENCE_ARGON2.read_text(encoding="utf-8")
|
||
chosen = (
|
||
f"Выбрано: m={MEASURED_AUTH_DEFAULTS['argon2_memory_kib']} KiB, "
|
||
f"t={MEASURED_AUTH_DEFAULTS['argon2_time_cost']}, "
|
||
f"p={MEASURED_AUTH_DEFAULTS['argon2_parallelism']}"
|
||
)
|
||
assert chosen in text
|
||
|
||
|
||
def test_example_toml_keeps_auth_defaults() -> None:
|
||
loaded = _ExampleToml()
|
||
assert loaded.auth == Auth()
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("field", "value"),
|
||
[
|
||
("argon2_memory_kib", 19455),
|
||
("argon2_memory_kib", 8192),
|
||
("argon2_time_cost", 1),
|
||
("argon2_parallelism", 0),
|
||
("kdf_concurrency", 0),
|
||
("kdf_max_waiting", -1),
|
||
("kdf_wait_timeout_seconds", 0),
|
||
("kdf_wait_timeout_seconds", float("inf")),
|
||
("login_window_seconds", 0),
|
||
("login_max_failures_per_account", -1),
|
||
("login_max_failures_per_address", -1),
|
||
],
|
||
)
|
||
def test_wrong_auth_value_names_field(field: str, value: object) -> None:
|
||
with pytest.raises(ValidationError) as caught:
|
||
Auth(**{field: value})
|
||
assert [error["loc"] for error in caught.value.errors()] == [(field,)]
|
||
|
||
|
||
@pytest.mark.parametrize(
|
||
("field", "value"),
|
||
[
|
||
("argon2_memory_kib", 19456),
|
||
("argon2_time_cost", 2),
|
||
("argon2_parallelism", 1),
|
||
("kdf_max_waiting", 0),
|
||
("login_max_failures_per_account", 0),
|
||
("login_max_failures_per_address", 0),
|
||
],
|
||
)
|
||
def test_auth_lower_bounds_accepted(field: str, value: object) -> None:
|
||
assert getattr(Auth(**{field: value}), field) == value
|
||
|
||
|
||
@pytest.mark.parametrize("wait", [6, 7])
|
||
def test_kdf_wait_not_shorter_than_request_names_field(wait: float) -> None:
|
||
with pytest.raises(ValidationError) as caught:
|
||
_ArgumentsOnly(
|
||
database={"request_timeout_seconds": 6},
|
||
auth={"kdf_wait_timeout_seconds": wait},
|
||
)
|
||
errors = caught.value.errors()
|
||
assert [error["loc"] for error in errors] == [("auth",)]
|
||
assert "auth.kdf_wait_timeout_seconds" in errors[0]["msg"]
|
||
# в ошибке нет значения секции database (там пароль)
|
||
assert "password" not in str(caught.value)
|
||
|
||
|
||
def test_kdf_wait_shorter_than_request() -> None:
|
||
loaded = _ArgumentsOnly(
|
||
database={"request_timeout_seconds": 2},
|
||
auth={"kdf_wait_timeout_seconds": 1},
|
||
)
|
||
assert loaded.auth.kdf_wait_timeout_seconds == 1
|
||
|
||
|
||
def test_auth_from_environment_over_file(
|
||
monkeypatch: pytest.MonkeyPatch,
|
||
tmp_path: Any,
|
||
) -> None:
|
||
toml = tmp_path.joinpath("config.toml")
|
||
toml.write_text(
|
||
"[auth]\nlogin_max_failures_per_account = 7\n",
|
||
encoding="utf-8",
|
||
)
|
||
|
||
class _EnvAndToml(_ArgumentsOnly):
|
||
model_config = SettingsConfigDict(
|
||
**{**_ArgumentsOnly.model_config, "toml_file": toml},
|
||
)
|
||
|
||
@classmethod
|
||
def settings_customise_sources(
|
||
cls,
|
||
settings_cls: type[BaseSettings],
|
||
init_settings: PydanticBaseSettingsSource,
|
||
env_settings: PydanticBaseSettingsSource,
|
||
*args: PydanticBaseSettingsSource, # noqa: ARG003
|
||
**kwargs: Any, # noqa: ARG003
|
||
) -> tuple[PydanticBaseSettingsSource, ...]:
|
||
return (
|
||
init_settings,
|
||
env_settings,
|
||
TomlConfigSettingsSource(settings_cls),
|
||
)
|
||
|
||
assert _EnvAndToml().auth.login_max_failures_per_account == 7
|
||
monkeypatch.setenv("AUTH__LOGIN_MAX_FAILURES_PER_ACCOUNT", "3")
|
||
assert _EnvAndToml().auth.login_max_failures_per_account == 3
|