lab7: тесты безопасности и перевод своих тестов на HTTPS, документы (trust-matrix, THREAT_MODEL, OPERATOR, DEFENSE, WINDOWS, PR), сборщик доказательств, чистка legacy bench

This commit is contained in:
Alexey Bodanyuk
2026-11-27 17:43:14 +03:00
parent 05df1695fe
commit 84dbdb4735
44 changed files with 1644 additions and 2686 deletions
+33 -5
View File
@@ -2,7 +2,8 @@
* `unit/` — pure functions (validation, cursor, auth headers, Argon2id); no services.
* `test_*` in this folder — marker `stack`: black-box HTTP against the running compose
stand THROUGH THE LOAD BALANCER (BASE_URL, default http://127.0.0.1:8080) plus
stand THROUGH THE LOAD BALANCER (BASE_URL, default https://localhost:8443, CA_FILE = the public
CA, default secrets/pki/public-ca.crt; certificate AND hostname always verified) plus
`docker compose` for database checks (psql inside the postgres container), the HAProxy
runtime state (scripts/lbctl.py) and failure injection. Every failure test restores the
stopped/paused service or replica in `finally` and waits until HAProxy sees all replicas UP.
@@ -23,6 +24,8 @@ import uuid
from pathlib import Path
from urllib.parse import quote
import ssl
import httpx2 as httpx
import pytest
from jsonschema import Draft202012Validator
@@ -33,7 +36,29 @@ sys.path.insert(0, str(ROOT / "scripts"))
import lbctl # noqa: E402
SPEC = json.loads((ROOT / "contracts" / "openapi.json").read_text(encoding="utf-8"))
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
BASE_URL = os.environ.get("BASE_URL", "https://localhost:8443").rstrip("/")
# Lab 7: every HTTP call of these tests verifies the server against the PUBLIC CA (+ hostname).
# There is no switch to turn verification off. The wrappers below make it the default of httpx.
CA_FILE = os.environ.get("CA_FILE") or str(ROOT / "secrets" / "pki" / "public-ca.crt")
TLS = ssl.create_default_context(cafile=CA_FILE)
class _VerifiedClient(httpx.Client):
def __init__(self, *args, **kwargs):
kwargs.setdefault("verify", TLS)
super().__init__(*args, **kwargs)
def _verified(function):
def call(*args, **kwargs):
kwargs.setdefault("verify", TLS)
return function(*args, **kwargs)
return call
httpx.Client = _VerifiedClient
for _name in ("get", "post", "put", "delete", "request"):
setattr(httpx, _name, _verified(getattr(httpx, _name)))
PASSWORD = "Test-password-Ω-12345" # synthetic; 12+ code points, non-ASCII on purpose
REPLICAS = int(os.environ.get("API_REPLICAS", "2")) # replicas the stand normally runs
@@ -61,7 +86,9 @@ def compose(*args: str, check: bool = True, timeout: float = 120, stdin: str | N
def psql(sql: str) -> str:
"""Run SQL inside the postgres container (no DB port is published) and return unaligned output."""
result = compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger",
# Lab 7: as the superuser over the container's local socket (peer auth of OS user postgres);
# pg_hba refuses the superuser over the network. Tests use it to inspect/break things on purpose.
result = compose("exec", "-T", "-u", "postgres", "postgres", "psql", "-d", "messenger",
"-At", "-v", "ON_ERROR_STOP=1", "-c", sql)
return result.stdout.strip()
@@ -430,9 +457,10 @@ def attachment_row(attachment_id: str) -> dict | None:
def probe_inside(replica: dict, path: str) -> int:
"""HTTP status of `path` asked inside the replica container itself (bypassing the LB)."""
"""HTTP status of `path` asked inside the replica container itself (bypassing the LB) - lab 7: on
the loopback health listener (127.0.0.1:8081), the mTLS port needs the LB's client certificate."""
code = ("import urllib.request as u, urllib.error as e\n"
"try: print(u.urlopen('http://127.0.0.1:8080%s', timeout=3).status)\n"
"try: print(u.urlopen('http://127.0.0.1:8081%s', timeout=3).status)\n"
"except e.HTTPError as x: print(x.code)") % path
out = subprocess.run(["docker", "exec", replica["id"], "python", "-c", code], capture_output=True, text=True,
timeout=30).stdout.strip()
+63 -25
View File
@@ -248,13 +248,17 @@ def test_graceful_shutdown_order_in_logs(api):
# ------------------------------------------------------------------ discovery: restart and scaling
def test_full_restart_lb_rediscovers_all_replicas(api):
actor = api.user("restart")
before = {r["instance"]: r["started_at"] for r in running_replicas()}
# Lab 7: X-Instance-Id is a random alias per PROCESS, so the replicas are compared by container
# id; a restarted process must show a NEW alias (it is not derived from the container).
before = {r["id"]: (r["started_at"], r["instance"]) for r in running_replicas()}
run_hook("restart.sh")
wait_healthy("postgres", "valkey", "api")
wait_stand()
after = {r["instance"]: r["started_at"] for r in running_replicas()}
assert set(after) == set(before) and all(after[h] != before[h] for h in after), "every replica restarted"
assert set(instances_seen(api, actor["token"])) == set(after) # same token, both replicas, no LB restart needed
after = {r["id"]: (r["started_at"], r["instance"]) for r in running_replicas()}
assert set(after) == set(before), "the same containers run again"
assert all(after[c][0] != before[c][0] and after[c][1] != before[c][1] for c in after), "every replica restarted"
seen = set(instances_seen(api, actor["token"]))
assert seen == {alias for _, alias in after.values()} # same token, both replicas, no LB restart needed
def test_scale_up_and_down_is_picked_up_without_errors(api):
@@ -278,14 +282,24 @@ def test_scale_up_and_down_is_picked_up_without_errors(api):
def test_compose_policy_limits_ports_secrets_images():
config = json.loads(compose("config", "--format", "json").stdout)
services = config["services"]
# auditor and jobctl (profile "tools") are started on demand and not part of the running stand.
# auditor, jobctl and mtls-check (profile "tools") are started on demand, not part of the stand.
assert set(services) == {"postgres", "valkey", "s3", "broker", "migrate", "s3-init", "api", "lb", "relay", "worker",
# lab 6: observability
"otel-collector", "prometheus", "loki", "tempo", "grafana"}
"otel-collector", "prometheus", "loki", "tempo", "grafana",
# lab 7: secrets
"openbao"}
for name, svc in services.items():
limits = svc.get("deploy", {}).get("resources", {}).get("limits", {})
assert limits.get("cpus") and limits.get("memory"), f"{name}: CPU/RAM limits"
assert "container_name" not in svc, f"{name}: container_name prevents scaling"
# lab 7 hardening: nothing privileged, no host namespaces, no Docker socket, no capabilities
assert not svc.get("privileged") and svc.get("network_mode") is None and svc.get("pid") is None, name
assert not any("docker.sock" in str(v.get("source", "")) for v in svc.get("volumes", [])), name
assert svc.get("cap_drop") == ["ALL"] and "no-new-privileges:true" in svc.get("security_opt", []), name
if name in ("postgres", "valkey", "s3", "broker"): # start as root, chown, drop to their user
assert sorted(svc.get("cap_add", [])) == ["CHOWN", "DAC_OVERRIDE", "FOWNER", "SETGID", "SETUID"], name
else:
assert not svc.get("cap_add"), name
if name in ("api", "migrate"):
assert "build" in svc # built from this repository's source
elif name in ("s3-init", "relay", "worker"):
@@ -294,39 +308,63 @@ def test_compose_policy_limits_ports_secrets_images():
assert "@sha256:" in svc["image"], f"{name}: image must be pinned by digest"
assert services["api"]["deploy"]["replicas"] >= 2 and not services["api"].get("ports")
published = {name: svc.get("ports", []) for name, svc in services.items() if svc.get("ports")}
# Published: the LB and (lab 6) the Grafana UI - both on loopback only. No OTLP/store/admin port.
# Published: the HTTPS ingress and the HTTPS Grafana UI - both on loopback only. Nothing else.
assert set(published) == {"lb", "grafana"}
assert all(p["host_ip"] in ("127.0.0.1", "::1") for ports in published.values() for p in ports)
assert [p["target"] for p in published["lb"]] == [8443, 8443]
assert [p["target"] for p in published["grafana"]] == [3000, 3000]
secrets = {name: sorted(s["source"] for s in svc.get("secrets", [])) for name, svc in services.items()}
s3_keys = sorted(f"s3_{who}_{part}" for who in ("admin", "api", "worker", "auditor")
for part in ("access_key_id", "secret_access_key"))
assert secrets == {"postgres": ["postgres_password"], "valkey": ["valkey_password"], "s3": s3_keys,
"migrate": ["database_url"], "s3-init": s3_keys, "lb": [],
"broker": ["rabbitmq_users"],
# the API: its own S3 key pair only (no admin/worker keys, no broker credentials)
"api": ["cache_url", "database_url", "s3_api_access_key_id", "s3_api_secret_access_key"],
# relay: database + its broker user only; worker: + its own S3 key pair
"relay": ["broker_url_relay", "database_url"],
"worker": ["broker_url_worker", "database_url", "s3_worker_access_key_id",
"s3_worker_secret_access_key"],
# lab 6: the telemetry services get no application secret at all
"otel-collector": [], "prometheus": [], "loki": [], "tempo": [],
"grafana": ["grafana_admin_password"]}
ca = "pki_internal_ca"
def own(*names):
return sorted([*names, ca])
assert secrets == {
# stores: their server certificate + what they verify; postgres creates the service roles once
"postgres": sorted(["postgres_password", "pki_postgres_crt", "pki_postgres_key", ca,
*(f"pg_{r}_password" for r in ("migrate", "api", "relay", "worker", "jobctl", "auditor"))]),
"valkey": own("valkey_api_password", "pki_valkey_crt", "pki_valkey_key"),
"s3": own(*s3_keys, "pki_s3_crt", "pki_s3_key"),
"broker": own("rabbitmq_users", "pki_broker_crt", "pki_broker_key"),
# bootstrap jobs: migrate = schema owner only; s3-init = the ONLY holder of the S3 admin key
"migrate": own("database_url_migrate"),
"s3-init": own(*s3_keys),
# the LB: public certificate + its client identity towards the API
"lb": own("pki_ingress_pem", "pki_lb_pem"),
# application services: ONLY their AppRole login + their certificate; every other secret
# comes from OpenBao (no database/cache/broker URL or S3 key file, no token)
"api": own("bao_api_role_id", "bao_api_secret_id", "pki_api_crt", "pki_api_key"),
"relay": own("bao_relay_role_id", "bao_relay_secret_id", "pki_relay_crt", "pki_relay_key"),
"worker": own("bao_worker_role_id", "bao_worker_secret_id", "pki_worker_crt", "pki_worker_key"),
"openbao": own("pki_openbao_crt", "pki_openbao_key"),
# telemetry: certificates only, no application secret
"otel-collector": own("pki_otel_collector_crt", "pki_otel_collector_key"),
"prometheus": own("pki_prometheus_crt", "pki_prometheus_key"),
"loki": own("pki_loki_crt", "pki_loki_key"),
"tempo": own("pki_tempo_crt", "pki_tempo_key"),
"grafana": own("grafana_admin_password", "pki_grafana_crt", "pki_grafana_key", "pki_grafana_ui_crt",
"pki_grafana_ui_key", "pki_public_ca"),
}, secrets
# No CA private key is defined as a secret at all; nothing mounts the operator's material.
assert not [s for s in config.get("secrets", {}) if s.endswith("ca_key") or "root" in s or "unseal" in s]
volumes = {name: [v["source"] for v in svc.get("volumes", []) if v["type"] == "volume"]
for name, svc in services.items()}
assert volumes == {"postgres": ["pgdata"], "valkey": ["valkeydata"], "s3": ["s3data"], "migrate": [],
"s3-init": [], "api": [], "lb": [], "broker": ["rabbitmqdata"], "relay": [], "worker": [],
"otel-collector": [], "prometheus": ["promdata"], "loki": ["lokidata"], "tempo": ["tempodata"],
"grafana": ["grafanadata"]}
"grafana": ["grafanadata"], "openbao": ["baodata"]}
networks = {name: sorted(svc.get("networks", {})) for name, svc in services.items()}
assert networks == {"postgres": ["data"], "valkey": ["data"], "s3": ["storage"], "migrate": ["data"],
"s3-init": ["storage"], "api": ["data", "edge", "storage", "telemetry"], "broker": ["queue"],
"relay": ["data", "queue", "telemetry"], "worker": ["data", "queue", "storage", "telemetry"],
"s3-init": ["storage"], "api": ["data", "edge", "storage", "telemetry", "vault"],
"broker": ["queue"], "relay": ["data", "queue", "telemetry", "vault"],
"worker": ["data", "queue", "storage", "telemetry", "vault"],
"lb": ["edge"], "otel-collector": ["telemetry"], "prometheus": ["telemetry"],
"loki": ["telemetry"], "tempo": ["telemetry"], "grafana": ["telemetry", "ui"]}, networks
"loki": ["telemetry"], "tempo": ["telemetry"], "grafana": ["telemetry", "ui"],
"openbao": ["vault"]}, networks
# the LB cannot reach the stores; the API not the broker; telemetry stores cannot reach the app stores
for network in ("data", "storage", "queue", "telemetry"):
for network in ("data", "storage", "queue", "telemetry", "vault"):
assert config["networks"][network].get("internal") is True, network
@@ -346,7 +384,7 @@ def test_running_containers_have_limits_and_no_bypass_ports():
def test_migrations_ran_once_by_the_migrate_service():
applied = psql("SELECT version FROM schema_migrations ORDER BY version").split()
assert applied == ["0001_init", "0002_idempotency_keys", "0003_post_message_function", "0004_attachments",
"0005_pipeline", "0006_observability"]
"0005_pipeline", "0006_observability", "0007_least_privilege"]
migrate = compose("ps", "-a", "--format", "json", "migrate").stdout
rows = [json.loads(line) for line in migrate.splitlines() if line.strip()]
assert rows and all(r["State"] == "exited" and r["ExitCode"] == 0 for r in rows)
+2 -2
View File
@@ -21,7 +21,7 @@ from pathlib import Path
import pytest
import imagegen
from conftest import api_with_env, attachment_row, psql, s3_size
from conftest import TLS, api_with_env, attachment_row, psql, s3_size
pytestmark = pytest.mark.stack
@@ -52,7 +52,7 @@ def wait_for(condition, timeout: float, what: str) -> None:
def raw_upload(token: str, chat_id: str, declared: int, body: bytes, *, wait_answer: float | None) -> bytes:
"""Hand-made HTTP request: announce `declared` bytes, send only `body`, then either close the
socket (client gone) or keep it open and read the answer after `wait_answer` seconds."""
sock = socket.create_connection(("127.0.0.1", 8080), timeout=30)
sock = TLS.wrap_socket(socket.create_connection(("127.0.0.1", 8443), timeout=30), server_hostname="localhost")
head = (f"POST /api/v1/chats/{chat_id}/attachments?filename=x.png HTTP/1.1\r\nHost: localhost\r\n"
f"Authorization: Bearer {token}\r\nContent-Type: image/png\r\nContent-Length: {declared}\r\n\r\n")
sock.sendall(head.encode() + body)
+15 -7
View File
@@ -1,13 +1,14 @@
"""Database-level guarantees, checked over HTTP and verified directly in PostgreSQL / Valkey."""
from __future__ import annotations
import subprocess
import threading
import time
import uuid
import pytest
from conftest import PASSWORD, Api, compose, psql
from conftest import PASSWORD, ROOT, Api, compose, psql
pytestmark = pytest.mark.stack
@@ -81,7 +82,8 @@ def test_migrations_rerun_is_a_noop():
assert "0004_attachments: already applied, skipped" in result.stdout
assert "0005_pipeline: already applied, skipped" in result.stdout
assert "0006_observability: already applied, skipped" in result.stdout
assert psql("SELECT count(*) FROM schema_migrations") == "6"
assert "0007_least_privilege: already applied, skipped" in result.stdout
assert psql("SELECT count(*) FROM schema_migrations") == "7"
assert psql("SELECT count(*) FROM users") == users_before
@@ -112,8 +114,14 @@ def test_secrets_are_not_stored_in_plain_text(api):
actor = api.user("store")
stored = psql(f"SELECT password_hash FROM users WHERE id = '{actor['id']}'")
assert stored.startswith("$argon2id$v=19$m=19456,t=2,p=1$") and PASSWORD not in stored
token_hex = actor["token"].encode().hex()
keys = compose("exec", "-T", "valkey", "sh", "-c",
'REDISCLI_AUTH="$(cat /run/secrets/valkey_password)" valkey-cli --scan --pattern "session:*"').stdout.split()
assert keys and all(len(k) == len("session:") + 64 for k in keys)
assert not any(actor["token"] in k or token_hex in k for k in keys)
# Lab 7: Valkey has no all-powerful user any more (default off; `api` may not SCAN/KEYS), so the
# check asks with the API's own ACL user: the session exists ONLY under SHA-256(token).
import hashlib
hashed = "session:" + hashlib.sha256(actor["token"].encode()).hexdigest()
script = ('read -r REDISCLI_AUTH; export REDISCLI_AUTH; read -r k1; read -r k2; '
'c="valkey-cli --tls --cacert /run/secrets/internal-ca.crt -h localhost --user api --no-auth-warning"; '
'$c exists "$k1"; $c exists "$k2"')
pw = (ROOT / "secrets" / "valkey_api_password").read_text(encoding="utf-8").strip()
out = subprocess.run(["docker", "compose", "exec", "-T", "valkey", "sh", "-c", script], cwd=ROOT, capture_output=True,
input=f"{pw}\n{hashed}\nsession:{actor['token']}\n".encode()).stdout.decode().split()
assert out == ["1", "0"], out # hashed key present, raw-token key absent
+1 -1
View File
@@ -81,7 +81,7 @@ def test_locked_table_gives_bounded_503(api, prepared):
"""A statement stuck behind a lock is stopped by lock_timeout, not after minutes."""
alice, bob, chat, message = prepared
locker = subprocess.Popen(
["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-c",
["docker", "compose", "exec", "-T", "-u", "postgres", "postgres", "psql", "-d", "messenger", "-c",
"BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(6); COMMIT;"],
cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
+1 -1
View File
@@ -213,7 +213,7 @@ def test_failure_after_the_key_insert_rolls_everything_back(api, pair):
def lock_chat_row(chat: dict, seconds: float) -> subprocess.Popen:
sql = (f"BEGIN; SELECT 1 FROM chats WHERE id = '{chat['id']}' FOR UPDATE; "
f"SELECT pg_sleep({seconds}); COMMIT;")
return subprocess.Popen(["docker", "compose", "exec", "-T", "postgres", "psql", "-U", "messenger", "-d",
return subprocess.Popen(["docker", "compose", "exec", "-T", "-u", "postgres", "postgres", "psql", "-d",
"messenger", "-c", sql], cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+8 -6
View File
@@ -20,7 +20,7 @@ import pytest
from PIL import Image
import imagegen
from conftest import (lbctl, attachment_row, audit, compose, events_of, job_rows, jobctl, psql, queue_depth, s3_keys,
from conftest import (ROOT, lbctl, attachment_row, audit, compose, events_of, job_rows, jobctl, psql, queue_depth, s3_keys,
s3_size, service_down, service_with_env, wait_healthy, wait_stand)
pytestmark = pytest.mark.stack
@@ -343,16 +343,18 @@ def test_bad_message_is_dead_lettered_not_processed(api, pair):
"""A message that does not match jobs.schema.json (published here with the relay's own broker
user) is rejected by the worker into the DLQ; nothing is processed."""
before = queue_depth("messenger.attachment-jobs.dlq")
script = ("import asyncio, aio_pika\n"
script = ("import asyncio, sys, aio_pika\n"
"from messenger.tls import client_context\n"
"async def m():\n"
" url = open('/run/secrets/broker_url').read().strip()\n"
" c = await aio_pika.connect(url)\n"
" url = sys.stdin.readline().strip()\n"
" c = await aio_pika.connect(url, ssl_context=client_context('/run/secrets/internal-ca.crt'))\n"
" ch = await c.channel(publisher_confirms=True)\n"
" ex = await ch.get_exchange('messenger.jobs', ensure=False)\n"
" await ex.publish(aio_pika.Message(b'{\"url\":\"http://evil/x.png\"}'), routing_key='attachment.process.v1')\n"
" await c.close()\n"
"asyncio.run(m())\n")
compose("exec", "-T", "relay", "python", "-c", script)
url = (ROOT / "secrets" / "broker_url_relay").read_text(encoding="utf-8").strip()
compose("exec", "-T", "relay", "python", "-c", script, stdin=url + "\n")
wait_for(lambda: queue_depth("messenger.attachment-jobs.dlq") == before + 1, 20, "not dead-lettered")
assert '"bad_message"' in compose("logs", "--no-log-prefix", "worker").stdout
@@ -438,7 +440,7 @@ def test_queued_staging_is_never_deleted_even_after_retention(api, pair):
row = attachment_row(att["id"])
assert row["status"] == "queued" and row["staging_state"] == "present"
assert s3_size(row["staging_key"], "staging") == len(SAMPLE)
refused = compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-c",
refused = compose("exec", "-T", "-u", "postgres", "postgres", "psql", "-d", "messenger", "-c",
f"UPDATE attachments SET staging_state = 'deleting' WHERE id = '{att['id']}'",
check=False)
assert refused.returncode != 0 and "attachments_active_has_source" in refused.stderr
+327
View File
@@ -0,0 +1,327 @@
"""Lab 7, grade 3: negative proofs of the trust matrix (contracts/trust-matrix.md) on the running stand.
Already covered elsewhere and kept: outsider 404 (test_api.test_foreign_chat_is_indistinguishable...),
X-User-Id ignored, logout/expiry (test_api, test_sessions), no secrets in Loki/Tempo
(test_observability), limits of request sizes (test_api, test_attachments), compose policy incl.
per-service secrets and hardening (test_balancing.test_compose_policy_limits_ports_secrets_images).
Here: external TLS (wrong hostname / empty trust / plaintext), LB->API mTLS (scripts/mtls_check.sh),
TLS + identities of every dependency (PostgreSQL roles, Valkey ACL, RabbitMQ users, S3 keys,
Collector/Prometheus/Loki/Tempo client certificates), OpenBao policies + sealed behaviour,
Argon2id PHC format, login rate limit (429 + Retry-After), X-Instance-Id alias, non-root/limits of
the running containers, no secrets in Git or in the image. Every test restores what it changes.
"""
from __future__ import annotations
import json
import re
import socket
import ssl
import subprocess
import time
import uuid
import httpx2 as httpx
import pytest
from conftest import BASE_URL, CA_FILE, PASSWORD, REPLICAS, ROOT, TLS, basic, compose, lbctl, psql, wait_healthy, \
wait_stand
pytestmark = pytest.mark.stack
SECRETS = ROOT / "secrets"
NO_PATHCONV = {"MSYS_NO_PATHCONV": "1"}
def secret(name: str) -> str:
return (SECRETS / name).read_text(encoding="utf-8").strip()
def sh(service: str, script: str, stdin: str | None = None, timeout: float = 60) -> subprocess.CompletedProcess:
"""Run a shell script inside a running service container; secrets go via stdin, never argv.
Bytes, not text: on Windows a text-mode pipe would turn "\\n" into "\\r\\n" (CR in the password)."""
result = subprocess.run(["docker", "compose", "exec", "-T", service, "sh", "-c", script], cwd=ROOT,
input=(stdin or "").encode("utf-8"), capture_output=True, timeout=timeout)
return subprocess.CompletedProcess(result.args, result.returncode, result.stdout.decode("utf-8", "replace"),
result.stderr.decode("utf-8", "replace"))
# ------------------------------------------------------------------ external TLS (client -> LB)
def tls_error(host: str, server_hostname: str, context: ssl.SSLContext) -> str | None:
try:
with socket.create_connection((host, 8443), timeout=5) as raw, \
context.wrap_socket(raw, server_hostname=server_hostname):
return None
except ssl.SSLCertVerificationError as exc:
return exc.verify_message
def test_ingress_verifies_ca_and_hostname():
assert tls_error("127.0.0.1", "localhost", TLS) is None # right CA + SAN
assert "Hostname mismatch" in (tls_error("127.0.0.1", "evil.example", TLS) or "") # wrong name
empty = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) # trusts nothing
assert "unable to get local issuer certificate" in (tls_error("127.0.0.1", "localhost", empty) or "")
internal = ssl.create_default_context(cafile=str(SECRETS / "pki" / "internal-ca.crt"))
assert tls_error("127.0.0.1", "localhost", internal) is not None # internal CA is not the public one
def test_no_plaintext_entry_point():
with socket.create_connection(("127.0.0.1", 8443), timeout=5) as s: # plain HTTP to the TLS port
s.sendall(b"GET /health/live HTTP/1.1\r\nHost: localhost\r\n\r\n")
assert not s.recv(256).startswith(b"HTTP/1.1 200")
for port in (8080, 8404, 9090, 3100, 3200, 4318, 5432, 6379, 5671, 8200, 8333):
with pytest.raises(OSError):
socket.create_connection(("127.0.0.1", port), timeout=2).close()
# ------------------------------------------------------------------ LB -> API mTLS
def test_lb_to_api_mtls_refuses_foreign_and_wrong_identity():
result = subprocess.run(["sh", "scripts/mtls_check.sh"], cwd=ROOT, capture_output=True, text=True,
encoding="utf-8", timeout=180)
assert result.returncode == 0, result.stdout[-3000:]
out = result.stdout
assert f"PASS: mTLS LB->API, {REPLICAS} replica(s), 0 failure(s)" in out
# the allowlist (not the CA chain) refused the worker certificate - the API logged that SAN
assert '"client_san": ["worker"]' in out and '"mtls_identity_rejected"' in out
def test_api_has_no_published_port_and_answers_only_mtls():
for item in lbctl.replicas(all_states=False):
assert not json.loads(subprocess.run(["docker", "inspect", "-f", "{{json .HostConfig.PortBindings}}", item["id"]],
capture_output=True, text=True).stdout or "{}")
# ------------------------------------------------------------------ dependencies: TLS + identities
def psql_as(role: str, sql: str, sslmode: str = "verify-full") -> subprocess.CompletedProcess:
"""Connect over TCP like a service: TLS verify-full against the internal CA, password via stdin."""
script = ('read -r PGPASSWORD; export PGPASSWORD; exec psql "host=localhost dbname=messenger user=messenger_%s '
'sslmode=%s sslrootcert=/run/secrets/internal-ca.crt" -At -v ON_ERROR_STOP=1 -c "%s"') % (role, sslmode, sql)
return sh("postgres", script, stdin=secret(f"pg_{role}_password") + "\n")
def test_postgres_tls_only_and_roles_least_privilege():
assert psql("SHOW ssl") == "on"
assert psql_as("api", "SELECT 1").stdout.strip() == "1"
assert psql_as("api", "SELECT ssl FROM pg_stat_ssl WHERE pid = pg_backend_pid()").stdout.strip() == "t"
refused = psql_as("api", "SELECT 1", sslmode="disable")
assert refused.returncode != 0 and "no encryption" in refused.stderr, refused.stderr
# superuser never over the network
su = sh("postgres", 'read -r PGPASSWORD; export PGPASSWORD; psql "host=localhost user=postgres dbname=messenger '
'sslmode=require" -c "SELECT 1"', stdin=secret("postgres_password") + "\n")
assert su.returncode != 0 and "pg_hba.conf" in su.stderr
denied = {
"api": ["DELETE FROM messages", "SELECT count(*) FROM job_attempts", "CREATE TABLE x (i int)",
"TRUNCATE users", "UPDATE users SET display_name = 'x'"],
"relay": ["SELECT count(*) FROM users", "SELECT count(*) FROM messages", "DELETE FROM jobs"],
"worker": ["SELECT count(*) FROM users", "SELECT count(*) FROM messages", "SELECT count(*) FROM sessions",
"DELETE FROM attachments", "SELECT post_message_v3(NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL)"],
"auditor": ["UPDATE jobs SET state = state", "INSERT INTO outbox (job_id, attempt) VALUES (gen_random_uuid(), 1)"],
}
for role, statements in denied.items():
for sql in statements:
result = psql_as(role, sql)
assert result.returncode != 0 and "permission denied" in result.stderr, (role, sql, result.stderr)
allowed = {"api": "SELECT count(*) FROM users", "relay": "SELECT count(*) FROM outbox",
"worker": "SELECT count(*) FROM jobs", "auditor": "SELECT count(*) FROM attachments"}
for role, sql in allowed.items():
assert psql_as(role, sql).returncode == 0, role
assert psql("SELECT rolsuper FROM pg_roles WHERE rolname LIKE 'messenger_%'").split() == ["f"] * 6
VALKEY = ('read -r REDISCLI_AUTH; export REDISCLI_AUTH; '
'valkey-cli --tls --cacert /run/secrets/internal-ca.crt -h localhost --user api ')
def test_valkey_tls_and_acl():
assert sh("valkey", VALKEY + "ping", stdin=secret("valkey_api_password") + "\n").stdout.strip() == "PONG"
# (DEBUG is disabled server-wide anyway: enable-debug-command defaults to no)
for command in ("flushall", "config get dir", "keys *", "acl list", "set other:key 1", "eval 'return 1' 0"):
out = sh("valkey", VALKEY + command, stdin=secret("valkey_api_password") + "\n").stdout
assert "NOPERM" in out, (command, out)
# no plaintext: the only port speaks TLS; the default user is off
assert "PONG" not in sh("valkey", "valkey-cli -h localhost -p 6379 ping 2>&1; true").stdout
default = sh("valkey", "valkey-cli --tls --cacert /run/secrets/internal-ca.crt -h localhost ping 2>&1; true").stdout
assert "PONG" not in default
AMQP_PROBE = r'''
import asyncio, sys, aio_pika
from messenger.tls import client_context
url = sys.stdin.readline().strip()
async def main():
conn = await aio_pika.connect(url, ssl_context=client_context("/run/secrets/internal-ca.crt"), timeout=5)
ch = await conn.channel()
try:
q = await ch.get_queue("messenger.attachment-jobs", ensure=False)
await q.get(no_ack=False, fail=False)
print("CONSUME_ALLOWED")
except Exception as exc:
print("CONSUME_REFUSED", type(exc).__name__)
await conn.close()
asyncio.run(main())
'''
def test_broker_tls_only_and_users_scoped():
# relay may not consume (its permission: write to the jobs exchange only)
out = compose("exec", "-T", "relay", "python", "-c", AMQP_PROBE, check=False,
stdin=secret("broker_url_relay") + "\n").stdout
assert "CONSUME_REFUSED" in out, out
# the plaintext AMQP port is closed (listeners.tcp = none)
probe = "import socket\ntry:\n socket.create_connection(('broker', 5672), timeout=3); print('OPEN')\nexcept OSError: print('CLOSED')"
assert compose("exec", "-T", "relay", "python", "-c", probe).stdout.strip() == "CLOSED"
def test_s3_https_and_scoped_keys():
out = compose("run", "--rm", "--no-deps", "s3-init", timeout=180).stdout
assert "api: write final: refused (AccessDenied) -> OK" in out
assert "done: private buckets, least-privilege keys verified" in out
probe = "import urllib.request\ntry:\n urllib.request.urlopen('http://s3:8333/healthz', timeout=3); print('PLAIN')\nexcept Exception: print('NO-PLAINTEXT')"
assert compose("exec", "-T", "worker", "python", "-c", probe).stdout.strip() == "NO-PLAINTEXT"
TELEMETRY_PROBE = r'''
import ssl, sys, urllib.request
ca = "/run/secrets/internal-ca.crt"
for url in sys.argv[1:]:
ctx = ssl.create_default_context(cafile=ca) # server verified, but NO client certificate
try:
urllib.request.urlopen(url, timeout=5, context=ctx); print(url, "ACCEPTED")
except Exception as exc:
print(url, "REFUSED", type(exc).__name__)
'''
def test_telemetry_endpoints_require_client_certificates():
# A process WITHOUT a client certificate (the worker's python, no cert loaded) is refused by the
# Collector; the backends are reachable only for the Collector/Grafana/Prometheus identities.
out = compose("exec", "-T", "worker", "python", "-c", TELEMETRY_PROBE, "https://otel-collector:4318/v1/logs").stdout
assert "REFUSED" in out and "ACCEPTED" not in out, out
# Prometheus: a certificate of OUR CA but not in its SAN allowlist (the worker's) is refused
allow = r'''
import ssl, urllib.request
ctx = ssl.create_default_context(cafile="/run/secrets/internal-ca.crt")
ctx.load_cert_chain("/run/secrets/service.crt", "/run/secrets/service.key")
try:
urllib.request.urlopen("https://prometheus:9090/-/ready", timeout=5, context=ctx); print("ACCEPTED")
except Exception as exc:
print("REFUSED", type(exc).__name__)
'''
# the worker is not on the telemetry backends' allowlist; it is on the `telemetry` network
assert "REFUSED" in compose("exec", "-T", "worker", "python", "-c", allow).stdout
# ------------------------------------------------------------------ OpenBao
def test_openbao_policies_and_no_root_credential_in_apps():
result = subprocess.run(["sh", "scripts/bao_check.sh"], cwd=ROOT, capture_output=True, text=True,
encoding="utf-8", timeout=300)
assert result.returncode == 0, result.stdout[-4000:]
assert result.stdout.count("FAIL") == 0
assert "PASS: OpenBao allow/deny and no root credential in the application" in result.stdout
def test_openbao_not_dev_and_persistent():
status = json.loads(sh("openbao", "bao status -format=json").stdout)
assert status["initialized"] and not status["sealed"] and status["storage_type"] == "raft"
cmd = compose("ps", "--format", "json", "openbao").stdout
assert "-dev" not in json.loads(cmd.splitlines()[0])["Command"]
def test_sealed_openbao_keeps_running_replicas_and_blocks_new_ones(api):
"""Restart = sealed. Running API replicas keep serving (their secrets are in memory); a NEW replica
cannot get its secrets and never becomes healthy; after the operator's unseal it starts."""
user = api.user("sealed")
compose("restart", "openbao")
try:
assert json.loads(sh("openbao", "bao status -format=json").stdout)["sealed"] is True
api.call("GET", "/api/v1/users/me", 200, token=user["token"]) # running replicas: fine
compose("up", "-d", "--no-recreate", "--no-deps", "--scale", f"api={REPLICAS + 1}", "api")
time.sleep(15)
logs = compose("logs", "--no-log-prefix", "--since", "30s", "api").stdout
assert "openbao_unavailable" in logs
assert len([r for r in lbctl.replicas(all_states=False) if r["health"] == "healthy"]) == REPLICAS
finally:
subprocess.run(["python", "scripts/bao_operator.py", "unseal"], cwd=ROOT, check=True, capture_output=True)
try:
lbctl.wait_up(REPLICAS + 1, timeout=120) # the new one comes up now
finally:
compose("up", "-d", "--no-recreate", "--no-deps", "--scale", f"api={REPLICAS}", "api")
wait_healthy("api", "relay", "worker", "openbao")
wait_stand()
# ------------------------------------------------------------------ passwords, login limit, instance id
def test_argon2id_hash_carries_salt_and_parameters(api):
a, b = api.register("phc"), api.register("phc")
rows = psql("SELECT password_hash FROM users WHERE id IN ('%s', '%s')" % (a["id"], b["id"])).split()
assert len(rows) == 2
for value in rows:
assert re.fullmatch(r"\$argon2id\$v=19\$m=(\d+),t=(\d+),p=(\d+)\$[A-Za-z0-9+/]{22}\$[A-Za-z0-9+/]{43}", value)
m, t, p = map(int, re.match(r"\$argon2id\$v=19\$m=(\d+),t=(\d+),p=(\d+)", value).groups())
assert m >= 19456 and t >= 2 and p >= 1
assert rows[0].split("$")[4] != rows[1].split("$")[4] # same password, different salts
def test_failed_logins_are_rate_limited_with_retry_after(api):
user = api.user("ratelimit")
url = BASE_URL + "/api/v1/auth/sessions"
codes = [httpx.post(url, headers={"Authorization": basic(user["username"], "Wrong-password-123")}, timeout=10)
for _ in range(5)]
assert [r.status_code for r in codes] == [401] * 5
blocked = httpx.post(url, headers={"Authorization": basic(user["username"], "Wrong-password-123")}, timeout=10)
assert blocked.status_code == 429 and blocked.json()["error"]["code"] == "rate_limited"
assert 1 <= int(blocked.headers["Retry-After"]) <= 60
assert blocked.headers.get("X-Instance-Id") and blocked.headers.get("X-Request-Id")
# even the RIGHT password is 429 while blocked (no oracle), on every replica (shared counter)
for _ in range(4):
assert httpx.post(url, headers={"Authorization": basic(user["username"], PASSWORD)}, timeout=10).status_code == 429
# another account is not affected
other = api.user("ratelimit2")
assert httpx.post(url, headers={"Authorization": basic(other["username"], PASSWORD)}, timeout=10).status_code == 201
def test_x_instance_id_is_a_random_alias_without_hostname_or_ip(api):
seen = {api.call("GET", "/health/live", 200).headers["X-Instance-Id"] for _ in range(20)}
assert len(seen) == REPLICAS
replicas = lbctl.replicas(all_states=False)
hostnames = {r["hostname"] for r in replicas}
ips = {ip for r in replicas for ip in r["ips"]}
for alias in seen:
assert re.fullmatch(r"i-[0-9a-f]{12}", alias)
assert alias not in hostnames and not any(ip in alias for ip in ips)
assert seen == {r["instance"] for r in replicas}
# ------------------------------------------------------------------ hardening, secrets outside Git/images
def test_running_containers_are_hardened():
ids = compose("ps", "-q").stdout.split()
for item in json.loads(subprocess.run(["docker", "inspect", *ids], capture_output=True, text=True, check=True).stdout):
name, host = item["Name"], item["HostConfig"]
assert not host["Privileged"] and host["NetworkMode"] != "host" and host["PidMode"] != "host", name
assert host["CapDrop"] == ["ALL"] and "no-new-privileges:true" in host["SecurityOpt"], name
assert host["NanoCpus"] > 0 and host["Memory"] > 0, name
assert not any("docker.sock" in m.get("Source", "") for m in item["Mounts"]), name
for service in ("api", "relay", "worker"):
for cid in compose("ps", "-q", service).stdout.split():
uid = subprocess.run(["docker", "exec", cid, "id", "-u"], capture_output=True, text=True).stdout.strip()
caps = subprocess.run(["docker", "exec", cid, "sh", "-c", "grep CapEff /proc/1/status"],
capture_output=True, text=True).stdout.split()[-1]
assert uid == "10001" and int(caps, 16) == 0, (service, uid, caps)
def test_no_secret_in_git_or_in_the_image():
tracked = subprocess.run(["git", "ls-files"], cwd=ROOT, capture_output=True, text=True, check=True).stdout.split()
assert not [f for f in tracked if f.startswith("secrets/") or f.endswith((".key", ".pem"))
or ".mtusi-lab7-operator" in f or f.endswith(".env")]
values = [secret("postgres_password"), secret("pg_api_password"), secret("valkey_api_password"),
secret("s3_api_secret_access_key"), secret("rabbitmq_worker_password"),
secret("bao/api_secret_id")]
for value in values:
grep = subprocess.run(["git", "grep", "-q", "-F", value], cwd=ROOT)
assert grep.returncode == 1 # not in any tracked file
image = json.loads(compose("config", "--format", "json").stdout)["services"]["api"]["image"]
script = ('n=0; while read -r v; do grep -rqsF -- "$v" /app /etc /usr/local/lib/python3.13/site-packages/messenger* '
'&& n=$((n+1)); done; find / -xdev \\( -name "*.key" -o -name "*.pem" \\) -not -path "/proc/*" '
'-not -path "/usr/*" -not -path "/etc/ssl/*" 2>/dev/null | wc -l; echo "hits=$n"')
out = subprocess.run(["docker", "run", "--rm", "-i", "--entrypoint", "sh", image, "-c", script],
input="\n".join(values) + "\n", capture_output=True, text=True, timeout=120).stdout.split()
assert out[-1] == "hits=0" and out[-2] == "0", out
+4 -3
View File
@@ -81,11 +81,12 @@ def test_bucket_is_private_outside_the_api(api, pair):
api.wait_status(alice, att["id"], "ready")
key = attachment_row(att["id"])["object_key"]
probe = (
"import urllib.request as u, urllib.error as e, socket\n"
"import urllib.request as u, urllib.error as e, socket, ssl\n"
"ctx = ssl.create_default_context(cafile='/run/secrets/internal-ca.crt')\n"
"def st(url):\n"
" try: return u.urlopen(url, timeout=3).status\n"
" try: return u.urlopen(url, timeout=3, context=ctx).status\n"
" except e.HTTPError as x: return x.code\n"
f"print(st('http://s3:8333/messenger-attachments/{key}'), st('http://s3:8333/messenger-attachments?list-type=2'))\n"
f"print(st('https://s3:8333/messenger-attachments/{key}'), st('https://s3:8333/messenger-attachments?list-type=2'))\n"
"for port in (9333, 8888, 8080):\n"
" s = socket.socket(); s.settimeout(2)\n"
" print(port, s.connect_ex(('s3', port)))\n")
+179
View File
@@ -0,0 +1,179 @@
"""Lab 7 units without services: mTLS identity check, TLS contexts, Argon2id parameters, login limit,
OpenBao client error handling, secret lookup order."""
from __future__ import annotations
import asyncio
import ssl
import subprocess
import sys
from pathlib import Path
from types import SimpleNamespace
import pytest
from messenger import bao, passwords, ratelimit, tls
from messenger.config import ConfigError, Settings
ROOT = Path(__file__).resolve().parents[2]
PKI = ROOT / "secrets" / "pki"
# ------------------------------------------------------------------ mTLS identity allowlist
class FakeSSL:
def __init__(self, sans):
self.sans = sans
def getpeercert(self):
return {"subjectAltName": tuple(("DNS", s) for s in self.sans)} if self.sans is not None else {}
class FakeTransport:
def __init__(self, ssl_object):
self.ssl_object, self.aborted = ssl_object, False
def get_extra_info(self, name, default=None):
return {"ssl_object": self.ssl_object, "peername": ("10.0.0.9", 4444)}.get(name, default)
def abort(self):
self.aborted = True
def test_dns_names_only_from_subject_alt_name():
assert tls.dns_names({"subjectAltName": (("DNS", "lb"), ("IP Address", "10.0.0.1"))}) == ["lb"]
assert tls.dns_names(None) == [] and tls.dns_names({}) == []
@pytest.mark.parametrize("sans, allowed", [(["lb"], True), (["worker"], False), (["lb.evil"], False),
([], False), (None, False)])
def test_protocol_aborts_every_identity_outside_the_allowlist(sans, allowed, monkeypatch):
monkeypatch.setenv("MTLS_ALLOWED_CLIENTS", "lb")
protocol_cls = tls.protocol_class()
called = []
monkeypatch.setattr(tls.HttpToolsProtocol, "connection_made", lambda self, transport: called.append(transport))
transport = FakeTransport(FakeSSL(sans))
protocol_cls.connection_made(object.__new__(protocol_cls), transport)
assert transport.aborted is (not allowed)
assert bool(called) is allowed
def test_protocol_aborts_a_plaintext_transport(monkeypatch):
protocol_cls = tls.protocol_class()
transport = FakeTransport(None)
protocol_cls.connection_made(object.__new__(protocol_cls), transport)
assert transport.aborted
def test_allowlist_cannot_be_empty(monkeypatch):
monkeypatch.setenv("MTLS_ALLOWED_CLIENTS", " , ")
with pytest.raises(ValueError):
tls.allowed_clients()
@pytest.mark.skipif(not (PKI / "api.crt").exists(), reason="PKI not generated (scripts/init_pki.py)")
def test_server_context_requires_client_certificates_of_the_internal_ca_only():
ctx = tls.server_context(str(PKI / "api.crt"), str(PKI / "api.key"), str(PKI / "internal-ca.crt"))
assert ctx.verify_mode == ssl.CERT_REQUIRED and ctx.minimum_version == ssl.TLSVersion.TLSv1_2
subjects = [dict(x[0] for x in c["subject"])["commonName"] for c in ctx.get_ca_certs()]
assert subjects == ["MTUSI lab7 internal CA"] # no system CAs, not the public CA
client = tls.client_context(str(PKI / "internal-ca.crt"))
assert client.check_hostname and client.verify_mode == ssl.CERT_REQUIRED
# ------------------------------------------------------------------ Argon2id parameters
def test_argon2_parameters_are_configurable_but_never_below_the_minimum(monkeypatch):
monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z")
monkeypatch.setenv("ARGON2_MEMORY_KIB", "47104")
monkeypatch.setenv("ARGON2_ITERATIONS", "3")
s = Settings.from_env(s3_credentials=False)
assert (s.argon2_memory_kib, s.argon2_iterations, s.argon2_parallelism) == (47104, 3, 1)
for name, bad in (("ARGON2_MEMORY_KIB", "19455"), ("ARGON2_ITERATIONS", "1"), ("ARGON2_PARALLELISM", "0")):
monkeypatch.setenv(name, bad)
with pytest.raises(ConfigError):
Settings.from_env(s3_credentials=False)
monkeypatch.delenv(name)
def test_hash_carries_the_configured_parameters_and_old_hashes_still_verify():
async def run():
passwords.configure(1)
old = await passwords.hash_password("correct horse battery")
passwords.configure(1, memory_kib=32768, iterations=3)
new = await passwords.hash_password("correct horse battery")
assert new.startswith("$argon2id$v=19$m=32768,t=3,p=1$")
assert await passwords.verify_password(old, "correct horse battery") # params come from the hash
assert await passwords.verify_password(new, "correct horse battery")
passwords.configure(2)
asyncio.run(run())
# ------------------------------------------------------------------ login rate limit (process fallback)
def limiter(user=3, ip=100):
settings = SimpleNamespace(cache_timeout_seconds=0.5, login_user_limit=user, login_user_window_seconds=60,
login_ip_limit=ip, login_ip_window_seconds=300)
return ratelimit.LoginLimiter(settings, client=None)
def test_limit_per_username_with_retry_after():
async def run():
lim = limiter(user=3)
for _ in range(3):
await lim.check("alice", "1.1.1.1")
await lim.failed("alice", "1.1.1.1")
with pytest.raises(ratelimit.RateLimited) as exc:
await lim.check("alice", "2.2.2.2") # another IP does not help
assert exc.value.status == 429 and exc.value.code == "rate_limited"
assert 1 <= int(exc.value.headers["Retry-After"]) <= 60
await lim.check("bob", "1.1.1.1") # another user is not blocked
asyncio.run(run())
def test_limit_per_ip_and_reset_on_success():
async def run():
lim = limiter(user=100, ip=4)
for i in range(4):
await lim.failed(f"user{i}", "9.9.9.9")
with pytest.raises(ratelimit.RateLimited):
await lim.check("someone-else", "9.9.9.9") # spraying many accounts from one IP
lim2 = limiter(user=2)
await lim2.failed("carol", "1.1.1.1")
await lim2.succeeded("carol") # success resets the username window
await lim2.failed("carol", "1.1.1.1")
await lim2.check("carol", "1.1.1.1")
asyncio.run(run())
# ------------------------------------------------------------------ OpenBao client / secret lookup order
def test_secrets_come_from_openbao_first(monkeypatch):
monkeypatch.setenv("BAO_ADDR", "https://openbao:8200")
monkeypatch.setattr(bao, "_cache", {"database_url": "postgresql://from-bao/x"})
monkeypatch.setenv("DATABASE_URL", "postgresql://from-env/x")
assert Settings.from_env(s3_credentials=False).database_url == "postgresql://from-bao/x"
monkeypatch.delenv("BAO_ADDR")
assert Settings.from_env(s3_credentials=False).database_url == "postgresql://from-env/x"
def test_openbao_refusal_is_a_config_error_without_retry(monkeypatch, tmp_path):
(tmp_path / "r").write_text("role")
(tmp_path / "s").write_text("secret")
monkeypatch.setattr(bao, "_cache", None)
for k, v in {"BAO_ADDR": "https://127.0.0.1:1", "BAO_SECRET_PATH": "messenger/data/api",
"BAO_ROLE_ID_FILE": str(tmp_path / "r"), "BAO_SECRET_ID_FILE": str(tmp_path / "s"),
"BAO_STARTUP_TIMEOUT_SECONDS": "0", "DATABASE_URL": "postgresql://x/y"}.items():
monkeypatch.setenv(k, v)
with pytest.raises(ConfigError, match="OpenBao unavailable"): # nothing listens: bounded wait, then stop
Settings.from_env(s3_credentials=False)
monkeypatch.delenv("BAO_SECRET_ID_FILE")
monkeypatch.setattr(bao, "_cache", None)
with pytest.raises(ConfigError, match="BAO_SECRET_ID_FILE"):
Settings.from_env(s3_credentials=False)
def test_pki_script_never_prints_key_material(tmp_path):
"""init_pki.py output names files only (run on a copy so the real ./secrets stays untouched)."""
script = (ROOT / "scripts" / "init_pki.py").read_text(encoding="utf-8")
(tmp_path / "scripts").mkdir()
(tmp_path / "scripts" / "init_pki.py").write_text(script, encoding="utf-8")
out = subprocess.run([sys.executable, str(tmp_path / "scripts" / "init_pki.py")], capture_output=True, text=True,
check=True).stdout
assert "BEGIN" not in out and "PRIVATE" not in out
assert (tmp_path / "secrets" / "pki" / "internal-ca.key").exists()
+12 -2
View File
@@ -194,14 +194,24 @@ def test_request_fingerprint_ignores_key_order_and_default_attachments():
assert request_fingerprint("x", [one]) != request_fingerprint("x", [])
def test_instance_id_defaults_to_hostname_and_is_validated(monkeypatch):
def test_instance_id_is_a_random_alias_stable_per_process_and_validated(monkeypatch):
"""Lab 7: X-Instance-Id is a random alias (no hostname/IP), drawn once per process."""
import re
import socket
from messenger import config
monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z")
monkeypatch.delenv("INSTANCE_ID", raising=False)
assert Settings.from_env().instance_id == socket.gethostname()
monkeypatch.setattr(config, "_INSTANCE_ID", None)
first = Settings.from_env().instance_id
assert re.fullmatch(r"i-[0-9a-f]{12}", first) and first != socket.gethostname()
assert Settings.from_env().instance_id == first # stable for the life of the process
monkeypatch.setattr(config, "_INSTANCE_ID", None)
assert Settings.from_env().instance_id != first # another process, another alias
monkeypatch.setattr(config, "_INSTANCE_ID", None)
monkeypatch.setenv("INSTANCE_ID", "replica-a")
assert Settings.from_env().instance_id == "replica-a"
for bad in ("with space", "x" * 65, "ip/1"):
monkeypatch.setattr(config, "_INSTANCE_ID", None)
monkeypatch.setenv("INSTANCE_ID", bad)
with pytest.raises(ConfigError):
Settings.from_env()