MC/website/ops/home-relocation-bank-access.py
2026-11-27 23:43:05 +00:00

22 lines
2.1 KiB
Python

"""Grant the central app only the bank table access needed by atomic relocations.
Run as the database administrator after inspecting an application-generated plan.
No account records, balances, passwords or existing grants are changed.
"""
import argparse,json,pathlib,re,subprocess
def main():
parser=argparse.ArgumentParser();parser.add_argument('--plan',required=True);parser.add_argument('--expected-user',required=True);parser.add_argument('--expected-schema',required=True);parser.add_argument('--apply',action='store_true');args=parser.parse_args()
plan=json.loads(pathlib.Path(args.plan).read_text());user=plan['user'];host=plan['host'];schema=plan['schema']
if user+'@'+host!=args.expected_user or schema!=args.expected_schema:raise ValueError('Database plan identity changed')
if not re.fullmatch(r'[a-zA-Z0-9_]+',user) or not re.fullmatch(r'[a-zA-Z0-9_.:%-]+',host) or not re.fullmatch(r'[a-z][a-z0-9_]{2,63}',schema):raise ValueError('Invalid database identity')
def query(sql):return subprocess.run(['mysql','--batch','--skip-column-names','--execute',sql],check=True,capture_output=True,text=True).stdout.strip()
if query('SELECT @@server_id')!=str(plan['serverId']):raise ValueError('Database server changed')
if query("SELECT COUNT(*) FROM mysql.user WHERE User='"+user+"' AND Host='"+host+"'")!='1':raise ValueError('Existing database user required')
privileges={'pb_entities':'SELECT','pb_clients':'SELECT','pb_packages':'SELECT','pb_account_authorisations':'SELECT','pb_accounts':'SELECT, UPDATE','pb_orders':'SELECT, INSERT, UPDATE','pb_entries':'SELECT, INSERT','pb_audit':'SELECT, INSERT'}
for table,rights in privileges.items():
if query("SELECT ENGINE FROM information_schema.TABLES WHERE TABLE_SCHEMA='"+schema+"' AND TABLE_NAME='"+table+"'")!='InnoDB':raise ValueError('Transactional bank tables required')
if args.apply:query('GRANT '+rights+' ON `'+schema+'`.`'+table+'` TO \''+user+'\'@\''+host+'\'')
print(json.dumps({'applied':args.apply,'user':user+'@'+host,'schema':schema,'tables':len(privileges),'grantOption':False}))
if __name__=='__main__':main()