57 lines
2.4 KiB
Python
57 lines
2.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Provision one shared backend/Next runtime secret; never emit its value.
|
|
|
|
Run under the environment's serialized CI deployment lock, before Compose config.
|
|
Existing operational files are read-only inputs, not rewritten or chmodded.
|
|
"""
|
|
import argparse
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import secrets
|
|
import stat
|
|
|
|
|
|
def provision(source: Path, output: Path) -> None:
|
|
for path in (source, output):
|
|
if any(parent.is_symlink() for parent in (path, *path.parents)):
|
|
raise ValueError('Unsafe runtime path')
|
|
if not source.exists():
|
|
fd = os.open(source, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
with os.fdopen(fd, 'w') as stream:
|
|
stream.write('REVALIDATION_SECRET=' + secrets.token_urlsafe(48) + '\n')
|
|
fd = os.open(source, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
|
|
with os.fdopen(fd) as stream:
|
|
info = os.fstat(stream.fileno())
|
|
if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1 or info.st_size > 4096:
|
|
raise ValueError('Unsafe runtime file')
|
|
text = stream.read(4097)
|
|
lines = [line.strip() for line in text.splitlines()
|
|
if line.strip() and not line.lstrip().startswith('#')]
|
|
if any(not line.startswith('REVALIDATION_SECRET=') for line in lines):
|
|
raise ValueError('Unexpected runtime configuration')
|
|
values = [line.partition('=')[2].strip().strip('\"\'') for line in lines]
|
|
if len(values) != 1 or not re.fullmatch(r'[A-Za-z0-9_+/=-]{32,256}', values[0]):
|
|
raise ValueError('Invalid revalidation runtime configuration')
|
|
fd = os.open(output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
with os.fdopen(fd, 'w') as stream:
|
|
stream.write('REVALIDATION_SECRET=' + values[0] + '\n')
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--environment', choices=('stage', 'prod'), required=True)
|
|
parser.add_argument('--source', type=Path, required=True)
|
|
parser.add_argument('--output', type=Path, required=True)
|
|
args = parser.parse_args()
|
|
if os.environ.get('GITHUB_ACTIONS', os.environ.get('GITEA_ACTIONS')) != 'true':
|
|
parser.error('Provisioning requires serialized CI deployment')
|
|
try:
|
|
provision(args.source, args.output)
|
|
except (ValueError, OSError):
|
|
parser.exit(1, 'ERROR: revalidation provisioning failed; no secret values logged\n')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|