Files
mtusi2026lab7/scripts/db_roles.py
T
ALMiron 912a874f00
Skeleton contracts / contracts (pull_request) Canceled after 0s
lab 7 openbao
2026-11-23 14:39:13 +03:00

77 lines
4.5 KiB
Python

#!/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()