Implement lab 7 security and mTLS
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Skeleton contracts / contracts (pull_request) Blocked by required conditions
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Create local-only CA and HTTPS certificate for the lab7 demo."""
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
CERTS = ROOT / "certs"
|
||||
|
||||
def run(*args):
|
||||
subprocess.run(args, cwd=CERTS, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
def main():
|
||||
CERTS.mkdir(exist_ok=True)
|
||||
if (CERTS / "ca.crt").exists() and not (CERTS / "redis.crt").exists():
|
||||
(CERTS / "redis.ext").write_text("subjectAltName=DNS:redis\nextendedKeyUsage=serverAuth\n", encoding="utf-8")
|
||||
run("openssl", "genrsa", "-out", "redis.key", "2048")
|
||||
run("openssl", "req", "-new", "-key", "redis.key", "-subj", "/CN=redis", "-out", "redis.csr")
|
||||
run("openssl", "x509", "-req", "-in", "redis.csr", "-CA", "ca.crt", "-CAkey", "ca.key", "-CAcreateserial", "-out", "redis.crt", "-days", "90", "-sha256", "-extfile", "redis.ext")
|
||||
(CERTS / "redis.csr").unlink()
|
||||
(CERTS / "redis.ext").unlink()
|
||||
for path in CERTS.glob("*.srl"):
|
||||
path.unlink()
|
||||
if (CERTS / "ca.crt").exists() and not (CERTS / "redis-health-client.crt").exists():
|
||||
(CERTS / "redis-client.ext").write_text("extendedKeyUsage=clientAuth\n", encoding="utf-8")
|
||||
run("openssl", "genrsa", "-out", "redis-health-client.key", "2048")
|
||||
run("openssl", "req", "-new", "-key", "redis-health-client.key", "-subj", "/CN=redis-health", "-out", "redis-health-client.csr")
|
||||
run("openssl", "x509", "-req", "-in", "redis-health-client.csr", "-CA", "ca.crt", "-CAkey", "ca.key", "-CAcreateserial", "-out", "redis-health-client.crt", "-days", "90", "-sha256", "-extfile", "redis-client.ext")
|
||||
(CERTS / "redis-health-client.csr").unlink()
|
||||
(CERTS / "redis-client.ext").unlink()
|
||||
for path in CERTS.glob("*.srl"):
|
||||
path.unlink()
|
||||
if (CERTS / "server.crt").exists() and (CERTS / "api1.crt").exists() and (CERTS / "collector.crt").exists() and (CERTS / "lb-client.crt").exists() and (CERTS / "redis.crt").exists():
|
||||
print(f"TLS material already exists in {CERTS}")
|
||||
return
|
||||
(CERTS / "server.ext").write_text("subjectAltName=DNS:localhost,IP:127.0.0.1\nextendedKeyUsage=serverAuth\n", encoding="utf-8")
|
||||
run("openssl", "genrsa", "-out", "ca.key", "4096")
|
||||
run("openssl", "req", "-x509", "-new", "-nodes", "-key", "ca.key", "-sha256", "-days", "365", "-subj", "/CN=MTUSI Lab7 Local CA", "-out", "ca.crt")
|
||||
run("openssl", "genrsa", "-out", "server.key", "2048")
|
||||
run("openssl", "req", "-new", "-key", "server.key", "-subj", "/CN=localhost", "-out", "server.csr")
|
||||
run("openssl", "x509", "-req", "-in", "server.csr", "-CA", "ca.crt", "-CAkey", "ca.key", "-CAcreateserial", "-out", "server.crt", "-days", "90", "-sha256", "-extfile", "server.ext")
|
||||
(CERTS / "client.ext").write_text("extendedKeyUsage=clientAuth\n", encoding="utf-8")
|
||||
for name in ("api1", "api2", "collector"):
|
||||
(CERTS / "service.ext").write_text("subjectAltName=DNS:api1,DNS:api2,DNS:messenger_api,DNS:collector,DNS:otel-collector\nextendedKeyUsage=serverAuth\n", encoding="utf-8")
|
||||
run("openssl", "genrsa", "-out", f"{name}.key", "2048")
|
||||
run("openssl", "req", "-new", "-key", f"{name}.key", "-subj", f"/CN={name}", "-out", f"{name}.csr")
|
||||
run("openssl", "x509", "-req", "-in", f"{name}.csr", "-CA", "ca.crt", "-CAkey", "ca.key", "-CAcreateserial", "-out", f"{name}.crt", "-days", "90", "-sha256", "-extfile", "service.ext")
|
||||
for name in ("api1", "api2", "worker"):
|
||||
run("openssl", "genrsa", "-out", f"{name}-client.key", "2048")
|
||||
run("openssl", "req", "-new", "-key", f"{name}-client.key", "-subj", f"/CN={name}", "-out", f"{name}-client.csr")
|
||||
run("openssl", "x509", "-req", "-in", f"{name}-client.csr", "-CA", "ca.crt", "-CAkey", "ca.key", "-CAcreateserial", "-out", f"{name}-client.crt", "-days", "90", "-sha256", "-extfile", "client.ext")
|
||||
run("openssl", "genrsa", "-out", "lb-client.key", "2048")
|
||||
run("openssl", "req", "-new", "-key", "lb-client.key", "-subj", "/CN=lb-client", "-out", "lb-client.csr")
|
||||
run("openssl", "x509", "-req", "-in", "lb-client.csr", "-CA", "ca.crt", "-CAkey", "ca.key", "-CAcreateserial", "-out", "lb-client.crt", "-days", "90", "-sha256", "-extfile", "client.ext")
|
||||
for path in CERTS.glob("*.csr"):
|
||||
path.unlink()
|
||||
for path in CERTS.glob("*.srl"):
|
||||
path.unlink()
|
||||
(CERTS / "server.ext").unlink()
|
||||
(CERTS / "service.ext").unlink()
|
||||
(CERTS / "client.ext").unlink()
|
||||
print(f"Created local CA and server certificate in {CERTS}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Bootstrap local TLS, start the lab7 Compose stack and run public checks."""
|
||||
import argparse, subprocess, time, urllib.request, ssl
|
||||
BASE = "https://127.0.0.1:8443"
|
||||
CA = "certs/ca.crt"
|
||||
def run(*args):
|
||||
print("$", " ".join(args), flush=True); subprocess.run(args, check=True)
|
||||
def ready():
|
||||
ctx = ssl.create_default_context(cafile=CA)
|
||||
for _ in range(120):
|
||||
try:
|
||||
with urllib.request.urlopen(BASE + "/health/ready", context=ctx, timeout=2) as r:
|
||||
if r.status == 200: print("READY", flush=True); return
|
||||
except Exception: time.sleep(1)
|
||||
raise SystemExit("HTTPS API не стал ready")
|
||||
def main():
|
||||
p = argparse.ArgumentParser(); p.add_argument("--full", action="store_true"); p.add_argument("--load", action="store_true"); p.add_argument("--down", action="store_true"); p.add_argument("--no-build", action="store_true"); a = p.parse_args()
|
||||
c = ("docker", "compose", "--env-file", ".env")
|
||||
if a.down: subprocess.run(c + ("down",), check=False); return
|
||||
run("python3", "scripts/bootstrap_tls.py")
|
||||
run(*c, "up", *(()) if a.no_build else ("--build",), "-d")
|
||||
ready(); run("make", "test", "BASE_URL=" + BASE, "CA_FILE=" + CA); run("make", "test-security", "BASE_URL=" + BASE, "CA_FILE=" + CA)
|
||||
if a.full: run("make", "test-persistence", "ACTION_SCRIPT=scripts/restart.sh", "BASE_URL=" + BASE, "CA_FILE=" + CA); run("make", "test-failover", "ACTION_SCRIPT=scripts/stop-one.sh", "BASE_URL=" + BASE, "CA_FILE=" + CA)
|
||||
if a.load: run("python3", "tests/load.py", "--base-url", BASE, "--ca-file", CA, "--duration", "30", "--concurrency", "4")
|
||||
print("Готово. Вручную дополнительно показываются mTLS policy, OpenBao allow/deny и rotation evidence.")
|
||||
if __name__ == "__main__": main()
|
||||
Executable
+26
@@ -0,0 +1,26 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
BAO_ADDR=${BAO_ADDR:-http://127.0.0.1:8200}
|
||||
export BAO_ADDR
|
||||
echo "OpenBao bootstrap. Secrets are printed only to the operator terminal; do not commit them."
|
||||
if ! bao status >/dev/null 2>&1; then
|
||||
echo "OpenBao is unavailable at $BAO_ADDR" >&2; exit 2
|
||||
fi
|
||||
if [ "$(bao status -format=json | sed -n 's/.*\"initialized\":\([a-z]*\).*/\1/p')" = "false" ]; then
|
||||
bao operator init -key-shares=3 -key-threshold=2
|
||||
echo "Save the init output in an external password manager, then unseal with two shares."
|
||||
exit 0
|
||||
fi
|
||||
echo "If sealed, run: bao operator unseal (twice, using different shares)."
|
||||
bao secrets enable -path=secret kv-v2 2>/dev/null || true
|
||||
bao policy write api infra/openbao/policies/api.hcl
|
||||
bao policy write worker infra/openbao/policies/worker.hcl
|
||||
bao auth enable approle 2>/dev/null || true
|
||||
echo "Create short-lived AppRoles and inject only their wrapped secret_ids into the services."
|
||||
echo "Example after authentication:"
|
||||
echo " bao kv put secret/messenger/database_url database_url=..."
|
||||
echo " bao kv put secret/messenger/cache_url cache_url=..."
|
||||
echo " bao kv put secret/messenger/s3_access_key_id s3_access_key_id=..."
|
||||
echo " bao kv put secret/messenger/s3_secret_access_key s3_secret_access_key=..."
|
||||
echo "Then write the scoped token to secrets/openbao_token.txt (chmod 600), set OPENBAO_ENABLED=true and recreate api/worker."
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Rotate one KV value and recreate only the consumers; no image rebuild is needed.
|
||||
VALUE=${1:?usage: openbao_rotation.sh NEW_DATABASE_URL}
|
||||
TOKEN_FILE=${OPENBAO_TOKEN_FILE:-secrets/openbao_token.txt}
|
||||
export BAO_ADDR=${BAO_ADDR:-http://127.0.0.1:8200}
|
||||
export BAO_TOKEN=$(cat "$TOKEN_FILE")
|
||||
bao kv put secret/messenger/database_url database_url="$VALUE" >/dev/null
|
||||
OPENBAO_ENABLED=true docker compose up -d --force-recreate api1 api2 worker >/dev/null
|
||||
echo "PASS: KV value rotated and consumers recreated without rebuilding images"
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Find S3 objects with no matching `attachments` row (e.g. PUT succeeded but
|
||||
the PostgreSQL INSERT that followed it never committed -- a crash between the
|
||||
two writes). Dry-run by default; --delete removes orphans older than the
|
||||
grace period, never anything referenced in the database.
|
||||
|
||||
Usage:
|
||||
python3 scripts/reconcile_attachments.py --grace-minutes 60
|
||||
python3 scripts/reconcile_attachments.py --grace-minutes 60 --delete
|
||||
"""
|
||||
import argparse
|
||||
import asyncio
|
||||
import datetime as dt
|
||||
import os
|
||||
import sys
|
||||
|
||||
import asyncpg
|
||||
import boto3
|
||||
|
||||
|
||||
def read_secret(file_env, inline_env):
|
||||
path = os.environ.get(file_env)
|
||||
if path and os.path.isfile(path):
|
||||
return open(path, encoding="utf-8").read().strip()
|
||||
return os.environ[inline_env]
|
||||
|
||||
|
||||
async def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--grace-minutes", type=int, default=60,
|
||||
help="Only objects older than this are candidates (protects in-flight uploads).")
|
||||
p.add_argument("--delete", action="store_true", help="Actually delete orphans (default: dry-run).")
|
||||
args = p.parse_args()
|
||||
|
||||
database_url = read_secret("DATABASE_URL_FILE", "DATABASE_URL")
|
||||
conn = await asyncpg.connect(database_url)
|
||||
known_keys = {r["s3_key"] for r in await conn.fetch("SELECT s3_key FROM attachments")}
|
||||
await conn.close()
|
||||
|
||||
s3 = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=os.environ["S3_ENDPOINT"],
|
||||
region_name=os.environ.get("S3_REGION", "us-east-1"),
|
||||
aws_access_key_id=read_secret("S3_ACCESS_KEY_ID_FILE", "S3_ACCESS_KEY_ID"),
|
||||
aws_secret_access_key=read_secret("S3_SECRET_ACCESS_KEY_FILE", "S3_SECRET_ACCESS_KEY"),
|
||||
)
|
||||
bucket = os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
cutoff = dt.datetime.now(dt.timezone.utc) - dt.timedelta(minutes=args.grace_minutes)
|
||||
|
||||
orphans = []
|
||||
paginator = s3.get_paginator("list_objects_v2")
|
||||
for page in paginator.paginate(Bucket=bucket, Prefix="attachments/"):
|
||||
for obj in page.get("Contents", []):
|
||||
if obj["Key"] in known_keys:
|
||||
continue
|
||||
if obj["LastModified"] > cutoff:
|
||||
continue # might still be an in-flight upload; not an orphan yet
|
||||
orphans.append(obj["Key"])
|
||||
|
||||
print(f"{len(orphans)} orphaned object(s) older than {args.grace_minutes} minutes with no DB row.")
|
||||
for key in orphans:
|
||||
print(" ", key)
|
||||
if args.delete:
|
||||
s3.delete_object(Bucket=bucket, Key=key)
|
||||
if orphans and args.delete:
|
||||
print(f"Deleted {len(orphans)} orphan(s).")
|
||||
elif orphans:
|
||||
print("Dry-run: nothing deleted. Re-run with --delete to remove them.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(asyncio.run(main()) or 0)
|
||||
Executable
+66
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit operator replay for a failed attachment: resets status to
|
||||
'queued' and republishes a fresh job (new job_id, attempt=1). Never replays
|
||||
an attachment that is already 'ready' -- the same protection the worker
|
||||
itself applies against stale duplicates.
|
||||
|
||||
Usage: python3 scripts/replay_failed.py <attachment-id>
|
||||
"""
|
||||
import asyncio
|
||||
import datetime as dt
|
||||
import os
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
import asyncpg
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from app import broker # noqa: E402
|
||||
|
||||
|
||||
def read_secret(file_env, inline_env):
|
||||
path = os.environ.get(file_env)
|
||||
if path and os.path.isfile(path):
|
||||
return open(path, encoding="utf-8").read().strip()
|
||||
return os.environ[inline_env]
|
||||
|
||||
|
||||
async def main():
|
||||
if len(sys.argv) != 2:
|
||||
print("usage: replay_failed.py <attachment-id>", file=sys.stderr)
|
||||
return 2
|
||||
attachment_id = uuid.UUID(sys.argv[1])
|
||||
|
||||
conn = await asyncpg.connect(read_secret("DATABASE_URL_FILE", "DATABASE_URL"))
|
||||
record = await conn.fetchrow("SELECT status FROM attachments WHERE id=$1", attachment_id)
|
||||
if record is None:
|
||||
print("no such attachment", file=sys.stderr)
|
||||
return 1
|
||||
if record["status"] == "ready":
|
||||
print("attachment is already ready; refusing to replay a finished job")
|
||||
return 0
|
||||
if record["status"] != "failed":
|
||||
print(f"attachment status is '{record['status']}', not 'failed'; nothing to replay")
|
||||
return 0
|
||||
|
||||
job_id = uuid.uuid4()
|
||||
await conn.execute("UPDATE attachments SET status='queued', error_code=NULL, updated_at=now() WHERE id=$1", attachment_id)
|
||||
await conn.close()
|
||||
|
||||
broker.init(read_secret("CACHE_URL_FILE", "CACHE_URL"))
|
||||
job = {
|
||||
"schema_version": 1,
|
||||
"job_id": str(job_id),
|
||||
"type": "attachment.process.v1",
|
||||
"attachment_id": str(attachment_id),
|
||||
"pipeline_version": 1,
|
||||
"attempt": 1,
|
||||
"created_at": dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
await broker.publish(job)
|
||||
print(f"replayed attachment {attachment_id} as job {job_id}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(asyncio.run(main()))
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
wait_healthy() {
|
||||
for svc in "$@"; do
|
||||
for _ in $(seq 1 60); do
|
||||
status=$(docker compose ps --format '{{.Health}}' "$svc" 2>/dev/null || true)
|
||||
[ "$status" = "healthy" ] && break
|
||||
sleep 1
|
||||
done
|
||||
done
|
||||
}
|
||||
|
||||
docker compose restart postgres redis seaweedfs
|
||||
wait_healthy postgres redis seaweedfs
|
||||
|
||||
docker compose restart otel-collector prometheus loki tempo grafana
|
||||
|
||||
docker compose restart api1 api2
|
||||
wait_healthy api1 api2
|
||||
|
||||
docker compose restart worker
|
||||
docker compose restart lb
|
||||
exit 0
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Rotation is deliberately operator-driven: no root token is stored in the repo.
|
||||
CERT_DIR=${CERT_DIR:-certs}
|
||||
SERVICE=${1:-api1}
|
||||
test -f "$CERT_DIR/ca.key" || { echo "CA key is missing" >&2; exit 2; }
|
||||
umask 077
|
||||
openssl genrsa -out "$CERT_DIR/$SERVICE-client.key.new" 2048
|
||||
openssl req -new -key "$CERT_DIR/$SERVICE-client.key.new" -subj "/CN=$SERVICE" -out "$CERT_DIR/$SERVICE-client.csr.new"
|
||||
printf 'extendedKeyUsage=clientAuth\n' > "$CERT_DIR/client.ext.new"
|
||||
openssl x509 -req -in "$CERT_DIR/$SERVICE-client.csr.new" -CA "$CERT_DIR/ca.crt" -CAkey "$CERT_DIR/ca.key" -CAcreateserial -out "$CERT_DIR/$SERVICE-client.crt.new" -days 30 -sha256 -extfile "$CERT_DIR/client.ext.new"
|
||||
mv "$CERT_DIR/$SERVICE-client.key.new" "$CERT_DIR/$SERVICE-client.key"
|
||||
mv "$CERT_DIR/$SERVICE-client.crt.new" "$CERT_DIR/$SERVICE-client.crt"
|
||||
rm -f "$CERT_DIR/$SERVICE-client.csr.new" "$CERT_DIR/client.ext.new" "$CERT_DIR/ca.srl"
|
||||
echo "Rotated $SERVICE client certificate. Restart only that service and revoke the previous identity in the CA/OpenBao registry."
|
||||
Executable
+23
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Small operator-facing negative checks for the level-4 defense."""
|
||||
import ssl, socket, urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
CA = ROOT / "certs/ca.crt"
|
||||
|
||||
def main():
|
||||
ctx = ssl.create_default_context(cafile=str(CA))
|
||||
with urllib.request.urlopen("https://localhost:8443/health/ready", context=ctx, timeout=5) as r:
|
||||
assert r.status in (200, 503)
|
||||
raw = socket.create_connection(("127.0.0.1", 8443), 3)
|
||||
try:
|
||||
raw.sendall(b"GET /health/ready HTTP/1.1\r\nHost: localhost\r\n\r\n")
|
||||
data = raw.recv(128)
|
||||
assert not data.startswith(b"HTTP/1.1 200")
|
||||
finally:
|
||||
raw.close()
|
||||
print("PASS: trusted HTTPS works and plaintext external access is rejected")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+12
@@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# Stops exactly the API replica identified by TARGET_INSTANCE_ID (api1 or api2),
|
||||
# leaving it stopped. The other replica keeps serving traffic through the LB.
|
||||
cd "$(dirname "$0")/.."
|
||||
: "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID must be set by the test harness}"
|
||||
case "$TARGET_INSTANCE_ID" in
|
||||
api1|api2) ;;
|
||||
*) echo "unknown instance id: $TARGET_INSTANCE_ID" >&2; exit 1 ;;
|
||||
esac
|
||||
docker compose stop "$TARGET_INSTANCE_ID"
|
||||
exit 0
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
export BAO_ADDR=${BAO_ADDR:-http://127.0.0.1:8200}
|
||||
docker compose exec -T openbao bao operator seal >/dev/null
|
||||
if docker compose exec -T api1 python -c 'import urllib.request; urllib.request.urlopen("https://127.0.0.1:8080/health/ready", context=__import__("ssl")._create_unverified_context(), timeout=3)' >/dev/null 2>&1; then
|
||||
echo "FAIL: API remained ready while OpenBao was sealed"; exit 1
|
||||
fi
|
||||
echo "PASS: API is unavailable while OpenBao is sealed"
|
||||
echo "Unseal with two operator keys before continuing the defense."
|
||||
Reference in New Issue
Block a user