forked from mtusi2026/mtusi2026lab7
feat(security): add scoped identities, TLS boundaries and OpenBao bootstrap
This commit is contained in:
+291
@@ -0,0 +1,291 @@
|
||||
"""Durable job state is authoritative; stream entries are wake-up notifications."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import time
|
||||
from datetime import UTC, datetime
|
||||
from uuid import UUID
|
||||
|
||||
import redis
|
||||
from psycopg.types.json import Jsonb
|
||||
|
||||
from src import telemetry
|
||||
from src.database import Database
|
||||
from src.identity import redis_tls
|
||||
from src.settings import integer, secret
|
||||
|
||||
STREAM = "attachments"
|
||||
GROUP = "image-workers"
|
||||
|
||||
|
||||
def database():
|
||||
db = Database(url=secret("DATABASE_URL"), size=4)
|
||||
db.open()
|
||||
return db
|
||||
|
||||
|
||||
def broker():
|
||||
return redis.Redis.from_url(
|
||||
secret("BROKER_URL"),
|
||||
decode_responses=True,
|
||||
socket_connect_timeout=1,
|
||||
socket_timeout=3,
|
||||
max_connections=8,
|
||||
**redis_tls(),
|
||||
)
|
||||
|
||||
|
||||
def envelope(row):
|
||||
return dict(
|
||||
schema_version=1,
|
||||
job_id=str(row["id"]),
|
||||
type="attachment.process.v1",
|
||||
attachment_id=str(row["attachment_id"]),
|
||||
pipeline_version=row["pipeline_version"],
|
||||
attempt=row["attempt"] + 1,
|
||||
created_at=datetime.now(UTC).isoformat().replace("+00:00", "Z"),
|
||||
)
|
||||
|
||||
|
||||
def validate_job(data):
|
||||
required = {
|
||||
"schema_version",
|
||||
"job_id",
|
||||
"type",
|
||||
"attachment_id",
|
||||
"pipeline_version",
|
||||
"attempt",
|
||||
"created_at",
|
||||
}
|
||||
if (
|
||||
not isinstance(data, dict)
|
||||
or not required <= data.keys()
|
||||
or data.keys() - required - {"traceparent", "tracestate"}
|
||||
):
|
||||
raise ValueError("Invalid job envelope")
|
||||
if (
|
||||
type(data["schema_version"]) is not int
|
||||
or data["schema_version"] != 1
|
||||
or data["type"] != "attachment.process.v1"
|
||||
):
|
||||
raise ValueError("Invalid job type")
|
||||
for k in ["job_id", "attachment_id"]:
|
||||
if not isinstance(data[k], str):
|
||||
raise ValueError("Invalid job UUID")
|
||||
UUID(data[k])
|
||||
for k in ["pipeline_version", "attempt"]:
|
||||
if type(data[k]) is not int or data[k] < 1:
|
||||
raise ValueError("Invalid job number")
|
||||
timestamp = data["created_at"]
|
||||
if not isinstance(timestamp, str) or not re.fullmatch(
|
||||
r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})",
|
||||
timestamp,
|
||||
):
|
||||
raise ValueError("Invalid job timestamp")
|
||||
datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
|
||||
if "traceparent" in data:
|
||||
if not isinstance(data["traceparent"], str) or not re.fullmatch(
|
||||
r"00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}", data["traceparent"]
|
||||
):
|
||||
raise ValueError("Invalid trace context")
|
||||
if "tracestate" in data and (
|
||||
not isinstance(data["tracestate"], str)
|
||||
or len(data["tracestate"]) > 512
|
||||
):
|
||||
raise ValueError("Invalid trace context")
|
||||
return data
|
||||
|
||||
|
||||
def event(conn, job_id, name, detail=None):
|
||||
conn.execute(
|
||||
"INSERT INTO pipeline_events(job_id,event,detail) VALUES(%s,%s,%s)",
|
||||
(job_id, name, Jsonb(detail or {})),
|
||||
)
|
||||
|
||||
|
||||
def enqueue(conn, job_id):
|
||||
row = conn.execute("SELECT * FROM jobs WHERE id=%s", (job_id,)).fetchone()
|
||||
context = telemetry.carrier()
|
||||
if not context and row.get("traceparent"):
|
||||
context = {"traceparent": row["traceparent"]}
|
||||
if row.get("tracestate"):
|
||||
context["tracestate"] = row["tracestate"]
|
||||
if context:
|
||||
conn.execute(
|
||||
"UPDATE jobs SET traceparent=%s,tracestate=%s WHERE id=%s",
|
||||
(
|
||||
context.get("traceparent", ""),
|
||||
context.get("tracestate", ""),
|
||||
job_id,
|
||||
),
|
||||
)
|
||||
conn.execute(
|
||||
"INSERT INTO outbox(job_id,payload,due_at) VALUES(%s,%s,%s)",
|
||||
(job_id, Jsonb(envelope(row) | context), row["next_at"]),
|
||||
)
|
||||
|
||||
|
||||
def fault(db, target, phase):
|
||||
if os.getenv("PIPELINE_FAULTS") != "1":
|
||||
return
|
||||
with db.connection() as conn, conn.transaction():
|
||||
row = conn.execute(
|
||||
"SELECT * FROM pipeline_faults WHERE target=%s AND phase=%s AND remaining>0 ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1",
|
||||
(target, phase),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return
|
||||
conn.execute(
|
||||
"UPDATE pipeline_faults SET remaining=remaining-1,hit_at=clock_timestamp() WHERE id=%s",
|
||||
(row["id"],),
|
||||
)
|
||||
action = row["action"]
|
||||
if action == "crash":
|
||||
os._exit(89)
|
||||
if action == "permanent":
|
||||
raise PermanentFailure("invalid_image")
|
||||
if action == "transient":
|
||||
raise RuntimeError("injected_transient")
|
||||
if action == "hang":
|
||||
time.sleep(120)
|
||||
if action == "wait":
|
||||
end = time.monotonic() + 60
|
||||
while time.monotonic() < end:
|
||||
with db.connection() as conn:
|
||||
released = conn.execute(
|
||||
"SELECT released_at FROM pipeline_faults WHERE id=%s",
|
||||
(row["id"],),
|
||||
).fetchone()
|
||||
if released and released["released_at"]:
|
||||
return
|
||||
time.sleep(0.05)
|
||||
raise RuntimeError("fault_wait_timeout")
|
||||
|
||||
|
||||
class PermanentFailure(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def retry(conn, row, error, *, permanent=False):
|
||||
maximum = integer("JOB_MAX_ATTEMPTS", 5, 1, 20)
|
||||
failed = permanent or row["attempt"] >= maximum
|
||||
delay = random.uniform(0.25, min(30, 2 ** row["attempt"]))
|
||||
state = "failed" if failed else "queued"
|
||||
code = error if permanent else ("retry_exhausted" if failed else error)
|
||||
conn.execute(
|
||||
"UPDATE jobs SET state=%s,fence=fence+1,lease_owner=NULL,lease_until=NULL,error_code=%s,next_at=clock_timestamp()+%s*interval '1 second',updated_at=clock_timestamp() WHERE id=%s",
|
||||
(state, code, delay, row["id"]),
|
||||
)
|
||||
conn.execute(
|
||||
"UPDATE attachments SET state=%s,error_code=%s,updated_at=clock_timestamp() WHERE id=%s AND pipeline_version=%s",
|
||||
(
|
||||
state,
|
||||
code if failed else None,
|
||||
row["attachment_id"],
|
||||
row["pipeline_version"],
|
||||
),
|
||||
)
|
||||
event(
|
||||
conn,
|
||||
row["id"],
|
||||
"failed" if failed else "retry",
|
||||
{"attempt": row["attempt"], "code": code, "backoff_seconds": delay},
|
||||
)
|
||||
if not failed:
|
||||
enqueue(conn, row["id"])
|
||||
|
||||
|
||||
def watchdog(db):
|
||||
with db.connection() as conn, conn.transaction():
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM jobs WHERE state='processing' AND lease_until<clock_timestamp() ORDER BY lease_until FOR UPDATE SKIP LOCKED LIMIT 16"
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
retry(conn, row, "lease_expired")
|
||||
# Recreate a wakeup if its stream entry was lost: never recreate logical jobs.
|
||||
rows = conn.execute(
|
||||
"SELECT j.* FROM jobs j WHERE j.state='queued' AND j.next_at<=clock_timestamp() AND NOT EXISTS(SELECT 1 FROM outbox o WHERE o.job_id=j.id AND (o.published_at IS NULL OR o.published_at>clock_timestamp()-interval '15 seconds')) FOR UPDATE OF j SKIP LOCKED LIMIT 16"
|
||||
).fetchall()
|
||||
for row in rows:
|
||||
enqueue(conn, row["id"])
|
||||
|
||||
|
||||
def relay_once(db, queue):
|
||||
watchdog(db)
|
||||
with db.connection() as conn, conn.transaction():
|
||||
row = conn.execute(
|
||||
"SELECT * FROM outbox WHERE published_at IS NULL AND due_at<=clock_timestamp() ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1"
|
||||
).fetchone()
|
||||
if not row:
|
||||
return False
|
||||
validate_job(row["payload"])
|
||||
with telemetry.span(
|
||||
"attachments publish",
|
||||
kind=telemetry.SpanKind.PRODUCER,
|
||||
parent=row["payload"],
|
||||
attributes={
|
||||
"job.id": str(row["job_id"]),
|
||||
"messaging.system": "valkey",
|
||||
"messaging.destination.name": STREAM,
|
||||
},
|
||||
):
|
||||
# WAITAOF must use the SAME connection as XADD (not two pooled calls).
|
||||
with queue.client() as dedicated:
|
||||
entry = dedicated.xadd(
|
||||
STREAM,
|
||||
{
|
||||
"job": json.dumps(
|
||||
row["payload"] | telemetry.carrier(),
|
||||
separators=(",", ":"),
|
||||
)
|
||||
},
|
||||
)
|
||||
confirmation = dedicated.execute_command("WAITAOF", 1, 0, 2000)
|
||||
if int(confirmation[0]) < 1:
|
||||
raise RuntimeError(
|
||||
"Broker durability confirmation timed out"
|
||||
)
|
||||
telemetry.log("job.published", job_id=str(row["job_id"]))
|
||||
fault(db, row["job_id"], "relay_after_publish")
|
||||
conn.execute(
|
||||
"UPDATE outbox SET published_at=clock_timestamp() WHERE id=%s",
|
||||
(row["id"],),
|
||||
)
|
||||
event(
|
||||
conn,
|
||||
row["job_id"],
|
||||
"published",
|
||||
{"entry": entry, "outbox": row["id"]},
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
def relay():
|
||||
telemetry.configure("messenger-relay")
|
||||
db, queue = database(), broker()
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
if not relay_once(db, queue):
|
||||
time.sleep(0.2)
|
||||
except Exception:
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"event": "relay_retry",
|
||||
"code": "dependency_unavailable",
|
||||
}
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
time.sleep(1)
|
||||
finally:
|
||||
queue.close()
|
||||
db.close()
|
||||
telemetry.stop()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
relay()
|
||||
Reference in New Issue
Block a user