Detect Dex credential drift before deployment
This commit is contained in:
parent
7c4a513b6b
commit
26b542a8c9
|
|
@ -60,7 +60,7 @@ var allowedCommands = map[string]bool{
|
|||
"backup": true, "drill-restore": true, "drill-gitea-restore": true,
|
||||
"drill-pihole-restore": true, "install-gitea-runner": true,
|
||||
"move-prometheus-stack-workers": true, "doctor-versions": true,
|
||||
"doctor-edge": true, "doctor-homelab": true, "doctor-gitea": true,
|
||||
"doctor-edge": true, "doctor-homelab": true, "doctor-gitea": true, "doctor-dex": true,
|
||||
"doctor-rpi": true, "doctor-cluster": true, "doctor-k8s": true,
|
||||
"preflight": true, "doctor-preapply": true, "inventory-check": true,
|
||||
"state-backup": true, "fix-debian-docker-root": true,
|
||||
|
|
|
|||
|
|
@ -651,3 +651,21 @@ the app image build and with the image globs in
|
|||
|
||||
Keep the `.terraform.lock.hcl` files committed. They pin provider selections and
|
||||
make bootstrap behavior reproducible across nodes and rebuilds.
|
||||
# Dex credential drift
|
||||
|
||||
`./jeannie doctor-dex` compares the encrypted Dex source with the rendered
|
||||
Debian Dex configuration and reports client names and match states without
|
||||
printing credential values. It checks whether the source is committed in the
|
||||
local checkout; it does not check whether that commit is on a remote. The
|
||||
check does not validate the password hash, the running process, or downstream
|
||||
client settings. A missing key, inaccessible config, unsupported user layout,
|
||||
or failed command is inconclusive, never a match. `./jeannie remote doctor-dex`
|
||||
is also available after the Jeannie API is redeployed.
|
||||
|
||||
`deploy-dex` refuses to overwrite an existing config when drift or an
|
||||
uncommitted source is detected. For initial setup, create the encrypted source
|
||||
with `dex-secret ensure`, review and commit it first. Confirmed Dex rotation
|
||||
checks for existing drift, retains an encrypted backup, updates the rendered
|
||||
config and checks it again, then updates dependent services. Validate SSO
|
||||
logins and commit the encrypted change; the rendered-config check does not
|
||||
prove that downstream SSO logins work. Back up the age private key separately.
|
||||
|
|
|
|||
|
|
@ -651,3 +651,21 @@ the app image build and with the image globs in
|
|||
|
||||
Keep the `.terraform.lock.hcl` files committed. They pin provider selections and
|
||||
make bootstrap behavior reproducible across nodes and rebuilds.
|
||||
# Dex credential drift
|
||||
|
||||
`./jeannie doctor-dex` compares the encrypted Dex source with the rendered
|
||||
Debian Dex configuration and reports client names and match states without
|
||||
printing credential values. It checks whether the source is committed in the
|
||||
local checkout; it does not check whether that commit is on a remote. The
|
||||
check does not validate the password hash, the running process, or downstream
|
||||
client settings. A missing key, inaccessible config, unsupported user layout,
|
||||
or failed command is inconclusive, never a match. `./jeannie remote doctor-dex`
|
||||
is also available after the Jeannie API is redeployed.
|
||||
|
||||
`deploy-dex` refuses to overwrite an existing config when drift or an
|
||||
uncommitted source is detected. For initial setup, create the encrypted source
|
||||
with `dex-secret ensure`, review and commit it first. Confirmed Dex rotation
|
||||
checks for existing drift, retains an encrypted backup, updates the rendered
|
||||
config and checks it again, then updates dependent services. Validate SSO
|
||||
logins and commit the encrypted change; the rendered-config check does not
|
||||
prove that downstream SSO logins work. Back up the age private key separately.
|
||||
|
|
|
|||
4
jeannie
4
jeannie
|
|
@ -188,6 +188,7 @@ Focused Doctors
|
|||
Run post-migration Pimox/Debian/edge checks.
|
||||
doctor-gitea [--all|--details|--verbose|--json]
|
||||
Diagnose Gitea local/public access.
|
||||
doctor-dex Check encrypted Dex source against its rendered config.
|
||||
doctor-rpi [--all|--details|--verbose|--json]
|
||||
Diagnose RPi services and DNS.
|
||||
doctor-cluster [--all|--details|--verbose|--json]
|
||||
|
|
@ -669,6 +670,9 @@ case "${1:-}" in
|
|||
doctor-gitea)
|
||||
doctor_gitea "${@:2}"
|
||||
;;
|
||||
doctor-dex)
|
||||
doctor_dex "${@:2}"
|
||||
;;
|
||||
doctor-rpi)
|
||||
doctor_rpi "${@:2}"
|
||||
;;
|
||||
|
|
|
|||
|
|
@ -1501,6 +1501,7 @@ status_cascade_warn() {
|
|||
|
||||
if truthy "${JEANNIE_REPORT_MODE:-false}"; then
|
||||
[[ "${description}" != "Backup freshness" ]] || fix="./jeannie backup oci freshness"
|
||||
[[ "${description}" != "Dex credential drift" ]] || fix="./jeannie doctor-dex"
|
||||
report_ui_check warn "${STATUS_CURRENT_SECTION:-Status}" "${description}" "${fix}" "" "" "$@"
|
||||
return 0
|
||||
fi
|
||||
|
|
@ -2022,6 +2023,7 @@ status_cascade_report() {
|
|||
status_cascade_warn "Backup freshness" backup_status
|
||||
fi
|
||||
status_cascade_warn "Recent deployments healthy" status_recent_deployments
|
||||
status_cascade_warn "Dex credential drift" dex_drift_check
|
||||
if [[ "${JEANNIE_STATUS_MODE:-deep}" == deep ]]; then
|
||||
status_cascade_warn "Pod restart pressure" status_pod_restart_pressure
|
||||
fi
|
||||
|
|
|
|||
|
|
@ -1098,6 +1098,11 @@ deploy_dex() {
|
|||
exit 1
|
||||
fi
|
||||
|
||||
if [[ "${1:-}" != rotation ]] && ! dex_drift_check; then
|
||||
echo "Dex deployment refused: inspect ./jeannie doctor-dex and reconcile the encrypted source first." >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
dex_env="$(dex_secret_values)" || exit 1
|
||||
eval "${dex_env}"
|
||||
office_client_secret="${office_client_secret:-${DEX_OFFICE_CLIENT_SECRET:-}}"
|
||||
|
|
|
|||
|
|
@ -195,6 +195,27 @@ dex_secret_file() {
|
|||
printf '%s\n' "${HOMELAB_DEX_SECRET_FILE:-${REPO_ROOT}/apps/dex/dex.secret.yaml}"
|
||||
}
|
||||
|
||||
dex_drift_check() {
|
||||
local args=()
|
||||
if [[ "${1:-}" == "--allow-dirty" ]]; then
|
||||
args+=(--allow-dirty)
|
||||
fi
|
||||
python3 "${REPO_ROOT}/scripts/doctor-dex-drift.py" \
|
||||
--repo "${REPO_ROOT}" \
|
||||
--secret "$(dex_secret_file)" \
|
||||
--config "${LAB_DEX_INSTALL_DIR:-/data/homelab-dex}/config.yaml" \
|
||||
"${args[@]}"
|
||||
}
|
||||
|
||||
doctor_dex() {
|
||||
require_debian_server "doctor-dex"
|
||||
if [[ $# -ne 0 ]]; then
|
||||
echo "Usage: ./jeannie doctor-dex" >&2
|
||||
return 2
|
||||
fi
|
||||
dex_drift_check
|
||||
}
|
||||
|
||||
generate_dex_secret_value() {
|
||||
if command -v openssl >/dev/null 2>&1; then
|
||||
openssl rand -base64 48 | tr -d '\n'
|
||||
|
|
@ -409,24 +430,34 @@ EOF
|
|||
ensure_sops_age_tools
|
||||
secret_file="$(dex_secret_file)"
|
||||
[[ -s "${secret_file}" ]] || { echo "Missing Dex secret file: ${secret_file}" >&2; return 1; }
|
||||
if ! dex_drift_check; then
|
||||
echo "Dex rotation refused: resolve source or deployed-config drift first with ./jeannie doctor-dex." >&2
|
||||
return 1
|
||||
fi
|
||||
backup_dir="${HOMELAB_STATE_DIR:-${HOME}/.local/share/homelab}/secret-rotation-backups"
|
||||
mkdir -p "${backup_dir}"
|
||||
backup_file="${backup_dir}/dex-secret-$(date +%Y%m%d-%H%M%S).yaml"
|
||||
cp -p "${secret_file}" "${backup_file}"
|
||||
chmod 600 "${backup_file}"
|
||||
echo "Encrypted pre-rotation backup: ${backup_file}"
|
||||
grafana_secret="$(generate_dex_secret_value)"
|
||||
gitea_secret="$(generate_dex_secret_value)"
|
||||
office_secret="$(generate_dex_secret_value)"
|
||||
SOPS_AGE_KEY_FILE="$(sops_age_key_file)" sops set "${secret_file}" '["stringData"]["DEX_GRAFANA_CLIENT_SECRET"]' "\"${grafana_secret}\""
|
||||
SOPS_AGE_KEY_FILE="$(sops_age_key_file)" sops set "${secret_file}" '["stringData"]["DEX_GITEA_CLIENT_SECRET"]' "\"${gitea_secret}\""
|
||||
SOPS_AGE_KEY_FILE="$(sops_age_key_file)" sops set "${secret_file}" '["stringData"]["DEX_OFFICE_CLIENT_SECRET"]' "\"${office_secret}\""
|
||||
deploy_dex
|
||||
deploy_dex rotation
|
||||
if ! dex_drift_check --allow-dirty; then
|
||||
echo "Dex rotation verification failed; encrypted backup retained at ${backup_file}." >&2
|
||||
return 1
|
||||
fi
|
||||
configure_grafana_dex_secret
|
||||
configure_gitea_sso_source
|
||||
if sudo docker inspect "${OFFICE_NEXTCLOUD_CONTAINER_NAME:-homelab-office-nextcloud}" >/dev/null 2>&1; then
|
||||
deploy_office
|
||||
fi
|
||||
echo "Dex client secrets rotated and dependent services updated. Backup: ${backup_file}"
|
||||
echo "Dex rendered configuration checked and dependent services updated. Backup: ${backup_file}"
|
||||
echo "Validate SSO logins and commit the encrypted Dex file before another deployment."
|
||||
;;
|
||||
gitea-runner)
|
||||
cat <<'EOF'
|
||||
|
|
|
|||
|
|
@ -0,0 +1,145 @@
|
|||
#!/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())
|
||||
|
|
@ -105,6 +105,7 @@ validate_security_static() {
|
|||
|
||||
validate_unit_tests() {
|
||||
"${REPO_ROOT}/tests/jeannie-unit"
|
||||
python3 -m unittest discover -s "${REPO_ROOT}/tests/jeannie" -p 'test_doctor_dex_drift.py'
|
||||
}
|
||||
|
||||
main() {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,75 @@
|
|||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
path = Path(__file__).resolve().parents[2] / 'scripts/doctor-dex-drift.py'
|
||||
spec = importlib.util.spec_from_file_location('dex_drift', path)
|
||||
drift = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(drift)
|
||||
|
||||
|
||||
class DexDriftTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.source = {'DEX_GRAFANA_CLIENT_SECRET': 'secret-a', 'DEX_GITEA_CLIENT_SECRET': 'secret-b',
|
||||
'DEX_USER_EMAIL': 'user@example.com', 'DEX_USER_NAME': 'user', 'DEX_USER_ID': 'uid'}
|
||||
self.deployed = {'staticClients': [{'id': 'grafana', 'secret': 'secret-a'},
|
||||
{'id': 'gitea', 'secret': 'secret-b'}],
|
||||
'staticPasswords': [{'email': 'user@example.com', 'username': 'user', 'userID': 'uid'}]}
|
||||
|
||||
def test_matching_source_and_optional_client(self):
|
||||
clients, identity = drift.compare(self.source, self.deployed)
|
||||
self.assertEqual(clients['grafana'], 'match')
|
||||
self.assertEqual(clients['argocd'], 'not configured')
|
||||
self.assertTrue(all(value == 'match' for value in identity.values()))
|
||||
self.assertNotIn('secret-a', str(clients))
|
||||
|
||||
def test_changed_and_unknown_clients_are_flagged(self):
|
||||
self.deployed['staticClients'][0]['secret'] = 'changed'
|
||||
self.deployed['staticClients'].append({'id': 'custom', 'secret': 'secret-c'})
|
||||
clients, _ = drift.compare(self.source, self.deployed)
|
||||
self.assertEqual(clients['grafana'], 'different')
|
||||
self.assertEqual(clients['custom'], 'not managed by Jeannie')
|
||||
self.assertNotIn('secret-c', str(clients))
|
||||
|
||||
def test_extra_users_and_duplicate_clients_refused(self):
|
||||
self.deployed['staticPasswords'].append({'email': 'another@example.com'})
|
||||
with self.assertRaises(ValueError):
|
||||
drift.compare(self.source, self.deployed)
|
||||
self.deployed['staticPasswords'].pop()
|
||||
self.deployed['staticClients'].append({'id': 'grafana', 'secret': 'other'})
|
||||
with self.assertRaises(ValueError):
|
||||
drift.compare(self.source, self.deployed)
|
||||
|
||||
def test_dirty_source_blocks_and_does_not_expose_values(self):
|
||||
self.source['DEX_USER_PASSWORD'] = 'password-value'
|
||||
decrypted = json.dumps({'stringData': self.source}).encode()
|
||||
result = subprocess.CompletedProcess([], 0, stdout=decrypted, stderr=b'')
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
secret = Path(directory) / 'secret.yaml'
|
||||
secret.write_text('sops: {}\nstringData:\n sample: ENC[test]\n')
|
||||
with patch.object(drift, 'git_state', return_value='modified or staged'), \
|
||||
patch.object(drift, 'read_deployed', return_value=self.deployed), \
|
||||
patch.object(drift.subprocess, 'run', return_value=result):
|
||||
report = drift.diagnose(Path(directory), secret, Path('/example/config'))
|
||||
self.assertEqual(report['result'], 'uncommitted')
|
||||
self.assertNotIn('password-value', json.dumps(report))
|
||||
self.assertNotIn('secret-a', json.dumps(report))
|
||||
self.assertEqual(drift.diagnose(Path(directory), secret, Path('/example/config'), True)['result'], 'ok')
|
||||
|
||||
def test_plaintext_source_is_refused_before_decryption(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
secret = Path(directory) / 'secret.yaml'
|
||||
secret.write_text('sops: {}\nstringData:\n secret: plaintext\n')
|
||||
with patch.object(drift, 'git_state', return_value='committed in local HEAD'), \
|
||||
patch.object(drift.subprocess, 'run') as run:
|
||||
with self.assertRaises(ValueError):
|
||||
drift.diagnose(Path(directory), secret, Path('/example/config'))
|
||||
run.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Loading…
Reference in New Issue