"""Create local synthetic secrets once; never overwrite existing credentials.""" import secrets from datetime import datetime, timedelta, timezone from ipaddress import ip_address from cryptography import x509 from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.x509.oid import NameOID from pathlib import Path root = Path(__file__).resolve().parents[1] directory = root / 'secrets' directory.mkdir(exist_ok=True) password_file = directory / 'db_password' if not password_file.exists(): with password_file.open('x', encoding='utf-8') as file: file.write(secrets.token_urlsafe(32)) password = password_file.read_text(encoding='utf-8').strip() url_file = directory / 'database_url' if not url_file.exists(): with url_file.open('x', encoding='utf-8') as file: file.write('postgresql://messenger:' + password + '@db:5432/messenger') env = root / '.env' if not env.exists(): with env.open('x', encoding='utf-8') as file: file.write('SESSION_TTL_SECONDS=3600\n') print('Local configuration ready; credentials are not printed.') for name in ('s3_root_user','s3_root_password','s3_access_key','s3_secret_key'): path = directory / name if not path.exists(): with path.open('x', encoding='utf-8') as file: file.write(secrets.token_hex(16)) certs = root / 'certs' certs.mkdir(exist_ok=True) ca = certs / 'ca.crt' key = certs / 'server.key' pem = certs / 'server.pem' if not ca.exists() or not key.exists() or not pem.exists(): private = rsa.generate_private_key(public_exponent=65537, key_size=2048) subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, 'localhost')]) certificate = (x509.CertificateBuilder().subject_name(subject).issuer_name(subject) .public_key(private.public_key()).serial_number(x509.random_serial_number()) .not_valid_before(datetime.now(timezone.utc) - timedelta(minutes=1)) .not_valid_after(datetime.now(timezone.utc) + timedelta(days=365)) .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True) .add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost'), x509.IPAddress(ip_address('127.0.0.1'))]), critical=False) .sign(private, hashes.SHA256())) cert_bytes = certificate.public_bytes(serialization.Encoding.PEM) key_bytes = private.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.TraditionalOpenSSL, serialization.NoEncryption()) ca.write_bytes(cert_bytes) key.write_bytes(key_bytes) pem.write_bytes(cert_bytes + key_bytes) print('Local TLS certificate ready; private key is ignored by git.')