43 lines
2.5 KiB
Python
43 lines
2.5 KiB
Python
"""Operator one-shot: install narrowly scoped login roles after migrations."""
|
|
import os
|
|
import psycopg
|
|
from psycopg import sql
|
|
|
|
# All application business tables are accessed via explicit grants;
|
|
# only migration role can CREATE, ALTER, DROP or read pg_* administration.
|
|
API_TABLES={'users','chats','chat_members','messages','message_attachments',
|
|
'message_idempotency','attachments','attachment_variants','processing_jobs','job_outbox'}
|
|
JOB_TABLES={'attachments','attachment_variants','processing_jobs','job_outbox',
|
|
'job_replay_audit','job_fault_once'}
|
|
|
|
def main():
|
|
with psycopg.connect(os.environ['DATABASE_URL'], autocommit=True) as c:
|
|
tables={r[0] for r in c.execute("SELECT tablename FROM pg_tables WHERE schemaname='public'")}
|
|
for role in ('api','worker','dispatcher'):
|
|
username='messenger_'+role
|
|
pw=os.environ['DB_'+role.upper()+'_PASSWORD']
|
|
row=c.execute('SELECT 1 FROM pg_roles WHERE rolname=%s',(username,)).fetchone()
|
|
if not row:
|
|
c.execute(sql.SQL('CREATE ROLE {} LOGIN PASSWORD {}').format(sql.Identifier(username), sql.Literal(pw)))
|
|
else:
|
|
c.execute(sql.SQL('ALTER ROLE {} LOGIN PASSWORD {}').format(sql.Identifier(username), sql.Literal(pw)))
|
|
c.execute(sql.SQL('GRANT CONNECT ON DATABASE {} TO {}').format(sql.Identifier(os.environ.get('POSTGRES_DB','messenger')),sql.Identifier(username)))
|
|
c.execute(sql.SQL('GRANT USAGE ON SCHEMA public TO {}').format(sql.Identifier(username)))
|
|
for table in sorted(tables):
|
|
# API handles metadata and HTTP; worker updates processing statuses;
|
|
# dispatcher works with outbox + jobs. No DDL privileges.
|
|
mode= None
|
|
if role=='api':
|
|
if table in API_TABLES: mode='SELECT, INSERT, UPDATE'
|
|
if role=='worker':
|
|
if table in JOB_TABLES:
|
|
mode='SELECT, INSERT, UPDATE, DELETE'
|
|
if role=='dispatcher':
|
|
if table in JOB_TABLES:
|
|
mode='SELECT, INSERT, UPDATE, DELETE'
|
|
if mode:
|
|
c.execute(sql.SQL('GRANT '+mode+' ON TABLE {} TO {}').format(sql.Identifier(table),sql.Identifier(username)))
|
|
c.execute(sql.SQL('GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO {}').format(sql.Identifier(username)))
|
|
print('Role permissions synchronized (no secrets shown)')
|
|
if __name__=='__main__': main()
|