forked from mtusi2026/mtusi2026lab7
Добавил TLS и защиту мессенджера для лабораторной 7
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
# Проверки студента
|
||||
|
||||
## Lab6: worker outage и telemetry
|
||||
|
||||
Сценарии из Lab6 используют тот же стенд через TLS. Первый сценарий останавливает worker и перезапускает обе API реплики; затем проверяет обработку вложения. Второй проверяет метрики и связь логов с трассами через TLS шлюзы:
|
||||
|
||||
PYTHONPATH=tests python3 student-tests/worker_outage.py --base-url https://localhost:8443 --ca-file secrets/pki/ca.crt
|
||||
docker compose exec -T worker python - < student-tests/telemetry_check.py
|
||||
|
||||
## Lab7: TLS, identities и scoped credentials
|
||||
|
||||
Все команды выполняются после инициализации OpenBao и запуска Compose на локальном synthetic стенде.
|
||||
|
||||
Публичный HTTPS smoke и отрицательная проверка пустого trust store:
|
||||
|
||||
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"
|
||||
|
||||
Внутренний API mTLS проверяет отсутствие client cert, foreign CA, доверенный CA с неправильным URI SAN и разрешённый LB URI SAN:
|
||||
|
||||
docker compose --profile checks run --rm mtls-test
|
||||
|
||||
OpenBao тест подтверждает, что API читает собственный KV v2 secret, но не worker path и не может писать:
|
||||
|
||||
docker compose --profile checks run --rm openbao-policy-test
|
||||
|
||||
RustFS проверяет полный путь записи вложения и отказ worker в чтении сохранённого оригинала:
|
||||
|
||||
docker compose --profile checks run --rm s3-policy-test
|
||||
|
||||
Общий Redis rate limiter возвращает 429 и Retry-After после десяти неверных входов для synthetic username:
|
||||
|
||||
python3 student-tests/login_rate_limit.py https://localhost:8443 "$PWD/secrets/pki/ca.crt"
|
||||
|
||||
Argon2id benchmark использует те же зависимости и CPU/RAM limits приложения, не сохраняет пароль или digest:
|
||||
|
||||
docker compose --profile checks run --rm argon2-benchmark
|
||||
|
||||
Истечение сессии проверяется с TTL 5 секунд на обеих репликах. После первой команды дождитесь ответа 200 от `/health/ready`. Последняя команда возвращает TTL из `.env`:
|
||||
|
||||
SESSION_TTL_SECONDS=5 docker compose up -d --no-deps --force-recreate api1 api2 envoy-api1 envoy-api2
|
||||
python3 student-tests/session_expiry.py --base-url https://localhost:8443 --ca-file "$PWD/secrets/pki/ca.crt"
|
||||
docker compose up -d --no-deps --force-recreate api1 api2 envoy-api1 envoy-api2
|
||||
|
||||
Проверки создают синтетические объекты и счётчики входа. Тест сам удаляет объекты. Сертификаты, tokens, credentials и приватные ключи в stdout не печатаются.
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Измеряет только время Argon2id; не печатает синтетический пароль или digest."""
|
||||
import os
|
||||
import platform
|
||||
import statistics
|
||||
import time
|
||||
from argon2 import PasswordHasher, Type
|
||||
|
||||
memory_kib = int(os.getenv("ARGON2_MEMORY_KIB", "19456"))
|
||||
iterations = int(os.getenv("ARGON2_ITERATIONS", "2"))
|
||||
parallelism = int(os.getenv("ARGON2_PARALLELISM", "1"))
|
||||
hasher = PasswordHasher(type=Type.ID, time_cost=iterations,
|
||||
memory_cost=memory_kib, parallelism=parallelism)
|
||||
samples = []
|
||||
for _ in range(5):
|
||||
started = time.perf_counter()
|
||||
hasher.hash("synthetic-password-for-local-benchmark")
|
||||
samples.append((time.perf_counter() - started) * 1000)
|
||||
print(f"python={platform.python_version()} os={platform.platform()} cpu_count={os.cpu_count()}")
|
||||
print(f"argon2id memory_kib={memory_kib} iterations={iterations} parallelism={parallelism} samples=5")
|
||||
print(f"latency_ms median={statistics.median(samples):.2f} min={min(samples):.2f} max={max(samples):.2f}")
|
||||
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверяет 401 на ошибочные попытки и 429/Retry-After после лимита."""
|
||||
import base64
|
||||
import ssl
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
base = sys.argv[1] if len(sys.argv) > 1 else "https://localhost:8443"
|
||||
ca = sys.argv[2] if len(sys.argv) > 2 else str(root / "secrets/pki/ca.crt")
|
||||
username = "rate_" + uuid.uuid4().hex[:20]
|
||||
password = "synthetic-invalid-password"
|
||||
request = urllib.request.Request(
|
||||
base.rstrip("/") + "/api/v1/auth/sessions",
|
||||
data=b"",
|
||||
headers={"Authorization": "Basic " + base64.b64encode(f"{username}:{password}".encode()).decode()},
|
||||
method="POST",
|
||||
)
|
||||
opener = urllib.request.build_opener(urllib.request.HTTPSHandler(
|
||||
context=ssl.create_default_context(cafile=ca)))
|
||||
for _ in range(10):
|
||||
try:
|
||||
opener.open(request, timeout=5)
|
||||
except urllib.error.HTTPError as exc:
|
||||
if exc.code != 401:
|
||||
raise SystemExit("FAIL: invalid login did not return 401 before the limit")
|
||||
else:
|
||||
raise SystemExit("FAIL: invalid credentials were accepted")
|
||||
try:
|
||||
opener.open(request, timeout=5)
|
||||
except urllib.error.HTTPError as exc:
|
||||
retry = exc.headers.get("Retry-After", "")
|
||||
if exc.code != 429 or not retry.isdigit() or int(retry) < 1:
|
||||
raise SystemExit("FAIL: limiter did not return 429 with Retry-After")
|
||||
else:
|
||||
raise SystemExit("FAIL: limiter accepted attempt 11")
|
||||
print("PASS: ten invalid logins returned 401; next login returned 429 with Retry-After")
|
||||
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка списка разрешённых identity Envoy из внутренней сети стенда."""
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
|
||||
PORT = 8443
|
||||
PKI = "/run/pki"
|
||||
|
||||
|
||||
def connect(host, cert=None, key=None):
|
||||
context = ssl.create_default_context(cafile=f"{PKI}/ca.crt")
|
||||
if cert:
|
||||
context.load_cert_chain(cert, key)
|
||||
with socket.create_connection((host, PORT), timeout=3) as raw:
|
||||
with context.wrap_socket(raw, server_hostname=host) as tls:
|
||||
request = f"GET /health/ready HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n"
|
||||
tls.sendall(request.encode("ascii"))
|
||||
return tls.recv(256).split(b"\r\n", 1)[0]
|
||||
|
||||
|
||||
def rejected(host, label, **kwargs):
|
||||
try:
|
||||
connect(host, **kwargs)
|
||||
except (ssl.SSLError, ssl.SSLCertVerificationError):
|
||||
print(f"PASS: {host}: {label} rejected during TLS identity validation")
|
||||
return
|
||||
except OSError as exc:
|
||||
print(f"FAIL: {host}: {label} transport error: {type(exc).__name__}")
|
||||
raise SystemExit(1)
|
||||
print(f"FAIL: {host}: {label} unexpectedly connected")
|
||||
raise SystemExit(1)
|
||||
|
||||
for host in ("api1", "api2"):
|
||||
rejected(host, "missing client certificate")
|
||||
rejected(host, "foreign client CA", cert=f"{PKI}/foreign-client.crt",
|
||||
key=f"{PKI}/foreign-client.key")
|
||||
rejected(host, "trusted CA with wrong URI SAN", cert=f"{PKI}/wrong-client.crt",
|
||||
key=f"{PKI}/wrong-client.key")
|
||||
status = connect(host, cert=f"{PKI}/lb-client.crt", key=f"{PKI}/lb-client.key")
|
||||
if status != b"HTTP/1.1 200 OK":
|
||||
print(f"FAIL: {host}: allowed LB identity did not reach ready API")
|
||||
sys.exit(1)
|
||||
print(f"PASS: {host}: allowlisted LB identity reached the API")
|
||||
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка AppRole: own KV path разрешён, чужой path и запись запрещены."""
|
||||
import json
|
||||
import ssl
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
BASE = "https://openbao:8200"
|
||||
CA = "/run/pki/ca.crt"
|
||||
IDENTITY = Path("/run/identity")
|
||||
|
||||
|
||||
def call(path, method="GET", payload=None, token=None):
|
||||
data = json.dumps(payload).encode() if payload is not None else None
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
request = urllib.request.Request(BASE + "/v1/" + path, data=data, headers=headers, method=method)
|
||||
context = ssl.create_default_context(cafile=str(CA))
|
||||
try:
|
||||
with urllib.request.urlopen(request, context=context, timeout=4) as response:
|
||||
return response.status
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code
|
||||
|
||||
|
||||
def expect(condition, label):
|
||||
if not condition:
|
||||
raise SystemExit("FAIL: " + label)
|
||||
print("PASS: " + label)
|
||||
|
||||
|
||||
role = (IDENTITY / "bao-api-role-id").read_text().strip()
|
||||
secret = (IDENTITY / "bao-api-secret-id").read_text().strip()
|
||||
with urllib.request.urlopen(
|
||||
urllib.request.Request(
|
||||
BASE + "/v1/auth/approle/login",
|
||||
data=json.dumps({"role_id": role, "secret_id": secret}).encode(),
|
||||
headers={"Content-Type": "application/json"},
|
||||
method="POST",
|
||||
),
|
||||
context=ssl.create_default_context(cafile=str(CA)),
|
||||
timeout=4,
|
||||
) as response:
|
||||
token = json.load(response)["auth"]["client_token"]
|
||||
|
||||
expect(call("secret/data/api", token=token) == 200, "API reads its own scoped secret")
|
||||
expect(call("secret/data/worker", token=token) == 403, "API cannot read worker secret")
|
||||
expect(call("secret/data/api", method="POST", payload={"data": {"x": "y"}}, token=token) == 403,
|
||||
"API cannot write its secret path")
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Проверяет RustFS IAM allow/deny для API и worker по TLS."""
|
||||
import json
|
||||
import ssl
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
import boto3
|
||||
from botocore.exceptions import ClientError
|
||||
|
||||
CA = "/run/pki/ca.crt"
|
||||
BAO = "https://openbao:8200"
|
||||
S3 = "https://s3:9000"
|
||||
BUCKET = "messenger-attachments"
|
||||
|
||||
|
||||
def read_secret(role_id_path, secret_id_path, path):
|
||||
role_id = open(role_id_path, encoding="utf-8").read().strip()
|
||||
secret_id = open(secret_id_path, encoding="utf-8").read().strip()
|
||||
context = ssl.create_default_context(cafile=CA)
|
||||
request = urllib.request.Request(
|
||||
BAO + "/v1/auth/approle/login",
|
||||
data=json.dumps({"role_id": role_id, "secret_id": secret_id}).encode(),
|
||||
headers={"Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
with urllib.request.urlopen(request, context=context, timeout=4) as response:
|
||||
token = json.load(response)["auth"]["client_token"]
|
||||
request = urllib.request.Request(
|
||||
BAO + "/v1/secret/data/" + path,
|
||||
headers={"X-Vault-Token": token},
|
||||
method="GET",
|
||||
)
|
||||
with urllib.request.urlopen(request, context=context, timeout=4) as response:
|
||||
return json.load(response)["data"]["data"]
|
||||
|
||||
|
||||
def client(data):
|
||||
return boto3.client("s3", endpoint_url=S3, region_name="us-east-1",
|
||||
aws_access_key_id=data["s3_access_key_id"],
|
||||
aws_secret_access_key=data["s3_secret_access_key"],
|
||||
verify=CA)
|
||||
|
||||
|
||||
api = client(read_secret("/run/identities/api/bao-api-role-id",
|
||||
"/run/identities/api/bao-api-secret-id", "api"))
|
||||
worker = client(read_secret("/run/identities/worker/bao-worker-role-id",
|
||||
"/run/identities/worker/bao-worker-secret-id", "worker"))
|
||||
marker = uuid.uuid4().hex
|
||||
staging_key = "staging/lab7-policy-" + marker
|
||||
original_key = "original/lab7-policy-" + marker
|
||||
variant_key = "variants/lab7-policy-" + marker
|
||||
payload = b"synthetic-policy-check"
|
||||
|
||||
try:
|
||||
api.put_object(Bucket=BUCKET, Key=staging_key, Body=payload)
|
||||
stream = worker.get_object(Bucket=BUCKET, Key=staging_key)["Body"]
|
||||
with stream:
|
||||
if stream.read() != payload:
|
||||
raise SystemExit("FAIL: worker received unexpected staging content")
|
||||
|
||||
worker.put_object(Bucket=BUCKET, Key=original_key, Body=payload)
|
||||
worker.put_object(Bucket=BUCKET, Key=variant_key, Body=payload)
|
||||
worker.delete_object(Bucket=BUCKET, Key=staging_key)
|
||||
print("PASS: API and worker have permissions for the attachment pipeline")
|
||||
|
||||
try:
|
||||
worker.get_object(Bucket=BUCKET, Key=original_key)["Body"].close()
|
||||
except ClientError as exc:
|
||||
if exc.response.get("ResponseMetadata", {}).get("HTTPStatusCode") != 403:
|
||||
raise SystemExit("FAIL: worker was denied for a non-policy reason")
|
||||
else:
|
||||
raise SystemExit("FAIL: worker read an object from the original prefix")
|
||||
print("PASS: worker cannot read a stored original")
|
||||
finally:
|
||||
for key in (staging_key, original_key, variant_key):
|
||||
api.delete_object(Bucket=BUCKET, Key=key)
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверяет, что действующий Bearer-токен перестаёт работать по истечении TTL."""
|
||||
import base64
|
||||
from datetime import datetime, timezone
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, arguments, check, run, timestamp
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Check session expiry with SESSION_TTL_SECONDS=5")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
registration = client.user("expiry")["registration"]
|
||||
credentials = f"{registration['username']}:{registration['password']}"
|
||||
authorization = "Basic " + base64.b64encode(credentials.encode()).decode()
|
||||
session = client.call("POST", "/api/v1/auth/sessions", 201,
|
||||
headers={"Authorization": authorization}, schema="Session")["json"]
|
||||
actor = {"token": session["token"]}
|
||||
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
remaining = (timestamp(session["expires_at"]) - datetime.now(timezone.utc)).total_seconds()
|
||||
check(0 < remaining <= 10, "set SESSION_TTL_SECONDS=5 on both API replicas")
|
||||
time.sleep(remaining + 1)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
print("PASS: an active Bearer session returned 401 after its declared expiry")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверяет свежие telemetry signals из сети Compose, не печатая их payload."""
|
||||
import json
|
||||
import ssl
|
||||
import time
|
||||
from urllib.parse import urlencode
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import urlopen
|
||||
|
||||
|
||||
TLS = ssl.create_default_context(cafile="/run/pki/ca.crt")
|
||||
|
||||
|
||||
def get_json(url):
|
||||
with urlopen(url, context=TLS, timeout=5) as response:
|
||||
return json.loads(response.read())
|
||||
|
||||
|
||||
def require(condition, message):
|
||||
if not condition:
|
||||
raise SystemExit("FAIL: " + message)
|
||||
|
||||
|
||||
now = time.time()
|
||||
names = get_json("https://lb:9543/api/v1/label/__name__/values")["data"]
|
||||
require("messenger_messenger_http_requests_total" in names, "API request counter missing")
|
||||
require("messenger_messenger_http_request_duration_seconds_bucket" in names, "API duration histogram missing")
|
||||
require("messenger_messenger_jobs_total" in names, "worker job counter missing")
|
||||
require("messenger_messenger_job_duration_seconds_bucket" in names, "worker duration histogram missing")
|
||||
|
||||
series_query = urlencode({"match[]": "messenger_messenger_http_requests_total"})
|
||||
series = get_json("https://lb:9543/api/v1/series?" + series_query)["data"]
|
||||
for labels in series:
|
||||
require(not {"user_id", "chat_id", "message_id", "attachment_id", "request_id"}.intersection(labels),
|
||||
"high-cardinality identifier found in metric labels")
|
||||
|
||||
|
||||
def find_correlated_log(service, event):
|
||||
selector = '{service_name="' + service + '"} |= "' + event + '"'
|
||||
query = urlencode({"query": selector, "limit": "20",
|
||||
"start": str(int((now - 1800) * 1_000_000_000)),
|
||||
"end": str(int(now * 1_000_000_000))})
|
||||
result = get_json("https://lb:9643/loki/api/v1/query_range?" + query)["data"]["result"]
|
||||
for stream in result:
|
||||
trace_id = stream["stream"].get("trace_id")
|
||||
span_id = stream["stream"].get("span_id")
|
||||
if trace_id and span_id:
|
||||
try:
|
||||
trace = get_json("https://lb:9843/api/traces/" + trace_id)
|
||||
if trace:
|
||||
return True
|
||||
except HTTPError as error:
|
||||
if error.code != 404:
|
||||
raise
|
||||
return False
|
||||
|
||||
|
||||
require(find_correlated_log("messenger-api", "http_request_completed"),
|
||||
"API log with matching trace/span IDs and stored trace missing")
|
||||
require(find_correlated_log("messenger-worker", "attachment_job_completed"),
|
||||
"worker log with matching trace/span IDs and stored trace missing")
|
||||
print("PASS: API/job metrics, bounded metric labels, Loki logs and matching Tempo traces")
|
||||
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unit check for the mandatory lab5 thumbnail conversion."""
|
||||
import io
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image
|
||||
from app.worker import _make_thumbnail
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
source = (ROOT / 'tests' / 'fixtures' / 'sample.png').read_bytes()
|
||||
content, width, height = _make_thumbnail(source)
|
||||
with Image.open(io.BytesIO(content)) as thumbnail:
|
||||
assert thumbnail.format == 'JPEG'
|
||||
assert thumbnail.size == (256, 160)
|
||||
assert (width, height) == (256, 160)
|
||||
print('PASS: 320x200 PNG produces a real JPEG thumbnail of 256x160')
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка очереди при остановленном worker и перезапуске API."""
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from client import Client, arguments, check
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
COMPOSE = ['docker', 'compose', '--env-file', '.env']
|
||||
|
||||
|
||||
def compose(*args):
|
||||
subprocess.run(COMPOSE + list(args), cwd=ROOT, check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments('Проверка durable очереди lab5 при остановке worker')
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
worker_stopped = False
|
||||
try:
|
||||
compose('stop', 'worker')
|
||||
worker_stopped = True
|
||||
attachment, source = client.attachment(alice, chat)
|
||||
check(attachment['status'] == 'queued', 'upload should stay queued while worker is stopped')
|
||||
ordinary = client.message(alice, chat, 'Обычное сообщение при остановленном worker')['json']
|
||||
check(ordinary['text'] == 'Обычное сообщение при остановленном worker', 'API stopped accepting ordinary messages')
|
||||
client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content',
|
||||
409, actor=alice)
|
||||
message = client.message(alice, chat, '', attachments=[attachment['id']])['json']
|
||||
check(message['attachment_ids'] == [attachment['id']], 'queued attachment was not linked')
|
||||
|
||||
compose('stop', 'envoy-api1', 'envoy-api2')
|
||||
compose('restart', 'api1', 'api2')
|
||||
compose('up', '-d', '--no-deps', '--force-recreate', 'envoy-api1', 'envoy-api2')
|
||||
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.3)
|
||||
client.call('GET', '/api/v1/users/me', actor=alice, schema='User')
|
||||
queued = client.call('GET', '/api/v1/attachments/' + attachment['id'],
|
||||
actor=bob, schema='Attachment')['json']
|
||||
check(queued['status'] == 'queued', 'queued state did not survive API restart')
|
||||
compose('up', '-d', '--no-deps', 'worker')
|
||||
worker_stopped = False
|
||||
|
||||
ready = client.wait_ready(bob, queued)
|
||||
original = client.call('GET', '/api/v1/attachments/' + attachment['id'] + '/content',
|
||||
actor=bob)
|
||||
check(original['bytes'] == source, 'original bytes changed during asynchronous processing')
|
||||
thumbnail = client.call(
|
||||
'GET', '/api/v1/attachments/' + attachment['id'] + '/content?variant=thumbnail',
|
||||
actor=bob,
|
||||
)
|
||||
check(thumbnail['headers'].get_content_type() == 'image/jpeg', 'thumbnail is not JPEG')
|
||||
check(ready['status'] == 'ready', 'attachment did not reach ready')
|
||||
print('PASS: queued upload survived API restart and worker completed original plus thumbnail')
|
||||
finally:
|
||||
if worker_stopped:
|
||||
compose('up', '-d', '--no-deps', 'worker')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user