forked from mtusi2026/mtusi2026lab3
33 lines
1.5 KiB
Python
33 lines
1.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Generate local-only credentials. Existing credentials are never overwritten."""
|
|
import base64
|
|
import os
|
|
from pathlib import Path
|
|
import secrets
|
|
root=Path(__file__).resolve().parents[1]
|
|
directory=root/'secrets'
|
|
directory.mkdir(mode=0o700,exist_ok=True)
|
|
password_file=directory/'postgres_password'
|
|
if not password_file.exists():
|
|
password=secrets.token_hex(24)
|
|
password_file.write_text(password+'\n')
|
|
else:
|
|
password=password_file.read_text().strip()
|
|
cache_file=directory/'valkey_config'
|
|
if not cache_file.exists():
|
|
cache_password=secrets.token_hex(24)
|
|
cache_file.write_text('bind 0.0.0.0\nprotected-mode yes\nport 6379\ndir /data\nsave ""\nappendonly no\nrequirepass '+cache_password+'\n')
|
|
else:
|
|
cache_password=next(line.split()[1] for line in cache_file.read_text().splitlines() if line.startswith('requirepass '))
|
|
values={'database_url':f'postgres://messenger:{password}@postgres:5432/messenger?sslmode=disable',
|
|
'cache_url':f'redis://:{cache_password}@valkey:6379/0',
|
|
'cursor_key':base64.urlsafe_b64encode(secrets.token_bytes(32)).decode().rstrip('=')}
|
|
for name,value in values.items():
|
|
p=directory/name
|
|
if not p.exists():p.write_text(value+'\n')
|
|
# Compose mounts individual files. Readable by container UID 10001; host
|
|
# directory 0700 prevents traversal by other local users.
|
|
for p in directory.iterdir():os.chmod(p,0o444)
|
|
if not (root/'.env').exists():(root/'.env').write_text('APP_PORT=8083\nSESSION_TTL_SECONDS=3600\n')
|
|
print('Local secrets ready (values hidden); .env and secrets/ are ignored by Git.')
|