Files
mtusi2026lab7-safronov/service-tests/unit/test_telemetry_backends_tls.py
T
2026-11-26 11:34:03 +03:00

874 lines
36 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Согласованность конфигураций каналов телеметрии без стенда (change
`telemetry-backends-tls`, design, решения 3–9, 13; спеки
`transport-security`, «mTLS к хранилищам телеметрии», «Метрики
балансировщика и Collector по mTLS», «Grafana по HTTPS», «Шлюзы хранилищ
телеметрии без обхода»).
- Allowlist и права шлюзов хранилищ, порта метрик LB и портов метрик шлюза
Collector — DNS SAN строк `infra/pki/identities.conf`: ни больше, ни меньше.
- У каждого `bind … ssl` (кроме ingress LB) — `verify required`,
`ssl-min-ver TLSv1.3`, CA и CRL стенда, серверный `.pem` строки списка;
остальные слушатели шлюзов — только loopback.
- Loki, Tempo и Prometheus слушают только `127.0.0.1`, работают в сетевом
пространстве своего шлюза и своих сетей не имеют; бэкенды шлюзов — порты
хранилищ на loopback.
- Сетевые цели `prometheus.yml` (и копии `bench/otel/prometheus-lean.yml`) —
`https` и `tls_config` с CA, парой `prometheus-client` и TLS 1.3, цель
`prometheus` — loopback.
- Экспортёры и приёмник LB Collector — TLS с парой `otel-collector-client`,
его метрики — только loopback.
- Источники Grafana — `https`, `tlsAuth`, `tlsAuthWithCACert`, `$__file{}` без
PEM в файле; потоковые запросы Tempo выключены.
Проверки — функции над корнем репозитория: тесты зовут их на рабочем дереве и
на копии с внесённой ошибкой (контроль: тест называет файл и строку).
"""
import re
import shutil
from pathlib import Path
import pytest
import yaml
from src.config.settings import BASE_DIR
# (файл шлюза, frontend) → строки identities.conf, чьи DNS SAN — allowlist
ALLOWLISTS: dict[tuple[str, str], tuple[str, ...]] = {
("infra/otel/loki-gateway.cfg", "loki_in"): (
"otel-collector-client",
"grafana-client",
"prometheus-client",
),
("infra/otel/tempo-gateway.cfg", "otlp_in"): ("otel-collector-client",),
("infra/otel/tempo-gateway.cfg", "query_in"): (
"grafana-client",
"prometheus-client",
),
("infra/otel/prometheus-gateway.cfg", "prometheus_in"): (
"grafana-client",
),
("infra/otel/gateway.cfg", "metrics_own"): ("prometheus-client",),
("infra/otel/gateway.cfg", "metrics_app"): ("prometheus-client",),
("infra/haproxy/haproxy.cfg", "monitor"): ("otel-collector-client",),
}
# права по identity (решение 4): frontend → identity → методы её правил allow.
# Collector только пишет (POST экспорта OTLP), Grafana только читает (у
# Prometheus — ещё POST запросов API), Prometheus только забирает метрики.
# Порты метрик (metrics_*, monitor) — одна identity и путь /metrics: права —
# правило deny по пути, их проверяет allowlist
RIGHTS: dict[tuple[str, str], dict[str, set[str]]] = {
("infra/otel/loki-gateway.cfg", "loki_in"): {
"otel-collector": {"POST"},
"grafana": {"GET"},
"prometheus": {"GET"},
},
("infra/otel/tempo-gateway.cfg", "otlp_in"): {"otel-collector": {"POST"}},
("infra/otel/tempo-gateway.cfg", "query_in"): {
"grafana": {"GET"},
"prometheus": {"GET"},
},
("infra/otel/prometheus-gateway.cfg", "prometheus_in"): {
"grafana": {"GET", "POST"},
},
}
# пути, которых нет ни у одной identity (решение 4): запись мимо OTLP,
# удаление, служебные и административные пути
FORBIDDEN_IN_ALLOW = ("push", "delete", "compactor", "/config", "/flush")
# путь экспорта OTLP Collector и путь метрик Prometheus — точно
EXACT_PATHS = {
"otel-collector": {"/otlp/v1/logs", "/v1/traces"},
"prometheus": {"/metrics"},
}
# серверный .pem bind → строка списка (profile server)
SERVER_PEMS = {
"infra/otel/loki-gateway.cfg": {"loki"},
"infra/otel/tempo-gateway.cfg": {"tempo"},
"infra/otel/prometheus-gateway.cfg": {"prometheus"},
"infra/otel/gateway.cfg": {"otel-collector"},
"infra/haproxy/haproxy.cfg": {"ingress"},
}
GATEWAY_FILES = tuple(SERVER_PEMS)
# frontend ingress LB: TLS ≥ 1.2 без сертификата клиента — по design
INGRESS = ("infra/haproxy/haproxy.cfg", "entry")
# хранилище → (шлюз, его конфигурация, бэкенды на loopback)
STORAGES = {
"loki": ("loki-gateway", "infra/otel/loki-gateway.cfg", {"13100"}),
"tempo": (
"tempo-gateway",
"infra/otel/tempo-gateway.cfg",
{"13200", "14318"},
),
"prometheus": (
"prometheus-gateway",
"infra/otel/prometheus-gateway.cfg",
{"19090"},
),
}
PROMETHEUS_FILES = (
"infra/otel/prometheus/prometheus.yml",
"bench/otel/prometheus-lean.yml",
)
# отказ шлюза первой строкой (правки verify, W1, S1): путь, который хранилище
# раскодирует или нормализует иначе, чем сравнивает шлюз
UNSAFE_ACL = "unsafe_path"
# без обратной косой (HAProxy снимает её в словах конфигурации без кавычек) и
# без «(» в начале (предупреждение HAProxy): путь всегда начинается с «/»
DOT_SEGMENT = "/[.][.]?(/|$)"
# единственное исключение из «%»: %3A порта запросов Tempo — Grafana кодирует
# им двоеточие встроенных тегов (span:name) в подсказках значений TraceQL
PERCENT_EXCEPTIONS = {
("infra/otel/tempo-gateway.cfg", "query_in"): "%(?!3[Aa])",
}
SECRETS = "/run/secrets/"
FILE_REF = re.compile(r"^\$__file\{/run/secrets/[A-Za-z0-9._-]+\}$")
def identity_rows(root: Path) -> dict[str, tuple[str, list[str]]]:
"""Строки identities.conf: имя → (профиль, DNS SAN)."""
rows: dict[str, tuple[str, list[str]]] = {}
path = root / "infra" / "pki" / "identities.conf"
for line in path.read_text(encoding="utf-8").splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
name, profile, sans, _form = line.split()[:4]
rows[name] = (profile, sans.split(","))
return rows
def sections(
root: Path,
rel: str,
) -> dict[tuple[str, str], list[tuple[int, str]]]:
"""Разделы конфигурации HAProxy: (тип, имя) → (номер строки, строка) без
комментариев."""
out: dict[tuple[str, str], list[tuple[int, str]]] = {}
current: tuple[str, str] | None = None
text = (root / rel).read_text(encoding="utf-8")
for number, raw in enumerate(text.splitlines(), start=1):
stripped = raw.strip()
if not stripped or stripped.startswith("#"):
continue
if not raw[0].isspace():
words = stripped.split()
current = (words[0], words[1] if len(words) > 1 else "")
out[current] = []
continue
if current is not None:
out[current].append((number, stripped))
return out
def line_of(root: Path, rel: str, needle: str) -> int:
"""Номер первой строки файла с `needle` (0 — нет): для сообщений о YAML."""
text = (root / rel).read_text(encoding="utf-8")
for number, line in enumerate(text.splitlines(), start=1):
if needle in line:
return number
return 0
def allowlist_problems(root: Path) -> list[str]:
rows = identity_rows(root)
problems: list[str] = []
for (rel, frontend), names in ALLOWLISTS.items():
lines = sections(root, rel).get(("frontend", frontend))
if lines is None:
problems.append(f"{rel}: no frontend {frontend}")
continue
expected: set[str] = set()
for name in names:
profile, sans = rows.get(name, ("missing", []))
if profile != "client" or len(sans) != 1:
problems.append(
f"infra/pki/identities.conf: {name} is not a client row "
"with one DNS name",
)
continue
expected.add(sans[0])
allow = [
(number, line)
for number, line in lines
if line.startswith("tcp-request session set-var")
and "ssl_c_san -m str" in line
]
if len(allow) != 1:
problems.append(
f"{rel}: frontend {frontend}: {len(allow)} allowlist lines",
)
continue
number, line = allow[0]
got = set(re.findall(r"DNS:([A-Za-z0-9.-]+)", line))
if got != expected:
problems.append(
f"{rel}:{number}: frontend {frontend} allowlist "
f"{sorted(got)} != identities {sorted(expected)}",
)
if not any(
line.startswith("tcp-request session reject") for _, line in lines
):
problems.append(f"{rel}: frontend {frontend}: no reject")
# права: каждая identity правил allow — из allowlist порта
for number, line in lines:
for name in re.findall(r"DNS:([A-Za-z0-9.-]+)", line):
if name not in got:
problems.append(
f"{rel}:{number}: identity {name} outside the "
f"allowlist of {frontend}",
)
return problems
def unsafe_path_problems(
rel: str,
frontend: str,
lines: list[tuple[int, str]],
) -> list[str]:
"""Правки verify (W1, S1): первое правило HTTP frontend хранилища — 403
шлюза на путь, который хранилище прочтёт иначе, чем шлюз: `%XX`, `//`,
сегмент `.` или `..` (точка в начале имени — не сегмент)."""
problems: list[str] = []
definitions = [
line.split()[2:]
for _, line in lines
if line.split()[:2] == ["acl", UNSAFE_ACL]
]
subs = {w for d in definitions if d[0] == "path_sub" for w in d[1:]}
regs = {" ".join(d[1:]) for d in definitions if d[0] == "path_reg"}
percent = PERCENT_EXCEPTIONS.get((rel, frontend))
has_percent = "%" in subs if percent is None else percent in regs
if not has_percent or "//" not in subs or DOT_SEGMENT not in regs:
problems.append(
f"{rel}: frontend {frontend}: acl {UNSAFE_ACL} is not "
f"{percent or '%'}, // and {DOT_SEGMENT}",
)
rules = [(n, line) for n, line in lines if line.startswith("http-request")]
if not rules:
problems.append(f"{rel}: frontend {frontend}: no http-request rules")
return problems
number, first = rules[0]
if not (
first.startswith("http-request deny deny_status 403")
and "X-Gateway-Refused" in first
and first.endswith(f"if {UNSAFE_ACL}")
):
problems.append(
f"{rel}:{number}: frontend {frontend}: first rule is not the "
f"refusal of {UNSAFE_ACL}",
)
return problems
def rights_problems(root: Path) -> list[str]: # noqa: C901, PLR0912
"""Права по identity: `http-request allow` — только identity и методы
таблицы RIGHTS, пути Collector и Prometheus — точно, служебных путей нет,
затем `deny` 403 с признаком отказа шлюза; без `allow` по всему пути
(`path_beg /`)."""
problems: list[str] = []
for (rel, frontend), methods in RIGHTS.items():
allowed = set(methods)
lines = sections(root, rel)[("frontend", frontend)]
acls: dict[str, str] = {}
path_acls: dict[str, str] = {}
for _number, line in lines:
words = line.split()
if words[0] == "acl" and "ssl_c_san" in line:
names = re.findall(r"DNS:([A-Za-z0-9.-]+)", line)
if len(names) == 1:
acls[words[1]] = names[0]
if words[0] == "acl" and words[2] == "path_reg":
path_acls[words[1]] = " ".join(words[3:])
seen: set[str] = set()
allows = [
(n, line)
for n, line in lines
if line.startswith("http-request allow")
]
for number, line in allows:
ids = {acls[w] for w in line.split() if w in acls}
if len(ids) != 1:
problems.append(
f"{rel}:{number}: allow rule without one identity",
)
continue
identity = ids.pop()
seen.add(identity)
if identity not in allowed:
problems.append(
f"{rel}:{number}: identity {identity} has a right in "
f"{frontend}",
)
continue
used = set(re.findall(r"\bMETH_([A-Z]+)\b", line))
if not used or not used <= methods[identity]:
problems.append(
f"{rel}:{number}: identity {identity} methods "
f"{sorted(used)} beyond {sorted(methods[identity])}",
)
if re.search(r"path_beg\s+/(\s|$|\})", line):
problems.append(f"{rel}:{number}: allow on every path")
for word in FORBIDDEN_IN_ALLOW:
if word in line:
problems.append(f"{rel}:{number}: allow with {word}")
if identity in EXACT_PATHS:
paths = set(re.findall(r"\{\s*path\s+(\S+)\s*\}", line))
if not paths or not paths <= EXACT_PATHS[identity]:
problems.append(
f"{rel}:{number}: identity {identity} paths "
f"{sorted(paths) or 'not exact'}",
)
# явный список путей (правки verify, W1): хранилище сравнивает
# раскодированный путь, префикс сырого пути обходится через %XX
if "path_beg" in line:
problems.append(f"{rel}:{number}: allow by path prefix")
for word in line.split():
pattern = path_acls.get(word)
if pattern is not None and not (
pattern.startswith("^") and pattern.endswith("$")
):
problems.append(
f"{rel}:{number}: path list {word} is not anchored",
)
problems.extend(unsafe_path_problems(rel, frontend, lines))
if seen != allowed:
problems.append(
f"{rel}: frontend {frontend} rights for {sorted(seen)}, "
f"expected {sorted(allowed)}",
)
last_allow = max((n for n, _ in allows), default=0)
denies = [
(n, line)
for n, line in lines
if line.startswith("http-request deny")
and "deny_status 403" in line
and "X-Gateway-Refused" in line
]
if not denies or denies[-1][0] < last_allow:
problems.append(
f"{rel}: frontend {frontend}: no deny 403 with "
"X-Gateway-Refused after the rights",
)
return problems
def bind_problems(root: Path) -> list[str]:
rows = identity_rows(root)
problems: list[str] = []
for rel in GATEWAY_FILES:
for (kind, name), lines in sections(root, rel).items():
if kind != "frontend":
continue
for number, line in lines:
if not line.startswith("bind "):
continue
words = line.split()
where = f"{rel}:{number}"
if " ssl " not in f" {line} ":
if not words[1].startswith("127.0.0.1:"):
problems.append(
f"{where}: listener {words[1]} without TLS "
"outside loopback",
)
continue
if (rel, name) == INGRESS:
continue
for needed in (
"verify required",
"ssl-min-ver TLSv1.3",
"ca-file /run/secrets/ca.crt",
"crl-file /run/secrets/crl.pem",
):
if needed not in line:
problems.append(f"{where}: bind without {needed!r}")
pem = re.search(
r"crt /run/secrets/([A-Za-z0-9.-]+)\.pem",
line,
)
if pem is None or pem.group(1) not in SERVER_PEMS[rel]:
problems.append(f"{where}: unexpected server certificate")
elif rows.get(pem.group(1), ("",))[0] != "server":
problems.append(
f"{where}: {pem.group(1)} is not a server identity",
)
return problems
def _compose(root: Path) -> dict:
return yaml.safe_load((root / "docker-compose.yml").read_text("utf-8"))
def storage_problems(root: Path) -> list[str]:
problems: list[str] = []
services = _compose(root)["services"]
for storage, (gateway, rel, ports) in STORAGES.items():
service = services[storage]
where = f"docker-compose.yml:{line_of(root, 'docker-compose.yml', f' {storage}:')}"
if service.get("network_mode") != f"service:{gateway}":
problems.append(
f"{where}: {storage} not in the {gateway} namespace",
)
if service.get("networks"):
problems.append(f"{where}: {storage} has its own networks")
if service.get("ports"):
problems.append(f"{where}: {storage} publishes ports")
depends = (service.get("depends_on") or {}).get(gateway) or {}
if not depends.get("restart"):
problems.append(
f"{where}: {storage} without restart with {gateway}",
)
aliases = (
services[gateway].get("networks", {}).get("telemetry") or {}
).get("aliases") or []
if storage not in aliases:
problems.append(f"{where}: {gateway} without alias {storage}")
backends = {
match
for (kind, _), lines in sections(root, rel).items()
if kind == "backend"
for _, line in lines
for match in re.findall(r"^server \S+ 127\.0\.0\.1:(\d+)$", line)
}
servers = [
line
for (kind, _), lines in sections(root, rel).items()
if kind == "backend"
for _, line in lines
if line.startswith("server ")
]
if backends != ports or len(servers) != len(ports):
problems.append(
f"{rel}: backends {servers} != loopback {sorted(ports)}",
)
for rel, keys in (
("infra/otel/loki/loki.yaml", ("server",)),
("infra/otel/tempo/tempo.yaml", ("server",)),
):
config = yaml.safe_load((root / rel).read_text("utf-8"))
server = config.get("server") or {}
for key in ("http_listen_address", "grpc_listen_address"):
value = server.get(key)
if value != "127.0.0.1":
problems.append(
f"{rel}:{line_of(root, rel, key) or line_of(root, rel, 'server:')}: "
f"server.{key} = {value}",
)
if keys and rel.endswith("tempo.yaml"):
endpoint = config["distributor"]["receivers"]["otlp"]["protocols"][
"http"
]["endpoint"]
if not str(endpoint).startswith("127.0.0.1:"):
problems.append(
f"{rel}:{line_of(root, rel, 'endpoint:')}: OTLP receiver "
f"{endpoint}",
)
if config.get("stream_over_http_enabled") is not False:
problems.append(
f"{rel}:{line_of(root, rel, 'stream_over_http_enabled')}: "
"streaming over HTTP is on",
)
command = services["prometheus"].get("command") or []
listen = [
arg for arg in command if arg.startswith("--web.listen-address=")
]
if listen != ["--web.listen-address=127.0.0.1:19090"]:
problems.append(
"docker-compose.yml:"
f"{line_of(root, 'docker-compose.yml', '--web.listen-address') or line_of(root, 'docker-compose.yml', ' prometheus:')}: "
f"prometheus listens {listen or 'on all addresses'}",
)
for storage in ("loki", "tempo"):
if services[storage].get("secrets"):
problems.append(f"docker-compose.yml: {storage} has secrets")
return problems
def prometheus_problems(root: Path) -> list[str]:
problems: list[str] = []
for rel in PROMETHEUS_FILES:
config = yaml.safe_load((root / rel).read_text("utf-8"))
for job in config["scrape_configs"]:
name = job["job_name"]
where = f"{rel}:{line_of(root, rel, f'job_name: {name}')}"
targets = [
target
for static in job.get("static_configs") or []
for target in static.get("targets") or []
]
loopback = all(t.startswith("127.0.0.1:") for t in targets)
if loopback:
if name != "prometheus":
problems.append(f"{where}: loopback target of job {name}")
continue
tls = job.get("tls_config") or {}
if job.get("scheme") != "https":
problems.append(f"{where}: job {name} without scheme https")
expected = {
"ca_file": f"{SECRETS}ca.crt",
"cert_file": f"{SECRETS}prometheus-client.crt",
"key_file": f"{SECRETS}prometheus-client.key",
"min_version": "TLS13",
}
for key, value in expected.items():
if tls.get(key) != value:
problems.append(
f"{where}: job {name} tls_config.{key} = {tls.get(key)}",
)
if tls.get("insecure_skip_verify"):
problems.append(f"{where}: job {name} skips verification")
jobs = {job["job_name"] for job in config["scrape_configs"]}
if "haproxy" in jobs:
problems.append(f"{rel}: Prometheus scrapes the LB directly")
return problems
def collector_problems(root: Path) -> list[str]:
rel = "infra/otel/collector.yaml"
config = yaml.safe_load((root / rel).read_text("utf-8"))
problems: list[str] = []
client = {
"ca_file": f"{SECRETS}ca.crt",
"cert_file": f"{SECRETS}otel-collector-client.crt",
"key_file": f"{SECRETS}otel-collector-client.key",
}
for name in ("otlp_http/loki", "otlp_http/tempo"):
exporter = config["exporters"][name]
where = f"{rel}:{line_of(root, rel, name + ':')}"
endpoint = str(exporter.get("endpoint", ""))
if not endpoint.startswith("https://"):
number = line_of(root, rel, f"endpoint: {endpoint}")
problems.append(f"{rel}:{number}: {name} endpoint {endpoint}")
tls = exporter.get("tls") or {}
for key, value in {**client, "min_version": "1.3"}.items():
if tls.get(key) != value:
problems.append(f"{where}: {name} tls.{key} = {tls.get(key)}")
if tls.get("insecure") or tls.get("insecure_skip_verify"):
problems.append(f"{where}: {name} without verification")
scrape = config["receivers"]["prometheus/haproxy"]["config"][
"scrape_configs"
]
for job in scrape:
where = f"{rel}:{line_of(root, rel, 'job_name: ' + job['job_name'])}"
tls = job.get("tls_config") or {}
if job.get("scheme") != "https":
problems.append(f"{where}: LB scrape without https")
expected = {**client, "server_name": "ingress", "min_version": "TLS13"}
for key, value in expected.items():
if tls.get(key) != value:
problems.append(
f"{where}: LB scrape tls_config.{key} = {tls.get(key)}",
)
endpoint = str(config["exporters"]["prometheus"]["endpoint"])
if not endpoint.startswith("127.0.0.1:"):
problems.append(
f"{rel}:{line_of(root, rel, 'endpoint: ' + endpoint)}: exporter "
f"prometheus on {endpoint}",
)
for reader in config["service"]["telemetry"]["metrics"]["readers"]:
host = reader["pull"]["exporter"]["prometheus"]["host"]
if host != "127.0.0.1":
problems.append(
f"{rel}:{line_of(root, rel, 'host: ' + str(host))}: own metrics "
f"on {host}",
)
return problems
def grafana_problems(root: Path) -> list[str]:
rel = "infra/otel/grafana/datasources.yaml"
text = (root / rel).read_text("utf-8")
problems: list[str] = []
if "BEGIN" in text or "PRIVATE KEY" in text:
problems.append(f"{rel}: PEM content in the file")
for source in yaml.safe_load(text)["datasources"]:
uid = source["uid"]
where = f"{rel}:{line_of(root, rel, 'uid: ' + uid)}"
if not str(source.get("url", "")).startswith("https://"):
problems.append(f"{where}: source {uid} url {source.get('url')}")
data = source.get("jsonData") or {}
for key in ("tlsAuth", "tlsAuthWithCACert"):
if data.get(key) is not True:
problems.append(f"{where}: source {uid} without {key}")
if data.get("tlsSkipVerify"):
problems.append(f"{where}: source {uid} skips verification")
secure = source.get("secureJsonData") or {}
expected = {
"tlsCACert": "ca.crt",
"tlsClientCert": "grafana-client.crt",
"tlsClientKey": "grafana-client.key",
}
for key, name in expected.items():
value = str(secure.get(key, ""))
if not FILE_REF.match(value) or not value.endswith(f"/{name}}}"):
problems.append(
f"{where}: source {uid} {key} = {value or '-'}",
)
if uid == "tempo" and data.get("streamingEnabled") != {
"search": False,
"metrics": False,
}:
problems.append(f"{where}: Tempo streaming is not off")
return problems
CHECKS = (
allowlist_problems,
rights_problems,
bind_problems,
storage_problems,
prometheus_problems,
collector_problems,
grafana_problems,
)
@pytest.mark.parametrize("check", CHECKS, ids=lambda f: f.__name__)
def test_configuration(check) -> None: # noqa: ANN001
assert check(BASE_DIR) == []
def test_new_identities_rows() -> None:
"""Решение 5: серверные и клиентские строки новых identity."""
rows = identity_rows(BASE_DIR)
assert rows["loki"] == ("server", ["loki"])
assert rows["tempo"] == ("server", ["tempo"])
assert rows["prometheus"] == ("server", ["prometheus"])
assert rows["grafana"] == ("server", ["grafana", "localhost"])
assert rows["otel-collector-client"] == ("client", ["otel-collector"])
assert rows["prometheus-client"] == ("client", ["prometheus"])
assert rows["grafana-client"] == ("client", ["grafana"])
def _grafana_reaches(rel: str, frontend: str, path: str) -> bool:
"""Решение шлюза для `GET <path>` от `grafana` по правилам конфигурации:
отказ первой строкой (`unsafe_path`), затем список путей чтения. Регулярные
выражения HAProxy (PCRE2) здесь — те же для `re`: классы и якоря."""
lines = sections(BASE_DIR, rel)[("frontend", frontend)]
subs: list[str] = []
regs: list[str] = []
reads: list[str] = []
for _, line in lines:
words = line.split()
if words[:2] == ["acl", UNSAFE_ACL]:
(subs if words[2] == "path_sub" else regs).extend(words[3:])
elif words[0] == "acl" and words[2] == "path_reg":
reads.append(" ".join(words[3:]))
if any(s in path for s in subs) or any(re.search(r, path) for r in regs):
return False
return any(re.search(r, path) for r in reads)
@pytest.mark.parametrize(
("rel", "frontend", "path", "reaches"),
[
# Prometheus: явный список, служебные пути и обходы — нет (W1)
(
"infra/otel/prometheus-gateway.cfg",
"prometheus_in",
"/api/v1/query",
True,
),
(
"infra/otel/prometheus-gateway.cfg",
"prometheus_in",
"/api/v1/label/__name__/values",
True,
),
(
"infra/otel/prometheus-gateway.cfg",
"prometheus_in",
"/api/v1/status/buildinfo",
True,
),
*(
("infra/otel/prometheus-gateway.cfg", "prometheus_in", p, False)
for p 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/%77rite",
"/api/v1/otlp/v1/metrics",
"/api/v1/%6ftlp/v1/metrics",
"/api/v1/query/../admin/tsdb/snapshot",
"/api/v1//admin/tsdb/snapshot",
"/api/v1/query/",
"/federate",
"/metrics",
)
),
# Loki и Tempo: тот же отказ первой строкой (S1)
(
"infra/otel/loki-gateway.cfg",
"loki_in",
"/loki/api/v1/label/service_name/values",
True,
),
*(
("infra/otel/loki-gateway.cfg", "loki_in", p, False)
for p in (
"/loki/api/v1/label/..%2F..%2Fconfig/values",
"/loki/api/v1/labels/../../../config",
"/loki/api/v1/label/%2e%2e/values",
)
),
(
"infra/otel/tempo-gateway.cfg",
"query_in",
"/api/v2/search/tag/.service.name/values",
True,
),
(
"infra/otel/tempo-gateway.cfg",
"query_in",
"/api/v2/search/tag/resource.service.name/values",
True,
),
# встроенный тег с двоеточием — как его кодирует Grafana
(
"infra/otel/tempo-gateway.cfg",
"query_in",
"/api/v2/search/tag/span%3Aname/values",
True,
),
*(
("infra/otel/tempo-gateway.cfg", "query_in", p, False)
for p 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/%2e%2e/%2e%2e/status/config",
"/api/search/./x",
"/api/search/..",
"/api/search//x",
)
),
],
)
def test_gateway_path_decision(
rel: str,
frontend: str,
path: str,
reaches: bool, # noqa: FBT001
) -> None:
assert _grafana_reaches(rel, frontend, path) is reaches
# --- контроль: копия с ошибкой — красная проверка с файлом и строкой ----------
def _copy(tmp_path: Path) -> Path:
for rel in (
"infra/pki/identities.conf",
*GATEWAY_FILES,
*PROMETHEUS_FILES,
"infra/otel/collector.yaml",
"infra/otel/loki/loki.yaml",
"infra/otel/tempo/tempo.yaml",
"infra/otel/grafana/datasources.yaml",
"docker-compose.yml",
):
target = tmp_path / rel
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(BASE_DIR / rel, target)
return tmp_path
def _replace(root: Path, rel: str, old: str, new: str) -> int:
path = root / rel
text = path.read_text("utf-8")
assert old in text, (rel, old)
number = text[: text.index(old)].count("\n") + 1
path.write_text(text.replace(old, new, 1), "utf-8")
return number
@pytest.mark.parametrize(
("check", "rel", "old", "new"),
[
(
allowlist_problems,
"infra/otel/loki-gateway.cfg",
"DNS:otel-collector DNS:grafana DNS:prometheus }",
"DNS:otel-collector DNS:grafana DNS:prometheus DNS:haproxy }",
),
(
rights_problems,
"infra/otel/loki-gateway.cfg",
"http-request allow if id_grafana METH_GET read_path",
"http-request allow if id_grafana METH_GET read_path\n"
" http-request allow if id_grafana METH_POST { path /otlp/v1/logs }",
),
(
rights_problems,
"infra/otel/prometheus-gateway.cfg",
" http-request deny deny_status 403 hdr X-Gateway-Refused "
"prometheus-gateway if unsafe_path\n",
"",
),
(
rights_problems,
"infra/otel/loki-gateway.cfg",
"acl unsafe_path path_sub % //",
"acl unsafe_path path_sub %",
),
(
rights_problems,
"infra/otel/prometheus-gateway.cfg",
"http-request allow if id_grafana METH_GET read_path",
"http-request allow if id_grafana METH_GET { path_beg /api/v1/ }",
),
(
bind_problems,
"infra/otel/tempo-gateway.cfg",
"bind :3200 ssl crt /run/secrets/tempo.pem ca-file "
"/run/secrets/ca.crt crl-file /run/secrets/crl.pem verify required",
"bind :3200 ssl crt /run/secrets/tempo.pem ca-file "
"/run/secrets/ca.crt crl-file /run/secrets/crl.pem verify optional",
),
(
storage_problems,
"infra/otel/loki/loki.yaml",
"http_listen_address: 127.0.0.1",
"http_listen_address: 0.0.0.0",
),
(
prometheus_problems,
"infra/otel/prometheus/prometheus.yml",
" - job_name: loki\n scheme: https",
" - job_name: loki\n scheme: http",
),
(
collector_problems,
"infra/otel/collector.yaml",
"endpoint: https://loki:3100/otlp",
"endpoint: http://loki:3100/otlp",
),
(
grafana_problems,
"infra/otel/grafana/datasources.yaml",
"url: https://tempo:3200",
"url: http://tempo:3200",
),
],
ids=lambda v: getattr(v, "__name__", None),
)
def test_control_names_file_and_line( # noqa: PLR0913
tmp_path: Path,
check, # noqa: ANN001
rel: str,
old: str,
new: str,
) -> None:
root = _copy(tmp_path)
assert check(root) == []
number = _replace(root, rel, old, new)
problems = check(root)
assert problems, (rel, old)
# файл и номер строки (у YAML — строка ключа или раздела)
assert any(p.startswith(f"{rel}:") for p in problems), problems
if check in (allowlist_problems, bind_problems, collector_problems):
assert any(f"{rel}:{number}:" in p for p in problems), problems