выполение на 5
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
kaktuz20000
2026-11-04 19:22:35 +03:00
parent 20afc2c790
commit 5a6fcff3ef
90 changed files with 8848 additions and 130 deletions
+25 -12
View File
@@ -1,12 +1,21 @@
# Публичные проверки
# Проверки lab7
Python **3.9+**, стандартная библиотека. Сервер уже должен быть запущен; проверки не создают готовое приложение и сами не управляют Docker. `make check` можно выполнить на исходном skeleton, `make test` — только после реализации API. Полная OpenAPI-валидация отдельно: `make validate` после установки `requirements-dev.txt` в venv.
HTTP проверки выполняются против запущенного Compose стенда; они не создают его автоматически. Клиенты Python используют стандартную библиотеку; сервер и unit tests требуют runtime зависимостей из `requirements.txt`. Полная OpenAPI-валидация отдельно: `make validate` после установки `requirements-dev.txt` в venv.
```sh
make check
make test BASE_URL=http://localhost:8080
# без make:
python3 tests/smoke.py --base-url http://localhost:8080
make test BASE_URL=https://localhost:8443 CA_FILE="$PWD/secrets/pki/ca.crt"
make test-security BASE_URL=https://localhost:8443 CA_FILE="$PWD/secrets/pki/ca.crt"
make test-primitives
make test-internal-mtls
make test-login-limit BASE_URL=https://localhost:8443 CA_FILE="$PWD/secrets/pki/ca.crt"
make test-openbao-acl PYTHON=.venv/bin/python
make test-worker-isolation
make test-worker-rotation PYTHON=.venv/bin/python ROOT_TOKEN_FILE=/secure/path/openbao-root-token
make test-leaf-rotation PYTHON=.venv/bin/python
make test-telemetry-redaction PYTHON=.venv/bin/python BASE_URL=https://localhost:8443 CA_FILE="$PWD/secrets/pki/ca.crt"
make test-argon-budget
.venv/bin/pip-audit -r requirements.txt
```
`smoke.py` выполняет **один сквозной сценарий**, автоматически выбирая профиль из `lab.json`: health → три пользователя → вход с lab2 → чат → сообщения → пагинация → ошибки доступа → идемпотентность с lab3 → файл с lab4 → thumbnail с lab5 → logout. Он проверяет JSON по используемому подмножеству схемы, коды/headers, Unicode, SHA-256 оригинала и фактические JPEG-размеры thumbnail. Это публичный минимум, не полный fuzz/security/load suite.
@@ -15,10 +24,9 @@ python3 tests/smoke.py --base-url http://localhost:8080
## Проверка сохранности, lab2+
Скопируйте `scripts/restart.example.sh` в `scripts/restart.sh`, реализуйте перезапуск **API и всех используемых хранилищ** с сохранением volumes и задайте executable bit. Скрипт может опираться на ваш compose.yaml или stack.yaml. Он не должен удалять volumes, повторно seed-ить БД или менять тестовые данные.
`scripts/restart.sh` перезапускает API и используемые stores, сохраняя volumes и тестовые данные.
```sh
chmod +x scripts/restart.sh
make test-persistence ACTION_SCRIPT=scripts/restart.sh
```
@@ -26,10 +34,9 @@ make test-persistence ACTION_SCRIPT=scripts/restart.sh
## Проверка отказа, lab3+
Реализуйте `scripts/stop-one.sh` на основе примера. `TARGET_INSTANCE_ID` в окружении содержит alias обслужившей тест API-реплики: сопоставьте его своему контейнеру/Swarm task и остановите именно его. Скрипт должен быстро вернуть 0 и **оставить эту реплику остановленной**; восстановление выполняйте отдельно. Swarm может создать новую task с другим ID — это допустимо.
`scripts/stop-one.sh` сопоставляет `TARGET_INSTANCE_ID` с hostname API container и останавливает только его. Скрипт оставляет реплику остановленной; восстановление выполняйте отдельно.
```sh
chmod +x scripts/stop-one.sh
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
```
@@ -50,8 +57,14 @@ make test BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt
make test-security BASE_URL=https://localhost:8443 CA_FILE=/absolute/path/to/ca.crt
```
Все скрипты принимают `--ca-file`/`CA_FILE` и проверяют серверный сертификат и hostname. `--insecure` отсутствует. TLS-тест сначала проверяет рабочее доверенное соединение, затем намеренно пустой trust store и именно ошибку проверки сертификата; network timeout не засчитывается как правильный отказ. **Внутреннее mTLS, identity/authorization, OpenBao policy и hardening проверяют отдельные тесты студента** по trust matrix. Клиентский сертификат внешнему учебному REST-клиенту не требуется: mTLS находится на внутренних связях.
Все скрипты принимают `--ca-file`/`CA_FILE` и проверяют серверный сертификат и hostname. `--insecure` отсутствует. TLS-тест сначала проверяет рабочее доверенное соединение, затем намеренно пустой trust store и именно ошибку проверки сертификата; network timeout не засчитывается как правильный отказ. `make test-internal-mtls` проверяет внутренний API listener из контейнера API: без клиентского сертификата, с недоверенной CA и с недопустимой URI SAN соединение отвергается, а LB identity проходит. `make test-login-limit` проверяет ответ 429 и Retry-After после серии неуспешных входов. Клиентский сертификат внешнему REST-клиенту не требуется: mTLS находится на связи LB→API.
## Что ещё остаётся доказать
`make test-openbao-acl` проверяет все сервисные AppRole: каждая identity читает собственный KV path и получает 403 на paths остальных identities; также проверяется ограниченный TTL токена. `make test-argon-budget` измеряет Argon2id verify latency, burst capacity и число одновременно занятых hash slots внутри API container с его CPU/RAM limits. Эти результаты характеризуют password hashing guard, а не end-to-end capacity стенда. `pip-audit -r requirements.txt` сканирует закреплённые Python runtime-зависимости по advisory database.
Smoke не доказывает persistence, число реальных контейнеров, durability брокера, outbox, отсутствие утечек/уязвимостей, полноту telemetry или выполнение уровня 4/5. Конкурентные/нагрузочные/негативные проверки своего решения добавляйте отдельно. Список защиты текущей лабы находится в README.md. Проверки рассчитаны на localhost-стенд, не на production.
`make test-worker-isolation` запускается внутри worker container: проверяет ограниченную PostgreSQL-роль, запрет чтения/перечисления защищённых S3 buckets, разрешённые staging/originals/variants операции и запрет публикации worker в RabbitMQ. Временные probe objects удаляются после теста.
`make test-worker-rotation ROOT_TOKEN_FILE=...` требует запущенный и распечатанный OpenBao и локальный путь к operator root-token file вне Git. Скрипт создаёт attachment при остановленном worker, выпускает новый SecretID, отзывает прежний, доказывает отказ старого credential, пересоздаёт только worker и проверяет `queued → ready`, checksum original и message link. Root token и SecretID не печатаются. Запуск создаёт синтетические записи и заменяет локальный worker SecretID.
`make test-leaf-rotation` выпускает и устанавливает новый LB client leaf с прежней URI SAN, пересоздаёт API и HAProxy без build, проверяет отказ старого сертификата, приём нового и неизменность Docker image IDs. `make test-telemetry-redaction` генерирует синтетические credentials и сообщение, затем сканирует API log entries в Loki и трассы Tempo на отсутствие этих значений.
Smoke и security-проверки рассчитаны на localhost Compose стенд, не на production. Нагрузочный benchmark, persistence hook и failover API выполняются отдельными командами выше; их машинные результаты записываются в `evidence/`.
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
import argparse
import json
import math
import resource
import statistics
from pathlib import Path
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from src import security
def percentile(values, fraction):
ordered = sorted(values)
return ordered[max(0, math.ceil(len(ordered) * fraction) - 1)]
def main():
parser = argparse.ArgumentParser(description="Measure Argon2id latency and bounded concurrency.")
parser.add_argument("--samples", type=int, default=20)
parser.add_argument("--concurrency", type=int, default=12)
args = parser.parse_args()
if args.samples < 1 or args.concurrency < 1:
parser.error("samples and concurrency must be positive")
encoded = security.hash_password("argon2-budget-synthetic-password")
durations = []
for _ in range(args.samples):
started = time.perf_counter()
if not security.verify_password("argon2-budget-synthetic-password", encoded):
raise RuntimeError("Argon2id self-verification failed")
durations.append(time.perf_counter() - started)
active = 0
peak_active = 0
lock = threading.Lock()
original_slots = security._PASSWORD_HASH_SLOTS
class TrackingSlots:
def acquire(self, timeout=None):
nonlocal active, peak_active
acquired = original_slots.acquire(timeout=timeout)
if acquired:
with lock:
active += 1
peak_active = max(peak_active, active)
return acquired
def release(self):
nonlocal active
with lock:
active -= 1
original_slots.release()
security._PASSWORD_HASH_SLOTS = TrackingSlots()
def verify_once(_):
try:
return security.verify_password("argon2-budget-synthetic-password", encoded)
except security.PasswordHashCapacityError:
return False
with ThreadPoolExecutor(max_workers=args.concurrency) as executor:
burst_results = list(executor.map(verify_once, range(args.concurrency)))
print(json.dumps({
"argon2_memory_kib": security._ARGON2_MEMORY_KIB,
"argon2_iterations": security._ARGON2_ITERATIONS,
"argon2_parallelism": security._ARGON2_PARALLELISM,
"hash_slots_per_process": security._PASSWORD_HASH_CONCURRENCY,
"hash_wait_seconds": security._PASSWORD_HASH_WAIT_SECONDS,
"sequential_samples": args.samples,
"verify_latency_ms": {
"p50": round(statistics.median(durations) * 1000, 3),
"p95": round(percentile(durations, 0.95) * 1000, 3),
"max": round(max(durations) * 1000, 3),
},
"burst_requests": args.concurrency,
"burst_successes": sum(burst_results),
"burst_capacity_rejections": args.concurrency - sum(burst_results),
"peak_active_hashes": peak_active,
"max_rss_platform_units": resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,
"platform": sys.platform,
}, sort_keys=True))
if __name__ == "__main__":
main()
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""Verify API listener client-certificate requirements from inside an API container."""
import ssl
import http.client
import urllib.error
import urllib.request
HOST = "https://127.0.0.1:8080/health/ready"
CA = "/run/secrets/ca_crt"
def context(client_cert=None, client_key=None):
result = ssl.create_default_context(cafile=CA)
if client_cert:
result.load_cert_chain(client_cert, client_key)
return result
def rejected(client_cert=None, client_key=None):
try:
with urllib.request.urlopen(HOST, context=context(client_cert, client_key), timeout=5) as response:
response.read(1024)
except (urllib.error.URLError, ssl.SSLError, http.client.HTTPException, OSError):
return
raise AssertionError("API accepted a request with an unauthorized client identity")
def main():
rejected()
rejected("/run/secrets/wrong_client_cert", "/run/secrets/wrong_client_key")
rejected("/run/secrets/foreign_client_cert", "/run/secrets/foreign_client_key")
with urllib.request.urlopen(
HOST,
context=context("/run/secrets/lb_tls_cert", "/run/secrets/lb_tls_key"),
timeout=5,
) as response:
if response.status != 200:
raise AssertionError(f"authorized LB identity returned HTTP {response.status}")
print("PASS: missing, foreign-CA and non-LB identities rejected; LB identity accepted.")
if __name__ == "__main__":
main()
+207
View File
@@ -0,0 +1,207 @@
#!/usr/bin/env python3
"""Rotate the LB client leaf, pin the replacement, and prove the prior leaf is rejected."""
import hashlib
import json
import os
from pathlib import Path
import ssl
import subprocess
import tempfile
import time
import urllib.request
ROOT = Path(__file__).resolve().parents[1]
PKI_DIR = ROOT / "secrets" / "pki"
CA_CERT = PKI_DIR / "ca.crt"
CA_KEY = PKI_DIR / "ca.key"
CERT_PATH = PKI_DIR / "lb-client.crt"
KEY_PATH = PKI_DIR / "lb-client.key"
BUNDLE_PATH = PKI_DIR / "lb-client.pem"
API_PROBE = """
import json, ssl, sys, tempfile, urllib.request, urllib.error
value = json.load(sys.stdin)
with tempfile.TemporaryDirectory() as directory:
cert = directory + "/client.crt"
key = directory + "/client.key"
open(cert, "w").write(value["cert"])
open(key, "w").write(value["key"])
context = ssl.create_default_context(cafile="/run/secrets/ca_crt")
context.load_cert_chain(cert, key)
try:
with urllib.request.urlopen("https://127.0.0.1:8080/health/ready", context=context, timeout=5) as response:
result = {"accepted": response.status == 200}
except (urllib.error.URLError, ssl.SSLError, OSError):
result = {"accepted": False}
print(json.dumps(result))
"""
def run(command, *, input_text=None):
return subprocess.run(
command,
cwd=ROOT,
input=input_text,
text=True,
check=True,
capture_output=True,
)
def compose(*args, input_text=None):
return run(["docker", "compose", *args], input_text=input_text)
def write_atomic(path: Path, content: bytes, mode: int) -> None:
temporary = path.with_suffix(path.suffix + ".rotation-tmp")
descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode)
with os.fdopen(descriptor, "wb") as output:
output.write(content)
os.chmod(temporary, mode)
os.replace(temporary, path)
def probe(cert: bytes, key: bytes) -> bool:
payload = json.dumps(
{
"cert": cert.decode("ascii"),
"key": key.decode("ascii"),
}
)
result = compose("exec", "-T", "api", "python3", "-c", API_PROBE, input_text=payload)
return json.loads(result.stdout)["accepted"]
def image_ids() -> set:
container_ids = compose("ps", "-q", "api").stdout.split()
if len(container_ids) != 2:
raise RuntimeError("expected exactly two running API replicas")
return {
run(["docker", "inspect", "--format", "{{.Image}}", container_id]).stdout.strip()
for container_id in container_ids
}
def wait_healthy(timeout: int = 90) -> None:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
containers = compose("ps", "-q", "api").stdout.split()
healthy = len(containers) == 2
for container_id in containers:
state = json.loads(
run(["docker", "inspect", "--format", "{{json .State.Health}}", container_id]).stdout
)
healthy = healthy and state.get("Status") == "healthy"
lb = compose("ps", "-q", "load_balancer").stdout.split()
healthy = healthy and len(lb) == 1
if healthy:
state = json.loads(
run(["docker", "inspect", "--format", "{{json .State.Health}}", lb[0]]).stdout
)
healthy = state.get("Status") == "healthy"
if healthy:
return
time.sleep(1)
raise RuntimeError("API and load balancer did not become healthy after certificate rotation")
def create_replacement(directory: Path) -> tuple[bytes, bytes, bytes]:
request_path = directory / "lb-client.csr"
cert_path = directory / "lb-client.crt"
key_path = directory / "lb-client.key"
extensions_path = directory / "lb-client.ext"
subprocess.run(
[
"openssl", "req", "-new", "-newkey", "rsa:2048", "-nodes",
"-keyout", str(key_path), "-out", str(request_path),
"-subj", "/CN=lab7-load-balancer",
],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
extensions_path.write_text(
"basicConstraints=critical,CA:FALSE\n"
"keyUsage=critical,digitalSignature,keyEncipherment\n"
"extendedKeyUsage=clientAuth\n"
"subjectAltName=URI:spiffe://mtusi2026lab7/load-balancer\n",
encoding="ascii",
)
subprocess.run(
[
"openssl", "x509", "-req", "-in", str(request_path),
"-CA", str(CA_CERT), "-CAkey", str(CA_KEY), "-CAcreateserial",
"-out", str(cert_path), "-days", "30", "-sha256",
"-extfile", str(extensions_path),
],
check=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
cert = cert_path.read_bytes()
key = key_path.read_bytes()
return cert, key, cert + key
def main() -> None:
if not CA_CERT.is_file() or not CA_KEY.is_file():
raise RuntimeError("local CA certificate and operator-held private key are required")
old_cert = CERT_PATH.read_bytes()
old_key = KEY_PATH.read_bytes()
old_bundle = BUNDLE_PATH.read_bytes()
before_images = image_ids()
if not probe(old_cert, old_key):
raise RuntimeError("current LB certificate was not accepted before rotation")
replaced = False
try:
with tempfile.TemporaryDirectory(prefix="lab7-lb-leaf-") as directory_name:
new_cert, new_key, new_bundle = create_replacement(Path(directory_name))
new_fingerprint = hashlib.sha256(ssl.PEM_cert_to_DER_cert(new_cert.decode("ascii"))).hexdigest()
write_atomic(CERT_PATH, new_cert, 0o644)
write_atomic(KEY_PATH, new_key, 0o600)
write_atomic(BUNDLE_PATH, new_bundle, 0o600)
replaced = True
compose("up", "-d", "--no-deps", "--force-recreate", "api", "load_balancer")
wait_healthy()
if probe(old_cert, old_key):
raise RuntimeError("previous LB certificate remains authorized after rotation")
if not probe(new_cert, new_key):
raise RuntimeError("replacement LB certificate was not accepted")
context = ssl.create_default_context(cafile=str(CA_CERT))
with urllib.request.urlopen(
"https://localhost:8443/health/ready",
context=context,
timeout=10,
) as response:
if response.status != 200:
raise RuntimeError("HTTPS ingress did not recover after leaf rotation")
after_images = image_ids()
if before_images != after_images:
raise RuntimeError("container image changed; expected rotation without rebuild")
print(
json.dumps(
{
"result": "PASS",
"old_leaf_rejected": True,
"new_leaf_accepted": True,
"https_ingress_healthy": True,
"images_unchanged": True,
"new_leaf_sha256": new_fingerprint,
},
sort_keys=True,
)
)
except Exception:
if replaced:
write_atomic(CERT_PATH, old_cert, 0o644)
write_atomic(KEY_PATH, old_key, 0o600)
write_atomic(BUNDLE_PATH, old_bundle, 0o600)
compose("up", "-d", "--no-deps", "--force-recreate", "api", "load_balancer")
raise
if __name__ == "__main__":
main()
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python3
import base64
import uuid
from client import Client, arguments, check, run
def main():
args = arguments("Verify the shared login rate limit")
client = Client(args.base_url, args.ca_file)
username = "limit_" + uuid.uuid4().hex[:16]
client.call(
"POST",
"/api/v1/users",
201,
body={"username": username, "display_name": "Rate limit test", "password": "Correct-Password-123"},
schema="User",
)
invalid = base64.b64encode((username + ":Wrong-Password-123").encode()).decode("ascii")
for _ in range(5):
client.call(
"POST",
"/api/v1/auth/sessions",
401,
headers={"Authorization": "Basic " + invalid},
)
result = client.call(
"POST",
"/api/v1/auth/sessions",
429,
headers={"Authorization": "Basic " + invalid},
)
check(result["json"]["error"]["code"] == "rate_limited", "expected rate_limited response")
check(int(result["headers"].get("Retry-After", "0")) > 0, "missing positive Retry-After")
print("PASS: sixth failed login in the window is rejected with 429 and Retry-After.")
if __name__ == "__main__":
run(main)
+95
View File
@@ -0,0 +1,95 @@
#!/usr/bin/env python3
import argparse
import json
import ssl
import urllib.error
import urllib.request
from pathlib import Path
SERVICES = ("api", "worker", "publisher", "migrate", "reconciler")
class BaoClient:
def __init__(self, address: str, ca_file: str):
self.address = address.rstrip("/")
self.context = ssl.create_default_context(cafile=ca_file)
def request(self, method: str, path: str, payload=None, token: str = ""):
body = json.dumps(payload).encode("utf-8") if payload is not None else None
headers = {"Content-Type": "application/json"}
if token:
headers["X-Vault-Token"] = token
request = urllib.request.Request(
self.address + "/v1/" + path,
data=body,
headers=headers,
method=method,
)
try:
with urllib.request.urlopen(request, context=self.context, timeout=5) as response:
return response.status, json.loads(response.read(1024 * 1024))
except urllib.error.HTTPError as error:
return error.code, {}
except (urllib.error.URLError, TimeoutError, OSError, ValueError) as error:
raise RuntimeError(f"OpenBao request failed ({type(error).__name__})") from None
def main() -> None:
parser = argparse.ArgumentParser(description="Check service AppRole path isolation.")
parser.add_argument("--address", default="https://localhost:8200")
parser.add_argument("--ca-file", required=True)
parser.add_argument("--credential-dir", default="secrets/openbao")
args = parser.parse_args()
credential_dir = Path(args.credential_dir)
client = BaoClient(args.address, args.ca_file)
for service in SERVICES:
role_id = (credential_dir / f"{service}_role_id").read_text(encoding="utf-8").strip()
secret_id = (credential_dir / f"{service}_secret_id").read_text(encoding="utf-8").strip()
status, response = client.request(
"POST",
"auth/approle/login",
{"role_id": role_id, "secret_id": secret_id},
)
token = response.get("auth", {}).get("client_token")
if status != 200 or not token:
raise RuntimeError(f"{service} AppRole authentication failed with HTTP {status}")
lease_duration = response.get("auth", {}).get("lease_duration")
if not isinstance(lease_duration, int) or not 1 <= lease_duration <= 3600:
raise RuntimeError(f"{service} AppRole returned an invalid token TTL")
own_status, _ = client.request(
"GET",
f"secret/data/messenger/{service}",
token=token,
)
if own_status != 200:
raise RuntimeError(f"{service} cannot read its own scoped KV path (HTTP {own_status})")
for other in SERVICES:
if other == service:
continue
denied_status, _ = client.request(
"GET",
f"secret/data/messenger/{other}",
token=token,
)
if denied_status != 403:
raise RuntimeError(
f"{service} AppRole accessed {other} KV path (HTTP {denied_status})"
)
lookup_status, lookup_response = client.request(
"GET",
"auth/token/lookup-self",
token=token,
)
token_data = lookup_response.get("data", {})
if lookup_status != 200 or not 1 <= token_data.get("ttl", 0) <= 3600:
raise RuntimeError(
f"{service} AppRole token TTL is not bounded (HTTP {lookup_status})"
)
print("PASS: each AppRole reads its own KV path and is denied all other service paths.")
if __name__ == "__main__":
main()
+1 -1
View File
@@ -36,7 +36,7 @@ def main():
script = Path(args.action_script).expanduser().resolve()
check(script.is_file() and os.access(script,os.X_OK),'action script must exist and be executable (chmod +x)')
check('.example.' not in script.name,'copy and implement the example hook first')
c = Client(args.base_url,args.ca_file,timeout=2)
c = Client(args.base_url,args.ca_file,timeout=15)
alice,bob,eve,chat = c.bootstrap()
sent = c.message(alice,chat,'Сохранить при отказе')
original = sent['json']
+116
View File
@@ -0,0 +1,116 @@
#!/usr/bin/env python3
"""Verify synthetic credentials and message bodies are absent from Loki logs and Tempo spans."""
import base64
import json
from pathlib import Path
import re
import subprocess
import time
import uuid
from client import Client, arguments, check, run
ROOT = Path(__file__).resolve().parents[1]
TELEMETRY_PROBE = r"""
import json, ssl, sys, time, urllib.parse, urllib.request
probe = json.load(sys.stdin)
context = ssl.create_default_context(cafile="/run/secrets/ca_crt")
def request(url):
with urllib.request.urlopen(url, context=context, timeout=8) as response:
return json.load(response)
log_query = '{service_name="messenger-api"}'
deadline = time.monotonic() + 30
trace_ids = []
log_entries = []
while time.monotonic() < deadline:
params = urllib.parse.urlencode({"query": log_query, "start": probe["start_ns"], "end": str(time.time_ns()), "limit": "1000"})
logs = request("https://loki:3100/loki/api/v1/query_range?" + params)
log_entries = [
{"labels": stream.get("stream", {}), "line": line}
for stream in logs.get("data", {}).get("result", [])
for _, line in stream.get("values", [])
]
search = urllib.parse.urlencode({"limit": "1000", "start": probe["start"], "end": str(int(time.time())), "tags": "service.name=messenger-api"})
found = request("https://tempo:3200/api/search?" + search)
trace_ids = [item["traceID"] for item in found.get("traces", []) if item.get("rootTraceName") == "POST /api/v1/chats/{chat_id}/messages"]
if trace_ids and log_entries:
break
time.sleep(1)
if not trace_ids:
raise RuntimeError("no API message trace appeared in Tempo within the deadline")
payloads = [json.dumps(log_entries, ensure_ascii=False)]
for trace_id in trace_ids:
payloads.append(json.dumps(request("https://tempo:3200/api/traces/" + trace_id), ensure_ascii=False))
leaked = [value for value in probe["values"] if any(value in payload for payload in payloads)]
print(json.dumps({"trace_count": len(trace_ids), "log_entries": len(log_entries), "leak_count": len(leaked)}))
"""
def main() -> None:
args = arguments("Verify request secrets and message bodies are excluded from telemetry")
client = Client(args.base_url, args.ca_file)
alice, bob, _, chat = client.bootstrap()
canary = "telemetry-canary-" + uuid.uuid4().hex
username = "u_probe_" + uuid.uuid4().hex[:12]
password = "Password-" + uuid.uuid4().hex
start_time = time.time()
user = client.call(
"POST",
"/api/v1/users",
201,
body={"username": username, "display_name": canary, "password": password},
schema="User",
)["json"]
auth_value = base64.b64encode(f"{username}:{password}".encode()).decode("ascii")
session = client.call(
"POST",
"/api/v1/auth/sessions",
201,
headers={"Authorization": "Basic " + auth_value},
schema="Session",
)["json"]
check(session["user"]["id"] == user["id"], "telemetry probe user session did not authenticate")
client.call(
"GET",
"/api/v1/users/me",
401,
headers={"Authorization": "Bearer " + canary},
)
client.message(alice, chat, canary)
values = [canary, username, password, auth_value, session["token"], alice["token"]]
probe = {
"values": values,
"start": str(max(0, int(start_time) - 5)),
"start_ns": str(max(0, int(start_time - 5) * 1_000_000_000)),
}
result = subprocess.run(
[
"docker", "compose", "exec", "-T", "api",
"python3", "-c", TELEMETRY_PROBE,
],
cwd=ROOT,
input=json.dumps(probe),
text=True,
capture_output=True,
check=True,
)
telemetry = json.loads(result.stdout)
check(telemetry["trace_count"] > 0, "no API traces were scanned")
check(telemetry["leak_count"] == 0, "synthetic credentials or message content appeared in telemetry")
print(
json.dumps(
{
"result": "PASS",
"synthetic_values_checked": len(values),
"api_traces_scanned": telemetry["trace_count"],
"log_entries_scanned": telemetry["log_entries"],
"leaks": 0,
},
sort_keys=True,
)
)
if __name__ == "__main__":
run(main)
+54
View File
@@ -0,0 +1,54 @@
import base64
import hashlib
import unittest
from unittest.mock import patch
from src.security import (
PasswordHashCapacityError,
allowed_client_identity,
hash_password,
password_hash_needs_upgrade,
verify_password,
)
class PasswordHashTests(unittest.TestCase):
def test_argon2id_verifies_unicode_password(self):
encoded = hash_password("корректный-password-123")
self.assertTrue(encoded.startswith("$argon2id$"))
self.assertIn("m=19456,t=2,p=1", encoded)
self.assertTrue(verify_password("корректный-password-123", encoded))
self.assertFalse(verify_password("другой-password-123", encoded))
self.assertFalse(password_hash_needs_upgrade(encoded))
oversized = "$argon2id$v=19$m=999999,t=2,p=1$c2FsdA$ZGlnaWVzdA"
self.assertFalse(verify_password("attacker-password-123", oversized))
def test_legacy_scrypt_hash_is_verified_and_marked_for_upgrade(self):
password = "legacy-password-123"
salt = b"lab6-test-salt!!"
digest = hashlib.scrypt(
password.encode(), salt=salt, n=32768, r=8, p=1, dklen=32, maxmem=64 * 1024 * 1024
)
stored = "scrypt$32768$8$1${}${}".format(
base64.urlsafe_b64encode(salt).decode(),
base64.urlsafe_b64encode(digest).decode(),
)
self.assertTrue(verify_password(password, stored))
self.assertTrue(password_hash_needs_upgrade(stored))
def test_only_lb_service_identity_is_authorized(self):
trusted = {"subjectAltName": [("URI", "spiffe://mtusi2026lab7/load-balancer")]}
other = {"subjectAltName": [("URI", "spiffe://mtusi2026lab7/other-service")]}
self.assertTrue(allowed_client_identity(trusted))
self.assertFalse(allowed_client_identity(other))
self.assertFalse(allowed_client_identity({}))
def test_password_hash_capacity_fails_fast(self):
with patch("src.security._PASSWORD_HASH_SLOTS") as slots:
slots.acquire.return_value = False
with self.assertRaises(PasswordHashCapacityError):
verify_password("password", "$argon2id$malformed")
if __name__ == "__main__":
unittest.main()
+168
View File
@@ -0,0 +1,168 @@
#!/usr/bin/env python3
"""Revoke the worker AppRole SecretID and recover a queued attachment with a replacement."""
import json
import os
from pathlib import Path
import ssl
import subprocess
import urllib.error
import urllib.request
from client import Client, arguments, check, run
ROOT = Path(__file__).resolve().parents[1]
SECRET_DIR = ROOT / "secrets" / "openbao"
class BaoClient:
def __init__(self, ca_file: str, root_token_file: str):
self.address = "https://localhost:8200"
self.context = ssl.create_default_context(cafile=ca_file)
self.root_token = Path(root_token_file).read_text(encoding="utf-8").strip()
check(bool(self.root_token), "operator root-token file is empty")
def request(self, method: str, path: str, payload=None, token=None):
body = json.dumps(payload).encode("utf-8") if payload is not None else None
headers = {"Content-Type": "application/json"}
if token is not None:
if token:
headers["X-Vault-Token"] = token
elif self.root_token:
headers["X-Vault-Token"] = self.root_token
request = urllib.request.Request(
self.address + "/v1/" + path,
data=body,
headers=headers,
method=method,
)
try:
with urllib.request.urlopen(request, context=self.context, timeout=8) as response:
data = response.read(1024 * 1024)
return response.status, json.loads(data) if data else {}
except urllib.error.HTTPError as error:
return error.code, {}
except (urllib.error.URLError, TimeoutError, OSError, ValueError) as error:
raise RuntimeError(f"OpenBao request failed ({type(error).__name__})") from None
def compose(*args) -> None:
subprocess.run(
["docker", "compose", *args],
cwd=ROOT,
check=True,
capture_output=True,
text=True,
)
def save_secret_id(value: str) -> None:
path = SECRET_DIR / "worker_secret_id"
temporary = path.with_suffix(".tmp")
descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(descriptor, "w", encoding="utf-8") as output:
output.write(value + "\n")
os.replace(temporary, path)
def rotate_worker_secret(bao: BaoClient) -> None:
role_id = (SECRET_DIR / "worker_role_id").read_text(encoding="utf-8").strip()
old_secret_id = (SECRET_DIR / "worker_secret_id").read_text(encoding="utf-8").strip()
check(bool(role_id) and bool(old_secret_id), "worker AppRole credential files are empty")
status, created = bao.request(
"POST",
"auth/approle/role/worker/secret-id",
{},
)
new_secret_id = created.get("data", {}).get("secret_id")
check(status == 200 and isinstance(new_secret_id, str), "OpenBao did not issue a replacement SecretID")
save_secret_id(new_secret_id)
status, login = bao.request(
"POST",
"auth/approle/login",
{"role_id": role_id, "secret_id": new_secret_id},
token="",
)
token = login.get("auth", {}).get("client_token")
check(status == 200 and isinstance(token, str), "replacement worker SecretID did not authenticate")
status, _ = bao.request(
"GET",
"secret/data/messenger/worker",
token=token,
)
check(status == 200, "replacement worker identity cannot read its own secret path")
status, _ = bao.request(
"POST",
"auth/approle/role/worker/secret-id/destroy",
{"secret_id": old_secret_id},
)
check(status == 204, "OpenBao did not revoke the previous worker SecretID")
status, _ = bao.request(
"POST",
"auth/approle/login",
{"role_id": role_id, "secret_id": old_secret_id},
token="",
)
check(status == 400, "revoked worker SecretID still authenticates")
def main() -> None:
def configure(parser):
parser.add_argument("--root-token-file", required=True)
args = arguments("Verify queued attachment recovery after worker SecretID rotation", configure)
ca_file = args.ca_file or str(ROOT / "secrets" / "pki" / "ca.crt")
client = Client(args.base_url, ca_file)
bao = BaoClient(ca_file, args.root_token_file)
alice, bob, _, chat = client.bootstrap()
worker_stopped = False
try:
compose("stop", "worker")
worker_stopped = True
attachment, original = client.attachment(alice, chat)
check(attachment["status"] == "queued", "upload was not queued while the worker was stopped")
message = client.message(alice, chat, "", attachments=[attachment["id"]])["json"]
check(message["attachment_ids"] == [attachment["id"]], "queued attachment was not linked to its message")
rotate_worker_secret(bao)
compose("up", "-d", "--no-deps", "--force-recreate", "worker")
worker_stopped = False
ready = client.wait_ready(bob, attachment)
original_bytes = client.call(
"GET",
f"/api/v1/attachments/{attachment['id']}/content",
actor=bob,
)["bytes"]
check(original_bytes == original, "rotated worker changed the original attachment bytes")
page = client.call(
"GET",
f"/api/v1/chats/{chat['id']}/messages",
actor=bob,
schema="MessagePage",
)["json"]
recovered = next(item for item in page["items"] if item["id"] == message["id"])
check(recovered["attachment_ids"] == [attachment["id"]], "message lost its attachment link")
print(
json.dumps(
{
"result": "PASS",
"old_worker_secret_id_revoked": True,
"replacement_worker_secret_id_authenticated": True,
"attachment_state": [attachment["status"], ready["status"]],
"original_sha256_preserved": True,
"message_attachment_link_preserved": True,
},
sort_keys=True,
)
)
finally:
if worker_stopped:
compose("up", "-d", "--no-deps", "--force-recreate", "worker")
if __name__ == "__main__":
run(main)
+132
View File
@@ -0,0 +1,132 @@
#!/usr/bin/env python3
"""Verify the worker identity is restricted to its required database, S3, and broker actions."""
import json
from pathlib import Path
import sys
import uuid
import pika
import psycopg
from botocore.exceptions import ClientError
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from src.jobs import connect
from src.object_store import ObjectStore
from src.store import database_url
def check_database() -> dict:
with psycopg.connect(database_url()) as connection:
with connection.cursor() as cursor:
cursor.execute("SELECT current_user")
role = cursor.fetchone()[0]
cursor.execute("SELECT id, status FROM attachments LIMIT 1")
cursor.fetchall()
try:
cursor.execute("SELECT id FROM users LIMIT 1")
except psycopg.errors.InsufficientPrivilege:
connection.rollback()
users_denied = True
else:
raise AssertionError("worker can read users")
if role != "messenger_worker":
raise AssertionError(f"unexpected worker database role: {role}")
return {"role": role, "attachments_read": True, "users_read_denied": users_denied}
def check_s3() -> dict:
client = ObjectStore().client
results = {}
for bucket in ("messenger-staging", "messenger-attachments", "messenger-variants"):
try:
client.list_objects_v2(Bucket=bucket, MaxKeys=1)
except ClientError as error:
code = error.response.get("Error", {}).get("Code")
if code not in ("AccessDenied", "403"):
raise
results[f"{bucket}_list_denied"] = True
else:
raise AssertionError(f"worker can list {bucket}")
for bucket, key in (
("messenger-attachments", f"original/{uuid.uuid4()}"),
("messenger-variants", f"variants/{uuid.uuid4()}"),
):
try:
client.get_object(Bucket=bucket, Key=key)
except ClientError as error:
code = error.response.get("Error", {}).get("Code")
if code not in ("AccessDenied", "403"):
raise
results[f"{bucket}_read_denied"] = True
else:
raise AssertionError(f"worker can read objects from {bucket}")
probe = str(uuid.uuid4())
allowed_objects = (
("messenger-staging", f"staging/isolation-probe/{probe}", True),
("messenger-attachments", f"original/isolation-probe/{probe}", False),
("messenger-variants", f"variants/isolation-probe/{probe}", False),
)
for bucket, key, verify_read in allowed_objects:
try:
client.put_object(Bucket=bucket, Key=key, Body=b"worker-scope-probe")
if verify_read:
response = client.get_object(Bucket=bucket, Key=key)
try:
if response["Body"].read() != b"worker-scope-probe":
raise AssertionError("worker staging read returned unexpected data")
finally:
response["Body"].close()
results[f"{bucket}_write"] = True
finally:
try:
client.delete_object(Bucket=bucket, Key=key)
except ClientError as error:
if error.response.get("Error", {}).get("Code") not in ("NoSuchKey", "404"):
raise
results["messenger-staging_read"] = True
results["temporary_objects_removed"] = True
return results
def check_broker() -> dict:
connection = connect()
channel = connection.channel()
try:
try:
channel.basic_publish(
exchange="",
routing_key="attachments.process.v1",
body=b"worker-isolation-probe",
)
channel.close()
except pika.exceptions.ChannelClosedByBroker as error:
if error.reply_code != 403:
raise
publish_denied = True
else:
publish_denied = False
if not publish_denied:
raise AssertionError("worker can publish to the processing queue")
return {"broker_identity_connected": True, "publish_denied": publish_denied}
finally:
if channel.is_open:
channel.close()
if connection.is_open:
connection.close()
def main() -> None:
result = {
"database": check_database(),
"s3": check_s3(),
"broker": check_broker(),
}
print(json.dumps({"result": "PASS", **result}, sort_keys=True))
if __name__ == "__main__":
main()