forked from mtusi2026/mtusi2026lab7
lab 7
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare Argon2 candidates in the actual limited API container."""
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
code = """import concurrent.futures,json,resource,statistics,time
|
||||
from argon2 import PasswordHasher
|
||||
rows=[]
|
||||
for memory,iterations,parallelism in [(19456,2,1),(65536,3,4)]:
|
||||
h=PasswordHasher(memory_cost=memory,time_cost=iterations,parallelism=parallelism)
|
||||
stored=h.hash('Synthetic-password-for-budget')
|
||||
def verify(_):
|
||||
started=time.perf_counter();h.verify(stored,'Synthetic-password-for-budget');return time.perf_counter()-started
|
||||
single=[verify(i) for i in range(6)]
|
||||
started=time.perf_counter()
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:durations=list(pool.map(verify,range(8)))
|
||||
rows.append(dict(memory_kib=memory,time_cost=iterations,parallelism=parallelism,single_p50_seconds=statistics.median(single),single_max_seconds=max(single),concurrency=2,batch_seconds=time.perf_counter()-started,batch_max_seconds=max(durations),process_peak_rss_kib=resource.getrusage(resource.RUSAGE_SELF).ru_maxrss))
|
||||
print(json.dumps(rows))"""
|
||||
result = subprocess.check_output(
|
||||
["docker", "compose", "exec", "-T", "api", "python", "-c", code], cwd=root, text=True
|
||||
)
|
||||
report = {
|
||||
"candidates": json.loads(result),
|
||||
"api_cpu_limit": 0.5,
|
||||
"api_memory_limit_bytes": 512 * 1024**2,
|
||||
"max_hashes_per_api": 2,
|
||||
"api_replicas": 2,
|
||||
"global_login_ip_limit_per_minute": 120,
|
||||
"global_login_account_limit_per_minute": 10,
|
||||
"measurement": "Six sequential and eight two-thread verifications per candidate; peak RSS is cumulative for this probe process, not container total.",
|
||||
}
|
||||
(root / "evidence/argon-budget.json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
print("Saved measured Argon2 budget; evidence/argon-budget.json")
|
||||
+568
@@ -0,0 +1,568 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit operator bootstrap/unseal/start/rotation; no secret values on stdout."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import secrets
|
||||
import shutil
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from securitylib import (
|
||||
LOCAL,
|
||||
OPERATOR,
|
||||
ROLES,
|
||||
ROOT,
|
||||
compose,
|
||||
issue,
|
||||
openssl,
|
||||
put,
|
||||
refresh_crl,
|
||||
request,
|
||||
root_token,
|
||||
wait_bao,
|
||||
)
|
||||
|
||||
|
||||
def prepare():
|
||||
LOCAL.mkdir(mode=0o700, exist_ok=True)
|
||||
LOCAL.chmod(0o700)
|
||||
OPERATOR.mkdir(mode=0o700, exist_ok=True)
|
||||
OPERATOR.chmod(0o700)
|
||||
if not (OPERATOR / "ca.key").exists():
|
||||
(OPERATOR / "newcerts").mkdir()
|
||||
put(OPERATOR / "index.txt", "", 0o600)
|
||||
put(OPERATOR / "serial", "1000\n", 0o600)
|
||||
put(OPERATOR / "crlnumber", "1000\n", 0o600)
|
||||
put(
|
||||
OPERATOR / "ca.cnf",
|
||||
f"""[ca]
|
||||
default_ca=lab
|
||||
[lab]
|
||||
database={OPERATOR}/index.txt
|
||||
new_certs_dir={OPERATOR}/newcerts
|
||||
certificate={LOCAL}/trust/ca.crt
|
||||
private_key={OPERATOR}/ca.key
|
||||
serial={OPERATOR}/serial
|
||||
crlnumber={OPERATOR}/crlnumber
|
||||
default_md=sha256
|
||||
default_days=2
|
||||
default_crl_days=7
|
||||
policy=names
|
||||
unique_subject=no
|
||||
[names]
|
||||
commonName=supplied
|
||||
""",
|
||||
0o600,
|
||||
)
|
||||
(LOCAL / "trust").mkdir(exist_ok=True)
|
||||
openssl(
|
||||
"req",
|
||||
"-x509",
|
||||
"-newkey",
|
||||
"ec",
|
||||
"-pkeyopt",
|
||||
"ec_paramgen_curve:P-256",
|
||||
"-nodes",
|
||||
"-keyout",
|
||||
OPERATOR / "ca.key",
|
||||
"-out",
|
||||
LOCAL / "trust/ca.crt",
|
||||
"-days",
|
||||
"365",
|
||||
"-subj",
|
||||
"/CN=MTUSI Lab7 Local CA",
|
||||
"-addext",
|
||||
"basicConstraints=critical,CA:TRUE",
|
||||
"-addext",
|
||||
"keyUsage=critical,keyCertSign,cRLSign",
|
||||
)
|
||||
(OPERATOR / "ca.key").chmod(0o600)
|
||||
for role in ROLES:
|
||||
if not (LOCAL / "identities" / role / "service.crt").exists():
|
||||
issue(role, expired=role == "expired")
|
||||
foreign = LOCAL / "identities/foreign"
|
||||
if not (foreign / "service.crt").exists():
|
||||
foreign.mkdir(exist_ok=True)
|
||||
openssl(
|
||||
"req",
|
||||
"-x509",
|
||||
"-newkey",
|
||||
"ec",
|
||||
"-pkeyopt",
|
||||
"ec_paramgen_curve:P-256",
|
||||
"-nodes",
|
||||
"-keyout",
|
||||
foreign / "service.key",
|
||||
"-out",
|
||||
foreign / "service.crt",
|
||||
"-days",
|
||||
"2",
|
||||
"-subj",
|
||||
"/CN=lb",
|
||||
"-addext",
|
||||
"subjectAltName=DNS:lb",
|
||||
)
|
||||
(foreign / "service.key").chmod(0o644)
|
||||
if not (LOCAL / "trust/ca.crl").exists():
|
||||
refresh_crl()
|
||||
path = OPERATOR / "credentials.json"
|
||||
if not path.exists():
|
||||
values = {
|
||||
name: secrets.token_urlsafe(32)
|
||||
for name in [
|
||||
"postgres",
|
||||
"admin",
|
||||
"grafana",
|
||||
"minio",
|
||||
"api_db",
|
||||
"worker_db",
|
||||
"dispatcher_db",
|
||||
"reconciler_db",
|
||||
"api_s3",
|
||||
"worker_s3",
|
||||
"reconciler_s3",
|
||||
"api_redis",
|
||||
"operator_redis",
|
||||
"worker_broker",
|
||||
"dispatcher_broker",
|
||||
"api_broker",
|
||||
"operator_broker",
|
||||
]
|
||||
}
|
||||
put(path, json.dumps(values), 0o600)
|
||||
values = json.loads(path.read_text())
|
||||
if "dispatcher_s3" not in values:
|
||||
values["dispatcher_s3"] = secrets.token_urlsafe(32)
|
||||
put(path, json.dumps(values), 0o600)
|
||||
put(OPERATOR / "postgres-password", values["postgres"])
|
||||
put(
|
||||
OPERATOR / "init.sql",
|
||||
"\n".join(
|
||||
f"CREATE ROLE messenger_{role} LOGIN PASSWORD '{values[role + '_db']}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION;"
|
||||
for role in ["api", "worker", "dispatcher", "reconciler"]
|
||||
)
|
||||
+ "\nREVOKE CREATE ON SCHEMA public FROM PUBLIC;\n",
|
||||
)
|
||||
put(
|
||||
OPERATOR / "minio.env",
|
||||
f"MINIO_ROOT_USER=operator\nMINIO_ROOT_PASSWORD={values['minio']}\nMINIO_BROWSER=off\n",
|
||||
)
|
||||
put(OPERATOR / "grafana.env", f"GF_SECURITY_ADMIN_PASSWORD={values['grafana']}\n")
|
||||
common = {
|
||||
"S3_ENDPOINT": "https://minio:9000",
|
||||
"S3_BUCKET": "messenger-attachments",
|
||||
"ADMIN_PASSWORD": values["admin"],
|
||||
}
|
||||
bootstrap = {
|
||||
**common,
|
||||
"DATABASE_URL": f"postgresql://operator:{values['postgres']}@postgres:5432/messenger",
|
||||
"REDIS_URL": f"rediss://operator:{values['operator_redis']}@redis:6379/0",
|
||||
"MINIO_ROOT_USER": "operator",
|
||||
"MINIO_ROOT_PASSWORD": values["minio"],
|
||||
"S3_ACCESS_KEY_ID": "messenger-api",
|
||||
"S3_SECRET_ACCESS_KEY": values["api_s3"],
|
||||
"S3_WORKER_ACCESS_KEY_ID": values.get("worker_s3_access", "messenger-worker"),
|
||||
"S3_WORKER_SECRET_ACCESS_KEY": values["worker_s3"],
|
||||
"S3_RECONCILE_ACCESS_KEY_ID": "messenger-reconciler",
|
||||
"S3_RECONCILE_SECRET_ACCESS_KEY": values["reconciler_s3"],
|
||||
"S3_DISPATCHER_ACCESS_KEY_ID": "messenger-dispatcher",
|
||||
"S3_DISPATCHER_SECRET_ACCESS_KEY": values["dispatcher_s3"],
|
||||
}
|
||||
put(OPERATOR / "bootstrap.env", "\n".join(k + "=" + v for k, v in bootstrap.items()) + "\n")
|
||||
put(
|
||||
LOCAL / "config/redis.acl",
|
||||
f"user default off\nuser operator on >{values['operator_redis']} ~* +@all\nuser api on >{values['api_redis']} ~session:v1:* ~user:v1:* ~rl:login:* +ping +get +set +del +incr +pexpire +pttl +eval +multi +exec +client|setinfo\n",
|
||||
)
|
||||
put(
|
||||
LOCAL / "config/broker.acl",
|
||||
f"user default off\nuser operator on >{values['operator_broker']} ~* +@all\nuser dispatcher on >{values['dispatcher_broker']} ~attachment-jobs-v1 +ping +xadd +client|setinfo\nuser worker on >{values['worker_broker']} ~attachment-jobs-v1 +ping +xgroup +xreadgroup +xautoclaim +xack +xdel +multi +exec +client|setinfo\nuser api on >{values['api_broker']} ~attachment-jobs-v1 +ping +client|setinfo\n",
|
||||
)
|
||||
# Grafana embeds public CA/client certificate and its own private key only.
|
||||
identity = LOCAL / "identities/grafana"
|
||||
tlsdata = {
|
||||
"tlsCACert": (LOCAL / "trust/ca.crt").read_text(),
|
||||
"tlsClientCert": (identity / "service.crt").read_text(),
|
||||
"tlsClientKey": (identity / "service.key").read_text(),
|
||||
}
|
||||
sources = []
|
||||
for name, kind, url in [
|
||||
("Prometheus", "prometheus", "https://prometheus:9090"),
|
||||
("Loki", "loki", "https://loki:3100"),
|
||||
("Tempo", "tempo", "https://tempo:3200"),
|
||||
]:
|
||||
extra = {
|
||||
"httpMethod": "GET",
|
||||
"tlsAuth": True,
|
||||
"tlsAuthWithCACert": True,
|
||||
"tlsSkipVerify": False,
|
||||
}
|
||||
if kind == "loki":
|
||||
extra["derivedFields"] = [
|
||||
{
|
||||
"name": "TraceID",
|
||||
"matcherRegex": '"trace_id":\\s*"([a-f0-9]+)"',
|
||||
"datasourceUid": "tempo",
|
||||
"url": "$${__value.raw}",
|
||||
}
|
||||
]
|
||||
if kind == "tempo":
|
||||
extra["tracesToLogsV2"] = {"datasourceUid": "loki", "filterByTraceID": True}
|
||||
sources.append(
|
||||
{
|
||||
"name": name,
|
||||
"uid": kind,
|
||||
"type": kind,
|
||||
"url": url,
|
||||
"access": "proxy",
|
||||
"isDefault": kind == "prometheus",
|
||||
"jsonData": extra,
|
||||
"secureJsonData": tlsdata,
|
||||
}
|
||||
)
|
||||
put(
|
||||
LOCAL / "config/grafana-sources.yaml",
|
||||
json.dumps({"apiVersion": 1, "datasources": sources}, indent=2),
|
||||
)
|
||||
print("Prepared local CA, identities and service credentials; values not printed.")
|
||||
|
||||
|
||||
def unseal():
|
||||
status = wait_bao()
|
||||
if not status["initialized"]:
|
||||
data = request("sys/init", {"secret_shares": 3, "secret_threshold": 2})
|
||||
put(OPERATOR / "bao-init.json", json.dumps(data), 0o600)
|
||||
if status["sealed"]:
|
||||
data = json.loads((OPERATOR / "bao-init.json").read_text())
|
||||
for key in data["keys"][:2]:
|
||||
request("sys/unseal", {"key": key})
|
||||
print("Operator unseal completed; material remains outside server containers.")
|
||||
|
||||
|
||||
def configure_bao():
|
||||
token = root_token()
|
||||
mounts = request("sys/mounts", token=token)
|
||||
if "secret/" not in mounts:
|
||||
request("sys/mounts/secret", {"type": "kv", "options": {"version": "2"}}, token=token)
|
||||
auth = request("sys/auth", token=token)
|
||||
if "cert/" not in auth:
|
||||
request("sys/auth/cert", {"type": "cert"}, token=token)
|
||||
values = json.loads((OPERATOR / "credentials.json").read_text())
|
||||
for role in ["api", "worker", "dispatcher", "reconciler"]:
|
||||
policy = (
|
||||
ROOT / f"infra/openbao/{role}.hcl"
|
||||
).read_text() + '\npath "auth/token/renew-self" { capabilities = ["update"] }\n'
|
||||
request("sys/policies/acl/" + role, {"policy": policy}, token=token)
|
||||
request(
|
||||
"auth/cert/certs/" + role,
|
||||
{
|
||||
"certificate": (LOCAL / "trust/ca.crt").read_text(),
|
||||
"allowed_common_names": [role],
|
||||
"allowed_dns_sans": [role],
|
||||
"token_policies": [role],
|
||||
"token_ttl": 60,
|
||||
"token_max_ttl": 300,
|
||||
},
|
||||
token=token,
|
||||
)
|
||||
env = {
|
||||
"DATABASE_URL": f"postgresql://messenger_{role}:{values[role + '_db']}@postgres:5432/messenger",
|
||||
"REDIS_URL": f"rediss://api:{values['api_redis']}@redis:6379/0"
|
||||
if role == "api"
|
||||
else "rediss://unused:unused@redis:6379/0",
|
||||
"ADMIN_PASSWORD": values["admin"] if role == "api" else secrets.token_urlsafe(32),
|
||||
"S3_ENDPOINT": "https://minio:9000",
|
||||
"S3_BUCKET": "messenger-attachments",
|
||||
}
|
||||
s3role = role
|
||||
prefix = {
|
||||
"api": "S3",
|
||||
"worker": "S3_WORKER",
|
||||
"reconciler": "S3_RECONCILE",
|
||||
"dispatcher": "S3_DISPATCHER",
|
||||
}[s3role]
|
||||
env[prefix + "_ACCESS_KEY_ID"] = values.get(s3role + "_s3_access", "messenger-" + s3role)
|
||||
env[prefix + "_SECRET_ACCESS_KEY"] = values[s3role + "_s3"]
|
||||
if role in ["worker", "dispatcher"]:
|
||||
env["BROKER_URL"] = f"rediss://{role}:{values[role + '_broker']}@broker:6379/0"
|
||||
import urllib.error
|
||||
|
||||
try:
|
||||
request("secret/data/messenger/" + role, token=token)
|
||||
except urllib.error.HTTPError as error:
|
||||
if error.code != 404:
|
||||
raise
|
||||
request("secret/data/messenger/" + role, {"data": env}, token=token)
|
||||
request("auth/cert/crls/lab7", {"crl": (LOCAL / "trust/ca.crl").read_text()}, token=token)
|
||||
try:
|
||||
request(
|
||||
"sys/audit/file",
|
||||
{"type": "file", "options": {"file_path": "/bao/data/audit.jsonl"}},
|
||||
token=token,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
print("Configured restricted service policies, certificate auth and KV secrets.")
|
||||
|
||||
|
||||
def sql(statement):
|
||||
# stdin keeps credentials and SQL literals out of process command lines/output.
|
||||
subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"psql",
|
||||
"-U",
|
||||
"operator",
|
||||
"-d",
|
||||
"messenger",
|
||||
"-p",
|
||||
"15432",
|
||||
"-v",
|
||||
"ON_ERROR_STOP=1",
|
||||
],
|
||||
input=statement,
|
||||
text=True,
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
)
|
||||
|
||||
|
||||
def grants():
|
||||
sql("""REVOKE ALL ON DATABASE messenger FROM PUBLIC;
|
||||
GRANT CONNECT ON DATABASE messenger TO messenger_api,messenger_worker,messenger_dispatcher,messenger_reconciler;
|
||||
GRANT USAGE ON SCHEMA public TO messenger_api,messenger_worker,messenger_dispatcher,messenger_reconciler;
|
||||
GRANT SELECT,INSERT,UPDATE,DELETE ON users,chats,chat_members,messages,message_requests,attachments,attachment_jobs,job_replays,message_attachments,upload_intents,storage_findings TO messenger_api;
|
||||
GRANT SELECT,UPDATE ON attachments,attachment_jobs TO messenger_worker;
|
||||
GRANT SELECT,UPDATE ON attachments,attachment_jobs,upload_intents TO messenger_dispatcher;
|
||||
GRANT SELECT,INSERT,UPDATE,DELETE ON attachments,upload_intents,storage_findings TO messenger_reconciler;
|
||||
GRANT SELECT ON message_attachments TO messenger_reconciler;
|
||||
""")
|
||||
|
||||
|
||||
def bootstrap():
|
||||
prepare()
|
||||
compose("build", "api")
|
||||
compose(
|
||||
"up",
|
||||
"-d",
|
||||
"volume-init",
|
||||
"postgres",
|
||||
"postgres-tls",
|
||||
"redis",
|
||||
"redis-tls",
|
||||
"broker",
|
||||
"broker-tls",
|
||||
"minio",
|
||||
"openbao",
|
||||
)
|
||||
unseal()
|
||||
# KV existence is checked per path on reruns.
|
||||
configure_bao()
|
||||
for _ in range(40):
|
||||
try:
|
||||
compose("run", "--rm", "--no-deps", "migration")
|
||||
break
|
||||
except subprocess.CalledProcessError:
|
||||
time.sleep(2)
|
||||
else:
|
||||
raise RuntimeError("Migration unavailable")
|
||||
grants()
|
||||
compose("run", "--rm", "--no-deps", "s3-bootstrap")
|
||||
compose(
|
||||
"up",
|
||||
"-d",
|
||||
"otel-collector",
|
||||
"otel-tls",
|
||||
"prometheus",
|
||||
"prometheus-tls",
|
||||
"loki",
|
||||
"loki-tls",
|
||||
"tempo",
|
||||
"tempo-tls",
|
||||
"grafana",
|
||||
"api",
|
||||
"worker",
|
||||
"dispatcher",
|
||||
"reconciler",
|
||||
)
|
||||
compose("up", "-d", "--wait", "lb")
|
||||
print("Lab7 ready: https://localhost:8443 ; CA: .local/trust/ca.crt")
|
||||
|
||||
|
||||
def rotate_certificate(role):
|
||||
folder = LOCAL / "identities" / role
|
||||
archive = OPERATOR / f"revoked-{role}-{int(time.time())}"
|
||||
shutil.copytree(folder, archive)
|
||||
archive.chmod(0o700)
|
||||
issue(role)
|
||||
openssl("ca", "-config", OPERATOR / "ca.cnf", "-revoke", archive / "service.crt")
|
||||
refresh_crl()
|
||||
request(
|
||||
"auth/cert/crls/lab7", {"crl": (LOCAL / "trust/ca.crl").read_text()}, token=root_token()
|
||||
)
|
||||
# Close old persistent TLS connections and reload CRL on all enforcing gateways.
|
||||
compose(
|
||||
"restart",
|
||||
"postgres-tls",
|
||||
"redis-tls",
|
||||
"broker-tls",
|
||||
"otel-tls",
|
||||
"loki-tls",
|
||||
"tempo-tls",
|
||||
"prometheus-tls",
|
||||
"lb",
|
||||
)
|
||||
if role not in ["api", "worker", "dispatcher", "reconciler"]:
|
||||
compose("restart", role)
|
||||
print("Rotated leaf certificate and revoked previous serial; no image rebuild.")
|
||||
|
||||
|
||||
def rotate_secret():
|
||||
record = request("secret/data/messenger/worker", token=root_token())["data"]["data"]
|
||||
oldurl = record["DATABASE_URL"]
|
||||
oldrole = oldurl.split("://", 1)[1].split(":", 1)[0]
|
||||
newrole = "worker_" + secrets.token_hex(4)
|
||||
password = secrets.token_urlsafe(32)
|
||||
sql(
|
||||
f"CREATE ROLE {newrole} LOGIN PASSWORD '{password}' NOSUPERUSER NOCREATEDB NOCREATEROLE; GRANT messenger_worker TO {newrole};"
|
||||
)
|
||||
record["DATABASE_URL"] = f"postgresql://{newrole}:{password}@postgres:5432/messenger"
|
||||
request("secret/data/messenger/worker", {"data": record}, token=root_token())
|
||||
time.sleep(15)
|
||||
sql(
|
||||
f"ALTER ROLE {oldrole} NOLOGIN; SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE usename='{oldrole}';"
|
||||
)
|
||||
put(
|
||||
OPERATOR / "last-worker-rotation.json",
|
||||
json.dumps({"old_url": oldurl, "new_role": newrole}),
|
||||
0o600,
|
||||
)
|
||||
print("Rotated worker DB credential, revoked old login and closed old sessions.")
|
||||
|
||||
|
||||
def rotate_s3():
|
||||
token = root_token()
|
||||
record = request("secret/data/messenger/worker", token=token)["data"]["data"]
|
||||
old = {key: record[key] for key in ["S3_WORKER_ACCESS_KEY_ID", "S3_WORKER_SECRET_ACCESS_KEY"]}
|
||||
access = "worker-" + secrets.token_hex(5)
|
||||
password = secrets.token_urlsafe(32)
|
||||
code = """import json,sys
|
||||
from src.core.storage_bootstrap import create_admin_client
|
||||
x=json.load(sys.stdin);admin=create_admin_client()
|
||||
if x['action']=='create':
|
||||
admin.user_add(x['access'],x['password']);admin.policy_set('messenger-worker',user=x['access'])
|
||||
else:admin.user_disable(x['access'])
|
||||
"""
|
||||
|
||||
def admin(data):
|
||||
subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"compose",
|
||||
"run",
|
||||
"--rm",
|
||||
"--no-deps",
|
||||
"-T",
|
||||
"s3-bootstrap",
|
||||
"python",
|
||||
"-c",
|
||||
code,
|
||||
],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
input=json.dumps(data),
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
)
|
||||
|
||||
admin({"action": "create", "access": access, "password": password})
|
||||
record.update(S3_WORKER_ACCESS_KEY_ID=access, S3_WORKER_SECRET_ACCESS_KEY=password)
|
||||
request("secret/data/messenger/worker", {"data": record}, token=token)
|
||||
time.sleep(15)
|
||||
admin({"action": "disable", "access": old["S3_WORKER_ACCESS_KEY_ID"]})
|
||||
values = json.loads((OPERATOR / "credentials.json").read_text())
|
||||
values.update(worker_s3=password, worker_s3_access=access)
|
||||
put(OPERATOR / "credentials.json", json.dumps(values), 0o600)
|
||||
put(OPERATOR / "last-s3-rotation.json", json.dumps(old), 0o600)
|
||||
prepare()
|
||||
print(
|
||||
"Rotated worker S3 identity; disabled old access key; bootstrap retains current credentials."
|
||||
)
|
||||
|
||||
|
||||
def renew_identities():
|
||||
# Explicit maintenance operation; CA remains unchanged, data volumes untouched.
|
||||
gateways = [
|
||||
"postgres-tls",
|
||||
"redis-tls",
|
||||
"broker-tls",
|
||||
"otel-tls",
|
||||
"loki-tls",
|
||||
"tempo-tls",
|
||||
"prometheus-tls",
|
||||
]
|
||||
compose(
|
||||
"stop",
|
||||
"api",
|
||||
"worker",
|
||||
"dispatcher",
|
||||
"reconciler",
|
||||
"lb",
|
||||
*gateways,
|
||||
"openbao",
|
||||
"minio",
|
||||
"grafana",
|
||||
"otel-collector",
|
||||
"prometheus",
|
||||
)
|
||||
archive = OPERATOR / ("renewal-" + str(int(time.time())))
|
||||
archive.mkdir(mode=0o700)
|
||||
for role in ROLES:
|
||||
if role == "expired":
|
||||
continue
|
||||
old = archive / (role + ".crt")
|
||||
shutil.copy2(LOCAL / "identities" / role / "service.crt", old)
|
||||
issue(role)
|
||||
openssl("ca", "-config", OPERATOR / "ca.cnf", "-revoke", old)
|
||||
refresh_crl()
|
||||
prepare()
|
||||
compose("up", "-d", "volume-init")
|
||||
compose("start", "openbao", "minio", "grafana", "otel-collector", "prometheus", *gateways)
|
||||
unseal()
|
||||
configure_bao()
|
||||
compose(
|
||||
"up", "-d", "--no-recreate", "--wait", "api", "worker", "dispatcher", "reconciler", "lb"
|
||||
)
|
||||
print("Renewed leaf identities with the existing CA; old serials revoked; data preserved.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument(
|
||||
"action",
|
||||
choices=[
|
||||
"prepare",
|
||||
"bootstrap",
|
||||
"unseal",
|
||||
"rotate-cert",
|
||||
"rotate-secret",
|
||||
"renew-identities",
|
||||
"rotate-s3",
|
||||
],
|
||||
)
|
||||
parser.add_argument("--role", default="worker", choices=ROLES)
|
||||
args = parser.parse_args()
|
||||
{
|
||||
"prepare": prepare,
|
||||
"bootstrap": bootstrap,
|
||||
"unseal": unseal,
|
||||
"rotate-cert": lambda: rotate_certificate(args.role),
|
||||
"rotate-secret": rotate_secret,
|
||||
"renew-identities": renew_identities,
|
||||
"rotate-s3": rotate_s3,
|
||||
}[args.action]()
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Управление только API-контейнерами текущего Compose-проекта."""
|
||||
|
||||
import json
|
||||
import ssl
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def docker(*args):
|
||||
return subprocess.check_output(["docker", *args], cwd=ROOT, text=True).strip()
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return docker("compose", "--env-file", os.environ.get("ENV_FILE", ".env"), *args)
|
||||
|
||||
|
||||
def containers():
|
||||
return compose("ps", "--all", "-q", "api").split()
|
||||
|
||||
|
||||
def describe(container):
|
||||
# Никогда не выводим Config.Env: там credentials.
|
||||
return json.loads(docker("inspect", "--format", "{{json .State}}", container))
|
||||
|
||||
|
||||
def instance_id(container):
|
||||
code = "import urllib.request; r=urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2); print(r.headers['X-Instance-Id'])"
|
||||
return docker("exec", container, "python", "-c", code)
|
||||
|
||||
|
||||
def wait_ready(container, timeout=60):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
state = describe(container)
|
||||
if state.get("Health", {}).get("Status") == "healthy":
|
||||
return instance_id(container)
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError("API container did not become healthy: " + container[:12])
|
||||
|
||||
|
||||
def wait_visible(instance, timeout=30):
|
||||
base = os.environ.get("BASE_URL", "https://localhost:8443").rstrip("/")
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with urllib.request.urlopen(base + "/health/ready", context=ssl.create_default_context(cafile=str(ROOT / ".local/trust/ca.crt")), timeout=2) as response:
|
||||
if response.headers.get("X-Instance-Id") == instance:
|
||||
return
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(0.1)
|
||||
raise RuntimeError("New replica was not discovered by HAProxy")
|
||||
@@ -1,10 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# TODO: copy to restart.sh and implement using YOUR compose/stack services.
|
||||
# Restart API and ALL used state stores (DB, sessions, S3, broker as applicable).
|
||||
# Preserve persistent volumes and schema/data; never down -v / flush / re-seed.
|
||||
# Allow operator unseal if required in lab7; do not print credentials.
|
||||
# Exit 0 only after the intended action; test waits for API readiness separately.
|
||||
printf '%s
|
||||
' 'TODO: implement restart.sh for your infrastructure' >&2
|
||||
exit 2
|
||||
Executable
+8
@@ -0,0 +1,8 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
# Full restart, including secret store and telemetry stores; preserve volumes.
|
||||
docker compose restart postgres redis broker minio openbao prometheus loki tempo grafana otel-collector
|
||||
python3 scripts/lab7.py unseal
|
||||
docker compose restart postgres-tls redis-tls broker-tls otel-tls prometheus-tls loki-tls tempo-tls
|
||||
docker compose restart api worker dispatcher reconciler lb
|
||||
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Scan local image archives; scanner gets no Docker socket or application secrets."""
|
||||
|
||||
import argparse
|
||||
import collections
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SCANNER = "aquasec/trivy:0.69.3"
|
||||
IMAGES = {
|
||||
"app": "mtusi-messenger:lab7",
|
||||
"minio": "mtusi-minio:RELEASE.2025-10-15T17-29-55Z",
|
||||
"postgres": "postgres:16.6-bookworm",
|
||||
"redis": "redis:7.4.2-bookworm",
|
||||
"gateway": "haproxy:3.0.12-alpine",
|
||||
"openbao": "openbao/openbao:2.5.0",
|
||||
"collector": "otel/opentelemetry-collector-contrib:0.123.0",
|
||||
"prometheus": "prom/prometheus:v3.2.1",
|
||||
"loki": "grafana/loki:3.4.2",
|
||||
"tempo": "grafana/tempo:2.7.2",
|
||||
"grafana": "grafana/grafana:11.6.0",
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--only", nargs="*")
|
||||
args = parser.parse_args()
|
||||
folder = ROOT / ".local/operator/scan"
|
||||
folder.mkdir(exist_ok=True)
|
||||
summary = []
|
||||
for name, image in IMAGES.items():
|
||||
if args.only and name not in args.only:
|
||||
continue
|
||||
archive = folder / (name + ".tar")
|
||||
output = ROOT / "evidence" / ("scan-" + name + ".json")
|
||||
subprocess.run(["docker", "save", image, "-o", str(archive)], check=True)
|
||||
subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"run",
|
||||
"--rm",
|
||||
"-v",
|
||||
str(archive) + ":/scan/image.tar:ro",
|
||||
"-v",
|
||||
"mtusi2026lab7_trivy_cache:/root/.cache/trivy",
|
||||
"-v",
|
||||
str(ROOT / "evidence") + ":/out",
|
||||
SCANNER,
|
||||
"image",
|
||||
"--quiet",
|
||||
"--timeout",
|
||||
"15m",
|
||||
"--scanners",
|
||||
"vuln",
|
||||
"--input",
|
||||
"/scan/image.tar",
|
||||
"--format",
|
||||
"json",
|
||||
"--output",
|
||||
"/out/" + output.name,
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
data = json.loads(output.read_text())
|
||||
findings = [
|
||||
v for result in data.get("Results", []) for v in result.get("Vulnerabilities", [])
|
||||
]
|
||||
item = {
|
||||
"image": image,
|
||||
"report": output.name,
|
||||
"severity": dict(collections.Counter(v["Severity"] for v in findings)),
|
||||
"findings": len(findings),
|
||||
"fix_available": sum(bool(v.get("FixedVersion")) for v in findings),
|
||||
}
|
||||
summary.append(item)
|
||||
archive.unlink()
|
||||
print(name, item["severity"], flush=True)
|
||||
previous = ROOT / "evidence/scan-summary.json"
|
||||
if args.only and previous.exists():
|
||||
existing = json.loads(previous.read_text())["images"]
|
||||
updated = {row["image"]: row for row in existing}
|
||||
updated.update({row["image"]: row for row in summary})
|
||||
summary = list(updated.values())
|
||||
(ROOT / "evidence/scan-summary.json").write_text(
|
||||
json.dumps({"scanner": SCANNER, "images": summary}, indent=2) + "\n"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Operator utilities. Never print credentials, tokens, environment or PEM keys."""
|
||||
|
||||
import json
|
||||
import ssl
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LOCAL = ROOT / ".local"
|
||||
OPERATOR = LOCAL / "operator"
|
||||
ROLES = [
|
||||
"operator",
|
||||
"lb",
|
||||
"api",
|
||||
"worker",
|
||||
"dispatcher",
|
||||
"reconciler",
|
||||
"postgres",
|
||||
"redis",
|
||||
"broker",
|
||||
"minio",
|
||||
"openbao",
|
||||
"otel-collector",
|
||||
"prometheus",
|
||||
"loki",
|
||||
"tempo",
|
||||
"grafana",
|
||||
"intruder",
|
||||
"expired",
|
||||
]
|
||||
|
||||
|
||||
def compose(*args, capture=False):
|
||||
result = subprocess.run(
|
||||
["docker", "compose", *args],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
stdout=subprocess.PIPE if capture else None,
|
||||
check=True,
|
||||
)
|
||||
return result.stdout.strip() if capture else ""
|
||||
|
||||
|
||||
def openssl(*args):
|
||||
subprocess.run(
|
||||
["openssl", *map(str, args)],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
|
||||
|
||||
def put(path, text, mode=0o644):
|
||||
path = Path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(text)
|
||||
path.chmod(mode)
|
||||
|
||||
|
||||
def tls(role="operator", *, identity=None, trust=True):
|
||||
ctx = (
|
||||
ssl.create_default_context(cafile=str(LOCAL / "trust/ca.crt"))
|
||||
if trust
|
||||
else ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
)
|
||||
ctx.minimum_version = ssl.TLSVersion.TLSv1_3
|
||||
if role:
|
||||
folder = Path(identity) if identity else LOCAL / "identities" / role
|
||||
ctx.load_cert_chain(folder / "service.crt", folder / "service.key")
|
||||
return ctx
|
||||
|
||||
|
||||
def request(
|
||||
path, body=None, *, token=None, role="operator", base="https://localhost:18200", method=None
|
||||
):
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if token:
|
||||
headers["X-Vault-Token"] = token
|
||||
req = urllib.request.Request(
|
||||
base + "/v1/" + path,
|
||||
headers=headers,
|
||||
data=json.dumps(body).encode() if body is not None else None,
|
||||
method=method,
|
||||
)
|
||||
with urllib.request.urlopen(req, context=tls(role), timeout=5) as response:
|
||||
data = response.read()
|
||||
return json.loads(data) if data else {}
|
||||
|
||||
|
||||
def root_token():
|
||||
return json.loads((OPERATOR / "bao-init.json").read_text())["root_token"]
|
||||
|
||||
|
||||
def issue(role, *, expired=False):
|
||||
folder = LOCAL / "identities" / role
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
openssl(
|
||||
"genpkey",
|
||||
"-algorithm",
|
||||
"EC",
|
||||
"-pkeyopt",
|
||||
"ec_paramgen_curve:P-256",
|
||||
"-out",
|
||||
folder / "service.key",
|
||||
)
|
||||
openssl(
|
||||
"req",
|
||||
"-new",
|
||||
"-key",
|
||||
folder / "service.key",
|
||||
"-subj",
|
||||
f"/CN={role}",
|
||||
"-out",
|
||||
folder / "service.csr",
|
||||
)
|
||||
names = [role]
|
||||
if role in ["lb", "openbao", "grafana", "prometheus", "loki", "tempo"]:
|
||||
names.append("localhost")
|
||||
extras = (
|
||||
"subjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid,issuer\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=serverAuth,clientAuth\nsubjectAltName="
|
||||
+ ",".join("DNS:" + name for name in names)
|
||||
+ "\n"
|
||||
)
|
||||
if "localhost" in names:
|
||||
extras = extras.rstrip() + ",IP:127.0.0.1\n"
|
||||
put(folder / "extensions.cnf", extras)
|
||||
dates = (
|
||||
["-startdate", "20200101000000Z", "-enddate", "20200102000000Z"]
|
||||
if expired
|
||||
else ["-days", "2"]
|
||||
)
|
||||
openssl(
|
||||
"ca",
|
||||
"-batch",
|
||||
"-config",
|
||||
OPERATOR / "ca.cnf",
|
||||
"-extfile",
|
||||
folder / "extensions.cnf",
|
||||
"-in",
|
||||
folder / "service.csr",
|
||||
"-out",
|
||||
folder / "service.crt",
|
||||
"-notext",
|
||||
*dates,
|
||||
)
|
||||
put(
|
||||
folder / "service.pem",
|
||||
(folder / "service.crt").read_text() + (folder / "service.key").read_text(),
|
||||
)
|
||||
# .local itself is 0700; container gets only its own read-only identity directory.
|
||||
(folder / "service.key").chmod(0o644)
|
||||
if role == "minio":
|
||||
put(folder / "public.crt", (folder / "service.crt").read_text())
|
||||
put(folder / "private.key", (folder / "service.key").read_text())
|
||||
return folder
|
||||
|
||||
|
||||
def refresh_crl():
|
||||
openssl("ca", "-gencrl", "-config", OPERATOR / "ca.cnf", "-out", LOCAL / "trust/ca.crl")
|
||||
|
||||
|
||||
def wait_bao():
|
||||
for _ in range(60):
|
||||
try:
|
||||
return request("sys/seal-status")
|
||||
except (OSError, urllib.error.URLError):
|
||||
time.sleep(1)
|
||||
raise RuntimeError("OpenBao did not start")
|
||||
@@ -1,10 +0,0 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
# TODO: copy to stop-one.sh, map TARGET_INSTANCE_ID to ONE API container/task.
|
||||
# Stop that instance and leave it stopped; no stop of DB/LB/volumes.
|
||||
# Return quickly (within 10 s); the test sends requests during this script.
|
||||
# Restore the replica explicitly after the test. Never print credentials.
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
printf '%s
|
||||
' 'TODO: implement stop-one.sh for your infrastructure' >&2
|
||||
exit 2
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Сопоставить X-Instance-Id реальному контейнеру и оставить его остановленным."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from replicas import containers, describe, docker, instance_id
|
||||
|
||||
target = os.environ["TARGET_INSTANCE_ID"]
|
||||
running = [c for c in containers() if describe(c)["Running"]]
|
||||
if len(running) < 2:
|
||||
raise SystemExit("Need at least two running API containers")
|
||||
for container in running:
|
||||
if instance_id(container) == target:
|
||||
before = describe(container)
|
||||
started = time.monotonic()
|
||||
docker("stop", "--time", "10", container)
|
||||
after = describe(container)
|
||||
assert not after["Running"]
|
||||
event = {"container": container[:12], "instance_id": target, "started_at": before["StartedAt"], "finished_at": after["FinishedAt"], "stop_seconds": round(time.monotonic()-started,3), "exit_code": after["ExitCode"]}
|
||||
path=Path(__file__).resolve().parents[1]/"evidence/failover-events.jsonl"
|
||||
with path.open("a") as stream:stream.write(json.dumps(event)+"\n")
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"container": container[:12],
|
||||
"instance_id": target,
|
||||
"started_at": before["StartedAt"],
|
||||
"finished_at": after["FinishedAt"],
|
||||
"stop_seconds": round(time.monotonic() - started, 3),
|
||||
"exit_code": after["ExitCode"],
|
||||
}
|
||||
)
|
||||
)
|
||||
break
|
||||
else:
|
||||
raise SystemExit("Requested instance not found in this Compose project")
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec "${PYTHON:-python3}" scripts/stop-one.py
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Public failover plus explicit coverage of both distinct API replicas."""
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from securitylib import ROOT, compose
|
||||
|
||||
(ROOT / "evidence/failover-events.jsonl").write_text("")
|
||||
logs = []
|
||||
try:
|
||||
for command in [
|
||||
[
|
||||
sys.executable,
|
||||
"tests/resilience.py",
|
||||
"--mode",
|
||||
"failover",
|
||||
"--action-script",
|
||||
"scripts/stop-one.sh",
|
||||
"--base-url",
|
||||
"https://localhost:8443",
|
||||
"--ca-file",
|
||||
str(ROOT / ".local/trust/ca.crt"),
|
||||
],
|
||||
[sys.executable, "tests/lab7_failovers.py"],
|
||||
]:
|
||||
result = subprocess.run(
|
||||
command, cwd=ROOT, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
|
||||
)
|
||||
logs.append(result.stdout)
|
||||
print(result.stdout, end="", flush=True)
|
||||
assert result.returncode == 0, "Failover verification failed"
|
||||
compose("start", "api")
|
||||
compose("up", "-d", "--no-recreate", "--wait", "api")
|
||||
(ROOT / "evidence/failover-checks.txt").write_text("\n".join(logs))
|
||||
finally:
|
||||
compose("start", "api")
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Public persistence test plus safe proof of all actual storage restarts."""
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from securitylib import ROOT, compose
|
||||
|
||||
|
||||
def snapshot():
|
||||
ids = compose("ps", "-q", capture=True).split()
|
||||
data = json.loads(subprocess.check_output(["docker", "inspect", *ids], text=True))
|
||||
return {
|
||||
x["Config"]["Labels"]["com.docker.compose.service"] + ":" + x["Id"][:12]: {
|
||||
"started_at": x["State"]["StartedAt"],
|
||||
"container": x["Id"][:12],
|
||||
}
|
||||
for x in data
|
||||
}
|
||||
|
||||
|
||||
before = snapshot()
|
||||
result = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
"tests/resilience.py",
|
||||
"--mode",
|
||||
"persistence",
|
||||
"--action-script",
|
||||
"scripts/restart.sh",
|
||||
"--base-url",
|
||||
"https://localhost:8443",
|
||||
"--ca-file",
|
||||
str(ROOT / ".local/trust/ca.crt"),
|
||||
],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT,
|
||||
)
|
||||
print(result.stdout, end="")
|
||||
assert result.returncode == 0
|
||||
changes = []
|
||||
after = snapshot()
|
||||
for key, old in before.items():
|
||||
new = after[key]
|
||||
assert old["started_at"] != new["started_at"], key + " not restarted"
|
||||
changes.append({"service": key, "before": old["started_at"], "after": new["started_at"]})
|
||||
(ROOT / "evidence/persistence-summary.json").write_text(
|
||||
json.dumps({"result": "PASS", "restarted_containers": changes}, indent=2) + "\n"
|
||||
)
|
||||
(ROOT / "evidence/persistence-checks.txt").write_text(result.stdout)
|
||||
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Acceptance suite; lifecycle and persistence are intentionally explicit operations."""
|
||||
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
python = str(root / ".venv/bin/python") if (root / ".venv/bin/python").exists() else "python3"
|
||||
|
||||
|
||||
def run(*args):
|
||||
subprocess.run(args, cwd=root, check=True)
|
||||
|
||||
|
||||
run("make", "check", "validate", "lint", "PYTHON=" + python)
|
||||
run("docker", "compose", "config", "--quiet")
|
||||
run("make", "test", "test-security", "PYTHON=" + python)
|
||||
run(python, "tests/lab7_security.py")
|
||||
run(python, "tests/lab7_lifecycle.py")
|
||||
run(python, "tests/lab7_s3_rotation.py")
|
||||
run(python, "tests/lab7_audit.py")
|
||||
print("PASS: lab7 acceptance; run documented persistence and both failovers separately.")
|
||||
Reference in New Issue
Block a user