Files
mtusi2026lab7/student-tests/unit/test_telemetry_backends_tls.py
T

656 lines
29 KiB
Python

"""Лаба 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