my-homelab-configs/scripts/doctor-dex-drift.py

146 lines
7.3 KiB
Python

#!/usr/bin/env python3
"""Compare encrypted Dex source with its rendered config without revealing values."""
import argparse
import base64
import json
import os
from pathlib import Path
import subprocess
import sys
import yaml
CLIENTS = {'grafana': 'DEX_GRAFANA_CLIENT_SECRET', 'gitea': 'DEX_GITEA_CLIENT_SECRET',
'nextcloud': 'DEX_OFFICE_CLIENT_SECRET', 'argocd': 'DEX_ARGOCD_CLIENT_SECRET'}
IDENTITY = {'email': 'DEX_USER_EMAIL', 'username': 'DEX_USER_NAME', 'userID': 'DEX_USER_ID'}
def compare(source, deployed):
"""Return names and statuses only; never include values in the result."""
raw = deployed.get('staticClients', [])
if not isinstance(raw, list) or any(not isinstance(item, dict) or not item.get('id') for item in raw):
raise ValueError('Dex staticClients is invalid')
ids = [item['id'] for item in raw]
if len(ids) != len(set(ids)):
raise ValueError('Dex staticClients has duplicate IDs')
clients = {item['id']: item for item in raw}
result = {}
for name, key in CLIENTS.items():
expected = source.get(key)
actual = clients.get(name)
if actual is None:
result[name] = 'not configured'
elif not expected or not actual.get('secret'):
result[name] = 'different or missing'
else:
result[name] = 'match' if expected == actual['secret'] else 'different'
# Preserve unknown clients: deploy-dex would otherwise remove them.
result.update({name: 'not managed by Jeannie' for name in ids if name not in CLIENTS})
raw_users = deployed.get('staticPasswords', [])
if not isinstance(raw_users, list) or len(raw_users) != 1 or not isinstance(raw_users[0], dict):
raise ValueError('Dex staticPasswords is not one managed user')
user = raw_users[0]
identity = {field: ('match' if source.get(key) and source[key] == user.get(field) else 'different or missing')
for field, key in IDENTITY.items()}
return result, identity
def git_state(repo, secret):
try:
relative = secret.resolve().relative_to(repo.resolve())
except ValueError:
return 'outside repository'
tracked = subprocess.run(['git', '-C', str(repo), 'ls-files', '--error-unmatch', '--', str(relative)],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10)
if tracked.returncode:
return 'untracked or unavailable'
result = subprocess.run(['git', '-C', str(repo), 'status', '--porcelain', '--', str(relative)],
capture_output=True, text=True, timeout=10)
if result.returncode:
return 'unavailable'
return 'modified or staged' if result.stdout.strip() else 'committed in local HEAD'
def read_deployed(config):
privilege = subprocess.run(['sudo', '-n', 'true'], capture_output=True, timeout=10)
if privilege.returncode:
raise RuntimeError('Passwordless sudo is unavailable')
result = subprocess.run(['sudo', '-n', 'cat', '--', str(config)], capture_output=True, timeout=10)
if result.returncode:
exists = subprocess.run(['sudo', '-n', 'test', '-e', str(config)], capture_output=True, timeout=10)
if exists.returncode == 1:
return None
raise RuntimeError('Cannot read deployed Dex config with passwordless sudo')
document = yaml.safe_load(result.stdout)
if not isinstance(document, dict):
raise ValueError('Deployed Dex config is not a YAML mapping')
return document
def diagnose(repo, secret, config, allow_dirty=False):
state = git_state(repo, secret)
encrypted = yaml.safe_load(secret.read_bytes())
if not isinstance(encrypted, dict) or not isinstance(encrypted.get('sops'), dict):
raise ValueError('Dex secret has no SOPS metadata')
for section in ('stringData', 'data'):
fields = encrypted.get(section) or {}
if not isinstance(fields, dict) or any(not isinstance(v, str) or not v.startswith('ENC[') for v in fields.values()):
raise ValueError('Dex source has unencrypted secret fields')
env = os.environ.copy()
env['SOPS_AGE_KEY_FILE'] = env.get('SOPS_AGE_KEY_FILE', str(Path.home() / '.config/sops/age/keys.txt'))
result = subprocess.run(['sops', '--decrypt', str(secret)], env=env, capture_output=True, timeout=20)
if result.returncode:
raise RuntimeError('Cannot decrypt Dex SOPS file using the configured age key')
document = yaml.safe_load(result.stdout)
if not isinstance(document, dict):
raise ValueError('Decrypted Dex secret is not a YAML mapping')
values = dict(document.get('stringData') or {})
for key, value in (document.get('data') or {}).items():
values[key] = base64.b64decode(value, validate=True).decode()
required = ('DEX_GRAFANA_CLIENT_SECRET', 'DEX_GITEA_CLIENT_SECRET',
'DEX_USER_EMAIL', 'DEX_USER_NAME', 'DEX_USER_ID', 'DEX_USER_PASSWORD')
if any(not isinstance(values.get(key), str) or not values[key] for key in required):
raise ValueError('Dex source is missing required fields')
deployed = read_deployed(config)
report = {'git': state, 'clients': {}, 'identity': {},
'scope': 'Rendered config only; password hash, live process, downstream clients and remote Git are not checked.'}
if deployed is None:
running = subprocess.run(['sudo', '-n', 'docker', 'ps', '--format', '{{.Names}}'],
capture_output=True, text=True, timeout=10)
if running.returncode:
raise RuntimeError('Cannot verify whether Dex is running without its config')
if os.environ.get('DEX_CONTAINER_NAME', 'homelab-dex') in running.stdout.splitlines():
raise RuntimeError('Dex is running but its rendered config is missing')
report['config'] = 'not configured'
else:
report['config'] = 'present'
report['clients'], report['identity'] = compare(values, deployed)
override = os.environ.get('LAB_OFFICE_OIDC_CLIENT_SECRET')
if override and override != values.get('DEX_OFFICE_CLIENT_SECRET'):
report['office_override'] = 'differs from encrypted source'
drift = any(v not in ('match', 'not configured') for v in report['clients'].values()) or \
any(v != 'match' for v in report['identity'].values()) or 'office_override' in report
report['result'] = 'drift' if drift else ('uncommitted' if state != 'committed in local HEAD' and not allow_dirty else 'ok')
return report
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--repo', type=Path, required=True)
parser.add_argument('--secret', type=Path, required=True)
parser.add_argument('--config', type=Path, required=True)
parser.add_argument('--allow-dirty', action='store_true', help=argparse.SUPPRESS)
args = parser.parse_args()
try:
report = diagnose(args.repo, args.secret, args.config, args.allow_dirty)
print(json.dumps(report, sort_keys=True))
return 0 if report['result'] == 'ok' else 1
except (OSError, ValueError, TypeError, RuntimeError, yaml.YAMLError, subprocess.SubprocessError):
# Do not print subprocess stderr or parser data, which could contain secrets.
print(json.dumps({'result': 'inconclusive', 'message': 'Dex source or rendered config could not be safely inspected; check the key, file and sudo access.'}))
return 2
if __name__ == '__main__':
sys.exit(main())