This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Measure Argon2id cost on THIS stand and derive the login-DoS budget. Usage (inside the app image or any venv with argon2-cffi):
|
||||
python scripts/argon2_bench.py [--runs 20]
|
||||
Budget = concurrency limit (ARGON2_CONCURRENCY per replica) x single-hash time: with c slots one replica can verify at most c / t logins per second;
|
||||
the shared Redis rate limit (30 attempts/min/IP, 10 failures/min/user) keeps the attacker far below that."""
|
||||
import argparse, statistics, time
|
||||
from argon2 import PasswordHasher, Type
|
||||
|
||||
ap = argparse.ArgumentParser(); ap.add_argument("--runs", type=int, default=20); a = ap.parse_args()
|
||||
for m, t, p in ((19456, 2, 1), (47104, 1, 1), (65536, 3, 4)):
|
||||
ph = PasswordHasher(time_cost=t, memory_cost=m, parallelism=p, type=Type.ID)
|
||||
h = ph.hash("benchmark-password"); xs = []
|
||||
for _ in range(a.runs):
|
||||
s = time.perf_counter(); ph.verify(h, "benchmark-password"); xs.append(time.perf_counter() - s)
|
||||
xs.sort()
|
||||
print(f"m={m//1024} MiB t={t} p={p}: median {statistics.median(xs)*1000:.0f} ms, p95 {xs[int(.95*len(xs))-1]*1000:.0f} ms, max logins/s per slot {1/statistics.median(xs):.1f}")
|
||||
@@ -0,0 +1,27 @@
|
||||
#!/bin/sh
|
||||
# Operator step (idempotent): KV v2 mount, AppRole auth, one policy + one role per service, initial secrets from ./secrets/ops.
|
||||
# AppRole: token_ttl 10m / max 30m, SecretID TTL 24h (re-issued by scripts/bao_secret_id.sh). RoleID is not a secret.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."; . scripts/bao_lib.sh; load_root
|
||||
baoc secrets list -format=json | grep -q "\"kv/\"" || baoc secrets enable -path=kv -version=2 kv >/dev/null
|
||||
baoc auth list -format=json | grep -q "\"approle/\"" || baoc auth enable approle >/dev/null
|
||||
for r in api worker dispatcher sweeper; do
|
||||
baoc policy write "$r" - < "infra/openbao/policies/$r.hcl" >/dev/null
|
||||
baoc write "auth/approle/role/$r" token_policies="$r" token_ttl=10m token_max_ttl=30m secret_id_ttl=24h secret_id_num_uses=0 >/dev/null
|
||||
mkdir -p "$S/approle/$r"
|
||||
baoc read -field=role_id "auth/approle/role/$r/role-id" > "$S/approle/$r/role_id"
|
||||
chmod 644 "$S/approle/$r/role_id"
|
||||
done
|
||||
O="$S/ops"
|
||||
python3 - "$O" <<"PY" | while IFS=" " read -r path json; do printf "%s" "$json" | baoc kv put "kv/$path" - >/dev/null; done
|
||||
import json, sys
|
||||
o = sys.argv[1]; r = lambda n: open(f"{o}/{n}").read().strip()
|
||||
data = {
|
||||
"api": {"db_password": r("db_api_password"), "redis_password": r("redis_api_password"), "s3_access_key": "svc-api", "s3_secret_key": r("s3_api_secret")},
|
||||
"worker": {"db_password": r("db_worker_password"), "s3_access_key": "svc-worker", "s3_secret_key": r("s3_worker_secret")},
|
||||
"dispatcher": {"db_password": r("db_dispatcher_password")},
|
||||
"sweeper": {"db_password": r("db_sweeper_password"), "s3_access_key": "svc-sweeper", "s3_secret_key": r("s3_sweeper_secret")},
|
||||
}
|
||||
for p, d in data.items(): print(p + "\t" + json.dumps(d))
|
||||
PY
|
||||
echo "OpenBao bootstrapped: kv/, approle, policies and roles for api worker dispatcher sweeper"
|
||||
@@ -0,0 +1,17 @@
|
||||
#!/bin/sh
|
||||
# ONE-TIME operator step: initialise OpenBao (3 key shares, threshold 2). Shares and root token go to ./secrets/operator
|
||||
# as separate 0600 files: the operator is expected to move shares to different custodians. Nothing is printed.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."; . scripts/bao_lib.sh
|
||||
umask 077; mkdir -p "$OPD"
|
||||
if baoc status -format=json 2>/dev/null | grep -q "\"initialized\": true"; then echo "OpenBao already initialised"; exit 0; fi
|
||||
baoc operator init -key-shares=3 -key-threshold=2 -format=json > "$OPD/init.json"
|
||||
python3 - "$OPD" <<"PY"
|
||||
import json, os, sys
|
||||
d = sys.argv[1]; j = json.load(open(d + "/init.json"))
|
||||
for i, k in enumerate(j["unseal_keys_b64"], 1):
|
||||
open(f"{d}/unseal-{i}", "w").write(k)
|
||||
open(d + "/root_token", "w").write(j["root_token"])
|
||||
os.remove(d + "/init.json")
|
||||
PY
|
||||
echo "initialised: unseal-1..3 and root_token written to $OPD (keep them OUT of Git and OUT of the stand)"
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/bin/sh
|
||||
# Shared helpers for operator scripts. The root token lives only in ./secrets/operator (0600, outside Git, outside any image/volume).
|
||||
S="${SECRETS_DIR:-secrets}"; OPD="$S/operator"
|
||||
# baoc <args...>: run the bao CLI. BAO_LOCAL=1 uses a host binary; default is `docker compose exec` into the openbao container.
|
||||
baoc() {
|
||||
if [ -n "${BAO_LOCAL:-}" ]; then
|
||||
BAO_ADDR="${BAO_LOCAL_ADDR:-https://localhost:8200}" BAO_CACERT="$S/pki/ca/ca.crt" BAO_TOKEN="${BAO_TOKEN_VALUE:-}" "${BAO_BIN:-bao}" "$@"
|
||||
else
|
||||
docker compose exec -T -e BAO_ADDR=https://openbao:8200 -e BAO_CACERT=/run/pki/ca.crt -e BAO_TOKEN="${BAO_TOKEN_VALUE:-}" openbao bao "$@"
|
||||
fi
|
||||
}
|
||||
load_root() { [ -f "$OPD/root_token" ] || { echo "no operator root token: run scripts/bao_init.sh" >&2; exit 1; }; BAO_TOKEN_VALUE="$(cat "$OPD/root_token")"; }
|
||||
@@ -0,0 +1,11 @@
|
||||
#!/bin/sh
|
||||
# Issue a fresh short-lived SecretID (24 h) into ./secrets/approle/<role>/secret_id. Usage: bao_secret_id.sh <role|all>
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."; . scripts/bao_lib.sh; load_root
|
||||
roles="${1:-all}"; [ "$roles" = all ] && roles="api worker dispatcher sweeper"
|
||||
for r in $roles; do
|
||||
mkdir -p "$S/approle/$r"
|
||||
baoc write -f -field=secret_id "auth/approle/role/$r/secret-id" > "$S/approle/$r/secret_id.new"
|
||||
chmod 644 "$S/approle/$r/secret_id.new"; mv -f "$S/approle/$r/secret_id.new" "$S/approle/$r/secret_id"
|
||||
echo "secret_id issued for $r"
|
||||
done
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
# Operator step after EVERY OpenBao restart (the vault starts sealed). Needs any 2 of the 3 shares.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."; . scripts/bao_lib.sh
|
||||
for i in 1 2 3; do
|
||||
baoc status -format=json 2>/dev/null | grep -q "\"sealed\": false" && { echo "OpenBao unsealed"; exit 0; }
|
||||
[ -f "$OPD/unseal-$i" ] && baoc operator unseal "$(cat "$OPD/unseal-$i")" >/dev/null
|
||||
done
|
||||
baoc status -format=json 2>/dev/null | grep -q "\"sealed\": false" && echo "OpenBao unsealed" || { echo "still sealed: need 2 shares" >&2; exit 1; }
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
# Operator bootstrap, idempotent, nothing printed: local PKI, random service passwords, Redis ACL file, .env. All under ./secrets (0700, ignored by Git).
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
S="${SECRETS_DIR:-secrets}"; O="$S/ops"
|
||||
umask 077; mkdir -p "$O"; chmod 700 "$S"
|
||||
gen() { [ -s "$O/$1" ] || { openssl rand -base64 36 | tr -d '/+=\n' | cut -c1-32 > "$O/$1"; }; }
|
||||
for n in postgres_password db_api_password db_worker_password db_dispatcher_password db_sweeper_password \
|
||||
redis_api_password redis_health_password s3_root_password s3_api_secret s3_worker_secret s3_sweeper_secret grafana_admin_password kafka_ssl_password; do gen "$n"; done
|
||||
sh scripts/pki.sh init
|
||||
[ -s "$O/s3_root_user" ] || printf 'root-%s' "$(openssl rand -hex 4)" > "$O/s3_root_user"
|
||||
h() { printf %s "$(cat "$O/$1")" | sha256sum | cut -d' ' -f1; }
|
||||
cat > "$O/redis_users.acl" <<ACL
|
||||
user default off
|
||||
user api on #$(h redis_api_password) ~session:* ~rl:* resetchannels -@all +get +set +setex +del +incr +incrby +expire +ttl +ping +multi +exec +client|setinfo
|
||||
user health on #$(h redis_health_password) resetkeys resetchannels -@all +ping
|
||||
ACL
|
||||
chmod 644 "$O"/* # ./secrets is 0700: only the operator can enter; containers run as other uids and mount single files read-only
|
||||
[ -f .env ] || { cp .env.example .env; }
|
||||
echo "bootstrap done (PKI, passwords, Redis ACL). Next: scripts/up.sh"
|
||||
+54
-54
@@ -1,54 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline structural checks; full schema validation is a separate target."""
|
||||
import ast
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
def main():
|
||||
lab = json.loads((ROOT/'lab.json').read_text())['number']
|
||||
spec = json.loads((ROOT/'contracts/openapi.json').read_text())
|
||||
assert spec['openapi']=='3.1.0'
|
||||
assert spec['info']['version']=='1.%d.0'%lab
|
||||
operation_ids = set()
|
||||
def walk(value):
|
||||
if isinstance(value,dict):
|
||||
if '$ref' in value:
|
||||
pointer = value['$ref']
|
||||
assert pointer.startswith('#/'), 'unexpected external reference'
|
||||
target = spec
|
||||
for part in pointer[2:].split('/'):
|
||||
target = target[part.replace('~1','/').replace('~0','~')]
|
||||
for v in value.values():
|
||||
walk(v)
|
||||
elif isinstance(value,list):
|
||||
for v in value:
|
||||
walk(v)
|
||||
walk(spec)
|
||||
for route,methods in spec['paths'].items():
|
||||
placeholders = set(re.findall(r'\{([^}]+)\}',route))
|
||||
for method,op in methods.items():
|
||||
assert op['operationId'] not in operation_ids, 'duplicate operationId'
|
||||
operation_ids.add(op['operationId'])
|
||||
params = {p['name'] for p in op.get('parameters',[]) if p['in']=='path' and p.get('required')}
|
||||
assert placeholders==params, 'path parameter mismatch: '+route
|
||||
for response in op['responses'].values():
|
||||
assert 'X-Request-Id' in response['headers']
|
||||
if lab>=3:
|
||||
assert 'X-Instance-Id' in response['headers']
|
||||
assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2)
|
||||
assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4)
|
||||
for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')):
|
||||
ast.parse(file.read_text(),filename=str(file))
|
||||
for file in ROOT.rglob('*.json'):
|
||||
if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts):
|
||||
continue
|
||||
json.loads(file.read_text())
|
||||
for required in ('README.md','COURSE.md','CONTRIBUTING.md','REPORT.md','contracts/README.md','tests/smoke.py','tests/README.md'):
|
||||
assert (ROOT/required).is_file(), 'missing '+required
|
||||
print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.')
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
#!/usr/bin/env python3
|
||||
"""Offline structural checks; full schema validation is a separate target."""
|
||||
import ast
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
def main():
|
||||
lab = json.loads((ROOT/'lab.json').read_text())['number']
|
||||
spec = json.loads((ROOT/'contracts/openapi.json').read_text())
|
||||
assert spec['openapi']=='3.1.0'
|
||||
assert spec['info']['version']=='1.%d.0'%lab
|
||||
operation_ids = set()
|
||||
def walk(value):
|
||||
if isinstance(value,dict):
|
||||
if '$ref' in value:
|
||||
pointer = value['$ref']
|
||||
assert pointer.startswith('#/'), 'unexpected external reference'
|
||||
target = spec
|
||||
for part in pointer[2:].split('/'):
|
||||
target = target[part.replace('~1','/').replace('~0','~')]
|
||||
for v in value.values():
|
||||
walk(v)
|
||||
elif isinstance(value,list):
|
||||
for v in value:
|
||||
walk(v)
|
||||
walk(spec)
|
||||
for route,methods in spec['paths'].items():
|
||||
placeholders = set(re.findall(r'\{([^}]+)\}',route))
|
||||
for method,op in methods.items():
|
||||
assert op['operationId'] not in operation_ids, 'duplicate operationId'
|
||||
operation_ids.add(op['operationId'])
|
||||
params = {p['name'] for p in op.get('parameters',[]) if p['in']=='path' and p.get('required')}
|
||||
assert placeholders==params, 'path parameter mismatch: '+route
|
||||
for response in op['responses'].values():
|
||||
assert 'X-Request-Id' in response['headers']
|
||||
if lab>=3:
|
||||
assert 'X-Instance-Id' in response['headers']
|
||||
assert ('/api/v1/auth/sessions' in spec['paths']) == (lab>=2)
|
||||
assert ('/api/v1/attachments/{attachment_id}' in spec['paths']) == (lab>=4)
|
||||
for file in list((ROOT/'tests').glob('*.py'))+list((ROOT/'scripts').glob('*.py')):
|
||||
ast.parse(file.read_text(),filename=str(file))
|
||||
for file in ROOT.rglob('*.json'):
|
||||
if any(part in {'.git','.venv','node_modules','vendor','output'} for part in file.parts):
|
||||
continue
|
||||
json.loads(file.read_text())
|
||||
for required in ('README.md','COURSE.md','CONTRIBUTING.md','REPORT.md','contracts/README.md','tests/smoke.py','tests/README.md'):
|
||||
assert (ROOT/required).is_file(), 'missing '+required
|
||||
print('PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.')
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab 7: separate least-privilege PostgreSQL roles (idempotent; run by the one-shot `migrate` service as the owner role, after migrations).
|
||||
|
||||
Passwords are read from the operator files mounted at /run/secrets (the same values the operator loaded into OpenBao).
|
||||
python scripts/db_roles.py create/update roles, grants and passwords
|
||||
python scripts/db_roles.py --terminate ROLE additionally kill live sessions of ROLE (credential rotation / revocation)
|
||||
The API role has no DDL, the worker cannot touch users/messages/sessions, the dispatcher cannot touch attachments metadata beyond job state.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
import psycopg
|
||||
from psycopg import sql
|
||||
|
||||
SECRETS = os.getenv("OPS_SECRETS_DIR", "/run/secrets")
|
||||
# role -> {table: privileges}. Anything not listed is denied (public schema CREATE is revoked, PUBLIC has no table rights).
|
||||
GRANTS = {
|
||||
"messenger_api": {
|
||||
"users": "SELECT, INSERT, UPDATE", "chats": "SELECT, INSERT", "chat_members": "SELECT, INSERT", "messages": "SELECT, INSERT",
|
||||
"idempotency_records": "SELECT, INSERT, DELETE", "attachments": "SELECT, INSERT, UPDATE", "message_attachments": "SELECT, INSERT",
|
||||
"attachment_variants": "SELECT", "attachment_jobs": "SELECT, INSERT", "job_events": "SELECT, INSERT", "outbox": "SELECT, INSERT",
|
||||
},
|
||||
"messenger_worker": {
|
||||
"attachment_jobs": "SELECT, UPDATE", "attachments": "SELECT, UPDATE", "attachment_variants": "SELECT, INSERT",
|
||||
"job_events": "INSERT", "outbox": "INSERT",
|
||||
},
|
||||
"messenger_dispatcher": {
|
||||
"outbox": "SELECT, INSERT, UPDATE", "attachment_jobs": "SELECT, UPDATE", "attachments": "SELECT, UPDATE", "job_events": "INSERT",
|
||||
},
|
||||
"messenger_sweeper": {"attachments": "SELECT, UPDATE"},
|
||||
}
|
||||
PASSWORD_FILES = {"messenger_api": "db_api_password", "messenger_worker": "db_worker_password",
|
||||
"messenger_dispatcher": "db_dispatcher_password", "messenger_sweeper": "db_sweeper_password"}
|
||||
SEQUENCES = {"messenger_api": ["job_events_id_seq", "outbox_id_seq"], "messenger_worker": ["job_events_id_seq", "outbox_id_seq"],
|
||||
"messenger_dispatcher": ["job_events_id_seq", "outbox_id_seq"], "messenger_sweeper": []}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
terminate = sys.argv[sys.argv.index("--terminate") + 1] if "--terminate" in sys.argv else None
|
||||
last = None
|
||||
for _ in range(30):
|
||||
try:
|
||||
conn = psycopg.connect(connect_timeout=3, autocommit=True)
|
||||
break
|
||||
except psycopg.Error as exc:
|
||||
last = exc
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise SystemExit(f"db_roles: database unavailable: {type(last).__name__}")
|
||||
with conn:
|
||||
db = os.environ["PGDATABASE"]
|
||||
conn.execute(sql.SQL("REVOKE ALL ON DATABASE {} FROM PUBLIC").format(sql.Identifier(db)))
|
||||
conn.execute("REVOKE CREATE ON SCHEMA public FROM PUBLIC")
|
||||
conn.execute("REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC")
|
||||
for role, tables in GRANTS.items():
|
||||
password = open(os.path.join(SECRETS, PASSWORD_FILES[role]), encoding="utf-8").read().strip()
|
||||
if conn.execute("SELECT 1 FROM pg_roles WHERE rolname=%s", (role,)).fetchone() is None:
|
||||
conn.execute(sql.SQL("CREATE ROLE {} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT CONNECTION LIMIT 40").format(sql.Identifier(role)))
|
||||
conn.execute(sql.SQL("ALTER ROLE {} PASSWORD {}").format(sql.Identifier(role), sql.Literal(password)))
|
||||
conn.execute(sql.SQL("GRANT CONNECT ON DATABASE {} TO {}").format(sql.Identifier(db), sql.Identifier(role)))
|
||||
conn.execute(sql.SQL("GRANT USAGE ON SCHEMA public TO {}").format(sql.Identifier(role)))
|
||||
conn.execute(sql.SQL("REVOKE ALL ON ALL TABLES IN SCHEMA public FROM {}").format(sql.Identifier(role)))
|
||||
for table, privs in tables.items():
|
||||
conn.execute(sql.SQL("GRANT {} ON {} TO {}").format(sql.SQL(privs), sql.Identifier(table), sql.Identifier(role)))
|
||||
for seq in SEQUENCES[role]:
|
||||
conn.execute(sql.SQL("GRANT USAGE ON SEQUENCE {} TO {}").format(sql.Identifier(seq), sql.Identifier(role)))
|
||||
print(f"role {role}: {len(tables)} tables granted", flush=True)
|
||||
if terminate:
|
||||
n = conn.execute("SELECT count(pg_terminate_backend(pid)) FROM pg_stat_activity WHERE usename=%s", (terminate,)).fetchone()[0]
|
||||
print(f"terminated {n} sessions of {terminate}", flush=True)
|
||||
print("PASS: database roles ready", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/bin/sh
|
||||
# Track 1 incident response for a compromised worker (isolated lab stand). Order matters:
|
||||
# 0 keep the OLD credentials (only to prove later that they are dead) 1 stop the worker (jobs stay in Kafka/PostgreSQL)
|
||||
# 2 revoke AppRole 3 rotate DB + S3 secrets (live sessions killed) 4 new worker certificate 5 fresh SecretID, start worker
|
||||
# 6 NEW connections with the old credentials must fail, with the new ones must work (security-tests/revoked_creds.py)
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
S="${SECRETS_DIR:-secrets}"; OLD="$S/incident-old"
|
||||
mkdir -p evidence; rm -rf "$OLD"; umask 077; mkdir -p "$OLD"; umask 022
|
||||
cp "$S/approle/worker/secret_id" "$OLD/secret_id"
|
||||
cp "$S/ops/db_worker_password" "$OLD/db_password"
|
||||
cp "$S/ops/s3_worker_secret" "$OLD/s3_secret"
|
||||
chmod 644 "$OLD"/*
|
||||
date -u +%FT%TZ > evidence/incident-start.txt
|
||||
docker compose stop worker
|
||||
sh scripts/revoke_identity.sh worker
|
||||
sh scripts/rotate_secret.sh db-worker
|
||||
sh scripts/rotate_secret.sh s3-worker
|
||||
sh scripts/pki.sh leaf worker
|
||||
sh scripts/bao_secret_id.sh worker
|
||||
docker compose up -d --no-deps worker
|
||||
date -u +%FT%TZ > evidence/incident-end.txt
|
||||
# step 6: fresh connections, public CA only; the saved old secrets are removed afterwards (also on failure)
|
||||
rc=0
|
||||
docker run --rm --network mtusi-lab7_backend --user 10001:10001 --read-only --cap-drop ALL --security-opt no-new-privileges:true \
|
||||
-v "$PWD/security-tests:/t:ro" -v "$PWD/$S/pki/ca:/pki/ca:ro" -v "$PWD/$OLD:/old:ro" -v "$PWD/$S/approle/worker:/approle:ro" \
|
||||
--entrypoint python mtusi-lab7-app:1.0.0 /t/revoked_creds.py | tee evidence/revoked-creds.txt || rc=$?
|
||||
rm -rf "$OLD"
|
||||
[ "$rc" -eq 0 ] || { echo "revocation check FAILED" >&2; exit "$rc"; }
|
||||
echo "worker recovered; old credentials are dead on new connections (evidence/revoked-creds.txt)"
|
||||
echo "also run: security-tests/run_in_net.sh worker_compromise.py --profile after"
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Apply SQL migrations once, before any API replica is started."""
|
||||
from pathlib import Path
|
||||
import os
|
||||
import time
|
||||
import psycopg
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
CONNINFO = os.getenv("DATABASE_URL", "")
|
||||
|
||||
def main():
|
||||
last_error = None
|
||||
for _ in range(30):
|
||||
try:
|
||||
with psycopg.connect(CONNINFO, connect_timeout=3) as conn:
|
||||
conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations (version TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT now())")
|
||||
conn.commit()
|
||||
for path in sorted((ROOT / "migrations").glob("*.sql")):
|
||||
version = path.name
|
||||
if conn.execute("SELECT 1 FROM schema_migrations WHERE version=%s", (version,)).fetchone():
|
||||
continue
|
||||
sql = path.read_text(encoding="utf-8")
|
||||
with conn.transaction():
|
||||
for statement in sql.split(";"):
|
||||
if statement.strip():
|
||||
conn.execute(statement)
|
||||
conn.execute("INSERT INTO schema_migrations(version) VALUES (%s)", (version,))
|
||||
print(f"APPLIED {version}", flush=True)
|
||||
print("PASS: migrations complete", flush=True)
|
||||
return
|
||||
except Exception as exc:
|
||||
last_error = exc
|
||||
time.sleep(1)
|
||||
raise SystemExit(f"Migration failed after retries: {type(last_error).__name__}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,85 @@
|
||||
#!/bin/sh
|
||||
# Local PKI for the lab stand. Operator-run, outside Git: everything is written under ./secrets (ignored by Git).
|
||||
# scripts/pki.sh init create root CA, workload CA and all leaf identities (idempotent: existing files are kept)
|
||||
# scripts/pki.sh leaf <name> re-issue ONE leaf with a NEW key (rotation, no image rebuild); the old file is replaced atomically
|
||||
# Identity model: root CA signs infrastructure leaves; intermediate "workload CA" signs application identities (api, worker, dispatcher, sweeper).
|
||||
set -eu
|
||||
umask 022
|
||||
S="${SECRETS_DIR:-secrets}"; PKI="$S/pki"; CA="$PKI/ca"
|
||||
INFRA_DAYS="${INFRA_DAYS:-90}"; WORKLOAD_DAYS="${WORKLOAD_DAYS:-14}"
|
||||
|
||||
mkca() {
|
||||
[ -f "$CA/ca.crt" ] && return 0
|
||||
mkdir -p "$CA"
|
||||
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 3650 -subj "/CN=mtusi-lab7-root-ca" \
|
||||
-addext "basicConstraints=critical,CA:TRUE" -addext "keyUsage=critical,keyCertSign,cRLSign" -keyout "$CA/ca.key" -out "$CA/ca.crt" 2>/dev/null
|
||||
chmod 600 "$CA/ca.key"
|
||||
}
|
||||
mkworkloadca() {
|
||||
[ -f "$CA/workload-ca.crt" ] && return 0
|
||||
openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -subj "/CN=mtusi-lab7-workload-ca" -keyout "$CA/workload-ca.key" -out "$CA/workload-ca.csr" 2>/dev/null
|
||||
printf "basicConstraints=critical,CA:TRUE,pathlen:0\nkeyUsage=critical,keyCertSign,cRLSign\n" > "$CA/wl.ext"
|
||||
openssl x509 -req -in "$CA/workload-ca.csr" -CA "$CA/ca.crt" -CAkey "$CA/ca.key" -set_serial "0x$(openssl rand -hex 8)" -days 1825 -extfile "$CA/wl.ext" -out "$CA/workload-ca.crt" 2>/dev/null
|
||||
chmod 600 "$CA/workload-ca.key"
|
||||
}
|
||||
# issue <name> <root|workload> <subjectAltName list> <days>
|
||||
issue() {
|
||||
name="$1"; signer="$2"; sans="$3"; days="$4"; d="$PKI/$name"; tmp="$PKI/.tmp-$name"
|
||||
rm -rf "$tmp"; mkdir -p "$tmp"
|
||||
openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -subj "/CN=$name" -keyout "$tmp/tls.key" -out "$tmp/tls.csr" 2>/dev/null
|
||||
printf "basicConstraints=CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=serverAuth,clientAuth\nsubjectAltName=%s\n" "$sans" > "$tmp/ext"
|
||||
if [ "$signer" = workload ]; then ca=workload-ca; else ca=ca; fi
|
||||
openssl x509 -req -in "$tmp/tls.csr" -CA "$CA/$ca.crt" -CAkey "$CA/$ca.key" -set_serial "0x$(openssl rand -hex 8)" -days "$days" -extfile "$tmp/ext" -out "$tmp/leaf.crt" 2>/dev/null
|
||||
if [ "$signer" = workload ]; then cat "$tmp/leaf.crt" "$CA/workload-ca.crt" > "$tmp/tls.crt"; else cp "$tmp/leaf.crt" "$tmp/tls.crt"; fi
|
||||
cp "$CA/ca.crt" "$tmp/ca.crt"
|
||||
cat "$tmp/tls.key" "$tmp/tls.crt" > "$tmp/keystore.pem" # key first: HAProxy "crt" and Kafka PEM keystore format
|
||||
openssl pkcs12 -export -in "$tmp/tls.crt" -inkey "$tmp/tls.key" -out "$tmp/keystore.p12" -passout "file:$S/ops/kafka_ssl_password" 2>/dev/null
|
||||
openssl pkcs12 -export -nokeys -in "$CA/ca.crt" -out "$tmp/truststore.p12" -passout "file:$S/ops/kafka_ssl_password" 2>/dev/null
|
||||
rm -f "$tmp/tls.csr" "$tmp/ext" "$tmp/leaf.crt"
|
||||
chmod 644 "$tmp"/* # ./secrets itself is 0700; containers run as other uids
|
||||
mkdir -p "$d"; mv -f "$tmp"/* "$d"/; rmdir "$tmp"
|
||||
echo "issued $name ($signer CA, $days d)"
|
||||
}
|
||||
spec() { # name signer SANs -- the single source of truth for identities
|
||||
cat <<EOF2
|
||||
lb-public root DNS:localhost,IP:127.0.0.1
|
||||
lb root DNS:lb
|
||||
postgres root DNS:postgres
|
||||
redis root DNS:redis
|
||||
s3 root DNS:s3,DNS:localhost
|
||||
kafka root DNS:kafka
|
||||
kafka-admin root DNS:kafka-admin
|
||||
otel-collector root DNS:otel-collector
|
||||
prometheus root DNS:prometheus
|
||||
loki root DNS:loki
|
||||
tempo root DNS:tempo
|
||||
grafana root DNS:grafana,DNS:localhost,IP:127.0.0.1
|
||||
openbao root DNS:openbao,DNS:localhost,IP:127.0.0.1
|
||||
api workload DNS:api
|
||||
worker workload DNS:worker
|
||||
dispatcher workload DNS:dispatcher
|
||||
sweeper workload DNS:sweeper
|
||||
EOF2
|
||||
}
|
||||
days_for() { if [ "$1" = workload ]; then echo "$WORKLOAD_DAYS"; else echo "$INFRA_DAYS"; fi; }
|
||||
|
||||
case "${1:-}" in
|
||||
init)
|
||||
umask 077; mkdir -p "$S" "$PKI"; umask 022; chmod 700 "$S"
|
||||
mkca; mkworkloadca
|
||||
spec | while read -r n s sans; do [ -f "$PKI/$n/tls.crt" ] || issue "$n" "$s" "$sans" "$(days_for "$s")"; done
|
||||
# Negative-test identities (never mounted into the stand): same root CA but not allowed; and a foreign CA.
|
||||
[ -f "$PKI/outsider/tls.crt" ] || issue outsider root DNS:outsider "$INFRA_DAYS"
|
||||
if [ ! -f "$PKI/rogue/tls.crt" ]; then
|
||||
mkdir -p "$PKI/rogue"
|
||||
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 30 -subj "/CN=rogue-ca" -keyout "$PKI/rogue/rogue-ca.key" -out "$PKI/rogue/rogue-ca.crt" 2>/dev/null
|
||||
openssl req -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -subj "/CN=lb" -keyout "$PKI/rogue/tls.key" -out "$PKI/rogue/tls.csr" 2>/dev/null
|
||||
printf "subjectAltName=DNS:lb\nextendedKeyUsage=clientAuth\n" > "$PKI/rogue/ext"
|
||||
openssl x509 -req -in "$PKI/rogue/tls.csr" -CA "$PKI/rogue/rogue-ca.crt" -CAkey "$PKI/rogue/rogue-ca.key" -CAcreateserial -days 30 -extfile "$PKI/rogue/ext" -out "$PKI/rogue/tls.crt" 2>/dev/null
|
||||
fi ;;
|
||||
leaf)
|
||||
n="${2:?usage: pki.sh leaf <name>}"
|
||||
line="$(spec | awk -v n="$n" "\$1==n")"; [ -n "$line" ] || { echo "unknown identity $n" >&2; exit 1; }
|
||||
set -- $line; issue "$1" "$2" "$3" "$(days_for "$2")" ;;
|
||||
*) echo "usage: pki.sh init | leaf <name>" >&2; exit 2 ;;
|
||||
esac
|
||||
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Operator tool: failed-job registry and SAFE explicit replay (lab5, level 4).
|
||||
|
||||
docker compose exec worker python scripts/replay_failed.py --list
|
||||
docker compose exec worker python scripts/replay_failed.py --job-id <uuid> --reason "ticket-123"
|
||||
|
||||
Replay never executes a duplicate of a successful job: it requires status=failed, that the staging source still exists,
|
||||
and that the effect (all variants of the pipeline version) is NOT already present. Everything happens in ONE transaction
|
||||
(state change + audit event + outbox row), so the new attempt is delivered by the normal dispatcher path.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
|
||||
import psycopg
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from src import jobs # noqa: E402
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--list", action="store_true")
|
||||
p.add_argument("--job-id")
|
||||
p.add_argument("--reason", default="operator replay")
|
||||
a = p.parse_args()
|
||||
with psycopg.connect(connect_timeout=5) as conn:
|
||||
if a.list or not a.job_id:
|
||||
for r in conn.execute("SELECT job_id, attachment_id, error_code, attempt, updated_at FROM attachment_jobs WHERE status='failed' ORDER BY updated_at"):
|
||||
print(*r, sep="\t")
|
||||
return 0
|
||||
row = conn.execute("SELECT j.status, j.attachment_id, j.pipeline_version, a.staging_key FROM attachment_jobs j "
|
||||
"JOIN attachments a ON a.id=j.attachment_id WHERE j.job_id=%s FOR UPDATE OF j", (a.job_id,)).fetchone()
|
||||
if row is None:
|
||||
print("REFUSED: unknown job"); return 1
|
||||
status, att_id, pv, staging_key = row
|
||||
if status != "failed":
|
||||
print(f"REFUSED: job is {status}, only failed jobs can be replayed"); return 1
|
||||
done = conn.execute("SELECT count(*) FROM attachment_variants WHERE attachment_id=%s AND pipeline_version=%s", (att_id, pv)).fetchone()[0]
|
||||
if done >= len(jobs.VARIANT_ORDER):
|
||||
print("REFUSED: the effect already exists (all variants present)"); return 1
|
||||
if not staging_key:
|
||||
print("REFUSED: staging source expired (retention), upload the file again"); return 1
|
||||
conn.execute("UPDATE attachment_jobs SET status='queued', attempt=0, error_code=NULL, lease_until=NULL, next_attempt_at=now(), updated_at=now() WHERE job_id=%s", (a.job_id,))
|
||||
conn.execute("UPDATE attachments SET status='queued', error_code=NULL, updated_at=now() WHERE id=%s", (att_id,))
|
||||
jobs.add_event(conn, a.job_id, "replay", a.reason[:200])
|
||||
jobs.enqueue(conn, a.job_id, att_id, pv, 1)
|
||||
print(f"REPLAYED job={a.job_id} attachment={att_id}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+10
-10
@@ -1,10 +1,10 @@
|
||||
#!/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
|
||||
#!/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
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
# Restart hook (tests/resilience.py --mode persistence): restarts ALL stores with their volumes (nothing is removed), then re-unseals OpenBao,
|
||||
# refreshes the 24 h SecretIDs and restarts the services that fetch secrets.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose restart postgres redis s3 kafka openbao prometheus loki tempo
|
||||
sh scripts/bao_unseal.sh
|
||||
sh scripts/bao_secret_id.sh all >/dev/null
|
||||
docker compose restart api dispatcher worker s3_sweeper otel-collector grafana
|
||||
@@ -0,0 +1,11 @@
|
||||
#!/bin/sh
|
||||
# Revoke an AppRole identity (stolen RoleID/SecretID/tokens become useless). Usage: revoke_identity.sh <role>
|
||||
# Destroys every SecretID of the role and revokes all tokens issued through AppRole login (apps only hold a token for milliseconds at start).
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."; . scripts/bao_lib.sh; load_root
|
||||
r="${1:?role}"
|
||||
for acc in $(baoc list -format=json "auth/approle/role/$r/secret-id" 2>/dev/null | python3 -c "import sys,json; print(' '.join(json.load(sys.stdin)))" 2>/dev/null || true); do
|
||||
baoc write "auth/approle/role/$r/secret-id-accessor/destroy" secret_id_accessor="$acc" >/dev/null
|
||||
done
|
||||
baoc lease revoke -prefix auth/approle/login >/dev/null 2>&1 || true
|
||||
echo "identity $r revoked (SecretIDs destroyed, login tokens revoked)"
|
||||
@@ -0,0 +1,20 @@
|
||||
#!/bin/sh
|
||||
# Rotate ONE working secret without rebuilding images. Usage: rotate_secret.sh db-<api|worker|dispatcher|sweeper> | s3-<api|worker|sweeper>
|
||||
# 1) new random value in ./secrets/ops 2) apply to the store (ALTER ROLE / mc admin user add) and kill old sessions 3) OpenBao KV 4) restart the consumer.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."; . scripts/bao_lib.sh; load_root
|
||||
t="${1:?usage: rotate_secret.sh db-worker|s3-worker|...}"; kind="${t%%-*}"; role="${t#*-}"
|
||||
new="$(openssl rand -base64 36 | tr -d '/+=\n' | cut -c1-32)"
|
||||
case "$kind" in
|
||||
db) f="$S/ops/db_${role}_password"; field=db_password ;;
|
||||
s3) f="$S/ops/s3_${role}_secret"; field=s3_secret_key ;;
|
||||
*) echo "unknown target" >&2; exit 2 ;;
|
||||
esac
|
||||
umask 022; printf %s "$new" > "$f"
|
||||
if [ "$kind" = db ]; then DB_ROLES_ARGS="--terminate messenger_$role" docker compose run --rm -e DB_ROLES_ARGS migrate >/dev/null
|
||||
else docker compose run --rm s3_init >/dev/null; fi
|
||||
baoc kv patch "kv/$role" "$field=$new" >/dev/null
|
||||
sh scripts/bao_secret_id.sh "$role" >/dev/null
|
||||
svc="$role"; [ "$role" = sweeper ] && svc=s3_sweeper
|
||||
docker compose restart "$svc" >/dev/null
|
||||
echo "rotated $t; old value is dead in the store, new value lives in OpenBao only; $svc restarted"
|
||||
@@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Orphan sweeper (lab5): staging/ and attachments/ cleanup, retention of failed staging (see run_once).
|
||||
|
||||
Safety: only objects older than --grace-seconds are candidates (default 3600, far above the few seconds between
|
||||
PUT and COMMIT), and the DB is re-checked immediately before each delete. Default mode is --dry-run.
|
||||
"""
|
||||
import argparse, os, sys, time
|
||||
from pathlib import Path
|
||||
from datetime import datetime, timezone
|
||||
import boto3, psycopg
|
||||
from botocore.config import Config
|
||||
|
||||
def run_once(s3, conn, bucket, grace, apply, retention):
|
||||
"""Lab5 cleanup rules (documented in REPORT.md):
|
||||
1) staging/<k> without any attachments.staging_key row older than grace = orphan of a crash between PUT and COMMIT -> delete
|
||||
(staging of ready attachments is deleted by the worker and its staging_key set to NULL, so a leftover is also an orphan);
|
||||
2) attachments/<id>/... whose attachment row no longer exists -> delete;
|
||||
3) staging of FAILED attachments older than retention -> delete object and NULL staging_key (replay is then impossible).
|
||||
Current work (queued/processing, or failed within retention) is never touched; the DB is re-checked right before each delete."""
|
||||
now = datetime.now(timezone.utc)
|
||||
seen = old = orphans = deleted = 0
|
||||
for prefix in ("staging/", "attachments/"):
|
||||
for page in s3.get_paginator("list_objects_v2").paginate(Bucket=bucket, Prefix=prefix):
|
||||
for obj in page.get("Contents", []):
|
||||
seen += 1
|
||||
key = obj["Key"]
|
||||
if key == "attachments/.ready" or (now - obj["LastModified"]).total_seconds() < grace:
|
||||
continue # fresh: may still be between PUT and COMMIT
|
||||
old += 1
|
||||
if prefix == "staging/":
|
||||
referenced = lambda: conn.execute("SELECT 1 FROM attachments WHERE staging_key=%s", (key,)).fetchone()
|
||||
else:
|
||||
att = key.split("/")[1] if key.count("/") >= 2 else ""
|
||||
referenced = lambda: conn.execute("SELECT 1 FROM attachments WHERE id::text=%s", (att,)).fetchone()
|
||||
if referenced():
|
||||
continue
|
||||
orphans += 1
|
||||
print(("DELETE " if apply else "WOULD-DELETE ") + key, flush=True)
|
||||
if apply and not referenced():
|
||||
s3.delete_object(Bucket=bucket, Key=key); deleted += 1
|
||||
expired = conn.execute("SELECT id, staging_key FROM attachments WHERE status='failed' AND staging_key IS NOT NULL "
|
||||
"AND updated_at < now() - make_interval(secs=>%s)", (retention,)).fetchall()
|
||||
for att_id, skey in expired:
|
||||
print(("EXPIRE-STAGING " if apply else "WOULD-EXPIRE-STAGING ") + skey, flush=True)
|
||||
if apply:
|
||||
s3.delete_object(Bucket=bucket, Key=skey)
|
||||
conn.execute("UPDATE attachments SET staging_key=NULL WHERE id=%s", (att_id,))
|
||||
deleted += 1
|
||||
print(f"sweep: seen={seen} older_than_grace={old} orphans={orphans} failed_expired={len(expired)} deleted={deleted} apply={apply}", flush=True)
|
||||
return orphans, deleted
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--apply", action="store_true", help="really delete (default: dry-run)")
|
||||
p.add_argument("--grace-seconds", type=int, default=int(os.getenv("SWEEP_GRACE_SECONDS", "3600")))
|
||||
p.add_argument("--loop", action="store_true"); p.add_argument("--interval", type=int, default=int(os.getenv("SWEEP_INTERVAL_SECONDS", "600")))
|
||||
p.add_argument("--retention-seconds", type=int, default=int(os.getenv("STAGING_RETENTION_SECONDS", "86400")))
|
||||
a = p.parse_args()
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from src import vault
|
||||
vault.load_into_env("sweeper") # lab 7: DB role messenger_sweeper + S3 key svc-sweeper from OpenBao
|
||||
if a.grace_seconds < 0: sys.exit("grace must be >= 0")
|
||||
s3 = boto3.client("s3", endpoint_url=os.environ["S3_ENDPOINT"], region_name=os.getenv("S3_REGION", "us-east-1"),
|
||||
aws_access_key_id=os.environ["S3_ACCESS_KEY_ID"], aws_secret_access_key=os.environ["S3_SECRET_ACCESS_KEY"], verify=os.getenv("TLS_CA_FILE", "/run/pki/ca.crt"),
|
||||
config=Config(signature_version="s3v4", s3={"addressing_style": "path"}, connect_timeout=3, read_timeout=15, retries={"max_attempts": 2}))
|
||||
bucket = os.environ["S3_BUCKET"]
|
||||
while True:
|
||||
try:
|
||||
with psycopg.connect(connect_timeout=5, autocommit=True) as conn:
|
||||
run_once(s3, conn, bucket, a.grace_seconds, a.apply, a.retention_seconds)
|
||||
except Exception as exc: # keep looping through outages
|
||||
print("sweep failed:", type(exc).__name__, flush=True)
|
||||
if not a.loop: raise
|
||||
if not a.loop: return
|
||||
time.sleep(a.interval)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/bin/sh
|
||||
# Dependency + image scan (results go to evidence/; triage by applicability is written in REPORT.md).
|
||||
set -eu
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
mkdir -p evidence
|
||||
|
||||
# pip-audit: non-zero exit is expected when vulnerabilities are found.
|
||||
docker run --rm \
|
||||
-v "$PWD/requirements.txt:/r.txt:ro" \
|
||||
python:3.12.11-slim-bookworm \
|
||||
sh -c "pip install -q pip-audit && pip-audit -r /r.txt" \
|
||||
> evidence/pip-audit.txt 2>&1 || true
|
||||
|
||||
# Trivy: preserve complete reports, including findings without fixes.
|
||||
scan_failed=0
|
||||
|
||||
for img in \
|
||||
mtusi-lab7-app:1.0.0 \
|
||||
openbao/openbao:2.4.1 \
|
||||
redis:7.4.2-alpine \
|
||||
postgres:17.6-alpine \
|
||||
haproxy:3.2.5-alpine
|
||||
do
|
||||
out="evidence/trivy-$(echo "$img" | tr '/:' '__').txt"
|
||||
|
||||
echo "Scanning $img ..."
|
||||
|
||||
if docker run --rm \
|
||||
-v /var/run/docker.sock:/var/run/docker.sock:ro \
|
||||
aquasec/trivy:0.58.1 image \
|
||||
--severity HIGH,CRITICAL \
|
||||
"$img" > "$out" 2>&1
|
||||
then
|
||||
echo "PASS: $img; report saved to $out"
|
||||
else
|
||||
rc=$?
|
||||
echo "ERROR: Trivy failed for $img (exit code $rc); see $out" >&2
|
||||
scan_failed=1
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "$scan_failed" -ne 0 ]; then
|
||||
echo "Scan failed for one or more images" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "scan finished: evidence/pip-audit.txt, evidence/trivy-*.txt"
|
||||
+10
-10
@@ -1,10 +1,10 @@
|
||||
#!/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
|
||||
#!/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,17 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
: "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID must be supplied by tests/resilience.py}"
|
||||
found=""
|
||||
for id in $(docker compose ps -q api); do
|
||||
host=$(docker inspect --format '{{.Config.Hostname}}' "$id")
|
||||
if [ "$host" = "$TARGET_INSTANCE_ID" ]; then
|
||||
found="$id"
|
||||
break
|
||||
fi
|
||||
done
|
||||
if [ -z "$found" ]; then
|
||||
echo "No running API container matches TARGET_INSTANCE_ID" >&2
|
||||
exit 1
|
||||
fi
|
||||
# Stop exactly one API replica and intentionally leave it stopped for the failover check.
|
||||
docker stop --time 10 "$found" >/dev/null
|
||||
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
# Operator: first start or start after a full stop. OpenBao is started first, initialised once, unsealed, filled; then the rest.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
sh scripts/bootstrap.sh
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d --build init_perms openbao
|
||||
i=0; until [ "$(docker inspect -f '{{.State.Health.Status}}' "$(docker compose ps -q openbao)")" = healthy ]; do i=$((i+1)); [ $i -lt 60 ] || exit 1; sleep 1; done
|
||||
sh scripts/bao_init.sh
|
||||
sh scripts/bao_unseal.sh
|
||||
sh scripts/bao_bootstrap.sh
|
||||
sh scripts/bao_secret_id.sh all
|
||||
docker compose --env-file .env up -d --build
|
||||
echo "stack started; wait for https://localhost:8443/health/ready, then: make test CA_FILE=\$PWD/secrets/pki/ca/ca.crt"
|
||||
+23
-23
@@ -1,23 +1,23 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Full OpenAPI and JSON Schema checks; install requirements-dev.txt first."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
from openapi_spec_validator import validate
|
||||
from jsonschema import Draft202012Validator
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
spec = json.loads((root/'contracts/openapi.json').read_text())
|
||||
validate(spec)
|
||||
from referencing import Registry, Resource
|
||||
# The base URI resolves local #/components references inside examples.
|
||||
resource = dict(spec, **{'$schema': 'https://json-schema.org/draft/2020-12/schema'})
|
||||
registry = Registry().with_resource('urn:mtusi:openapi', Resource.from_contents(resource))
|
||||
for name, example in json.loads((root/'contracts/examples.json').read_text()).items():
|
||||
schema = {'$ref': 'urn:mtusi:openapi#/components/schemas/' + name}
|
||||
Draft202012Validator(schema, registry=registry).validate(example)
|
||||
for path in (root/'contracts').glob('*.schema.json'):
|
||||
schema = json.loads(path.read_text())
|
||||
Draft202012Validator.check_schema(schema)
|
||||
for example in schema.get('examples',[]):
|
||||
Draft202012Validator(schema).validate(example)
|
||||
print('PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.')
|
||||
#!/usr/bin/env python3
|
||||
"""Full OpenAPI and JSON Schema checks; install requirements-dev.txt first."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
from openapi_spec_validator import validate
|
||||
from jsonschema import Draft202012Validator
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
spec = json.loads((root/'contracts/openapi.json').read_text())
|
||||
validate(spec)
|
||||
from referencing import Registry, Resource
|
||||
# The base URI resolves local #/components references inside examples.
|
||||
resource = dict(spec, **{'$schema': 'https://json-schema.org/draft/2020-12/schema'})
|
||||
registry = Registry().with_resource('urn:mtusi:openapi', Resource.from_contents(resource))
|
||||
for name, example in json.loads((root/'contracts/examples.json').read_text()).items():
|
||||
schema = {'$ref': 'urn:mtusi:openapi#/components/schemas/' + name}
|
||||
Draft202012Validator(schema, registry=registry).validate(example)
|
||||
for path in (root/'contracts').glob('*.schema.json'):
|
||||
schema = json.loads(path.read_text())
|
||||
Draft202012Validator.check_schema(schema)
|
||||
for example in schema.get('examples',[]):
|
||||
Draft202012Validator(schema).validate(example)
|
||||
print('PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.')
|
||||
|
||||
Reference in New Issue
Block a user