165 lines
8.8 KiB
Python
165 lines
8.8 KiB
Python
#!/usr/bin/env python3
|
|
"""Fail-closed, read-only comparison of Stage operational configuration."""
|
|
|
|
import argparse
|
|
import json
|
|
from pathlib import Path
|
|
import posixpath
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
|
|
|
|
def mounts(config, name):
|
|
result = []
|
|
for mount in config['services'][name].get('volumes', []):
|
|
kind = mount['type']
|
|
source = mount.get('source', '')
|
|
if kind == 'volume':
|
|
source = config.get('volumes', {}).get(source, {}).get('name', source)
|
|
result.append((kind, posixpath.normpath(source), posixpath.normpath(mount['target']),
|
|
not mount.get('read_only', False)))
|
|
return sorted(result)
|
|
|
|
|
|
def networks(config, name):
|
|
return sorted(config.get('networks', {}).get(key, {}).get('name', key)
|
|
for key in config['services'][name].get('networks', {}))
|
|
|
|
|
|
def labels(values):
|
|
return {key: value for key, value in values.items() if key.startswith('traefik.')}
|
|
|
|
|
|
def verify(base, planned, live, nginx, live_nginx):
|
|
"""Return property/key mismatches, never configuration values."""
|
|
errors = []
|
|
# Validate resolved Compose environment, not env_file input: environment
|
|
# entries can override a provisioned secret. Match provisioner's format.
|
|
secrets = [planned['services'][name]['environment'].get('REVALIDATION_SECRET')
|
|
for name in ('backend_stage', 'frontend_stage')]
|
|
for name, secret in zip(('backend_stage', 'frontend_stage'), secrets):
|
|
if not isinstance(secret, str) or not re.fullmatch(r'[A-Za-z0-9_+/=-]{32,256}', secret):
|
|
errors.append(name + '.environment.REVALIDATION_SECRET')
|
|
if secrets[0] != secrets[1]:
|
|
errors.extend(name + '.environment.REVALIDATION_SECRET'
|
|
for name in ('backend_stage', 'frontend_stage'))
|
|
# Intentional rotation is permitted: do not compare these values to live.
|
|
allowed = {'REVALIDATION_SECRET', 'FRONTEND_INTERNAL_URL', 'INTERNAL_API_URL'}
|
|
defaults = {'PATH', 'NODE_VERSION', 'YARN_VERSION', 'PRISMA_HIDE_UPDATE_MESSAGE'}
|
|
for name in ('backend_stage', 'frontend_stage'):
|
|
required_args = {'NPM_REGISTRY': 'https://registry.parsaaghayi.ir/repository/npm/'}
|
|
if name == 'frontend_stage':
|
|
required_args.update(NEXT_PUBLIC_API_URL='https://stageapi.canina.ir/api',
|
|
VITE_API_URL='https://stageapi.canina.ir')
|
|
args = planned['services'][name].get('build', {}).get('args', {})
|
|
for key, expected_value in required_args.items():
|
|
if args.get(key) != expected_value:
|
|
errors.append(name + '.build.args.' + key)
|
|
original = base['services'][name]['environment']
|
|
target = planned['services'][name]['environment']
|
|
actual = dict(entry.split('=', 1) for entry in live[name]['Config']['Env'])
|
|
for key in sorted(set(original) | set(target) | set(actual)):
|
|
if key in allowed:
|
|
if ((key in original or key in actual) and key not in target
|
|
or key in target and target[key] is None):
|
|
errors.append(name + '.environment.' + key)
|
|
continue
|
|
if key not in original and key not in target and key in defaults:
|
|
continue
|
|
if (key not in original or key not in target or key not in actual
|
|
or original[key] is None or target[key] is None
|
|
or original[key] != actual[key] or target[key] != actual[key]):
|
|
errors.append(name + '.environment.' + key)
|
|
actual_mounts = sorted((m['Type'], posixpath.normpath(
|
|
m['Name'] if m['Type'] == 'volume' else m.get('Source', '')),
|
|
posixpath.normpath(m['Destination']), m.get('RW')) for m in live[name]['Mounts'])
|
|
actual_networks = sorted(live[name]['NetworkSettings']['Networks'])
|
|
actual_labels = labels(live[name]['Config'].get('Labels') or {})
|
|
for config in (base, planned):
|
|
if mounts(config, name) != actual_mounts:
|
|
errors.append(name + '.mounts')
|
|
for mount in config['services'][name].get('volumes', []):
|
|
if mount['type'] == 'bind' and 'propagation' in mount.get('bind', {}):
|
|
matches = [m for m in live[name]['Mounts']
|
|
if posixpath.normpath(m['Destination']) == posixpath.normpath(mount['target'])]
|
|
if (len(matches) != 1 or matches[0].get('Propagation')
|
|
!= mount['bind']['propagation']):
|
|
errors.append(name + '.mounts')
|
|
if mount['type'] == 'volume' and 'nocopy' in mount.get('volume', {}):
|
|
source = config.get('volumes', {}).get(mount.get('source'), {}).get(
|
|
'name', mount.get('source'))
|
|
matches = [m for m in live[name].get('HostConfig', {}).get('Mounts', [])
|
|
if m.get('Type') == 'volume' and m.get('Source') == source
|
|
and m.get('Target') == mount['target']]
|
|
# Some engines expose only HostConfig.Binds; never infer nocopy
|
|
# from the runtime Mounts summary, which omits this option.
|
|
if (len(matches) != 1 or matches[0].get('VolumeOptions', {}).get('NoCopy')
|
|
is not mount['volume']['nocopy']):
|
|
errors.append(name + '.mounts')
|
|
if networks(config, name) != actual_networks:
|
|
errors.append(name + '.networks')
|
|
for key, options in config['services'][name].get('networks', {}).items():
|
|
network_name = config.get('networks', {}).get(key, {}).get('name', key)
|
|
endpoint = live[name]['NetworkSettings']['Networks'].get(network_name, {})
|
|
options = options or {}
|
|
if not set(options.get('aliases') or []).issubset(set(endpoint.get('Aliases') or [])):
|
|
errors.append(name + '.networks')
|
|
for option, field in (('ipv4_address', 'IPAddress'),
|
|
('ipv6_address', 'GlobalIPv6Address')):
|
|
if option in options and options[option] != endpoint.get(field):
|
|
errors.append(name + '.networks')
|
|
expected = labels(config['services'][name].get('labels', {}))
|
|
for key in sorted(set(expected) | set(actual_labels)):
|
|
if key not in expected or key not in actual_labels or expected[key] != actual_labels[key]:
|
|
errors.append(name + '.labels.' + key)
|
|
if nginx != live_nginx:
|
|
errors.append('frontend_stage.nginx.bytes')
|
|
return sorted(set(errors))
|
|
|
|
|
|
def main(argv=None):
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument('--base-compose', required=True)
|
|
parser.add_argument('--override', action='append', default=[])
|
|
parser.add_argument('--project-directory', required=True)
|
|
parser.add_argument('--project-name', default='stage')
|
|
parser.add_argument('--nginx', required=True)
|
|
options = parser.parse_args(argv)
|
|
# Subprocess diagnostics may contain interpolated credentials. Capture them
|
|
# and never include exceptions, argv, config, or values in diagnostics.
|
|
def capture(command):
|
|
return subprocess.run(command, capture_output=True, check=True, timeout=30).stdout
|
|
|
|
try:
|
|
compose = ['docker', 'compose', '-p', options.project_name,
|
|
'--project-directory', options.project_directory,
|
|
'-f', options.base_compose]
|
|
base = json.loads(capture(compose + ['config', '--format', 'json']))
|
|
planned_command = compose.copy()
|
|
for override in options.override:
|
|
planned_command.extend(['-f', override])
|
|
planned = json.loads(capture(planned_command + ['config', '--format', 'json']))
|
|
inspected = json.loads(capture(['docker', 'inspect', 'canino_backend_stage',
|
|
'canino_frontend_stage']))
|
|
if not isinstance(inspected, list) or len(inspected) != 2:
|
|
raise ValueError()
|
|
live = dict(zip(('backend_stage', 'frontend_stage'), inspected))
|
|
live_nginx = capture(['docker', 'exec', 'canino_frontend_stage', 'cat',
|
|
'/etc/nginx/conf.d/default.conf'])
|
|
errors = verify(base, planned, live, Path(options.nginx).read_bytes(), live_nginx)
|
|
except (OSError, subprocess.SubprocessError, ValueError, KeyError, TypeError, AttributeError):
|
|
print('authority.input unavailable or malformed', file=sys.stderr)
|
|
return 1
|
|
for error in errors:
|
|
# Only property/key names are emitted, with control characters removed.
|
|
print('authority mismatch: ' + re.sub(r'[^a-zA-Z0-9_.-]', '?', error), file=sys.stderr)
|
|
if errors:
|
|
return 1
|
|
print('Stage runtime authority verified')
|
|
return 0
|
|
|
|
|
|
if __name__ == '__main__':
|
|
sys.exit(main())
|