fix: address telemetry-backends-tls verify findings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 11:34:03 +03:00
co-authored by Claude Opus 5.5
parent c34279c6b6
commit eaa5bca796
22 changed files with 762 additions and 79 deletions
@@ -109,6 +109,17 @@ 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._-]+\}$")
@@ -209,6 +220,46 @@ def allowlist_problems(root: Path) -> list[str]:
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 — точно, служебных путей нет,
@@ -219,12 +270,15 @@ def rights_problems(root: Path) -> list[str]: # noqa: C901, PLR0912
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)
@@ -264,11 +318,19 @@ def rights_problems(root: Path) -> list[str]: # noqa: C901, PLR0912
f"{rel}:{number}: identity {identity} paths "
f"{sorted(paths) or 'not exact'}",
)
if (
rel.endswith("prometheus-gateway.cfg")
and "!closed_path" not in line
):
problems.append(f"{rel}:{number}: allow without !closed_path")
# явный список путей (правки 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)}, "
@@ -577,6 +639,123 @@ def test_new_identities_rows() -> None:
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
# --- контроль: копия с ошибкой — красная проверка с файлом и строкой ----------
@@ -622,6 +801,25 @@ def _replace(root: Path, rel: str, old: str, new: str) -> int:
"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",
+40
View File
@@ -743,6 +743,46 @@ def test_gateway_bind_requires_client_tls13_and_crl() -> None:
assert "server collector 127.0.0.1:14318" in config
def _section(config: str, kind: str, name: str = "") -> list[str]:
"""Строки раздела `<kind> [<name>]` без комментариев."""
out: list[str] = []
inside = False
head = [kind, name] if name else [kind]
for line in config.splitlines():
if line and not line[0].isspace():
inside = line.split()[: len(head)] == head
continue
stripped = line.strip()
if inside and stripped and not stripped.startswith("#"):
out.append(stripped)
return out
def test_gateway_collector_down_closes_without_response() -> None:
"""Спек `observability`, «Потери SDK при недоступном Collector» (правки
verify change `telemetry-backends-tls`, W2): остановленный Collector —
закрытие соединения шлюзом без ответа HTTP, а не 503. SDK 1.45 считает
ответ 503 завершённым экспортом без потери (`_ExportResult` без
исключения), ошибку соединения — потерей. Бэкенды метрик Collector
отвечают 503 по-прежнему: Prometheus сам считает его отказом scrape."""
config = GATEWAY_CFG.read_text(encoding="utf-8")
assert "errorfile 503 /dev/null" in _section(
config,
"backend",
"collector",
)
for name in ("collector_own", "collector_app"):
assert not any(
line.startswith("errorfile")
for line in _section(config, "backend", name)
), name
# только backend приёма: в defaults и frontend правило задело бы и порты
# метрик
for kind, name in (("defaults", ""), ("frontend", "otlp")):
lines = _section(config, kind, name)
assert not any(line.startswith("errorfile") for line in lines), kind
# --- модули без телеметрии ----------------------------------------------------