ЛР 7: TLS, mTLS, OpenBao и безопасность — на 3
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,113 @@
|
||||
"""Local operator-only OpenBao initialization and manual unseal on Windows."""
|
||||
import argparse
|
||||
import json
|
||||
import ssl
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
PRIVATE = Path("secrets")
|
||||
RECOVERY = PRIVATE / "operator" / "openbao.dpapi"
|
||||
ADDRESS = "https://localhost:8200"
|
||||
DPAPI = """
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Add-Type -AssemblyName System.Security
|
||||
$bytes = [Convert]::FromBase64String([Console]::In.ReadToEnd())
|
||||
$result = [Security.Cryptography.ProtectedData]::ACTION(
|
||||
$bytes, $null, [Security.Cryptography.DataProtectionScope]::CurrentUser)
|
||||
[Console]::Write([Convert]::ToBase64String($result))
|
||||
"""
|
||||
|
||||
|
||||
def protect(data, action):
|
||||
import base64
|
||||
|
||||
proc = subprocess.run(
|
||||
["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", DPAPI.replace("ACTION", action)],
|
||||
input=base64.b64encode(data), capture_output=True, check=True,
|
||||
)
|
||||
return base64.b64decode(proc.stdout, validate=True)
|
||||
|
||||
|
||||
def request(path, method="GET", payload=None, token=None):
|
||||
context = ssl.create_default_context(cafile=PRIVATE / "ca/server.crt")
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}),
|
||||
urllib.request.HTTPSHandler(context=context))
|
||||
req = urllib.request.Request(ADDRESS + "/v1/" + path,
|
||||
data=None if payload is None else json.dumps(payload).encode(),
|
||||
headers=headers, method=method)
|
||||
try:
|
||||
with opener.open(req, timeout=5) as response:
|
||||
body = response.read()
|
||||
except urllib.error.HTTPError as exc:
|
||||
raise RuntimeError(f"OpenBao {method} {path} returned HTTP {exc.code}") from None
|
||||
return json.loads(body) if body else {}
|
||||
|
||||
|
||||
def seal_status():
|
||||
for attempt in range(20):
|
||||
try:
|
||||
return request("sys/seal-status")
|
||||
except (urllib.error.URLError, OSError):
|
||||
if attempt == 19:
|
||||
raise RuntimeError("OpenBao TLS listener is unavailable") from None
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def configure(token):
|
||||
if "lab7/" not in request("sys/mounts", token=token):
|
||||
request("sys/mounts/lab7", "POST", {"type": "kv", "options": {"version": "2"}}, token)
|
||||
if "cert/" not in request("sys/auth", token=token):
|
||||
request("sys/auth/cert", "POST", {"type": "cert"}, token)
|
||||
cert_ca = (PRIVATE / "ca/bao.crt").read_text(encoding="ascii")
|
||||
for role in ("api", "worker"):
|
||||
policy = f"lab7-{role}"
|
||||
request(f"sys/policies/acl/{policy}", "PUT",
|
||||
{"policy": Path(f"infra/openbao/{role}.hcl").read_text(encoding="ascii")}, token)
|
||||
request(f"auth/cert/certs/{role}", "POST", {
|
||||
"certificate": cert_ca, "allowed_dns_sans": [f"bao-{role}"],
|
||||
"token_policies": [policy], "token_no_default_policy": True,
|
||||
"token_ttl": 300, "token_max_ttl": 300,
|
||||
}, token)
|
||||
data = json.loads((PRIVATE / f"bao-seed/{role}.json").read_bytes())
|
||||
request(f"lab7/data/{role}", "POST", {"data": data}, token)
|
||||
print("PASS: persistent KV v2, independent certificate auth, scoped policies, 300s max TTL")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("action", choices=("bootstrap", "unseal", "status"))
|
||||
args = parser.parse_args()
|
||||
status = seal_status()
|
||||
print(f"OpenBao {status['version']}: initialized={status['initialized']} sealed={status['sealed']}")
|
||||
if args.action == "status":
|
||||
return
|
||||
if not status["initialized"]:
|
||||
if args.action != "bootstrap" or RECOVERY.exists():
|
||||
raise SystemExit("Use explicit bootstrap with matching local operator state")
|
||||
RECOVERY.parent.mkdir(parents=True, exist_ok=True)
|
||||
# Verify local DPAPI before creating operator material.
|
||||
probe = b"lab7"
|
||||
if protect(protect(probe, "Protect"), "Unprotect") != probe:
|
||||
raise RuntimeError("DPAPI self-check failed")
|
||||
recovery = request("sys/init", "PUT", {"secret_shares": 3, "secret_threshold": 2})
|
||||
RECOVERY.write_bytes(protect(json.dumps(recovery).encode(), "Protect"))
|
||||
print("PASS: initialized file storage, 2-of-3 shares encrypted for local Windows operator")
|
||||
recovery = json.loads(protect(RECOVERY.read_bytes(), "Unprotect"))
|
||||
if status["sealed"]:
|
||||
for share in recovery["keys_base64"][:2]:
|
||||
result = request("sys/unseal", "PUT", {"key": share})
|
||||
if result["sealed"]:
|
||||
raise RuntimeError("Unseal did not finish")
|
||||
print("PASS: operator unseal completed")
|
||||
if args.action == "bootstrap":
|
||||
configure(recovery["root_token"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+28
@@ -0,0 +1,28 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
export HOME=/tmp
|
||||
export SSL_CERT_FILE=/run/ca/server.crt
|
||||
export AWS_CA_BUNDLE=/run/ca/server.crt
|
||||
mkdir -p /tmp/.config
|
||||
bucket=lab7/messenger-attachments
|
||||
run() {
|
||||
step=$1
|
||||
shift
|
||||
if ! "$@" >/dev/null 2>&1; then
|
||||
echo "RustFS bootstrap step failed: $step" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
run alias rc alias set lab7 https://s3:9000 "$(cat /run/admin/access)" "$(cat /run/admin/password)"
|
||||
buckets=$(rc bucket list lab7 --json)
|
||||
if ! printf '%s' "$buckets" | python -c 'import json,sys; sys.exit(not any(i["key"]=="messenger-attachments" for i in json.load(sys.stdin)["items"]))'; then
|
||||
run bucket rc mb "$bucket"
|
||||
fi
|
||||
run private rc bucket anonymous set private "$bucket"
|
||||
printf 'ready\n' | run readiness rc pipe "$bucket/health/ready"
|
||||
for role in api worker; do
|
||||
run "create-$role" rc admin user add lab7/ "lab7-$role" "$(cat "/run/scoped/$role")"
|
||||
run "policy-$role" rc admin policy create lab7/ "lab7-$role" "/run/scoped/$role.json"
|
||||
run "attach-$role" rc admin policy attach lab7/ "lab7-$role" --user "lab7-$role"
|
||||
done
|
||||
echo 'PASS: RustFS private bucket and separate scoped identities'
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
: "${LAB7_HOOK_DIR:?run through scripts/test-resilience.ps1}"
|
||||
printf '%s\n' "$1" > "$LAB7_HOOK_DIR/request.tmp"
|
||||
mv "$LAB7_HOOK_DIR/request.tmp" "$LAB7_HOOK_DIR/request"
|
||||
for i in $(seq 1 85); do
|
||||
if [ -f "$LAB7_HOOK_DIR/result" ]; then
|
||||
test "$(cat "$LAB7_HOOK_DIR/result")" = 0
|
||||
exit
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
exit 1
|
||||
@@ -0,0 +1,10 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-Location (Split-Path -Parent $PSScriptRoot)
|
||||
if (!(Test-Path -LiteralPath secrets)) {
|
||||
New-Item -ItemType Directory -Path secrets | Out-Null
|
||||
$identity = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
|
||||
icacls.exe secrets /inheritance:r /grant:r "*${identity}:(OI)(CI)F" "*S-1-5-18:(OI)(CI)F" | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Could not restrict the local private directory' }
|
||||
}
|
||||
py -3 scripts/init_env.py
|
||||
if ($LASTEXITCODE -ne 0) { throw 'PKI/configuration bootstrap failed' }
|
||||
@@ -0,0 +1,188 @@
|
||||
"""Generate persistent local credentials and rendered configs once per project."""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import secrets
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path.cwd()
|
||||
PRIVATE = ROOT / "secrets"
|
||||
BUCKET = "messenger-attachments"
|
||||
|
||||
|
||||
def write(name, text):
|
||||
path = PRIVATE / name
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text, encoding="utf-8", newline="\n")
|
||||
|
||||
|
||||
def encode(name, value):
|
||||
write(name, json.dumps(value, indent=2) + "\n")
|
||||
|
||||
|
||||
def get_or_create(name):
|
||||
path = PRIVATE / name
|
||||
if not path.exists():
|
||||
write(name, secrets.token_hex(24))
|
||||
return path.read_text(encoding="utf-8").strip()
|
||||
|
||||
|
||||
def rabbit_user(name, password):
|
||||
salt = secrets.token_bytes(4)
|
||||
digest = salt + hashlib.sha256(salt + password.encode()).digest()
|
||||
return {
|
||||
"name": name, "password_hash": base64.b64encode(digest).decode(),
|
||||
"hashing_algorithm": "rabbit_password_hashing_sha256", "tags": [],
|
||||
}
|
||||
|
||||
|
||||
def switch(service, port, routes):
|
||||
header = """global
|
||||
ssl-default-bind-options ssl-min-ver TLSv1.2
|
||||
maxconn 64
|
||||
defaults
|
||||
mode http
|
||||
timeout connect 2s
|
||||
timeout client 10s
|
||||
timeout server 10s
|
||||
"""
|
||||
userlist = ""
|
||||
frontend = f"frontend secure\n bind :{port} ssl crt /run/tls/server.pem\n"
|
||||
backends = ""
|
||||
for role, username, password, method, paths, local_port in routes:
|
||||
userlist += f"userlist {role}\n user {username} insecure-password {password}\n"
|
||||
frontend += (
|
||||
f" acl {role}_method method {method}\n"
|
||||
f" acl {role}_path {paths}\n"
|
||||
f" use_backend {role} if {role}_method {role}_path {{ http_auth({role}) }}\n"
|
||||
)
|
||||
backends += (
|
||||
f"backend {role}\n http-request del-header Authorization\n"
|
||||
f" server local 127.0.0.1:{local_port}\n"
|
||||
)
|
||||
backends += "backend rejected\n http-request deny deny_status 403\n"
|
||||
write(f"generated/{service}.cfg", header + userlist + frontend + " default_backend rejected\n" + backends)
|
||||
|
||||
|
||||
def telemetry(api, worker, collector, grafana):
|
||||
switch("otel-collector", 4318, [
|
||||
(role, role, value, "POST", "path /v1/metrics /v1/logs /v1/traces", 14318)
|
||||
for role, value in (("api", api), ("worker", worker))
|
||||
])
|
||||
backends = [
|
||||
("prometheus", 9090, "/api/v1/write", 19090, 19090,
|
||||
"/api/v1/query /api/v1/label /api/v1/series /api/v1/metadata /-/ready"),
|
||||
("loki", 3100, "/otlp/v1/logs", 13100, 13100,
|
||||
"/loki/api/v1/query /loki/api/v1/label /loki/api/v1/series /loki/api/v1/index/stats /ready"),
|
||||
("tempo", 3200, "/v1/traces", 14318, 13200,
|
||||
"/api/traces /api/v2/traces /api/search /api/echo /api/metrics /ready"),
|
||||
]
|
||||
ca = (PRIVATE / "ca/server.crt").read_text(encoding="ascii")
|
||||
sources = []
|
||||
for service, port, ingest_path, ingest_port, query_port, query_paths in backends:
|
||||
switch(service, port, [
|
||||
("ingest", "collector", collector, "POST", f"path {ingest_path}", ingest_port),
|
||||
("query", "grafana", grafana, "GET POST", f"path_beg {query_paths}", query_port),
|
||||
])
|
||||
source = {
|
||||
"name": service.title(), "uid": f"lab6-{service}", "type": service, "access": "proxy",
|
||||
"url": f"https://{service}:{port}", "isDefault": service == "prometheus", "editable": False,
|
||||
"basicAuth": True, "basicAuthUser": "grafana",
|
||||
"jsonData": {"tlsAuthWithCACert": True},
|
||||
"secureJsonData": {"basicAuthPassword": grafana, "tlsCACert": ca},
|
||||
}
|
||||
if service == "prometheus":
|
||||
source["jsonData"]["timeInterval"] = "5s"
|
||||
if service == "loki":
|
||||
source["jsonData"]["derivedFields"] = [{
|
||||
"name": "Trace", "matcherType": "label", "matcherRegex": "trace_id",
|
||||
"datasourceUid": "lab6-tempo", "url": "$${__value.raw}",
|
||||
}]
|
||||
sources.append(source)
|
||||
encode("generated/datasources.json", {"apiVersion": 1, "datasources": sources})
|
||||
basic = base64.b64encode(f"collector:{collector}".encode()).decode()
|
||||
base = {"tls": {"ca_file": "/run/ca/server.crt"}, "headers": {"Authorization": f"Basic {basic}"}}
|
||||
exporters = {
|
||||
"prometheusremotewrite": {**base, "endpoint": "https://prometheus:9090/api/v1/write",
|
||||
"resource_to_telemetry_conversion": {"enabled": True}},
|
||||
"otlphttp/loki": {**base, "endpoint": "https://loki:3100/otlp"},
|
||||
"otlphttp/tempo": {**base, "endpoint": "https://tempo:3200"},
|
||||
}
|
||||
encode("generated/collector.json", {
|
||||
"receivers": {"otlp": {"protocols": {"http": {"endpoint": "127.0.0.1:14318"}}}},
|
||||
"processors": {"memory_limiter": {"check_interval": "1s", "limit_mib": 128, "spike_limit_mib": 32},
|
||||
"batch": {"timeout": "1s", "send_batch_size": 256, "send_batch_max_size": 512}},
|
||||
"exporters": exporters,
|
||||
"service": {"telemetry": {"metrics": {"level": "none"}}, "pipelines": {
|
||||
signal: {"receivers": ["otlp"], "processors": ["memory_limiter", "batch"], "exporters": [exporter]}
|
||||
for signal, exporter in zip(("metrics", "logs", "traces"), exporters)
|
||||
}},
|
||||
})
|
||||
|
||||
|
||||
def policy(grants):
|
||||
return {"Version": "2012-10-17", "Statement": [
|
||||
{"Effect": "Allow", "Action": [f"s3:{op}" for op in actions],
|
||||
"Resource": [f"arn:aws:s3:::{BUCKET}/{prefix}" for prefix in prefixes]}
|
||||
for actions, prefixes in grants
|
||||
]}
|
||||
|
||||
|
||||
def main():
|
||||
if not (PRIVATE / "ca/public.crt").exists():
|
||||
subprocess.run([
|
||||
"docker", "run", "--rm", "--network", "none",
|
||||
"-v", f"{PRIVATE}:/private", "-v", f"{ROOT / 'scripts/pki.sh'}:/pki.sh:ro",
|
||||
"--entrypoint", "sh", "postgres:16.8-bookworm", "/pki.sh",
|
||||
], check=True)
|
||||
if not (ROOT / ".env").exists():
|
||||
(ROOT / ".env").write_bytes((ROOT / ".env.example").read_bytes())
|
||||
get_or_create("postgres/pg_admin")
|
||||
get_or_create("grafana/password")
|
||||
write("s3-admin/access", "lab7-bootstrap")
|
||||
get_or_create("s3-admin/password")
|
||||
api_otel, worker_otel, collector, grafana = (
|
||||
get_or_create(f"telemetry/{role}") for role in ("api", "worker", "collector", "grafana")
|
||||
)
|
||||
telemetry(api_otel, worker_otel, collector, grafana)
|
||||
passwords = {}
|
||||
for role in ("api", "worker", "migrate"):
|
||||
pg = get_or_create(f"postgres/pg_{role}")
|
||||
dsn = f"postgresql://lab_{role}:{pg}@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/run/ca/server.crt"
|
||||
if role == "migrate":
|
||||
write("postgres/pg_url", dsn)
|
||||
continue
|
||||
amqp = passwords[f"lab_{role}"] = get_or_create(f"broker/{role}")
|
||||
s3_password = get_or_create(f"s3/{role}")
|
||||
encode(f"bao-seed/{role}.json", {
|
||||
"DATABASE_URL": dsn, "BROKER_URL": f"amqps://lab_{role}:{amqp}@broker:5671/jobs",
|
||||
"S3_ACCESS_KEY_ID": f"lab7-{role}", "S3_SECRET_ACCESS_KEY": s3_password,
|
||||
"OTEL_LOGIN": f"{role}:{api_otel if role == 'api' else worker_otel}",
|
||||
})
|
||||
encode("generated/definitions.json", {
|
||||
"users": [rabbit_user(name, password) for name, password in passwords.items()],
|
||||
"vhosts": [{"name": "jobs"}],
|
||||
"permissions": [
|
||||
{"user": name, "vhost": "jobs", "configure": "^$", "write": "^amq\\.default$",
|
||||
"read": "^attachment\\.process\\.v1$" if name == "lab_worker" else "^$"}
|
||||
for name in passwords
|
||||
],
|
||||
"queues": [
|
||||
{"name": "attachment.process.v1", "vhost": "jobs", "durable": True,
|
||||
"auto_delete": False, "arguments": {"x-queue-type": "classic"}},
|
||||
],
|
||||
})
|
||||
encode("s3/api.json", policy([
|
||||
(["PutObject"], ["staging/*"]),
|
||||
(["GetObject"], ["health/ready", "originals/*", "variants/*"]),
|
||||
]))
|
||||
encode("s3/worker.json", policy([
|
||||
(["GetObject", "DeleteObject"], ["staging/*"]),
|
||||
(["PutObject"], ["originals/*", "variants/*"]),
|
||||
]))
|
||||
print("Local PKI and scoped service configuration ready (values withheld).")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+42
@@ -0,0 +1,42 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd /private
|
||||
umask 077
|
||||
mkdir -p roots ca pki
|
||||
root() {
|
||||
openssl req -x509 -newkey rsa:3072 -nodes -sha256 -days 365 \
|
||||
-subj "/CN=MTUSI Lab7 $1" -addext 'basicConstraints=critical,CA:TRUE,pathlen:0' \
|
||||
-addext 'keyUsage=critical,keyCertSign,cRLSign' -keyout "roots/$1.key" -out "ca/$1.crt" >/dev/null 2>&1
|
||||
}
|
||||
leaf() {
|
||||
name=$1 issuer=$2 subject=$3 usage=$4 san=$5
|
||||
mkdir -p "pki/$name"
|
||||
openssl req -new -newkey rsa:2048 -nodes -subj "/CN=$subject" \
|
||||
-keyout "pki/$name/$usage.key" -out roots/leaf.csr >/dev/null 2>&1
|
||||
printf 'subjectAltName=%s\nextendedKeyUsage=%sAuth\nkeyUsage=critical,digitalSignature,keyEncipherment\nbasicConstraints=critical,CA:FALSE\n' \
|
||||
"$san" "$usage" > roots/leaf.ext
|
||||
openssl x509 -req -in roots/leaf.csr -CA "ca/$issuer.crt" -CAkey "roots/$issuer.key" -CAcreateserial \
|
||||
-CAserial "roots/$issuer.srl" -days 90 -sha256 -extfile roots/leaf.ext \
|
||||
-out "pki/$name/$usage.crt" >/dev/null 2>&1
|
||||
cat "pki/$name/$usage.crt" "pki/$name/$usage.key" > "pki/$name/$usage.pem"
|
||||
# Each bind exposes only one service's files. The outer NTFS ACL controls host access.
|
||||
chmod 0644 "pki/$name/"*
|
||||
}
|
||||
for ca_type in public server client bao unrelated; do root "$ca_type"; done
|
||||
leaf lb public localhost server DNS:localhost,IP:127.0.0.1
|
||||
for service in api1 api2 postgres s3 broker otel-collector prometheus loki tempo; do
|
||||
leaf "$service" server "$service" server "DNS:$service"
|
||||
done
|
||||
for service in openbao grafana; do
|
||||
leaf "$service" server "$service" server "DNS:$service,DNS:localhost,IP:127.0.0.1"
|
||||
done
|
||||
leaf lb-client client lb-client client DNS:lb-client
|
||||
leaf wrong-san client other-client client DNS:other-client
|
||||
leaf wrong-ca unrelated lb-client client DNS:lb-client
|
||||
leaf bao-api bao bao-api client DNS:bao-api
|
||||
leaf bao-worker bao bao-worker client DNS:bao-worker
|
||||
cp pki/s3/server.crt pki/s3/rustfs_cert.pem
|
||||
cp pki/s3/server.key pki/s3/rustfs_key.pem
|
||||
chmod 0755 ca pki pki/*
|
||||
chmod 0644 ca/*.crt pki/s3/rustfs_*.pem
|
||||
rm -f roots/leaf.csr roots/leaf.ext
|
||||
Executable
+3
@@ -0,0 +1,3 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
exec "$(dirname "$0")/compose-hook.sh" restart
|
||||
@@ -0,0 +1,115 @@
|
||||
"""Build and verify an exact review snapshot of public working-tree files."""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
from bao_operator import RECOVERY, protect
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
EVIDENCE = ROOT / "evidence" / "grade3"
|
||||
OMIT = {"PR_GRADE3_DRAFT.md"}
|
||||
PRIVATE_DIRS = {".git", "secrets", "certs", "volumes", "data", "backups", ".venv",
|
||||
"__pycache__", "dist", "build", "node_modules"}
|
||||
PRIVATE_SUFFIXES = {".key", ".pem", ".crt", ".p12", ".pfx", ".dpapi", ".zip", ".pyc", ".log"}
|
||||
SECRET_PATTERNS = re.compile(rb"-----BEGIN [A-Z ]*PRIVATE KEY-----|(?i:Bearer )[A-Za-z0-9_-]{43}\b")
|
||||
MODES = {".sh": 0o100755}
|
||||
|
||||
|
||||
def git(*args):
|
||||
return subprocess.check_output(["git", *args], cwd=ROOT)
|
||||
|
||||
|
||||
def names(*args):
|
||||
return {p.decode("utf-8") for p in git(*args).split(b"\0") if p}
|
||||
|
||||
|
||||
def public_files():
|
||||
paths = names("ls-files", "--cached", "--others", "--exclude-standard", "-z") - OMIT
|
||||
for path in sorted(paths):
|
||||
relative = Path(path)
|
||||
file = ROOT / relative
|
||||
if set(relative.parts) & PRIVATE_DIRS or relative.suffix.lower() in PRIVATE_SUFFIXES:
|
||||
raise RuntimeError(f"Private/build candidate in archive list: {path}")
|
||||
if relative.name.startswith(".env") and relative.name != ".env.example":
|
||||
raise RuntimeError(f"Private environment file selected: {path}")
|
||||
if file.is_symlink() or not file.is_file() or not file.resolve().is_relative_to(ROOT):
|
||||
raise RuntimeError(f"Unexpected filesystem path: {path}")
|
||||
yield path, file
|
||||
|
||||
|
||||
def runtime_secrets():
|
||||
private = ROOT / "secrets"
|
||||
paths = [*private.glob("postgres/pg_*"), *private.glob("s3/*"),
|
||||
*private.glob("broker/*"), *private.glob("telemetry/*"),
|
||||
private / "s3-admin/password", private / "grafana/password"]
|
||||
values = {p.read_bytes().strip() for p in paths if p.is_file() and p.suffix != ".json"}
|
||||
for role in ("api", "worker", "collector", "grafana"):
|
||||
value = (private / "telemetry" / role).read_bytes().strip()
|
||||
values.add(base64.b64encode(role.encode() + b":" + value))
|
||||
if RECOVERY.exists():
|
||||
recovery = json.loads(protect(RECOVERY.read_bytes(), "Unprotect"))
|
||||
values.update(s.encode() for s in (*recovery["keys"], *recovery["keys_base64"], recovery["root_token"]))
|
||||
return {value for value in values if len(value) >= 20}
|
||||
|
||||
|
||||
def scan(files, secrets):
|
||||
for name, data in files:
|
||||
if SECRET_PATTERNS.search(data) or any(secret in data for secret in secrets):
|
||||
raise RuntimeError(f"Secret signature in {name} (value withheld)")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("archive", type=Path)
|
||||
output = parser.parse_args().archive.resolve()
|
||||
if output.is_relative_to(ROOT):
|
||||
raise SystemExit("Choose an archive destination outside the checkout")
|
||||
secrets = runtime_secrets()
|
||||
files = list(public_files())
|
||||
scan(((name, path.read_bytes()) for name, path in files), secrets)
|
||||
runtime = subprocess.check_output(["docker", "compose", "--project-name", "mtusi-lab7-grade3", "logs",
|
||||
"--no-color"], cwd=ROOT, stderr=subprocess.STDOUT)
|
||||
scan([("Compose logs", runtime)], secrets)
|
||||
(EVIDENCE / "secrets-scan.txt").write_text(
|
||||
f"PASS: public artifact bytes and project Compose logs checked against {len(secrets)} local secret literals "
|
||||
"and private-key/Bearer patterns. No matches.\n", encoding="utf-8",
|
||||
)
|
||||
files = list(public_files())
|
||||
metadata = []
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=8) as archive:
|
||||
for name, path in files:
|
||||
data = path.read_bytes()
|
||||
spec = zipfile.ZipInfo(name)
|
||||
spec.create_system = 3
|
||||
mode = MODES.get(path.suffix, 0o100644)
|
||||
spec.external_attr = mode << 16
|
||||
spec.compress_type = zipfile.ZIP_DEFLATED
|
||||
if mode == 0o100755 and ".example." not in name:
|
||||
assert b"\r" not in data and data.startswith(b"#!/"), name
|
||||
archive.writestr(spec, data, compresslevel=8)
|
||||
metadata.append({"file": name, "sha256": hashlib.sha256(data).hexdigest(), "mode": oct(mode)[2:]})
|
||||
with zipfile.ZipFile(output) as archive, tempfile.TemporaryDirectory(prefix="lab7-zip-") as directory:
|
||||
assert archive.testzip() is None
|
||||
archive.extractall(directory)
|
||||
assert sorted(archive.namelist()) == sorted(name for name, _ in files)
|
||||
for name, path in files:
|
||||
assert (Path(directory) / name).read_bytes() == path.read_bytes()
|
||||
assert archive.getinfo(name).external_attr >> 16 == MODES.get(path.suffix, 0o100644)
|
||||
changes = (names("diff", "--name-only", "-z") |
|
||||
names("ls-files", "--others", "--exclude-standard", "-z")) - OMIT
|
||||
payload = {"archive": output.name, "sha256": hashlib.sha256(output.read_bytes()).hexdigest(),
|
||||
"files": len(files), "crc": "PASS", "unzip_byte_comparison": "PASS", "manifest": metadata}
|
||||
output.with_suffix(".manifest.json").write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
|
||||
output.with_suffix(".staging.txt").write_text("\n".join(sorted(changes)) + "\n", encoding="utf-8")
|
||||
print(json.dumps({k: v for k, v in payload.items() if k != "manifest"}))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Read the Compose runtime configuration without exporting environment values."""
|
||||
import hashlib
|
||||
import json
|
||||
import ssl
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PROJECT = "mtusi-lab7-grade3"
|
||||
PUBLICATIONS = {"lb": ("8443/tcp", "8443"), "openbao": ("8200/tcp", "8200"),
|
||||
"grafana": ("3000/tcp", "3443")}
|
||||
APP = {"api1", "api2", "worker"}
|
||||
TARGET = ROOT / "evidence" / "grade3"
|
||||
|
||||
|
||||
def docker(*args):
|
||||
return subprocess.check_output(["docker", *args], cwd=ROOT)
|
||||
|
||||
|
||||
def record_certs():
|
||||
entries = []
|
||||
for cert in sorted((ROOT / "secrets" / "pki").glob("*/*.crt")):
|
||||
details = ssl._ssl._test_decode_cert(str(cert))
|
||||
der = ssl.PEM_cert_to_DER_cert(cert.read_text(encoding="ascii"))
|
||||
entries.append({"role": cert.parent.name, "sans": details.get("subjectAltName", []),
|
||||
"issuer": details["issuer"], "valid_until": details["notAfter"],
|
||||
"sha256": hashlib.sha256(der).hexdigest()})
|
||||
(TARGET / "certificates.json").write_text(json.dumps(entries, indent=2) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def main():
|
||||
ids = docker("ps", "-aq", "--filter", f"label=com.docker.compose.project={PROJECT}",
|
||||
"--filter", "label=com.docker.compose.oneoff=False").decode().splitlines()
|
||||
assert ids
|
||||
containers = json.loads(docker("inspect", *ids))
|
||||
evidence = []
|
||||
for item in containers:
|
||||
cfg, host = item["Config"], item["HostConfig"]
|
||||
service = cfg["Labels"]["com.docker.compose.service"]
|
||||
assert not host["Privileged"] and host["NetworkMode"] != "host"
|
||||
assert all("/docker.sock" not in m["Source"] and "/docker.sock" not in m["Destination"]
|
||||
for m in item["Mounts"])
|
||||
binds = host["PortBindings"] or {}
|
||||
if service in PUBLICATIONS:
|
||||
port, external = PUBLICATIONS[service]
|
||||
assert binds == {port: [{"HostIp": "127.0.0.1", "HostPort": external}]}, service
|
||||
else:
|
||||
assert not binds, service
|
||||
if service in APP:
|
||||
assert cfg["User"] == "appuser" and host["CapDrop"] == ["ALL"]
|
||||
assert "no-new-privileges:true" in host["SecurityOpt"]
|
||||
assert all(host[key] > 0 for key in ("Memory", "NanoCpus", "PidsLimit"))
|
||||
names = {entry.split("=", 1)[0] for entry in cfg["Env"]}
|
||||
assert names.isdisjoint({"BAO_TOKEN", "VAULT_TOKEN", "BAO_ROOT_TOKEN", "SECRET_ID",
|
||||
"DATABASE_URL", "BROKER_URL", "S3_SECRET_ACCESS_KEY"})
|
||||
uid = docker("exec", item["Id"], "id", "-u").decode().strip()
|
||||
assert uid == "10001"
|
||||
else:
|
||||
uid = None
|
||||
evidence.append({"service": service, "uid": uid, "status": item["State"]["Status"],
|
||||
"ports": binds, "memory_bytes": host["Memory"], "nano_cpus": host["NanoCpus"],
|
||||
"pids_limit": host["PidsLimit"], "image": item["Image"]})
|
||||
assert APP | set(PUBLICATIONS) <= {item["service"] for item in evidence}
|
||||
evidence.sort(key=lambda entry: entry["service"])
|
||||
(TARGET / "hardening.json").write_text(json.dumps(evidence, indent=2) + "\n", encoding="utf-8")
|
||||
record_certs()
|
||||
print("PASS: loopback-only published ingress and admin ports, app UID 10001 and resource/privilege limits")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,20 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-Location (Split-Path -Parent $PSScriptRoot)
|
||||
|
||||
function Invoke-Checked([string]$Program, [string[]]$Parameters) {
|
||||
& $Program @Parameters
|
||||
if ($LASTEXITCODE -ne 0) { throw "$Program failed with exit $LASTEXITCODE" }
|
||||
}
|
||||
|
||||
& "$PSScriptRoot/init-env.ps1"
|
||||
$compose = @('compose', '--project-name', 'mtusi-lab7-grade3')
|
||||
Invoke-Checked docker ($compose + @('config', '--quiet'))
|
||||
Invoke-Checked docker ($compose + @('build', 'migrate', 'tools', 's3-bootstrap'))
|
||||
Invoke-Checked docker ($compose + @('up', '-d', 'openbao', 'postgres', 's3', 'broker',
|
||||
'otel-collector', 'collector-local', 'prometheus', 'prometheus-local', 'loki', 'loki-local',
|
||||
'tempo', 'tempo-local', 'grafana', 'lb'))
|
||||
# This is the explicit local operator step. No OpenBao container reads the recovery file.
|
||||
Invoke-Checked py @('-3', 'scripts/bao_operator.py', 'bootstrap')
|
||||
Invoke-Checked docker ($compose + @('run', '--rm', '-T', 's3-bootstrap'))
|
||||
Invoke-Checked docker ($compose + @('up', '-d', '--no-build', 'api1', 'api2', 'worker'))
|
||||
Invoke-Checked py @('-3', '-c', "import sys; sys.path.insert(0, 'scripts'); from test_resilience import ready; ready(); print('PASS: HTTPS readiness')")
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
case "${TARGET_INSTANCE_ID:-}" in api1|api2) ;; *) exit 2 ;; esac
|
||||
exec "$(dirname "$0")/compose-hook.sh" "$TARGET_INSTANCE_ID"
|
||||
@@ -0,0 +1,22 @@
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-Location (Split-Path -Parent $PSScriptRoot)
|
||||
function Check-Exit {
|
||||
if ($LASTEXITCODE -ne 0) { throw "Network check failed with exit $LASTEXITCODE" }
|
||||
}
|
||||
docker compose run --rm --no-deps -T `
|
||||
-v "${PWD}/student-tests/tls.py:/probe.py:ro" `
|
||||
-v "${PWD}/secrets/pki/lb-client:/run/probe/correct:ro" `
|
||||
-v "${PWD}/secrets/pki/wrong-ca:/run/probe/wrong-ca:ro" `
|
||||
-v "${PWD}/secrets/pki/wrong-san:/run/probe/wrong-san:ro" tools python /probe.py
|
||||
Check-Exit
|
||||
foreach ($service in @('api1', 'worker')) {
|
||||
Get-Content student-tests/dependencies.py -Raw | docker compose exec -T $service python -
|
||||
Check-Exit
|
||||
}
|
||||
docker compose run --rm --no-deps -T `
|
||||
-v "${PWD}/student-tests/telemetry_acl.py:/probe.py:ro" `
|
||||
-v "${PWD}/secrets/generated/collector.json:/run/check/collector.json:ro" `
|
||||
-v "${PWD}/secrets/generated/datasources.json:/run/check/datasources.json:ro" tools python /probe.py
|
||||
Check-Exit
|
||||
py -3 scripts/stack_audit.py
|
||||
Check-Exit
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Verify persistent seal state and fail-closed service startup on real restart."""
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from bao_operator import seal_status
|
||||
from test_resilience import COMPOSE, ready
|
||||
|
||||
|
||||
def inspect():
|
||||
identifier = subprocess.check_output([*COMPOSE, "ps", "-q", "openbao"], text=True).strip()
|
||||
result = json.loads(subprocess.check_output(["docker", "inspect", identifier]))[0]
|
||||
volume = next(m["Name"] for m in result["Mounts"] if m["Destination"] == "/openbao/file")
|
||||
return identifier, result["State"]["StartedAt"], volume
|
||||
|
||||
|
||||
def client(service, expect_sealed=False):
|
||||
script = """
|
||||
import sys
|
||||
from src.config import bao_config
|
||||
try:
|
||||
configuration = bao_config()
|
||||
except RuntimeError:
|
||||
if sys.argv[1] != 'sealed':
|
||||
raise
|
||||
print('PASS: new process refuses to start with sealed OpenBao')
|
||||
else:
|
||||
assert sys.argv[1] == 'unsealed' and len(configuration) == 5
|
||||
print('PASS: scoped KV restored without bootstrap rewrite')
|
||||
"""
|
||||
subprocess.run([*COMPOSE, "run", "--rm", "--no-deps", "-T", service,
|
||||
"python", "-c", script, "sealed" if expect_sealed else "unsealed"], check=True)
|
||||
|
||||
|
||||
def main():
|
||||
before = inspect()
|
||||
assert seal_status()["sealed"] is False
|
||||
print("Before restart:", *before, flush=True)
|
||||
subprocess.run([*COMPOSE, "restart", "openbao"], check=True)
|
||||
try:
|
||||
status = seal_status()
|
||||
after = inspect()
|
||||
assert before[0] == after[0] and before[2] == after[2]
|
||||
assert before[1] != after[1] and status["initialized"] and status["sealed"]
|
||||
print("After restart:", *after, "initialized=True sealed=True", flush=True)
|
||||
client("worker", expect_sealed=True)
|
||||
ready()
|
||||
print("PASS: running API retains its in-memory dependencies while OpenBao is sealed", flush=True)
|
||||
finally:
|
||||
subprocess.run([sys.executable, "scripts/bao_operator.py", "unseal"], check=True)
|
||||
assert not seal_status()["sealed"]
|
||||
client("api1")
|
||||
client("worker")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Run the unchanged Make targets, with Docker actions executed by the host."""
|
||||
import argparse
|
||||
import ssl
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
PROJECT = "mtusi-lab7-grade3"
|
||||
COMPOSE = ["docker", "compose", "--project-name", PROJECT]
|
||||
STORAGE = ("postgres", "s3", "broker")
|
||||
APP = ("api1", "api2", "worker")
|
||||
|
||||
|
||||
def compose(*args):
|
||||
subprocess.run([*COMPOSE, *args], check=True)
|
||||
|
||||
|
||||
def snapshot(*services):
|
||||
for service in services:
|
||||
ident = subprocess.check_output([*COMPOSE, "ps", "-aq", service], text=True).strip()
|
||||
state = subprocess.check_output([
|
||||
"docker", "inspect", "--format",
|
||||
"{{.Id}} {{.State.Status}} started={{.State.StartedAt}} finished={{.State.FinishedAt}}",
|
||||
ident,
|
||||
], text=True).strip()
|
||||
print(f"{service} {state}", flush=True)
|
||||
|
||||
|
||||
def ready():
|
||||
context = ssl.create_default_context(cafile="secrets/ca/public.crt")
|
||||
for attempt in range(40):
|
||||
try:
|
||||
with urllib.request.urlopen("https://localhost:8443/health/ready", context=context, timeout=2):
|
||||
return
|
||||
except OSError:
|
||||
if attempt == 39:
|
||||
raise
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def broker_ready():
|
||||
identifier = subprocess.check_output([*COMPOSE, "ps", "-q", "broker"], text=True).strip()
|
||||
for attempt in range(45):
|
||||
status = subprocess.check_output(["docker", "inspect", "--format", "{{.State.Health.Status}}", identifier],
|
||||
text=True).strip()
|
||||
if status == "healthy":
|
||||
return
|
||||
if attempt == 44:
|
||||
raise TimeoutError("RabbitMQ did not become healthy")
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def scenario(mode):
|
||||
hook = "scripts/restart.sh" if mode == "persistence" else "scripts/stop-one.sh"
|
||||
with tempfile.TemporaryDirectory(prefix="hook-", dir="secrets") as directory:
|
||||
bridge = Path(directory).resolve()
|
||||
process = subprocess.Popen([
|
||||
*COMPOSE, "run", "--rm", "--no-deps", "-T",
|
||||
"-v", f"{bridge}:/hook", "-e", "LAB7_HOOK_DIR=/hook",
|
||||
"tools", "make", f"test-{mode}", f"ACTION_SCRIPT={hook}",
|
||||
])
|
||||
target = None
|
||||
try:
|
||||
deadline = time.monotonic() + 180
|
||||
while process.poll() is None:
|
||||
if time.monotonic() > deadline:
|
||||
raise TimeoutError("Resilience test exceeded 180 seconds")
|
||||
if target is None and (bridge / "request").is_file():
|
||||
target = (bridge / "request").read_text().strip()
|
||||
allowed = {"restart"} if mode == "persistence" else {"api1", "api2"}
|
||||
if target not in allowed:
|
||||
(bridge / "result").write_bytes(b"2\n")
|
||||
raise RuntimeError("Invalid Compose hook request")
|
||||
print(f"Hook accepted for project {PROJECT}: {target}", flush=True)
|
||||
if target == "restart":
|
||||
snapshot(*APP, *STORAGE)
|
||||
compose("restart", "-t", "3", *STORAGE)
|
||||
compose("restart", "-t", "3", *APP)
|
||||
snapshot(*APP, *STORAGE)
|
||||
else:
|
||||
compose("stop", "-t", "1", target)
|
||||
(bridge / "result.tmp").write_bytes(b"0\n")
|
||||
(bridge / "result.tmp").replace(bridge / "result")
|
||||
time.sleep(0.1)
|
||||
if process.wait() != 0 or target is None:
|
||||
raise RuntimeError(f"Public {mode} test failed")
|
||||
if target in {"api1", "api2"}:
|
||||
snapshot("api1", "api2")
|
||||
return target
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
process.wait(timeout=10)
|
||||
if target in {"api1", "api2"}:
|
||||
compose("start", target)
|
||||
ready()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("mode", choices=("persistence", "failover", "all"))
|
||||
mode = parser.parse_args().mode
|
||||
ready()
|
||||
if mode in {"persistence", "all"}:
|
||||
scenario("persistence")
|
||||
if mode in {"failover", "all"}:
|
||||
broker_ready()
|
||||
targets = set()
|
||||
for _ in range(5):
|
||||
targets.add(scenario("failover"))
|
||||
if targets == {"api1", "api2"}:
|
||||
print("PASS: public failover test observed both stopped replicas")
|
||||
break
|
||||
# One additional request advances round-robin before the next test.
|
||||
ready()
|
||||
else:
|
||||
raise RuntimeError("Public tests did not exercise both separate replicas")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user