This commit is contained in:
+23
-10
@@ -1,19 +1,32 @@
|
||||
# Модель угроз — заполнить
|
||||
# Модель угроз
|
||||
|
||||
## Активы и акторы
|
||||
## Активы и границы
|
||||
|
||||
TODO: пользовательские credentials/сессии, сообщения/вложения, service identities, CA/secrets, telemetry. Акторы: участник чата, посторонний пользователь, внешний клиент, скомпрометированный сервис, оператор. Опишите доступ атакующего и границы учебного стенда.
|
||||
Активы стенда включают сообщения, вложения, пароли, сессии, очередь, ключи сервисов и телеметрию. PostgreSQL хранит пользователей и метаданные. MinIO хранит содержимое. Redis хранит сессии и очередь.
|
||||
|
||||
## Границы доверия
|
||||
Внешний клиент видит HTTPS на HAProxy. Участник чата может читать его данные и отправлять сообщения. Посторонний пользователь имеет действующую сессию и доступ к своим чатам. Worker обрабатывает задачи и имеет доступ к обработке вложений. Оператор контролирует Docker, CA, OpenBao и bootstrap.
|
||||
|
||||
TODO: схема и ссылка на заполненную contracts/trust-matrix.md; публичные/внутренние интерфейсы, процессы, секреты и их выдача.
|
||||
Прямой доступ к Docker и к файлам оператора даёт полный контроль над стендом. Эксперимент ограничивает доступ копией сертификата worker и его рабочими правами. [Матрица доверия](../contracts/trust-matrix.md)
|
||||
|
||||
| Угроза и конкретный путь | Нарушаемый инвариант | Контроль | Отрицательный тест | Остаточное ограничение |
|
||||
## Угрозы и проверки
|
||||
|
||||
| Угроза | Инвариант | Контроль | Проверка | Остаточный риск |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO | TODO |
|
||||
| Клиент соединяется с подменой ingress | Клиент получает сертификат своего стенда | Проверка цепочки CA и SAN | `make test-security`, `audit matrix` | Ключ CA контролирует оператор. |
|
||||
| Сервис с сертификатом того же CA открывает API напрямую | API принимает только HAProxy | mTLS и URI SAN `gateway` | `audit matrix` с `outsider` и `worker` | Ключ HAProxy даёт доступ к сетевому слою API. Bearer по-прежнему нужен. |
|
||||
| Посторонний подставляет ID владельца или чужое вложение | Доступ определяет членство в чате | Bearer, проверка членства и принадлежности вложения | `make test`, `http_checks.py authorization` | Действующий украденный Bearer несёт права владельца. |
|
||||
| Клиент перебирает пароль через обе реплики | Дорогая проверка пароля ограничена | Общий лимит Redis, Argon2id, 4 вычисления на реплику | `http_checks.py rate`, `BenchmarkVerify` | Общий лимит может временно ограничить честные входы. |
|
||||
| Пользователь посылает слишком большой файл | Приложение ограничивает тело и обработку | 10 MiB в HAProxy/API, лимит пикселей, таймаут worker | `http_checks.py authorization`, публичный smoke | Поддерживаемые изображения требуют процессорного времени. |
|
||||
| Украденная роль worker читает сообщения или сессии | Права worker ограничены обработкой | Права на поля PostgreSQL, ACL Redis и префиксы S3 | `worker_experiment.py` | Worker по-прежнему может повредить обработку и объекты в `original/`. |
|
||||
| Посторонний сервис пишет сигналы или читает телеметрию | У каждой роли свои маршруты | mTLS, проверка URI SAN, роли HTTP-прокси | `audit matrix` | Скомпрометированный API может писать ложную телеметрию. |
|
||||
| Строка входа или Bearer попадают в telemetry | Диагностика не раскрывает учётные данные | Схема логов и меток без заголовков, тел и SQL-аргументов | `http_checks.py telemetry` | Проверка покрывает синтетические запросы. |
|
||||
| Worker читает секрет API или меняет политику | Роль читает один путь, токен быстро истекает | Cert auth и KV policy OpenBao | `audit bao-expiry` | Скопированный вне OpenBao пароль действует до ротации. |
|
||||
| Старый worker продолжает подключаться после отзыва | Новый сеанс требует актуальной identity и пароль | Отзыв serial, замена привязки OpenBao, Redis ACL и разрыв сеансов | `audit rotation` | Ротация Redis не заменяет отзыв паролей PostgreSQL и S3. |
|
||||
|
||||
На 4 минимум 6 конкретных угроз. Не заменяйте сценарии словами «SQL injection», «безопасный Docker», «mTLS включён» без пути и проверки.
|
||||
## Жизненный цикл
|
||||
|
||||
## Lifecycle и инциденты
|
||||
Оператор создаёт CA и ключи локально. OpenBao использует постоянный том и Shamir 2 из 3. Оператор хранит корневой токен и доли отдельно от контейнеров. Сервисы входят с сертификатом и отзывают токен после чтения.
|
||||
|
||||
TODO: bootstrap, expiry/renewal, revoke/rotation, компрометация identity, sealed OpenBao и восстановление. Указать владельца CA/unseal и способ защиты bootstrap credentials. Сопоставить scan findings с реальной применимостью и исправлением/остаточным риском.
|
||||
Ротация worker останавливает обработчик, отзывает старый сертификат и заменяет пароль Redis. API продолжает принимать вложения. После запуска worker забирает очередь и обрабатывает задачи. Если OpenBao запечатан дольше окна доступа, сервис выходит и ожидает доступности при перезапуске.
|
||||
|
||||
Применимость уязвимостей и результаты сканирования описаны отдельно. [Разбор сканирования](../evidence/scan-triage.md)
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Authorization and TLS checks invoked by the operator in an isolated test container."""
|
||||
|
||||
from http.client import HTTPSConnection
|
||||
import json
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import ssl
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
|
||||
CA = "/trust/ca.crt"
|
||||
STREAM = "attachments:jobs:v1"
|
||||
|
||||
|
||||
def check(condition, description):
|
||||
if not condition:
|
||||
raise AssertionError(description)
|
||||
|
||||
|
||||
def context(role=None):
|
||||
ctx = ssl.create_default_context(cafile=CA)
|
||||
ctx.maximum_version = ssl.TLSVersion.TLSv1_2 # TLS alerts are observable before sending HTTP bodies.
|
||||
if role == "gateway":
|
||||
ctx.load_cert_chain("/identities/gateway/client.pem")
|
||||
elif role:
|
||||
identity = Path("/retired" if role == "retired" else f"/identities/{role}")
|
||||
ctx.load_cert_chain(identity / "tls.crt", identity / "tls.key")
|
||||
return ctx
|
||||
|
||||
|
||||
def connect(host, port, role, ip=None, name=None):
|
||||
sock = socket.create_connection((ip or host, port), timeout=4)
|
||||
try:
|
||||
return context(role).wrap_socket(sock, server_hostname=name or host)
|
||||
except BaseException:
|
||||
sock.close()
|
||||
raise
|
||||
|
||||
|
||||
def http(host, port, role, path, method="GET", data=None, headers=None, ip=None, name=None):
|
||||
client = HTTPSConnection(host, port, timeout=4)
|
||||
with connect(host, port, role, ip, name) as tls:
|
||||
client.sock = tls
|
||||
client.request(method, path, body=data, headers=headers or {})
|
||||
result = client.getresponse()
|
||||
return result.status, result.read()
|
||||
|
||||
|
||||
def post(host, port, role, path, data=None, token=None):
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
return http(host, port, role, path, "POST", json.dumps(data or {}), headers)
|
||||
|
||||
|
||||
def redis(role, port, user, password, commands):
|
||||
def command(sock, inp, *args):
|
||||
data = [str(arg).encode() for arg in args]
|
||||
sock.sendall(b"*%d\r\n" % len(data) + b"".join(b"$%d\r\n%s\r\n" % (len(x), x) for x in data))
|
||||
return inp.readline()
|
||||
|
||||
with connect("redis", port, role) as tls, tls.makefile("rb") as inp:
|
||||
if user:
|
||||
auth = command(tls, inp, "AUTH", user, password)
|
||||
if auth != b"+OK\r\n":
|
||||
return [auth]
|
||||
return [command(tls, inp, *item) for item in commands]
|
||||
|
||||
|
||||
def secret(role):
|
||||
return Path(f"/bootstrap/{role}/REDIS_PASSWORD").read_text()
|
||||
|
||||
|
||||
def rejected(name, probe):
|
||||
try:
|
||||
probe()
|
||||
except ssl.SSLCertVerificationError:
|
||||
raise AssertionError(f"{name}: client received invalid server cert")
|
||||
except ssl.SSLError as error:
|
||||
check("ALERT" in (error.reason or ""), f"{name}: unexpected TLS error {error.reason}")
|
||||
print(f"PASS {name}: {error.reason}")
|
||||
return
|
||||
raise AssertionError(f"{name}: expected TLS alert")
|
||||
|
||||
|
||||
def log_export():
|
||||
def field(number, raw):
|
||||
return bytes((number * 8 + 2, len(raw))) + raw
|
||||
metadata = field(1, b"service.name") + field(2, field(1, b"lab7-tls-audit"))
|
||||
resource = field(1, metadata)
|
||||
record = b"\x09" + struct.pack("<Q", time.time_ns()) + field(5, field(1, b"synthetic TLS audit"))
|
||||
return field(1, field(1, resource) + field(2, field(2, record)))
|
||||
|
||||
|
||||
def check_matrix():
|
||||
replicas = sorted({a[4][0] for a in socket.getaddrinfo("api", 8080, family=socket.AF_INET)})
|
||||
check(len(replicas) == 2, "two active API replicas required")
|
||||
for index, ip in enumerate(replicas, 1):
|
||||
def api(role):
|
||||
return http("api", 8080, role, "/health/ready", ip=ip)
|
||||
check(api("gateway")[0] == 200, "gateway identity")
|
||||
for role in (None, "foreign", "outsider", "worker"):
|
||||
rejected(f"API {index} {role}", lambda: api(role))
|
||||
print(f"PASS API {index}: gateway verified")
|
||||
|
||||
for role, port in (("api", 6380), ("worker", 6381)):
|
||||
def broker(identity):
|
||||
return redis(identity, port, role, secret(role), [("PING",)])
|
||||
check(broker(role) == [b"+PONG\r\n"], "broker valid identity")
|
||||
for invalid in (None, "foreign", "outsider", "worker" if role == "api" else "api"):
|
||||
rejected(f"broker {port} {invalid}", lambda: broker(invalid))
|
||||
|
||||
for role in ("api", "worker", None, "foreign", "outsider"):
|
||||
def ingest():
|
||||
return post("collector", 44318, role, "/v1/traces")
|
||||
if role in ("api", "worker"):
|
||||
check(ingest()[0] == 200, "collector valid identity")
|
||||
else:
|
||||
rejected(f"collector {role}", ingest)
|
||||
|
||||
endpoints = [
|
||||
("collector", 48888, "prometheus", "/metrics"),
|
||||
("collector", 48889, "prometheus", "/metrics"),
|
||||
("loki", 43102, "prometheus", "/metrics"),
|
||||
("tempo", 43201, "prometheus", "/metrics"),
|
||||
("prometheus", 49090, "grafana", "/api/v1/query?query=up"),
|
||||
("loki", 43101, "grafana", "/loki/api/v1/labels"),
|
||||
("tempo", 43200, "grafana", "/api/search"),
|
||||
]
|
||||
for host, port, identity, path in endpoints:
|
||||
def query(role):
|
||||
return http(host, port, role, path)
|
||||
check(query(identity)[0] == 200, f"TLS {host}:{port} route")
|
||||
rejected(f"{host}:{port} worker", lambda: query("worker"))
|
||||
print(f"PASS {host}:{port} {identity}")
|
||||
for host, port, route in (("loki", 43100, "/otlp/v1/logs"), ("tempo", 44318, "/v1/traces")):
|
||||
status, _ = http(host, port, "collector", route, "POST", log_export() if host == "loki" else b"",
|
||||
{"Content-Type": "application/x-protobuf"})
|
||||
check(status in (200, 204), f"collector export {host}: HTTP {status}")
|
||||
rejected(f"{host} ingest wrong identity", lambda: post(host, port, "grafana", route))
|
||||
check(post("loki", 43101, "grafana", "/loki/api/v1/push")[0] == 403, "Grafana cannot push logs")
|
||||
check(post("prometheus", 49090, "grafana", "/api/v1/write")[0] == 403, "Grafana cannot write metrics")
|
||||
check(http("minio", 9000, None, "/minio/health/live")[0] == 200, "MinIO HTTPS")
|
||||
check(http("minio", 9000, None, "/attachments")[0] == 403, "S3 anonymous denied")
|
||||
check(http("grafana", 3000, None, "/api/user")[0] == 401, "Grafana requires user auth")
|
||||
try:
|
||||
http("gateway", 8443, None, "/health/live", name="missing-name.lab")
|
||||
except ssl.SSLCertVerificationError:
|
||||
print("PASS ingress hostname verification")
|
||||
else:
|
||||
raise AssertionError("ingress accepted mismatched SAN")
|
||||
|
||||
for host, port in (("redis", 6379), ("collector", 4318), ("loki", 3100),
|
||||
("tempo", 4318), ("tempo", 3200), ("prometheus", 9090)):
|
||||
try:
|
||||
with socket.create_connection((host, port), timeout=2):
|
||||
raise AssertionError(f"{host}:{port} loopback service accessible from network")
|
||||
except ConnectionRefusedError:
|
||||
print(f"PASS {host}:{port} local hop closed")
|
||||
|
||||
|
||||
def bao_scope(expiry=False):
|
||||
for role, other in (("worker", "api"), ("api", "worker")):
|
||||
status, data = post("openbao", 8200, role, "/v1/auth/cert/login")
|
||||
check(status == 200, f"{role} cert login")
|
||||
auth = json.loads(data)["auth"]
|
||||
token, ttl = auth["client_token"], auth["lease_duration"]
|
||||
check(0 < ttl <= 30 and auth["policies"] == [role], "scoped short TTL")
|
||||
headers = {"X-Vault-Token": token}
|
||||
def read(path):
|
||||
return http("openbao", 8200, role, "/v1/lab/data/" + path, headers=headers)[0]
|
||||
check(read(role) == 200 and read(other) == 403, "role KV scoping")
|
||||
check(post("openbao", 8200, role, "/v1/sys/policies/acl/canary", token=token)[0] == 403,
|
||||
"role policy write denied")
|
||||
if expiry and role == "worker":
|
||||
time.sleep(ttl + 2)
|
||||
check(read(role) == 403, "working token is denied after expiry")
|
||||
print(f"PASS OpenBao token expiry ({ttl}s)")
|
||||
else:
|
||||
check(post("openbao", 8200, role, "/v1/auth/token/revoke-self", token=token)[0] == 204,
|
||||
"self-revocation")
|
||||
check(read(role) == 403, "revoked token")
|
||||
print(f"PASS OpenBao {role} own KV allowed, peer KV and policy write denied")
|
||||
check(post("openbao", 8200, "outsider", "/v1/auth/cert/login")[0] in (400, 403), "unregistered leaf denied")
|
||||
|
||||
|
||||
def worker_scope():
|
||||
def worker(*ops):
|
||||
return redis("worker", 6381, "worker", secret("worker"), ops)[0]
|
||||
allow = worker(("XREADGROUP", "GROUP", "image-workers-v1", "scope-audit", "COUNT", 1,
|
||||
"STREAMS", STREAM, "0"))
|
||||
check(allow.startswith(b"*"), "consume existing stream authorized")
|
||||
for operation in (("GET", "session:synthetic"), ("XADD", STREAM, "*", "job", "synthetic"),
|
||||
("XREADGROUP", "GROUP", "image-workers-v1", "scope-audit",
|
||||
"STREAMS", "unrelated:stream", "0"), ("FLUSHALL",)):
|
||||
check(worker(operation).startswith(b"-NOPERM"), f"deny {operation[0]} outside worker scope")
|
||||
print("PASS worker can consume queue; publish, foreign queue, sessions and FLUSHALL denied")
|
||||
|
||||
|
||||
def reload_redis():
|
||||
result = redis("operator", 6382, "operator", secret("operator"),
|
||||
[("ACL", "LOAD"), ("CLIENT", "KILL", "USER", "worker")])
|
||||
check(result[0] == b"+OK\r\n" and result[1].startswith(b":"), "reload and disconnect worker")
|
||||
|
||||
|
||||
def audit_rotation():
|
||||
old = Path("/retired/REDIS_PASSWORD").read_text()
|
||||
def connect_redis(cert, password):
|
||||
return redis(cert, 6381, "worker", password, [("PING",)])
|
||||
rejected("retired worker / broker", lambda: connect_redis("retired", old))
|
||||
rejected("retired worker / Collector",
|
||||
lambda: post("collector", 44318, "retired", "/v1/traces"))
|
||||
check(post("openbao", 8200, "retired", "/v1/auth/cert/login")[0] in (400, 403),
|
||||
"retired worker identity denied by Bao")
|
||||
check(connect_redis("worker", old)[0].startswith(b"-WRONGPASS"), "old password cannot use new identity")
|
||||
check(connect_redis("worker", secret("worker")) == [b"+PONG\r\n"], "new identity and secret valid")
|
||||
print("PASS renewed leaf, retired identity denied on three channels, old password rejected")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
actions = {"matrix": check_matrix, "bao": bao_scope, "bao-expiry": lambda: bao_scope(True),
|
||||
"worker": worker_scope, "redis-reload": reload_redis, "rotation": audit_rotation}
|
||||
actions[sys.argv[1]]()
|
||||
@@ -0,0 +1,33 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
export PGCONNECT_TIMEOUT=4
|
||||
export PGPASSWORD="$(cat /bootstrap/worker/POSTGRES_PASSWORD)"
|
||||
worker() { psql -XAtq -v ON_ERROR_STOP=1 -h postgres -U messenger_worker -d messenger -c "$1"; }
|
||||
deny() {
|
||||
if error=$(worker "$1" 2>&1); then
|
||||
printf '%s\n' 'Worker operation unexpectedly permitted' >&2
|
||||
exit 1
|
||||
fi
|
||||
case "$error" in *"permission denied"*) ;; *) printf '%s\n' 'Unexpected PostgreSQL failure' >&2; exit 1;; esac
|
||||
}
|
||||
[ "$(worker 'SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()')" = t ]
|
||||
[ "$(worker "SELECT has_column_privilege(current_user,'attachments','status','UPDATE')")" = t ]
|
||||
worker 'SELECT state FROM attachment_jobs LIMIT 1' >/dev/null
|
||||
deny 'SELECT password_hash FROM users LIMIT 0'
|
||||
deny 'SELECT text FROM messages LIMIT 0'
|
||||
deny 'SELECT chat_id FROM attachments LIMIT 0'
|
||||
deny "UPDATE attachments SET chat_id=chat_id WHERE false"
|
||||
deny 'DELETE FROM attachment_jobs WHERE false'
|
||||
deny 'CREATE TABLE public.audit_canary(id int)'
|
||||
if result=$(PGSSLMODE=disable worker 'SELECT 1' 2>&1); then
|
||||
exit 1
|
||||
fi
|
||||
case "$result" in *"no encryption"*) ;; *) exit 1;; esac
|
||||
printf '%s\n' 'PASS PostgreSQL verified TLS; job read/processing update granted, business data/delete/DDL/plaintext denied.'
|
||||
if [ "${1:-}" = rotated ]; then
|
||||
if result=$(PGPASSWORD="$(cat /retired/POSTGRES_PASSWORD)" worker 'SELECT 1' 2>&1); then
|
||||
exit 1
|
||||
fi
|
||||
case "$result" in *"password authentication failed"*) ;; *) exit 1;; esac
|
||||
printf '%s\n' 'PASS PostgreSQL rejects the retired worker password.'
|
||||
fi
|
||||
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check effective runtime settings without printing environment variables or mounts."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
compose = ROOT / "scripts/compose.sh"
|
||||
services = subprocess.check_output([str(compose), "config", "--services"], cwd=ROOT, text=True).split()
|
||||
ids = subprocess.check_output([str(compose), "ps", "-q", *services], cwd=ROOT, text=True).split()
|
||||
assert len(ids) == len(services) + 1, "expected full stack with two API replicas"
|
||||
template = ('{"name":{{json .Name}},"user":{{json .Config.User}},'
|
||||
'"network_mode":{{json .HostConfig.NetworkMode}},"privileged":{{json .HostConfig.Privileged}},'
|
||||
'"readonly":{{json .HostConfig.ReadonlyRootfs}},"security":{{json .HostConfig.SecurityOpt}},'
|
||||
'"drop":{{json .HostConfig.CapDrop}},"memory":{{json .HostConfig.Memory}},'
|
||||
'"cpus":{{json .HostConfig.NanoCpus}},"tmpfs":{{json .HostConfig.Tmpfs}},'
|
||||
'"ports":{{json .HostConfig.PortBindings}},"mounts":{{json .Mounts}}}')
|
||||
for row in subprocess.check_output(["docker", "inspect", "--format", template, *ids], text=True).splitlines():
|
||||
container = json.loads(row)
|
||||
assert not container["privileged"] and container["network_mode"] != "host"
|
||||
assert container["memory"] > 0 and container["cpus"] > 0
|
||||
assert container["readonly"] and "/tmp" in container["tmpfs"] and "ALL" in container["drop"]
|
||||
assert any(item.startswith("no-new-privileges") for item in container["security"])
|
||||
assert all("docker.sock" not in mount["Source"] and "docker.sock" not in mount["Destination"]
|
||||
for mount in container["mounts"])
|
||||
name = container["name"]
|
||||
ports = container["ports"] or {}
|
||||
known = {"gateway": ("8443/tcp", None), "openbao": ("8200/tcp", "18200"),
|
||||
"grafana": ("3000/tcp", "13000")}
|
||||
for service, (container_port, host_port) in known.items():
|
||||
if name.endswith(f"-{service}-1"):
|
||||
assert set(ports) == {container_port}
|
||||
assert all(binding["HostIp"] == "127.0.0.1" and
|
||||
(host_port is None or binding["HostPort"] == host_port) for binding in ports[container_port])
|
||||
break
|
||||
else:
|
||||
assert not ports
|
||||
if "-api-" in name or "-worker-" in name:
|
||||
assert container["user"] == "messenger:messenger"
|
||||
destinations = {mount["Destination"] for mount in container["mounts"]}
|
||||
assert destinations == {"/trust", "/identity"}
|
||||
print(json.dumps({k: container[k] for k in ("name", "user", "memory", "cpus", "readonly", "ports")}))
|
||||
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Public authorization, rate limit, expiry and telemetry checks using HTTPS."""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
from http.client import HTTPSConnection
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import ssl
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, check, timestamp
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
return "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
|
||||
|
||||
def authorization(client, cafile):
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
attachment, _ = client.attachment(alice, chat)
|
||||
client.wait_ready(alice, attachment)
|
||||
other = client.call("POST", "/api/v1/chats", 201, actor=eve,
|
||||
body={"title": "ACL isolation", "member_ids": [eve["id"], bob["id"]]},
|
||||
schema="Chat")["json"]
|
||||
path = "/api/v1/chats/" + other["id"] + "/messages"
|
||||
client.call("POST", path, 404, body={"text": "", "attachment_ids": [attachment["id"]]},
|
||||
actor=eve, headers={"Idempotency-Key": secrets.token_hex(8)})
|
||||
client.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", 404, actor=eve,
|
||||
headers={"X-User-Id": alice["id"]})
|
||||
upload = "/api/v1/chats/" + chat["id"] + "/attachments?filename=test.png"
|
||||
parsed = urllib.parse.urlsplit(client.base)
|
||||
connection = HTTPSConnection(parsed.hostname, parsed.port, context=ssl.create_default_context(cafile=cafile),
|
||||
timeout=4)
|
||||
connection.putrequest("POST", upload)
|
||||
connection.putheader("Authorization", "Bearer " + alice["token"])
|
||||
connection.putheader("Content-Type", "image/png")
|
||||
connection.putheader("Content-Length", str(10 * 1024 * 1024 + 1))
|
||||
connection.putheader("Expect", "100-continue")
|
||||
connection.endheaders()
|
||||
with connection.getresponse() as response:
|
||||
check(response.status == 413, "ingress accepted oversized body")
|
||||
details = json.loads(response.read())["error"]
|
||||
check(details["request_id"] == response.getheader("X-Request-Id"), "ingress mismatch request ID")
|
||||
connection.close()
|
||||
print("PASS cross-chat attachment, spoofed identity and oversized upload denied")
|
||||
|
||||
|
||||
def rate_limit(client):
|
||||
username = "canary_" + secrets.token_hex(8)
|
||||
auth = {"Authorization": basic(username, "synthetic-wrong-password")}
|
||||
instances = set()
|
||||
latencies = []
|
||||
for index in range(10):
|
||||
result = client.call("POST", "/api/v1/auth/sessions", 401 if index < 8 else 429, headers=auth)
|
||||
instances.add(result["headers"]["X-Instance-Id"])
|
||||
if index < 8:
|
||||
latencies.append(round(result["elapsed"] * 1000, 1))
|
||||
else:
|
||||
check(0 < int(result["headers"]["Retry-After"]) <= 30, "Retry-After outside window")
|
||||
check(len(instances) >= 2, "test must traverse two API replicas")
|
||||
print(json.dumps({"limit_scope": "shared between replicas", "replicas": len(instances),
|
||||
"account_window": 30, "kdf_http_ms": latencies, "allowed": 8, "http_429": 2}))
|
||||
|
||||
|
||||
def expiry(client):
|
||||
actor = client.user("expiry")
|
||||
reg = actor["registration"]
|
||||
result = client.call("POST", "/api/v1/auth/sessions", 201, schema="Session",
|
||||
headers={"Authorization": basic(reg["username"], reg["password"])})["json"]
|
||||
delay = timestamp(result["expires_at"]).timestamp() - time.time()
|
||||
check(0 < delay <= 15, "launch API with SESSION_TTL_SECONDS=8 for this check")
|
||||
actor["token"] = result["token"]
|
||||
client.call("GET", "/api/v1/users/me", actor=actor)
|
||||
time.sleep(delay + 0.3)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
print("PASS session expiry enforced with a previously valid token")
|
||||
|
||||
|
||||
def telemetry(client, cafile):
|
||||
actor = client.user("telemetry")
|
||||
password, username = actor["registration"]["password"], actor["registration"]["username"]
|
||||
basic_header = basic(username, password)
|
||||
login = client.call("POST", "/api/v1/auth/sessions", 201, headers={"Authorization": basic_header},
|
||||
schema="Session")
|
||||
trace_id = login["headers"]["X-Trace-Id"]
|
||||
request_id = login["headers"]["X-Request-Id"]
|
||||
actor["token"] = login["json"]["token"]
|
||||
me = client.call("GET", "/api/v1/users/me", actor=actor)
|
||||
markers = tuple(item.encode() for item in (password, username, basic_header, actor["token"]))
|
||||
ca = ssl.create_default_context(cafile=cafile)
|
||||
admin_password = (ROOT / ".runtime/bootstrap/grafana/GRAFANA_PASSWORD").read_text()
|
||||
|
||||
def via_grafana(source, path):
|
||||
target = f"https://localhost:13000/api/datasources/proxy/uid/{source}{path}"
|
||||
request = urllib.request.Request(target, headers={"Authorization": basic("admin", admin_password)})
|
||||
with urllib.request.urlopen(request, timeout=4, context=ca) as response:
|
||||
return response.read()
|
||||
|
||||
deadline = time.monotonic() + 45
|
||||
while True:
|
||||
try:
|
||||
traces = [via_grafana("tempo", "/api/traces/" + tid)
|
||||
for tid in (trace_id, me["headers"]["X-Trace-Id"])]
|
||||
query = urllib.parse.urlencode({"query": '{service_name="messenger-api"} |= "' + request_id + '"',
|
||||
"start": time.time_ns() - 120_000_000_000})
|
||||
logs = via_grafana("loki", "/loki/api/v1/query_range?" + query)
|
||||
if request_id.encode() in logs:
|
||||
break
|
||||
except OSError:
|
||||
pass
|
||||
check(time.monotonic() < deadline, "trace or correlated logs missing from Grafana query")
|
||||
time.sleep(1)
|
||||
query = urllib.parse.urlencode({"query": 'messenger_http_requests_total{route="/api/v1/auth/sessions"}'})
|
||||
metrics = via_grafana("prometheus", "/api/v1/query?" + query)
|
||||
check(bool(json.loads(metrics)["data"]["result"]), "login metric missing")
|
||||
check(all(value not in doc for value in markers for doc in [*traces, logs, metrics]),
|
||||
"secret canary found in telemetry")
|
||||
print("PASS correlated login logs, traces and metrics present; no credential canaries")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
p = argparse.ArgumentParser(description=__doc__)
|
||||
p.add_argument("check", choices=("authorization", "rate", "expiry", "telemetry"))
|
||||
p.add_argument("--base-url", default="https://localhost:8443")
|
||||
p.add_argument("--ca-file", default=str(ROOT / ".runtime/trust/ca.crt"))
|
||||
options = p.parse_args()
|
||||
client = Client(options.base_url, options.ca_file)
|
||||
if options.check == "telemetry":
|
||||
telemetry(client, options.ca_file)
|
||||
elif options.check == "authorization":
|
||||
authorization(client, options.ca_file)
|
||||
else:
|
||||
{"rate": rate_limit, "expiry": expiry}[options.check](client)
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
export MC_CONFIG_DIR=/tmp/mc
|
||||
mkdir -p "$MC_CONFIG_DIR/certs/CAs"
|
||||
cp /trust/ca.crt "$MC_CONFIG_DIR/certs/CAs/lab.crt"
|
||||
for role in admin api worker; do
|
||||
mc alias set "$role" https://minio:9000 "$(cat "/bootstrap/$role/S3_ACCESS_KEY")" \
|
||||
"$(cat "/bootstrap/$role/S3_SECRET_KEY")" --api S3v4 >/dev/null
|
||||
done
|
||||
suffix="lab7-audit-$(date +%s)-$$"
|
||||
stage="staging/$suffix"
|
||||
original="original/$suffix"
|
||||
foreign="restricted/$suffix"
|
||||
trap 'mc rm "admin/attachments/$stage" "admin/attachments/$original" "admin/attachments/$foreign" >/dev/null 2>&1 || true' EXIT
|
||||
put() { printf '%s' 'synthetic test fixture' | mc pipe "$1" >/dev/null; }
|
||||
deny() {
|
||||
if error=$("$@" 2>&1); then
|
||||
printf '%s\n' 'Worker operation unexpectedly permitted' >&2
|
||||
exit 1
|
||||
fi
|
||||
case "$error" in *"Access Denied"*|*"Access denied"*|*"not have sufficient permissions"*|*"Insufficient permissions"*|*"Access to the resource is denied"*) ;;
|
||||
*) printf 'Unexpected S3 denial for %s %s\n' "$1" "$2" >&2; exit 1;;
|
||||
esac
|
||||
}
|
||||
put "api/attachments/$stage"
|
||||
put "admin/attachments/$foreign"
|
||||
[ "$(mc cat "worker/attachments/$stage")" = 'synthetic test fixture' ]
|
||||
put "worker/attachments/$original"
|
||||
[ "$(mc cat "api/attachments/$original")" = 'synthetic test fixture' ]
|
||||
deny mc cat "worker/attachments/$foreign"
|
||||
deny put "worker/attachments/staging/${suffix}-write"
|
||||
deny put "api/attachments/original/${suffix}-write"
|
||||
deny mc rm "api/attachments/$original"
|
||||
deny mc admin info worker
|
||||
printf '%s\n' 'PASS S3 HTTPS: worker can read staging and write originals. Foreign prefixes, staging writes and admin denied.'
|
||||
if [ "${1:-}" = rotated ]; then
|
||||
if error=$(mc alias set retired https://minio:9000 "$(cat /retired/S3_ACCESS_KEY)" \
|
||||
"$(cat /retired/S3_SECRET_KEY)" --api S3v4 2>&1) &&
|
||||
error=$(mc cat "retired/attachments/$original" 2>&1); then
|
||||
printf '%s\n' 'Retired S3 account accepted' >&2
|
||||
exit 1
|
||||
fi
|
||||
case "$error" in *"Access Key Id you provided does not exist"*|*"InvalidAccessKeyId"*) ;;
|
||||
*) printf '%s\n' 'Unexpected retired S3 authentication result' >&2; exit 1;;
|
||||
esac
|
||||
printf '%s\n' 'PASS MinIO rejects the retired worker access key.'
|
||||
fi
|
||||
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Measure loss and restoration of service after sealing the local OpenBao."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path[:0] = [str(ROOT / "scripts"), str(ROOT / "tests")]
|
||||
from stand import bao, root_token, unseal
|
||||
from client import Client, Failure, check
|
||||
|
||||
client = Client("https://localhost:8443", str(ROOT / ".runtime/trust/ca.crt"), timeout=2)
|
||||
actor = client.user("seal")
|
||||
client.call("GET", "/api/v1/users/me", actor=actor)
|
||||
|
||||
sealed_at = time.monotonic()
|
||||
bao("sys/seal", {}, root_token())
|
||||
try:
|
||||
status = bao("sys/seal-status")
|
||||
check(status["sealed"], "seal did not take effect")
|
||||
consecutive = 0
|
||||
last_ready = None
|
||||
ca = ssl.create_default_context(cafile=str(ROOT / ".runtime/trust/ca.crt"))
|
||||
while consecutive < 3:
|
||||
elapsed = time.monotonic() - sealed_at
|
||||
check(elapsed < 55, "API served beyond credential grace")
|
||||
try:
|
||||
with urllib.request.urlopen("https://localhost:8443/health/ready", context=ca, timeout=3) as result:
|
||||
check(result.status == 200, "unexpected readiness status")
|
||||
last_ready = elapsed
|
||||
consecutive = 0
|
||||
except urllib.error.HTTPError as error:
|
||||
check(error.code == 503, "unexpected ingress readiness error")
|
||||
if elapsed >= 20:
|
||||
consecutive += 1
|
||||
except OSError:
|
||||
consecutive = 0
|
||||
time.sleep(0.5)
|
||||
unavailable_at = time.monotonic()
|
||||
check(last_ready is not None, "no successful sample within the grace period")
|
||||
try:
|
||||
client.call("GET", "/api/v1/users/me", actor=actor)
|
||||
except Failure:
|
||||
pass
|
||||
else:
|
||||
raise AssertionError("session still served while the credentials lease is lost")
|
||||
finally:
|
||||
unseal()
|
||||
|
||||
start = time.monotonic()
|
||||
while True:
|
||||
try:
|
||||
client.call("GET", "/api/v1/users/me", actor=actor)
|
||||
break
|
||||
except Failure:
|
||||
check(time.monotonic() - start < 45, "original session did not recover")
|
||||
time.sleep(0.5)
|
||||
print(json.dumps({"sealed_to_unavailable_s": round(unavailable_at - sealed_at, 2),
|
||||
"last_ready_after_seal_s": round(last_ready, 2),
|
||||
"unseal_to_ready_s": round(time.monotonic() - start, 2),
|
||||
"previous_session_preserved": True}))
|
||||
@@ -0,0 +1,162 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check worker scope, rotate TLS identity and Redis credential, and verify queued content."""
|
||||
|
||||
import argparse
|
||||
import math
|
||||
import concurrent.futures
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
|
||||
from stand import ROOT, rotate_worker, run_compose
|
||||
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check
|
||||
|
||||
|
||||
def snapshot():
|
||||
result = run_compose("images", "--format", "json", "worker", capture_output=True, text=True)
|
||||
return json.loads(result.stdout)[0]["ID"]
|
||||
|
||||
|
||||
def summary(values):
|
||||
values = sorted(values)
|
||||
def pct(n):
|
||||
return round(values[max(0, math.ceil(len(values) * n / 100) - 1)] * 1000, 1)
|
||||
return {f"p{n}_ms": pct(n) for n in (50, 95, 99)}
|
||||
|
||||
|
||||
def experiment(client, count):
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
|
||||
def burst():
|
||||
def upload(_):
|
||||
c = Client(client.base, args.ca_file)
|
||||
started = time.monotonic()
|
||||
att, original = c.attachment(alice, chat)
|
||||
c.message(alice, chat, "lab7 worker experiment", attachments=[att["id"]])
|
||||
return att, original, started, time.monotonic() - started
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
|
||||
work = list(pool.map(upload, range(count)))
|
||||
check(len({a["id"] for a, *_ in work}) == count, "upload IDs must be unique")
|
||||
return work
|
||||
|
||||
def drain(work):
|
||||
def get(item):
|
||||
c = Client(client.base, args.ca_file)
|
||||
att, original, submitted, _ = item
|
||||
deadline = time.monotonic() + 60
|
||||
retries = 0
|
||||
while time.monotonic() < deadline:
|
||||
path = "/api/v1/attachments/" + att["id"]
|
||||
try:
|
||||
ready = c.call("GET", path, actor=bob, schema="Attachment")["json"]
|
||||
check(ready["status"] != "failed", "attachment processing failed")
|
||||
if ready["status"] == "ready":
|
||||
latency = time.monotonic() - submitted
|
||||
check(ready["id"] == att["id"] and ready["sha256"] == att["sha256"],
|
||||
"attachment identity changed")
|
||||
check(c.call("GET", path + "/content", actor=bob)["bytes"] == original, "original changed")
|
||||
check(len(ready["variants"]) == 3, "missing generated variants")
|
||||
thumbnail = c.call("GET", path + "/content?variant=thumbnail", actor=bob)
|
||||
check(thumbnail["bytes"].startswith(b"\xff\xd8"), "thumbnail not present")
|
||||
return latency, retries
|
||||
except Failure as error:
|
||||
if "received 503" not in str(error) and "connection/TLS failure" not in str(error):
|
||||
raise
|
||||
retries += 1
|
||||
time.sleep(0.3)
|
||||
raise Failure("attachment did not become ready within 60 seconds")
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool:
|
||||
return list(pool.map(get, work))
|
||||
|
||||
def worker_usage():
|
||||
worker = run_compose("ps", "-q", "worker", capture_output=True, text=True).stdout.strip()
|
||||
result = subprocess.check_output(["docker", "stats", "--no-stream", "--format", "{{json .}}", worker],
|
||||
text=True, timeout=12)
|
||||
sample = json.loads(result)
|
||||
return {"cpu": sample["CPUPerc"], "memory": sample["MemUsage"]}
|
||||
|
||||
run_compose("run", "--rm", "--no-deps", "audit", "worker")
|
||||
run_compose("run", "--rm", "--no-deps", "--entrypoint", "sh", "db_grants", "/db-audit.sh")
|
||||
run_compose("run", "--rm", "--no-deps", "--entrypoint", "sh", "s3_bootstrap", "/s3-audit.sh")
|
||||
image = snapshot()
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as monitor:
|
||||
usage = monitor.submit(worker_usage)
|
||||
start = time.monotonic()
|
||||
warm = burst()
|
||||
warm_ready = drain(warm)
|
||||
warm_seconds = time.monotonic() - start
|
||||
resources = usage.result()
|
||||
run_compose("stop", "worker")
|
||||
paused = time.monotonic()
|
||||
queued = burst()
|
||||
time.sleep(2)
|
||||
for att, *_ in queued:
|
||||
path = "/api/v1/attachments/" + att["id"]
|
||||
check(client.call("GET", path, actor=bob, schema="Attachment")["json"]["status"] == "queued",
|
||||
"accepted attachment was not queued without worker")
|
||||
rotation_start = time.monotonic()
|
||||
try:
|
||||
rotate_worker()
|
||||
restarted = time.monotonic()
|
||||
post_ready = drain(queued)
|
||||
recovered = time.monotonic()
|
||||
run_compose("run", "--rm", "--no-deps", "audit", "rotation")
|
||||
run_compose("run", "--rm", "--no-deps", "--entrypoint", "sh", "db_grants", "/db-audit.sh", "rotated")
|
||||
run_compose("run", "--rm", "--no-deps", "--entrypoint", "sh", "s3_bootstrap", "/s3-audit.sh", "rotated")
|
||||
check(snapshot() == image, "worker image changed during rotation")
|
||||
time.sleep(2)
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
|
||||
rows = client.call("GET", path, actor=bob, schema="MessagePage")["json"]["items"]
|
||||
linked = [row["attachment_ids"][0] for row in rows]
|
||||
expected = {att["id"] for att, *_ in (*warm, *queued)}
|
||||
check(set(linked) == expected and len(rows) == len(expected), "confirmed messages lost or duplicated")
|
||||
finally:
|
||||
# Retired material is kept only long enough to prove rejection.
|
||||
for name in ("tls.crt", "tls.key", "REDIS_PASSWORD", "POSTGRES_PASSWORD", "S3_ACCESS_KEY", "S3_SECRET_KEY"):
|
||||
path = ROOT / ".runtime/retired" / name
|
||||
if path.exists():
|
||||
path.unlink()
|
||||
|
||||
return {
|
||||
"worker_image_id": image,
|
||||
"baseline": {"jobs": count, "verified": len(warm_ready), "ready_latency": summary([latency for latency, _ in warm_ready]),
|
||||
"read_retries": sum(retries for _, retries in warm_ready), "worker_sample": resources,
|
||||
"submission_latency": summary([cost for *_, cost in warm]),
|
||||
"verified_per_second": round(count / warm_seconds, 2)},
|
||||
"incident": {"queued": count, "verified": len(post_ready), "lost_or_duplicate": 0,
|
||||
"submission_latency": summary([cost for *_, cost in queued]),
|
||||
"ready_latency": summary([latency for latency, _ in post_ready]),
|
||||
"read_retries": sum(retries for _, retries in post_ready),
|
||||
"rotation_seconds": round(restarted - rotation_start, 2),
|
||||
"worker_unavailable_seconds": round(recovered - paused, 2),
|
||||
"drain_seconds_after_start": round(recovered - restarted, 2)},
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--ca-file", default=str(ROOT / ".runtime/trust/ca.crt"))
|
||||
parser.add_argument("--base-url", default="https://localhost:8443")
|
||||
parser.add_argument("--jobs", type=int, default=8, choices=range(1, 41))
|
||||
parser.add_argument("--repeats", type=int, default=3, choices=range(1, 6))
|
||||
parser.add_argument("--output", type=Path)
|
||||
args = parser.parse_args()
|
||||
runs = [experiment(Client(args.base_url, args.ca_file), args.jobs) for _ in range(args.repeats)]
|
||||
environment = subprocess.check_output(
|
||||
["docker", "info", "--format", "{{.OSType}}/{{.Architecture}} {{.NCPU}} {{.MemTotal}}"], text=True,
|
||||
).split()
|
||||
result = {
|
||||
"docker_platform": environment[0], "docker_vcpus": int(environment[1]),
|
||||
"docker_memory_bytes": int(environment[2]),
|
||||
"fixture_png_bytes": (ROOT / "tests/fixtures/sample.png").stat().st_size,
|
||||
"closed_loop_concurrency": 4, "queue_observation_seconds": 2, "runs": runs,
|
||||
}
|
||||
encoded = json.dumps(result, indent=2) + "\n"
|
||||
if args.output:
|
||||
args.output.write_text(encoded)
|
||||
print(encoded, end="")
|
||||
Reference in New Issue
Block a user