Выполнить лабораторную 7 по безопасности мессенджера
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Remove old staging objects only when no live attachment needs them."""
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
|
||||
import psycopg
|
||||
from jobs import s3_client
|
||||
|
||||
DB = os.environ["DATABASE_URL"]
|
||||
BUCKET = os.getenv("S3_BUCKET", "messenger-attachments")
|
||||
RETENTION = max(3600, int(os.getenv("STAGING_RETENTION_SECONDS", "86400")))
|
||||
|
||||
|
||||
def main():
|
||||
dry_run = "--apply" not in sys.argv
|
||||
s3 = s3_client()
|
||||
removed = kept = 0
|
||||
token = None
|
||||
while True:
|
||||
args = {"Bucket": BUCKET, "Prefix": "staging/", "MaxKeys": 500}
|
||||
if token: args["ContinuationToken"] = token
|
||||
page = s3.list_objects_v2(**args)
|
||||
for obj in page.get("Contents", []):
|
||||
key, modified = obj["Key"], obj["LastModified"]
|
||||
age = (datetime.now(timezone.utc) - modified).total_seconds()
|
||||
if age < RETENTION:
|
||||
kept += 1; continue
|
||||
with psycopg.connect(DB) as conn:
|
||||
# Replay takes the same row lock before validating the retained input.
|
||||
live = conn.execute(
|
||||
"SELECT status,updated_at FROM attachments WHERE staging_key=%s FOR UPDATE", (key,)
|
||||
).fetchone()
|
||||
if live and (live[0] in ("queued", "processing") or
|
||||
(datetime.now(timezone.utc) - live[1]).total_seconds() < RETENTION):
|
||||
kept += 1
|
||||
continue
|
||||
if not dry_run:
|
||||
s3.delete_object(Bucket=BUCKET, Key=key)
|
||||
removed += 1
|
||||
if not page.get("IsTruncated"):
|
||||
break
|
||||
token = page["NextContinuationToken"]
|
||||
print(f"mode={'dry-run' if dry_run else 'apply'} retention_seconds={RETENTION} candidates={removed} kept={kept}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
umask 077
|
||||
if [ ! -e .env ]; then cp .env.example .env; fi
|
||||
exec python3 scripts/operator.py prepare
|
||||
@@ -0,0 +1,11 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
. /run/s3/env
|
||||
export DATABASE_URL="$(cat /run/operator/database_url)"
|
||||
export S3_ACCESS_KEY_ID="$RUSTFS_ACCESS_KEY"
|
||||
export S3_SECRET_ACCESS_KEY="$RUSTFS_SECRET_KEY"
|
||||
case "${1:-}" in
|
||||
cleanup_staging|replay_failed|reprocess_pipeline) script=$1; shift ;;
|
||||
*) echo "Use cleanup_staging, replay_failed or reprocess_pipeline" >&2; exit 2 ;;
|
||||
esac
|
||||
exec python "/app/scripts/$script.py" "$@"
|
||||
Executable
+27
@@ -0,0 +1,27 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose exec -T api python - <<'PY'
|
||||
from argon2 import PasswordHasher
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from time import perf_counter
|
||||
import json
|
||||
|
||||
password = "locally generated benchmark fixture"
|
||||
result = {}
|
||||
for memory in (19456, 24576, 32768):
|
||||
h = PasswordHasher(time_cost=2, memory_cost=memory, parallelism=1)
|
||||
digest = h.hash(password)
|
||||
|
||||
def verify(_):
|
||||
start = perf_counter()
|
||||
assert h.verify(digest, password)
|
||||
return (perf_counter() - start) * 1000
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
start = perf_counter()
|
||||
samples = sorted(pool.map(verify, range(40)))
|
||||
result[memory] = {"samples": len(samples), "verify_per_s": round(40/(perf_counter()-start), 1),
|
||||
"p50_ms": round(samples[19], 2), "p95_ms": round(samples[37], 2)}
|
||||
print(json.dumps(result, indent=2))
|
||||
PY
|
||||
Executable
+210
@@ -0,0 +1,210 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Bootstrap and operate the isolated, synthetic lab deployment."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from bao_client import Bao, BaoError
|
||||
from scripts.pki import OPERATOR, ROOT, RUN, SECRETS, init, write
|
||||
|
||||
INIT_STATE = OPERATOR / "bao-init.json"
|
||||
SEED = OPERATOR / "seed.json"
|
||||
|
||||
|
||||
def compose(*arguments, **kwargs):
|
||||
return subprocess.run(["docker", "compose", *arguments], cwd=ROOT, check=True, **kwargs)
|
||||
|
||||
|
||||
def settings():
|
||||
path = ROOT / ".env"
|
||||
return dict(line.split("=", 1) for line in path.read_text().splitlines()
|
||||
if line and not line.startswith("#") and "=" in line) if path.exists() else {}
|
||||
|
||||
|
||||
def administrative_bao():
|
||||
cert = str(SECRETS / "trust" / "openbao.crt")
|
||||
context = ssl.create_default_context(cafile=cert)
|
||||
return Bao("https://127.0.0.1:" + settings().get("BAO_PORT", "8277"), context, timeout=30)
|
||||
|
||||
|
||||
def prepare():
|
||||
init()
|
||||
if not SEED.exists():
|
||||
values = {key: secrets.token_hex(24) for key in ("postgres", "bao_db", "cursor", "grafana")}
|
||||
for role in ("api", "worker", "root"):
|
||||
values[role + "_user"] = role + "-" + secrets.token_hex(8)
|
||||
values[role + "_secret"] = secrets.token_hex(24)
|
||||
write(SEED, json.dumps(values).encode(), 0o600)
|
||||
values = json.loads(SEED.read_text())
|
||||
write(RUN / "postgres" / "postgres_password", values["postgres"].encode())
|
||||
postgres_url = (f"postgresql://owner:{values['postgres']}@postgres:5432/messenger"
|
||||
"?sslmode=verify-full&sslrootcert=/run/operator/ca.crt&connect_timeout=3")
|
||||
write(RUN / "migrate" / "database_url", postgres_url.encode())
|
||||
write(RUN / "migrate" / "ca.crt", (RUN / "postgres" / "ca.crt").read_bytes())
|
||||
write(RUN / "grafana-config" / "grafana_password", values["grafana"].encode())
|
||||
root_s3 = (f"export RUSTFS_ACCESS_KEY={values['root_user']}\n"
|
||||
f"export RUSTFS_SECRET_KEY={values['root_secret']}\n")
|
||||
write(RUN / "s3-store" / "env", root_s3.encode())
|
||||
s3 = root_s3 + "".join(f"{r.upper()}_S3_USER={values[r + '_user']}\n"
|
||||
f"{r.upper()}_S3_PASSWORD={values[r + '_secret']}\n" for r in ("api", "worker"))
|
||||
write(RUN / "s3-bootstrap" / "env", s3.encode())
|
||||
write(RUN / "s3-bootstrap" / "ca.crt", (RUN / "rustfs" / "ca.crt").read_bytes())
|
||||
|
||||
|
||||
def wait_for_bao(bao):
|
||||
for _ in range(30):
|
||||
try:
|
||||
return bao.request("sys/seal-status")
|
||||
except OSError:
|
||||
time.sleep(1)
|
||||
raise SystemExit("OpenBao HTTPS listener unavailable")
|
||||
|
||||
|
||||
def initialize_bao(bao):
|
||||
state = wait_for_bao(bao)
|
||||
if state["initialized"]:
|
||||
if not INIT_STATE.exists():
|
||||
raise SystemExit("The operator's existing init state must be supplied")
|
||||
return
|
||||
if INIT_STATE.exists():
|
||||
raise SystemExit("Existing init material belongs to another storage volume")
|
||||
config = bao.request("sys/init", {"secret_shares": 3, "secret_threshold": 2}, method="PUT")
|
||||
write(INIT_STATE, json.dumps(config).encode(), 0o600)
|
||||
print("Initialized persistent OpenBao. Operator material saved locally with mode 0600.")
|
||||
|
||||
|
||||
def operator_credentials():
|
||||
return json.loads(INIT_STATE.read_text())
|
||||
|
||||
|
||||
def unseal(bao):
|
||||
state = wait_for_bao(bao)
|
||||
if not state["sealed"]:
|
||||
return
|
||||
for share in operator_credentials()["keys_base64"][:2]:
|
||||
state = bao.request("sys/unseal", {"key": share}, method="PUT")
|
||||
if state["sealed"]:
|
||||
raise SystemExit("OpenBao remains sealed")
|
||||
print("OpenBao unsealed by operator.")
|
||||
|
||||
|
||||
def provision_database():
|
||||
config = json.loads(SEED.read_text())
|
||||
sql = rf"""
|
||||
SELECT 'CREATE ROLE messenger_api NOLOGIN' WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname='messenger_api') \gexec
|
||||
SELECT 'CREATE ROLE messenger_worker NOLOGIN' WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname='messenger_worker') \gexec
|
||||
SELECT 'CREATE ROLE bao_db LOGIN CREATEROLE' WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname='bao_db') \gexec
|
||||
ALTER ROLE bao_db PASSWORD '{config['bao_db']}';
|
||||
GRANT messenger_api, messenger_worker TO bao_db WITH ADMIN OPTION;
|
||||
"""
|
||||
compose("exec", "-T", "postgres", "psql", "-X", "-U", "owner", "-d", "messenger",
|
||||
"--set=ON_ERROR_STOP=1", input=sql.encode(), stdout=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def configure_bao(bao):
|
||||
token = operator_credentials()["root_token"]
|
||||
values = json.loads(SEED.read_text())
|
||||
auth = bao.request("sys/auth", token=token)
|
||||
mounts = bao.request("sys/mounts", token=token)
|
||||
if "cert/" not in auth:
|
||||
bao.request("sys/auth/cert", {"type": "cert"}, token)
|
||||
for path, body in (("runtime", {"type": "kv", "options": {"version": "2"}}),
|
||||
("database", {"type": "database"})):
|
||||
if path + "/" not in mounts:
|
||||
bao.request("sys/mounts/" + path, body, token)
|
||||
ca = (RUN / "openbao" / "ca.crt").read_text()
|
||||
bao.request("database/config/messenger", {
|
||||
"plugin_name": "postgresql-database-plugin",
|
||||
"connection_url": ("postgresql://{{username}}:{{password}}@postgres:5432/messenger"
|
||||
"?sslmode=verify-full&sslrootcert=/run/identity/ca.crt"),
|
||||
"username": "bao_db", "password": values["bao_db"],
|
||||
"allowed_roles": ["api", "worker"], "max_open_connections": 3,
|
||||
}, token)
|
||||
policy = (ROOT / "infra/openbao/service-policy.hcl").read_text()
|
||||
for role in ("api", "worker"):
|
||||
bao.request("sys/policies/acl/" + role, {"policy": policy.replace("ROLE", role)}, token)
|
||||
bao.request("auth/cert/certs/" + role, {
|
||||
"certificate": ca, "allowed_common_names": [role],
|
||||
"allowed_uri_sans": ["spiffe://lab7/" + role],
|
||||
"token_policies": [role], "token_no_default_policy": True,
|
||||
"token_ttl": "45s", "token_max_ttl": "150s",
|
||||
}, token)
|
||||
bao.request("database/roles/" + role, {
|
||||
"db_name": "messenger", "default_ttl": "40s", "max_ttl": "120s",
|
||||
"creation_statements": [f"""CREATE ROLE "{{{{name}}}}" WITH LOGIN PASSWORD '{{{{password}}}}'
|
||||
VALID UNTIL '{{{{expiration}}}}' IN ROLE messenger_{role};"""],
|
||||
"renew_statements": ["""ALTER ROLE "{{name}}" VALID UNTIL '{{expiration}}';"""],
|
||||
"revocation_statements": ['DROP ROLE IF EXISTS "{{name}}";'],
|
||||
}, token)
|
||||
try:
|
||||
bao.request("runtime/data/" + role, token=token)
|
||||
except BaoError as exc:
|
||||
if exc.status != 404:
|
||||
raise
|
||||
data = {"S3_ACCESS_KEY_ID": values[role + "_user"],
|
||||
"S3_SECRET_ACCESS_KEY": values[role + "_secret"]}
|
||||
if role == "api":
|
||||
data["CURSOR_SECRET"] = values["cursor"]
|
||||
bao.request("runtime/data/" + role, {"data": data}, token)
|
||||
print("Enabled audit, certificate auth, separate policies and short database leases.")
|
||||
|
||||
|
||||
def rotate_s3(bao, stage, username=None):
|
||||
token = operator_credentials()["root_token"]
|
||||
path = "runtime/data/worker"
|
||||
current = bao.request(path, token=token)["data"]
|
||||
if stage == "add":
|
||||
data = {"S3_ACCESS_KEY_ID": "worker-" + secrets.token_hex(8),
|
||||
"S3_SECRET_ACCESS_KEY": secrets.token_hex(24)}
|
||||
payload = "\n".join(data.values()) + "\n"
|
||||
compose("run", "--rm", "--no-deps", "-T", "bucket-bootstrap", "add",
|
||||
input=payload.encode(), stdout=sys.stderr)
|
||||
bao.request(path, {"options": {"cas": current["metadata"]["version"]}, "data": data}, token)
|
||||
seed = json.loads(SEED.read_text())
|
||||
seed.update(worker_user=data["S3_ACCESS_KEY_ID"], worker_secret=data["S3_SECRET_ACCESS_KEY"])
|
||||
write(SEED, json.dumps(seed).encode(), 0o600)
|
||||
print(current["data"]["S3_ACCESS_KEY_ID"])
|
||||
else:
|
||||
if not username or username == current["data"]["S3_ACCESS_KEY_ID"]:
|
||||
raise SystemExit("Supply only the previous identity after checking the new worker")
|
||||
compose("run", "--rm", "--no-deps", "-T", "bucket-bootstrap", "remove",
|
||||
input=(username + "\n").encode())
|
||||
print("Previous S3 identity revoked.")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("action", choices=("prepare", "init", "unseal", "seal", "configure",
|
||||
"rotate-s3-add", "rotate-s3-remove", "database"))
|
||||
parser.add_argument("username", nargs="?")
|
||||
args = parser.parse_args()
|
||||
if args.action == "prepare":
|
||||
prepare()
|
||||
return
|
||||
if args.action == "database":
|
||||
provision_database()
|
||||
return
|
||||
bao = administrative_bao()
|
||||
if args.action == "init":
|
||||
initialize_bao(bao)
|
||||
elif args.action == "unseal":
|
||||
unseal(bao)
|
||||
elif args.action == "seal":
|
||||
bao.request("sys/seal", {}, operator_credentials()["root_token"], "PUT")
|
||||
elif args.action == "configure":
|
||||
configure_bao(bao)
|
||||
elif args.action == "rotate-s3-add":
|
||||
rotate_s3(bao, "add")
|
||||
else:
|
||||
rotate_s3(bao, "remove", args.username)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+178
@@ -0,0 +1,178 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Operator-side CA, short-lived leaf issuance, and staged ingress rotation."""
|
||||
import argparse
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SECRETS = ROOT / "secrets"
|
||||
OPERATOR = SECRETS / "operator"
|
||||
RUN = SECRETS / "runtime"
|
||||
MESH_ROLES = {
|
||||
"api": "DNS:api",
|
||||
"worker": "DNS:worker",
|
||||
"ingress": "DNS:ingress",
|
||||
"postgres": "DNS:postgres",
|
||||
"rabbitmq": "DNS:rabbitmq",
|
||||
"rustfs": "DNS:rustfs",
|
||||
"collector": "DNS:collector",
|
||||
"prometheus": "DNS:prometheus",
|
||||
"loki": "DNS:loki",
|
||||
"tempo": "DNS:tempo",
|
||||
"grafana": "DNS:grafana,DNS:localhost,IP:127.0.0.1",
|
||||
"openbao": "DNS:openbao,DNS:localhost,IP:127.0.0.1",
|
||||
"auditor": "DNS:auditor",
|
||||
}
|
||||
EDGE_SAN = "DNS:localhost,IP:127.0.0.1"
|
||||
|
||||
|
||||
def run(*arguments):
|
||||
return subprocess.check_output(["openssl", *map(str, arguments)], stderr=subprocess.PIPE)
|
||||
|
||||
|
||||
def write(path, data, mode=0o644):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if path.parent.parent == RUN:
|
||||
path.parent.chmod(0o755)
|
||||
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as file:
|
||||
file.write(data)
|
||||
temporary = Path(file.name)
|
||||
temporary.chmod(mode)
|
||||
temporary.replace(path)
|
||||
|
||||
|
||||
def make_ca(name):
|
||||
folder = OPERATOR / name
|
||||
if (folder / "ca.crt").exists():
|
||||
return folder
|
||||
folder.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
run("req", "-new", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1",
|
||||
"-noenc", "-x509", "-sha256", "-days", 365, "-subj", f"/CN=MTUSI Lab7 {name}",
|
||||
"-addext", "basicConstraints=critical,CA:TRUE,pathlen:0",
|
||||
"-addext", "keyUsage=critical,keyCertSign,cRLSign",
|
||||
"-out", folder / "ca.crt", "-keyout", folder / "ca.key")
|
||||
(folder / "ca.key").chmod(0o600)
|
||||
return folder
|
||||
|
||||
|
||||
def issue(authority, role, san, lifetime, target):
|
||||
ca = make_ca(authority)
|
||||
with tempfile.TemporaryDirectory(dir=OPERATOR) as temporary:
|
||||
work = Path(temporary)
|
||||
run("req", "-new", "-newkey", "ec", "-pkeyopt", "ec_paramgen_curve:prime256v1",
|
||||
"-noenc", "-subj", f"/CN={role}", "-out", work / "req", "-keyout", work / "key")
|
||||
(work / "index").touch()
|
||||
(work / "serial").write_text(os.urandom(16).hex().upper() + "\n")
|
||||
config = work / "ca.conf"
|
||||
config.write_text(f"""[ca]
|
||||
default_ca = issuer
|
||||
[issuer]
|
||||
database = {work / "index"}
|
||||
serial = {work / "serial"}
|
||||
new_certs_dir = {work}
|
||||
certificate = {ca / "ca.crt"}
|
||||
private_key = {ca / "ca.key"}
|
||||
default_md = sha256
|
||||
policy = names
|
||||
unique_subject = no
|
||||
[names]
|
||||
commonName = supplied
|
||||
[leaf]
|
||||
basicConstraints = critical,CA:FALSE
|
||||
keyUsage = critical,digitalSignature
|
||||
extendedKeyUsage = serverAuth,clientAuth
|
||||
subjectAltName = {san},URI:spiffe://lab7/{role}
|
||||
""")
|
||||
now = datetime.now(timezone.utc)
|
||||
start = (now - timedelta(minutes=2)).strftime("%Y%m%d%H%M%SZ")
|
||||
end = (now + timedelta(seconds=lifetime)).strftime("%Y%m%d%H%M%SZ")
|
||||
run("ca", "-batch", "-notext", "-config", config, "-extensions", "leaf", "-in",
|
||||
work / "req", "-out", work / "cert", "-startdate", start, "-enddate", end)
|
||||
key = (work / "key").read_bytes()
|
||||
cert = (work / "cert").read_bytes()
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
write(target / "service.key", key)
|
||||
write(target / "service.crt", cert)
|
||||
write(target / "service.pem", cert + key)
|
||||
write(target / "ca.crt", (ca / "ca.crt").read_bytes())
|
||||
return run("x509", "-in", target / "service.crt", "-serial", "-noout").decode().strip().split("=")[1]
|
||||
|
||||
|
||||
def init():
|
||||
SECRETS.mkdir(mode=0o700, exist_ok=True)
|
||||
OPERATOR.mkdir(mode=0o700, exist_ok=True)
|
||||
RUN.mkdir(mode=0o700, exist_ok=True)
|
||||
for role, san in MESH_ROLES.items():
|
||||
path = RUN / role
|
||||
if not (path / "service.crt").exists():
|
||||
issue("mesh", role, san, 7 * 86400, path)
|
||||
if not (RUN / "foreign" / "service.crt").exists():
|
||||
issue("foreign", "auditor", "DNS:foreign", 7 * 86400, RUN / "foreign")
|
||||
for role in ("openbao", "grafana"):
|
||||
write(SECRETS / "trust" / f"{role}.crt", (RUN / role / "ca.crt").read_bytes())
|
||||
if not (RUN / "api" / "ingress-serials").exists():
|
||||
serial = run("x509", "-in", RUN / "ingress" / "service.crt", "-serial", "-noout")
|
||||
write(RUN / "api" / "ingress-serials", serial.split(b"=")[1])
|
||||
if not (RUN / "edge" / "service.crt").exists():
|
||||
issue("edge-a", "edge", EDGE_SAN, 86400, RUN / "edge")
|
||||
for authority in ("edge-a", "mesh"):
|
||||
write(SECRETS / "trust" / f"{authority}.crt", (OPERATOR / authority / "ca.crt").read_bytes())
|
||||
if not (SECRETS / "trust" / "edge.crt").exists():
|
||||
write(SECRETS / "trust" / "edge.crt", (OPERATOR / "edge-a" / "ca.crt").read_bytes())
|
||||
|
||||
|
||||
def renew_edge(authority, lifetime, threshold, reload):
|
||||
leaf = RUN / "edge" / "service.crt"
|
||||
try:
|
||||
run("x509", "-in", leaf, "-checkend", threshold, "-noout")
|
||||
premise = run("verify", "-CAfile", OPERATOR / authority / "ca.crt", leaf)
|
||||
if premise:
|
||||
return False
|
||||
except subprocess.CalledProcessError:
|
||||
pass
|
||||
issue(authority, "edge", EDGE_SAN, lifetime, RUN / "edge")
|
||||
if reload:
|
||||
subprocess.run(["docker", "compose", "kill", "-s", "USR2", "haproxy"], cwd=ROOT, check=True)
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
sub = parser.add_subparsers(dest="action", required=True)
|
||||
sub.add_parser("init")
|
||||
for name in ("edge-issue", "edge-renew", "edge-trust", "edge-retire"):
|
||||
command = sub.add_parser(name)
|
||||
command.add_argument("authority", choices=("edge-a", "edge-b"))
|
||||
if name in ("edge-issue", "edge-renew"):
|
||||
command.add_argument("--lifetime", type=int, default=86400)
|
||||
command.add_argument("--reload", action="store_true")
|
||||
if name == "edge-renew":
|
||||
command.add_argument("--threshold", type=int, default=1800)
|
||||
args = parser.parse_args()
|
||||
if args.action == "init":
|
||||
init()
|
||||
elif args.action == "edge-issue":
|
||||
issue(args.authority, "edge", EDGE_SAN, args.lifetime, RUN / "edge")
|
||||
if args.reload:
|
||||
subprocess.run(["docker", "compose", "kill", "-s", "USR2", "haproxy"], cwd=ROOT, check=True)
|
||||
elif args.action == "edge-renew":
|
||||
print("Renewed" if renew_edge(args.authority, args.lifetime, args.threshold, args.reload) else "Leaf current")
|
||||
else:
|
||||
ca = (make_ca(args.authority) / "ca.crt").read_bytes()
|
||||
path = SECRETS / "trust" / "edge.crt"
|
||||
write(SECRETS / "trust" / f"{args.authority}.crt", ca)
|
||||
if args.action == "edge-trust" and ca not in path.read_bytes():
|
||||
write(path, path.read_bytes() + ca)
|
||||
if args.action == "edge-retire":
|
||||
run("verify", "-CAfile", OPERATOR / args.authority / "ca.crt", RUN / "edge" / "service.crt")
|
||||
write(path, ca)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except subprocess.CalledProcessError as error:
|
||||
raise SystemExit((error.stderr or b"OpenSSL/Docker command failed").decode(errors="replace")) from None
|
||||
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicitly replay a failed attachment while its verified staging bytes remain."""
|
||||
import hashlib
|
||||
import os
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
import psycopg
|
||||
from jobs import s3_client
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
DB=os.environ["DATABASE_URL"]
|
||||
BUCKET=os.getenv("S3_BUCKET","messenger-attachments")
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) not in (2,3) or (len(sys.argv)==3 and sys.argv[2]!="--apply"):
|
||||
raise SystemExit("usage: python scripts/replay_failed.py ATTACHMENT_UUID [--apply]")
|
||||
aid=uuid.UUID(sys.argv[1]); apply=len(sys.argv)==3
|
||||
s3=s3_client()
|
||||
with psycopg.connect(DB,row_factory=dict_row) as conn:
|
||||
with conn.transaction():
|
||||
row=conn.execute("SELECT * FROM attachments WHERE id=%s FOR UPDATE",(aid,)).fetchone()
|
||||
if not row: raise SystemExit("attachment not found")
|
||||
if row["status"]!="failed" or not row["staging_key"]: raise SystemExit("only failed attachments with retained staging can be replayed")
|
||||
obj=s3.get_object(Bucket=BUCKET,Key=row["staging_key"])
|
||||
body=obj["Body"].read(int(row["size_bytes"])+1)
|
||||
if len(body)!=row["size_bytes"] or hashlib.sha256(body).hexdigest()!=row["sha256"]:
|
||||
raise SystemExit("staging original failed checksum verification")
|
||||
if not apply:
|
||||
print(f"dry-run attachment={aid} version={row['pipeline_version']} error={row['error_code']} verified_bytes={len(body)}")
|
||||
return
|
||||
job_id=uuid.uuid4()
|
||||
conn.execute("UPDATE attachments SET job_id=%s,status='queued',attempts=0,error_code=NULL,lease_until=NULL,next_attempt_at=NULL,updated_at=now() WHERE id=%s",
|
||||
(job_id,aid))
|
||||
conn.execute("INSERT INTO job_outbox(job_id,attempt,attachment_id,pipeline_version) VALUES (%s,1,%s,%s)",(job_id,aid,row["pipeline_version"]))
|
||||
conn.execute("INSERT INTO pipeline_audit(attachment_id,job_id,pipeline_version,event,detail) VALUES (%s,%s,%s,'manual_replay',jsonb_build_object('previous_error',%s::text))",
|
||||
(aid,job_id,row["pipeline_version"],row["error_code"]))
|
||||
print(f"queued attachment={aid} version={row['pipeline_version']}")
|
||||
|
||||
|
||||
if __name__=="__main__":
|
||||
main()
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Start a new, explicitly versioned processing job for a ready attachment."""
|
||||
import os
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
import psycopg
|
||||
from jobs import s3_client
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
DB=os.environ["DATABASE_URL"]
|
||||
BUCKET=os.getenv("S3_BUCKET","messenger-attachments")
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) not in (3,4) or (len(sys.argv)==4 and sys.argv[3]!="--apply"):
|
||||
raise SystemExit("usage: python scripts/reprocess_pipeline.py ATTACHMENT_UUID NEW_VERSION [--apply]")
|
||||
attachment_id=uuid.UUID(sys.argv[1]); new_version=int(sys.argv[2]); apply=len(sys.argv)==4
|
||||
if new_version<1: raise SystemExit("NEW_VERSION must be positive")
|
||||
s3=s3_client()
|
||||
staged=None
|
||||
with psycopg.connect(DB,row_factory=dict_row) as conn:
|
||||
with conn.transaction():
|
||||
row=conn.execute("SELECT * FROM attachments WHERE id=%s FOR UPDATE",(attachment_id,)).fetchone()
|
||||
if not row: raise SystemExit("attachment not found")
|
||||
if row["status"]!="ready": raise SystemExit("only ready attachments can start a new pipeline version")
|
||||
if new_version<=row["pipeline_version"]: raise SystemExit("NEW_VERSION must be greater than the current version")
|
||||
old_key=row["object_key"]
|
||||
if not apply:
|
||||
print(f"dry-run attachment={attachment_id} current_version={row['pipeline_version']} new_version={new_version} source={old_key}")
|
||||
return
|
||||
obj=s3.get_object(Bucket=BUCKET,Key=old_key)
|
||||
body=obj["Body"].read(int(row["size_bytes"])+1)
|
||||
if len(body)!=row["size_bytes"] or __import__('hashlib').sha256(body).hexdigest()!=row["sha256"]:
|
||||
raise SystemExit("stored original failed checksum verification")
|
||||
job_id=uuid.uuid4(); staged=f"staging/{attachment_id}/{job_id}/original"
|
||||
s3.put_object(Bucket=BUCKET,Key=staged,Body=body,ContentType=row["content_type"],Metadata={"sha256":row["sha256"],"attachment-id":str(attachment_id),"job-id":str(job_id)})
|
||||
conn.execute("""UPDATE attachments SET object_key=NULL,staging_key=%s,job_id=%s,pipeline_version=%s,status='queued',attempts=0,
|
||||
lease_until=NULL,next_attempt_at=NULL,variants='[]'::jsonb,error_code=NULL,updated_at=now() WHERE id=%s""",
|
||||
(staged,job_id,new_version,attachment_id))
|
||||
conn.execute("INSERT INTO job_outbox(job_id,attempt,attachment_id,pipeline_version) VALUES (%s,1,%s,%s)",(job_id,attachment_id,new_version))
|
||||
conn.execute("INSERT INTO pipeline_audit(attachment_id,job_id,pipeline_version,event,detail) VALUES (%s,%s,%s,'reprocess_requested',jsonb_build_object('previous_version',%s::integer))",
|
||||
(attachment_id,job_id,new_version,row["pipeline_version"]))
|
||||
print(f"queued attachment={attachment_id} version={new_version}")
|
||||
|
||||
|
||||
if __name__=="__main__":
|
||||
main()
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose restart postgres rabbitmq s3-store collector-core prometheus-core loki-core tempo-core grafana
|
||||
docker compose restart api worker haproxy
|
||||
Executable
+36
@@ -0,0 +1,36 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
cache=mtusi2026lab7_grype_cache
|
||||
grype=anchore/grype:v0.110.0
|
||||
docker run --rm -e GRYPE_DB_CACHE_DIR=/cache -v "$cache:/cache" "$grype" db update >&2
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
if [ "$#" -gt 0 ]; then
|
||||
images=$(printf '%s\n' "$@")
|
||||
else
|
||||
images=$(docker compose --profile operator config --images | sort -u)
|
||||
fi
|
||||
printf '%s\n' "$images" | while IFS= read -r image; do
|
||||
[ -n "$image" ] || continue
|
||||
docker image save "$image" -o "$work/image.tar"
|
||||
docker run --rm -e GRYPE_DB_CACHE_DIR=/cache -e GRYPE_DB_AUTO_UPDATE=false \
|
||||
-v "$cache:/cache" -v "$work/image.tar:/image.tar:ro" "$grype" docker-archive:/image.tar -o json \
|
||||
> "$work/result.json"
|
||||
python3 - "$image" "$work/result.json" <<'PY'
|
||||
import collections
|
||||
import json
|
||||
import sys
|
||||
doc = json.load(open(sys.argv[2]))
|
||||
assert doc["descriptor"]["db"]["status"]["valid"]
|
||||
counts = collections.Counter(entry["vulnerability"]["severity"] for entry in doc["matches"])
|
||||
examples = []
|
||||
for entry in doc["matches"]:
|
||||
vuln, pkg = entry["vulnerability"], entry["artifact"]
|
||||
if vuln["severity"] == "Critical" or (pkg["type"] == "python" and vuln["severity"] == "High"):
|
||||
examples.append({"id": vuln["id"], "package": pkg["name"], "version": pkg["version"],
|
||||
"fix": vuln["fix"]["versions"]})
|
||||
print(json.dumps({"image": sys.argv[1], "db_built": doc["descriptor"]["db"]["status"]["built"],
|
||||
"counts": dict(counts), "critical_or_python_high": examples[:10]}))
|
||||
PY
|
||||
done
|
||||
Executable
+16
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
scripts/init-env.sh
|
||||
docker compose up -d --wait postgres rabbitmq rustfs s3-store openbao \
|
||||
collector collector-core prometheus prometheus-core loki loki-core tempo tempo-core grafana
|
||||
python3 scripts/operator.py init
|
||||
python3 scripts/operator.py unseal
|
||||
python3 scripts/operator.py database
|
||||
docker compose run --rm --no-deps -T bucket-bootstrap
|
||||
python3 scripts/operator.py configure
|
||||
docker compose up -d --build api worker haproxy
|
||||
port=$(python3 -c 'from scripts.operator import settings; print(settings().get("HTTPS_PORT", "8443"))')
|
||||
curl --retry 15 --retry-delay 1 --retry-all-errors --max-time 5 \
|
||||
--cacert secrets/trust/edge.crt -fsS "https://localhost:$port/health/ready"
|
||||
printf '\n'
|
||||
Executable
+13
@@ -0,0 +1,13 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
: "${TARGET_INSTANCE_ID:?TARGET_INSTANCE_ID is required}"
|
||||
cd "$(dirname "$0")/.."
|
||||
for container in $(docker compose ps -q api); do
|
||||
instance=$(docker exec "$container" cat /run/local/instance 2>/dev/null || true)
|
||||
if [ "$instance" = "$TARGET_INSTANCE_ID" ]; then
|
||||
docker stop --time 3 "$container" >/dev/null
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
echo "No API container matches the requested process alias" >&2
|
||||
exit 1
|
||||
Reference in New Issue
Block a user