forked from mtusi2026/mtusi2026lab7
solution
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Команды управления учебным стендом."""
|
||||
@@ -0,0 +1,140 @@
|
||||
"""Проверки TLS внутри сети Compose на закреплённых версиях клиентов."""
|
||||
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import ssl
|
||||
import time
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
import aio_pika
|
||||
import asyncpg
|
||||
from aiormq.exceptions import ChannelAccessRefused
|
||||
from opentelemetry.proto.collector.logs.v1.logs_service_pb2 import ExportLogsServiceRequest
|
||||
|
||||
from app.core.jobs import JobSettings
|
||||
from app.storage.broker import connect_broker
|
||||
|
||||
CERTS = Path("/certificates")
|
||||
|
||||
|
||||
def context(identity=None):
|
||||
tls = ssl.create_default_context(cafile=str(CERTS / "ca.crt"))
|
||||
if identity:
|
||||
tls.load_cert_chain(CERTS / f"{identity}.crt", CERTS / f"{identity}.key")
|
||||
return tls
|
||||
|
||||
|
||||
def http(host, port, path, identity=None, *, body=None):
|
||||
request = Request(f"https://{host}:{port}{path}", data=body, headers={
|
||||
"Content-Type": "application/x-protobuf",
|
||||
})
|
||||
try:
|
||||
with urlopen(request, context=context(identity), timeout=4) as response:
|
||||
return response.status
|
||||
except HTTPError as error:
|
||||
return error.code
|
||||
except (ssl.SSLError, ConnectionError):
|
||||
return 0
|
||||
except URLError as error:
|
||||
if isinstance(error.reason, (ssl.SSLError, ConnectionError)):
|
||||
return 0
|
||||
raise
|
||||
|
||||
|
||||
def check_http():
|
||||
for role in ("otel-api", "otel-worker", "otel-publisher"):
|
||||
assert http("otel-collector", 4318, "/v1/traces", role, body=b"") == 200
|
||||
assert http("otel-collector", 4318, "/v1/traces", "otel-wrong-role", body=b"") == 403
|
||||
for role in (None, "foreign-client"):
|
||||
assert http("otel-collector", 4318, "/v1/traces", role, body=b"") in (0, 400)
|
||||
for port in (8888, 8889):
|
||||
assert http("otel-collector", port, "/metrics", "otel-scraper") == 200
|
||||
assert http("otel-collector", port, "/metrics", "otel-api") in (0, 400)
|
||||
status = http("loki", 3100, "/loki/api/v1/labels", "otel-reader")
|
||||
assert status == 200, ("loki", status)
|
||||
status = http("tempo", 3200, "/api/search?limit=1", "otel-reader")
|
||||
assert status == 200, ("tempo", status)
|
||||
assert http("prometheus", 9090, "/-/ready", "otel-reader") == 200
|
||||
assert http("tempo", 4318, "/v1/traces", "otel-writer", body=b"") == 200
|
||||
assert http("tempo", 4318, "/v1/traces", "otel-reader", body=b"") == 0
|
||||
logs = ExportLogsServiceRequest()
|
||||
resource = logs.resource_logs.add()
|
||||
resource.resource.attributes.add(key="service.name").value.string_value = "tls-audit"
|
||||
event = resource.scope_logs.add().log_records.add(time_unix_nano=time.time_ns())
|
||||
event.body.string_value = "synthetic TLS audit"
|
||||
status = http("loki", 3100, "/otlp/v1/logs", "otel-writer", body=logs.SerializeToString())
|
||||
assert status in (200, 204), ("loki ingest", status)
|
||||
assert http("loki", 3100, "/ready", "otel-api") == 0
|
||||
assert http("grafana", 3000, "/api/datasources") == 401
|
||||
assert http("minio", 9000, "/minio/health/ready") == 200
|
||||
assert http("openbao", 8200, "/v1/sys/health") == 200
|
||||
|
||||
for port in (14318, 8887, 13133):
|
||||
try:
|
||||
with socket.create_connection(("otel-collector", port), 2):
|
||||
pass
|
||||
except ConnectionRefusedError:
|
||||
continue
|
||||
raise AssertionError(f"Loopback-порт Collector {port} доступен извне")
|
||||
|
||||
|
||||
async def check_broker():
|
||||
async def connect(identity):
|
||||
return await connect_broker(JobSettings(
|
||||
broker_port=5671, broker_ca_file=str(CERTS / "ca.crt"),
|
||||
broker_cert_file=str(CERTS / f"{identity}.crt"),
|
||||
broker_key_file=str(CERTS / f"{identity}.key"),
|
||||
))
|
||||
|
||||
for role in ("api-broker", "attachment-worker", "attachment-publisher"):
|
||||
async with await connect(role) as connection:
|
||||
assert not connection.is_closed
|
||||
for role in ("broker-wrong-role", "foreign-client"):
|
||||
try:
|
||||
async with await connect(role):
|
||||
pass
|
||||
except (aio_pika.exceptions.AMQPException, OSError):
|
||||
continue
|
||||
raise AssertionError(f"RabbitMQ принял запрещённую identity: {role}")
|
||||
|
||||
try:
|
||||
async with await aio_pika.connect(host="broker", port=5671, ssl=True,
|
||||
ssl_context=context(), auth="external", timeout=4):
|
||||
pass
|
||||
except (aio_pika.exceptions.AMQPException, OSError):
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("RabbitMQ принял соединение без сертификата")
|
||||
|
||||
async with await connect("api-broker") as connection:
|
||||
channel = await connection.channel()
|
||||
try:
|
||||
await channel.declare_queue("scope-audit-probe", auto_delete=True)
|
||||
except ChannelAccessRefused:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("Роль API смогла объявить очередь")
|
||||
|
||||
|
||||
async def check_database():
|
||||
try:
|
||||
await asyncpg.connect(host="postgres", user="worker", database="postgres",
|
||||
ssl=False, timeout=3)
|
||||
except asyncpg.InvalidAuthorizationSpecificationError as error:
|
||||
assert "rejects connection" in str(error)
|
||||
else:
|
||||
raise AssertionError("PostgreSQL принял plaintext")
|
||||
|
||||
with socket.create_connection(("redis", 6379), 3) as raw:
|
||||
with context().wrap_socket(raw, server_hostname="redis") as tls:
|
||||
tls.sendall(b"*1\r\n$4\r\nPING\r\n")
|
||||
assert tls.recv(128).startswith(b"-NOAUTH")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
check_http()
|
||||
asyncio.run(check_broker())
|
||||
asyncio.run(check_database())
|
||||
print("PASS: TLS-зависимости, mTLS identity и ACL RabbitMQ/Collector")
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Операторская настройка OpenBao по TLS с локальным хранением unseal-материала."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import time
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import HTTPSHandler, Request, build_opener
|
||||
|
||||
from app.core.bao import NoRedirect
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
TLS = ROOT / "secrets/tls"
|
||||
ROLES = ("api", "worker", "publisher", "cleanup")
|
||||
|
||||
|
||||
class Bao:
|
||||
def __init__(self, port: int, certificate: Path | None = None, key: Path | None = None):
|
||||
self.address = f"https://localhost:{port}/v1/"
|
||||
context = ssl.create_default_context(cafile=str(TLS / "ca.crt"))
|
||||
if certificate:
|
||||
context.load_cert_chain(certificate, key)
|
||||
self.opener = build_opener(NoRedirect(), HTTPSHandler(context=context))
|
||||
|
||||
def call(self, path, payload=None, *, token=None, method=None):
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
request = Request(self.address + path, headers=headers, method=method,
|
||||
data=None if payload is None else json.dumps(payload).encode())
|
||||
with self.opener.open(request, timeout=5) as response:
|
||||
body = response.read()
|
||||
return json.loads(body) if body else None
|
||||
|
||||
|
||||
def operator_token(port: int) -> str:
|
||||
config = ROOT / f"secrets/bao-operator/operator-{port}.json"
|
||||
return json.loads(config.read_text())["root_token"]
|
||||
|
||||
|
||||
def bootstrap(port: int, *, unseal_only: bool = False) -> None:
|
||||
call = Bao(port).call
|
||||
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
try:
|
||||
status = call("sys/seal-status")
|
||||
break
|
||||
except OSError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError("OpenBao недоступен") from None
|
||||
time.sleep(0.5)
|
||||
|
||||
directory = ROOT / "secrets/bao-operator"
|
||||
directory.mkdir(mode=0o700, exist_ok=True)
|
||||
# После удаления тома прежние ключи сохраняются отдельным operator-файлом.
|
||||
material = directory / f"operator-{port}.json"
|
||||
if not status["initialized"]:
|
||||
if unseal_only:
|
||||
raise RuntimeError("OpenBao ещё не инициализирован")
|
||||
if material.exists():
|
||||
material.rename(directory / f"operator-{port}-{time.time_ns()}.json")
|
||||
descriptor = os.open(material, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
try:
|
||||
result = call("sys/init", {"secret_shares": 1, "secret_threshold": 1})
|
||||
with os.fdopen(descriptor, "w") as target:
|
||||
descriptor = -1
|
||||
json.dump(result, target)
|
||||
finally:
|
||||
if descriptor != -1:
|
||||
os.close(descriptor)
|
||||
credentials = json.loads(material.read_text())
|
||||
if status["sealed"] or not status["initialized"]:
|
||||
call("sys/unseal", {"key": credentials["keys_base64"][0]})
|
||||
if unseal_only:
|
||||
print("OpenBao распечатан")
|
||||
return
|
||||
token = credentials["root_token"]
|
||||
if "cert/" not in call("sys/auth", token=token):
|
||||
call("sys/auth/cert", {"type": "cert"}, token=token)
|
||||
if "messenger/" not in call("sys/mounts", token=token):
|
||||
call("sys/mounts/messenger", {"type": "kv", "options": {"version": "2"}}, token=token)
|
||||
for role in ROLES:
|
||||
path = f"messenger/data/{role}"
|
||||
policy = (ROOT / "infra/openbao/read-secret.hcl").read_text().replace("SERVICE_ROLE", role)
|
||||
call(f"sys/policies/acl/{role}", {"policy": policy}, token=token)
|
||||
call(f"auth/cert/certs/{role}", {
|
||||
"certificate": (TLS / f"{role}-bao.crt").read_text(),
|
||||
"token_policies": [role], "token_no_default_policy": True,
|
||||
"token_ttl": "10m", "token_max_ttl": "10m",
|
||||
}, token=token)
|
||||
value = (ROOT / "secrets" / f"{role}_db_password").read_text().strip()
|
||||
call(path, {"data": {"db_password": value}}, token=token)
|
||||
print("OpenBao готов: роли и KV настроены")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--port", type=int, default=18200)
|
||||
parser.add_argument("--unseal-only", action="store_true")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
bootstrap(args.port, unseal_only=args.unseal_only)
|
||||
except HTTPError as error:
|
||||
raise SystemExit(f"Ошибка OpenBao HTTP {error.code}") from None
|
||||
+59
-35
@@ -1,5 +1,6 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline structural checks; full schema validation is a separate target."""
|
||||
|
||||
import ast
|
||||
import json
|
||||
from pathlib import Path
|
||||
@@ -7,48 +8,71 @@ import re
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def main():
|
||||
lab = json.loads((ROOT/'lab.json').read_text())['number']
|
||||
spec = json.loads((ROOT/'contracts/openapi.json').read_text())
|
||||
assert spec['openapi']=='3.1.0'
|
||||
assert spec['info']['version']=='1.%d.0'%lab
|
||||
lab = json.loads((ROOT / "lab.json").read_text(encoding="utf-8"))["number"]
|
||||
spec = json.loads((ROOT / "contracts/openapi.json").read_text(encoding="utf-8"))
|
||||
assert spec["openapi"] == "3.1.0"
|
||||
assert spec["info"]["version"] == "1.%d.0" % lab
|
||||
operation_ids = set()
|
||||
|
||||
def walk(value):
|
||||
if isinstance(value,dict):
|
||||
if '$ref' in value:
|
||||
pointer = value['$ref']
|
||||
assert pointer.startswith('#/'), 'unexpected external reference'
|
||||
if isinstance(value, dict):
|
||||
if "$ref" in value:
|
||||
pointer = value["$ref"]
|
||||
assert pointer.startswith("#/"), "unexpected external reference"
|
||||
target = spec
|
||||
for part in pointer[2:].split('/'):
|
||||
target = target[part.replace('~1','/').replace('~0','~')]
|
||||
for part in pointer[2:].split("/"):
|
||||
target = target[part.replace("~1", "/").replace("~0", "~")]
|
||||
for v in value.values():
|
||||
walk(v)
|
||||
elif isinstance(value,list):
|
||||
elif isinstance(value, list):
|
||||
for v in value:
|
||||
walk(v)
|
||||
walk(spec)
|
||||
for route,methods in spec['paths'].items():
|
||||
placeholders = set(re.findall(r'\{([^}]+)\}',route))
|
||||
for method,op in methods.items():
|
||||
assert op['operationId'] not in operation_ids, 'duplicate operationId'
|
||||
operation_ids.add(op['operationId'])
|
||||
params = {p['name'] for p in op.get('parameters',[]) if p['in']=='path' and p.get('required')}
|
||||
assert placeholders==params, 'path parameter mismatch: '+route
|
||||
for response in op['responses'].values():
|
||||
assert 'X-Request-Id' in response['headers']
|
||||
if lab>=3:
|
||||
assert 'X-Instance-Id' in response['headers']
|
||||
assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2)
|
||||
assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4)
|
||||
for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')):
|
||||
ast.parse(file.read_text(),filename=str(file))
|
||||
for file in ROOT.rglob('*.json'):
|
||||
if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts):
|
||||
continue
|
||||
json.loads(file.read_text())
|
||||
for required in ('README.md','COURSE.md','CONTRIBUTING.md','REPORT.md','contracts/README.md','tests/smoke.py','tests/README.md'):
|
||||
assert (ROOT/required).is_file(), 'missing '+required
|
||||
print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.')
|
||||
|
||||
if __name__=='__main__':
|
||||
walk(spec)
|
||||
for route, methods in spec["paths"].items():
|
||||
placeholders = set(re.findall(r"\{([^}]+)\}", route))
|
||||
for method, op in methods.items():
|
||||
assert op["operationId"] not in operation_ids, "duplicate operationId"
|
||||
operation_ids.add(op["operationId"])
|
||||
params = {
|
||||
p["name"]
|
||||
for p in op.get("parameters", [])
|
||||
if p["in"] == "path" and p.get("required")
|
||||
}
|
||||
assert placeholders == params, "path parameter mismatch: " + route
|
||||
for response in op["responses"].values():
|
||||
assert "X-Request-Id" in response["headers"]
|
||||
if lab >= 3:
|
||||
assert "X-Instance-Id" in response["headers"]
|
||||
assert ("/api/v1/auth/sessions" in spec["paths"]) == (lab >= 2)
|
||||
assert ("/api/v1/attachments/{attachment_id}" in spec["paths"]) == (lab >= 4)
|
||||
for file in list((ROOT / "tests").glob("*.py")) + list(
|
||||
(ROOT / "scripts").glob("*.py")
|
||||
):
|
||||
ast.parse(file.read_text(encoding="utf-8"), filename=str(file))
|
||||
for file in ROOT.rglob("*.json"):
|
||||
if any(
|
||||
part in {".git", ".venv", "node_modules", "vendor", "output"}
|
||||
for part in file.parts
|
||||
):
|
||||
continue
|
||||
json.loads(file.read_text(encoding="utf-8"))
|
||||
for required in (
|
||||
"README.md",
|
||||
"COURSE.md",
|
||||
"CONTRIBUTING.md",
|
||||
"REPORT.md",
|
||||
"contracts/README.md",
|
||||
"tests/smoke.py",
|
||||
"tests/README.md",
|
||||
):
|
||||
assert (ROOT / required).is_file(), "missing " + required
|
||||
print(
|
||||
"PASS: offline skeleton structure, local refs and Python syntax; application NOT tested."
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,434 @@
|
||||
"""Fault/recovery очереди на явно выбранном Compose-стенде; только синтетические данные."""
|
||||
|
||||
import argparse
|
||||
from datetime import datetime
|
||||
import hashlib
|
||||
from io import BytesIO
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from scripts.check_outbox_recovery import COMPOSE, ROOT, compose, require_compose
|
||||
from scripts.deployment import ComposeProject
|
||||
from tests.client import Client, check
|
||||
|
||||
PROBE = """
|
||||
import asyncio, hashlib, json
|
||||
from uuid import UUID
|
||||
from sqlalchemy import select
|
||||
from app.core.bao import database_secret
|
||||
from app.core.config import Settings
|
||||
from app.core.database import create_db_engine, create_session_factory
|
||||
from app.models.job import AttachmentJob
|
||||
from app.models.attachment import Attachment
|
||||
from app.storage.s3 import create_s3_storage
|
||||
async def main():
|
||||
settings=Settings(**database_secret()); engine=create_db_engine(settings); storage=create_s3_storage(settings.s3)
|
||||
try:
|
||||
async with create_session_factory(engine)() as session:
|
||||
job, att=(await session.execute(select(AttachmentJob,Attachment).join(Attachment,Attachment.id==AttachmentJob.attachment_id).where(Attachment.id==UUID(ATTACHMENT_ID)))).one()
|
||||
result=dict(job_id=str(job.id),status=att.status,attempt=job.attempt,published_attempt=job.published_attempt,limit=job.attempt_limit,updated_at=att.updated_at,next_attempt_at=job.next_attempt_at,last_error_code=job.last_error_code,permanent=job.last_error_permanent)
|
||||
objects=[]
|
||||
for prefix in ('originals/'+UUID(ATTACHMENT_ID).hex+'/', 'variants/'+UUID(ATTACHMENT_ID).hex+'/'):
|
||||
entries=await asyncio.to_thread(lambda: list(storage._client.list_objects(storage.settings.bucket,prefix=prefix,recursive=True)))
|
||||
for obj in entries:
|
||||
stream=await storage.open_object(obj.object_name); checksum=hashlib.sha256()
|
||||
try:
|
||||
async for chunk in stream: checksum.update(chunk)
|
||||
finally: await stream.aclose()
|
||||
objects.append(dict(name=obj.object_name.split('/')[-1],size=obj.size,sha256=checksum.hexdigest(),last_modified=obj.last_modified))
|
||||
result['objects']=sorted(objects,key=lambda x:x['name']);print(json.dumps(result,default=str))
|
||||
finally: await storage.aclose();await engine.dispose()
|
||||
asyncio.run(main())
|
||||
"""
|
||||
|
||||
|
||||
def probe(attachment_id):
|
||||
code = "ATTACHMENT_ID = " + repr(str(UUID(attachment_id))) + "\n" + PROBE
|
||||
result = subprocess.run(
|
||||
COMPOSE + ["exec", "-T", "api", "python", "-"],
|
||||
input=code,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
cwd=ROOT,
|
||||
timeout=30,
|
||||
)
|
||||
check(result.returncode == 0, "Probe failed; diagnostic output hidden")
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def admin(*arguments, expected=0):
|
||||
result = compose(
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"worker",
|
||||
"python",
|
||||
"-m",
|
||||
"app.core.job_admin",
|
||||
*arguments
|
||||
)
|
||||
check(result.returncode == expected, "Unexpected operator command exit status")
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def verify_result(client, actor, attachment, original):
|
||||
ready = client.wait_ready(actor, attachment, wait_seconds=180)
|
||||
check(ready["id"] == attachment["id"], "Attachment identity changed")
|
||||
path = "/api/v1/attachments/" + ready["id"] + "/content"
|
||||
check(
|
||||
client.call("GET", path, actor=actor)["bytes"] == original, "Original changed"
|
||||
)
|
||||
check(
|
||||
{v["name"] for v in ready["variants"]} == {"thumbnail", "crop", "optimized"},
|
||||
"Incomplete pipeline",
|
||||
)
|
||||
for variant in ready["variants"]:
|
||||
data = client.call("GET", path + "?variant=" + variant["name"], actor=actor)[
|
||||
"bytes"
|
||||
]
|
||||
check(
|
||||
hashlib.sha256(data).hexdigest() == variant["sha256"], "Checksum mismatch"
|
||||
)
|
||||
with Image.open(BytesIO(data)) as image:
|
||||
check(
|
||||
image.size == (variant["width"], variant["height"]),
|
||||
"Metadata dimensions mismatch",
|
||||
)
|
||||
check(
|
||||
image.format == ("WEBP" if variant["name"] == "optimized" else "JPEG"),
|
||||
"Wrong format",
|
||||
)
|
||||
check(
|
||||
not image.getexif()
|
||||
and not image.info.get("icc_profile")
|
||||
and not image.info.get("xmp"),
|
||||
"Metadata leaked",
|
||||
)
|
||||
if variant["name"] == "crop":
|
||||
check(image.size == (128, 128), "Wrong crop size")
|
||||
snapshot = probe(ready["id"])
|
||||
check(
|
||||
len(snapshot["objects"]) == 4,
|
||||
"Expected exactly one original and three variants",
|
||||
)
|
||||
return snapshot
|
||||
|
||||
|
||||
def crash(client, actor, chat, mode):
|
||||
name = "messenger-worker-fault-" + uuid4().hex
|
||||
try:
|
||||
require_compose("stop", "worker")
|
||||
attachment, original = client.attachment(actor, chat)
|
||||
result = compose(
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"--name",
|
||||
name,
|
||||
"worker",
|
||||
"python",
|
||||
"-m",
|
||||
"app.core.job_worker",
|
||||
"--" + mode,
|
||||
attachment["id"],
|
||||
)
|
||||
phase = (
|
||||
"after_object:optimized" if mode == "crash-after-object" else "before_ack"
|
||||
)
|
||||
marker = json.dumps({"fault": phase, "attachment_id": attachment["id"]})
|
||||
check(
|
||||
result.returncode == 137 and marker in result.stdout,
|
||||
"Targeted crash not observed",
|
||||
)
|
||||
before = probe(attachment["id"])
|
||||
check(
|
||||
before["status"]
|
||||
== ("processing" if mode == "crash-after-object" else "ready"),
|
||||
"Unexpected crash state",
|
||||
)
|
||||
check(len(before["objects"]) == 4, "Crash must occur after all four PUTs")
|
||||
finally:
|
||||
subprocess.run(["docker", "rm", "-f", name], capture_output=True, timeout=30)
|
||||
require_compose("start", "worker")
|
||||
after = verify_result(client, actor, attachment, original)
|
||||
if mode == "crash-before-ack":
|
||||
# Wait for RabbitMQ to deliver and acknowledge the ready duplicate.
|
||||
wait_queue_empty()
|
||||
after = probe(attachment["id"])
|
||||
check(after == before, "Ready duplicate rewrote result")
|
||||
else:
|
||||
check(
|
||||
after["attempt"] == before["attempt"] + 1,
|
||||
"Lease did not recover the interrupted attempt",
|
||||
)
|
||||
check(
|
||||
[(x["name"], x["sha256"]) for x in before["objects"]]
|
||||
== [(x["name"], x["sha256"]) for x in after["objects"]],
|
||||
"Replay changed object content",
|
||||
)
|
||||
return dict(
|
||||
scenario=mode,
|
||||
attachment_id=attachment["id"],
|
||||
exit_code=137,
|
||||
before=before,
|
||||
after=after,
|
||||
)
|
||||
|
||||
|
||||
def retry_replay(client, actor, chat, permanent, on_failed=None, on_queued=None):
|
||||
name = "messenger-retry-fault-" + uuid4().hex
|
||||
samples = []
|
||||
configuration = ComposeProject().config["services"]["worker"]["environment"]
|
||||
retry_base = float(configuration["JOB_RETRY_SECONDS"])
|
||||
retry_max = float(configuration["JOB_RETRY_MAX_SECONDS"])
|
||||
try:
|
||||
require_compose("stop", "worker")
|
||||
attachment, original = client.attachment(actor, chat)
|
||||
if on_queued is not None:
|
||||
on_queued(attachment)
|
||||
mode = "fail-permanent" if permanent else "fail-transient"
|
||||
require_compose(
|
||||
"run",
|
||||
"-d",
|
||||
"--no-deps",
|
||||
"--name",
|
||||
name,
|
||||
"worker",
|
||||
"python",
|
||||
"-m",
|
||||
"app.core.job_worker",
|
||||
"--" + mode,
|
||||
attachment["id"],
|
||||
)
|
||||
deadline = time.monotonic() + 180
|
||||
while time.monotonic() < deadline:
|
||||
sample = probe(attachment["id"])
|
||||
if (
|
||||
sample["attempt"]
|
||||
and sample["status"] in {"queued", "failed"}
|
||||
and (not samples or samples[-1]["attempt"] != sample["attempt"])
|
||||
):
|
||||
samples.append(sample)
|
||||
if sample["status"] == "failed":
|
||||
break
|
||||
time.sleep(0.5)
|
||||
check(sample["status"] == "failed", "Retry never reached failed")
|
||||
check(
|
||||
sample["attempt"] == (1 if permanent else sample["limit"]),
|
||||
"Incorrect attempt budget",
|
||||
)
|
||||
check(sample["permanent"] == permanent, "Incorrect error classification")
|
||||
if not permanent:
|
||||
check(len(samples) == sample["limit"], "Missed retry samples")
|
||||
for entry in samples:
|
||||
delay = (
|
||||
datetime.fromisoformat(entry["next_attempt_at"])
|
||||
- datetime.fromisoformat(entry["updated_at"])
|
||||
).total_seconds()
|
||||
ceiling = min(retry_max, retry_base * 2 ** (entry["attempt"] - 1))
|
||||
check(
|
||||
ceiling / 2 <= delay <= ceiling,
|
||||
"Retry delay outside configured jitter bounds",
|
||||
)
|
||||
client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + attachment["id"] + "/content",
|
||||
actor=actor,
|
||||
expected=409,
|
||||
)
|
||||
if on_failed is not None:
|
||||
on_failed(sample, name)
|
||||
job_id = sample["job_id"]
|
||||
request_id = str(uuid4())
|
||||
listing = admin("list-failed")
|
||||
check(
|
||||
any(row["job_id"] == job_id for row in listing),
|
||||
"Job missing from failed registry",
|
||||
)
|
||||
subprocess.run(
|
||||
["docker", "rm", "-f", name], capture_output=True, timeout=30, check=True
|
||||
)
|
||||
first = admin(
|
||||
"replay",
|
||||
job_id,
|
||||
"--request-id",
|
||||
request_id,
|
||||
"--actor",
|
||||
"verification",
|
||||
"--reason",
|
||||
"dependency_restored",
|
||||
)
|
||||
check(first["status"] == "queued", "Replay did not queue job")
|
||||
finally:
|
||||
subprocess.run(["docker", "rm", "-f", name], capture_output=True, timeout=30)
|
||||
require_compose("start", "worker")
|
||||
after = verify_result(client, actor, attachment, original)
|
||||
repeat = admin(
|
||||
"replay",
|
||||
job_id,
|
||||
"--request-id",
|
||||
request_id,
|
||||
"--actor",
|
||||
"verification",
|
||||
"--reason",
|
||||
"dependency_restored",
|
||||
)
|
||||
check(repeat["already_applied"], "Replay request id not idempotent")
|
||||
refused = admin(
|
||||
"replay",
|
||||
job_id,
|
||||
"--request-id",
|
||||
str(uuid4()),
|
||||
"--actor",
|
||||
"verification",
|
||||
"--reason",
|
||||
"manual_review",
|
||||
expected=2,
|
||||
)
|
||||
check(refused["error_code"] == "job_not_failed", "Successful job was replayed")
|
||||
check(probe(attachment["id"]) == after, "Operator replay altered ready job")
|
||||
check(len(admin("history", job_id)) == 1, "Incorrect audit count")
|
||||
return dict(
|
||||
scenario=mode,
|
||||
attachment_id=attachment["id"],
|
||||
samples=samples,
|
||||
after=after,
|
||||
replay_idempotent=True,
|
||||
)
|
||||
|
||||
|
||||
def queue_state():
|
||||
output = require_compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"broker",
|
||||
"rabbitmqctl",
|
||||
"list_queues",
|
||||
"--formatter=json",
|
||||
"name",
|
||||
"messages_ready",
|
||||
"messages_unacknowledged",
|
||||
"consumers",
|
||||
"durable",
|
||||
)
|
||||
return next(row for row in json.loads(output) if row["name"] == "attachment-jobs")
|
||||
|
||||
|
||||
def wait_queue_empty():
|
||||
deadline = time.monotonic() + 20
|
||||
while time.monotonic() < deadline:
|
||||
state = queue_state()
|
||||
if state["messages_ready"] == 0 and state["messages_unacknowledged"] == 0:
|
||||
return state
|
||||
time.sleep(0.5)
|
||||
check(False, "RabbitMQ did not acknowledge all completed deliveries")
|
||||
|
||||
|
||||
def persistence(client, actor, chat):
|
||||
try:
|
||||
require_compose("stop", "worker")
|
||||
attachment, original = client.attachment(actor, chat)
|
||||
client.message(actor, chat, "", attachments=[attachment["id"]])
|
||||
client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + attachment["id"] + "/content",
|
||||
actor=actor,
|
||||
expected=409,
|
||||
)
|
||||
time.sleep(2)
|
||||
queued_before = queue_state()
|
||||
check(
|
||||
queued_before["messages_ready"] >= 1 and queued_before["durable"],
|
||||
"No durable queued message before restart",
|
||||
)
|
||||
result = subprocess.run(
|
||||
[str(ROOT / "scripts/restart.sh")],
|
||||
cwd=ROOT,
|
||||
capture_output=True,
|
||||
timeout=180,
|
||||
)
|
||||
check(result.returncode == 0, "Restart hook failed")
|
||||
check(
|
||||
"worker"
|
||||
not in require_compose(
|
||||
"ps", "--status", "running", "--services"
|
||||
).splitlines(),
|
||||
"Restart started deliberately stopped worker",
|
||||
)
|
||||
queued_after = queue_state()
|
||||
check(
|
||||
queued_after["messages_ready"] >= 1 and queued_after["durable"],
|
||||
"Broker lost queued delivery across restart",
|
||||
)
|
||||
client.message(actor, chat, "session and chat survived broker/API restart")
|
||||
finally:
|
||||
require_compose("start", "worker")
|
||||
after = verify_result(client, actor, attachment, original)
|
||||
return dict(
|
||||
scenario="worker_stopped_restart_all",
|
||||
attachment_id=attachment["id"],
|
||||
queue_before=queued_before,
|
||||
queue_after=queued_after,
|
||||
after=after,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", required=True)
|
||||
parser.add_argument("--ca-file")
|
||||
parser.add_argument(
|
||||
"--scenario",
|
||||
choices=[
|
||||
"all",
|
||||
"persistence",
|
||||
"crash-after-object",
|
||||
"crash-before-ack",
|
||||
"fail-transient",
|
||||
"fail-permanent",
|
||||
],
|
||||
default="all",
|
||||
)
|
||||
parser.add_argument("--output", default="evidence/jobs.json")
|
||||
args = parser.parse_args()
|
||||
client = Client(args.base_url, args.ca_file, timeout=40)
|
||||
aliases = {r.instance_id for r in ComposeProject().replicas() if r.running}
|
||||
check(
|
||||
client.call("GET", "/health/live", schema="Health")["headers"].get(
|
||||
"X-Instance-Id"
|
||||
)
|
||||
in aliases,
|
||||
"Wrong Compose project for BASE_URL",
|
||||
)
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
results = []
|
||||
operations = {
|
||||
"persistence": persistence,
|
||||
"crash-after-object": lambda *x: crash(*x, "crash-after-object"),
|
||||
"crash-before-ack": lambda *x: crash(*x, "crash-before-ack"),
|
||||
"fail-transient": lambda *x: retry_replay(*x, False),
|
||||
"fail-permanent": lambda *x: retry_replay(*x, True),
|
||||
}
|
||||
selected = (
|
||||
operations.values() if args.scenario == "all" else [operations[args.scenario]]
|
||||
)
|
||||
for operation in selected:
|
||||
result = operation(client, actor, chat)
|
||||
results.append(result)
|
||||
Path(args.output).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(args.output).write_text(
|
||||
json.dumps(dict(status="in_progress", results=results), indent=2) + "\n"
|
||||
)
|
||||
print("PASS: " + result["scenario"], flush=True)
|
||||
Path(args.output).write_text(
|
||||
json.dumps(dict(status="passed", results=results), indent=2) + "\n"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Испытания TTL, распечатывания и отзыва cert identity OpenBao."""
|
||||
|
||||
import argparse
|
||||
import time
|
||||
from urllib.error import HTTPError
|
||||
|
||||
from scripts.bootstrap_bao import TLS, Bao, bootstrap, operator_token
|
||||
from scripts.deployment import ComposeProject
|
||||
from scripts.rotate_worker import cert_role, rotate
|
||||
from tests.client import Client
|
||||
|
||||
|
||||
def deny(call, codes=(400, 403)):
|
||||
try:
|
||||
call()
|
||||
except HTTPError as error:
|
||||
assert error.code in codes, error.code
|
||||
return
|
||||
raise AssertionError("OpenBao разрешил запрещённую операцию")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", required=True)
|
||||
parser.add_argument("--bao-port", required=True, type=int)
|
||||
args = parser.parse_args()
|
||||
project = ComposeProject()
|
||||
port = args.bao_port
|
||||
client = Client(args.base_url, str(TLS / "ca.crt"))
|
||||
cert, key = TLS / "worker-bao.crt", TLS / "worker-bao.key"
|
||||
operator, old_identity = Bao(port), Bao(port, cert, key)
|
||||
root = operator_token(port)
|
||||
probe = "auth/cert/certs/worker-expiry-probe"
|
||||
secret = "messenger/data/worker"
|
||||
|
||||
def login(bao, role="worker"):
|
||||
return bao.call("auth/cert/login", {"name": role})["auth"]
|
||||
|
||||
operator.call(probe, cert_role(cert, "worker", "3s"), token=root)
|
||||
try:
|
||||
temporary = login(old_identity, "worker-expiry-probe")
|
||||
assert 0 < temporary["lease_duration"] <= 3
|
||||
old_identity.call(secret, token=temporary["client_token"])
|
||||
time.sleep(temporary["lease_duration"] + 1)
|
||||
deny(lambda: old_identity.call(secret, token=temporary["client_token"]))
|
||||
finally:
|
||||
operator.call(probe, token=root, method="DELETE")
|
||||
print("PASS: короткоживущий токен теряет доступ после TTL")
|
||||
|
||||
operator.call("sys/seal", {}, token=root)
|
||||
try:
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
deny(lambda: login(old_identity), (503,))
|
||||
try:
|
||||
project.run("exec", "-T", "worker", "python", "-c",
|
||||
"from app.core.bao import database_secret; database_secret()")
|
||||
except RuntimeError as error:
|
||||
assert "Не удалось получить секрет DB" in str(error)
|
||||
else:
|
||||
raise AssertionError("Новый процесс получил секрет из sealed OpenBao")
|
||||
finally:
|
||||
bootstrap(port, unseal_only=True)
|
||||
print("PASS: при seal текущий API готов, новая выдача запрещена")
|
||||
|
||||
old_token = login(old_identity)
|
||||
original = old_identity.call(secret, token=old_token["client_token"])["data"]["data"]["db_password"]
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
image = project.run("images", "-q", "worker")
|
||||
rotate(project, port)
|
||||
operator.call("auth/token/revoke-accessor", {"accessor": old_token["accessor"]}, token=root)
|
||||
deny(lambda: login(old_identity))
|
||||
deny(lambda: old_identity.call(secret, token=old_token["client_token"]))
|
||||
new_identity = Bao(port, cert, key)
|
||||
new_token = login(new_identity)["client_token"]
|
||||
assert new_identity.call(secret, token=new_token)["data"]["data"]["db_password"] != original
|
||||
assert project.run("images", "-q", "worker") == image
|
||||
attachment, _ = client.attachment(actor, chat)
|
||||
client.wait_ready(actor, attachment, wait_seconds=60)
|
||||
print("PASS: старый leaf и токен отозваны, worker обработал вложение с новым паролем")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Проверяет политику mTLS каждой реплики из внутренней сети Compose."""
|
||||
|
||||
import http.client
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
|
||||
CERTIFICATES = Path("/certificates")
|
||||
|
||||
|
||||
class ApiConnection(http.client.HTTPSConnection):
|
||||
def __init__(self, address: str, context: ssl.SSLContext):
|
||||
super().__init__("api", 8080, timeout=4, context=context)
|
||||
self.address = address
|
||||
|
||||
def connect(self):
|
||||
raw = socket.create_connection((self.address, self.port), self.timeout)
|
||||
self.sock = self._context.wrap_socket(raw, server_hostname=self.host)
|
||||
|
||||
|
||||
def request(address: str, identity: str | None) -> int:
|
||||
context = ssl.create_default_context(cafile=str(CERTIFICATES / "ca.crt"))
|
||||
if identity:
|
||||
context.load_cert_chain(CERTIFICATES / f"{identity}.crt",
|
||||
CERTIFICATES / f"{identity}.key")
|
||||
connection = ApiConnection(address, context)
|
||||
try:
|
||||
connection.request("GET", "/health/live")
|
||||
return connection.getresponse().status
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
assert len(sys.argv[1:]) >= 2, "Нужны минимум две API-реплики"
|
||||
for address in sys.argv[1:]:
|
||||
assert request(address, "load-balancer") == 200
|
||||
for identity in (None, "foreign-client", "wrong-role"):
|
||||
try:
|
||||
request(address, identity)
|
||||
except (ssl.SSLError, ConnectionError, http.client.RemoteDisconnected):
|
||||
continue
|
||||
raise AssertionError(f"Реплика приняла запрещённую identity: {identity}")
|
||||
print("PASS: mTLS allow/deny на всех API-репликах")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,277 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверки реального nginx в отдельном Compose-проекте без БД и приложения."""
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import gzip
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import ssl
|
||||
import tempfile
|
||||
import time
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request, urlopen
|
||||
from uuid import uuid4
|
||||
|
||||
from scripts.init_tls import initialize
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
IMAGE = "nginx:1.28.0-alpine"
|
||||
PAYLOAD = json.dumps({"text": "message " * 256}).encode()
|
||||
|
||||
|
||||
def check(condition: bool, message: str) -> None:
|
||||
if not condition:
|
||||
raise AssertionError(message)
|
||||
|
||||
|
||||
class Stand:
|
||||
def __init__(self, directory: str) -> None:
|
||||
self.directory = Path(directory)
|
||||
self.project = "messenger-nginx-check-" + uuid4().hex[:12]
|
||||
self.base_url = ""
|
||||
initialize(self.directory)
|
||||
tls = self.directory / "secrets/tls"
|
||||
self.tls = ssl.create_default_context(cafile=str(tls / "ca.crt"))
|
||||
|
||||
def certificates(*names):
|
||||
return [f"{tls / name}:/run/tls/{name}:ro" for name in names]
|
||||
backend = self.directory / "backend.conf"
|
||||
backend.write_text(
|
||||
"worker_processes 1;\n"
|
||||
"events { worker_connections 1024; }\n"
|
||||
"http {\n"
|
||||
" log_format backend 'BACKEND $request_method $uri';\n"
|
||||
" access_log /dev/stdout backend;\n"
|
||||
" server {\n"
|
||||
" listen 8080 ssl;\n"
|
||||
" ssl_certificate /run/tls/api.crt;\n"
|
||||
" ssl_certificate_key /run/tls/api.key;\n"
|
||||
" ssl_client_certificate /run/tls/ca.crt;\n"
|
||||
" ssl_verify_client on;\n"
|
||||
" default_type application/json;\n"
|
||||
" add_header X-Instance-Id $hostname always;\n"
|
||||
" add_header X-Request-Id $request_id always;\n"
|
||||
" add_header Retry-After 7 always;\n"
|
||||
' location /health/ { return 200 \'{"status":"ok"}\'; }\n'
|
||||
" location = /api/limited {\n"
|
||||
' return 429 \'{"error":{"code":"rate_limited",'
|
||||
'"message":"upstream limit","request_id":"$request_id"}}\';\n'
|
||||
" }\n"
|
||||
" location = /api/post-failure {\n"
|
||||
' return 503 \'{"error":{"code":"unavailable",'
|
||||
'"message":"upstream failure","request_id":"$request_id"}}\';\n'
|
||||
" }\n"
|
||||
" location / { return 200 '" + PAYLOAD.decode() + "'; }\n"
|
||||
" }\n"
|
||||
"}\n"
|
||||
)
|
||||
self.compose_file = self.directory / "compose.json"
|
||||
self.compose_file.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"services": {
|
||||
"api": {
|
||||
"image": IMAGE,
|
||||
"volumes": [f"{backend}:/etc/nginx/nginx.conf:ro",
|
||||
*certificates("api.crt", "api.key", "ca.crt")],
|
||||
},
|
||||
"nginx": {
|
||||
"image": IMAGE,
|
||||
"volumes": [
|
||||
f"{ROOT / 'infra/nginx/nginx.conf'}:/etc/nginx/nginx.conf:ro",
|
||||
*certificates("ingress.crt", "ingress.key", "ca.crt",
|
||||
"load-balancer.crt", "load-balancer.key"),
|
||||
],
|
||||
"ports": ["127.0.0.1::8443"],
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
def compose(self, *args: str) -> str:
|
||||
# Явный файл, уникальный проект и пустой env-file исключают основной стенд.
|
||||
result = subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"--env-file",
|
||||
"/dev/null",
|
||||
"-f",
|
||||
str(self.compose_file),
|
||||
"-p",
|
||||
self.project,
|
||||
*args,
|
||||
],
|
||||
cwd=self.directory,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=45,
|
||||
)
|
||||
if result.returncode:
|
||||
raise RuntimeError(result.stdout + result.stderr)
|
||||
return result.stdout + result.stderr
|
||||
|
||||
def call(self, path: str, *, method: str = "GET", encoding: str = "identity"):
|
||||
request = Request(
|
||||
self.base_url + path,
|
||||
method=method,
|
||||
headers={"Accept-Encoding": encoding},
|
||||
data=b"{}" if method == "POST" else None,
|
||||
)
|
||||
try:
|
||||
response = urlopen(request, timeout=5, context=self.tls)
|
||||
except HTTPError as error:
|
||||
response = error
|
||||
except (URLError, TimeoutError):
|
||||
return 0, {}, b""
|
||||
with response:
|
||||
return (
|
||||
response.status,
|
||||
{key.lower(): value for key, value in response.headers.items()},
|
||||
response.read(),
|
||||
)
|
||||
|
||||
def wait_instances(self, count: int) -> set[str]:
|
||||
seen: set[str] = set()
|
||||
deadline = time.monotonic() + 15
|
||||
while time.monotonic() < deadline:
|
||||
status, headers, _ = self.call("/health/live")
|
||||
if status == 200:
|
||||
seen.add(headers["x-instance-id"])
|
||||
if len(seen) == count:
|
||||
return seen
|
||||
time.sleep(0.05)
|
||||
raise AssertionError(f"Ожидалось {count} реплик, наблюдалось {len(seen)}")
|
||||
|
||||
|
||||
def check_error(response, status: int, code: str) -> None:
|
||||
actual_status, headers, body = response
|
||||
check(actual_status == status, f"Ожидался HTTP {status}, получен {actual_status}")
|
||||
check(
|
||||
headers.get("content-type", "").startswith("application/json"), "Ошибка не JSON"
|
||||
)
|
||||
error = json.loads(body)["error"]
|
||||
check(error["code"] == code, "Неверный код ошибки")
|
||||
check(error["request_id"] == headers.get("x-request-id"), "request_id не совпадает")
|
||||
|
||||
|
||||
def run_checks(stand: Stand) -> None:
|
||||
stand.compose("up", "-d", "--pull", "never", "--scale", "api=2", "api", "nginx")
|
||||
port = stand.compose("port", "nginx", "8443").strip().rsplit(":", 1)[1]
|
||||
stand.base_url = "https://localhost:" + port
|
||||
stand.wait_instances(2)
|
||||
print(stand.compose("exec", "-T", "nginx", "nginx", "-v").strip())
|
||||
stand.compose("exec", "-T", "nginx", "nginx", "-t")
|
||||
print("PASS: nginx -t и балансировка двух реплик")
|
||||
|
||||
status, headers, body = stand.call("/api/large", encoding="gzip")
|
||||
check(
|
||||
status == 200 and headers.get("content-encoding") == "gzip", "Нет gzip для JSON"
|
||||
)
|
||||
check(gzip.decompress(body) == PAYLOAD, "gzip изменил содержимое")
|
||||
check(len(body) < len(PAYLOAD), "gzip не уменьшил тестовый ответ")
|
||||
check(
|
||||
"accept-encoding" in headers.get("vary", "").lower(),
|
||||
"Нет Vary: Accept-Encoding",
|
||||
)
|
||||
check(stand.call("/api/large")[2] == PAYLOAD, "Ответ без gzip изменён")
|
||||
small = stand.call("/health/live", encoding="gzip")
|
||||
check(
|
||||
small[0] == 200 and "content-encoding" not in small[1], "Маленький ответ сжат"
|
||||
)
|
||||
print(f"PASS: gzip {len(PAYLOAD)} → {len(body)} байт, содержимое сохранено")
|
||||
|
||||
limited = stand.call("/api/limited")
|
||||
check_error(limited, 429, "rate_limited")
|
||||
check(limited[1].get("retry-after") == "7", "Подменён Retry-After приложения")
|
||||
check("x-instance-id" in limited[1], "Потерян id backend на ошибке API")
|
||||
print("PASS: JSON и заголовки ошибки API передаются без подмены")
|
||||
|
||||
failure = stand.call("/api/post-failure", method="POST")
|
||||
check_error(failure, 503, "unavailable")
|
||||
backend_logs = stand.compose("logs", "--no-color", "--no-log-prefix", "api")
|
||||
check(backend_logs.count("BACKEND POST /api/post-failure") == 1, "POST повторился")
|
||||
print("PASS: отправленный POST не повторяется на другой реплике")
|
||||
|
||||
with ThreadPoolExecutor(max_workers=32) as pool:
|
||||
responses = list(pool.map(lambda _: stand.call("/api/large"), range(500)))
|
||||
rejected = [response for response in responses if response[0] == 429]
|
||||
check(bool(rejected), "Не удалось вызвать ограничение частоты")
|
||||
check(
|
||||
all(response[0] in (200, 429) for response in responses), "Ошибка при нагрузке"
|
||||
)
|
||||
for response in rejected:
|
||||
check_error(response, 429, "rate_limited")
|
||||
check(response[1].get("retry-after") == "1", "Нет Retry-After балансировщика")
|
||||
check("x-instance-id" not in response[1], "LB выдал себя за API-реплику")
|
||||
with ThreadPoolExecutor(max_workers=16) as pool:
|
||||
health = list(pool.map(lambda _: stand.call("/health/ready"), range(100)))
|
||||
check(all(response[0] == 200 for response in health), "Лимит затронул health")
|
||||
check(stand.call("/lb-health")[0] == 200, "Проверка LB недоступна")
|
||||
print(f"PASS: лимит вернул {len(rejected)} ответов 429; health доступен")
|
||||
|
||||
stand.compose(
|
||||
"up", "-d", "--pull", "never", "--scale", "api=3", "--no-recreate", "api"
|
||||
)
|
||||
instances = stand.wait_instances(3)
|
||||
print("PASS: третья реплика обнаружена через DNS без reload nginx")
|
||||
|
||||
target = sorted(instances)[0]
|
||||
containers = stand.compose("ps", "-q", "api").splitlines()
|
||||
matching = [container for container in containers if container.startswith(target)]
|
||||
check(len(matching) == 1, "Не найдена тестовая реплика для остановки")
|
||||
# Все id взяты только из уникального временного Compose-проекта.
|
||||
started = time.monotonic()
|
||||
subprocess.run(
|
||||
["docker", "stop", "--time", "1", matching[0]], check=True, capture_output=True
|
||||
)
|
||||
recovery = None
|
||||
for _ in range(20):
|
||||
status, headers, _ = stand.call("/health/live")
|
||||
if status == 200:
|
||||
check(headers["x-instance-id"] != target, "Остановленная реплика отвечает")
|
||||
if recovery is None:
|
||||
recovery = time.monotonic() - started
|
||||
check(recovery is not None and recovery < 10, "Чтение не восстановилось за 10 с")
|
||||
print(f"PASS: отказ реплики, первое успешное чтение через {recovery:.3f} с")
|
||||
|
||||
stand.compose("stop", "--timeout", "1", "api")
|
||||
unavailable = stand.call("/health/ready")
|
||||
check_error(unavailable, 503, "unavailable")
|
||||
check(
|
||||
unavailable[1].get("retry-after") == "1", "Нет Retry-After при отказе всех API"
|
||||
)
|
||||
check("x-instance-id" not in unavailable[1], "У ошибки LB есть id реплики")
|
||||
check(stand.call("/lb-health")[0] == 200, "Отказ API сломал проверку самого LB")
|
||||
print("PASS: недоступность всех backend возвращает JSON 503")
|
||||
|
||||
logs = stand.compose("logs", "--no-color", "--no-log-prefix", "nginx")
|
||||
entries = [json.loads(line) for line in logs.splitlines() if line.startswith("{")]
|
||||
check(bool(entries), "Нет JSON access log")
|
||||
check(
|
||||
all("request_id" in entry and "upstream_time" in entry for entry in entries),
|
||||
"Неполный лог",
|
||||
)
|
||||
check(
|
||||
any(entry["limit_status"] == "REJECTED" for entry in entries),
|
||||
"Лимит не отражён в логе",
|
||||
)
|
||||
print("PASS: JSON access log содержит время backend и результат лимита")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
with tempfile.TemporaryDirectory(prefix="messenger-nginx-check-") as directory:
|
||||
stand = Stand(directory)
|
||||
try:
|
||||
run_checks(stand)
|
||||
except Exception:
|
||||
print(stand.compose("logs", "--no-color", "--tail", "20"), flush=True)
|
||||
raise
|
||||
finally:
|
||||
stand.compose("down", "--volumes", "--remove-orphans", "--timeout", "1")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,398 @@
|
||||
"""Проверка наблюдаемости через реальные запросы Grafana к трём backend.
|
||||
|
||||
--incidents явно разрешает ограниченные отказы на выбранном Compose-проекте.
|
||||
В evidence сохраняются только агрегаты и выбранные технические поля.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import math
|
||||
import os
|
||||
import ssl
|
||||
import subprocess
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
from pathlib import Path
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from uuid import uuid4
|
||||
|
||||
from scripts.deployment import ComposeProject
|
||||
from tests.client import Client, Failure, check
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def eventually(operation, message, timeout=90):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
value = operation()
|
||||
if value:
|
||||
return value
|
||||
except (OSError, ValueError, KeyError, AssertionError):
|
||||
pass
|
||||
time.sleep(1)
|
||||
raise AssertionError(message)
|
||||
|
||||
|
||||
class Grafana:
|
||||
def __init__(self, base):
|
||||
self.base = base.rstrip('/')
|
||||
self.tls = ssl.create_default_context(cafile=os.getenv("CA_FILE"))
|
||||
secret = (ROOT / 'secrets/grafana_admin_password').read_text().strip()
|
||||
self.authorization = 'Basic ' + base64.b64encode(('admin:' + secret).encode()).decode()
|
||||
|
||||
def get(self, path, **params):
|
||||
url = self.base + path
|
||||
if params:
|
||||
url += '?' + urllib.parse.urlencode(params)
|
||||
request = urllib.request.Request(url, headers={'Authorization': self.authorization, 'Accept': 'application/json'})
|
||||
with urllib.request.urlopen(request, timeout=10, context=self.tls) as response:
|
||||
return json.load(response)
|
||||
|
||||
def proxy(self, source, path, **params):
|
||||
return self.get('/api/datasources/proxy/uid/' + source + path, **params)
|
||||
|
||||
def query(self, expression):
|
||||
value = self.proxy('prometheus', '/api/v1/query', query=expression)
|
||||
check(value['status'] == 'success', 'Prometheus query failed')
|
||||
return value['data']['result']
|
||||
|
||||
def logs(self, selector, start):
|
||||
value = self.proxy('loki', '/loki/api/v1/query_range', query=selector, start=start, end=time.time_ns(), limit=1000, direction='forward')
|
||||
check(value['status'] == 'success', 'Loki query failed')
|
||||
return [json.loads(line) for stream in value['data']['result'] for _, line, *_ in stream['values']]
|
||||
|
||||
def trace(self, trace_id):
|
||||
return self.proxy('tempo', '/api/traces/' + trace_id)
|
||||
|
||||
|
||||
def identifier_hex(value, byte_length):
|
||||
if len(value) == byte_length * 2 and all(c in '0123456789abcdefABCDEF' for c in value):
|
||||
return value.lower()
|
||||
return base64.b64decode(value, validate=True).hex()
|
||||
|
||||
|
||||
def spans_in(value):
|
||||
found = []
|
||||
if isinstance(value, dict):
|
||||
for key, item in value.items():
|
||||
if key == 'spans':
|
||||
found.extend(item)
|
||||
else:
|
||||
found.extend(spans_in(item))
|
||||
elif isinstance(value, list):
|
||||
for item in value:
|
||||
found.extend(spans_in(item))
|
||||
return found
|
||||
|
||||
|
||||
def correlation(grafana, service, start, *, trace_id=None, attachment_id=None, request_id=None):
|
||||
selector = '{service_name="' + service + '"} | json'
|
||||
if service == 'messenger-api':
|
||||
selector += ' | event="http.request"'
|
||||
if trace_id:
|
||||
selector += ' | trace_id="' + trace_id + '"'
|
||||
if attachment_id:
|
||||
selector += ' | attachment_id="' + attachment_id + '"'
|
||||
if request_id:
|
||||
selector += ' | request_id="' + request_id + '"'
|
||||
records = eventually(lambda: grafana.logs(selector, start), 'No correlated log for ' + service)
|
||||
record = records[0]
|
||||
trace_id = record['trace_id']
|
||||
def matching_trace():
|
||||
candidate = grafana.trace(trace_id)
|
||||
return candidate if any(identifier_hex(span.get('spanId', ''), 8) == record['span_id'] for span in spans_in(candidate)) else None
|
||||
trace = eventually(matching_trace, 'Matching span is missing in Tempo')
|
||||
spans = [span for span in spans_in(trace) if identifier_hex(span.get('spanId', ''), 8) == record['span_id']]
|
||||
# Tempo 2.9 JSON использует protobuf bytes (Base64); Loki хранит hex.
|
||||
check(any(identifier_hex(span.get('spanId', ''), 8) == record['span_id'] for span in spans), 'Log span_id not found in real trace')
|
||||
check(all(int(span['endTimeUnixNano']) > int(span['startTimeUnixNano']) for span in spans), 'Trace has no real duration')
|
||||
return {'trace_id': trace_id, 'span_id': record['span_id'], 'log': record,
|
||||
'spans': [{key: span.get(key) for key in ('name', 'kind', 'spanId', 'startTimeUnixNano', 'endTimeUnixNano', 'status')} for span in spans]}, trace
|
||||
|
||||
|
||||
def run_load(args):
|
||||
check(1 <= args.duration <= 300 and 1 <= args.rate <= 40 and 1 <= args.concurrency <= 16, 'Load profile outside bounds')
|
||||
client = Client(args.base_url)
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
project = ComposeProject()
|
||||
container_ids = project.run('ps', '--quiet').splitlines()
|
||||
samples = []
|
||||
stop = threading.Event()
|
||||
|
||||
def sample():
|
||||
while not stop.is_set():
|
||||
result = subprocess.run(['docker','stats','--no-stream','--format','{{json .}}',*container_ids],capture_output=True,text=True,timeout=15)
|
||||
if result.returncode == 0:
|
||||
samples.append({'elapsed_seconds':round(time.monotonic()-started,3), 'containers':[
|
||||
{k:row[k] for k in ('Name','CPUPerc','MemUsage','MemPerc')} for row in (json.loads(line) for line in result.stdout.splitlines())]})
|
||||
stop.wait(3)
|
||||
|
||||
def write(index):
|
||||
local = Client(args.base_url)
|
||||
before = time.monotonic()
|
||||
try:
|
||||
local.message(actor,chat,'synthetic-observability-' + str(index))
|
||||
return time.monotonic()-before
|
||||
except Failure:
|
||||
return None
|
||||
|
||||
started = time.monotonic()
|
||||
sampler = threading.Thread(target=sample)
|
||||
sampler.start()
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
||||
futures = []
|
||||
for index in range(args.duration * args.rate):
|
||||
time.sleep(max(0, started + index/args.rate - time.monotonic()))
|
||||
futures.append(pool.submit(write,index))
|
||||
results = [future.result() for future in futures]
|
||||
elapsed = time.monotonic()-started
|
||||
finally:
|
||||
stop.set()
|
||||
sampler.join()
|
||||
latencies = sorted(value for value in results if value is not None)
|
||||
failed = len(results)-len(latencies)
|
||||
def percentile(q):
|
||||
return round(latencies[max(0, math.ceil(q*len(latencies))-1)]*1000,3) if latencies else None
|
||||
report = {'date_utc':datetime.now(timezone.utc).isoformat(), 'workload':'synthetic POST messages; fixed arrival rate; no retries',
|
||||
'duration_seconds':args.duration,'elapsed_seconds':round(elapsed,3),'arrival_rate':args.rate,'concurrency_limit':args.concurrency,
|
||||
'successful_requests':len(latencies),'failed_requests':failed,'error_ratio':failed/len(results),
|
||||
'successful_rps':round(len(latencies)/elapsed,3), 'successful_latency_ms':{name:percentile(q) for name,q in [('p50',.5),('p95',.95),('p99',.99)]},
|
||||
'dataset':{'users':3,'chats':1,'messages':len(latencies)},'resource_samples':samples,
|
||||
'limits':'Latency covers successes from worker start; client scheduling is not included. Small controlled load, not a capacity benchmark.'}
|
||||
check(bool(latencies) and failed == 0, 'Controlled load contains errors')
|
||||
|
||||
return report
|
||||
|
||||
|
||||
def metric(grafana, expression):
|
||||
rows = grafana.query(expression)
|
||||
return float(rows[0]['value'][1]) if rows else None
|
||||
|
||||
|
||||
def alert_firing(grafana, name):
|
||||
return bool(grafana.query(f'ALERTS{{alertname="{name}",alertstate="firing"}}'))
|
||||
|
||||
|
||||
def trace_chain(grafana, trace_id, *, retry=False):
|
||||
def inspect():
|
||||
spans = spans_in(grafana.trace(trace_id))
|
||||
by_id = {identifier_hex(span['spanId'], 8): span for span in spans}
|
||||
workers = [span for span in spans if span['name'] == 'attachment.process.v1'
|
||||
and span.get('kind') in ('SPAN_KIND_CONSUMER', 5)]
|
||||
for worker in workers:
|
||||
publisher = by_id.get(identifier_hex(worker.get('parentSpanId', ''), 8), {})
|
||||
if publisher.get('kind') not in ('SPAN_KIND_PRODUCER', 4):
|
||||
return None
|
||||
upload = by_id.get(identifier_hex(publisher.get('parentSpanId', ''), 8), {})
|
||||
if upload.get('name') != 'POST /api/v1/chats/{chat_id}/attachments':
|
||||
return None
|
||||
names = {span['name'] for span in spans}
|
||||
if not workers or not {'s3.read_staging', 's3.write_result', 'postgres.commit_ready'} <= names:
|
||||
return None
|
||||
if retry:
|
||||
outcomes = set()
|
||||
for span in workers:
|
||||
attrs = {row['key']: row['value'] for row in span.get('attributes', [])}
|
||||
outcomes.add((int(attrs['job.attempt']['intValue']), attrs.get('outcome', {}).get('stringValue')))
|
||||
if not {(1, 'error'), (2, 'error')} <= outcomes or not any(n > 2 and outcome == 'success' for n, outcome in outcomes):
|
||||
return None
|
||||
return [{'name': span['name'], 'kind': span.get('kind'),
|
||||
'span_id': identifier_hex(span['spanId'], 8),
|
||||
'parent_span_id': identifier_hex(span.get('parentSpanId', ''), 8),
|
||||
'job': {entry['key']: entry['value'] for entry in span.get('attributes', [])
|
||||
if entry['key'] in {'job.attempt', 'outcome'}}} for span in spans]
|
||||
return eventually(inspect, 'Missing upload -> producer -> consumer -> S3/DB chain')
|
||||
|
||||
|
||||
def telemetry_outage(project, client, grafana, actor, chat):
|
||||
failed = 'sum({__name__=~"otelcol_exporter_send_failed_log_records(_total)?",exporter="otlphttp/loki"}) or vector(0)'
|
||||
refused = 'sum({__name__=~"otelcol_exporter_enqueue_failed_log_records(_total)?",exporter="otlphttp/loki"}) or vector(0)'
|
||||
baseline = [metric(grafana, expr) for expr in (failed, refused)]
|
||||
rss = 'sum({__name__=~"otelcol_process_memory_rss(_bytes)?"})'
|
||||
samples = []
|
||||
successful = 0
|
||||
try:
|
||||
project.run('stop', 'loki')
|
||||
start = time.monotonic()
|
||||
for second in range(51):
|
||||
for index in range(4):
|
||||
client.message(actor, chat, f'outage-{second}-{index}')
|
||||
successful += 1
|
||||
if second % 5 == 0:
|
||||
samples.append({
|
||||
'seconds': round(time.monotonic() - start, 2),
|
||||
'rss_bytes': metric(grafana, rss),
|
||||
'queued_batches': metric(grafana, 'sum(otelcol_exporter_queue_size{exporter="otlphttp/loki"})'),
|
||||
'capacity_batches': metric(grafana, 'sum(otelcol_exporter_queue_capacity{exporter="otlphttp/loki"})'),
|
||||
})
|
||||
time.sleep(max(0, start + second + 1 - time.monotonic()))
|
||||
losses = [metric(grafana, expr) - count for expr, count in zip((failed, refused), baseline)]
|
||||
check(sum(losses) > 0, 'No measured Collector log loss during prolonged outage')
|
||||
check(all(0 <= row['queued_batches'] <= row['capacity_batches'] == 256 for row in samples), 'Unexpected queue bound')
|
||||
check(max(row['rss_bytes'] for row in samples) < 256 * 1024**2, 'Collector crossed container memory limit')
|
||||
finally:
|
||||
project.run('start', 'loki')
|
||||
eventually(lambda: grafana.proxy('loki', '/loki/api/v1/labels').get('status') == 'success',
|
||||
'Loki did not recover')
|
||||
restored = client.message(actor, chat, 'telemetry-backend-restored')
|
||||
correlation(grafana, 'messenger-api', time.time_ns() - 30 * 10**9,
|
||||
trace_id=restored['headers']['X-Trace-Id'])
|
||||
return {'scenario':'loki_unavailable', 'successful_messages': successful,
|
||||
'dropped_after_export_failure': losses[0], 'dropped_at_enqueue': losses[1],
|
||||
'samples': samples, 'log_export_recovered': True}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--base-url', required=True)
|
||||
parser.add_argument('--grafana-url', default='https://localhost:13000')
|
||||
parser.add_argument('--incidents', action='store_true')
|
||||
parser.add_argument('--restart-telemetry', action='store_true')
|
||||
parser.add_argument('--output', default='evidence/observability.json')
|
||||
parser.add_argument('--duration', type=int, default=10)
|
||||
parser.add_argument('--rate', type=int, default=10)
|
||||
parser.add_argument('--concurrency', type=int, default=2)
|
||||
args = parser.parse_args()
|
||||
load = run_load(args)
|
||||
start = time.time_ns()
|
||||
project = ComposeProject()
|
||||
client = Client(args.base_url, timeout=40)
|
||||
aliases = {r.instance_id for r in project.replicas() if r.running}
|
||||
check(len(aliases) >= 2, 'Need two real API containers')
|
||||
check(client.call('GET', '/health/live')['headers'].get('X-Instance-Id') in aliases, 'Wrong Compose project for BASE_URL')
|
||||
grafana = Grafana(args.grafana_url)
|
||||
eventually(lambda: grafana.get('/api/health').get('database') == 'ok', 'Grafana is not ready')
|
||||
sources = grafana.get('/api/datasources')
|
||||
check({'prometheus', 'loki', 'tempo'} <= {source['uid'] for source in sources}, 'Missing provisioned datasource')
|
||||
dashboard = grafana.get('/api/dashboards/uid/messenger-overview')['dashboard']
|
||||
check(len(dashboard['panels']) >= 8, 'Dashboard is missing panels')
|
||||
actor, bob, eve, chat = client.bootstrap()
|
||||
sentinel = 'private-content-' + uuid4().hex
|
||||
response = client.message(actor, chat, sentinel)
|
||||
controlled_trace = response['headers'].get('X-Trace-Id')
|
||||
check(bool(controlled_trace), 'No API trace identifier')
|
||||
attachment, _ = client.attachment(actor, chat)
|
||||
client.wait_ready(actor, attachment)
|
||||
api, api_trace = correlation(grafana, 'messenger-api', start, trace_id=controlled_trace, request_id=response['headers']['X-Request-Id'])
|
||||
worker, worker_trace = correlation(grafana, 'messenger-worker', start, attachment_id=attachment['id'])
|
||||
accepted_chain = trace_chain(grafana, worker['trace_id'])
|
||||
check(api['log']['request_id'] == response['headers']['X-Request-Id'], 'Request id correlation lost')
|
||||
check(any(span['kind'] in ('SPAN_KIND_SERVER', 2) for span in api['spans']), 'No server span')
|
||||
check(any(span['kind'] in ('SPAN_KIND_CONSUMER', 5) for span in worker['spans']), 'No consumer span')
|
||||
processed = eventually(lambda: grafana.logs('{service_name="messenger-worker"} | json | event="job.processed" | trace_id="' + worker['trace_id'] + '"', start), 'No worker result log')
|
||||
check(processed[0]['outcome'] == 'success', 'Controlled worker did not succeed')
|
||||
metrics = {}
|
||||
expressions = {
|
||||
'http_requests': 'sum(messenger_http_requests_total)',
|
||||
'http_duration': 'sum(messenger_http_duration_seconds_count)',
|
||||
'job_success': 'sum(messenger_job_attempts_total{outcome="success"})',
|
||||
'job_duration': 'sum(messenger_job_duration_seconds_count)',
|
||||
}
|
||||
for name, expression in expressions.items():
|
||||
metrics[name] = eventually(lambda expression=expression: grafana.query(expression), 'Missing metric: ' + expression)
|
||||
check(float(metrics[name][0]['value'][1]) > 0, 'Empty metric: ' + name)
|
||||
# Все PromQL из dashboard должны давать численные данные после traffic.
|
||||
for panel in dashboard['panels']:
|
||||
if panel['datasource']['uid'] == 'prometheus':
|
||||
eventually(lambda panel=panel: all(grafana.query(target['expr']) for target in panel['targets']), 'Empty dashboard panel: ' + panel['title'])
|
||||
forbidden_labels = {'user_id','chat_id','message_id','attachment_id','request_id','filename','url','http_target','http_url'}
|
||||
series = grafana.query('{__name__=~"messenger_.*"}')
|
||||
check(not any(forbidden_labels & set(row['metric']) for row in series), 'High cardinality metric label')
|
||||
report = {'date_utc': datetime.now(timezone.utc).isoformat(), 'project': project.name,
|
||||
'load': load, 'api_replicas': len(aliases), 'dashboard_uid': dashboard['uid'],
|
||||
'api_correlation': api, 'worker_correlation': worker, 'metrics': metrics, 'upload_trace': {'trace_id':worker['trace_id'], 'chain':accepted_chain}, 'incidents': []}
|
||||
if args.incidents:
|
||||
def fail_request():
|
||||
return client.call('POST', '/api/v1/users', expected=503,
|
||||
body={'username':'fault_' + uuid4().hex[:12],
|
||||
'display_name':'Synthetic', 'password':'not-exported-' + uuid4().hex})
|
||||
|
||||
before = time.monotonic()
|
||||
try:
|
||||
project.run('stop', 'postgres')
|
||||
failed = fail_request()
|
||||
error_trace = failed['headers'].get('X-Trace-Id')
|
||||
error, db_trace = correlation(grafana, 'messenger-api', start, trace_id=error_trace,
|
||||
request_id=failed['headers']['X-Request-Id'])
|
||||
diagnostics = eventually(lambda: grafana.logs(
|
||||
'{service_name="messenger-api"} | json | event="dependency.unavailable" | trace_id="' + error_trace + '"', start),
|
||||
'No dependency diagnostic log')
|
||||
checkout = next(span for span in spans_in(db_trace) if span['name'] == 'postgres.checkout'
|
||||
and span.get('status', {}).get('code') in ('STATUS_CODE_ERROR', 2))
|
||||
|
||||
def db_alert():
|
||||
for _ in range(4):
|
||||
fail_request()
|
||||
return alert_firing(grafana, 'MessengerHighErrorRate')
|
||||
|
||||
eventually(db_alert, 'Error rate alert did not fire', timeout=75)
|
||||
report['incidents'].append({'scenario':'postgres_unavailable','http_status':503,'correlation':error,
|
||||
'diagnostic':diagnostics[0], 'db_span':checkout['name'],
|
||||
'alert':'MessengerHighErrorRate', 'firing_after_seconds':round(time.monotonic()-before,3)})
|
||||
finally:
|
||||
project.run('start', 'postgres')
|
||||
eventually(lambda: _ready(client), 'API did not recover after PostgreSQL')
|
||||
eventually(lambda: not alert_firing(grafana, 'MessengerHighErrorRate'), 'Error rate alert not resolved')
|
||||
report['incidents'][-1]['resolved_after_seconds'] = round(time.monotonic() - before, 3)
|
||||
|
||||
from scripts.check_jobs import retry_replay
|
||||
queue = {}
|
||||
|
||||
def observe_queue(_):
|
||||
observed = time.monotonic()
|
||||
eventually(lambda: alert_firing(grafana, 'MessengerQueueLag'), 'Queue lag alert did not fire')
|
||||
queue.update(depth=metric(grafana, 'max(messenger_queue_depth_ratio)'),
|
||||
oldest_seconds=metric(grafana, 'max(messenger_queue_oldest_seconds)'),
|
||||
firing_after_seconds=round(time.monotonic()-observed,3))
|
||||
|
||||
incident = retry_replay(client, actor, chat, permanent=False, on_queued=observe_queue)
|
||||
retried_worker, retry_trace = correlation(grafana, 'messenger-worker', start,
|
||||
attachment_id=incident['attachment_id'])
|
||||
chain = trace_chain(grafana, retried_worker['trace_id'], retry=True)
|
||||
eventually(lambda: not alert_firing(grafana, 'MessengerQueueLag')
|
||||
and metric(grafana, 'max(messenger_queue_depth_ratio)') == 0, 'Backlog did not drain')
|
||||
queue.update(resolved=True, final_depth=0)
|
||||
report['incidents'].append({'scenario':'worker_stopped_then_transient_retry',
|
||||
'alert':'MessengerQueueLag', 'queue':queue, 'recovered_status':incident['after']['status'],
|
||||
'trace_id':retried_worker['trace_id'], 'chain':chain})
|
||||
report['incidents'].append(telemetry_outage(project, client, grafana, actor, chat))
|
||||
else:
|
||||
retry_trace = {}
|
||||
# Не сохраняем API bodies или SDK exceptions; проверяем реальные выбранные сигналы.
|
||||
logs = grafana.logs('{service_name=~"messenger-api|messenger-worker"}', start)
|
||||
exported = json.dumps([logs, api_trace, worker_trace, retry_trace])
|
||||
private = [sentinel, *(person['token'] for person in (actor,bob,eve)), *(person['registration']['password'] for person in (actor,bob,eve))]
|
||||
private.extend(path.read_text().strip() for path in (ROOT / 'secrets').iterdir() if path.is_file())
|
||||
check(not any(secret and secret in exported for secret in private), 'Private value found in telemetry')
|
||||
check(all(record.get('trace_id') and record.get('span_id') and record.get('timestamp') and record.get('severity') for record in logs), 'Incomplete structured logs')
|
||||
report['privacy_checked_logs'] = len(logs)
|
||||
report['checks'] = {'three_backends':True, 'dashboard_queries':True,'server_consumer_traces':True,'log_trace_correlation':True,'low_cardinality':True,'privacy':True}
|
||||
if args.restart_telemetry:
|
||||
historical_time = time.time()
|
||||
expression = 'sum(messenger_http_requests_total)'
|
||||
before = grafana.proxy('prometheus', '/api/v1/query', query=expression, time=historical_time)['data']['result']
|
||||
project.run('restart', 'prometheus', 'loki', 'tempo', 'grafana')
|
||||
after = eventually(lambda: grafana.proxy('prometheus', '/api/v1/query', query=expression, time=historical_time)['data']['result'], 'Prometheus history lost')
|
||||
check(before == after, 'Historical metric changed after storage restart')
|
||||
correlation(grafana, 'messenger-api', start, trace_id=api['trace_id'])
|
||||
correlation(grafana, 'messenger-worker', start, trace_id=worker['trace_id'])
|
||||
report['checks']['history_survives_restart'] = True
|
||||
destination = ROOT / args.output
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
destination.write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n')
|
||||
print('PASS: telemetry, dashboard, privacy, correlations' + ('; alerts and outage recovery verified' if args.incidents else ''))
|
||||
|
||||
|
||||
def _ready(client):
|
||||
return client.call('GET', '/health/ready', expected=[200,503])['status'] == 200
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,147 @@
|
||||
"""Сценарий COMMIT → SIGKILL до publish → ready без повторного upload.
|
||||
|
||||
Требуется уже работающий отдельный стенд. Скрипт не выполняется при запуске API.
|
||||
Публичные tests не изменяет, secrets/tokens не печатает и evidence сам не сохраняет.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from uuid import uuid4
|
||||
|
||||
from scripts.deployment import ComposeProject
|
||||
from tests.client import Client, check
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
COMPOSE = ["docker", "compose", "--env-file", ".env"]
|
||||
|
||||
|
||||
def compose(*arguments: str, timeout: int = 90) -> subprocess.CompletedProcess:
|
||||
return subprocess.run(
|
||||
COMPOSE + list(arguments),
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=timeout,
|
||||
)
|
||||
|
||||
|
||||
def require_compose(*arguments: str) -> str:
|
||||
result = compose(*arguments)
|
||||
check(result.returncode == 0, "Compose command failed; output hidden")
|
||||
return result.stdout
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Отказ publisher после COMMIT перед RabbitMQ publish"
|
||||
)
|
||||
parser.add_argument("--base-url", required=True)
|
||||
parser.add_argument("--ca-file")
|
||||
args = parser.parse_args()
|
||||
running = set(
|
||||
require_compose("ps", "--status", "running", "--services").splitlines()
|
||||
)
|
||||
check(
|
||||
{"api", "postgres", "minio", "broker", "publisher", "worker"} <= running,
|
||||
"Start the application stack before this scenario",
|
||||
)
|
||||
client = Client(args.base_url, args.ca_file, timeout=40)
|
||||
project = ComposeProject()
|
||||
aliases = {replica.instance_id for replica in project.replicas() if replica.running}
|
||||
live = client.call("GET", "/health/live", schema="Health")
|
||||
check(
|
||||
live["headers"].get("X-Instance-Id") in aliases,
|
||||
"BASE_URL does not belong to the selected Compose project",
|
||||
)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
attachment = None
|
||||
fault_container = "messenger-outbox-fault-" + uuid4().hex
|
||||
try:
|
||||
require_compose("stop", "publisher")
|
||||
attachment, original = client.attachment(alice, chat)
|
||||
message = client.message(alice, chat, "", attachments=[attachment["id"]])[
|
||||
"json"
|
||||
]
|
||||
client.call(
|
||||
"GET",
|
||||
f"/api/v1/attachments/{attachment['id']}/content",
|
||||
expected=409,
|
||||
actor=alice,
|
||||
)
|
||||
killed = compose(
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"--name",
|
||||
fault_container,
|
||||
"publisher",
|
||||
"python",
|
||||
"-m",
|
||||
"app.core.outbox_publisher",
|
||||
"--crash-before-publish",
|
||||
attachment["id"],
|
||||
)
|
||||
marker = json.dumps(
|
||||
{"fault": "before_publish", "attachment_id": attachment["id"]}
|
||||
)
|
||||
check(
|
||||
killed.returncode == 137 and marker in killed.stdout,
|
||||
"Expected targeted SIGKILL before publish was not observed",
|
||||
)
|
||||
pending = client.call(
|
||||
"GET",
|
||||
f"/api/v1/attachments/{attachment['id']}",
|
||||
actor=alice,
|
||||
schema="Attachment",
|
||||
)["json"]
|
||||
check(pending["status"] == "queued", "Crash must leave accepted job queued")
|
||||
finally:
|
||||
# Если docker compose run оборвался по timeout, одноразовый контейнер тоже удаляется.
|
||||
try:
|
||||
subprocess.run(
|
||||
["docker", "rm", "-f", fault_container], capture_output=True, timeout=30
|
||||
)
|
||||
finally:
|
||||
require_compose("start", "publisher")
|
||||
ready = client.wait_ready(alice, attachment, wait_seconds=60)
|
||||
check(ready["id"] == attachment["id"], "Recovered a different attachment")
|
||||
check(
|
||||
{variant["name"] for variant in ready["variants"]}
|
||||
== {"thumbnail", "crop", "optimized"},
|
||||
"Missing required variants",
|
||||
)
|
||||
path = f"/api/v1/attachments/{attachment['id']}/content"
|
||||
check(
|
||||
client.call("GET", path, actor=alice)["bytes"] == original,
|
||||
"Original changed after recovery",
|
||||
)
|
||||
for variant in ready["variants"]:
|
||||
downloaded = client.call(
|
||||
"GET", path + "?variant=" + variant["name"], actor=alice
|
||||
)["bytes"]
|
||||
check(
|
||||
len(downloaded) == variant["size_bytes"]
|
||||
and hashlib.sha256(downloaded).hexdigest() == variant["sha256"],
|
||||
"Recovered variant checksum mismatch",
|
||||
)
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"scenario": "commit_before_publish",
|
||||
"attachment_id": ready["id"],
|
||||
"message_id": message["id"],
|
||||
"publisher_exit_code": killed.returncode,
|
||||
"status_after_crash": pending["status"],
|
||||
"status_after_restart": ready["status"],
|
||||
"variants": [variant["name"] for variant in ready["variants"]],
|
||||
"reuploaded": False,
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Реальный MinIO: повтор bootstrap, private bucket, ограниченные права и отказ."""
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from scripts.deployment import ComposeProject
|
||||
from tests.client import Client, arguments, check, run
|
||||
|
||||
PROBE = r"""
|
||||
import asyncio, json, ssl, sys
|
||||
from pathlib import Path
|
||||
from uuid import UUID
|
||||
from urllib.request import Request, urlopen
|
||||
from urllib.error import HTTPError, URLError
|
||||
from app.core.bao import database_secret
|
||||
from app.core.config import Settings
|
||||
from app.core.database import create_db_engine, create_session_factory
|
||||
from app.storage.s3 import create_s3_storage
|
||||
from app.models.attachment import Attachment
|
||||
from minio.error import S3Error
|
||||
async def main():
|
||||
settings = Settings(**database_secret())
|
||||
tls = ssl.create_default_context(cafile=settings.s3.ca_file)
|
||||
engine = create_db_engine(settings)
|
||||
storage = create_s3_storage(settings.s3)
|
||||
try:
|
||||
async with create_session_factory(engine)() as session:
|
||||
record = await session.get(Attachment, UUID(json.load(sys.stdin)['attachment_id']))
|
||||
key = record.object_key
|
||||
results = {}
|
||||
for method in ('GET', 'PUT'):
|
||||
request = Request(settings.s3.endpoint + '/' + settings.s3.bucket + '/' + key,
|
||||
method=method, data=b'x' if method == 'PUT' else None)
|
||||
try:
|
||||
with urlopen(request, timeout=3, context=tls) as response:
|
||||
results[method] = response.status
|
||||
except HTTPError as error:
|
||||
results[method] = error.code
|
||||
error.close()
|
||||
try:
|
||||
storage._client.get_bucket_policy(settings.s3.bucket)
|
||||
results['admin_denied'] = False
|
||||
except S3Error as error:
|
||||
results['admin_denied'] = error.code == 'AccessDenied'
|
||||
try:
|
||||
buckets = storage._client.list_buckets()
|
||||
results['other_buckets_denied'] = all(bucket.name == settings.s3.bucket for bucket in buckets)
|
||||
except S3Error as error:
|
||||
results['other_buckets_denied'] = error.code == 'AccessDenied'
|
||||
try:
|
||||
with urlopen(settings.s3.endpoint.replace(':9000', ':9001'), timeout=1, context=tls):
|
||||
results['console_unreachable'] = False
|
||||
except HTTPError as error:
|
||||
results['console_unreachable'] = False
|
||||
error.close()
|
||||
except URLError:
|
||||
results['console_unreachable'] = True
|
||||
results['temp_originals_absent'] = not any(Path('/tmp').glob('messenger-upload-*'))
|
||||
results['root_files_absent'] = not any(Path('/run/secrets', name).exists()
|
||||
for name in ('minio_root_user', 'minio_root_password'))
|
||||
print(json.dumps(results))
|
||||
finally:
|
||||
await storage.aclose()
|
||||
await engine.dispose()
|
||||
asyncio.run(main())
|
||||
"""
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument(
|
||||
"--with-outage",
|
||||
action="store_true",
|
||||
help="временно остановить MinIO выбранного проекта",
|
||||
)
|
||||
|
||||
args = arguments("MinIO private bucket and failure checks", configure)
|
||||
project = ComposeProject()
|
||||
client = Client(args.base_url, args.ca_file, timeout=40)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
aliases = {replica.instance_id for replica in project.replicas() if replica.running}
|
||||
live = client.call("GET", "/health/live", schema="Health")
|
||||
check(
|
||||
live["headers"].get("X-Instance-Id") in aliases,
|
||||
"BASE_URL does not belong to the selected Compose project",
|
||||
)
|
||||
attachment, original = client.attachment(alice, chat)
|
||||
attachment = client.wait_ready(alice, attachment)
|
||||
# Повторный bootstrap не должен очистить bucket или сменить используемые credentials.
|
||||
for _ in range(2):
|
||||
project.run("run", "--rm", "--no-deps", "minio-bootstrap", timeout=100)
|
||||
replicas = project.replicas()
|
||||
check(bool(replicas), "API not running")
|
||||
result = subprocess.run(
|
||||
["docker", "exec", "-i", replicas[0].id, "python", "-c", PROBE],
|
||||
input=json.dumps({"attachment_id": attachment["id"]}),
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=20,
|
||||
)
|
||||
check(result.returncode == 0, "private bucket probe failed (details hidden)")
|
||||
statuses = json.loads(result.stdout)
|
||||
check(statuses["GET"] == statuses["PUT"] == 403, "anonymous S3 access allowed")
|
||||
check(
|
||||
statuses["admin_denied"]
|
||||
and statuses["other_buckets_denied"]
|
||||
and statuses["root_files_absent"],
|
||||
"API has excessive access",
|
||||
)
|
||||
check(statuses["console_unreachable"], "console reachable from API network")
|
||||
check(statuses["temp_originals_absent"], "API retained temporary originals")
|
||||
check(
|
||||
not project.config["services"]["minio"].get("ports"),
|
||||
"MinIO publishes host ports",
|
||||
)
|
||||
env = project.config["services"]["minio"]["environment"]
|
||||
check(env["MINIO_BROWSER"] == "off", "browser enabled")
|
||||
check(
|
||||
"127.0.0.1:9001" in project.config["services"]["minio"]["command"],
|
||||
"console is not bound to loopback",
|
||||
)
|
||||
path = "/api/v1/attachments/" + attachment["id"] + "/content"
|
||||
check(
|
||||
client.call("GET", path, actor=alice)["bytes"] == original,
|
||||
"bootstrap changed original",
|
||||
)
|
||||
if args.with_outage:
|
||||
try:
|
||||
project.run("stop", "minio")
|
||||
client.call("GET", path, expected=503, actor=alice)
|
||||
finally:
|
||||
project.run("start", "minio")
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
try:
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
break
|
||||
except Exception:
|
||||
if time.monotonic() >= deadline:
|
||||
raise
|
||||
time.sleep(0.5)
|
||||
check(
|
||||
client.call("GET", path, actor=alice)["bytes"] == original,
|
||||
"original lost after MinIO restart",
|
||||
)
|
||||
print(
|
||||
"PASS: idempotent bootstrap, anonymous GET/PUT denied, restricted API credentials, private console"
|
||||
+ (", MinIO outage/recovery" if args.with_outage else "")
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,302 @@
|
||||
"""Сквозные проверки защиты для запущенного HTTPS-стенда."""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import time
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlsplit
|
||||
from urllib.request import Request, urlopen
|
||||
|
||||
from scripts.deployment import ComposeProject
|
||||
from tests.client import Client
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
TLS = ROOT / "secrets/tls"
|
||||
|
||||
|
||||
WORKER_SCOPE_PROBE = """
|
||||
import asyncio
|
||||
import io
|
||||
|
||||
from minio.error import S3Error
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import DBAPIError
|
||||
|
||||
from app.core.bao import database_secret
|
||||
from app.core.config import Settings
|
||||
from app.core.database import create_db_engine
|
||||
from app.storage.s3 import create_s3_storage
|
||||
|
||||
|
||||
async def probe():
|
||||
settings = Settings(**database_secret())
|
||||
engine = create_db_engine(settings)
|
||||
try:
|
||||
async with engine.connect() as connection:
|
||||
assert (await connection.execute(text("SELECT 1"))).scalar() == 1
|
||||
try:
|
||||
await connection.execute(text("SELECT 1 FROM users LIMIT 1"))
|
||||
except DBAPIError as error:
|
||||
assert error.orig.sqlstate == "42501"
|
||||
else:
|
||||
raise AssertionError("Worker имеет доступ к users")
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
storage = create_s3_storage(settings.s3)
|
||||
try:
|
||||
try:
|
||||
storage._client.put_object(settings.s3.bucket, "outside-security-probe",
|
||||
io.BytesIO(b"x"), 1)
|
||||
except S3Error as error:
|
||||
assert error.code == "AccessDenied"
|
||||
else:
|
||||
raise AssertionError("Worker может записать вне разрешённых префиксов")
|
||||
finally:
|
||||
await storage.aclose()
|
||||
|
||||
|
||||
asyncio.run(probe())
|
||||
"""
|
||||
|
||||
|
||||
ROOTFS_PROBE = """
|
||||
from os import ST_RDONLY, statvfs
|
||||
from tempfile import TemporaryFile
|
||||
|
||||
assert statvfs("/app").f_flag & ST_RDONLY
|
||||
with TemporaryFile(dir="/tmp") as temporary:
|
||||
temporary.write(b"tmpfs probe")
|
||||
"""
|
||||
|
||||
API_BROKER_PROBE = """
|
||||
import asyncio
|
||||
from app.core.jobs import JobSettings
|
||||
from app.storage.broker import connect_broker
|
||||
|
||||
|
||||
async def probe():
|
||||
async with await connect_broker(JobSettings()) as connection:
|
||||
assert not connection.is_closed
|
||||
|
||||
|
||||
asyncio.run(probe())
|
||||
"""
|
||||
|
||||
|
||||
def probe_deployment(project: ComposeProject) -> None:
|
||||
services = project.config["services"]
|
||||
for name in ("api", "worker"):
|
||||
service = services[name]
|
||||
assert not service.get("ports")
|
||||
assert "ALL" in service["cap_drop"] and service["read_only"]
|
||||
assert "no-new-privileges:true" in service["security_opt"]
|
||||
assert service["tmpfs"]
|
||||
assert service["deploy"]["resources"]["limits"]["memory"]
|
||||
uid = project.run("exec", "-T", name, "id", "-u")
|
||||
assert int(uid) > 0
|
||||
project.run("exec", "-T", name, "python", "-c", ROOTFS_PROBE)
|
||||
for service in services.values():
|
||||
assert not service.get("privileged") and service.get("network_mode") != "host"
|
||||
assert all(mount["target"] != "/var/run/docker.sock"
|
||||
for mount in service.get("volumes", ()))
|
||||
project.run("exec", "-T", "worker", "python", "-c", WORKER_SCOPE_PROBE)
|
||||
print("PASS: ограничения контейнеров, роли PostgreSQL и префиксы S3")
|
||||
|
||||
|
||||
def probe_mtls(project: ComposeProject) -> None:
|
||||
replicas = project.replicas()
|
||||
network = project.name + "_default"
|
||||
addresses = [
|
||||
project.docker("inspect", "--format",
|
||||
'{{(index .NetworkSettings.Networks "' + network + '").IPAddress}}',
|
||||
replica.id)
|
||||
for replica in replicas
|
||||
]
|
||||
command = [
|
||||
"run", "--rm", "--network", network,
|
||||
"-v", f"{ROOT / 'scripts/check_mtls.py'}:/check.py:ro",
|
||||
"-v", f"{TLS / 'ca.crt'}:/certificates/ca.crt:ro",
|
||||
]
|
||||
for identity in ("load-balancer", "foreign-client", "wrong-role"):
|
||||
for extension in ("key", "crt"):
|
||||
name = f"{identity}.{extension}"
|
||||
command.extend(("-v", f"{TLS / name}:/certificates/{name}:ro"))
|
||||
image = project.config["services"]["api"]["image"]
|
||||
output = project.docker(*command, image, "python", "/check.py", *addresses)
|
||||
print(output)
|
||||
|
||||
|
||||
def audit_dependencies(project: ComposeProject) -> None:
|
||||
command = ["run", "--rm", "--network", project.name + "_default",
|
||||
"--network", project.name + "_objects",
|
||||
"-v", f"{ROOT / 'scripts/audit_tls.py'}:/app/audit_tls.py:ro",
|
||||
"-v", f"{TLS / 'ca.crt'}:/certificates/ca.crt:ro"]
|
||||
for role in ("otel-api", "otel-worker", "otel-publisher", "otel-wrong-role",
|
||||
"otel-reader", "otel-writer", "otel-scraper", "api-broker",
|
||||
"attachment-worker", "attachment-publisher", "broker-wrong-role", "foreign-client"):
|
||||
for extension in ("crt", "key"):
|
||||
name = f"{role}.{extension}"
|
||||
command.extend(("-v", f"{TLS / name}:/certificates/{name}:ro"))
|
||||
project.run("exec", "-T", "api", "python", "-c", API_BROKER_PROBE)
|
||||
image = project.config["services"]["api"]["image"]
|
||||
print(project.docker(*command, image, "python", "-m", "audit_tls"))
|
||||
|
||||
|
||||
def probe_bao(port: int) -> None:
|
||||
def call(context, path, *, token=None, data=None):
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
request = Request(f"https://localhost:{port}/v1/{path}", headers=headers,
|
||||
data=None if data is None else json.dumps(data).encode())
|
||||
with urlopen(request, context=context, timeout=5) as response:
|
||||
return json.load(response)
|
||||
|
||||
for role, other in (("api", "worker"), ("worker", "api")):
|
||||
context = ssl.create_default_context(cafile=str(TLS / "ca.crt"))
|
||||
context.load_cert_chain(TLS / f"{role}-bao.crt", TLS / f"{role}-bao.key")
|
||||
try:
|
||||
call(context, "auth/cert/login", data={"name": other})
|
||||
except HTTPError as error:
|
||||
assert error.code in (400, 403)
|
||||
else:
|
||||
raise AssertionError("OpenBao принял чужую cert-роль")
|
||||
login = call(context, "auth/cert/login", data={"name": role})["auth"]
|
||||
assert login["token_policies"] == [role] and 0 < login["lease_duration"] <= 600
|
||||
token = login["client_token"]
|
||||
assert call(context, f"messenger/data/{role}", token=token)["data"]["data"]["db_password"]
|
||||
for path, body in ((f"messenger/data/{other}", None),
|
||||
(f"messenger/data/{role}", {"data": {"db_password": "denied"}}),
|
||||
("sys/policies/acl/denied-probe", {"policy": ""})):
|
||||
try:
|
||||
call(context, path, data=body, token=token)
|
||||
except HTTPError as error:
|
||||
assert error.code == 403
|
||||
else:
|
||||
raise AssertionError(f"OpenBao разрешил {path}")
|
||||
print("PASS: OpenBao cert roles, KV allow/deny, TTL")
|
||||
|
||||
|
||||
def probe_http(base: str, project: ComposeProject) -> None:
|
||||
cafile = str(TLS / "ca.crt")
|
||||
tls = ssl.create_default_context(cafile=cafile)
|
||||
port = urlsplit(base).port
|
||||
try:
|
||||
urlopen(f"https://127.0.0.1:{port}/health/live", context=tls, timeout=5)
|
||||
except URLError as error:
|
||||
assert isinstance(error.reason, ssl.SSLCertVerificationError)
|
||||
else:
|
||||
raise AssertionError("TLS принял неверный SAN")
|
||||
|
||||
client = Client(base, cafile)
|
||||
actor, bob, outsider, chat = client.bootstrap()
|
||||
attachment, _ = client.attachment(actor, chat)
|
||||
endpoint = f"/api/v1/attachments/{attachment['id']}"
|
||||
for suffix in ("", "/content"):
|
||||
client.call("GET", endpoint + suffix, 404, actor=outsider)
|
||||
client.call("GET", f"/api/v1/chats/{chat['id']}", 404, actor=outsider,
|
||||
headers={"X-User-Id": actor["id"]})
|
||||
other_chat = client.call(
|
||||
"POST", "/api/v1/chats", 201, actor=outsider,
|
||||
body={"title": "Проверка чужого вложения", "member_ids": [outsider["id"], bob["id"]]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
client.call("POST", f"/api/v1/chats/{other_chat['id']}/messages", 404,
|
||||
actor=outsider, body={"text": "", "attachment_ids": [attachment["id"]]},
|
||||
headers={"Idempotency-Key": "negative-acl-probe"})
|
||||
client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=actor)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
key = "session:" + hashlib.sha256(outsider["token"].encode()).hexdigest()
|
||||
result = project.run(
|
||||
"exec", "-T", "redis", "sh", "-ec",
|
||||
'REDISCLI_AUTH="$(cat /run/secrets/test_redis_password)" redis-cli --tls '
|
||||
'--cacert /run/tls/ca.crt -h localhost pexpire "$1" 50', "sh", key,
|
||||
)
|
||||
assert result.strip() == "1"
|
||||
time.sleep(0.1)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=outsider)
|
||||
|
||||
basic = "Basic " + base64.b64encode(b"unknown:synthetic-password").decode()
|
||||
login = base + "/api/v1/auth/sessions"
|
||||
|
||||
def login_attempt(_):
|
||||
request = Request(login, data=b"", headers={"Authorization": basic})
|
||||
try:
|
||||
urlopen(request, context=tls, timeout=5)
|
||||
except HTTPError as error:
|
||||
if error.code == 429:
|
||||
assert int(error.headers["Retry-After"]) > 0
|
||||
return error.code, error.headers.get("X-Instance-Id")
|
||||
raise AssertionError("Неизвестный пользователь получил сессию")
|
||||
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=12) as pool:
|
||||
results = list(pool.map(login_attempt, range(25)))
|
||||
statuses = [status for status, _ in results]
|
||||
replicas = {instance for status, instance in results if status == 401 and instance}
|
||||
assert set(statuses) == {401, 429} and len(replicas) >= 2, (statuses, len(replicas))
|
||||
print(f"PASS: login burst 25 за {time.monotonic() - started:.2f} с, "
|
||||
f"{statuses.count(401)} проверок на {len(replicas)} репликах, "
|
||||
f"{statuses.count(429)} ограничений")
|
||||
|
||||
try:
|
||||
urlopen(Request(login, data=b"x" * 17000), context=tls, timeout=5)
|
||||
except HTTPError as error:
|
||||
assert error.code == 413
|
||||
else:
|
||||
raise AssertionError("Превышение размера запроса не отклонено")
|
||||
print("PASS: hostname, ACL, logout, expiry, 429/Retry-After, 413")
|
||||
|
||||
|
||||
def measure_argon2(project: ComposeProject) -> None:
|
||||
probe = """
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from resource import RUSAGE_SELF, getrusage
|
||||
from statistics import median
|
||||
from time import perf_counter, process_time
|
||||
|
||||
from app.core.security import _hash_password_sync, _verify_password_sync
|
||||
|
||||
password = "generated-probe-password"
|
||||
encoded = _hash_password_sync(password)
|
||||
assert encoded.startswith("$argon2id$v=19$m=19456,t=2,p=1$")
|
||||
timings = []
|
||||
for _ in range(15):
|
||||
started = perf_counter()
|
||||
assert _verify_password_sync(password, encoded)
|
||||
timings.append((perf_counter() - started) * 1000)
|
||||
wall, cpu = perf_counter(), process_time()
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
assert all(pool.map(lambda _: _verify_password_sync(password, encoded), range(24)))
|
||||
wall, cpu = perf_counter() - wall, process_time() - cpu
|
||||
print(f"PASS: Argon2id, медиана {median(timings):.1f} мс, 24 проверки на 2 потоках "
|
||||
f"за {wall:.2f} с, CPU {cpu / 24 * 1000:.1f} мс/проверку, "
|
||||
f"пиковый RSS {getrusage(RUSAGE_SELF).ru_maxrss / 1024:.1f} MiB")
|
||||
"""
|
||||
print(project.run("exec", "-T", "api", "python", "-c", probe))
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", required=True)
|
||||
parser.add_argument("--bao-port", required=True, type=int)
|
||||
args = parser.parse_args()
|
||||
project = ComposeProject()
|
||||
probe_deployment(project)
|
||||
probe_mtls(project)
|
||||
audit_dependencies(project)
|
||||
probe_bao(args.bao_port)
|
||||
probe_http(args.base_url, project)
|
||||
measure_argon2(project)
|
||||
# Отдельный сценарий отказа начинает вход с восстановленным burst-бюджетом.
|
||||
time.sleep(6)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Выполняет проверки ЛР № 7 внутри временного контейнера."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import tarfile
|
||||
import time
|
||||
|
||||
WORKSPACE = Path("/workspace")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
with tarfile.open("/tmp/source.tar") as archive:
|
||||
archive.extractall(WORKSPACE, filter="data")
|
||||
os.chdir(WORKSPACE)
|
||||
(WORKSPACE / "evidence").mkdir(exist_ok=True)
|
||||
deadline = time.monotonic() + 120
|
||||
while subprocess.run(["docker", "info"], capture_output=True).returncode:
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError("Docker для проверочного стенда не запустился")
|
||||
time.sleep(1)
|
||||
try:
|
||||
subprocess.run(
|
||||
["docker", "image", "load", "--input", "/tmp/images.tar"],
|
||||
check=True,
|
||||
timeout=600,
|
||||
)
|
||||
finally:
|
||||
Path("/tmp/images.tar").unlink(missing_ok=True)
|
||||
os.environ["LAB7_PREBUILT"] = "1"
|
||||
os.execv(sys.executable, ["python3", "-m", "scripts.deployment", "verify"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,458 @@
|
||||
"""Общие операции с репликами текущего Compose-проекта."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Replica:
|
||||
"""Состояние контейнера API."""
|
||||
|
||||
id: str
|
||||
image: str
|
||||
instance_id: str
|
||||
running: bool
|
||||
health: str | None
|
||||
|
||||
|
||||
class ComposeProject:
|
||||
"""Работает только с выбранным Compose-проектом."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.command = ["docker", "compose", "--env-file", ".env"]
|
||||
self.config = json.loads(self.run("config", "--format", "json"))
|
||||
self.name = self.config["name"]
|
||||
|
||||
def docker(self, *args: str, timeout: int = 90, env=None, input_text=None) -> str:
|
||||
"""Выполняет Docker-команду с ограничением времени."""
|
||||
result = subprocess.run(
|
||||
["docker", *args],
|
||||
cwd=ROOT,
|
||||
encoding="utf-8",
|
||||
input=input_text,
|
||||
capture_output=True,
|
||||
timeout=timeout,
|
||||
env={**os.environ, **(env or {})},
|
||||
)
|
||||
if result.returncode:
|
||||
raise RuntimeError(result.stderr.strip() or result.stdout.strip())
|
||||
return result.stdout.strip()
|
||||
|
||||
def run(self, *args: str, timeout: int = 90, env=None, input_text=None) -> str:
|
||||
"""Выполняет команду Compose с текущими overrides."""
|
||||
return self.docker(
|
||||
*self.command[1:], *args, timeout=timeout, env=env, input_text=input_text
|
||||
)
|
||||
|
||||
def replicas(self) -> list[Replica]:
|
||||
"""Читает состояние API без окружения контейнеров."""
|
||||
ids = self.run("ps", "--all", "--quiet", "api").splitlines()
|
||||
if not ids:
|
||||
return []
|
||||
template = (
|
||||
'{"id":{{json .Id}},"image":{{json .Image}},'
|
||||
'"hostname":{{json .Config.Hostname}},"running":{{json .State.Running}},'
|
||||
'"health":{{if .State.Health}}{{json .State.Health.Status}}{{else}}null{{end}}}'
|
||||
)
|
||||
rows = self.docker("inspect", "--format", template, *ids).splitlines()
|
||||
configured = str(
|
||||
self.config["services"]["api"].get("environment", {}).get("INSTANCE_ID")
|
||||
or ""
|
||||
).strip()
|
||||
return [
|
||||
Replica(
|
||||
row["id"],
|
||||
row["image"],
|
||||
configured or row["hostname"],
|
||||
row["running"],
|
||||
row["health"],
|
||||
)
|
||||
for row in map(json.loads, rows)
|
||||
]
|
||||
|
||||
|
||||
def cleanup_docker(*args, allow_failure=False):
|
||||
result = subprocess.run(
|
||||
["docker", *args], cwd=ROOT, encoding="utf-8", capture_output=True, timeout=120
|
||||
)
|
||||
if result.returncode and not allow_failure:
|
||||
raise RuntimeError("Docker cleanup failed: " + " ".join(args[:2]))
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def inventory(projects):
|
||||
resources = {"containers": [], "networks": [], "volumes": []}
|
||||
for project in projects:
|
||||
label = "label=com.docker.compose.project=" + project
|
||||
resources["containers"].extend(
|
||||
cleanup_docker("ps", "-aq", "--filter", label).splitlines()
|
||||
)
|
||||
resources["networks"].extend(
|
||||
cleanup_docker("network", "ls", "-q", "--filter", label).splitlines()
|
||||
)
|
||||
resources["volumes"].extend(
|
||||
cleanup_docker("volume", "ls", "-q", "--filter", label).splitlines()
|
||||
)
|
||||
return resources
|
||||
|
||||
|
||||
def clean_stands(*, apply=False):
|
||||
config = json.loads(
|
||||
cleanup_docker("compose", "--env-file", ".env", "config", "--format", "json")
|
||||
)
|
||||
projects = sorted(
|
||||
{
|
||||
config["name"],
|
||||
os.getenv("MAIN_PROJECT", "messenger-lab7"),
|
||||
os.getenv("TEST_PROJECT", "messenger-lab7-test"),
|
||||
}
|
||||
)
|
||||
resources = inventory(projects)
|
||||
names = {
|
||||
service["image"]
|
||||
for service in config["services"].values()
|
||||
if "build" in service
|
||||
}
|
||||
image_tags = []
|
||||
image_ids = set()
|
||||
rows = cleanup_docker("image", "ls", "--format", "{{.Repository}} {{.Tag}} {{.ID}}")
|
||||
for row in rows.splitlines():
|
||||
repository, tag, image_id = row.split()
|
||||
name = f"{repository}:{tag}"
|
||||
if tag != "<none>" and (
|
||||
name in names
|
||||
or repository == "messenger"
|
||||
or repository.startswith(("messenger-", "mns-"))
|
||||
):
|
||||
image_tags.append(name)
|
||||
image_ids.add(image_id)
|
||||
plan = {
|
||||
"projects": projects,
|
||||
"resources": resources,
|
||||
"application_images": sorted(image_tags),
|
||||
"application_image_ids": sorted(image_ids),
|
||||
"local_settings_preserved": True,
|
||||
}
|
||||
if not apply:
|
||||
return plan
|
||||
if resources["containers"]:
|
||||
cleanup_docker("rm", "-f", "-v", *resources["containers"])
|
||||
if resources["networks"]:
|
||||
cleanup_docker("network", "rm", *resources["networks"])
|
||||
if resources["volumes"]:
|
||||
cleanup_docker("volume", "rm", *resources["volumes"])
|
||||
if image_tags:
|
||||
cleanup_docker("image", "rm", *image_tags)
|
||||
remaining = inventory(projects)
|
||||
if any(remaining.values()):
|
||||
raise RuntimeError("Cleanup incomplete")
|
||||
plan["remaining"] = remaining
|
||||
plan["application_images_remaining"] = [
|
||||
name for name in image_tags if cleanup_docker("image", "ls", "-q", name)
|
||||
]
|
||||
if plan["application_images_remaining"]:
|
||||
raise RuntimeError("Application images remain")
|
||||
plan["result"] = "PASS"
|
||||
return plan
|
||||
|
||||
|
||||
def verify(*, keep_stand=False):
|
||||
"""Один последовательный прогон на одном стенде с обязательной очисткой."""
|
||||
from datetime import datetime, timezone
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
|
||||
project_name = os.getenv("TEST_PROJECT", "messenger-lab7-test")
|
||||
if any(inventory([project_name]).values()):
|
||||
raise RuntimeError(
|
||||
f"Choose an unused TEST_PROJECT; {project_name} already has resources"
|
||||
)
|
||||
bao_port = os.getenv("TEST_BAO_PORT", "28200")
|
||||
os.environ.update(
|
||||
COMPOSE_PROJECT_NAME=project_name,
|
||||
COMPOSE_FILE="compose.yaml:compose.test.yaml",
|
||||
GRAFANA_HOST_PORT="23000",
|
||||
LB_HOST_PORT="28080",
|
||||
BAO_HOST_PORT=bao_port,
|
||||
CA_FILE=str(ROOT / "secrets/tls/ca.crt"),
|
||||
PGSSLROOTCERT=str(ROOT / "secrets/tls/ca.crt"),
|
||||
DOCKER_TESTS="1",
|
||||
OTEL_ENABLED="true",
|
||||
)
|
||||
report = {
|
||||
"date_utc": datetime.now(timezone.utc).isoformat(),
|
||||
"checks": [],
|
||||
"profile": {
|
||||
"single_stack": True,
|
||||
"load_duration_seconds": 10,
|
||||
"load_requests_per_second": 10,
|
||||
"load_concurrency": 2,
|
||||
},
|
||||
}
|
||||
destination = ROOT / "evidence/verification.json"
|
||||
destination.parent.mkdir(exist_ok=True)
|
||||
|
||||
def run(name, command, timeout=600, *, env=None, required=True):
|
||||
print("RUN: " + name, flush=True)
|
||||
started = time.monotonic()
|
||||
result = subprocess.run(
|
||||
command,
|
||||
cwd=ROOT,
|
||||
encoding="utf-8",
|
||||
capture_output=True,
|
||||
timeout=timeout,
|
||||
env={**os.environ, **(env or {})},
|
||||
)
|
||||
executable = Path(command[0])
|
||||
display_command = [
|
||||
"python3" if executable == Path(sys.executable) else command[0],
|
||||
*command[1:],
|
||||
]
|
||||
entry = {
|
||||
"name": name,
|
||||
"command": display_command,
|
||||
"exit_code": result.returncode,
|
||||
"duration_seconds": round(time.monotonic() - started, 3),
|
||||
"result": "PASS" if result.returncode == 0 else "FAIL",
|
||||
}
|
||||
if name == "regression":
|
||||
summary = re.search(r"\d+ passed[^\n]*", result.stdout)
|
||||
if summary:
|
||||
entry["summary"] = summary.group(0)
|
||||
if (
|
||||
name
|
||||
in (
|
||||
"api",
|
||||
"external-tls",
|
||||
"security",
|
||||
"lifecycle",
|
||||
"observability",
|
||||
"persistence",
|
||||
"failover",
|
||||
"scan",
|
||||
)
|
||||
and not result.returncode
|
||||
):
|
||||
entry["summary"] = result.stdout.strip().splitlines()
|
||||
print(result.stdout.strip(), flush=True)
|
||||
if result.returncode:
|
||||
# Полные диагностические логи локальны; в evidence нет путей/credentials.
|
||||
errors = ROOT / "evidence" / f"{name}-error.txt"
|
||||
diagnostic = result.stdout + result.stderr
|
||||
secrets = ROOT / "secrets"
|
||||
for path in secrets.iterdir() if secrets.is_dir() else ():
|
||||
if path.is_file():
|
||||
value = path.read_text(encoding="utf-8").strip()
|
||||
if value:
|
||||
diagnostic = diagnostic.replace(value, "[redacted]")
|
||||
diagnostic = re.sub(
|
||||
r"(?i)(https?://[^\s\"?]+)\?[^\s\"]+", r"\1?[redacted]", diagnostic
|
||||
)
|
||||
diagnostic = re.sub(
|
||||
r"-----BEGIN [A-Z ]*PRIVATE KEY-----.*?-----END [A-Z ]*PRIVATE KEY-----",
|
||||
"[redacted key]",
|
||||
diagnostic,
|
||||
flags=re.DOTALL,
|
||||
)
|
||||
errors.write_text(diagnostic, encoding="utf-8")
|
||||
entry["diagnostics"] = errors.name
|
||||
report["checks"].append(entry)
|
||||
print(entry["result"] + ": " + name, flush=True)
|
||||
if result.returncode and required:
|
||||
raise RuntimeError(name + " failed; inspect evidence")
|
||||
|
||||
try:
|
||||
python = sys.executable
|
||||
compose = ["docker", "compose", "--env-file", ".env"]
|
||||
base = ["--base-url", "https://localhost:28080"]
|
||||
bao = ["--bao-port", bao_port]
|
||||
run("init", [python, "-m", "scripts.init_local"])
|
||||
run("contract", [python, "scripts/check_contract.py"])
|
||||
run("openapi", [python, "scripts/validate_openapi.py"])
|
||||
run("compose", compose + ["config", "--quiet"])
|
||||
images = (
|
||||
["--no-build", "--pull", "never"]
|
||||
if os.getenv("LAB7_PREBUILT") == "1"
|
||||
else ["--build"]
|
||||
)
|
||||
run("openbao", compose + ["up", "-d", *images, "openbao"])
|
||||
run("bootstrap", [python, "-m", "scripts.bootstrap_bao", "--port", bao_port])
|
||||
run("startup", compose + ["up", "-d", *images], timeout=900)
|
||||
run(
|
||||
"readiness",
|
||||
compose
|
||||
+ [
|
||||
"up",
|
||||
"-d",
|
||||
"--no-deps",
|
||||
"--wait",
|
||||
"--wait-timeout",
|
||||
"240",
|
||||
"nginx",
|
||||
"grafana",
|
||||
],
|
||||
)
|
||||
run(
|
||||
"test-database",
|
||||
compose
|
||||
+ [
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"sh",
|
||||
"-ec",
|
||||
'createdb -U "$POSTGRES_USER" "${POSTGRES_DB}_test"',
|
||||
],
|
||||
)
|
||||
config = ComposeProject().config["services"]
|
||||
db_port = next(
|
||||
port["published"]
|
||||
for port in config["postgres"]["ports"]
|
||||
if port["target"] == 5432
|
||||
)
|
||||
redis_port = next(
|
||||
port["published"]
|
||||
for port in config["redis"]["ports"]
|
||||
if port["target"] == 6379
|
||||
)
|
||||
db_user = config["postgres"]["environment"]["POSTGRES_USER"]
|
||||
db_name = config["postgres"]["environment"]["POSTGRES_DB"] + "_test"
|
||||
db_password = (ROOT / "secrets/db_password").read_text(encoding="utf-8").strip()
|
||||
test_env = {
|
||||
"OTEL_ENABLED": "false",
|
||||
"TEST_DATABASE_URL": f"postgresql+asyncpg://{db_user}:{db_password}@localhost:{db_port}/{db_name}?ssl=verify-full",
|
||||
"TEST_REDIS_HOST": "localhost",
|
||||
"TEST_REDIS_PORT": str(redis_port),
|
||||
"TEST_REDIS_PASSWORD": (ROOT / "secrets/test_redis_password")
|
||||
.read_text(encoding="utf-8")
|
||||
.strip(),
|
||||
"TEST_REDIS_DB": "15",
|
||||
"TEST_REDIS_CA_FILE": os.environ["CA_FILE"],
|
||||
}
|
||||
run(
|
||||
"regression",
|
||||
[python, "-m", "pytest", "-q"],
|
||||
timeout=1800,
|
||||
env=test_env,
|
||||
required=False,
|
||||
)
|
||||
run("api", [python, "tests/smoke.py", *base], required=False)
|
||||
run(
|
||||
"observability",
|
||||
[
|
||||
python,
|
||||
"-m",
|
||||
"scripts.check_observability",
|
||||
*base,
|
||||
"--grafana-url",
|
||||
"https://localhost:23000",
|
||||
"--incidents",
|
||||
"--restart-telemetry",
|
||||
],
|
||||
timeout=900,
|
||||
required=False,
|
||||
)
|
||||
run(
|
||||
"persistence",
|
||||
[
|
||||
python,
|
||||
"tests/resilience.py",
|
||||
"--mode",
|
||||
"persistence",
|
||||
"--action-script",
|
||||
"scripts/restart.sh",
|
||||
*base,
|
||||
],
|
||||
required=False,
|
||||
)
|
||||
run("external-tls", [python, "tests/security.py", *base], required=False)
|
||||
run(
|
||||
"security",
|
||||
[python, "-m", "scripts.check_security", *base, *bao],
|
||||
required=False,
|
||||
)
|
||||
run(
|
||||
"lifecycle",
|
||||
[python, "-m", "scripts.check_lifecycle", *base, *bao],
|
||||
required=False,
|
||||
)
|
||||
run(
|
||||
"failover",
|
||||
[
|
||||
python,
|
||||
"tests/resilience.py",
|
||||
"--mode",
|
||||
"failover",
|
||||
"--action-script",
|
||||
"scripts/stop-one.sh",
|
||||
*base,
|
||||
],
|
||||
required=False,
|
||||
)
|
||||
run(
|
||||
"scan",
|
||||
[python, "-m", "scripts.scan_security"],
|
||||
timeout=1800,
|
||||
required=False,
|
||||
)
|
||||
report["result"] = (
|
||||
"PASS"
|
||||
if all(check["exit_code"] == 0 for check in report["checks"])
|
||||
else "FAIL"
|
||||
)
|
||||
except BaseException:
|
||||
report["result"] = "FAIL"
|
||||
raise
|
||||
finally:
|
||||
try:
|
||||
if keep_stand:
|
||||
report["cleanup"] = {"project": project_name, "result": "DEFERRED"}
|
||||
else:
|
||||
print("RUN: cleanup", flush=True)
|
||||
ComposeProject().run(
|
||||
"down", "--volumes", "--remove-orphans", timeout=120
|
||||
)
|
||||
remaining = inventory([project_name])
|
||||
if any(remaining.values()):
|
||||
raise RuntimeError("Verification project cleanup incomplete")
|
||||
report["cleanup"] = {
|
||||
"project": project_name,
|
||||
"remaining": remaining,
|
||||
"result": "PASS",
|
||||
}
|
||||
print("PASS: cleanup", flush=True)
|
||||
finally:
|
||||
report["finished_at_utc"] = datetime.now(timezone.utc).isoformat()
|
||||
destination.write_text(
|
||||
json.dumps(report, ensure_ascii=False, indent=2) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
if report["result"] != "PASS":
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
def main():
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(description="Проверка и очистка Compose-стендов")
|
||||
parser.add_argument("command", choices=["verify", "clean"])
|
||||
parser.add_argument("--keep-stand", action="store_true")
|
||||
parser.add_argument(
|
||||
"--apply", action="store_true", help="Подтвердить удаление ресурсов"
|
||||
)
|
||||
args = parser.parse_args()
|
||||
if args.command == "verify":
|
||||
verify(keep_stand=args.keep_stand)
|
||||
else:
|
||||
print(json.dumps(clean_stands(apply=args.apply), indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Готовит cert-пользователей RabbitMQ и их права очереди."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
|
||||
def initialize(directory: Path, queue: str, vhost: str) -> None:
|
||||
queue_pattern = f"^{re.escape(queue)}$"
|
||||
denied = "^$a"
|
||||
roles = (
|
||||
("api-broker", denied, denied, denied),
|
||||
("attachment-publisher", queue_pattern, denied, r"^amq\.default$"),
|
||||
("attachment-worker", queue_pattern, queue_pattern, denied),
|
||||
)
|
||||
users = [
|
||||
{"name": name, "password_hash": "", "hashing_algorithm": "rabbit_password_hashing_sha256",
|
||||
"tags": []}
|
||||
for name, *_ in roles
|
||||
]
|
||||
permissions = [
|
||||
{"user": name, "vhost": vhost, "configure": configure, "read": read, "write": write}
|
||||
for name, configure, read, write in roles
|
||||
]
|
||||
definitions = json.dumps({"users": users, "vhosts": [{"name": vhost}],
|
||||
"permissions": permissions})
|
||||
path = directory / "broker_definitions.json"
|
||||
if not path.exists() or path.read_text() != definitions:
|
||||
temporary = path.with_suffix(".tmp")
|
||||
temporary.write_text(definitions)
|
||||
temporary.chmod(0o444)
|
||||
temporary.replace(path)
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Создаёт только отсутствующие локальные настройки и файловые секреты."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
|
||||
from scripts.init_broker import initialize as initialize_broker
|
||||
from scripts.init_tls import initialize
|
||||
|
||||
|
||||
def main() -> None:
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
destination = root / ".env"
|
||||
if not destination.exists():
|
||||
with destination.open("x", encoding="utf-8", newline="\n") as target:
|
||||
target.write((root / ".env.example").read_text(encoding="utf-8"))
|
||||
destination.chmod(0o600)
|
||||
directory = root / "secrets"
|
||||
directory.mkdir(mode=0o700, exist_ok=True)
|
||||
for name in (
|
||||
"grafana_admin_password",
|
||||
"db_password",
|
||||
"api_db_password",
|
||||
"worker_db_password",
|
||||
"publisher_db_password",
|
||||
"cleanup_db_password",
|
||||
"redis_password",
|
||||
"test_redis_password",
|
||||
"minio_root_user",
|
||||
"minio_root_password",
|
||||
"s3_access_key_id",
|
||||
"s3_secret_access_key",
|
||||
"worker_s3_access_key_id",
|
||||
"worker_s3_secret_access_key",
|
||||
):
|
||||
path = directory / name
|
||||
try:
|
||||
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o444)
|
||||
except FileExistsError:
|
||||
continue
|
||||
with os.fdopen(descriptor, "w", encoding="utf-8") as target:
|
||||
target.write(secrets.token_urlsafe(24))
|
||||
print("Создан файл " + str(path.relative_to(root)))
|
||||
settings = {
|
||||
key: value
|
||||
for line in destination.read_text(encoding="utf-8").splitlines()
|
||||
if line and not line.lstrip().startswith("#") and "=" in line
|
||||
for key, value in [line.split("=", 1)]
|
||||
}
|
||||
initialize_broker(directory, settings["BROKER_QUEUE"], settings["BROKER_VHOST"])
|
||||
initialize(root)
|
||||
print("Настройки готовы; существующие значения сохранены")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Выпускает локальные CA и сертификаты для учебного стенда."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
SERVER_NAMES = {
|
||||
"ingress": "DNS:localhost",
|
||||
"api": "DNS:api",
|
||||
"postgres": "DNS:postgres,DNS:localhost",
|
||||
"redis": "DNS:redis,DNS:localhost",
|
||||
"broker": "DNS:broker",
|
||||
"minio": "DNS:minio",
|
||||
"openbao": "DNS:openbao,DNS:localhost",
|
||||
"collector": "DNS:otel-collector",
|
||||
"prometheus": "DNS:prometheus",
|
||||
"loki": "DNS:loki",
|
||||
"tempo": "DNS:tempo",
|
||||
"grafana": "DNS:grafana,DNS:localhost",
|
||||
}
|
||||
|
||||
|
||||
def openssl(*args: str) -> None:
|
||||
subprocess.run(["openssl", *args], check=True, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def create_ca(directory: Path, name: str) -> None:
|
||||
key, cert = directory / f"{name}.key", directory / f"{name}.crt"
|
||||
if key.exists() and cert.exists():
|
||||
return
|
||||
openssl("req", "-x509", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1",
|
||||
"-nodes", "-days", "365", "-subj", f"/CN={name}", "-keyout", str(key),
|
||||
"-out", str(cert), "-addext", "basicConstraints=critical,CA:TRUE",
|
||||
"-addext", "keyUsage=critical,keyCertSign,cRLSign")
|
||||
key.chmod(0o600)
|
||||
cert.chmod(0o644)
|
||||
|
||||
|
||||
def issue(directory: Path, name: str, san: str, usage: str, ca: str) -> None:
|
||||
cert = directory / f"{name}.crt"
|
||||
key = directory / f"{name}.key"
|
||||
if cert.exists() and key.exists():
|
||||
return
|
||||
request, extensions = directory / f"{name}.csr", directory / f"{name}.ext"
|
||||
try:
|
||||
openssl("req", "-new", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1",
|
||||
"-nodes", "-subj", f"/CN={name}", "-keyout", str(key), "-out", str(request))
|
||||
extensions.write_text(
|
||||
"basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature\n"
|
||||
f"extendedKeyUsage={usage}\nsubjectAltName={san}\n"
|
||||
)
|
||||
openssl("x509", "-req", "-in", str(request), "-CA", str(directory / f"{ca}.crt"),
|
||||
"-CAkey", str(directory / f"{ca}.key"), "-set_serial", f"0x{os.urandom(16).hex()}",
|
||||
"-days", "30", "-extfile", str(extensions), "-out", str(cert))
|
||||
# Каталог 0700 защищает ключи на хосте. В контейнер монтируется только его ключ.
|
||||
key.chmod(0o444)
|
||||
cert.chmod(0o644)
|
||||
finally:
|
||||
request.unlink(missing_ok=True)
|
||||
extensions.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def initialize(root: Path) -> None:
|
||||
directory = root / "secrets" / "tls"
|
||||
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
for name in ("ca", "foreign-ca", "broker-client-ca", "otel-ingest-ca", "otel-write-ca", "otel-read-ca", "otel-scrape-ca"):
|
||||
create_ca(directory, name)
|
||||
for name, san in SERVER_NAMES.items():
|
||||
issue(directory, name, san, "serverAuth", "ca")
|
||||
for name in ("load-balancer", "api-bao", "worker-bao", "publisher-bao", "cleanup-bao", "wrong-role"):
|
||||
issue(directory, name, f"DNS:{name}", "clientAuth", "ca")
|
||||
issue(directory, "foreign-client", "DNS:load-balancer", "clientAuth", "foreign-ca")
|
||||
for name, authority in (
|
||||
("otel-writer", "otel-write-ca"),
|
||||
("otel-reader", "otel-read-ca"),
|
||||
("otel-api", "otel-ingest-ca"),
|
||||
("otel-worker", "otel-ingest-ca"),
|
||||
("otel-publisher", "otel-ingest-ca"),
|
||||
("otel-wrong-role", "otel-ingest-ca"),
|
||||
("api-broker", "broker-client-ca"),
|
||||
("attachment-worker", "broker-client-ca"),
|
||||
("attachment-publisher", "broker-client-ca"),
|
||||
("broker-wrong-role", "broker-client-ca"),
|
||||
("otel-scraper", "otel-scrape-ca"),
|
||||
):
|
||||
issue(directory, name, f"DNS:{name}", "clientAuth", authority)
|
||||
bundle = "".join((directory / f"otel-{role}-ca.crt").read_text() for role in ("read", "write"))
|
||||
(directory / "loki-clients.crt").write_text(bundle)
|
||||
@@ -0,0 +1,45 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
compose() {
|
||||
docker compose --env-file .env "$@"
|
||||
}
|
||||
|
||||
wait_healthy() {
|
||||
for service in "$@"; do
|
||||
attempts=0
|
||||
until states=$(compose ps --format '{{.Health}}' "$service") \
|
||||
&& [ -n "$states" ] \
|
||||
&& [ -z "$(printf '%s\n' "$states" | grep -v '^healthy$')" ]; do
|
||||
attempts=$((attempts + 1))
|
||||
if [ "$attempts" -ge 60 ]; then
|
||||
echo "$service не стал healthy за 60 секунд" >&2
|
||||
exit 1
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
done
|
||||
}
|
||||
|
||||
worker_running=$(compose ps --status running --quiet worker)
|
||||
compose stop worker publisher cleanup
|
||||
compose restart postgres redis minio broker prometheus loki tempo grafana otel-collector
|
||||
wait_healthy postgres redis minio broker
|
||||
compose restart openbao
|
||||
"${PYTHON:-python3}" -m scripts.bootstrap_bao --unseal-only --port "${BAO_HOST_PORT:-18200}"
|
||||
wait_healthy openbao
|
||||
compose restart api nginx
|
||||
wait_healthy api nginx
|
||||
# Compose start также запускает завершённые migrate/bootstrap dependencies.
|
||||
# Здесь нужны только ранее созданные фоновые контейнеры, без повторного bootstrap.
|
||||
background_ids=$(compose ps --all --quiet publisher cleanup)
|
||||
docker start $background_ids
|
||||
# Сценарий с заранее остановленным worker сохраняет его остановленным.
|
||||
if [ -n "$worker_running" ]; then
|
||||
worker_ids=$(compose ps --all --quiet worker)
|
||||
docker start $worker_ids
|
||||
fi
|
||||
# Пока восстанавливался бизнес-путь, telemetry backend тоже успели запуститься.
|
||||
# Grafana healthcheck проверяет также готовность Loki, Tempo и Collector.
|
||||
wait_healthy grafana
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Ротация пароля PostgreSQL и cert identity worker из операторского контура."""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
from tempfile import TemporaryDirectory
|
||||
from urllib.error import HTTPError
|
||||
|
||||
from scripts.bootstrap_bao import ROOT, TLS, Bao, operator_token
|
||||
from scripts.deployment import ComposeProject
|
||||
from scripts.init_tls import issue
|
||||
|
||||
|
||||
def cert_role(certificate: Path, role: str, ttl: str = "10m") -> dict:
|
||||
return {
|
||||
"certificate": certificate.read_text(),
|
||||
"token_policies": [role],
|
||||
"token_no_default_policy": True,
|
||||
"token_ttl": ttl,
|
||||
"token_max_ttl": ttl,
|
||||
}
|
||||
|
||||
|
||||
def change_db_password(project: ComposeProject, password: str) -> None:
|
||||
salt = secrets.token_bytes(16)
|
||||
iterations = 4096
|
||||
salted = hashlib.pbkdf2_hmac("sha256", password.encode(), salt, iterations)
|
||||
client_key = hmac.digest(salted, b"Client Key", "sha256")
|
||||
server_key = hmac.digest(salted, b"Server Key", "sha256")
|
||||
|
||||
def encode(value):
|
||||
return base64.b64encode(value).decode()
|
||||
|
||||
verifier = (f"SCRAM-SHA-256${iterations}:{encode(salt)}"
|
||||
f"${encode(hashlib.sha256(client_key).digest())}:{encode(server_key)}")
|
||||
project.run("exec", "-T", "postgres", "sh", "-ec",
|
||||
'exec psql --no-psqlrc -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"',
|
||||
input_text=f"ALTER ROLE worker PASSWORD '{verifier}';\n")
|
||||
|
||||
|
||||
def rotate(project: ComposeProject, port: int) -> None:
|
||||
bao, token = Bao(port), operator_token(port)
|
||||
role_path = "auth/cert/certs/worker"
|
||||
secret_path = "messenger/data/worker"
|
||||
previous = bao.call(secret_path, token=token)["data"]["data"]
|
||||
current_cert = TLS / "worker-bao.crt"
|
||||
current_key = TLS / "worker-bao.key"
|
||||
password_file = ROOT / "secrets/worker_db_password"
|
||||
password = secrets.token_urlsafe(24)
|
||||
|
||||
with TemporaryDirectory(prefix=".worker-rotation-", dir=TLS) as directory:
|
||||
staging = Path(directory)
|
||||
for suffix in ("crt", "key"):
|
||||
(staging / f"ca.{suffix}").symlink_to(TLS / f"ca.{suffix}")
|
||||
issue(staging, "worker-bao", "DNS:worker-bao", "clientAuth", "ca")
|
||||
new_cert, new_key = (staging / f"worker-bao.{suffix}" for suffix in ("crt", "key"))
|
||||
old_certificate, old_key = current_cert.read_bytes(), current_key.read_bytes()
|
||||
project.run("stop", "worker")
|
||||
try:
|
||||
change_db_password(project, password)
|
||||
bao.call(secret_path, {"data": {"db_password": password}}, token=token)
|
||||
bao.call(role_path, cert_role(new_cert, "worker"), token=token)
|
||||
password_stage = staging / "password"
|
||||
password_stage.write_text(password)
|
||||
password_stage.chmod(0o444)
|
||||
os.replace(password_stage, password_file)
|
||||
os.replace(new_cert, current_cert)
|
||||
os.replace(new_key, current_key)
|
||||
project.run("up", "-d", "--no-build", "--no-deps", "--force-recreate", "worker")
|
||||
except (HTTPError, OSError, RuntimeError):
|
||||
change_db_password(project, previous["db_password"])
|
||||
bao.call(secret_path, {"data": previous}, token=token)
|
||||
for path, data in ((current_cert, old_certificate), (current_key, old_key),
|
||||
(password_file, previous["db_password"].encode())):
|
||||
temporary = staging / (path.name + ".rollback")
|
||||
temporary.write_bytes(data)
|
||||
temporary.chmod(0o444)
|
||||
os.replace(temporary, path)
|
||||
bao.call(role_path, cert_role(current_cert, "worker"), token=token)
|
||||
project.run("up", "-d", "--no-build", "--no-deps", "--force-recreate", "worker")
|
||||
raise
|
||||
print("PASS: пароль PostgreSQL и клиентский сертификат worker заменены без сборки")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--bao-port", type=int, default=18200)
|
||||
rotate(ComposeProject(), parser.parse_args().bao_port)
|
||||
@@ -0,0 +1,119 @@
|
||||
"""Сканирует lock-файл и локальные образы, не передавая сокет Docker сканеру."""
|
||||
|
||||
from datetime import UTC, datetime
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
from tempfile import TemporaryDirectory
|
||||
|
||||
from scripts.deployment import ROOT, ComposeProject
|
||||
|
||||
SCANNER = "ghcr.io/aquasecurity/trivy:0.76.2"
|
||||
|
||||
|
||||
def scan() -> dict:
|
||||
project = ComposeProject()
|
||||
images = sorted(
|
||||
{
|
||||
service["image"]
|
||||
for service in project.config["services"].values()
|
||||
if "build" in service
|
||||
}
|
||||
)
|
||||
with TemporaryDirectory(prefix="lab7-scan-", dir=ROOT) as directory:
|
||||
workspace = Path(directory)
|
||||
packages = workspace / "packages"
|
||||
packages.mkdir()
|
||||
shutil.copyfile(ROOT / "requirements.txt", packages / "requirements.txt")
|
||||
cache = workspace / "cache"
|
||||
cache.mkdir()
|
||||
|
||||
def trivy(mount, args):
|
||||
result = subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"run",
|
||||
"--rm",
|
||||
"--pull",
|
||||
"never",
|
||||
"--cap-drop=ALL",
|
||||
"--user",
|
||||
f"{os.getuid()}:{os.getgid()}",
|
||||
"--security-opt=no-new-privileges",
|
||||
"-v",
|
||||
f"{cache}:/cache",
|
||||
"-v",
|
||||
mount,
|
||||
SCANNER,
|
||||
*args,
|
||||
"--cache-dir",
|
||||
"/cache",
|
||||
"--quiet",
|
||||
"--scanners",
|
||||
"vuln",
|
||||
"--severity",
|
||||
"HIGH,CRITICAL",
|
||||
"--format",
|
||||
"json",
|
||||
"--timeout",
|
||||
"6m",
|
||||
],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
stdout=subprocess.PIPE,
|
||||
)
|
||||
report = json.loads(result.stdout)
|
||||
return {
|
||||
"targets": [item["Target"] for item in report.get("Results", [])],
|
||||
"findings": [
|
||||
{
|
||||
name: issue.get(name)
|
||||
for name in (
|
||||
"VulnerabilityID",
|
||||
"PkgName",
|
||||
"InstalledVersion",
|
||||
"FixedVersion",
|
||||
"Severity",
|
||||
"PrimaryURL",
|
||||
"Status",
|
||||
)
|
||||
}
|
||||
for item in report.get("Results", [])
|
||||
for issue in item.get("Vulnerabilities", [])
|
||||
],
|
||||
}
|
||||
|
||||
result = {
|
||||
"scanner": SCANNER,
|
||||
"date_utc": datetime.now(UTC).isoformat(),
|
||||
"dependency": trivy(
|
||||
f"{packages}:/scan:ro",
|
||||
["fs", "/scan"],
|
||||
),
|
||||
"images": {},
|
||||
}
|
||||
archive = workspace / "image.tar"
|
||||
for name in images:
|
||||
subprocess.run(
|
||||
["docker", "image", "save", "-o", archive, name], cwd=ROOT, check=True
|
||||
)
|
||||
findings = trivy(
|
||||
f"{archive}:/image.tar:ro", ["image", "--input", "/image.tar"]
|
||||
)
|
||||
result["images"][name] = {
|
||||
"image_id": project.docker(
|
||||
"image", "inspect", "--format", "{{.Id}}", name
|
||||
),
|
||||
**findings,
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
destination = ROOT / "evidence/security-scan.json"
|
||||
destination.write_text(
|
||||
json.dumps(scan(), ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
|
||||
)
|
||||
print("Результаты Trivy сохранены в evidence/security-scan.json")
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
|
||||
case "$TARGET_INSTANCE_ID" in
|
||||
*[!a-zA-Z0-9_.:-]*|'') exit 1 ;;
|
||||
esac
|
||||
|
||||
target=""
|
||||
for container in $(docker compose --env-file .env ps -q api); do
|
||||
hostname=$(docker inspect --format '{{.Config.Hostname}}' "$container")
|
||||
configured=$(docker inspect --format '{{range .Config.Env}}{{if eq (index (split . "=") 0) "INSTANCE_ID"}}{{println .}}{{end}}{{end}}' "$container" \
|
||||
| sed -n 's/^INSTANCE_ID=//p' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
|
||||
if [ "$TARGET_INSTANCE_ID" = "$hostname" ] || [ "$TARGET_INSTANCE_ID" = "$configured" ]; then
|
||||
if [ -n "$target" ]; then
|
||||
echo 'Instance id matches multiple API containers' >&2
|
||||
exit 1
|
||||
fi
|
||||
target="$container"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -z "$target" ]; then
|
||||
echo 'Target API instance not found in this Compose project' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Stopping API container $target" >&2
|
||||
docker stop --timeout 8 "$target" >/dev/null
|
||||
+246
@@ -0,0 +1,246 @@
|
||||
"""Запускает проверки в одноразовом Docker-окружении и сохраняет evidence."""
|
||||
|
||||
import argparse
|
||||
from datetime import datetime, timezone
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tarfile
|
||||
import tempfile
|
||||
from uuid import uuid4
|
||||
|
||||
SCANNER = "ghcr.io/aquasecurity/trivy:0.76.2"
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
EXCLUDED = {
|
||||
".git",
|
||||
".agents",
|
||||
".aws",
|
||||
".codex",
|
||||
".env",
|
||||
"secrets",
|
||||
"evidence",
|
||||
".venv",
|
||||
"venv",
|
||||
"__pycache__",
|
||||
".pytest_cache",
|
||||
".github",
|
||||
"docs",
|
||||
".cache",
|
||||
".ruff_cache",
|
||||
".mypy_cache",
|
||||
"data",
|
||||
"volumes",
|
||||
"backups",
|
||||
"certs",
|
||||
}
|
||||
TEXT_SUFFIXES = {".py", ".sh", ".conf", ".yaml", ".yml", ".json", ".txt", ".md", ".ini"}
|
||||
|
||||
|
||||
def docker(*args, **kwargs):
|
||||
kwargs.setdefault("check", True)
|
||||
return subprocess.run(["docker", *args], cwd=ROOT, **kwargs)
|
||||
|
||||
|
||||
def archive_source(destination):
|
||||
with tarfile.open(destination, "w") as archive:
|
||||
for path in sorted(ROOT.rglob("*")):
|
||||
relative = path.relative_to(ROOT)
|
||||
if (
|
||||
not path.is_file()
|
||||
or path.is_symlink()
|
||||
or any(part in EXCLUDED for part in relative.parts)
|
||||
or path.name.startswith(".env.")
|
||||
and path.name != ".env.example"
|
||||
or path.suffix in {".zip", ".log", ".pem", ".key"}
|
||||
):
|
||||
continue
|
||||
content = path.read_bytes()
|
||||
if path.suffix in TEXT_SUFFIXES:
|
||||
content = content.replace(b"\r\n", b"\n")
|
||||
entry = tarfile.TarInfo(relative.as_posix())
|
||||
entry.size = len(content)
|
||||
entry.mode = 0o755 if path.suffix == ".sh" else 0o644
|
||||
archive.addfile(entry, io.BytesIO(content))
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.parse_args()
|
||||
project = "messenger-check-" + uuid4().hex[:12]
|
||||
image = project + ":tools"
|
||||
image_env = {
|
||||
"API_IMAGE": project + ":api",
|
||||
"MINIO_IMAGE": project + ":server",
|
||||
"MINIO_BOOTSTRAP_IMAGE": project + ":bootstrap",
|
||||
}
|
||||
engine = project + "-engine"
|
||||
runner = project + "-runner"
|
||||
workspace = project + "-workspace"
|
||||
data = project + "-data"
|
||||
network = project + "-network"
|
||||
output = ROOT / "evidence" / "lab7"
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
summary = {
|
||||
"status": "failed",
|
||||
"project": project,
|
||||
"started_at": datetime.now(timezone.utc).isoformat(),
|
||||
}
|
||||
try:
|
||||
docker("build", "--tag", image, "--file", "infra/testing/Dockerfile", ".")
|
||||
compose = ("compose", "--env-file", ".env.example")
|
||||
env = {**os.environ, **image_env}
|
||||
config = json.loads(
|
||||
docker(
|
||||
*compose, "config", "--format", "json", env=env, capture_output=True
|
||||
).stdout
|
||||
)
|
||||
dependencies = sorted(
|
||||
{
|
||||
service["image"]
|
||||
for service in config["services"].values()
|
||||
if "build" not in service
|
||||
}
|
||||
)
|
||||
docker(
|
||||
*compose,
|
||||
"pull",
|
||||
"--ignore-buildable",
|
||||
"--policy",
|
||||
"missing",
|
||||
env=env,
|
||||
timeout=3600,
|
||||
)
|
||||
docker(
|
||||
*compose, "build", "api", "minio", "minio-bootstrap", env=env, timeout=3600
|
||||
)
|
||||
if docker(
|
||||
"image",
|
||||
"inspect",
|
||||
SCANNER,
|
||||
check=False,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
).returncode:
|
||||
docker("pull", SCANNER, timeout=900)
|
||||
docker("network", "create", network, stdout=subprocess.DEVNULL)
|
||||
for volume in (workspace, data):
|
||||
docker("volume", "create", volume, stdout=subprocess.DEVNULL)
|
||||
docker(
|
||||
"run",
|
||||
"-d",
|
||||
"--privileged",
|
||||
"--name",
|
||||
engine,
|
||||
"--network",
|
||||
network,
|
||||
"--env",
|
||||
"DOCKER_TLS_CERTDIR=",
|
||||
"--volume",
|
||||
workspace + ":/workspace",
|
||||
"--volume",
|
||||
data + ":/var/lib/docker",
|
||||
"docker:29.1.3-dind",
|
||||
"dockerd",
|
||||
"--host=unix:///var/run/docker.sock",
|
||||
"--host=tcp://127.0.0.1:2375",
|
||||
"--tls=false",
|
||||
stdout=subprocess.DEVNULL,
|
||||
)
|
||||
docker(
|
||||
"create",
|
||||
"--name",
|
||||
runner,
|
||||
"--network",
|
||||
"container:" + engine,
|
||||
"--env",
|
||||
"DOCKER_HOST=tcp://127.0.0.1:2375",
|
||||
*[
|
||||
arg
|
||||
for key, value in image_env.items()
|
||||
for arg in ("--env", f"{key}={value}")
|
||||
],
|
||||
"--volume",
|
||||
workspace + ":/workspace",
|
||||
image,
|
||||
stdout=subprocess.DEVNULL,
|
||||
)
|
||||
with tempfile.TemporaryDirectory(prefix="messenger-check-") as directory:
|
||||
archive = Path(directory) / "source.tar"
|
||||
archive_source(archive)
|
||||
docker("cp", str(archive), runner + ":/tmp/source.tar")
|
||||
image_archive = Path(directory) / "images.tar"
|
||||
docker(
|
||||
"image",
|
||||
"save",
|
||||
"--output",
|
||||
str(image_archive),
|
||||
*image_env.values(),
|
||||
*dependencies,
|
||||
SCANNER,
|
||||
)
|
||||
docker("cp", str(image_archive), runner + ":/tmp/images.tar")
|
||||
docker("start", "--attach", runner, check=False, timeout=7200)
|
||||
result = subprocess.run(
|
||||
["docker", "wait", runner],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
capture_output=True,
|
||||
timeout=7200,
|
||||
)
|
||||
result.check_returncode()
|
||||
docker("cp", runner + ":/workspace/evidence/.", str(output))
|
||||
if int(result.stdout.strip()) != 0:
|
||||
raise RuntimeError(
|
||||
f"Проверки завершились ошибкой. См. {output.relative_to(ROOT)}."
|
||||
)
|
||||
summary["status"] = "passed"
|
||||
finally:
|
||||
cleanup = []
|
||||
for command in (
|
||||
["rm", "--force", runner, engine],
|
||||
["volume", "rm", workspace, data],
|
||||
["network", "rm", network],
|
||||
["image", "rm", image, *image_env.values()],
|
||||
):
|
||||
result = subprocess.run(
|
||||
["docker", *command], cwd=ROOT, encoding="utf-8", capture_output=True
|
||||
)
|
||||
cleanup.append(
|
||||
{
|
||||
"command": ["docker", *command],
|
||||
"returncode": result.returncode,
|
||||
"output": result.stdout.strip() + result.stderr.strip(),
|
||||
}
|
||||
)
|
||||
remaining = {}
|
||||
for kind in ("container", "volume", "network", "image"):
|
||||
result = subprocess.run(
|
||||
["docker", kind, "ls", "--format", "{{json .}}"],
|
||||
cwd=ROOT,
|
||||
encoding="utf-8",
|
||||
capture_output=True,
|
||||
)
|
||||
remaining[kind] = [
|
||||
line for line in result.stdout.splitlines() if project in line
|
||||
]
|
||||
if result.returncode:
|
||||
remaining[kind].append("resource audit failed")
|
||||
summary["cleanup"] = cleanup
|
||||
summary["remaining_resources"] = remaining
|
||||
summary["finished_at"] = datetime.now(timezone.utc).isoformat()
|
||||
if any(remaining.values()):
|
||||
summary["status"] = "failed"
|
||||
(output / "run.json").write_text(
|
||||
json.dumps(summary, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
|
||||
)
|
||||
if summary["status"] == "failed":
|
||||
raise SystemExit(1)
|
||||
print("PASS: проверки завершены, временное окружение удалено")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+15
-10
@@ -1,23 +1,28 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Full OpenAPI and JSON Schema checks; install requirements-dev.txt first."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from openapi_spec_validator import validate
|
||||
from jsonschema import Draft202012Validator
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
spec = json.loads((root/'contracts/openapi.json').read_text())
|
||||
spec = json.loads((root / "contracts/openapi.json").read_text(encoding="utf-8"))
|
||||
validate(spec)
|
||||
from referencing import Registry, Resource
|
||||
# The base URI resolves local #/components references inside examples.
|
||||
resource = dict(spec, **{'$schema': 'https://json-schema.org/draft/2020-12/schema'})
|
||||
registry = Registry().with_resource('urn:mtusi:openapi', Resource.from_contents(resource))
|
||||
for name, example in json.loads((root/'contracts/examples.json').read_text()).items():
|
||||
schema = {'$ref': 'urn:mtusi:openapi#/components/schemas/' + name}
|
||||
|
||||
resource = dict(spec, **{"$schema": "https://json-schema.org/draft/2020-12/schema"})
|
||||
registry = Registry().with_resource(
|
||||
"urn:messenger:openapi", Resource.from_contents(resource)
|
||||
)
|
||||
for name, example in json.loads(
|
||||
(root / "contracts/examples.json").read_text(encoding="utf-8")
|
||||
).items():
|
||||
schema = {"$ref": "urn:messenger:openapi#/components/schemas/" + name}
|
||||
Draft202012Validator(schema, registry=registry).validate(example)
|
||||
for path in (root/'contracts').glob('*.schema.json'):
|
||||
schema = json.loads(path.read_text())
|
||||
for path in (root / "contracts").glob("*.schema.json"):
|
||||
schema = json.loads(path.read_text(encoding="utf-8"))
|
||||
Draft202012Validator.check_schema(schema)
|
||||
for example in schema.get('examples',[]):
|
||||
for example in schema.get("examples", []):
|
||||
Draft202012Validator(schema).validate(example)
|
||||
print('PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.')
|
||||
print("PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.")
|
||||
|
||||
Reference in New Issue
Block a user