Files
mtusi2026lab7/student-tests/legacy/queue_contract_check.py
T
zemiles 9cc80d2529
Application / app (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
ЛР 7 — БПИ2303 — Лазарев — на 3
Перенесена реализация lab6; бизнес-API без изменений, транспорт — HTTPS.

- Внешний HTTPS (public-ca) на 127.0.0.1:8443; HSTS, TLS >= 1.2.
- Обязательное mTLS LB -> каждая API-реплика: API проверяет цепочку
  internal-ca и SAN клиента (allowlist: lb); health только на 127.0.0.1.
- TLS с проверкой сервера ко всем зависимостям: PostgreSQL verify-full
  (pg_hba только hostssl), HTTPS S3, AMQPS, OTLP/HTTPS с client cert,
  mTLS Collector -> Prometheus/Loki/Tempo, Grafana -> datasources, scrape.
- OpenBao 2.7.2 не в dev-mode: Raft на volume, init/unseal оператором,
  auth/cert с ролью и policy на сервис, TTL 15 мин + renew/re-login.
- Отдельные роли PostgreSQL с грантами по таблицам; разные ключи S3 и
  пользователи брокера выдаются из OpenBao.
- Argon2id (m=19 MiB, t=2, p=1, замер на стенде) и rehash при входе.
- Случайный X-Instance-Id; hardening контейнеров (non-root, cap_drop ALL,
  no-new-privileges, read-only, лимиты); TCP_NODELAY на сокете API.
- Модель угроз, trust matrix, отрицательные тесты TLS/mTLS, API, OpenBao,
  hardening; evidence, в т.ч. прогон из чистого clone.
2026-11-18 23:59:35 +03:00

99 lines
4.5 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.
#!/usr/bin/env python3
"""Аудит F12 и F11: разбор сообщения брокера = contracts/jobs.schema.json; версия pipeline.
python3 -m venv .venv && .venv/bin/pip install -r requirements-dev.txt rfc3339-validator
.venv/bin/python student-tests/queue_contract_check.py --output evidence/queue-contract-check.json
F12: набор сообщений (валидные и контрпримеры из аудита) проверяется src/jobs.parse_message
и jsonschema Draft 2020-12 с FormatChecker (date-time, uuid). Вердикты должны совпасть.
F11: API с PIPELINE_VERSION=2 не стартует (понятная ошибка), а не работает «молча» неверно.
"""
import argparse
import copy
import json
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "src"))
import jobs # noqa: E402
from jsonschema import Draft202012Validator, FormatChecker # noqa: E402
BASE = {"schema_version": 1, "job_id": "11111111-1111-4111-8111-111111111111", "type": "attachment.process.v1",
"attachment_id": "22222222-2222-4222-8222-222222222222", "pipeline_version": 1, "attempt": 1,
"created_at": "2026-09-01T12:00:00Z"}
def variant(**kw):
m = copy.deepcopy(BASE)
for k, v in kw.items():
if v is None:
m.pop(k, None)
else:
m[k] = v
return m
CASES = {
"valid minimal": variant(),
"valid with trace context": variant(traceparent="00-" + "a" * 32 + "-" + "b" * 16 + "-01", tracestate="k=v"),
"valid created_at with offset and fraction": variant(created_at="2026-09-01T15:00:00.123+03:00"),
"schema_version true (audit)": variant(schema_version=True),
"created_at date only (audit)": variant(created_at="2026-01-01"),
"traceparent number (audit)": variant(traceparent=123),
"tracestate 513 chars (audit)": variant(tracestate="x" * 513),
"attempt true": variant(attempt=True),
"attempt 0": variant(attempt=0),
"pipeline_version 1.0": variant(pipeline_version=1.0),
"job_id not uuid": variant(job_id="not-a-uuid"),
"job_id uuid without hyphens": variant(job_id="11111111111141118111111111111111"),
"extra field": variant(url="http://evil/"),
"missing created_at": variant(created_at=None),
"wrong type": variant(type="attachment.delete.v1"),
"traceparent bad version": variant(traceparent="01-" + "a" * 32 + "-" + "b" * 16 + "-01"),
"created_at no timezone": variant(created_at="2026-09-01T12:00:00"),
}
def main():
p = argparse.ArgumentParser()
p.add_argument("--output")
args = p.parse_args()
schema = json.loads((ROOT / "contracts/jobs.schema.json").read_text())
try:
import rfc3339_validator # noqa: F401 (без него FormatChecker не проверяет date-time)
formats = True
except ImportError:
formats = False
validator = Draft202012Validator(schema, format_checker=FormatChecker())
results, mismatches = [], 0
for name, msg in CASES.items():
schema_ok = validator.is_valid(msg)
try:
jobs.parse_message(json.dumps(msg).encode())
parser_ok = True
except jobs.InvalidMessage:
parser_ok = False
same = schema_ok == parser_ok
mismatches += not same
results.append({"case": name, "jsonschema_valid": schema_ok, "parser_valid": parser_ok, "match": same})
print("%s %-45s schema=%-5s parser=%s" % ("PASS" if same else "FAIL", name, schema_ok, parser_ok))
# F11
proc = subprocess.run(["docker", "compose", "run", "--rm", "--no-deps", "-T", "-e", "PIPELINE_VERSION=2", "api"],
cwd=ROOT, capture_output=True, text=True, timeout=180)
f11 = {"exit_code": proc.returncode,
"message": [l for l in (proc.stdout + proc.stderr).splitlines() if "PIPELINE_VERSION" in l][-1:]}
f11_ok = proc.returncode != 0 and bool(f11["message"])
print("%s F11 api with PIPELINE_VERSION=2 refuses to start: %s" % ("PASS" if f11_ok else "FAIL", f11))
if args.output:
Path(args.output).write_text(json.dumps({"date_time_format_checked": formats, "cases": results,
"F11": f11}, ensure_ascii=False, indent=1) + "\n")
ok = mismatches == 0 and f11_ok and formats
print("PASS" if ok else "FAIL", "(%d cases, %d mismatches, date-time format checked: %s)" % (len(CASES), mismatches, formats))
return 0 if ok else 1
if __name__ == "__main__":
sys.exit(main())