#!/usr/bin/env python3 # #region FullFlow.FinanceMillion.Environment [C:4] [TYPE Module] [SEMANTICS credentials,private,additive,fixture] # @PRE An existing owner-controlled mode0600 full-flow env is supplied; no production env is used. # @POST Adds one strong ClickHouse secret once, preserving every existing byte/key and printing only the path. # @INVARIANT Existing secrets are never replaced; symlinks/insecure permissions/empty existing credentials refuse. import fcntl import os from pathlib import Path import secrets import stat import sys # #region FullFlow.FinanceMillion.Environment.Validate [C:3] [TYPE Function] [SEMANTICS permission,ownership,regular-file] def validate_private_file(descriptor): info = os.fstat(descriptor) if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid(): raise ValueError('PRIVATE_LAB_ENV_REQUIRED') if stat.S_IMODE(info.st_mode) != 0o600: raise ValueError('PRIVATE_LAB_ENV_MODE_0600_REQUIRED') # #endregion FullFlow.FinanceMillion.Environment.Validate # #region FullFlow.FinanceMillion.Environment.Extend [C:4] [TYPE Function] [SEMANTICS secret,append,idempotent] # @SIDE_EFFECT Locks the private file and appends only the missing generated lab credential; no secret is logged. # @RELATION CALLS -> [FullFlow.FinanceMillion.Environment.Validate] def extend(path): descriptor = os.open(path, os.O_RDWR | os.O_NOFOLLOW) with os.fdopen(descriptor, 'r+') as target: fcntl.flock(target, fcntl.LOCK_EX) validate_private_file(target.fileno()) content = target.read() entries = [line for line in content.splitlines() if line.startswith('CLICKHOUSE_PASSWORD=')] if entries: if len(entries) != 1 or not entries[0].split('=', 1)[1].strip(): raise ValueError('CLICKHOUSE_SECRET_INVALID') return target.seek(0, os.SEEK_END) separator = '' if not content or content.endswith('\n') else '\n' target.write(f'{separator}CLICKHOUSE_PASSWORD={secrets.token_hex(24)}\n') target.flush() os.fsync(target.fileno()) # #endregion FullFlow.FinanceMillion.Environment.Extend # #region FullFlow.FinanceMillion.Environment.Main [C:2] [TYPE Function] [SEMANTICS cli,private-path] def main(): if len(sys.argv) != 2: raise SystemExit('Usage: full-flow-finance-env.py ') path = Path(sys.argv[1]) extend(path) print(path) # #endregion FullFlow.FinanceMillion.Environment.Main if __name__ == '__main__': main() # #endregion FullFlow.FinanceMillion.Environment