Files
mtusi2026lab7/scripts/test-credential-rotation.py
2026-11-26 23:34:55 +03:00

28 lines
2.3 KiB
Python

#!/usr/bin/env python3
"""Operator test: rotates worker secrets; never prints old or new values."""
import json,ssl,subprocess,urllib.request,urllib.error,shlex
from pathlib import Path
root=Path(__file__).resolve().parent.parent
op=root/'secrets/operator'
old_redis=(op/'redis-worker').read_text().strip()
old_s3=(op/'s3-worker').read_text().strip()
role=(root/'secrets/approle/worker/role-id').read_text()
old_sid=(root/'secrets/approle/worker/secret-id').read_text()
dc=[str(root/'scripts/dc.sh')]
subprocess.run([str(root/'scripts/rotate-service-secret.sh'),'worker'],cwd=root,check=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=120)
ctx=ssl.create_default_context(cafile=str(root/'certs/ca.crt'))
r=urllib.request.Request('https://localhost:8200/v1/auth/approle/login',data=json.dumps({'role_id':role,'secret_id':old_sid}).encode(),headers={'Content-Type':'application/json'})
try:
urllib.request.urlopen(r,context=ctx,timeout=10)
raise AssertionError('old SecretID still accepted')
except urllib.error.HTTPError as e:assert e.code in (400,403)
script=f'valkey-cli --tls --cacert /pki/ca.crt --cert /identity/redis.crt --key /identity/redis.key --sni redis -h redis --user worker --pass {shlex.quote(old_redis)} PING\n'
p=subprocess.run(dc+['run','--rm','-T','--no-deps','--entrypoint','/bin/sh','cache','-s'],cwd=root,input=script,text=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=20)
assert 'WRONGPASS' in p.stdout+p.stderr,'old Redis password did not fail authentication'
script=f'mc alias set old https://minio:9000 messenger-worker {shlex.quote(old_s3)} >/dev/null && mc ls old/attachments/staging\n'
p=subprocess.run(dc+['run','--rm','-T','mc','-s'],cwd=root,input=script,text=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=20)
assert p.returncode!=0 and any(x in (p.stdout+p.stderr).lower() for x in ['signature','access denied','access key']),'old S3 secret did not fail authentication'
p=subprocess.run(dc+['run','--rm','-T','--no-deps','--entrypoint','/app/dependency_security_test','worker'],cwd=root,stdout=subprocess.PIPE,stderr=subprocess.PIPE,timeout=30)
assert p.returncode==0,'fresh worker credentials failed validation'
print('PASS: worker SecretID, Redis password and S3 secret rotated; old credentials denied; fresh worker credentials succeed')