ЛР 7: TLS/mTLS, Argon2id, OpenBao и negative tests (оценка 3)
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
Яковлев Матвей Дмитриевич
2026-11-28 12:29:50 +01:00
parent 20afc2c790
commit 8c75b7266f
53 changed files with 3114 additions and 89 deletions
+91
View File
@@ -0,0 +1,91 @@
#!/usr/bin/env python3
"""One-time operator bootstrap for the lab7 OpenBao instance.
Creates init keys (saved outside Git), unseals, enables KV-v2, writes a scoped
policy and an AppRole, stores role_id/secret_id outside Git, and writes the
application secrets. Root token and unseal keys are never given to the app.
"""
import json
import os
import ssl
import urllib.error
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
PRIVATE = ROOT / "certs" / "private"
CA = ROOT / "certs" / "ca.crt"
ADDR = "https://localhost:8200"
CTX = ssl.create_default_context(cafile=str(CA))
def call(method, path, body=None, token=None, allow_codes=()):
data = json.dumps(body).encode() if body is not None else None
headers = {"Content-Type": "application/json"}
if token:
headers["X-Vault-Token"] = token
req = urllib.request.Request(ADDR + path, data=data, headers=headers, method=method)
try:
with urllib.request.urlopen(req, context=CTX, timeout=10) as response:
raw = response.read()
return json.loads(raw) if raw else {}
except urllib.error.HTTPError as exc:
if exc.code in allow_codes:
return json.loads(exc.read())
raise RuntimeError("%s %s -> %s: %s" % (method, path, exc.code, exc.read()[:300])) from None
def load_dotenv():
env_file = ROOT / ".env"
if env_file.exists():
for line in env_file.read_text().splitlines():
if "=" in line and not line.lstrip().startswith("#"):
key, value = line.split("=", 1)
os.environ.setdefault(key.strip(), value.strip())
def main():
load_dotenv()
init_file = PRIVATE / "bao-init.json"
if init_file.exists():
initial = json.loads(init_file.read_text())
else:
if call("GET", "/v1/sys/init").get("initialized"):
raise SystemExit("OpenBao is already initialized but local init file is missing")
initial = call("POST", "/v1/sys/init", {"secret_shares": 5, "secret_threshold": 3})
init_file.write_text(json.dumps(initial, indent=2))
os.chmod(init_file, 0o600)
root = initial["root_token"]
health = call("GET", "/v1/sys/health", allow_codes=(503, 472, 473))
if health.get("sealed"):
for key in initial["keys"][:3]:
call("POST", "/v1/sys/unseal", {"key": key}, token=root)
print("OpenBao unsealed with operator-held keys")
configured = (PRIVATE / "bao-approle.json").exists()
if not configured:
call("POST", "/v1/sys/mounts/secret", {"type": "kv", "options": {"version": "2"}}, token=root)
policy = (ROOT / "security" / "app-policy.hcl").read_text()
call("POST", "/v1/sys/policies/acl/messenger-app", {"policy": policy}, token=root)
call("POST", "/v1/sys/auth/approle", {"type": "approle"}, token=root)
call("POST", "/v1/auth/approle/role/messenger-app", {
"token_policies": "messenger-app", "token_ttl": "1h", "token_max_ttl": "4h",
}, token=root)
role_id = call("GET", "/v1/auth/approle/role/messenger-app/role-id", token=root)["data"]["role_id"]
secret_id = call("POST", "/v1/auth/approle/role/messenger-app/secret-id", token=root)["data"]["secret_id"]
approle_file = PRIVATE / "bao-approle.json"
approle_file.write_text(json.dumps({"role_id": role_id, "secret_id": secret_id}, indent=2))
os.chmod(approle_file, 0o600)
secret = {
"DATABASE_URL": os.environ.get("DATABASE_URL",
"postgresql://messenger:messenger@db:5432/messenger"),
"S3_ACCESS_KEY": os.environ.get("S3_ACCESS_KEY", "messenger"),
"S3_SECRET_KEY": os.environ.get("S3_SECRET_KEY", "local-only-synthetic-s3-secret"),
"REDIS_PASSWORD": os.environ.get("REDIS_PASSWORD", "local-only-synthetic-redis"),
}
call("POST", "/v1/secret/data/messenger/app", {"data": secret}, token=root)
print("OpenBao bootstrapped: unsealed, KV-v2 + scoped AppRole, secret path secret/messenger/app")
if __name__ == "__main__":
main()
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env python3
"""Level-3 demonstration: accepted work survives a stopped worker.
Stops only the worker, uploads (expects 202 queued and 409 on content), then starts
the worker again and waits for ready + a valid 256x160 thumbnail.
"""
import subprocess
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "tests"))
from client import Client, check # noqa: E402
def compose(*args):
script = ROOT / "scripts" / ("stop-worker.cmd" if sys.platform == "win32" else "stop-worker.sh")
subprocess.run([str(script), *args], cwd=str(ROOT), check=True,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
def main():
c = Client("http://localhost:8080")
alice, bob, _eve, chat = c.bootstrap()
compose("stop") # worker down, broker/API/S3 intact
attachment, original = c.attachment(alice, chat)
check(attachment["status"] == "queued", "upload must be 202 queued")
c.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", 409, actor=bob)
print("ACCEPTED:", attachment["id"], "status=queued; content=409 while worker is stopped")
compose("start")
deadline = time.monotonic() + 90
while True:
ready = c.call("GET", "/api/v1/attachments/" + attachment["id"], 200,
actor=bob, schema="Attachment")["json"]
if ready["status"] == "ready":
break
check(ready["status"] != "failed", "job reached failed")
check(time.monotonic() < deadline, "job did not reach ready within 90 s")
time.sleep(0.3)
thumb = [v for v in ready["variants"] if v["name"] == "thumbnail"]
check(len(thumb) == 1 and (thumb[0]["width"], thumb[0]["height"]) == (256, 160),
"thumbnail missing or wrong size")
check(len(c.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content",
200, actor=bob)["bytes"]) == len(original), "original changed")
c.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content?variant=thumbnail",
200, actor=bob)
print("RECOVERED:", attachment["id"], "status=ready, thumbnail=256x160, original intact")
if __name__ == "__main__":
main()
+107
View File
@@ -0,0 +1,107 @@
#!/usr/bin/env python3
"""Local synthetic PKI bootstrap. Private keys stay outside Git (certs/private/).
Generates one CA plus leaf certificates with explicit SANs for every service in
the lab7 trust matrix. Re-run to rotate leaves (keep the CA unless rotating trust).
"""
import datetime as dt
from pathlib import Path
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
ROOT = Path(__file__).resolve().parents[1]
CERTS = ROOT / "certs"
PRIVATE = CERTS / "private"
DAYS = 365
def new_key():
return rsa.generate_private_key(public_exponent=65537, key_size=2048)
def save(key, cert, name):
PRIVATE.mkdir(parents=True, exist_ok=True)
CERTS.mkdir(parents=True, exist_ok=True)
(PRIVATE / (name + ".key")).write_bytes(key.private_bytes(
serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL,
serialization.NoEncryption()))
(CERTS / (name + ".crt")).write_bytes(cert.public_bytes(serialization.Encoding.PEM))
def make_ca(common_name="mtusi-lab7-local-ca", filename="ca"):
key = new_key()
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, common_name)])
cert = (x509.CertificateBuilder()
.subject_name(name).issuer_name(name).public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(dt.datetime.now(dt.timezone.utc) - dt.timedelta(minutes=5))
.not_valid_after(dt.datetime.now(dt.timezone.utc) + dt.timedelta(days=DAYS))
.add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True)
.add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()), critical=False)
.add_extension(x509.KeyUsage(
digital_signature=True, content_commitment=False, key_encipherment=False,
data_encipherment=False, key_agreement=False, key_cert_sign=True,
crl_sign=True, encipher_only=False, decipher_only=False), critical=True)
.sign(key, hashes.SHA256()))
save(key, cert, filename)
return key, cert
def leaf(ca_key, ca_cert, name, dns, ips=(), client=False, server=True):
key = new_key()
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, name)])
builder = (x509.CertificateBuilder()
.subject_name(subject).issuer_name(ca_cert.subject)
.public_key(key.public_key()).serial_number(x509.random_serial_number())
.not_valid_before(dt.datetime.now(dt.timezone.utc) - dt.timedelta(minutes=5))
.not_valid_after(dt.datetime.now(dt.timezone.utc) + dt.timedelta(days=DAYS)))
if server:
builder = builder.add_extension(
x509.SubjectAlternativeName(
[x509.DNSName(d) for d in dns] + [x509.IPAddress(__import__("ipaddress").ip_address(i)) for i in ips]),
critical=False)
eku = []
if server:
eku.append(ExtendedKeyUsageOID.SERVER_AUTH)
if client:
eku.append(ExtendedKeyUsageOID.CLIENT_AUTH)
if eku:
builder = builder.add_extension(x509.ExtendedKeyUsage(eku), critical=False)
builder = builder.add_extension(x509.KeyUsage(
digital_signature=True, content_commitment=False, key_encipherment=True,
data_encipherment=False, key_agreement=False, key_cert_sign=False,
crl_sign=False, encipher_only=False, decipher_only=False), critical=False)
builder = builder.add_extension(
x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()), critical=False)
cert = builder.sign(ca_key, hashes.SHA256())
save(key, cert, name)
def main():
ca_key, ca_cert = make_ca()
# Dedicated issuing CA for the only allowed mesh client identity (the LB).
mesh_key, mesh_cert = make_ca("mtusi-lab7-lb-mesh-ca", "mesh-ca")
specs = [
("ingress", ["localhost", "ingress"], ["127.0.0.1"], True, False),
("api", ["api1", "api2", "api"], [], True, True),
("lb", ["lb"], [], False, True),
("db", ["db"], [], True, False),
("minio", ["minio"], [], True, False),
("redis", ["redis"], [], True, False),
("otel-collector", ["otel-collector"], [], True, False),
("openbao", ["openbao", "localhost"], ["127.0.0.1"], True, False),
]
for name, dns, ips, server, client in specs:
if name == "lb":
leaf(mesh_key, mesh_cert, name, dns, ips, client=client, server=server)
else:
leaf(ca_key, ca_cert, name, dns, ips, client=client, server=server)
print("generated CA and %d leaves in %s (private keys in %s)" % (len(specs), CERTS, PRIVATE))
print("public CA: %s" % (CERTS / "ca.crt"))
if __name__ == "__main__":
main()
+5
View File
@@ -0,0 +1,5 @@
@echo off
cd /d "%~dp0.."
docker compose --env-file .env restart db minio redis api1 api2 worker
docker compose --env-file .env exec -T lb nginx -s reload
exit /b %ERRORLEVEL%
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
set -eu
# Restart business services through the TLS mesh; OpenBao stays unsealed with its volume.
cd "$(dirname "$0")/.."
docker compose restart db minio redis api1 api2 worker
# nginx caches upstream IPs at start; reload after container recreation.
docker compose exec -T lb nginx -s reload
+9
View File
@@ -0,0 +1,9 @@
@echo off
cd /d "%~dp0.."
if "%TARGET_INSTANCE_ID%"=="api1" goto stop
if "%TARGET_INSTANCE_ID%"=="api2" goto stop
echo unknown target instance: %TARGET_INSTANCE_ID% >&2
exit /b 1
:stop
docker compose --env-file .env stop %TARGET_INSTANCE_ID%
exit /b %ERRORLEVEL%
+8
View File
@@ -0,0 +1,8 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
case "$TARGET_INSTANCE_ID" in
api1|api2) docker compose stop "$TARGET_INSTANCE_ID" ;;
*) echo "unknown target instance: $TARGET_INSTANCE_ID" >&2; exit 1 ;;
esac
+8
View File
@@ -0,0 +1,8 @@
@echo off
cd /d "%~dp0.."
if "%~1"=="start" goto start
docker compose --env-file .env stop worker
exit /b %ERRORLEVEL%
:start
docker compose --env-file .env start worker
exit /b %ERRORLEVEL%
+10
View File
@@ -0,0 +1,10 @@
#!/bin/sh
set -eu
# Explicit demo hook: stop or start ONLY the worker.
# Stop: uploads keep returning 202; accepted jobs remain in Redis Streams.
cd "$(dirname "$0")/.."
if [ "${1:-stop}" = "start" ]; then
docker compose start worker
else
docker compose stop worker
fi
+137
View File
@@ -0,0 +1,137 @@
#!/usr/bin/env python3
"""Level-3 negative checks: internal mTLS identity and scoped OpenBao policy."""
import datetime as dt
import json
import ssl
import urllib.error
import urllib.request
from pathlib import Path
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import ExtendedKeyUsageOID, NameOID
ROOT = Path(__file__).resolve().parents[1]
CERTS = ROOT / "certs"
PRIVATE = CERTS / "private"
def https(url, cert=None, key=None, cafile=None, data=None, headers=None, timeout=8, method=None):
context = ssl.create_default_context(cafile=str(cafile or CERTS / "ca.crt"))
if cert:
context.load_cert_chain(str(cert), str(key))
request = urllib.request.Request(
url, data=data, headers=headers or {}, method=method or ("POST" if data is not None else "GET"))
try:
with urllib.request.urlopen(request, context=context, timeout=timeout) as response:
return response.status, response.read(), dict(response.headers)
except urllib.error.HTTPError as exc:
return exc.code, exc.read(), dict(exc.headers)
except (urllib.error.URLError, ssl.SSLError, OSError) as exc:
return 0, str(exc).encode(), {}
def make_rogue_client():
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
ca_key = serialization.load_pem_private_key((PRIVATE / "ca.key").read_bytes(), password=None)
ca_cert = x509.load_pem_x509_certificate((CERTS / "ca.crt").read_bytes())
subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "evil-lb")])
cert = (x509.CertificateBuilder()
.subject_name(subject).issuer_name(ca_cert.subject).public_key(key.public_key())
.serial_number(x509.random_serial_number())
.not_valid_before(dt.datetime.now(dt.timezone.utc) - dt.timedelta(minutes=5))
.not_valid_after(dt.datetime.now(dt.timezone.utc) + dt.timedelta(hours=1))
.add_extension(x509.SubjectAlternativeName([x509.DNSName("evil-lb")]), critical=False)
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.CLIENT_AUTH]), critical=False)
.sign(ca_key, hashes.SHA256()))
(PRIVATE / "rogue-lb.key").write_bytes(key.private_bytes(
serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL,
serialization.NoEncryption()))
(CERTS / "rogue-lb.crt").write_bytes(cert.public_bytes(serialization.Encoding.PEM))
def main():
url = "https://api1:8443/health/ready" # direct API port, bypassing the LB
host_ctx = None
# Resolve api1 through Docker DNS: run checks from the host against published LB
# for lack of DNS, so we use the container network via a temporary helper.
# Here we verify the API's client-cert requirement through the LB's upstream:
# the LB always presents a valid identity; a direct no-cert probe must fail.
status, body, _ = https("https://localhost:8443/health/ready")
assert status == 200, "valid trusted HTTPS failed: %s" % body[:100]
print("TLS OK: trusted CA and hostname accepted")
# Direct API probes are executed inside the api1 container (Docker DNS + network).
import subprocess
script = (
"import ssl,urllib.request;"
"c=ssl.create_default_context(cafile='/certs/ca.crt');"
"print(urllib.request.urlopen('https://api1:8443/health/ready',context=c,timeout=3).status)"
)
result = subprocess.run(
["docker", "compose", "--env-file", ".env", "exec", "-T", "api1", "python", "-c", script],
cwd=str(ROOT), capture_output=True, text=True)
assert result.returncode != 0, "API accepted a client without a certificate"
print("MTLS OK: no client certificate rejected by API")
make_rogue_client()
script = (
"import ssl,urllib.request;"
"c=ssl.create_default_context(cafile='/certs/ca.crt');"
"c.load_cert_chain('/certs/rogue-lb.crt','/certs/private/rogue-lb.key');"
"print(urllib.request.urlopen('https://api1:8443/health/ready',context=c,timeout=3).status)"
)
result = subprocess.run(
["docker", "compose", "--env-file", ".env", "exec", "-T", "api1", "python", "-c", script],
cwd=str(ROOT), capture_output=True, text=True)
assert result.returncode != 0, "API accepted a trusted-CA but unauthorized identity"
print("MTLS OK: trusted-CA but wrong identity rejected by API")
# OpenBao: scoped AppRole may read its own path, not write it or read others.
creds = json.loads((PRIVATE / "bao-approle.json").read_text())
ctx = ssl.create_default_context(cafile=str(CERTS / "ca.crt"))
login = urllib.request.Request(
"https://localhost:8200/v1/auth/approle/login",
data=json.dumps(creds).encode(), headers={"Content-Type": "application/json"}, method="POST")
with urllib.request.urlopen(login, context=ctx, timeout=8) as response:
token = json.loads(response.read())["auth"]["client_token"]
def bao(path, method="GET", body=None):
request = urllib.request.Request(
"https://localhost:8200/v1/" + path,
data=json.dumps(body).encode() if body else None,
headers={"X-Vault-Token": token, "Content-Type": "application/json"}, method=method)
try:
with urllib.request.urlopen(request, context=ctx, timeout=8) as response:
return response.status
except urllib.error.HTTPError as exc:
return exc.code
assert bao("secret/data/messenger/app") == 200
assert bao("secret/data/messenger/other") == 403
assert bao("secret/data/messenger/app", "POST", {"data": {"x": "y"}}) == 403
print("BAO OK: own path readable; write and foreign path denied")
# Login rate limit: the sixth attempt in a minute is rejected with Retry-After.
import base64
import uuid
user = "u_rate_" + uuid.uuid4().hex[:10]
credential = base64.b64encode((user + ":wrong-password-123").encode()).decode()
statuses = []
last_headers = {}
for _ in range(6):
status, _, headers = https(
"https://localhost:8443/api/v1/auth/sessions",
headers={"Authorization": "Basic " + credential}, method="POST",
)
statuses.append(status)
last_headers = headers
assert statuses[:5] == [401] * 5, "unexpected login statuses: %s" % statuses
retry_after = next((v for k, v in last_headers.items() if k.lower() == "retry-after"), None)
assert statuses[5] == 429 and retry_after, "429/Retry-After missing"
print("RATE OK: 5x401 then 429 with Retry-After=%s" % retry_after)
if __name__ == "__main__":
main()
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env python3
"""Verify that all three telemetry signals are really stored and queryable."""
import base64
import json
import time
import urllib.parse
import urllib.request
def get(url, headers=None):
req = urllib.request.Request(url, headers=headers or {})
with urllib.request.urlopen(req, timeout=15) as response:
return json.loads(response.read().decode())
def main():
# 1. Metrics: real low-cardinality HTTP and job metrics from the Collector.
prom = get("http://localhost:9090/api/v1/query?query=" +
urllib.parse.quote("http_server_requests_total"))["data"]["result"]
assert prom, "no http_server_requests_total series"
assert any("http_route" in s["metric"] for s in prom), "route label missing"
jobs = get("http://localhost:9090/api/v1/query?query=" +
urllib.parse.quote("messenger_jobs_total"))["data"]["result"]
assert jobs, "no messenger_jobs_total series"
print("METRICS OK: http series=%d, job series=%d" % (len(prom), len(jobs)))
# 2. Logs: structured OTLP records with trace/span IDs for an API request.
now = int(time.time() * 1e9)
query = urllib.parse.quote('{job=~"messenger-.*"} |= "message.created"')
logs = get("http://localhost:3100/loki/api/v1/query_range?query=%s&start=%d&end=%d&limit=3"
% (query, now - 30 * 60 * 10**9, now + 30 * 60 * 10**9))["data"]["result"]
assert logs, "no API logs in Loki"
line = logs[0]["values"][0][1]
assert "traceid" in line and "spanid" in line, "trace/span IDs missing from log"
print("LOGS OK: job=%s, traceid/spanid present" % logs[0]["stream"]["job"])
# 3. Traces: real API and worker spans in Tempo.
api = get("http://localhost:3200/api/search?tags=service.name%3Dmessenger-api&limit=3")["traces"]
worker = get("http://localhost:3200/api/search?tags=service.name%3Dmessenger-worker&limit=3")["traces"]
assert api and worker, "missing API or worker traces"
print("TRACES OK: api=%d, worker-linked=%d" % (len(api), len(worker)))
# 4. Grafana provisioning: datasources and an imported dashboard.
auth = {"Authorization": "Basic " + base64.b64encode(b"admin:admin-local-only").decode()}
sources = get("http://localhost:3000/api/datasources", auth)
boards = get("http://localhost:3000/api/search?type=dash-db", auth)
assert len(sources) >= 3, "datasources not provisioned"
assert any(b["uid"] == "messenger-lab6" for b in boards), "dashboard not provisioned"
print("GRAFANA OK: datasources=%d, dashboard=messenger-lab6" % len(sources))
if __name__ == "__main__":
main()